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