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