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