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