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