squish a couple of redraw bugs
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.text.TextField;
4         import flash.display.DisplayObjectContainer;
5         import flash.display.Loader;
6         import flash.display.Sprite;
7         import flash.display.Shape;
8         import flash.display.Stage;
9         import flash.display.BitmapData;
10         import flash.display.LoaderInfo;
11         import flash.text.Font;
12         import flash.utils.ByteArray;
13         import flash.events.*;
14         import flash.net.*;
15
16     import net.systemeD.halcyon.connection.*;
17     import net.systemeD.halcyon.connection.EntityEvent;
18         import net.systemeD.halcyon.styleparser.*;
19         import net.systemeD.halcyon.Globals;
20
21 //      for experimental export function:
22 //      import flash.net.FileReference;
23 //      import com.adobe.images.JPGEncoder;
24
25     public class Map extends Sprite {
26
27                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
28                                                                                                                 // (for Landsat, 5120)
29                 public const MINSCALE:uint=13;                                  // don't zoom out past this
30                 public const MAXSCALE:uint=19;                                  // don't zoom in past this
31
32                 public var paint:MapPaint;                                              // sprite for ways and (POI/tagged) nodes in core layer
33                 public var vectorbg:Sprite;                                             // sprite for vector background layers
34
35                 public var scale:uint=14;                                               // map scale
36                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
37                 public var bigedge_l:Number= 999999;                    // area of largest whichways
38                 public var bigedge_r:Number=-999999;                    //  |
39                 public var bigedge_b:Number= 999999;                    //  |
40                 public var bigedge_t:Number=-999999;                    //  |
41
42                 public var edge_l:Number;                                               // current bounding box
43                 public var edge_r:Number;                                               //  |
44                 public var edge_t:Number;                                               //  |
45                 public var edge_b:Number;                                               //  |
46                 public var centre_lat:Number;                                   // centre lat/lon
47                 public var centre_lon:Number;                                   //  |
48
49                 public var baselon:Number;                                              // urllon-xradius/masterscale;
50                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
51                 public var mapwidth:uint;                                               // width (Flash pixels)
52                 public var mapheight:uint;                                              // height (Flash pixels)
53
54                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map
55                 private var _draggable:Boolean=true;                    //  |
56                 private var lastxmouse:Number;                                  //  |
57                 private var lastymouse:Number;                                  //  |
58                 private var downX:Number;                                               //  |
59                 private var downY:Number;                                               //  |
60                 public const NOT_DRAGGING:uint=0;                               //  |
61                 public const NOT_MOVED:uint=1;                                  //  |
62                 public const DRAGGING:uint=2;                                   //  |
63                 
64                 public var initparams:Object;                                   // object containing HTML page parameters
65
66                 public var backdrop:Object;                                             // reference to backdrop sprite
67                 public var tileset:TileSet;                                             // 900913 tile background
68                 private var tileurl:String='';                                  // internal tile URL
69                 private var styleurl:String='';                                 // internal style URL
70                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
71                 
72                 public var connection:Connection;                               // server connection
73                 public var vectorlayers:Object={};                              // VectorLayer objects 
74
75                 public const TILESPRITE:uint=0;
76                 public const VECTORSPRITE:uint=1;
77                 public const WAYSPRITE:uint=2;
78                 public const NAMESPRITE:uint=13;
79                 
80                 // ------------------------------------------------------------------------------------------
81                 // Map constructor function
82
83         public function Map(initparams:Object) {
84
85                         this.initparams=initparams;
86                         connection = Connection.getConnection(initparams);
87             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
88             connection.addEventListener(Connection.NEW_POI, newPOICreated);
89             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
90             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
91                         gotEnvironment(null);
92
93                         addEventListener(Event.ENTER_FRAME, everyFrame);
94         }
95
96                 public function gotEnvironment(r:Object):void {
97                         var loader:Loader = new Loader();
98                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
99                         loader.load(new URLRequest("FontLibrary.swf"));
100                 }
101                 
102                 public function gotFont(r:Event):void {
103                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
104                         Font.registerFont(FontLibrary.DejaVu);
105
106                         if (initparams['lat'] != null) {
107                                 // parameters sent from HTML
108                                 init(initparams['lat'],
109                                          initparams['lon'],
110                                          initparams['zoom']);
111
112                         } else {
113                                 // somewhere innocuous
114                                 init(53.09465,-2.56495,17);
115                         }
116                 }
117
118                 // ------------------------------------------------------------------------------------------
119                 // Initialise map at a given lat/lon
120
121         public function init(startlat:Number,startlon:Number,startscale:uint=0):void {
122                         while (numChildren) { removeChildAt(0); }
123
124                         tileset=new TileSet(this);                                      // 0 - 900913 background
125                         addChild(tileset);                                                      //   |
126                         tileset.init(tileurl);                                          //   |
127
128                         vectorbg = new Sprite();                                        // 1 - vector background layers
129                         addChild(vectorbg);                                                     //   |
130
131                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
132                         addChild(paint);                                                        //   |
133                         paint.isBackground=false;                                       //   |
134
135                         if (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
136                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
137                                 paint.ruleset.loadFromCSS(styleurl);
138                         }
139                         if (startscale>0) { scale=startscale; }
140
141                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
142                         baselon    =startlon          -(mapwidth /2)/scalefactor;
143                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
144                         addDebug("Baselon "+baselon+", basey "+basey);
145                         updateCoords(0,0);
146                         download();
147                         
148         }
149
150                 // ------------------------------------------------------------------------------------------
151                 // Recalculate co-ordinates from new Flash origin
152
153                 public function updateCoords(tx:Number,ty:Number):void {
154                         x=tx; y=ty;
155
156                         edge_t=coord2lat(-y          );
157                         edge_b=coord2lat(-y+mapheight);
158                         edge_l=coord2lon(-x          );
159                         edge_r=coord2lon(-x+mapwidth );
160                         setCentre();
161
162                         tileset.update();
163                 }
164                 
165                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
166                         var cy:Number=-(lat2coord(lat)-mapheight/2);
167                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
168                         updateCoords(cx,cy);
169                 }
170                 
171                 private function setCentre():void {
172                         centre_lat=coord2lat(-y+mapheight/2);
173                         centre_lon=coord2lon(-x+mapwidth/2);
174                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale}));
175                 }
176                 
177                 public function nudgeBackground(x:Number,y:Number):void {
178                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
179                 }
180
181                 // Co-ordinate conversion functions
182
183                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
184                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
185                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
186                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
187
188                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
189                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
190
191                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
192                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
193
194 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
195 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
196
197
198                 // ------------------------------------------------------------------------------------------
199                 // Resize map size based on current stage and height
200
201                 public function updateSize(w:uint, h:uint):void {
202                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
203                         
204                         mapwidth = w;
205                         mapheight= h;
206             if ( backdrop != null ) {
207                 backdrop.width=mapwidth;
208                 backdrop.height=mapheight;
209             }
210             if ( mask != null ) {
211                 mask.width=mapwidth;
212                 mask.height=mapheight;
213             }
214                 }
215
216                 // ------------------------------------------------------------------------------------------
217                 // Download map data
218                 // (typically from whichways, but will want to add more connections)
219
220                 public function download():void {
221                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
222                         
223                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
224                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
225                         bigedge_l=edge_l; bigedge_r=edge_r;
226                         bigedge_b=edge_b; bigedge_t=edge_t;
227                         if (connection.waycount>1000) {
228                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
229                         }
230                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
231                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
232                 }
233
234         private function newWayCreated(event:EntityEvent):void {
235             var way:Way = event.entity as Way;
236                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
237                         paint.createWayUI(way);
238         }
239
240         private function newPOICreated(event:EntityEvent):void {
241             var node:Node = event.entity as Node;
242                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
243                         paint.createNodeUI(node);
244         }
245
246                 private function wayRenumbered(event:EntityRenumberedEvent):void {
247             var way:Way = event.entity as Way;
248                         paint.renumberWayUI(way,event.oldID);
249                 }
250
251                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
252             var node:Node = event.entity as Node;
253                         paint.renumberNodeUI(node,event.oldID);
254                 }
255
256         public function setHighlight(entity:Entity, settings:Object):void {
257                         var stateType:String;
258                         var ui:EntityUI=null;
259                         if      ( entity is Way  ) { ui = paint.wayuis[entity.id]; }
260                         else if ( entity is Node ) { ui = paint.nodeuis[entity.id]; }
261                         if (ui==null) { return; }
262                         for (stateType in settings) {
263                                 ui.setHighlight(stateType, settings[stateType]);
264                         }
265                         ui.redraw();
266         }
267
268         // Handle mouse events on ways/nodes
269         private var mapController:MapController = null;
270
271         public function setController(controller:MapController):void {
272             this.mapController = controller;
273         }
274
275         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
276             if ( mapController != null )
277                 mapController.entityMouseEvent(event, entity);
278                                 
279         }
280
281                 // ------------------------------------------------------------------------------------------
282                 // Redraw all items, zoom in and out
283                 
284                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
285                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
286                         for each (var v:VectorLayer in vectorlayers) {
287                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
288                         }
289                 }
290                 public function redraw():void {
291                         paint.redraw();
292                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
293                 }
294                 public function redrawPOIs():void { 
295                         paint.redrawPOIs();
296                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
297                 }
298                 
299                 public function zoomIn():void {
300                         if (scale==MAXSCALE) { return; }
301                         changeScale(scale+1);
302                 }
303
304                 public function zoomOut():void {
305                         if (scale==MINSCALE) { return; }
306                         changeScale(scale-1);
307                 }
308
309                 private function changeScale(newscale:uint):void {
310                         addDebug("new scale "+newscale);
311                         scale=newscale;
312                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
313                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
314                         tileset.changeScale(scale);
315                         updateEntityUIs(true,true);
316                         download();
317                 }
318
319                 private function reportPosition():void {
320                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
321                 }
322                 
323                 public function setStyle(url:String):void {
324                         styleurl=url;
325                         if (paint) { 
326                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
327                                 paint.ruleset.loadFromCSS(url);
328                         }
329         }
330
331                 public function setBackground(url:String):void {
332                         tileurl=url;
333                         if (tileset) { tileset.init(url, url!=''); }
334                 }
335
336                 public function setDimming(dim:Boolean):void {
337                         if (tileset) { tileset.setDimming(dim); }
338                 }
339
340                 // ------------------------------------------------------------------------------------------
341                 // Export (experimental)
342                 // ** just a bit of fun for now!
343                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
344                 // to that area (will probably require creating a new DisplayObject with a different origin
345                 // and mask)
346 /*              
347                 public function export():void {
348                         addDebug("size is "+this.width+","+this.height);
349                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
350                         jpgSource.draw(this);
351                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
352                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
353                         var fileRef:FileReference = new FileReference();
354 //                      fileRef.save(jpgStream,'map.jpeg');
355                 }
356
357 */
358
359                 // ==========================================================================================
360                 // Events
361                 
362                 // ------------------------------------------------------------------------------------------
363                 // Mouse events
364                 
365                 public function set draggable(draggable:Boolean):void {
366                         _draggable=draggable;
367                         dragstate=NOT_DRAGGING;
368                 }
369
370                 public function mouseDownHandler(event:MouseEvent):void {
371                         if (!_draggable) { return; }
372                         dragstate=NOT_MOVED;
373                         lastxmouse=downX=mouseX;
374                         lastymouse=downY=mouseY;
375                 }
376         
377                 public function mouseUpHandler(event:MouseEvent=null):void {
378                         if (dragstate==DRAGGING) {
379                                 updateCoords(x,y);
380                                 updateEntityUIs(false, false);
381                                 download();
382                         }
383                         dragstate=NOT_DRAGGING;
384                 }
385         
386                 public function mouseMoveHandler(event:MouseEvent):void {
387                         if (!_draggable) { return; }
388                         if (dragstate==NOT_DRAGGING) { return; }
389                         
390                         if (dragstate==NOT_MOVED && Math.abs(downX - mouseX) < 3 && Math.abs(downY - mouseY) < 3) {
391                                 return;
392                         }
393                         
394                         dragstate=DRAGGING;
395                         x+=mouseX-lastxmouse;
396                         y+=mouseY-lastymouse;
397                         lastxmouse=mouseX; lastymouse=mouseY;
398                         setCentre();
399                 }
400         
401                 // ------------------------------------------------------------------------------------------
402                 // Do every frame
403
404                 private function everyFrame(event:Event):void {
405                         if (tileset) { tileset.serviceQueue(); }
406                 }
407
408                 // ------------------------------------------------------------------------------------------
409                 // Miscellaneous events
410                 
411                 public function keyUpHandler(event:KeyboardEvent):void {
412                         if ( !event.ctrlKey ) return;
413                         addDebug("pressed "+event.keyCode);
414                         if (event.keyCode==73) { zoomIn(); }                    // I - zoom in
415                         if (event.keyCode==79) { zoomOut(); }                   // O - zoom out
416                         if (event.keyCode==76) { reportPosition(); }    // L - report lat/long
417                 }
418
419                 public function connectionError(err:Object=null): void {
420                         addDebug("got error"); 
421                 }
422
423                 // ------------------------------------------------------------------------------------------
424                 // Debugging
425                 
426                 public function clearDebug():void {
427                         if (!Globals.vars.hasOwnProperty('debug')) return;
428                         Globals.vars.debug.text='';
429                 }
430                         
431                 public function addDebug(text:String):void {
432                         if (!Globals.vars.hasOwnProperty('debug')) return;
433                         if (!Globals.vars.debug.visible) return;
434                         Globals.vars.debug.appendText(text+"\n");
435                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
436                 }
437
438         }
439 }