Separate Halcyon (rendering) into standalone target without Flex dependency; JavaScri...
[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.Sprite;
6         import flash.display.Shape;
7         import flash.display.Stage;
8         import flash.display.BitmapData;
9         import flash.display.LoaderInfo;
10         import flash.utils.ByteArray;
11         import flash.events.*;
12         import flash.net.*;
13
14     import net.systemeD.halcyon.connection.*;
15     import net.systemeD.halcyon.connection.EntityEvent;
16         import net.systemeD.halcyon.styleparser.*;
17
18 //      for experimental export function:
19 //      import flash.net.FileReference;
20 //      import com.adobe.images.JPGEncoder;
21
22     public class Map extends Sprite {
23
24                 public const MASTERSCALE:Number=5825.4222222222;// master map scale - how many Flash pixels in 1 degree longitude
25                                                                                                                 // (for Landsat, 5120)
26                 public const MINSCALE:uint=13;                                  // don't zoom out past this
27                 public const MAXSCALE:uint=19;                                  // don't zoom in past this
28
29                 public var ruleset:RuleSet=new RuleSet(redrawPOIs);     // rules
30                 
31                 public var ways:Object=new Object();                    // geodata
32                 public var nodes:Object=new Object();                   //  |
33                 public var pois:Object=new Object();                    //  |
34                 public var relations:Object=new Object();               //  |
35
36                 public var scale:uint=14;                                               // map scale
37                 public var scalefactor:Number=MASTERSCALE;              // current scaling factor for lon/latp
38                 public var bigedge_l:Number= 999999;                    // area of largest whichways
39                 public var bigedge_r:Number=-999999;                    //  |
40                 public var bigedge_b:Number= 999999;                    //  |
41                 public var bigedge_t:Number=-999999;                    //  |
42
43                 public var waycount:uint=0;                                             // ways:                number currently loaded
44                 public var waysrequested:uint=0;                                //                              total number requested
45                 public var waysreceived:uint=0;                                 //                              total number received
46                 public var relcount:uint=0;                                             // relations:   number currently loaded
47                 public var relsrequested:uint=0;                                //                              total number requested
48                 public var relsreceived:uint=0;                                 //                              total number received
49                 public var poicount:uint=0;                                             // POIs:                number currently loaded
50                 public var whichrequested:uint=0;                               // whichways:   total number requested
51                 public var whichreceived:uint=0;                                //                              total number received
52
53                 public var edge_l:Number;                                               // current bounding box
54                 public var edge_r:Number;                                               //  |
55                 public var edge_t:Number;                                               //  |
56                 public var edge_b:Number;                                               //  |
57
58                 public var baselon:Number;                                              // urllon-xradius/masterscale;
59                 public var basey:Number;                                                // lat2lat2p(urllat)+yradius/masterscale;
60                 public var mapwidth:uint;                                               // width (Flash pixels)
61                 public var mapheight:uint;                                              // height (Flash pixels)
62
63                 private var dragging:Boolean=false;                             // dragging map?
64                 private var lastxmouse:Number;                                  //  |
65                 private var lastymouse:Number;                                  //  |
66                 
67                 public var initparams:Object;                                   // object containing 
68
69                 public var backdrop:Object;                                             // reference to backdrop sprite
70                 
71                 public var connection:Connection;                               // server connection
72
73                 // ------------------------------------------------------------------------------------------
74                 // Map constructor function
75
76         public function Map(initparams:Object) {
77
78                         // Set up layering
79                         // [layer][2]                   - names
80                         // [layer][1][sublayer] - stroke
81                         // [layer][0]                   - fill
82
83                         for (var l:int=0; l<13; l++) {                          // 11 layers (10 is +5, 0 is -5)
84                                 var s:Sprite = getPaintSprite();                //  |
85                                 s.addChild(getPaintSprite());                   //      | 0 fill
86                                 var t:Sprite = getPaintSprite();                //  | 1 stroke
87                                 for (var j:int=0; j<11; j++) {                  //      |  | ten sublayers
88                                         t.addChild(getPaintSprite());           //  |  |  |
89                                 }                                                                               //  |  |  |
90                                 s.addChild(t);                                                  //  |  |
91                                 s.addChild(getPaintSprite());                   //      | 2 names
92                                 addChild(s);                                                    //  |
93                         }
94                         s=getPaintSprite(); addChild(s);                        // 11 - POIs
95                         s=getPaintSprite(); addChild(s);                        // 12 - shields and POI names
96
97                         this.initparams=initparams;
98                         connection = Connection.getConnection(initparams['api'],initparams['policy'],initparams['connection']);
99             connection.addEventListener(Connection.NEW_WAY, newWayCreated);
100             connection.addEventListener(Connection.NEW_POI, newPOICreated);
101                         connection.getEnvironment(new Responder(gotEnvironment,connectionError));
102
103         }
104
105         private function getPaintSprite():Sprite {
106             var s:Sprite = new Sprite();
107             s.mouseEnabled = false;
108             return s;
109         }
110
111                 public function gotEnvironment(r:Object):void {
112                         if (initparams.hasOwnProperty('lat')) {
113                                 // parameters sent from HTML
114                                 init(initparams['lat'],
115                                          initparams['lon'],
116                                          initparams['zoom'],
117                                          initparams['style']);
118
119                         } else {
120                                 // somewhere innocuous
121                                 init(53.09465,-2.56495,17,"test.yaml?d="+Math.random());
122                         }
123                 }
124
125                 // ------------------------------------------------------------------------------------------
126                 // Initialise map at a given lat/lon
127
128         public function init(startlat:Number,startlon:Number,startscale:uint,style:String):void {
129
130                         ruleset.load(style);
131 //                      rules.initExample();            // initialise dummy rules
132
133                         //updateSize();
134
135                         scale=startscale;
136                         scalefactor=MASTERSCALE/Math.pow(2,14-scale);
137                         baselon    =startlon          -(mapwidth /2)/scalefactor;
138                         basey      =lat2latp(startlat)+(mapheight/2)/scalefactor;
139                         addDebug("Baselon "+baselon+", basey "+basey);
140                         updateCoords(0,0);
141                         download();
142                         
143         }
144
145                 // ------------------------------------------------------------------------------------------
146                 // Recalculate co-ordinates from new Flash origin
147
148                 public function updateCoords(tx:Number,ty:Number):void {
149                         x=tx; y=ty;
150
151                         // ** calculate tile_l etc.
152                         edge_t=coord2lat(-y          );
153                         edge_b=coord2lat(-y+mapheight);
154                         edge_l=coord2lon(-x          );
155                         edge_r=coord2lon(-x+mapwidth );
156                         addDebug("Lon "+edge_l+"-"+edge_r);
157                         addDebug("Lat "+edge_b+"-"+edge_t);
158                 }
159                 
160                 public function updateCoordsFromLatLon(lat:Number,lon:Number):void {
161                         var cy:Number=-(lat2coord(lat)-mapheight/2);
162                         var cx:Number=-(lon2coord(lon)-mapwidth/2);
163                         updateCoords(cx,cy);
164                 }
165
166
167                 // Co-ordinate conversion functions
168
169                 public function latp2coord(a:Number):Number     { return -(a-basey)*scalefactor; }
170                 public function coord2latp(a:Number):Number     { return a/-scalefactor+basey; }
171                 public function lon2coord(a:Number):Number      { return (a-baselon)*scalefactor; }
172                 public function coord2lon(a:Number):Number      { return a/scalefactor+baselon; }
173
174                 public function latp2lat(a:Number):Number       { return 180/Math.PI * (2 * Math.atan(Math.exp(a*Math.PI/180)) - Math.PI/2); }
175                 public function lat2latp(a:Number):Number       { return 180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2)); }
176
177                 public function lat2coord(a:Number):Number      { return -(lat2latp(a)-basey)*scalefactor; }
178                 public function coord2lat(a:Number):Number      { return latp2lat(a/-scalefactor+basey); }
179
180 //              public function centrelat(o) { return coord2lat((yradius-_root.map._y-o)/Math.pow(2,_root.scale-13)); }
181 //              public function centrelon(o) { return coord2lon((xradius-_root.map._x-o)/Math.pow(2,_root.scale-13)); }
182
183
184                 // ------------------------------------------------------------------------------------------
185                 // Resize map size based on current stage and height
186
187                 public function updateSize(w:uint, h:uint):void {
188                         mapwidth = w;
189                         mapheight= h;
190             if ( backdrop != null ) {
191                 backdrop.width=mapwidth;
192                 backdrop.height=mapheight;
193             }
194             if ( mask != null ) {
195                 mask.width=mapwidth;
196                 mask.height=mapheight;
197             }
198                 }
199
200                 // ------------------------------------------------------------------------------------------
201                 // Download map data
202                 // (typically from whichways, but will want to add more connections)
203
204                 public function download():void {
205                         this.dispatchEvent(new MapEvent(MapEvent.DOWNLOAD,edge_l,edge_r,edge_t,edge_b));
206                         
207                         if (edge_l>=bigedge_l && edge_r<=bigedge_r &&
208                                 edge_b>=bigedge_b && edge_t<=bigedge_t) { return; }     // we have already loaded this area, so ignore
209                         bigedge_l=edge_l; bigedge_r=edge_r;
210                         bigedge_b=edge_b; bigedge_t=edge_t;
211                         addDebug("Calling with "+edge_l+"-"+edge_r+", "+edge_t+"-"+edge_b);
212                         connection.loadBbox(edge_l,edge_r,edge_t,edge_b);
213                 }
214
215
216
217         private function newWayCreated(event:EntityEvent):void {
218             var way:Way = event.entity as Way;
219             ways[way.id] = new WayUI(way, this);
220         }
221
222         private function newPOICreated(event:EntityEvent):void {
223             var node:Node = event.entity as Node;
224             pois[node.id] = new POI(node, this);
225         }
226
227         public function setHighlight(entity:Entity, highlight:Boolean):void {
228             if ( entity is Way ) {
229                 var wayUI:WayUI = ways[entity.id];
230                 if ( wayUI != null )
231                     wayUI.setHighlight(highlight);
232             }
233         }
234
235         // Handle mouse events on ways/nodes
236         private var mapController:MapController = null;
237
238         public function setController(controller:MapController):void {
239             this.mapController = controller;
240         }
241
242         public function wayMouseEvent(event:MouseEvent, way:Way):void {
243             if ( mapController != null )
244                 mapController.entityMouseEvent(event, way);
245                                 
246         }
247
248                 // ------------------------------------------------------------------------------------------
249                 // Redraw all items, zoom in and out
250                 
251                 public function redraw():void {
252                         for each (var w:WayUI in ways) { w.recalculate(); w.redraw(); }
253                         for each (var p:POI in pois) { p.redraw(); }
254                 }
255
256                 public function redrawPOIs():void {
257                         for each (var p:POI in pois) { p.redraw(); }
258                 }
259
260                 public function zoomIn():void {
261                         if (scale==MAXSCALE) { return; }
262                         changeScale(scale+1);
263                 }
264
265                 public function zoomOut():void {
266                         if (scale==MINSCALE) { return; }
267                         changeScale(scale-1);
268                 }
269
270                 private function changeScale(newscale:uint):void {
271                         addDebug("new scale "+newscale);
272                         scale=newscale;
273                         scalefactor=MASTERSCALE/Math.pow(2,14-scale);
274                         updateCoordsFromLatLon((edge_t+edge_b)/2,(edge_l+edge_r)/2);    // recentre
275                         download();
276                         redraw();
277                 }
278
279                 private function reportPosition():void {
280                         addDebug("lon "+coord2lon(mouseX)+", lat "+coord2lat(mouseY));
281                 }
282
283                 // ------------------------------------------------------------------------------------------
284                 // Export (experimental)
285                 // ** just a bit of fun for now!
286                 // really needs to take a bbox, and make sure that the image is correctly cropped/resized 
287                 // to that area (will probably require creating a new DisplayObject with a different origin
288                 // and mask)
289 /*              
290                 public function export():void {
291                         addDebug("size is "+this.width+","+this.height);
292                         var jpgSource:BitmapData = new BitmapData(800,800); // (this.width, this.height);
293                         jpgSource.draw(this);
294                         var jpgEncoder:JPGEncoder = new JPGEncoder(85);
295                         var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
296                         var fileRef:FileReference = new FileReference();
297 //                      fileRef.save(jpgStream,'map.jpeg');
298                 }
299
300 */
301
302                 // ==========================================================================================
303                 // Events
304                 
305                 // ------------------------------------------------------------------------------------------
306                 // Mouse events
307                 
308                 public function mouseDownHandler(event:MouseEvent):void {
309                         dragging=true;
310                         lastxmouse=mouseX; lastymouse=mouseY;
311                 }
312         
313                 public function mouseUpHandler(event:MouseEvent):void {
314 addDebug("up");
315                         if (!dragging) { return; }
316                         dragging=false;
317                         updateCoords(x,y);
318                         download();
319                 }
320         
321                 public function mouseMoveHandler(event:MouseEvent):void {
322                         if (!dragging) { return; }
323                         x+=mouseX-lastxmouse;
324                         y+=mouseY-lastymouse;
325                         lastxmouse=mouseX; lastymouse=mouseY;
326                 }
327         
328                 // ------------------------------------------------------------------------------------------
329                 // Miscellaneous events
330                 
331                 public function keyUpHandler(event:KeyboardEvent):void {
332 // addDebug("pressed "+event.keyCode);
333             if ( !event.ctrlKey ) return;
334                         if (event.keyCode==82) { this.redraw(); }                       // R - redraw
335                         if (event.keyCode==73) { this.zoomIn(); }                       // I - zoom in
336                         if (event.keyCode==79) { this.zoomOut(); }                      // O - zoom out
337                         if (event.keyCode==76) { this.reportPosition(); }       // L - report lat/long
338 //                      if (event.keyCode==69) { this.export(); }                       // E - export
339                 }
340
341                 public function connectionError(err:Object=null): void {
342                         addDebug("got error"); 
343                 }
344
345                 // ------------------------------------------------------------------------------------------
346                 // Debugging
347                 
348                 public function addDebug(text:String):void {
349                         if (!Globals.vars.hasOwnProperty('debug')) return;
350                         if (!Globals.vars.debug.visible) return;
351                         Globals.vars.debug.appendText(text+"\n");
352                         Globals.vars.debug.scrollV=Globals.vars.debug.maxScrollV;
353                 }
354                 
355         }
356 }