Merge pull request #40 from stevage/vet-pool-4128
[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
210                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
211                         
212             if ( backdrop != null ) {
213                 backdrop.width=mapwidth;
214                 backdrop.height=mapheight;
215             }
216             if ( mask != null ) {
217                 mask.width=mapwidth;
218                 mask.height=mapheight;
219             }
220                 }
221
222         /** Download map data. Data is downloaded for the currently visible layers
223         * The bounding box for the download is taken from the current map edges.
224         */
225                 public function download():void {
226                         for (var i:uint=0; i<paintContainer.numChildren; i++)
227                                 if(getLayerAt(i).visible == true) {
228                     getLayerAt(i).connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
229                 }
230                 }
231
232         // Handle mouse events on ways/nodes
233         private var mapController:MapController = null;
234
235         /** Assign map controller. */
236         public function setController(controller:MapController):void {
237             this.mapController = controller;
238         }
239
240         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
241             if ( mapController != null )
242                 mapController.entityMouseEvent(event, entity);
243         }
244
245                 // ------------------------------------------------------------------------------------------
246                 // Add layers
247                 
248                 public function addLayer(connection:Connection, styleurl:String, backgroundlayer:Boolean=true, interactive:Boolean=false):MapPaint {
249                         var paint:MapPaint=new MapPaint(this, connection, styleurl, -5, 5);
250                         paintContainer.addChildAt(paint,0);
251                         paint.isBackground=backgroundlayer;
252                         paint.interactive=interactive;
253                         return paint;
254                 }
255
256                 public function removeLayerByName(name:String):void {
257                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
258                                 if (getLayerAt(i).connection.name==name)
259                                         paintContainer.removeChildAt(i);
260                                         // >>>> REFACTOR: needs to do the equivalent of VectorLayer.blank()
261                         }
262                 }
263                 
264                 public function findLayer(name:String):MapPaint {
265                         for (var i:uint=0; i<paintContainer.numChildren; i++)
266                                 if (getLayerAt(i).connection.name==name) return getLayerAt(i);
267                         return null;
268                 }
269
270                 private function getLayerAt(i:uint):MapPaint {
271                         return MapPaint(paintContainer.getChildAt(i));
272                 }
273
274         /** Get all the layers available for this Map object
275         *   @return An array of MapPaint objects */
276         public function getLayers():Array {
277             var a:Array = [];
278             for (var i:uint=0; i<paintContainer.numChildren; i++) {
279                 a.push(getLayerAt(i));
280             }
281             return a;
282         }
283                 
284                 /* Find which layer is editable */
285                 public function get editableLayer():MapPaint {
286                         var editableLayer:MapPaint;
287                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
288                                 if (!getLayerAt(i).isBackground) {
289                                         if (editableLayer) trace("Multiple editable layers found");
290                                         editableLayer=getLayerAt(i);
291                                 }
292                         }
293                         return editableLayer;
294                 }
295
296                 /** Find which paint object an entity will be displayed on. */
297                 public function getLayerForEntity(entity:Entity):MapPaint {
298                         for (var i:uint=0; i<paintContainer.numChildren; i++) {
299                                 if (getLayerAt(i).sameConnection(entity)) return getLayerAt(i);
300                         }
301                         return null;
302                 }
303
304                 // ------------------------------------------------------------------------------------------
305                 // Redraw all items, zoom in and out
306                 
307                 private function updateAllEntityUIs(redraw:Boolean,remove:Boolean):void {
308                         for (var i:uint=0; i<paintContainer.numChildren; i++)
309                                 getLayerAt(i).updateEntityUIs(redraw, remove);
310                 }
311                 public function redraw():void {
312                         for (var i:uint=0; i<paintContainer.numChildren; i++)
313                                 getLayerAt(i).redraw();
314                 }
315                 public function redrawPOIs():void { 
316                         for (var i:uint=0; i<paintContainer.numChildren; i++)
317                                 getLayerAt(i).redrawPOIs();
318                 }
319                 
320                 public function zoomIn():void {
321                         if (scale!=MAXSCALE) changeScale(scale+1);
322                 }
323
324                 public function zoomOut():void {
325                         if (scale!=MINSCALE) changeScale(scale-1);
326                 }
327
328                 private function changeScale(newscale:uint):void {
329                         scale=newscale;
330                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
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                         updateAllEntityUIs(true,true);
335                         download();
336                 }
337
338                 /** Set background dimming on/off. */
339                 public function setDimming(dim:Boolean):void {
340                         if (tileset) { tileset.setDimming(dim); }
341                 }
342                 
343                 /** Return background dimming. */
344                 public function getDimming():Boolean {
345                         if (tileset) { return tileset.getDimming(); }
346                         return true;
347                 }
348
349                 /** Set background sharpening on/off. */
350                 public function setSharpen(sharpen:Boolean):void {
351                         if (tileset) { tileset.setSharpen(sharpen); }
352                 }
353                 /** Return background sharpening. */
354                 public function getSharpen():Boolean {
355                         if (tileset) { return tileset.getSharpen(); }
356                         return false;
357                 }
358
359                 // ------------------------------------------------------------------------------------------
360                 // Export (experimental)
361                 // ** just a bit of fun for now!
362                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
363                 // to that area (will probably require creating a new DisplayObject with a different origin
364                 // and mask)
365 /*              
366                 public function export():void {
367                         trace("size is "+this.width+","+this.height);
368                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
369                         jpgSource.draw(this);
370                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
371                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
372                         var fileRef:FileReference = new FileReference();
373 //                      fileRef.save(jpgStream,'map.jpeg');
374                 }
375
376 */
377
378                 // ==========================================================================================
379                 // Events
380                 
381                 // ------------------------------------------------------------------------------------------
382                 // Mouse events
383                 
384                 /** Should map be allowed to pan? */
385                 public function set draggable(draggable:Boolean):void {
386                         _draggable=draggable;
387                         dragstate=NOT_DRAGGING;
388                 }
389
390                 /** Prepare for being dragged by recording start time and location of mouse. */
391                 public function mouseDownHandler(event:MouseEvent):void {
392                         if (!_draggable) { return; }
393                         if (dragstate==DRAGGING) { moveMap(x,y); dragstate=SWALLOW_MOUSEUP; }   // cancel drag if mouse-up occurred outside the window (thanks, Safari)
394                         else { dragstate=NOT_MOVED; }
395                         lastxmouse=stage.mouseX; downX=stage.mouseX;
396                         lastymouse=stage.mouseY; downY=stage.mouseY;
397                         downTime=new Date().getTime();
398                 }
399         
400                 /** Respond to mouse up by possibly moving map. */
401                 public function mouseUpHandler(event:MouseEvent=null):void {
402                         if (dragstate==DRAGGING) { moveMap(x,y); }
403                         dragstate=NOT_DRAGGING;
404                 }
405         
406                 /** Respond to mouse movement, dragging the map if tolerance threshold met. */
407                 public function mouseMoveHandler(event:MouseEvent):void {
408                         if (!_draggable) { return; }
409                         if (dragstate==NOT_DRAGGING) { 
410                            this.dispatchEvent(new MapEvent(MapEvent.MOUSE_MOVE, { x: coord2lon(mouseX), y: coord2lat(mouseY) }));
411                return; 
412             }
413                         
414                         if (dragstate==NOT_MOVED) {
415                                 if (new Date().getTime()-downTime<300) {
416                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
417                                 } else {
418                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
419                                 }
420                                 dragstate=DRAGGING;
421                         }
422                         
423                         setScrollRectXY(getX()+stage.mouseX-lastxmouse,getY()+stage.mouseY-lastymouse);
424                         lastxmouse=stage.mouseX; lastymouse=stage.mouseY;
425                         setCentre();
426                 }
427         
428                 // ------------------------------------------------------------------------------------------
429                 // Do every frame
430
431                 private function everyFrame(event:Event):void {
432                         if (tileset) { tileset.serviceQueue(); }
433                         if (stage.focus && !stage.contains(stage.focus)) { stage.focus=stage; }
434                 }
435
436                 // ------------------------------------------------------------------------------------------
437                 // Miscellaneous events
438                 
439                 /** Respond to cursor movements and zoom in/out.*/
440                 public function keyUpHandler(event:KeyboardEvent):void {
441                         if (event.target is TextField) return;                          // not meant for us
442                         switch (event.keyCode) {
443                                 case Keyboard.PAGE_UP:  zoomIn(); break;                 // Page Up - zoom in
444                                 case Keyboard.PAGE_DOWN:        zoomOut(); break;            // Page Down - zoom out
445                                 case Keyboard.LEFT:     moveMap(mapwidth/2,0); break;        // left cursor
446                                 case Keyboard.UP:       moveMap(0,mapheight/2); break;           // up cursor
447                                 case Keyboard.RIGHT:    moveMap(-mapwidth/2,0); break;   // right cursor
448                                 case Keyboard.DOWN:     moveMap(0,-mapheight/2); break;      // down cursor
449                         }
450                 }
451
452         }
453 }