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