continuing to expand and rework selection stuff. Not finished yet but getting there
[potlatch2.git] / net / systemeD / halcyon / Map.as
1 package net.systemeD.halcyon {
2
3         import flash.text.TextField;
4         import flash.display.DisplayObjectContainer;
5         import flash.display.Loader;
6         import flash.display.Sprite;
7         import flash.display.Shape;
8         import flash.display.Stage;
9         import flash.display.BitmapData;
10         import flash.display.LoaderInfo;
11         import flash.text.Font;
12         import flash.utils.ByteArray;
13         import flash.events.*;
14         import flash.net.*;
15
16     import net.systemeD.halcyon.connection.*;
17     import net.systemeD.halcyon.connection.EntityEvent;
18         import net.systemeD.halcyon.styleparser.*;
19
20 //      for experimental export function:
21 //      import flash.net.FileReference;
22 //      import com.adobe.images.JPGEncoder;
23
24     public class Map extends Sprite {
25
26                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
27                                                                                                                 // (for Landsat, 5120)
28                 public const MINSCALE:uint=13;                                  // don't zoom out past this
29                 public const MAXSCALE:uint=19;                                  // don't zoom in past this
30
31                 public var ruleset:RuleSet;                                             // rules
32                 
33                 public var ways:Object=new Object();                    // geodata
34                 public var nodes:Object=new Object();                   //  |
35                 public var pois:Object=new Object();                    //  |
36                 public var relations:Object=new Object();               //  |
37
38                 public var scale:uint=14;                                               // map scale
39                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
40                 public var bigedge_l:Number= 999999;                    // area of largest whichways
41                 public var bigedge_r:Number=-999999;                    //  |
42                 public var bigedge_b:Number= 999999;                    //  |
43                 public var bigedge_t:Number=-999999;                    //  |
44
45                 public var waycount:uint=0;                                             // ways:                number currently loaded
46                 public var waysrequested:uint=0;                                //                              total number requested
47                 public var waysreceived:uint=0;                                 //                              total number received
48                 public var relcount:uint=0;                                             // relations:   number currently loaded
49                 public var relsrequested:uint=0;                                //                              total number requested
50                 public var relsreceived:uint=0;                                 //                              total number received
51                 public var poicount:uint=0;                                             // POIs:                number currently loaded
52                 public var whichrequested:uint=0;                               // whichways:   total number requested
53                 public var whichreceived:uint=0;                                //                              total number received
54
55                 public var edge_l:Number;                                               // current bounding box
56                 public var edge_r:Number;                                               //  |
57                 public var edge_t:Number;                                               //  |
58                 public var edge_b:Number;                                               //  |
59                 public var centre_lat:Number;                                   // centre lat/lon
60                 public var centre_lon:Number;                                   //  |
61
62                 public var baselon:Number;                                              // urllon-xradius/masterscale;
63                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
64                 public var mapwidth:uint;                                               // width (Flash pixels)
65                 public var mapheight:uint;                                              // height (Flash pixels)
66
67                 public var dragstate:uint=NOT_DRAGGING;                 // dragging map
68                 private var lastxmouse:Number;                                  //  |
69                 private var lastymouse:Number;                                  //  |
70                 private var downX:Number;                                               //  |
71                 private var downY:Number;                                               //  |
72                 public const NOT_DRAGGING:uint=0;                               //  |
73                 public const NOT_MOVED:uint=1;                                  //  |
74                 public const DRAGGING:uint=2;                                   //  |
75                 
76                 public var initparams:Object;                                   // object containing 
77
78                 public var backdrop:Object;                                             // reference to backdrop sprite
79                 public var tileset:TileSet;                                             // 900913 tile background
80                 public var showall:Boolean=true;                                // show all objects, even if unstyled?
81                 
82                 public var connection:Connection;                               // server connection
83
84                 public const TILESPRITE:uint=0;
85                 public const GPSSPRITE:uint=1;
86                 public const WAYSPRITE:uint=2;
87                 public const NAMESPRITE:uint=13;
88                 
89                 // ------------------------------------------------------------------------------------------
90                 // Map constructor function
91
92         public function Map(initparams:Object) {
93                         this.initparams=initparams;
94                         connection = Connection.getConnection(initparams);
95             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
96             connection.addEventListener(Connection.NEW_POI, newPOICreated);
97                         gotEnvironment(null);
98
99                         addEventListener(Event.ENTER_FRAME, everyFrame);
100         }
101
102                 // Set up layering
103                 // [layer][3]                   - names
104                 // [layer][2][sublayer] - stroke
105                 // [layer][1]                   - casing
106                 // [layer][0]                   - fill
107
108                 private function createSprites():void {
109                         tileset=new TileSet(this);                                      // 0 - 900913 background
110                         addChild(tileset);                                                      //      |
111                         addChild(new Sprite());                                         // 1 - GPS
112
113                         for (var l:int=0; l<13; l++) {                          // 11 layers (12 is +5, 2 is -5)
114                                 var s:Sprite = getHitSprite();          //  |
115                                 s.addChild(getPaintSprite());                   //      | 0 fill
116                                 s.addChild(getPaintSprite());                   //      | 1 casing
117                                 var t:Sprite = getPaintSprite();                //  | 2 stroke
118                                 for (var j:int=0; j<11; j++) {                  //      |  | ten sublayers
119                                         t.addChild(getPaintSprite());           //  |  |  |
120                                 }                                                                               //  |  |  |
121                                 s.addChild(t);                                                  //  |  |
122                                 s.addChild(getPaintSprite());                   //      | 3 names
123                                 s.addChild(getPaintSprite());                   //      | 4 nodes
124                                 s.addChild(getHitSprite());                         //  | 5 entity hit tests
125                                 addChild(s);                                                    //  |
126                         }
127                         addChild(getPaintSprite());                             // 13 - name sprite
128                 }
129                 
130                 private function removeSprites():void {
131                         while (numChildren) { removeChildAt(0); }
132                 }
133
134         private function getPaintSprite():Sprite {
135             var s:Sprite = new Sprite();
136             s.mouseEnabled = false;
137             s.mouseChildren = false;
138             return s;
139         }
140
141         private function getHitSprite():Sprite {
142             var s:Sprite = new Sprite();
143             return s;
144         }
145
146                 public function gotEnvironment(r:Object):void {
147                         var loader:Loader = new Loader();
148                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotFont);
149                         loader.load(new URLRequest("FontLibrary.swf"));
150                 }
151                 
152                 public function gotFont(r:Event):void {
153                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
154                         Font.registerFont(FontLibrary.DejaVu);
155
156                         if (initparams['lat'] != null) {
157                                 // parameters sent from HTML
158                                 init(initparams['lat'],
159                                          initparams['lon'],
160                                          initparams['zoom'],
161                                          initparams['style'],
162                                          initparams['tileurl']);
163
164                         } else {
165                                 // somewhere innocuous
166                                 init(53.09465,-2.56495,17,"test.css?d="+Math.random(),"");
167                         }
168                 }
169
170                 // ------------------------------------------------------------------------------------------
171                 // Initialise map at a given lat/lon
172
173         public function init(startlat:Number,startlon:Number,startscale:uint=0,style:String=null,tileurl:String=''):void {
174                         removeSprites();
175                         createSprites();
176                         tileset.init(tileurl);
177
178                         if (style) {
179                                 ruleset=new RuleSet(this,redrawPOIs);
180                                 ruleset.loadFromCSS(style);
181                         }
182                         if (startscale>0) { scale=startscale; }
183
184                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
185                         baselon    =startlon          -(mapwidth /2)/scalefactor;
186                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
187                         addDebug("Baselon "+baselon+", basey "+basey);
188                         updateCoords(0,0);
189                         download();
190                         
191         }
192
193                 // ------------------------------------------------------------------------------------------
194                 // Recalculate co-ordinates from new Flash origin
195
196                 public function updateCoords(tx:Number,ty:Number):void {
197                         x=tx; y=ty;
198
199                         edge_t=coord2lat(-y          );
200                         edge_b=coord2lat(-y+mapheight);
201                         edge_l=coord2lon(-x          );
202                         edge_r=coord2lon(-x+mapwidth );
203                         setCentre();
204 //                      addDebug("Lon "+edge_l+"-"+edge_r);
205 //                      addDebug("Lat "+edge_b+"-"+edge_t);
206
207                         tileset.update();
208                 }
209                 
210                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
211                         var cy:Number=-(lat2coord(lat)-mapheight/2);
212                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
213                         updateCoords(cx,cy);
214                 }
215                 
216                 private function setCentre():void {
217                         centre_lat=coord2lat(-y+mapheight/2);
218                         centre_lon=coord2lon(-x+mapwidth/2);
219                         this.dispatchEvent(new MapEvent(MapEvent.MOVE, {lat:centre_lat, lon:centre_lon, scale:scale}));
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 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
236 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
237
238
239                 // ------------------------------------------------------------------------------------------
240                 // Resize map size based on current stage and height
241
242                 public function updateSize(w:uint, h:uint):void {
243                         this.dispatchEvent(new MapEvent(MapEvent.RESIZE, {width:w, height:h}));
244                         
245                         mapwidth = w;
246                         mapheight= h;
247             if ( backdrop != null ) {
248                 backdrop.width=mapwidth;
249                 backdrop.height=mapheight;
250             }
251             if ( mask != null ) {
252                 mask.width=mapwidth;
253                 mask.height=mapheight;
254             }
255                 }
256
257                 // ------------------------------------------------------------------------------------------
258                 // Download map data
259                 // (typically from whichways, but will want to add more connections)
260
261                 public function download():void {
262                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD, {minlon:edge_l, maxlon:edge_r, maxlat:edge_t, minlat:edge_b} ));
263                         
264                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
265                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
266                         bigedge_l=edge_l; bigedge_r=edge_r;
267                         bigedge_b=edge_b; bigedge_t=edge_t;
268                         addDebug("Calling download with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
269                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
270                 }
271
272
273
274         private function newWayCreated(event:EntityEvent):void {
275             var way:Way = event.entity as Way;
276                         if (!way.loaded) { return; }
277             ways[way.id] = new WayUI(way, this);
278         }
279
280         private function newPOICreated(event:EntityEvent):void {
281             var node:Node = event.entity as Node;
282             pois[node.id] = new NodeUI(node, this);
283                         pois[node.id].redraw();
284         }
285
286         public function setHighlight(entity:Entity, settings:Object):void {
287                         var stateType:String;
288             if ( entity is Way ) {
289                 var wayUI:WayUI = ways[entity.id];
290                 if (wayUI==null) { return; }
291                                 for (stateType in settings) {
292                         wayUI.setHighlight(stateType, settings[stateType]);
293                                 }
294                                 wayUI.redraw();
295             } else if (entity is Node) {
296                                 var nodeUI:NodeUI = nodes[entity.id];
297                 if (nodeUI==null) { return; }
298                                 for (stateType in settings) {
299                         nodeUI.setHighlight(stateType, settings[stateType]);
300                                 }
301                                 nodeUI.redraw();
302                         }
303         }
304
305         // Handle mouse events on ways/nodes
306         private var mapController:MapController = null;
307
308         public function setController(controller:MapController):void {
309             this.mapController = controller;
310         }
311
312         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
313             if ( mapController != null )
314                 mapController.entityMouseEvent(event, entity);
315                                 
316         }
317
318                 // ------------------------------------------------------------------------------------------
319                 // Redraw all items, zoom in and out
320                 
321                 public function redraw():void {
322                         for each (var w:WayUI in ways) { w.recalculate(); w.redraw(); }
323                         for each (var p:NodeUI in pois) { p.redraw(); }
324                 }
325
326                 public function redrawPOIs():void {
327                         for each (var p:NodeUI in pois) { p.redraw(); }
328                 }
329
330                 public function zoomIn():void {
331                         if (scale==MAXSCALE) { return; }
332                         changeScale(scale+1);
333                 }
334
335                 public function zoomOut():void {
336                         if (scale==MINSCALE) { return; }
337                         changeScale(scale-1);
338                 }
339
340                 private function changeScale(newscale:uint):void {
341                         addDebug("new scale "+newscale);
342                         scale=newscale;
343                         scalefactor=MASTERSCALE/Math.pow(2,13-scale);
344                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
345                         tileset.changeScale(scale);
346                         download();
347                         redraw();
348                 }
349
350                 private function reportPosition():void {
351                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
352                 }
353
354                 // ------------------------------------------------------------------------------------------
355                 // Export (experimental)
356                 // ** just a bit of fun for now!
357                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
358                 // to that area (will probably require creating a new DisplayObject with a different origin
359                 // and mask)
360 /*              
361                 public function export():void {
362                         addDebug("size is "+this.width+","+this.height);
363                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
364                         jpgSource.draw(this);
365                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
366                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
367                         var fileRef:FileReference = new FileReference();
368 //                      fileRef.save(jpgStream,'map.jpeg');
369                 }
370
371 */
372
373                 // ==========================================================================================
374                 // Events
375                 
376                 // ------------------------------------------------------------------------------------------
377                 // Mouse events
378                 
379                 public function mouseDownHandler(event:MouseEvent):void {
380                         dragstate=NOT_MOVED;
381                         lastxmouse=downX=mouseX;
382                         lastymouse=downY=mouseY;
383                 }
384         
385                 public function mouseUpHandler(event:MouseEvent):void {
386                         if (dragstate==DRAGGING) {
387                                 updateCoords(x,y);
388                                 download();
389                         }
390                         dragstate=NOT_DRAGGING;
391                 }
392         
393                 public function mouseMoveHandler(event:MouseEvent):void {
394                         if (dragstate==NOT_DRAGGING) {
395                                 return;
396                         }
397                         
398                         if (dragstate==NOT_MOVED && Math.abs(downX - mouseX) < 3 && Math.abs(downY - mouseY) < 3) {
399                                 return;
400                         }
401                         
402                         dragstate=DRAGGING;
403                         x+=mouseX-lastxmouse;
404                         y+=mouseY-lastymouse;
405                         lastxmouse=mouseX; lastymouse=mouseY;
406                         setCentre();
407                 }
408         
409                 // ------------------------------------------------------------------------------------------
410                 // Do every frame
411
412                 private function everyFrame(event:Event):void {
413                         if (tileset) { tileset.serviceQueue(); }
414                 }
415
416                 // ------------------------------------------------------------------------------------------
417                 // Miscellaneous events
418                 
419                 public function keyUpHandler(event:KeyboardEvent):void {
420 // addDebug("pressed "+event.keyCode);
421             if ( !event.ctrlKey ) return;
422                         if (event.keyCode==82) { this.redraw(); }                       // R - redraw
423                         if (event.keyCode==73) { this.zoomIn(); }                       // I - zoom in
424                         if (event.keyCode==79) { this.zoomOut(); }                      // O - zoom out
425                         if (event.keyCode==76) { this.reportPosition(); }       // L - report lat/long
426 //                      if (event.keyCode==69) { this.export(); }                       // E - export
427                 }
428
429                 public function connectionError(err:Object=null): void {
430                         addDebug("got error"); 
431                 }
432
433                 // ------------------------------------------------------------------------------------------
434                 // Debugging
435                 
436                 public function addDebug(text:String):void {
437                         if (!Globals.vars.hasOwnProperty('debug')) return;
438                         if (!Globals.vars.debug.visible) return;
439                         Globals.vars.debug.appendText(text+"\n");
440                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
441                 }
442                 
443         }
444 }