beginning of vector background layers. And a whole load of other stuff too
[potlatch2.git] / net / systemeD / halcyon / WayUI.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.geom.Matrix;
5         import flash.geom.Point;
6         import flash.geom.Rectangle;
7         import flash.text.TextField;
8         import flash.text.TextFormat;
9         import flash.events.*;
10         import net.systemeD.halcyon.styleparser.*;
11     import net.systemeD.halcyon.connection.*;
12         import net.systemeD.halcyon.Globals;
13
14         public class WayUI extends EntityUI {
15
16         private var way:Way;
17                 public var pathlength:Number;                           // length of path
18                 public var patharea:Number;                                     // area of path
19                 public var centroid_x:Number;                           // centroid
20                 public var centroid_y:Number;                           //  |
21                 public var heading:Array=new Array();           // angle at each node
22         private var hitzone:Sprite;
23                 public var nameformat:TextFormat;
24
25                 private const NODESIZE:uint=6;
26
27                 public function WayUI(way:Way, paint:MapPaint, interactive:Boolean=true) {
28                         super();
29                         this.way = way;
30                         this.paint = paint;
31                         this.ruleset = ruleset;
32                         this.interactive = interactive;
33             init();
34             way.addEventListener(Connection.TAG_CHANGED, wayTagChanged);
35             way.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
36             way.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
37                         way.addEventListener(Connection.WAY_DELETED, wayDeleted);
38                         way.addEventListener(Connection.ADDED_TO_RELATION, wayRelationAdded);
39                         way.addEventListener(Connection.REMOVED_FROM_RELATION, wayRelationRemoved);
40                         way.addEventListener(Connection.SUSPEND_REDRAW, suspendRedraw);
41                         way.addEventListener(Connection.RESUME_REDRAW, resumeRedraw);
42             attachNodeListeners();
43             attachRelationListeners();
44                 }
45                 
46                 private function attachNodeListeners():void {
47             for (var i:uint = 0; i < way.length; i++ ) {
48                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
49             }
50                 }
51
52                 private function attachRelationListeners():void {
53                     var relations:Array = way.parentRelations;
54             for each(var relation:Relation in relations ) {
55                 relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
56             }
57                 }
58                 
59                 private function wayRelationAdded(event:RelationMemberEvent):void {
60                     event.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
61                     redraw();
62                 }
63                 
64                 private function wayRelationRemoved(event:RelationMemberEvent):void {
65                     event.relation.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
66                     redraw();
67                 }
68                 
69                 private function wayNodeAdded(event:WayNodeEvent):void {
70                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved);
71                     redraw();
72                 }
73                     
74                 private function wayNodeRemoved(event:WayNodeEvent):void {
75                     event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
76                     redraw();
77                 }
78                     
79         private function wayTagChanged(event:TagEvent):void {
80             redraw();
81         }
82         private function relationTagChanged(event:TagEvent):void {
83             redraw();
84         }
85         private function nodeMoved(event:NodeMovedEvent):void {
86             redraw();
87         }
88                 private function wayDeleted(event:EntityEvent):void {
89                         redraw();
90                 }
91
92                 private function init():void {
93                         recalculate();
94                         redraw();
95                         // updateBbox(lon, lat);
96                         // ** various other stuff
97                 }
98
99                 // ------------------------------------------------------------------------------------------
100                 // Calculate length etc.
101                 // ** this could be made scale-independent - would speed up redraw
102                 
103                 public function recalculate():void {
104                         var lx:Number, ly:Number, sc:Number;
105                         var node:Node, latp:Number, lon:Number;
106                         var cx:Number=0, cy:Number=0;
107                         pathlength=0;
108                         patharea=0;
109                         if (way.length==0) { return; }
110                         
111                         lx = way.getNode(way.length-1).lon;
112                         ly = way.getNode(way.length-1).latp;
113                         for ( var i:uint = 0; i < way.length; i++ ) {
114                 node = way.getNode(i);
115                 latp = node.latp;
116                 lon  = node.lon;
117
118                                 // length and area
119                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
120                                 sc = (lx*latp-lon*ly)*paint.map.scalefactor;
121                                 cx += (lx+lon)*sc;
122                                 cy += (ly+latp)*sc;
123                                 patharea += sc;
124                                 
125                                 // heading
126                                 if (i>0) { heading[i-1]=Math.atan2((lon-lx),(latp-ly)); }
127
128                                 lx=lon; ly=latp;
129                         }
130                         heading[way.length-1]=heading[way.length-2];
131
132                         pathlength*=paint.map.scalefactor;
133                         patharea/=2;
134                         if (patharea!=0 && way.isArea()) {
135                                 centroid_x=paint.map.lon2coord(cx/patharea/6);
136                                 centroid_y=paint.map.latp2coord(cy/patharea/6);
137                         } else if (pathlength>0) {
138                                 var c:Array=pointAt(0.5);
139                                 centroid_x=c[0];
140                                 centroid_y=c[1];
141                         }
142                 }
143
144                 // ------------------------------------------------------------------------------------------
145                 // Redraw
146
147                 override public function doRedraw(sl:StyleList):Boolean {
148                         removeSprites();
149                         if (way.length==0) { return false; }
150                         if (!paint.ready) { return false; }
151
152             // Copy tags object, and add states
153             var tags:Object = way.getTagsCopy();
154                         tags=applyStateClasses(tags);
155                         if (way.isArea()) { tags[':area']='yes'; }
156
157                         // Which layer?
158                         layer=0;
159                         if (tags['layer']) { layer=Math.min(Math.max(tags['layer'],paint.minlayer),paint.maxlayer); }
160
161                         // Iterate through each sublayer, drawing any styles on that layer
162                         if (!sl) { sl=paint.ruleset.getStyles(this.way, tags); }
163                         var drawn:Boolean;
164                         for (var sublayer:int=10; sublayer>=0; sublayer--) {
165                                 if (sl.shapeStyles[sublayer]) {
166                                         var s:ShapeStyle=sl.shapeStyles[sublayer];
167                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
168                                         var x0:Number=paint.map.lon2coord(way.getNode(0).lon);
169                                         var y0:Number=paint.map.latp2coord(way.getNode(0).latp);
170
171                                         // Stroke
172                                         if (s.width)  {
173                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,sublayer);
174                                                 stroke.graphics.moveTo(x0,y0);
175                                                 s.applyStrokeStyle(stroke.graphics);
176                                                 if (s.dashes && s.dashes.length>0) { dashedLine(stroke.graphics,s.dashes); }
177                                                                                                           else { solidLine(stroke.graphics); }
178                                                 drawn=true;
179                                         }
180
181                                         // Fill
182                                         if (s.fill_color || s.fill_image) {
183                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE);
184                                                 fill.graphics.moveTo(x0,y0);
185                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
186                                                                          else { s.applyFill(fill.graphics); }
187                                                 solidLine(fill.graphics);
188                                                 fill.graphics.endFill();
189                                                 drawn=true;
190                                         }
191
192                                         // Casing
193                                         if (s.casing_width) { 
194                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
195                                                 casing.graphics.moveTo(x0,y0);
196                                                 s.applyCasingStyle(casing.graphics);
197                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
198                                                                                                                                         else { solidLine(casing.graphics); }
199                                                 drawn=true;
200                                         }
201                                 }
202                                 
203                                 if (sl.textStyles[sublayer]) {
204                                         var t:TextStyle=sl.textStyles[sublayer];
205                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
206                                         nameformat = t.getTextFormat();
207                                         var a:String=tags[t.text];
208                                         if (a) {
209                                                 if (t.font_caps) { a=a.toUpperCase(); }
210                                                 if (t.text_center && centroid_x) {
211                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
212                                                 } else {
213                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
214                                                 }
215                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
216                                         }
217                                 }
218                                 
219                                 // ** ShieldStyle to do
220                         }
221
222                         // Draw icons
223                         // ** there should be huge potential to optimise this - at present we're
224                         //    running getStyles for every node in the way on every redraw
225                         // ** fix r/heading behaviour - that doesn't look right
226                         var r:Number;
227                         var nodetags:Object;
228                         var nodeSelected:int=stateClasses["nodeSelected"];
229                         for (var i:uint = 0; i < way.length; i++) {
230                 var node:Node = way.getNode(i);
231                                 nodetags=node.getTagsCopy();
232                                 if (i==0) { nodetags['_heading']= heading[i]; }
233                                      else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
234                                 if (stateClasses["showNodes"]) { nodetags[':selectedway']='yes'; }
235                                 if (stateClasses["showNodesHover"]) { nodetags[':hoverway']='yes'; }
236                                 if (node.id==nodeSelected) { nodetags[':selected']='yes'; }
237                                 if (node.numParentWays>1) { nodetags[':junction']='yes'; }
238                                 sl=paint.ruleset.getStyles(node,nodetags);
239                                 if (sl.hasStyles()) {
240                                         if (!paint.nodeuis[node.id]) {
241                                                 paint.nodeuis[node.id]=new NodeUI(node,paint,r);
242                                         }
243                                         paint.nodeuis[node.id].redraw(sl);
244                                 } else if (paint.nodeuis[node.id]) {
245                                         paint.nodeuis[node.id].removeSprites();
246                                         delete paint.nodeuis[node.id];
247                                 }
248                         }
249                         if (!drawn) { return false; }
250                         
251             // create a generic "way" hitzone sprite
252             hitzone = new Sprite();
253             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
254             solidLine(hitzone.graphics);
255             addToLayer(hitzone, CLICKSPRITE);
256             hitzone.visible = false;
257                         setListenSprite(hitzone);
258
259                         return true;
260                 }
261                 
262                 // ------------------------------------------------------------------------------------------
263                 // Drawing support functions
264
265                 // Draw solid polyline
266                 
267                 public function solidLine(g:Graphics):void {
268             var node:Node = way.getNode(0);
269                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
270                         for (var i:uint = 1; i < way.length; i++) {
271                 node = way.getNode(i);
272                                 g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
273                         }
274                 }
275
276                 // Draw dashed polyline
277                 
278                 private function dashedLine(g:Graphics,dashes:Array):void {
279                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
280                         var a:Number, xc:Number, yc:Number;
281                         var curx:Number, cury:Number;
282                         var dx:Number, dy:Number, segleft:Number=0;
283                         var i:int=0;
284
285             var node:Node = way.getNode(0);
286             var nextNode:Node = way.getNode(0);
287                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
288                         while (i < way.length-1 || segleft>0) {
289                                 if (dashleft<=0) {      // should be ==0
290                                         if (dc.length==0) { dc=dashes.slice(0); }
291                                         dashleft=dc.shift();
292                                         draw=!draw;
293                                 }
294                                 if (segleft<=0) {       // should be ==0
295                     node = way.getNode(i);
296                     nextNode = way.getNode(i+1);
297                                         curx=paint.map.lon2coord(node.lon);
298                     dx=paint.map.lon2coord(nextNode.lon)-curx;
299                                         cury=paint.map.latp2coord(node.latp);
300                     dy=paint.map.latp2coord(nextNode.latp)-cury;
301                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
302                                         segleft=Math.sqrt(dx*dx+dy*dy);
303                                         i++;
304                                 }
305
306                                 if (segleft<=dashleft) {
307                                         // the path segment is shorter than the dash
308                                         curx+=dx; cury+=dy;
309                                         moveLine(g,curx,cury,draw);
310                                         dashleft-=segleft; segleft=0;
311                                 } else {
312                                         // the path segment is longer than the dash
313                                         curx+=dashleft*xc; dx-=dashleft*xc;
314                                         cury+=dashleft*yc; dy-=dashleft*yc;
315                                         moveLine(g,curx,cury,draw);
316                                         segleft-=dashleft; dashleft=0;
317                                 }
318                         }
319                 }
320
321                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
322                         if (draw) { g.lineTo(x,y); }
323                                  else { g.moveTo(x,y); }
324                 }
325
326                 
327                 // Find point partway (0-1) along a path
328                 // returns (x,y,angle)
329                 // inspired by senocular's Path.as
330                 
331                 private function pointAt(t:Number):Array {
332                         var totallen:Number = t*pathlength;
333                         var curlen:Number = 0;
334                         var dx:Number, dy:Number, seglen:Number;
335                         for (var i:int = 1; i < way.length; i++){
336                                 dx=paint.map.lon2coord(way.getNode(i).lon)-paint.map.lon2coord(way.getNode(i-1).lon);
337                                 dy=paint.map.latp2coord(way.getNode(i).latp)-paint.map.latp2coord(way.getNode(i-1).latp);
338                                 seglen=Math.sqrt(dx*dx+dy*dy);
339                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
340                                 return new Array(paint.map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
341                                                                  paint.map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
342                                                                  Math.atan2(dy,dx));
343                         }
344                         return new Array(0, 0, 0);
345                 }
346
347                 // Draw name along path
348                 // based on code by Tom Carden
349                 
350                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
351
352                         // make a dummy textfield so we can measure its width
353                         var tf:TextField = new TextField();
354                         tf.defaultTextFormat = nameformat;
355                         tf.text = a;
356                         tf.width = tf.textWidth+4;
357                         tf.height = tf.textHeight+4;
358                         if (pathlength<tf.width) { return; }    // no room for text?
359
360                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
361                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
362
363                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
364                         var offsetSign:Number;  // -1 if we're starting at t2
365                         var tStart:Number;      // t1 or t2
366
367                         // make sure text doesn't run right->left or upside down
368                         if (p1[0] < p2[0] && 
369                                 p1[2] < Math.PI/2 &&
370                                 p1[2] > -Math.PI/2) {
371                                 angleOffset = 0; offsetSign = 1; tStart = t1;
372                         } else {
373                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
374                         } 
375
376                         // make a textfield for each char, centered on the line,
377                         // using getCharBoundaries to rotate it around its center point
378                         var chars:Array = a.split('');
379                         for (var i:int = 0; i < chars.length; i++) {
380                                 var rect:Rectangle = tf.getCharBoundaries(i);
381                                 if (rect) {
382                                         s.addChild(rotatedLetter(chars[i],
383                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
384                                                                                          rect.width, tf.height, angleOffset, textOffset));
385                                 }
386                         }
387                 }
388
389                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
390                         var tf:TextField = new TextField();
391             tf.mouseEnabled = false;
392             tf.mouseWheelEnabled = false;
393                         tf.defaultTextFormat = nameformat;
394                         tf.embedFonts = true;
395                         tf.text = char;
396                         tf.width = tf.textWidth+4;
397                         tf.height = tf.textHeight+4;
398
399                         var p:Array=pointAt(t);
400                         var matrix:Matrix = new Matrix();
401                         matrix.translate(-w/2, -h/2-o);
402                         // ** add (say) -4 to the height to move it up by 4px
403                         matrix.rotate(p[2]+a);
404                         matrix.translate(p[0], p[1]);
405                         tf.transform.matrix = matrix;
406                         return tf;
407                 }
408                 
409                 public function getNodeAt(x:Number, y:Number):Node {
410                         for (var i:uint = 0; i < way.length; i++) {
411                 var node:Node = way.getNode(i);
412                 var nodeX:Number = paint.map.lon2coord(node.lon);
413                 var nodeY:Number = paint.map.latp2coord(node.latp);
414                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
415                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
416                     return node;
417             }
418             return null;
419                 }
420
421         override protected function mouseEvent(event:MouseEvent):void {
422                         paint.map.entityMouseEvent(event, way);
423         }
424
425         }
426 }