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