improve display performance, particularly when panning the map and when dragging...
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.text.TextField;
4         import flash.geom.Rectangle;
5         import flash.display.DisplayObjectContainer;
6         import flash.display.Loader;
7         import flash.display.Sprite;
8         import flash.display.Shape;
9         import flash.display.Stage;
10         import flash.display.BitmapData;
11         import flash.display.LoaderInfo;
12         import flash.text.Font;
13         import flash.utils.ByteArray;
14         import flash.events.*;
15         import flash.net.*;
16     import flash.external.ExternalInterface;
17
18     import net.systemeD.halcyon.connection.*;
19     import net.systemeD.halcyon.connection.EntityEvent;
20         import net.systemeD.halcyon.styleparser.*;
21         import net.systemeD.halcyon.Globals;
22
23 //      for experimental export function:
24 //      import flash.net.FileReference;
25 //      import com.adobe.images.JPGEncoder;
26
27     public class Map extends Sprite {
28
29                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
30                                                                                                                 // (for Landsat, 5120)
31                 public const MINSCALE:uint=13;                                  // don't zoom out past this
32                 public const MAXSCALE:uint=23;                                  // don't zoom in past this
33
34                 public var paint:MapPaint;                                              // sprite for ways and (POI/tagged) nodes in core layer
35                 public var vectorbg:Sprite;                                             // sprite for vector background layers
36
37                 public var scale:uint=14;                                               // map scale
38                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
39                 public var bigedge_l:Number= 999999;                    // area of largest whichways
40                 public var bigedge_r:Number=-999999;                    //  |
41                 public var bigedge_b:Number= 999999;                    //  |
42                 public var bigedge_t:Number=-999999;                    //  |
43
44                 public var edge_l:Number;                                               // current bounding box
45                 public var edge_r:Number;                                               //  |
46                 public var edge_t:Number;                                               //  |
47                 public var edge_b:Number;                                               //  |
48                 public var centre_lat:Number;                                   // centre lat/lon
49                 public var centre_lon:Number;                                   //  |
50
51                 public var baselon:Number;                                              // urllon-xradius/masterscale;
52                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
53                 public var mapwidth:uint;                                               // width (Flash pixels)
54                 public var mapheight:uint;                                              // height (Flash pixels)
55
56                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map
57                 private var _draggable:Boolean=true;                    //  |
58                 private var lastxmouse:Number;                                  //  |
59                 private var lastymouse:Number;                                  //  |
60                 private var downX:Number;                                               //  |
61                 private var downY:Number;                                               //  |
62                 private var downTime:Number;                                    //  |
63                 public const NOT_DRAGGING:uint=0;                               //  |
64                 public const NOT_MOVED:uint=1;                                  //  |
65                 public const DRAGGING:uint=2;                                   //  |
66                 public const TOLERANCE:uint=7;                                  //  |
67                 
68                 public var initparams:Object;                                   // object containing HTML page parameters
69
70                 public var backdrop:Object;                                             // reference to backdrop sprite
71                 public var tileset:TileSet;                                             // background tile object
72                 private var tileparams:Object={ url:'' };               // background tile URL, name and scheme
73                 private var styleurl:String='';                                 // internal style URL
74                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
75                 
76                 public var connection:Connection;                               // server connection
77                 public var vectorlayers:Object={};                              // VectorLayer objects 
78                 
79                 // ------------------------------------------------------------------------------------------
80                 // Map constructor function
81
82         public function Map(initparams:Object) {
83
84                         this.initparams=initparams;
85                         connection = Connection.getConnection(initparams);
86             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
87             connection.addEventListener(Connection.NEW_POI, newPOICreated);
88             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
89             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
90                         gotEnvironment(null);
91
92                         addEventListener(Event.ENTER_FRAME, everyFrame);
93                         scrollRect=new Rectangle(0,0,800,600);
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                         if (initparams['tileblocks']) {                         //   | option to block dodgy tile sources
126                                 tileset.blocks=initparams['tileblocks'];//   |
127                         }                                                                                       //   |
128                         addChild(tileset);                                                      //   |
129                         tileset.init(tileparams, false, 
130                                      initparams['background_dim']    ==null ? true  : initparams['background_dim'],
131                                      initparams['background_sharpen']==null ? false : initparams['background_sharpen']);
132
133                         vectorbg = new Sprite();                                        // 1 - vector background layers
134                         addChild(vectorbg);                                                     //   |
135
136                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
137                         addChild(paint);                                                        //   |
138                         paint.isBackground=false;                                       //   |
139
140                         if (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
141                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
142                                 paint.ruleset.loadFromCSS(styleurl);
143                         }
144                         if (startscale>0) {
145                                 scale=startscale;
146                                 this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
147                         }
148
149                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
150                         baselon    =startlon          -(mapwidth /2)/scalefactor;
151                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
152                         addDebug("Baselon "+baselon+", basey "+basey);
153                         updateCoords(0,0);
154             this.dispatchEvent(new Event(MapEvent.INITIALISED));
155                         download();
156
157             if (ExternalInterface.available) {
158               ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
159                   updateCoordsFromLatLon(lat, lon);
160                   changeScale(zoom);
161               });
162             }
163         }
164
165                 // ------------------------------------------------------------------------------------------
166                 // Recalculate co-ordinates from new Flash origin
167
168                 public function updateCoords(tx:Number,ty:Number):void {
169                         setScrollRectXY(tx,ty);
170
171                         edge_t=coord2lat(-ty          );
172                         edge_b=coord2lat(-ty+mapheight);
173                         edge_l=coord2lon(-tx          );
174                         edge_r=coord2lon(-tx+mapwidth );
175                         setCentre();
176
177                         tileset.update();
178                 }
179                 
180                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
181                         var cy:Number=-(lat2coord(lat)-mapheight/2);
182                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
183                         updateCoords(cx,cy);
184                 }
185                 
186                 private function setScrollRectXY(tx:Number,ty:Number):void {
187                         var w:Number=scrollRect.width;
188                         var h:Number=scrollRect.height;
189                         scrollRect=new Rectangle(-tx,-ty,w,h);
190                 }
191                 private function setScrollRectSize(width:Number,height:Number):void {
192                         var sx:Number=scrollRect.x ? scrollRect.x : 0;
193                         var sy:Number=scrollRect.y ? scrollRect.y : 0;
194                         scrollRect=new Rectangle(sx,sy,width,height);
195                 }
196                 
197                 private function getX():Number { return -scrollRect.x; }
198                 private function getY():Number { return -scrollRect.y; }
199                 
200                 private function setCentre():void {
201                         centre_lat=coord2lat(-getY()+mapheight/2);
202                         centre_lon=coord2lon(-getX()+mapwidth/2);
203                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale, minlon:edge_l, maxlon:edge_r, minlat:edge_b, maxlat:edge_t}));
204                 }
205                 
206                 public function nudgeBackground(x:Number,y:Number):void {
207                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
208                 }
209
210                 private function moveMap(dx:Number,dy:Number):void {
211                         updateCoords(getX()+dx,getY()+dy);
212                         updateEntityUIs(false, false);
213                         download();
214                 }
215
216                 // Co-ordinate conversion functions
217
218                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
219                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
220                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
221                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
222
223                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
224                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
225
226                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
227                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
228
229
230                 // ------------------------------------------------------------------------------------------
231                 // Resize map size based on current stage and height
232
233                 public function updateSize(w:uint, h:uint):void {
234                         mapwidth = w; centre_lon=coord2lon(-getX()+w/2);
235                         mapheight= h; centre_lat=coord2lat(-getY()+h/2);
236                         setScrollRectSize(w,h);
237
238                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
239                         
240             if ( backdrop != null ) {
241                 backdrop.width=mapwidth;
242                 backdrop.height=mapheight;
243             }
244             if ( mask != null ) {
245                 mask.width=mapwidth;
246                 mask.height=mapheight;
247             }
248                 }
249
250         /** Download map data. Data is downloaded for the connection and the vector layers, where supported.
251         * The bounding box for the download is taken from the current map edges.
252         */
253                 public function download():void {
254                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
255                         
256                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
257                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
258                         bigedge_l=edge_l; bigedge_r=edge_r;
259                         bigedge_b=edge_b; bigedge_t=edge_t;
260                         if (connection.waycount>1000) {
261                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
262                         }
263                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
264                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
265
266             // Do the same for vector layers
267             for each (var layer:VectorLayer in vectorlayers) {
268               layer.loadBbox(edge_l,edge_r,edge_t,edge_b);
269             }
270                 }
271
272         private function newWayCreated(event:EntityEvent):void {
273             var way:Way = event.entity as Way;
274                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
275                         paint.createWayUI(way);
276         }
277
278         private function newPOICreated(event:EntityEvent):void {
279             var node:Node = event.entity as Node;
280                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
281                         paint.createNodeUI(node);
282         }
283
284                 private function wayRenumbered(event:EntityRenumberedEvent):void {
285             var way:Way = event.entity as Way;
286                         paint.renumberWayUI(way,event.oldID);
287                 }
288
289                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
290             var node:Node = event.entity as Node;
291                         paint.renumberNodeUI(node,event.oldID);
292                 }
293
294         public function setHighlight(entity:Entity, settings:Object):void {
295                         if      ( entity is Way  && paint.wayuis[entity.id] ) { paint.wayuis[entity.id].setHighlight(settings);  }
296                         else if ( entity is Node && paint.nodeuis[entity.id]) { paint.nodeuis[entity.id].setHighlight(settings); }
297         }
298
299         public function setHighlightOnNodes(way:Way, settings:Object):void {
300                         if (paint.wayuis[way.id]) paint.wayuis[way.id].setHighlightOnNodes(settings);
301         }
302
303                 public function protectWay(way:Way):void {
304                         if (paint.wayuis[way.id]) paint.wayuis[way.id].protectSprites();
305                 }
306
307                 public function unprotectWay(way:Way):void {
308                         if (paint.wayuis[way.id]) paint.wayuis[way.id].unprotectSprites();
309                 }
310                 
311                 public function limitWayDrawing(way:Way,except:Number=NaN,only:Number=NaN):void {
312                         if (!paint.wayuis[way.id]) return;
313                         paint.wayuis[way.id].drawExcept=except;
314                         paint.wayuis[way.id].drawOnly  =only;
315                         paint.wayuis[way.id].redraw();
316                 }
317
318                 /* Protect Entities and EntityUIs against purging. This prevents the currently selected items
319                    from being purged even though they're off-screen. */
320
321                 public function setPurgable(entities:Array, purgable:Boolean):void {
322                         for each (var entity:Entity in entities) {
323                                 entity.locked=!purgable;
324                                 if ( entity is Way  ) {
325                                         var way:Way=entity as Way;
326                                         if (paint.wayuis[way.id]) { paint.wayuis[way.id].purgable=purgable; }
327                                         for (var i:uint=0; i<way.length; i++) {
328                                                 var node:Node=way.getNode(i)
329                                                 node.locked=!purgable;
330                                                 if (paint.nodeuis[node.id]) { paint.nodeuis[node.id].purgable=purgable; }
331                                         }
332                                 } else if ( entity is Node && paint.nodeuis[entity.id]) { 
333                                         paint.nodeuis[entity.id].purgable=purgable;
334                                 }
335                         }
336                 }
337
338         // Handle mouse events on ways/nodes
339         private var mapController:MapController = null;
340
341         public function setController(controller:MapController):void {
342             this.mapController = controller;
343         }
344
345         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
346             if ( mapController != null )
347                 mapController.entityMouseEvent(event, entity);
348                                 
349         }
350
351                 // ------------------------------------------------------------------------------------------
352                 // Add vector layer
353                 
354                 public function addVectorLayer(layer:VectorLayer):void {
355                         vectorlayers[layer.name]=layer;
356                         vectorbg.addChild(layer.paint);
357                 }
358
359                 // ------------------------------------------------------------------------------------------
360                 // Redraw all items, zoom in and out
361                 
362                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
363                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
364                         for each (var v:VectorLayer in vectorlayers) {
365                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
366                         }
367                 }
368                 public function redraw():void {
369                         paint.redraw();
370                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
371                 }
372                 public function redrawPOIs():void { 
373                         paint.redrawPOIs();
374                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
375                 }
376                 
377                 public function zoomIn():void {
378                         if (scale==MAXSCALE) { return; }
379                         changeScale(scale+1);
380                 }
381
382                 public function zoomOut():void {
383                         if (scale==MINSCALE) { return; }
384                         changeScale(scale-1);
385                 }
386
387                 private function changeScale(newscale:uint):void {
388                         addDebug("new scale "+newscale);
389                         scale=newscale;
390                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
391                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
392                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
393                         tileset.changeScale(scale);
394                         updateEntityUIs(true,true);
395                         download();
396                 }
397
398                 private function reportPosition():void {
399                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
400                 }
401                 
402                 public function setStyle(url:String):void {
403                         styleurl=url;
404                         if (paint) { 
405                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
406                                 paint.ruleset.loadFromCSS(url);
407                         }
408         }
409
410                 public function setBackground(bg:Object):void {
411                         tileparams=bg;
412                         if (tileset) { tileset.init(bg, bg.url!=''); }
413                 }
414
415                 public function setDimming(dim:Boolean):void {
416                         if (tileset) { tileset.setDimming(dim); }
417                 }
418                 public function getDimming():Boolean {
419                         if (tileset) { return tileset.getDimming(); }
420                         return true;
421                 }
422
423                 public function setSharpen(sharpen:Boolean):void {
424                         if (tileset) { tileset.setSharpen(sharpen); }
425                 }
426                 public function getSharpen():Boolean {
427                         if (tileset) { return tileset.getSharpen(); }
428                         return false;
429                 }
430
431                 // ------------------------------------------------------------------------------------------
432                 // Export (experimental)
433                 // ** just a bit of fun for now!
434                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
435                 // to that area (will probably require creating a new DisplayObject with a different origin
436                 // and mask)
437 /*              
438                 public function export():void {
439                         addDebug("size is "+this.width+","+this.height);
440                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
441                         jpgSource.draw(this);
442                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
443                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
444                         var fileRef:FileReference = new FileReference();
445 //                      fileRef.save(jpgStream,'map.jpeg');
446                 }
447
448 */
449
450                 // ==========================================================================================
451                 // Events
452                 
453                 // ------------------------------------------------------------------------------------------
454                 // Mouse events
455                 
456                 public function set draggable(draggable:Boolean):void {
457                         _draggable=draggable;
458                         dragstate=NOT_DRAGGING;
459                 }
460
461                 public function mouseDownHandler(event:MouseEvent):void {
462                         if (!_draggable) { return; }
463                         dragstate=NOT_MOVED;
464                         lastxmouse=stage.mouseX; downX=stage.mouseX;
465                         lastymouse=stage.mouseY; downY=stage.mouseY;
466                         downTime=new Date().getTime();
467                 }
468         
469                 public function mouseUpHandler(event:MouseEvent=null):void {
470                         if (dragstate==DRAGGING) { moveMap(x,y); }
471                         dragstate=NOT_DRAGGING;
472                 }
473         
474                 public function mouseMoveHandler(event:MouseEvent):void {
475                         if (!_draggable) { return; }
476                         if (dragstate==NOT_DRAGGING) { return; }
477                         
478                         if (dragstate==NOT_MOVED) {
479                                 if (new Date().getTime()-downTime<300) {
480                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
481                                 } else {
482                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
483                                 }
484                                 dragstate=DRAGGING;
485                         }
486                         
487                         setScrollRectXY(getX()+stage.mouseX-lastxmouse,getY()+stage.mouseY-lastymouse);
488                         lastxmouse=stage.mouseX; lastymouse=stage.mouseY;
489                         setCentre();
490                 }
491         
492                 // ------------------------------------------------------------------------------------------
493                 // Do every frame
494
495                 private function everyFrame(event:Event):void {
496                         if (tileset) { tileset.serviceQueue(); }
497                 }
498
499                 // ------------------------------------------------------------------------------------------
500                 // Miscellaneous events
501                 
502                 public function keyUpHandler(event:KeyboardEvent):void {
503                         if (event.target is TextField) return;                          // not meant for us
504                         switch (event.keyCode) {
505                                 case 33:        zoomIn(); break;                                        // Page Up - zoom in
506                                 case 34:        zoomOut(); break;                                       // Page Down - zoom out
507                                 case 37:        moveMap(mapwidth/2,0); break;           // left cursor
508                                 case 38:        moveMap(0,mapheight/2); break;          // up cursor
509                                 case 39:        moveMap(-mapwidth/2,0); break;          // right cursor
510                                 case 40:        moveMap(0,-mapheight/2); break;         // down cursor
511 //                              case 76:        reportPosition(); break;                        // L - report lat/long
512                         }
513                 }
514
515                 public function connectionError(err:Object=null): void {
516                         addDebug("got error"); 
517                 }
518
519                 // ------------------------------------------------------------------------------------------
520                 // Debugging
521                 
522                 public function clearDebug():void {
523                         if (!Globals.vars.hasOwnProperty('debug')) return;
524                         Globals.vars.debug.text='';
525                 }
526                         
527                 public function addDebug(text:String):void {
528                         trace(text);
529                         if (!Globals.vars.hasOwnProperty('debug')) return;
530                         if (!Globals.vars.debug.visible) return;
531                         Globals.vars.debug.appendText(text+"\n");
532                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
533                 }
534
535         }
536 }