pull through POIs from vector background layers
[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;                                             // 900913 tile background
70                 private var tileurl:String='';                                  // internal tile URL
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                 public const TILESPRITE:uint=0;
78                 public const VECTORSPRITE:uint=1;
79                 public const WAYSPRITE:uint=2;
80                 public const NAMESPRITE:uint=13;
81                 
82                 // ------------------------------------------------------------------------------------------
83                 // Map constructor function
84
85         public function Map(initparams:Object) {
86
87                         this.initparams=initparams;
88                         connection = Connection.getConnection(initparams);
89             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
90             connection.addEventListener(Connection.NEW_POI, newPOICreated);
91             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
92             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
93                         gotEnvironment(null);
94
95                         addEventListener(Event.ENTER_FRAME, everyFrame);
96         }
97
98                 public function gotEnvironment(r:Object):void {
99                         var loader:Loader = new Loader();
100                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
101                         loader.load(new URLRequest("FontLibrary.swf"));
102                 }
103                 
104                 public function gotFont(r:Event):void {
105                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
106                         Font.registerFont(FontLibrary.DejaVu);
107
108                         if (initparams['lat'] != null) {
109                                 // parameters sent from HTML
110                                 init(initparams['lat'],
111                                          initparams['lon'],
112                                          initparams['zoom']);
113
114                         } else {
115                                 // somewhere innocuous
116                                 init(53.09465,-2.56495,17);
117                         }
118                 }
119
120                 // ------------------------------------------------------------------------------------------
121                 // Initialise map at a given lat/lon
122
123         public function init(startlat:Number,startlon:Number,startscale:uint=0):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 (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
138                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
139                                 paint.ruleset.loadFromCSS(styleurl);
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                 private function moveMap(dx:Number,dy:Number):void {
184                         updateCoords(x+dx,y+dy);
185                         updateEntityUIs(false, false);
186                         download();
187                 }
188
189                 // Co-ordinate conversion functions
190
191                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
192                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
193                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
194                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
195
196                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
197                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
198
199                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
200                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
201
202 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
203 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
204
205
206                 // ------------------------------------------------------------------------------------------
207                 // Resize map size based on current stage and height
208
209                 public function updateSize(w:uint, h:uint):void {
210                         mapwidth = w; centre_lon=coord2lon(-x+w/2);
211                         mapheight= h; centre_lat=coord2lat(-y+h/2);
212
213                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
214                         
215             if ( backdrop != null ) {
216                 backdrop.width=mapwidth;
217                 backdrop.height=mapheight;
218             }
219             if ( mask != null ) {
220                 mask.width=mapwidth;
221                 mask.height=mapheight;
222             }
223                 }
224
225                 // ------------------------------------------------------------------------------------------
226                 // Download map data
227                 // (typically from whichways, but will want to add more connections)
228
229                 public function download():void {
230                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
231                         
232                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
233                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
234                         bigedge_l=edge_l; bigedge_r=edge_r;
235                         bigedge_b=edge_b; bigedge_t=edge_t;
236                         if (connection.waycount>1000) {
237                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
238                         }
239                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
240                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
241                 }
242
243         private function newWayCreated(event:EntityEvent):void {
244             var way:Way = event.entity as Way;
245                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
246                         paint.createWayUI(way);
247         }
248
249         private function newPOICreated(event:EntityEvent):void {
250             var node:Node = event.entity as Node;
251                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
252                         paint.createNodeUI(node);
253         }
254
255                 private function wayRenumbered(event:EntityRenumberedEvent):void {
256             var way:Way = event.entity as Way;
257                         paint.renumberWayUI(way,event.oldID);
258                 }
259
260                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
261             var node:Node = event.entity as Node;
262                         paint.renumberNodeUI(node,event.oldID);
263                 }
264
265         public function setHighlight(entity:Entity, settings:Object):void {
266                         if      ( entity is Way  && paint.wayuis[entity.id] ) { paint.wayuis[entity.id].setHighlight(settings);  }
267                         else if ( entity is Node && paint.nodeuis[entity.id]) { paint.nodeuis[entity.id].setHighlight(settings); }
268         }
269
270         public function setHighlightOnNodes(way:Way, settings:Object):void {
271                         paint.wayuis[way.id].setHighlightOnNodes(settings);
272         }
273
274                 public function setPurgable(entity:Entity, purgable:Boolean):void {
275                         if ( entity is Way  ) {
276                                 var way:Way=entity as Way;
277                                 paint.wayuis[way.id].purgable=purgable;
278                                 for (var i:uint=0; i<way.length; i++) {
279                                         if (paint.nodeuis[way.getNode(i).id]) {
280                                                 paint.nodeuis[way.getNode(i).id].purgable=purgable;
281                                         }
282                                 }
283                         } else if ( entity is Node ) { 
284                                 paint.nodeuis[entity.id].purgable=purgable;
285                         }
286                 }
287
288         // Handle mouse events on ways/nodes
289         private var mapController:MapController = null;
290
291         public function setController(controller:MapController):void {
292             this.mapController = controller;
293         }
294
295         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
296             if ( mapController != null )
297                 mapController.entityMouseEvent(event, entity);
298                                 
299         }
300
301                 // ------------------------------------------------------------------------------------------
302                 // Add vector layer
303                 
304                 public function addVectorLayer(layer:VectorLayer):void {
305                         vectorlayers[layer.name]=layer;
306                         vectorbg.addChild(layer.paint);
307                 }
308
309                 // ------------------------------------------------------------------------------------------
310                 // Redraw all items, zoom in and out
311                 
312                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
313                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
314                         for each (var v:VectorLayer in vectorlayers) {
315                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
316                         }
317                 }
318                 public function redraw():void {
319                         paint.redraw();
320                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
321                 }
322                 public function redrawPOIs():void { 
323                         paint.redrawPOIs();
324                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
325                 }
326                 
327                 public function zoomIn():void {
328                         if (scale==MAXSCALE) { return; }
329                         changeScale(scale+1);
330                 }
331
332                 public function zoomOut():void {
333                         if (scale==MINSCALE) { return; }
334                         changeScale(scale-1);
335                 }
336
337                 private function changeScale(newscale:uint):void {
338                         addDebug("new scale "+newscale);
339                         scale=newscale;
340                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
341                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
342                         tileset.changeScale(scale);
343                         updateEntityUIs(true,true);
344                         download();
345                 }
346
347                 private function reportPosition():void {
348                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
349                 }
350                 
351                 public function setStyle(url:String):void {
352                         styleurl=url;
353                         if (paint) { 
354                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
355                                 paint.ruleset.loadFromCSS(url);
356                         }
357         }
358
359                 public function setBackground(url:String):void {
360                         tileurl=url;
361                         if (tileset) { tileset.init(url, url!=''); }
362                 }
363
364                 public function setDimming(dim:Boolean):void {
365                         if (tileset) { tileset.setDimming(dim); }
366                 }
367
368                 // ------------------------------------------------------------------------------------------
369                 // Export (experimental)
370                 // ** just a bit of fun for now!
371                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
372                 // to that area (will probably require creating a new DisplayObject with a different origin
373                 // and mask)
374 /*              
375                 public function export():void {
376                         addDebug("size is "+this.width+","+this.height);
377                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
378                         jpgSource.draw(this);
379                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
380                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
381                         var fileRef:FileReference = new FileReference();
382 //                      fileRef.save(jpgStream,'map.jpeg');
383                 }
384
385 */
386
387                 // ==========================================================================================
388                 // Events
389                 
390                 // ------------------------------------------------------------------------------------------
391                 // Mouse events
392                 
393                 public function set draggable(draggable:Boolean):void {
394                         _draggable=draggable;
395                         dragstate=NOT_DRAGGING;
396                 }
397
398                 public function mouseDownHandler(event:MouseEvent):void {
399                         if (!_draggable) { return; }
400                         dragstate=NOT_MOVED;
401                         lastxmouse=mouseX; downX=stage.mouseX;
402                         lastymouse=mouseY; downY=stage.mouseY;
403                         downTime=new Date().getTime();
404                 }
405         
406                 public function mouseUpHandler(event:MouseEvent=null):void {
407                         if (dragstate==DRAGGING) { moveMap(0,0); }
408                         dragstate=NOT_DRAGGING;
409                 }
410         
411                 public function mouseMoveHandler(event:MouseEvent):void {
412                         if (!_draggable) { return; }
413                         if (dragstate==NOT_DRAGGING) { return; }
414                         
415                         if (dragstate==NOT_MOVED) {
416                                 if (new Date().getTime()-downTime<300) {
417                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
418                                 } else {
419                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
420                                 }
421                                 dragstate=DRAGGING;
422                         }
423                         
424                         x+=mouseX-lastxmouse;
425                         y+=mouseY-lastymouse;
426                         lastxmouse=mouseX; lastymouse=mouseY;
427                         setCentre();
428                 }
429         
430                 // ------------------------------------------------------------------------------------------
431                 // Do every frame
432
433                 private function everyFrame(event:Event):void {
434                         if (tileset) { tileset.serviceQueue(); }
435                 }
436
437                 // ------------------------------------------------------------------------------------------
438                 // Miscellaneous events
439                 
440                 public function keyUpHandler(event:KeyboardEvent):void {
441                         if (event.target is TextField) return;                          // not meant for us
442                         switch (event.keyCode) {
443                                 case 33:        zoomIn(); break;                                        // Page Up - zoom in
444                                 case 34:        zoomOut(); break;                                       // Page Down - zoom out
445                                 case 37:        moveMap(mapwidth/2,0); break;           // left cursor
446                                 case 38:        moveMap(0,mapheight/2); break;          // up cursor
447                                 case 39:        moveMap(-mapwidth/2,0); break;          // right cursor
448                                 case 40:        moveMap(0,-mapheight/2); break;         // down cursor
449 //                              case 76:        reportPosition(); break;                        // L - report lat/long
450                         }
451                 }
452
453                 public function connectionError(err:Object=null): void {
454                         addDebug("got error"); 
455                 }
456
457                 // ------------------------------------------------------------------------------------------
458                 // Debugging
459                 
460                 public function clearDebug():void {
461                         if (!Globals.vars.hasOwnProperty('debug')) return;
462                         Globals.vars.debug.text='';
463                 }
464                         
465                 public function addDebug(text:String):void {
466                         if (!Globals.vars.hasOwnProperty('debug')) return;
467                         if (!Globals.vars.debug.visible) return;
468                         Globals.vars.debug.appendText(text+"\n");
469                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
470                 }
471
472         }
473 }