Download on resize
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.display.Loader;
4         import flash.display.Sprite;
5         import flash.events.*;
6         import flash.external.ExternalInterface;
7         import flash.geom.Rectangle;
8         import flash.net.*;
9         import flash.text.Font;
10         import flash.text.TextField;
11         import flash.ui.Keyboard;
12         
13         import net.systemeD.halcyon.connection.*;
14         import net.systemeD.halcyon.styleparser.*;
15
16 //      for experimental export function:
17 //      import flash.net.FileReference;
18 //      import com.adobe.images.JPGEncoder;
19
20     /** The representation of part of the map on the screen, including information about coordinates, background imagery, paint properties etc. */
21     public class Map extends Sprite {
22
23                 /** master map scale - how many Flash pixels in 1 degree longitude (for Landsat, 5120) */
24                 public const MASTERSCALE:Number=5825.4222222222; 
25                                                                                                 
26                 /** don't zoom out past this */
27                 public const MINSCALE:uint=13; 
28                 /** don't zoom in past this */
29                 public const MAXSCALE:uint=23; 
30
31                 // Container for MapPaint objects
32                 private var paintContainer:Sprite;
33
34                 /** map scale */
35                 public var scale:uint=14;                                                
36                 /** current scaling factor for lon/latp */
37                 public var scalefactor:Number=MASTERSCALE;
38
39                 public var edge_l:Number;                                               // current bounding box
40                 public var edge_r:Number;                                               //  |
41                 public var edge_t:Number;                                               //  |
42                 public var edge_b:Number;                                               //  |
43                 public var centre_lat:Number;                                   // centre lat/lon
44                 public var centre_lon:Number;                                   //  |
45
46                 /** urllon-xradius/masterscale; */ 
47                 public var baselon:Number;
48                 /** lat2lat2p(urllat)+yradius/masterscale; */
49                 public var basey:Number; 
50                 /** width (Flash pixels) */
51                 public var mapwidth:uint; 
52                 /** height (Flash pixels) */
53                 public var mapheight:uint; 
54
55                 /** Is the map being panned */
56                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map (panning)
57                 /** Can the map be panned */
58                 private var _draggable:Boolean=true;                    //  |
59                 private var lastxmouse:Number;                                  //  |
60                 private var lastymouse:Number;                                  //  |
61                 private var downX:Number;                                               //  |
62                 private var downY:Number;                                               //  |
63                 private var downTime:Number;                                    //  |
64                 public const NOT_DRAGGING:uint=0;                               //  |
65                 public const NOT_MOVED:uint=1;                                  //  |
66                 public const DRAGGING:uint=2;                                   //  |
67                 public const SWALLOW_MOUSEUP:uint=3;                    //  |
68                 /** How far the map can be dragged without actually triggering a pan. */
69                 public const TOLERANCE:uint=7;                                  //  |
70                 
71                 /** object containing HTML page parameters: lat, lon, zoom, background_dim, background_sharpen, tileblocks */
72                 public var initparams:Object; 
73
74                 /** reference to backdrop sprite */
75                 public var backdrop:Object; 
76                 /** background tile object */
77                 public var tileset:TileSet; 
78                 /** show all objects, even if unstyled? */
79                 public var showall:Boolean=true; 
80                 
81                 // ------------------------------------------------------------------------------------------
82                 /** Map constructor function */
83         public function Map() {
84                         // Remove any existing sprites
85                         while (numChildren) { removeChildAt(0); }
86
87                         // 900913 background
88                         tileset=new TileSet(this);
89                         addChild(tileset);
90
91                         // Container for all MapPaint objects
92                         paintContainer = new Sprite();
93                         addChild(paintContainer);
94
95                         addEventListener(Event.ENTER_FRAME, everyFrame);
96                         scrollRect=new Rectangle(0,0,800,600);
97
98                         if (ExternalInterface.available) {
99                                 ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
100                                         updateCoordsFromLatLon(lat, lon);
101                                         changeScale(zoom);
102                                 });
103                         }
104                 }
105
106                 // ------------------------------------------------------------------------------------------
107                 /** Initialise map at a given lat/lon */
108         public function init(startlat:Number, startlon:Number, startscale:uint=0):void {
109                         if (startscale>0) {
110                                 scale=startscale;
111                                 this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
112                         }
113                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
114                         baselon    =startlon          -(mapwidth /2)/scalefactor;
115                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
116                         updateCoords(0,0);
117             this.dispatchEvent(new Event(MapEvent.INITIALISED));
118                         download();
119         }
120
121                 // ------------------------------------------------------------------------------------------
122                 /** Recalculate co-ordinates from new Flash origin */
123
124                 private function updateCoords(tx:Number,ty:Number):void {
125                         setScrollRectXY(tx,ty);
126
127                         edge_t=coord2lat(-ty          );
128                         edge_b=coord2lat(-ty+mapheight);
129                         edge_l=coord2lon(-tx          );
130                         edge_r=coord2lon(-tx+mapwidth );
131                         setCentre();
132
133                         tileset.update();
134                 }
135                 
136                 /** Move the map to centre on a given latitude/longitude. */
137                 private function updateCoordsFromLatLon(lat:Number,lon:Number):void {
138                         var cy:Number=-(lat2coord(lat)-mapheight/2);
139                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
140                         updateCoords(cx,cy);
141                 }
142                 
143                 private function setScrollRectXY(tx:Number,ty:Number):void {
144                         var w:Number=scrollRect.width;
145                         var h:Number=scrollRect.height;
146                         scrollRect=new Rectangle(-tx,-ty,w,h);
147                 }
148                 private function setScrollRectSize(width:Number,height:Number):void {
149                         var sx:Number=scrollRect.x ? scrollRect.x : 0;
150                         var sy:Number=scrollRect.y ? scrollRect.y : 0;
151                         scrollRect=new Rectangle(sx,sy,width,height);
152                 }
153                 
154                 private function getX():Number { return -scrollRect.x; }
155                 private function getY():Number { return -scrollRect.y; }
156                 
157                 private function setCentre():void {
158                         centre_lat=coord2lat(-getY()+mapheight/2);
159                         centre_lon=coord2lon(-getX()+mapwidth/2);
160                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale, minlon:edge_l, maxlon:edge_r, minlat:edge_b, maxlat:edge_t}));
161                 }
162                 
163                 /** Sets the offset between the background imagery and the map. */
164                 public function nudgeBackground(x:Number,y:Number):void {
165                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
166                 }
167
168                 private function moveMap(dx:Number,dy:Number):void {
169                         updateCoords(getX()+dx,getY()+dy);
170                         updateAllEntityUIs(false, false);
171                         download();
172                 }
173                 
174                 /** Recentre map at given lat/lon, updating the UI and downloading entities. */
175                 public function moveMapFromLatLon(lat:Number,lon:Number):void {
176                         updateCoordsFromLatLon(lat,lon);
177                         updateAllEntityUIs(false,false);
178                         download();
179                 }
180                 
181                 /** Recentre map at given lat/lon, if that point is currently outside the visible area. */
182                 public function scrollIfNeeded(lat:Number,lon:Number): void{
183             if (lat> edge_t || lat < edge_b || lon < edge_l || lon > edge_r) {
184                 moveMapFromLatLon(lat, lon);
185             }
186                 }
187
188                 // Co-ordinate conversion functions
189
190                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
191                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
192                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
193                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
194
195                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
196                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
197
198                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
199                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
200
201
202                 // ------------------------------------------------------------------------------------------
203                 /** Resize map size based on current stage and height */
204
205                 public function updateSize(w:uint, h:uint):void {
206                         mapwidth = w; centre_lon=coord2lon(-getX()+w/2);
207                         mapheight= h; centre_lat=coord2lat(-getY()+h/2);
208                         setScrollRectSize(w,h);
209                         updateCoords(getX(),getY());
210
211                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
212                         
213             if ( backdrop != null ) {
214                 backdrop.width=mapwidth;
215                 backdrop.height=mapheight;
216             }
217             if ( mask != null ) {
218                 mask.width=mapwidth;
219                 mask.height=mapheight;
220             }
221                 }
222
223         /** Download map data. Data is downloaded for the currently visible layers
224         * The bounding box for the download is taken from the current map edges.
225         */
226                 public function download():void {
227                         for (var i:uint=0; i<paintContainer.numChildren; i++)
228                                 if(getLayerAt(i).visible == true) {
229                     getLayerAt(i).connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
230                 }
231                 }
232
233         // Handle mouse events on ways/nodes
234         private var mapController:MapController = null;
235
236         /** Assign map controller. */
237         public function setController(controller:MapController):void {
238             this.mapController = controller;
239         }
240
241         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
242             if ( mapController != null )
243                 mapController.entityMouseEvent(event, entity);
244         }
245
246                 // ------------------------------------------------------------------------------------------
247                 // Add layers
248                 
249                 public function addLayer(connection:Connection, styleurl:String, backgroundlayer:Boolean=true, interactive:Boolean=false):MapPaint {
250                         var paint:MapPaint=new MapPaint(this, connection, styleurl, -5, 5);
251                         paintContainer.addChildAt(paint,0);
252                         paint.isBackground=backgroundlayer;
253                         paint.interactive=interactive;
254                         return paint;
255                 }
256
257                 public function removeLayerByName(name:String):void {
258                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
259                                 if (getLayerAt(i).connection.name==name)
260                                         paintContainer.removeChildAt(i);
261                                         // >>>> REFACTOR: needs to do the equivalent of VectorLayer.blank()
262                         }
263                 }
264                 
265                 public function findLayer(name:String):MapPaint {
266                         for (var i:uint=0; i<paintContainer.numChildren; i++)
267                                 if (getLayerAt(i).connection.name==name) return getLayerAt(i);
268                         return null;
269                 }
270
271                 private function getLayerAt(i:uint):MapPaint {
272                         return MapPaint(paintContainer.getChildAt(i));
273                 }
274
275         /** Get all the layers available for this Map object
276         *   @return An array of MapPaint objects */
277         public function getLayers():Array {
278             var a:Array = [];
279             for (var i:uint=0; i<paintContainer.numChildren; i++) {
280                 a.push(getLayerAt(i));
281             }
282             return a;
283         }
284                 
285                 /* Find which layer is editable */
286                 public function get editableLayer():MapPaint {
287                         var editableLayer:MapPaint;
288                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
289                                 if (!getLayerAt(i).isBackground) {
290                                         if (editableLayer) trace("Multiple editable layers found");
291                                         editableLayer=getLayerAt(i);
292                                 }
293                         }
294                         return editableLayer;
295                 }
296
297                 /** Find which paint object an entity will be displayed on. */
298                 public function getLayerForEntity(entity:Entity):MapPaint {
299                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
300                                 if (getLayerAt(i).sameConnection(entity)) return getLayerAt(i);
301                         }
302                         return null;
303                 }
304
305                 // ------------------------------------------------------------------------------------------
306                 // Redraw all items, zoom in and out
307                 
308                 private function updateAllEntityUIs(redraw:Boolean,remove:Boolean):void {
309                         for (var i:uint=0; i<paintContainer.numChildren; i++)
310                                 getLayerAt(i).updateEntityUIs(redraw, remove);
311                 }
312                 public function redraw():void {
313                         for (var i:uint=0; i<paintContainer.numChildren; i++)
314                                 getLayerAt(i).redraw();
315                 }
316                 public function redrawPOIs():void { 
317                         for (var i:uint=0; i<paintContainer.numChildren; i++)
318                                 getLayerAt(i).redrawPOIs();
319                 }
320                 
321                 public function zoomIn():void {
322                         if (scale!=MAXSCALE) changeScale(scale+1);
323                 }
324
325                 public function zoomOut():void {
326                         if (scale!=MINSCALE) changeScale(scale-1);
327                 }
328
329                 private function changeScale(newscale:uint):void {
330                         scale=newscale;
331                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
332                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
333                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
334                         tileset.changeScale(scale);
335                         updateAllEntityUIs(true,true);
336                         download();
337                 }
338
339                 /** Set background dimming on/off. */
340                 public function setDimming(dim:Boolean):void {
341                         if (tileset) { tileset.setDimming(dim); }
342                 }
343                 
344                 /** Return background dimming. */
345                 public function getDimming():Boolean {
346                         if (tileset) { return tileset.getDimming(); }
347                         return true;
348                 }
349
350                 /** Set background sharpening on/off. */
351                 public function setSharpen(sharpen:Boolean):void {
352                         if (tileset) { tileset.setSharpen(sharpen); }
353                 }
354                 /** Return background sharpening. */
355                 public function getSharpen():Boolean {
356                         if (tileset) { return tileset.getSharpen(); }
357                         return false;
358                 }
359
360                 // ------------------------------------------------------------------------------------------
361                 // Export (experimental)
362                 // ** just a bit of fun for now!
363                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
364                 // to that area (will probably require creating a new DisplayObject with a different origin
365                 // and mask)
366 /*              
367                 public function export():void {
368                         trace("size is "+this.width+","+this.height);
369                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
370                         jpgSource.draw(this);
371                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
372                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
373                         var fileRef:FileReference = new FileReference();
374 //                      fileRef.save(jpgStream,'map.jpeg');
375                 }
376
377 */
378
379                 // ==========================================================================================
380                 // Events
381                 
382                 // ------------------------------------------------------------------------------------------
383                 // Mouse events
384                 
385                 /** Should map be allowed to pan? */
386                 public function set draggable(draggable:Boolean):void {
387                         _draggable=draggable;
388                         dragstate=NOT_DRAGGING;
389                 }
390
391                 /** Prepare for being dragged by recording start time and location of mouse. */
392                 public function mouseDownHandler(event:MouseEvent):void {
393                         if (!_draggable) { return; }
394                         if (dragstate==DRAGGING) { moveMap(x,y); dragstate=SWALLOW_MOUSEUP; }   // cancel drag if mouse-up occurred outside the window (thanks, Safari)
395                         else { dragstate=NOT_MOVED; }
396                         lastxmouse=stage.mouseX; downX=stage.mouseX;
397                         lastymouse=stage.mouseY; downY=stage.mouseY;
398                         downTime=new Date().getTime();
399                 }
400         
401                 /** Respond to mouse up by possibly moving map. */
402                 public function mouseUpHandler(event:MouseEvent=null):void {
403                         if (dragstate==DRAGGING) { moveMap(x,y); }
404                         dragstate=NOT_DRAGGING;
405                 }
406         
407                 /** Respond to mouse movement, dragging the map if tolerance threshold met. */
408                 public function mouseMoveHandler(event:MouseEvent):void {
409                         if (!_draggable) { return; }
410                         if (dragstate==NOT_DRAGGING) { 
411                            this.dispatchEvent(new MapEvent(MapEvent.MOUSE_MOVE, { x: coord2lon(mouseX), y: coord2lat(mouseY) }));
412                return; 
413             }
414                         
415                         if (dragstate==NOT_MOVED) {
416                                 if (new Date().getTime()-downTime<300) {
417                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
418                                 } else {
419                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
420                                 }
421                                 dragstate=DRAGGING;
422                         }
423                         
424                         setScrollRectXY(getX()+stage.mouseX-lastxmouse,getY()+stage.mouseY-lastymouse);
425                         lastxmouse=stage.mouseX; lastymouse=stage.mouseY;
426                         setCentre();
427                 }
428         
429                 // ------------------------------------------------------------------------------------------
430                 // Do every frame
431
432                 private function everyFrame(event:Event):void {
433                         if (tileset) { tileset.serviceQueue(); }
434                         if (stage.focus && !stage.contains(stage.focus)) { stage.focus=stage; }
435                 }
436
437                 // ------------------------------------------------------------------------------------------
438                 // Miscellaneous events
439                 
440                 /** Respond to cursor movements and zoom in/out.*/
441                 public function keyUpHandler(event:KeyboardEvent):void {
442                         if (event.target is TextField) return;                          // not meant for us
443                         switch (event.keyCode) {
444                                 case Keyboard.PAGE_UP:  zoomIn(); break;                 // Page Up - zoom in
445                                 case Keyboard.PAGE_DOWN:        zoomOut(); break;            // Page Down - zoom out
446                                 case Keyboard.LEFT:     moveMap(mapwidth/2,0); break;        // left cursor
447                                 case Keyboard.UP:       moveMap(0,mapheight/2); break;           // up cursor
448                                 case Keyboard.RIGHT:    moveMap(-mapwidth/2,0); break;   // right cursor
449                                 case Keyboard.DOWN:     moveMap(0,-mapheight/2); break;      // down cursor
450                         }
451                 }
452
453         }
454 }