error/conflict-handling work-in-progress
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.text.TextField;
4         import flash.geom.Rectangle;
5         import flash.display.DisplayObjectContainer;
6         import flash.display.Loader;
7         import flash.display.Sprite;
8         import flash.display.Shape;
9         import flash.display.Stage;
10         import flash.display.BitmapData;
11         import flash.display.LoaderInfo;
12         import flash.text.Font;
13         import flash.utils.ByteArray;
14         import flash.events.*;
15         import flash.net.*;
16     import flash.external.ExternalInterface;
17
18     import net.systemeD.halcyon.connection.*;
19     import net.systemeD.halcyon.connection.EntityEvent;
20         import net.systemeD.halcyon.styleparser.*;
21         import net.systemeD.halcyon.Globals;
22
23 //      for experimental export function:
24 //      import flash.net.FileReference;
25 //      import com.adobe.images.JPGEncoder;
26
27     public class Map extends Sprite {
28
29                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
30                                                                                                                 // (for Landsat, 5120)
31                 public const MINSCALE:uint=13;                                  // don't zoom out past this
32                 public const MAXSCALE:uint=23;                                  // don't zoom in past this
33
34                 public var paint:MapPaint;                                              // sprite for ways and (POI/tagged) nodes in core layer
35                 public var vectorbg:Sprite;                                             // sprite for vector background layers
36
37                 public var scale:uint=14;                                               // map scale
38                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
39                 public var bigedge_l:Number= 999999;                    // area of largest whichways
40                 public var bigedge_r:Number=-999999;                    //  |
41                 public var bigedge_b:Number= 999999;                    //  |
42                 public var bigedge_t:Number=-999999;                    //  |
43
44                 public var edge_l:Number;                                               // current bounding box
45                 public var edge_r:Number;                                               //  |
46                 public var edge_t:Number;                                               //  |
47                 public var edge_b:Number;                                               //  |
48                 public var centre_lat:Number;                                   // centre lat/lon
49                 public var centre_lon:Number;                                   //  |
50
51                 public var baselon:Number;                                              // urllon-xradius/masterscale;
52                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
53                 public var mapwidth:uint;                                               // width (Flash pixels)
54                 public var mapheight:uint;                                              // height (Flash pixels)
55
56                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map
57                 private var _draggable:Boolean=true;                    //  |
58                 private var lastxmouse:Number;                                  //  |
59                 private var lastymouse:Number;                                  //  |
60                 private var downX:Number;                                               //  |
61                 private var downY:Number;                                               //  |
62                 private var downTime:Number;                                    //  |
63                 public const NOT_DRAGGING:uint=0;                               //  |
64                 public const NOT_MOVED:uint=1;                                  //  |
65                 public const DRAGGING:uint=2;                                   //  |
66                 public const TOLERANCE:uint=7;                                  //  |
67                 
68                 public var initparams:Object;                                   // object containing HTML page parameters
69
70                 public var backdrop:Object;                                             // reference to backdrop sprite
71                 public var tileset:TileSet;                                             // background tile object
72                 private var tileparams:Object={ url:'' };               // background tile URL, name and scheme
73                 private var styleurl:String='';                                 // internal style URL
74                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
75                 
76                 public var connection:Connection;                               // server connection
77                 public var vectorlayers:Object={};                              // VectorLayer objects 
78                 
79                 // ------------------------------------------------------------------------------------------
80                 // Map constructor function
81
82         public function Map(initparams:Object) {
83
84                         this.initparams=initparams;
85                         connection = Connection.getConnection(initparams);
86             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
87             connection.addEventListener(Connection.NEW_POI, newPOICreated);
88             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumbered);
89             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumbered);
90                         gotEnvironment(null);
91
92                         addEventListener(Event.ENTER_FRAME, everyFrame);
93                         scrollRect=new Rectangle(0,0,800,600);
94         }
95
96                 public function gotEnvironment(r:Object):void {
97                         var loader:Loader = new Loader();
98                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
99                         loader.load(new URLRequest("FontLibrary.swf"));
100                 }
101                 
102                 public function gotFont(r:Event):void {
103                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
104                         Font.registerFont(FontLibrary.DejaVu);
105
106                         if (initparams['lat'] != null) {
107                                 // parameters sent from HTML
108                                 init(initparams['lat'],
109                                          initparams['lon'],
110                                          initparams['zoom']);
111
112                         } else {
113                                 // somewhere innocuous
114                                 init(53.09465,-2.56495,17);
115                         }
116                 }
117
118                 // ------------------------------------------------------------------------------------------
119                 // Initialise map at a given lat/lon
120
121         public function init(startlat:Number, startlon:Number, startscale:uint=0):void {
122                         while (numChildren) { removeChildAt(0); }
123
124                         tileset=new TileSet(this);                                      // 0 - 900913 background
125                         if (initparams['tileblocks']) {                         //   | option to block dodgy tile sources
126                                 tileset.blocks=initparams['tileblocks'];//   |
127                         }                                                                                       //   |
128                         addChild(tileset);                                                      //   |
129                         tileset.init(tileparams, false, 
130                                      initparams['background_dim']    ==null ? true  : initparams['background_dim'],
131                                      initparams['background_sharpen']==null ? false : initparams['background_sharpen']);
132
133                         vectorbg = new Sprite();                                        // 1 - vector background layers
134                         addChild(vectorbg);                                                     //   |
135
136                         paint = new MapPaint(this,-5,5);                        // 2 - core paint object
137                         addChild(paint);                                                        //   |
138                         paint.isBackground=false;                                       //   |
139
140                         if (styleurl) {                                                         // if we've only just set up paint, then setStyle won't have created the RuleSet
141                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
142                                 paint.ruleset.loadFromCSS(styleurl);
143                         }
144                         if (startscale>0) {
145                                 scale=startscale;
146                                 this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
147                         }
148
149                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
150                         baselon    =startlon          -(mapwidth /2)/scalefactor;
151                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
152                         addDebug("Baselon "+baselon+", basey "+basey);
153                         updateCoords(0,0);
154             this.dispatchEvent(new Event(MapEvent.INITIALISED));
155                         download();
156
157             if (ExternalInterface.available) {
158               ExternalInterface.addCallback("setPosition", function (lat:Number,lon:Number,zoom:uint):void {
159                   updateCoordsFromLatLon(lat, lon);
160                   changeScale(zoom);
161               });
162             }
163         }
164
165                 // ------------------------------------------------------------------------------------------
166                 // Recalculate co-ordinates from new Flash origin
167
168                 public function updateCoords(tx:Number,ty:Number):void {
169                         setScrollRectXY(tx,ty);
170
171                         edge_t=coord2lat(-ty          );
172                         edge_b=coord2lat(-ty+mapheight);
173                         edge_l=coord2lon(-tx          );
174                         edge_r=coord2lon(-tx+mapwidth );
175                         setCentre();
176
177                         tileset.update();
178                 }
179                 
180                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
181                         var cy:Number=-(lat2coord(lat)-mapheight/2);
182                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
183                         updateCoords(cx,cy);
184                 }
185                 
186                 private function setScrollRectXY(tx:Number,ty:Number):void {
187                         var w:Number=scrollRect.width;
188                         var h:Number=scrollRect.height;
189                         scrollRect=new Rectangle(-tx,-ty,w,h);
190                 }
191                 private function setScrollRectSize(width:Number,height:Number):void {
192                         var sx:Number=scrollRect.x ? scrollRect.x : 0;
193                         var sy:Number=scrollRect.y ? scrollRect.y : 0;
194                         scrollRect=new Rectangle(sx,sy,width,height);
195                 }
196                 
197                 private function getX():Number { return -scrollRect.x; }
198                 private function getY():Number { return -scrollRect.y; }
199                 
200                 private function setCentre():void {
201                         centre_lat=coord2lat(-getY()+mapheight/2);
202                         centre_lon=coord2lon(-getX()+mapwidth/2);
203                         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}));
204                 }
205                 
206                 public function nudgeBackground(x:Number,y:Number):void {
207                         this.dispatchEvent(new MapEvent(MapEvent.NUDGE_BACKGROUND, { x: x, y: y }));
208                 }
209
210                 private function moveMap(dx:Number,dy:Number):void {
211                         updateCoords(getX()+dx,getY()+dy);
212                         updateEntityUIs(false, false);
213                         download();
214                 }
215                 
216                 public function moveMapFromLatLon(lat:Number,lon:Number):void {
217                         updateCoordsFromLatLon(lat,lon);
218                         updateEntityUIs(false,false);
219                         download();
220                 }
221
222                 // Co-ordinate conversion functions
223
224                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
225                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
226                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
227                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
228
229                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
230                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
231
232                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
233                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
234
235
236                 // ------------------------------------------------------------------------------------------
237                 // Resize map size based on current stage and height
238
239                 public function updateSize(w:uint, h:uint):void {
240                         mapwidth = w; centre_lon=coord2lon(-getX()+w/2);
241                         mapheight= h; centre_lat=coord2lat(-getY()+h/2);
242                         setScrollRectSize(w,h);
243
244                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
245                         
246             if ( backdrop != null ) {
247                 backdrop.width=mapwidth;
248                 backdrop.height=mapheight;
249             }
250             if ( mask != null ) {
251                 mask.width=mapwidth;
252                 mask.height=mapheight;
253             }
254                 }
255
256         /** Download map data. Data is downloaded for the connection and the vector layers, where supported.
257         * The bounding box for the download is taken from the current map edges.
258         */
259                 public function download():void {
260                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
261                         
262                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
263                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
264                         bigedge_l=edge_l; bigedge_r=edge_r;
265                         bigedge_b=edge_b; bigedge_t=edge_t;
266                         if (connection.waycount>1000) {
267                                 connection.purgeOutside(edge_l,edge_r,edge_t,edge_b);
268                         }
269                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
270                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
271
272             // Do the same for vector layers
273             for each (var layer:VectorLayer in vectorlayers) {
274               layer.loadBbox(edge_l,edge_r,edge_t,edge_b);
275             }
276                 }
277
278         private function newWayCreated(event:EntityEvent):void {
279             var way:Way = event.entity as Way;
280                         if (!way.loaded || !way.within(edge_l,edge_r,edge_t,edge_b)) { return; }
281                         paint.createWayUI(way);
282         }
283
284         private function newPOICreated(event:EntityEvent):void {
285             var node:Node = event.entity as Node;
286                         if (!node.within(edge_l,edge_r,edge_t,edge_b)) { return; }
287                         paint.createNodeUI(node);
288         }
289
290                 private function wayRenumbered(event:EntityRenumberedEvent):void {
291             var way:Way = event.entity as Way;
292                         paint.renumberWayUI(way,event.oldID);
293                 }
294
295                 private function nodeRenumbered(event:EntityRenumberedEvent):void {
296             var node:Node = event.entity as Node;
297                         paint.renumberNodeUI(node,event.oldID);
298                 }
299
300         public function setHighlight(entity:Entity, settings:Object):void {
301                         if      ( entity is Way  && paint.wayuis[entity.id] ) { paint.wayuis[entity.id].setHighlight(settings);  }
302                         else if ( entity is Node && paint.nodeuis[entity.id]) { paint.nodeuis[entity.id].setHighlight(settings); }
303         }
304
305         public function setHighlightOnNodes(way:Way, settings:Object):void {
306                         if (paint.wayuis[way.id]) paint.wayuis[way.id].setHighlightOnNodes(settings);
307         }
308
309                 public function protectWay(way:Way):void {
310                         if (paint.wayuis[way.id]) paint.wayuis[way.id].protectSprites();
311                 }
312
313                 public function unprotectWay(way:Way):void {
314                         if (paint.wayuis[way.id]) paint.wayuis[way.id].unprotectSprites();
315                 }
316                 
317                 public function limitWayDrawing(way:Way,except:Number=NaN,only:Number=NaN):void {
318                         if (!paint.wayuis[way.id]) return;
319                         paint.wayuis[way.id].drawExcept=except;
320                         paint.wayuis[way.id].drawOnly  =only;
321                         paint.wayuis[way.id].redraw();
322                 }
323
324                 /* Protect Entities and EntityUIs against purging. This prevents the currently selected items
325                    from being purged even though they're off-screen. */
326
327                 public function setPurgable(entities:Array, purgable:Boolean):void {
328                         for each (var entity:Entity in entities) {
329                                 entity.locked=!purgable;
330                                 if ( entity is Way  ) {
331                                         var way:Way=entity as Way;
332                                         if (paint.wayuis[way.id]) { paint.wayuis[way.id].purgable=purgable; }
333                                         for (var i:uint=0; i<way.length; i++) {
334                                                 var node:Node=way.getNode(i)
335                                                 node.locked=!purgable;
336                                                 if (paint.nodeuis[node.id]) { paint.nodeuis[node.id].purgable=purgable; }
337                                         }
338                                 } else if ( entity is Node && paint.nodeuis[entity.id]) { 
339                                         paint.nodeuis[entity.id].purgable=purgable;
340                                 }
341                         }
342                 }
343
344         // Handle mouse events on ways/nodes
345         private var mapController:MapController = null;
346
347         public function setController(controller:MapController):void {
348             this.mapController = controller;
349         }
350
351         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
352             if ( mapController != null )
353                 mapController.entityMouseEvent(event, entity);
354                                 
355         }
356
357                 // ------------------------------------------------------------------------------------------
358                 // Add vector layer
359                 
360                 public function addVectorLayer(layer:VectorLayer):void {
361                         vectorlayers[layer.name]=layer;
362                         vectorbg.addChild(layer.paint);
363                 }
364
365                 // ------------------------------------------------------------------------------------------
366                 // Redraw all items, zoom in and out
367                 
368                 public function updateEntityUIs(redraw:Boolean,remove:Boolean):void {
369                         paint.updateEntityUIs(connection.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
370                         for each (var v:VectorLayer in vectorlayers) {
371                                 v.paint.updateEntityUIs(v.getObjectsByBbox(edge_l, edge_r, edge_t, edge_b), redraw, remove);
372                         }
373                 }
374                 public function redraw():void {
375                         paint.redraw();
376                         for each (var v:VectorLayer in vectorlayers) { v.paint.redraw(); }
377                 }
378                 public function redrawPOIs():void { 
379                         paint.redrawPOIs();
380                         for each (var v:VectorLayer in vectorlayers) { v.paint.redrawPOIs(); }
381                 }
382                 
383                 public function zoomIn():void {
384                         if (scale==MAXSCALE) { return; }
385                         changeScale(scale+1);
386                 }
387
388                 public function zoomOut():void {
389                         if (scale==MINSCALE) { return; }
390                         changeScale(scale-1);
391                 }
392
393                 private function changeScale(newscale:uint):void {
394                         addDebug("new scale "+newscale);
395                         scale=newscale;
396                         this.dispatchEvent(new MapEvent(MapEvent.SCALE, {scale:scale}));
397                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
398                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
399                         tileset.changeScale(scale);
400                         updateEntityUIs(true,true);
401                         download();
402                 }
403
404                 private function reportPosition():void {
405                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
406                 }
407                 
408                 public function setStyle(url:String):void {
409                         styleurl=url;
410                         if (paint) { 
411                                 paint.ruleset=new RuleSet(MINSCALE,MAXSCALE,redraw,redrawPOIs);
412                                 paint.ruleset.loadFromCSS(url);
413                         }
414         }
415
416                 public function setBackground(bg:Object):void {
417                         tileparams=bg;
418                         if (tileset) { tileset.init(bg, bg.url!=''); }
419                 }
420
421                 public function setDimming(dim:Boolean):void {
422                         if (tileset) { tileset.setDimming(dim); }
423                 }
424                 public function getDimming():Boolean {
425                         if (tileset) { return tileset.getDimming(); }
426                         return true;
427                 }
428
429                 public function setSharpen(sharpen:Boolean):void {
430                         if (tileset) { tileset.setSharpen(sharpen); }
431                 }
432                 public function getSharpen():Boolean {
433                         if (tileset) { return tileset.getSharpen(); }
434                         return false;
435                 }
436
437                 // ------------------------------------------------------------------------------------------
438                 // Export (experimental)
439                 // ** just a bit of fun for now!
440                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
441                 // to that area (will probably require creating a new DisplayObject with a different origin
442                 // and mask)
443 /*              
444                 public function export():void {
445                         addDebug("size is "+this.width+","+this.height);
446                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
447                         jpgSource.draw(this);
448                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
449                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
450                         var fileRef:FileReference = new FileReference();
451 //                      fileRef.save(jpgStream,'map.jpeg');
452                 }
453
454 */
455
456                 // ==========================================================================================
457                 // Events
458                 
459                 // ------------------------------------------------------------------------------------------
460                 // Mouse events
461                 
462                 public function set draggable(draggable:Boolean):void {
463                         _draggable=draggable;
464                         dragstate=NOT_DRAGGING;
465                 }
466
467                 public function mouseDownHandler(event:MouseEvent):void {
468                         if (!_draggable) { return; }
469                         dragstate=NOT_MOVED;
470                         lastxmouse=stage.mouseX; downX=stage.mouseX;
471                         lastymouse=stage.mouseY; downY=stage.mouseY;
472                         downTime=new Date().getTime();
473                 }
474         
475                 public function mouseUpHandler(event:MouseEvent=null):void {
476                         if (dragstate==DRAGGING) { moveMap(x,y); }
477                         dragstate=NOT_DRAGGING;
478                 }
479         
480                 public function mouseMoveHandler(event:MouseEvent):void {
481                         if (!_draggable) { return; }
482                         if (dragstate==NOT_DRAGGING) { return; }
483                         
484                         if (dragstate==NOT_MOVED) {
485                                 if (new Date().getTime()-downTime<300) {
486                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE   && Math.abs(downY-stage.mouseY)<=TOLERANCE  ) return;
487                                 } else {
488                                         if (Math.abs(downX-stage.mouseX)<=TOLERANCE/2 && Math.abs(downY-stage.mouseY)<=TOLERANCE/2) return;
489                                 }
490                                 dragstate=DRAGGING;
491                         }
492                         
493                         setScrollRectXY(getX()+stage.mouseX-lastxmouse,getY()+stage.mouseY-lastymouse);
494                         lastxmouse=stage.mouseX; lastymouse=stage.mouseY;
495                         setCentre();
496                 }
497         
498                 // ------------------------------------------------------------------------------------------
499                 // Do every frame
500
501                 private function everyFrame(event:Event):void {
502                         if (tileset) { tileset.serviceQueue(); }
503                 }
504
505                 // ------------------------------------------------------------------------------------------
506                 // Miscellaneous events
507                 
508                 public function keyUpHandler(event:KeyboardEvent):void {
509                         if (event.target is TextField) return;                          // not meant for us
510                         switch (event.keyCode) {
511                                 case 33:        zoomIn(); break;                                        // Page Up - zoom in
512                                 case 34:        zoomOut(); break;                                       // Page Down - zoom out
513                                 case 37:        moveMap(mapwidth/2,0); break;           // left cursor
514                                 case 38:        moveMap(0,mapheight/2); break;          // up cursor
515                                 case 39:        moveMap(-mapwidth/2,0); break;          // right cursor
516                                 case 40:        moveMap(0,-mapheight/2); break;         // down cursor
517 //                              case 76:        reportPosition(); break;                        // L - report lat/long
518                         }
519                 }
520
521                 public function connectionError(err:Object=null): void {
522                         addDebug("got error"); 
523                 }
524
525                 // ------------------------------------------------------------------------------------------
526                 // Debugging
527                 
528                 public function clearDebug():void {
529                         if (!Globals.vars.hasOwnProperty('debug')) return;
530                         Globals.vars.debug.text='';
531                 }
532                         
533                 public function addDebug(text:String):void {
534                         trace(text);
535                         if (!Globals.vars.hasOwnProperty('debug')) return;
536                         if (!Globals.vars.debug.visible) return;
537                         Globals.vars.debug.appendText(text+"\n");
538                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
539                 }
540
541         }
542 }