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