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