support Potlatch legacy tile scheme; don't support Google
[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             ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
154                 updateCoordsFromLatLon(lat, lon);
155                 changeScale(zoom);
156             });
157         }
158
159                 // ------------------------------------------------------------------------------------------
160                 // Recalculate co-ordinates from new Flash origin
161
162                 public function updateCoords(tx:Number,ty:Number):void {
163                         x=tx; y=ty;
164
165                         edge_t=coord2lat(-y          );
166                         edge_b=coord2lat(-y+mapheight);
167                         edge_l=coord2lon(-x          );
168                         edge_r=coord2lon(-x+mapwidth );
169                         setCentre();
170
171                         tileset.update();
172                 }
173                 
174                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
175                         var cy:Number=-(lat2coord(lat)-mapheight/2);
176                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
177                         updateCoords(cx,cy);
178                 }
179                 
180                 private function setCentre():void {
181                         centre_lat=coord2lat(-y+mapheight/2);
182                         centre_lon=coord2lon(-x+mapwidth/2);
183                         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}));
184                 }
185                 
186                 public function nudgeBackground(x:Number,y:Number):void {
187                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
188                 }
189
190                 private function moveMap(dx:Number,dy:Number):void {
191                         updateCoords(x+dx,y+dy);
192                         updateEntityUIs(false, false);
193                         download();
194                 }
195
196                 // Co-ordinate conversion functions
197
198                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
199                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
200                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
201                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
202
203                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
204                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
205
206                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
207                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
208
209 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
210 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
211
212
213                 // ------------------------------------------------------------------------------------------
214                 // Resize map size based on current stage and height
215
216                 public function updateSize(w:uint, h:uint):void {
217                         mapwidth = w; centre_lon=coord2lon(-x+w/2);
218                         mapheight= h; centre_lat=coord2lat(-y+h/2);
219
220                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
221                         
222             if ( backdrop != null ) {
223                 backdrop.width=mapwidth;
224                 backdrop.height=mapheight;
225             }
226             if ( mask != null ) {
227                 mask.width=mapwidth;
228                 mask.height=mapheight;
229             }
230                 }
231
232         /** Download map data. Data is downloaded for the connection and the vector layers, where supported.
233         * The bounding box for the download is taken from the current map edges.
234         */
235                 public function download():void {
236                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
237                         
238                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
239                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
240                         bigedge_l=edge_l; bigedge_r=edge_r;
241                         bigedge_b=edge_b; bigedge_t=edge_t;
242                         if (connection.waycount>1000) {
243                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
244                         }
245                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
246                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
247
248             // Do the same for vector layers
249             for each (var layer:VectorLayer in vectorlayers) {
250               layer.loadBbox(edge_l,edge_r,edge_t,edge_b);
251             }
252                 }
253
254         private function newWayCreated(event:EntityEvent):void {
255             var way:Way = event.entity as Way;
256                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
257                         paint.createWayUI(way);
258         }
259
260         private function newPOICreated(event:EntityEvent):void {
261             var node:Node = event.entity as Node;
262                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
263                         paint.createNodeUI(node);
264         }
265
266                 private function wayRenumbered(event:EntityRenumberedEvent):void {
267             var way:Way = event.entity as Way;
268                         paint.renumberWayUI(way,event.oldID);
269                 }
270
271                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
272             var node:Node = event.entity as Node;
273                         paint.renumberNodeUI(node,event.oldID);
274                 }
275
276         public function setHighlight(entity:Entity, settings:Object):void {
277                         if      ( entity is Way  && paint.wayuis[entity.id] ) { paint.wayuis[entity.id].setHighlight(settings);  }
278                         else if ( entity is Node && paint.nodeuis[entity.id]) { paint.nodeuis[entity.id].setHighlight(settings); }
279         }
280
281         public function setHighlightOnNodes(way:Way, settings:Object):void {
282                         if (paint.wayuis[way.id]) paint.wayuis[way.id].setHighlightOnNodes(settings);
283         }
284
285                 /* Protect Entities and EntityUIs against purging. This prevents the currently selected items
286                    from being purged even though they're off-screen. */
287
288                 public function setPurgable(entities:Array, purgable:Boolean):void {
289                         for each (var entity:Entity in entities) {
290                                 entity.locked=!purgable;
291                                 if ( entity is Way  ) {
292                                         var way:Way=entity as Way;
293                                         if (paint.wayuis[way.id]) { paint.wayuis[way.id].purgable=purgable; }
294                                         for (var i:uint=0; i<way.length; i++) {
295                                                 var node:Node=way.getNode(i)
296                                                 node.locked=!purgable;
297                                                 if (paint.nodeuis[node.id]) { paint.nodeuis[node.id].purgable=purgable; }
298                                         }
299                                 } else if ( entity is Node && paint.nodeuis[entity.id]) { 
300                                         paint.nodeuis[entity.id].purgable=purgable;
301                                 }
302                         }
303                 }
304
305         // Handle mouse events on ways/nodes
306         private var mapController:MapController = null;
307
308         public function setController(controller:MapController):void {
309             this.mapController = controller;
310         }
311
312         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
313             if ( mapController != null )
314                 mapController.entityMouseEvent(event, entity);
315                                 
316         }
317
318                 // ------------------------------------------------------------------------------------------
319                 // Add vector layer
320                 
321                 public function addVectorLayer(layer:VectorLayer):void {
322                         vectorlayers[layer.name]=layer;
323                         vectorbg.addChild(layer.paint);
324                 }
325
326                 // ------------------------------------------------------------------------------------------
327                 // Redraw all items, zoom in and out
328                 
329                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
330                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
331                         for each (var v:VectorLayer in vectorlayers) {
332                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
333                         }
334                 }
335                 public function redraw():void {
336                         paint.redraw();
337                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
338                 }
339                 public function redrawPOIs():void { 
340                         paint.redrawPOIs();
341                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
342                 }
343                 
344                 public function zoomIn():void {
345                         if (scale==MAXSCALE) { return; }
346                         changeScale(scale+1);
347                 }
348
349                 public function zoomOut():void {
350                         if (scale==MINSCALE) { return; }
351                         changeScale(scale-1);
352                 }
353
354                 private function changeScale(newscale:uint):void {
355                         addDebug("new scale "+newscale);
356                         scale=newscale;
357                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
358                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
359                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
360                         tileset.changeScale(scale);
361                         updateEntityUIs(true,true);
362                         download();
363                 }
364
365                 private function reportPosition():void {
366                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
367                 }
368                 
369                 public function setStyle(url:String):void {
370                         styleurl=url;
371                         if (paint) { 
372                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
373                                 paint.ruleset.loadFromCSS(url);
374                         }
375         }
376
377                 public function setBackground(bg:Object):void {
378                         tileparams=bg;
379                         if (tileset) { tileset.init(bg, bg.url!=''); }
380                 }
381
382                 public function setDimming(dim:Boolean):void {
383                         if (tileset) { tileset.setDimming(dim); }
384                 }
385
386                 public function setSharpen(sharpen:Boolean):void {
387                         if (tileset) { tileset.setSharpen(sharpen); }
388                 }
389
390                 // ------------------------------------------------------------------------------------------
391                 // Export (experimental)
392                 // ** just a bit of fun for now!
393                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
394                 // to that area (will probably require creating a new DisplayObject with a different origin
395                 // and mask)
396 /*              
397                 public function export():void {
398                         addDebug("size is "+this.width+","+this.height);
399                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
400                         jpgSource.draw(this);
401                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
402                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
403                         var fileRef:FileReference = new FileReference();
404 //                      fileRef.save(jpgStream,'map.jpeg');
405                 }
406
407 */
408
409                 // ==========================================================================================
410                 // Events
411                 
412                 // ------------------------------------------------------------------------------------------
413                 // Mouse events
414                 
415                 public function set draggable(draggable:Boolean):void {
416                         _draggable=draggable;
417                         dragstate=NOT_DRAGGING;
418                 }
419
420                 public function mouseDownHandler(event:MouseEvent):void {
421                         if (!_draggable) { return; }
422                         dragstate=NOT_MOVED;
423                         lastxmouse=mouseX; downX=stage.mouseX;
424                         lastymouse=mouseY; downY=stage.mouseY;
425                         downTime=new Date().getTime();
426                 }
427         
428                 public function mouseUpHandler(event:MouseEvent=null):void {
429                         if (dragstate==DRAGGING) { moveMap(0,0); }
430                         dragstate=NOT_DRAGGING;
431                 }
432         
433                 public function mouseMoveHandler(event:MouseEvent):void {
434                         if (!_draggable) { return; }
435                         if (dragstate==NOT_DRAGGING) { return; }
436                         
437                         if (dragstate==NOT_MOVED) {
438                                 if (new Date().getTime()-downTime<300) {
439                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
440                                 } else {
441                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
442                                 }
443                                 dragstate=DRAGGING;
444                         }
445                         
446                         x+=mouseX-lastxmouse;
447                         y+=mouseY-lastymouse;
448                         lastxmouse=mouseX; lastymouse=mouseY;
449                         setCentre();
450                 }
451         
452                 // ------------------------------------------------------------------------------------------
453                 // Do every frame
454
455                 private function everyFrame(event:Event):void {
456                         if (tileset) { tileset.serviceQueue(); }
457                 }
458
459                 // ------------------------------------------------------------------------------------------
460                 // Miscellaneous events
461                 
462                 public function keyUpHandler(event:KeyboardEvent):void {
463                         if (event.target is TextField) return;                          // not meant for us
464                         switch (event.keyCode) {
465                                 case 33:        zoomIn(); break;                                        // Page Up - zoom in
466                                 case 34:        zoomOut(); break;                                       // Page Down - zoom out
467                                 case 37:        moveMap(mapwidth/2,0); break;           // left cursor
468                                 case 38:        moveMap(0,mapheight/2); break;          // up cursor
469                                 case 39:        moveMap(-mapwidth/2,0); break;          // right cursor
470                                 case 40:        moveMap(0,-mapheight/2); break;         // down cursor
471 //                              case 76:        reportPosition(); break;                        // L - report lat/long
472                         }
473                 }
474
475                 public function connectionError(err:Object=null): void {
476                         addDebug("got error"); 
477                 }
478
479                 // ------------------------------------------------------------------------------------------
480                 // Debugging
481                 
482                 public function clearDebug():void {
483                         if (!Globals.vars.hasOwnProperty('debug')) return;
484                         Globals.vars.debug.text='';
485                 }
486                         
487                 public function addDebug(text:String):void {
488                         trace(text);
489                         if (!Globals.vars.hasOwnProperty('debug')) return;
490                         if (!Globals.vars.debug.visible) return;
491                         Globals.vars.debug.appendText(text+"\n");
492                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
493                 }
494
495         }
496 }