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