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