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