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