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