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