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