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