remember background imagery; infinite sublayers; bugfixes
[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.vectorlayers.*;
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=19;                                  // 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                 public const NOT_DRAGGING:uint=0;                               //  |
62                 public const NOT_MOVED:uint=1;                                  //  |
63                 public const DRAGGING:uint=2;                                   //  |
64                 
65                 public var initparams:Object;                                   // object containing HTML page parameters
66
67                 public var backdrop:Object;                                             // reference to backdrop sprite
68                 public var tileset:TileSet;                                             // 900913 tile background
69                 private var tileurl:String='';                                  // internal tile URL and priority - allows setting before tileset inited
70                 private var tileprio:uint=0;                                    //  | 
71                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
72                 
73                 public var connection:Connection;                               // server connection
74                 public var vectorlayers:Array=[];                               // VectorLayer objects 
75
76                 public const TILESPRITE:uint=0;
77                 public const VECTORSPRITE:uint=1;
78                 public const WAYSPRITE:uint=2;
79                 public const NAMESPRITE:uint=13;
80                 
81                 // ------------------------------------------------------------------------------------------
82                 // Map constructor function
83
84         public function Map(initparams:Object) {
85
86                         this.initparams=initparams;
87                         connection = Connection.getConnection(initparams);
88             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
89             connection.addEventListener(Connection.NEW_POI, newPOICreated);
90             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
91             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
92                         gotEnvironment(null);
93
94                         addEventListener(Event.ENTER_FRAME, everyFrame);
95         }
96
97                 public function gotEnvironment(r:Object):void {
98                         var loader:Loader = new Loader();
99                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
100                         loader.load(new URLRequest("FontLibrary.swf"));
101                 }
102                 
103                 public function gotFont(r:Event):void {
104                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
105                         Font.registerFont(FontLibrary.DejaVu);
106
107                         if (initparams['lat'] != null) {
108                                 // parameters sent from HTML
109                                 init(initparams['lat'],
110                                          initparams['lon'],
111                                          initparams['zoom'],
112                                          initparams['style']);
113
114                         } else {
115                                 // somewhere innocuous
116                                 init(53.09465,-2.56495,17,"test.css?d="+Math.random());
117                         }
118                 }
119
120                 // ------------------------------------------------------------------------------------------
121                 // Initialise map at a given lat/lon
122
123         public function init(startlat:Number,startlon:Number,startscale:uint=0,style:String=null):void {
124                         while (numChildren) { removeChildAt(0); }
125
126                         tileset=new TileSet(this);                                      // 0 - 900913 background
127                         addChild(tileset);                                                      //   |
128                         tileset.init(tileurl);                                          //   |
129
130                         vectorbg = new Sprite();                                        // 1 - vector background layers
131                         addChild(vectorbg);                                                     //   |
132
133                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
134                         addChild(paint);                                                        //   |
135                         paint.isBackground=false;                                       //   |
136
137                         if (style) {
138                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
139                                 paint.ruleset.loadFromCSS(style);
140                         }
141                         if (startscale>0) { scale=startscale; }
142
143                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
144                         baselon    =startlon          -(mapwidth /2)/scalefactor;
145                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
146                         addDebug("Baselon "+baselon+", basey "+basey);
147                         updateCoords(0,0);
148                         download();
149                         
150         }
151
152                 // ------------------------------------------------------------------------------------------
153                 // Recalculate co-ordinates from new Flash origin
154
155                 public function updateCoords(tx:Number,ty:Number):void {
156                         x=tx; y=ty;
157
158                         edge_t=coord2lat(-y          );
159                         edge_b=coord2lat(-y+mapheight);
160                         edge_l=coord2lon(-x          );
161                         edge_r=coord2lon(-x+mapwidth );
162                         setCentre();
163
164                         tileset.update();
165                 }
166                 
167                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
168                         var cy:Number=-(lat2coord(lat)-mapheight/2);
169                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
170                         updateCoords(cx,cy);
171                 }
172                 
173                 private function setCentre():void {
174                         centre_lat=coord2lat(-y+mapheight/2);
175                         centre_lon=coord2lon(-x+mapwidth/2);
176                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale}));
177                 }
178                 
179                 public function nudgeBackground(x:Number,y:Number):void {
180                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
181                 }
182
183                 // Co-ordinate conversion functions
184
185                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
186                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
187                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
188                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
189
190                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
191                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
192
193                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
194                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
195
196 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
197 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
198
199
200                 // ------------------------------------------------------------------------------------------
201                 // Resize map size based on current stage and height
202
203                 public function updateSize(w:uint, h:uint):void {
204                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
205                         
206                         mapwidth = w;
207                         mapheight= h;
208             if ( backdrop != null ) {
209                 backdrop.width=mapwidth;
210                 backdrop.height=mapheight;
211             }
212             if ( mask != null ) {
213                 mask.width=mapwidth;
214                 mask.height=mapheight;
215             }
216                 }
217
218                 // ------------------------------------------------------------------------------------------
219                 // Download map data
220                 // (typically from whichways, but will want to add more connections)
221
222                 public function download():void {
223                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
224                         
225                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
226                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
227                         bigedge_l=edge_l; bigedge_r=edge_r;
228                         bigedge_b=edge_b; bigedge_t=edge_t;
229                         if (connection.waycount>1000) {
230                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
231                         }
232                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
233                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
234                 }
235
236         private function newWayCreated(event:EntityEvent):void {
237             var way:Way = event.entity as Way;
238                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
239                         paint.createWayUI(way);
240         }
241
242         private function newPOICreated(event:EntityEvent):void {
243             var node:Node = event.entity as Node;
244                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
245                         var nodeui:NodeUI=paint.createNodeUI(node);
246                         nodeui.redraw();
247         }
248
249                 private function wayRenumbered(event:EntityRenumberedEvent):void {
250             var way:Way = event.entity as Way;
251                         paint.renumberWayUI(way,event.oldID);
252                 }
253
254                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
255             var node:Node = event.entity as Node;
256                         paint.renumberNodeUI(node,event.oldID);
257                 }
258
259         public function setHighlight(entity:Entity, settings:Object):void {
260                         var stateType:String;
261                         var ui:EntityUI=null;
262                         if      ( entity is Way  ) { ui = paint.wayuis[entity.id]; }
263                         else if ( entity is Node ) { ui = paint.nodeuis[entity.id]; }
264                         if (ui==null) { return; }
265                         for (stateType in settings) {
266                                 ui.setHighlight(stateType, settings[stateType]);
267                         }
268                         ui.redraw();
269         }
270
271         // Handle mouse events on ways/nodes
272         private var mapController:MapController = null;
273
274         public function setController(controller:MapController):void {
275             this.mapController = controller;
276         }
277
278         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
279             if ( mapController != null )
280                 mapController.entityMouseEvent(event, entity);
281                                 
282         }
283
284                 // ------------------------------------------------------------------------------------------
285                 // Redraw all items, zoom in and out
286                 
287                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
288                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
289                         for each (var v:VectorLayer in vectorlayers) {
290                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
291                         }
292                 }
293                 public function redraw():void {
294                         paint.redraw();
295                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
296                 }
297                 public function redrawPOIs():void { 
298                         paint.redrawPOIs();
299                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
300                 }
301                 
302                 public function zoomIn():void {
303                         if (scale==MAXSCALE) { return; }
304                         changeScale(scale+1);
305                 }
306
307                 public function zoomOut():void {
308                         if (scale==MINSCALE) { return; }
309                         changeScale(scale-1);
310                 }
311
312                 private function changeScale(newscale:uint):void {
313                         addDebug("new scale "+newscale);
314                         scale=newscale;
315                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
316                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
317                         tileset.changeScale(scale);
318                         updateEntityUIs(true,true);
319                         download();
320                 }
321
322                 private function reportPosition():void {
323                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
324                 }
325                 
326                 public function setStyle(style:String):void {
327                         if (style) {
328                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
329                                 paint.ruleset.loadFromCSS(style);
330                         }
331         }
332
333                 public function setBackground(url:String,priority:int):Boolean {
334                         if (priority<tileprio) { return false; }
335                         tileurl=url; tileprio=priority;
336                         if (tileset) { tileset.init(url, url!=''); }
337                         return true;
338                 }
339
340                 public function setDimming(dim:Boolean):void {
341                         if (tileset) { tileset.setDimming(dim); }
342                 }
343
344                 // ------------------------------------------------------------------------------------------
345                 // Export (experimental)
346                 // ** just a bit of fun for now!
347                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
348                 // to that area (will probably require creating a new DisplayObject with a different origin
349                 // and mask)
350 /*              
351                 public function export():void {
352                         addDebug("size is "+this.width+","+this.height);
353                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
354                         jpgSource.draw(this);
355                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
356                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
357                         var fileRef:FileReference = new FileReference();
358 //                      fileRef.save(jpgStream,'map.jpeg');
359                 }
360
361 */
362
363                 // ==========================================================================================
364                 // Events
365                 
366                 // ------------------------------------------------------------------------------------------
367                 // Mouse events
368                 
369                 public function set draggable(draggable:Boolean):void {
370                         _draggable=draggable;
371                         dragstate=NOT_DRAGGING;
372                 }
373
374                 public function mouseDownHandler(event:MouseEvent):void {
375                         if (!_draggable) { return; }
376                         dragstate=NOT_MOVED;
377                         lastxmouse=downX=mouseX;
378                         lastymouse=downY=mouseY;
379                 }
380         
381                 public function mouseUpHandler(event:MouseEvent):void {
382                         if (dragstate==DRAGGING) {
383                                 updateCoords(x,y);
384                                 updateEntityUIs(false, false);
385                                 download();
386                         }
387                         dragstate=NOT_DRAGGING;
388                 }
389         
390                 public function mouseMoveHandler(event:MouseEvent):void {
391                         if (!_draggable) { return; }
392                         if (dragstate==NOT_DRAGGING) { return; }
393                         
394                         if (dragstate==NOT_MOVED && Math.abs(downX - mouseX) < 3 && Math.abs(downY - mouseY) < 3) {
395                                 return;
396                         }
397                         
398                         dragstate=DRAGGING;
399                         x+=mouseX-lastxmouse;
400                         y+=mouseY-lastymouse;
401                         lastxmouse=mouseX; lastymouse=mouseY;
402                         setCentre();
403                 }
404         
405                 // ------------------------------------------------------------------------------------------
406                 // Do every frame
407
408                 private function everyFrame(event:Event):void {
409                         if (tileset) { tileset.serviceQueue(); }
410                 }
411
412                 // ------------------------------------------------------------------------------------------
413                 // Miscellaneous events
414                 
415                 public function keyUpHandler(event:KeyboardEvent):void {
416                         if ( !event.ctrlKey ) return;
417                         addDebug("pressed "+event.keyCode);
418                         if (event.keyCode==73) { zoomIn(); }                    // I - zoom in
419                         if (event.keyCode==79) { zoomOut(); }                   // O - zoom out
420                         if (event.keyCode==76) { reportPosition(); }    // L - report lat/long
421                 }
422
423                 public function connectionError(err:Object=null): void {
424                         addDebug("got error"); 
425                 }
426
427                 // ------------------------------------------------------------------------------------------
428                 // Debugging
429                 
430                 public function clearDebug():void {
431                         if (!Globals.vars.hasOwnProperty('debug')) return;
432                         Globals.vars.debug.text='';
433                 }
434                         
435                 public function addDebug(text:String):void {
436                         if (!Globals.vars.hasOwnProperty('debug')) return;
437                         if (!Globals.vars.debug.visible) return;
438                         Globals.vars.debug.appendText(text+"\n");
439                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
440                 }
441
442         }
443 }