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