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