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