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