Merge pull request #7 from jetthe/3791
[potlatch2.git] / net / systemeD / halcyon / WayUI.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.events.*;
5         import flash.geom.Matrix;
6         import flash.geom.Rectangle;
7         import flash.text.TextField;
8         import flash.text.TextFormat;
9         
10         import net.systemeD.halcyon.connection.*;
11         import net.systemeD.halcyon.styleparser.*;
12
13         /** The graphical representation of a Way. */ 
14         public class WayUI extends EntityUI {
15
16                 /** Total length of way */
17                 public var pathlength:Number;
18                 /** Area of the way */
19                 public var patharea:Number;
20                 /** X coord of the centre of the area */
21                 public var centroid_x:Number;
22                 /** Y coord of the centre of the area */
23                 public var centroid_y:Number;                           //  |
24                 /** Angle at each node */
25                 public var heading:Array=new Array();
26                 /** vertex to draw exclusively, or not at all (used by DragWayNode) */ 
27                 public var drawExcept:Number;
28                 /** " */
29                 public var drawOnly:Number;
30                 private var indexStart:uint;
31                 private var indexEnd:uint;
32                 public var nameformat:TextFormat;
33                 private var recalculateDue:Boolean=false;
34                 // Store the temporary highlight settings applied to all nodes.
35                 private var nodehighlightsettings: Object={};
36
37                 private const NODESIZE:uint=6;
38
39                 public function WayUI(way:Way, paint:MapPaint) {
40                         super(way,paint);
41             entity.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded, false, 0, true);
42             entity.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved, false, 0, true);
43             entity.addEventListener(Connection.WAY_REORDERED, wayReordered, false, 0, true);
44             entity.addEventListener(Connection.ENTITY_DRAGGED, wayDragged, false, 0, true);
45             attachNodeListeners();
46             attachRelationListeners();
47             recalculate();
48                         redraw();
49                         redrawMultis();
50                 }
51                 
52                 public function removeEventListeners():void {
53                         removeGenericEventListeners();
54             entity.removeEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
55             entity.removeEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
56             entity.removeEventListener(Connection.WAY_REORDERED, wayReordered);
57             entity.removeEventListener(Connection.ENTITY_DRAGGED, wayDragged);
58                         removeNodeListeners();
59                         removeRelationListeners();
60                 }
61                 
62                 private function attachNodeListeners():void {
63                         var way:Way=entity as Way;
64             for (var i:uint = 0; i < way.length; i++ ) {
65                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved, false, 0, true);
66             }
67                 }
68                 
69                 private function removeNodeListeners():void {
70                         var way:Way=entity as Way;
71             for (var i:uint = 0; i < way.length; i++ ) {
72                 way.getNode(i).removeEventListener(Connection.NODE_MOVED, nodeMoved);
73             }
74                 }
75                 
76                 private function wayNodeAdded(event:WayNodeEvent):void {
77                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved, false, 0, true);
78             recalculate();
79                     redraw();
80                         redrawMultis();
81                 }
82                     
83                 private function wayNodeRemoved(event:WayNodeEvent):void {
84                     if (!event.node.hasParent(event.way)) {
85                                 event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
86                         }
87                         paint.redrawEntity(event.node);
88             recalculate();
89                     redraw();
90                         redrawMultis();
91                 }
92                     
93         private function nodeMoved(event:NodeMovedEvent):void {
94                         recalculate();
95             redraw();
96                         redrawMultis();
97         }
98         private function wayReordered(event:EntityEvent):void {
99             redraw();
100                         redrawMultis();
101         }
102                 private function wayDragged(event:EntityDraggedEvent):void {
103                         offsetSprites(event.xDelta,event.yDelta);
104                 }
105
106                 override protected function relationAdded(event:RelationMemberEvent):void {
107                         super.relationAdded(event);
108                         redrawMultis();
109                 }
110                 override protected function relationRemoved(event:RelationMemberEvent):void {
111                         super.relationRemoved(event);
112                         redrawMultis();
113                 }
114                 override protected function relationTagChanged(event:TagEvent):void {
115                         super.relationTagChanged(event);
116                         redrawMultis();
117                 }
118
119                 /** Don't redraw until further notice. */
120                 override public function suspendRedraw(event:EntityEvent):void {
121                         super.suspendRedraw(event);
122                         recalculateDue=false;
123                 }
124                 
125                 /** Continue redrawing as normal. */
126                 override public function resumeRedraw(event:EntityEvent):void {
127                         suspended=false;
128                         if (recalculateDue) { recalculate(); }
129                         super.resumeRedraw(event);
130                 }
131
132                 /** Redraw other ways that are the "outer" part of a multipolygon of which we are the "inner" */
133                 public function redrawMultis():void {
134                         var multis:Array=entity.findParentRelationsOfType('multipolygon','inner');
135                         for each (var m:Relation in multis) {
136                                 var outers:Array=m.findMembersByRole('outer');
137                                 for each (var e:Entity in outers) { 
138                                         paint.redrawEntity(e);
139                                 }
140                         }
141                 }
142         
143         /** Mark every node in this way as highlighted, and redraw it. 
144         * 
145         * @param settings Style state that it applies to. @see EntityUI#setStateClass()
146         *  */
147         public function setHighlightOnNodes(settings:Object):void {
148                         for (var i:uint = 0; i < Way(entity).length; i++) {
149                 var node:Node = Way(entity).getNode(i);
150                                 // Speed things up a bit by only setting the highlight if it's either:
151                                 // a) an "un-highlight" (so we don't leave mess behind when scrolling)
152                                 // b) currently onscreen
153                                 // Currently this means if you highlight an object then scroll, nodes will scroll
154                                 // into view that should be highlighted but aren't.
155                                 if (settings.hoverway==false || 
156                                     settings.selectedway==false || 
157                                     node.within(paint.map.edge_l, paint.map.edge_r, paint.map.edge_t, paint.map.edge_b)) {
158                                     paint.setHighlight(node,settings); // Triggers redraw if required
159                                 }
160                                 if (settings.selectedway || settings.hoverway)
161                                         nodehighlightsettings=settings;
162                                 else
163                                         nodehighlightsettings={}; 
164                         }
165         }
166         
167         // An ugly hack to allow nodes that have recently scrolled into view to get highlighted.
168         public function updateHighlights():void {
169                 if (nodehighlightsettings)
170                    setHighlightOnNodes(nodehighlightsettings);
171         }
172
173                 // ------------------------------------------------------------------------------------------
174                 /** Calculate pathlength, patharea, centroid_x, centroid_y, heading[]. 
175                 * ** this could be made scale-independent - would speed up redraw
176                 */
177                 public function recalculate():void {
178                         if (suspended) { recalculateDue=true; return; }
179                         
180                         var lx:Number, ly:Number, sc:Number;
181                         var node:Node, latp:Number, lon:Number;
182                         var cx:Number=0, cy:Number=0;
183                         var way:Way=entity as Way;
184                         
185                         pathlength=0;
186                         patharea=0;
187                         if (way.length==0) { return; }
188                         
189                         lx = way.getNode(way.length-1).lon;
190                         ly = way.getNode(way.length-1).latp;
191                         for ( var i:uint = 0; i < way.length; i++ ) {
192                 node = way.getNode(i);
193                 latp = node.latp;
194                 lon  = node.lon;
195
196                                 // length and area
197                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
198                                 sc = (lx*latp-lon*ly)*paint.map.scalefactor;
199                                 cx += (lx+lon)*sc;
200                                 cy += (ly+latp)*sc;
201                                 patharea += sc;
202                                 
203                                 // heading
204                                 if (i>0) { heading[i-1]=Math.atan2((lon-lx),(latp-ly)); }
205
206                                 lx=lon; ly=latp;
207                         }
208                         heading[way.length-1]=heading[way.length-2];
209
210                         pathlength*=paint.map.scalefactor;
211                         patharea/=2;
212                         if (patharea!=0 && way.isArea()) {
213                                 centroid_x=paint.map.lon2coord(cx/patharea/6);
214                                 centroid_y=paint.map.latp2coord(cy/patharea/6);
215                         } else if (pathlength>0) {
216                                 var c:Array=pointAt(0.5);
217                                 centroid_x=c[0];
218                                 centroid_y=c[1];
219                         }
220                 }
221
222                 // ------------------------------------------------------------------------------------------
223         
224                 /** Go through the complex process of drawing this way, including applying styles, casings, fills, fonts... */
225                 override public function doRedraw():Boolean {
226                         interactive=false;
227                         removeSprites();
228                         if (Way(entity).length==0) { return false; }
229                         if (!paint.ready) { return false; }
230
231             // Copy tags object, and add states
232             var tags:Object = entity.getTagsCopy();
233             setStateClass('area', Way(entity).isArea());
234             setStateClass('background', paint.isBackground);
235             setStateClass('tiger', (entity.isUneditedTiger() && Globals.vars.highlightTiger));
236             tags=applyStateClasses(tags);
237                         if (entity.status) { tags['_status']=entity.status; }
238
239                         // Keep track of maximum stroke width for hitzone
240                         var maxwidth:Number=4;
241
242                         // Create styleList if not already drawn
243                         if (!styleList || !styleList.isValidAt(paint.map.scale)) {
244                                 styleList=paint.ruleset.getStyles(entity, tags, paint.map.scale);
245                         }
246
247                         // Which layer?
248                         layer=styleList.layerOverride();
249                         if (isNaN(layer)) {
250                                 layer=0;
251                                 if (tags['layer']) { layer=Math.min(Math.max(tags['layer'],paint.minlayer),paint.maxlayer); }
252                         }
253
254                         // Do we have to draw all nodes in the way?
255                         var hasFills:Boolean=styleList.hasFills();
256                         if (isNaN(drawOnly) || hasFills) {
257                                 indexStart=0; indexEnd=Way(entity).length; 
258                         } else {
259                                 indexStart=Math.max(0,drawOnly-1);
260                                 indexEnd  =Math.min(drawOnly+2,Way(entity).length);
261                         }
262
263                         // Iterate through each subpart, drawing any styles on that layer
264                         var drawn:Boolean;
265                         var multis:Array=entity.findParentRelationsOfType('multipolygon','outer');
266                         var inners:Array=[];
267                         for each (var m:Relation in multis) {
268                                 inners=inners.concat(m.findMembersByRole('inner',Way));
269                         }
270
271                         for each (var subpart:String in styleList.subparts) {
272                                 if (styleList.shapeStyles[subpart]) {
273                                         var s:ShapeStyle=styleList.shapeStyles[subpart];
274                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
275                                         var x0:Number=paint.map.lon2coord(Way(entity).getNode(0).lon);
276                                         var y0:Number=paint.map.latp2coord(Way(entity).getNode(0).latp);
277                                         interactive||=s.interactive;
278
279                                         // Stroke
280                                         if (s.width)  {
281                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,s.sublayer);
282                                                 stroke.graphics.moveTo(x0,y0);
283                                                 s.applyStrokeStyle(stroke.graphics);
284                                                 if (s.dashes && s.dashes.length>0) {
285                                                         var segments:Array=dashedLine(stroke.graphics,s.dashes); 
286                                                         if (s.line_style) { lineDecoration(stroke.graphics,s,segments); }
287                                                 } else { solidLines(stroke.graphics,inners); }
288                                                 drawn=true;
289                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.width); }
290                                         }
291
292                                         // Fill
293                                         if ((!isNaN(s.fill_color) || s.fill_image) && entity.findParentRelationsOfType('multipolygon','inner').length==0 && isNaN(drawExcept)) {
294                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE,s.sublayer);
295                                                 fill.graphics.moveTo(x0,y0);
296                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
297                                                                          else { s.applyFill(fill.graphics); }
298                                                 solidLines(fill.graphics,inners);
299                                                 fill.graphics.endFill();
300                                                 drawn=true;
301                                         }
302
303                                         // Casing
304                                         if (s.casing_width) { 
305                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
306                                                 casing.graphics.moveTo(x0,y0);
307                                                 s.applyCasingStyle(casing.graphics);
308                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
309                                                                                                                                         else { solidLines(casing.graphics,inners); }
310                                                 drawn=true;
311                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.casing_width); }
312                                         }
313                                 }
314                                 
315                                 if (styleList.textStyles[subpart] && isNaN(drawExcept)) {
316                                         var t:TextStyle=styleList.textStyles[subpart];
317                                         interactive||=t.interactive;
318                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
319                                         nameformat = t.getTextFormat();
320                                         var a:String=tags[t.text];
321                                         if (a) {
322                                                 if (t.font_caps) { a=a.toUpperCase(); }
323                                                 if (t.text_center && centroid_x) {
324                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
325                                                 } else {
326                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
327                                                 }
328                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
329                                         }
330                                 }
331                                 
332                                 // ** ShieldStyle to do
333                         }
334
335                         // Draw icons
336                         var r:Number;
337                         var nodeSelected:int=stateClasses["nodeSelected"];
338                         for (var i:uint = indexStart; i < indexEnd; i++) {
339                 var node:Node = Way(entity).getNode(i);
340                                 var nodeStateClasses:Object={};
341 //                              if (i==0) { nodetags['_heading']= heading[i]; }
342 //                                   else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
343                                 // ** FIXME - heading isn't currently applied
344                                 nodeStateClasses['junction']=(node.numParentWays>1);
345                                 paint.createNodeUI(node,r,layer,nodeStateClasses);
346                         }
347                         if (!drawn) { return false; } // If not visible, no hitzone.
348                         
349             // create a generic "way" hitzone sprite
350                         if (interactive && drawn) {
351                     hitzone = new Sprite();
352                     hitzone.graphics.lineStyle(maxwidth, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
353                     solidLines(hitzone.graphics,[]);
354                     hitzone.visible = false;
355                                 setListenSprite();
356                         }
357
358                         return true;
359                 }
360                 
361                 // ------------------------------------------------------------------------------------------
362                 // Drawing support functions
363
364                 /** Draw solid polyline */
365                 
366                 public function solidLines(g:Graphics,inners:Array):void {
367                         solidLine(g);
368                         for each (var w:Way in inners) { solidLineOtherWay(g,w); }
369                 }
370
371                 private function solidLine(g:Graphics):void {
372                         if (indexEnd==0) { return; }
373                         var way:Way=entity as Way;
374                         
375             var node:Node = way.getNode(indexStart);
376                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
377                         for (var i:uint = indexStart+1; i < indexEnd; i++) {
378                 node = way.getNode(i);
379                                 if (!isNaN(drawExcept) && (i-1==drawExcept || i==drawExcept)) {
380                                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
381                                 } else {
382                                         g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
383                                 }
384                         }
385                 }
386
387                 private function solidLineOtherWay(g:Graphics,way:Way):void {
388                         if (way.length==0) { return; }
389                         
390                         var node:Node = way.getNode(0);
391                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
392                         for (var i:uint = 1; i < way.length; i++) {
393                                 node = way.getNode(i);
394                                 g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
395                         }
396                 }
397
398                 /** Draw dashed polyline */
399                 
400                 private function dashedLine(g:Graphics,dashes:Array):Array {
401                         var way:Way=entity as Way;
402                         var segments:Array=[]; // array of dash locations being constructed for later arrow drawing
403                         var draw:Boolean=false; // are we drawing or marking empty space till next dash
404                         var dashleft:Number=0; // how much of current dash is left
405                         var dc:Array=new Array(); // copy of dashes, gets consumed then replaced
406                         var xc:Number, yc:Number; // normalised vector coordinates of direction to next node 
407                         var curx:Number, cury:Number; // current drawing location
408                         var dx:Number, dy:Number, segleft:Number=0; // distance remaining until next node
409                         var i:int=indexStart; // node index
410                         var dashstartx:int, dashstarty:int; // needed to draw reverse arrows
411                         var dashstartxc: Number, dashstartyc: Number;
412
413             var node:Node = way.getNode(i);
414             var nextNode:Node = way.getNode(i);
415                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
416                         while (i < indexEnd-1 || segleft>0) {
417                                 if (dashleft<=0) {      // should be ==0
418                                     // finished drawing current dash, pop another one off the pattern, looping if necessary
419                                         if (dc.length==0) { dc=dashes.slice(0); }
420                                         dashleft=dc.shift();
421                                         if (draw) { segments.push([curx,cury,xc,yc, dashstartx, dashstarty, dashstartxc, dashstartyc]); }
422                                         draw=!draw;
423                                         // record start of each dash, if we need to draw a reverse arrow head later
424                                         dashstartx = curx; dashstarty = cury;
425                                         dashstartxc = xc; dashstartyc = yc;
426                                 }
427                                 if (i==drawExcept || i==drawExcept+1) { draw=false; }
428                                 if (segleft<=0) {       // should be ==0
429                     // arrived at target node. calculate direction to next node.
430                     node = way.getNode(i);
431                     nextNode = way.getNode(i+1);
432                                         curx=paint.map.lon2coord(node.lon);
433                     dx=paint.map.lon2coord(nextNode.lon)-curx;
434                                         cury=paint.map.latp2coord(node.latp);
435                     dy=paint.map.latp2coord(nextNode.latp)-cury;
436                                         segleft=Math.sqrt(dx*dx+dy*dy);
437                                         xc = dx/segleft;
438                                         yc = dy/segleft;
439                                         if (i==0) {
440                         // record start location of very first dash
441                         dashstartx = curx; dashstarty = cury;
442                         dashstartxc = xc; dashstartyc = yc;
443                                         }
444                                         i++;
445                                 }
446
447                                 if (segleft<=dashleft) {
448                                         // the path segment is shorter than the dash: draw to end of segment
449                                         curx+=dx; cury+=dy;
450                                         moveLine(g,curx,cury,draw);
451                                         dashleft-=segleft; segleft=0;
452                                 } else {
453                                         // draw whole dash, then loop
454                                         curx+=dashleft*xc; dx-=dashleft*xc;
455                                         cury+=dashleft*yc; dy-=dashleft*yc;
456                                         moveLine(g,curx,cury,draw);
457                                         segleft-=dashleft; dashleft=0;
458                                 }
459                         }
460                         return segments;
461                 }
462
463                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
464                         if (draw) { g.lineTo(x,y); }
465                                  else { g.moveTo(x,y); }
466                 }
467
468                 /** Draw decoration (arrows etc.) */
469                 
470                 private function lineDecoration(g:Graphics,s:ShapeStyle,segments:Array):void {
471                         var c:int=s.color ? s.color : 0;
472                         switch (s.line_style.toLowerCase()) {
473
474                                 case 'arrows':; case 'arrows-reversed':
475                                         var w:Number=s.width*1.5;  // width of arrow
476                                         var l:Number=s.width*2;    // length of arrow
477                                         g.lineStyle(1,c);
478                                         for each (var seg:Array in segments) {
479                                                 g.beginFill(c);
480                                                 // seg: {dashendx, dashendy, dx, dy, dashstartx, dashstarty, dashstartdx, dashstartdy} 
481                                                 // where dx is normalised x component of direction vector
482                                                 // note that a dash can go around a corner, so the info is not redundant
483                                                 
484                                                 if (s.line_style.toLowerCase() == "arrows-reversed") {
485                                 g.moveTo(seg[4]-l*seg[6], seg[5]-l*seg[7]); // note reversed arrow head
486                                 g.lineTo(seg[4]-w*seg[7], seg[5]+w*seg[6]);
487                                 g.lineTo(seg[4]+w*seg[7], seg[5]-w*seg[6]);
488                                                 } else {
489                                                         g.moveTo(seg[0]+l*seg[2], seg[1]+l*seg[3]);
490                                 g.lineTo(seg[0]-w*seg[3], seg[1]+w*seg[2]);
491                                 g.lineTo(seg[0]+w*seg[3], seg[1]-w*seg[2]);
492                             }
493                                                 g.endFill();
494                                         }
495                                         break;
496                 case 'triangle':
497                     w=s.width*10;   //triangle egde
498                     g.lineStyle(1,c);
499                     for each (seg in segments) {
500                         g.beginFill(c);
501                         var angle0:Number = -Math.atan2(seg[3], seg[2]) + Math.PI / 2; //0
502                         var angle1:Number = -Math.atan2(seg[3], seg[2]) - Math.PI/6;       //60
503                         g.moveTo(seg[0], seg[1]);//start 0,0
504                         g.lineTo(seg[0] - w * Math.sin(angle0), seg[1] - w * Math.cos(angle0));
505                         g.lineTo(seg[0] + w * Math.sin(angle1), seg[1] + w * Math.cos(angle1));
506                         g.endFill();
507                     }
508                     break;
509                                 }
510                 }
511                 
512                 /** Find point partway (0-1) along a path
513                   * @return (x,y,angle)
514                   * inspired by senocular's Path.as */
515                 
516                 private function pointAt(t:Number):Array {
517                         var way:Way=entity as Way;
518                         var totallen:Number = t*pathlength;
519                         var curlen:Number = 0;
520                         var dx:Number, dy:Number, seglen:Number;
521                         for (var i:int = 1; i < way.length; i++){
522                                 dx=paint.map.lon2coord(way.getNode(i).lon)-paint.map.lon2coord(way.getNode(i-1).lon);
523                                 dy=paint.map.latp2coord(way.getNode(i).latp)-paint.map.latp2coord(way.getNode(i-1).latp);
524                                 seglen=Math.sqrt(dx*dx+dy*dy);
525                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
526                                 return new Array(paint.map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
527                                                                  paint.map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
528                                                                  Math.atan2(dy,dx));
529                         }
530                         return new Array(0, 0, 0);
531                 }
532
533                 /** Draw name along path
534                  * based on code by Tom Carden
535                  * */
536                 
537                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
538
539                         // make a dummy textfield so we can measure its width
540                         var tf:TextField = new TextField();
541                         tf.defaultTextFormat = nameformat;
542                         tf.text = a;
543                         tf.width = tf.textWidth+4;
544                         tf.height = tf.textHeight+4;
545                         if (pathlength<tf.width) { return; }    // no room for text?
546
547                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
548                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
549
550                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
551                         var offsetSign:Number;  // -1 if we're starting at t2
552                         var tStart:Number;      // t1 or t2
553
554                         // make sure text doesn't run right->left or upside down
555                         if (p1[0] < p2[0] && 
556                                 p1[2] < Math.PI/2 &&
557                                 p1[2] > -Math.PI/2) {
558                                 angleOffset = 0; offsetSign = 1; tStart = t1;
559                         } else {
560                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
561                         } 
562
563                         // make a textfield for each char, centered on the line,
564                         // using getCharBoundaries to rotate it around its center point
565                         var chars:Array = a.split('');
566                         for (var i:int = 0; i < chars.length; i++) {
567                                 var rect:Rectangle = tf.getCharBoundaries(i);
568                                 if (rect) {
569                                         s.addChild(rotatedLetter(chars[i],
570                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
571                                                                                          rect.width, tf.height, angleOffset, textOffset));
572                                 }
573                         }
574                 }
575
576                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
577                         var tf:TextField = new TextField();
578             tf.mouseEnabled = false;
579             tf.mouseWheelEnabled = false;
580                         tf.defaultTextFormat = nameformat;
581                         tf.embedFonts = true;
582                         tf.text = char;
583                         tf.width = tf.textWidth+4;
584                         tf.height = tf.textHeight+4;
585
586                         var p:Array=pointAt(t);
587                         var matrix:Matrix = new Matrix();
588                         matrix.translate(-w/2, -h/2-o);
589                         // ** add (say) -4 to the height to move it up by 4px
590                         matrix.rotate(p[2]+a);
591                         matrix.translate(p[0], p[1]);
592                         tf.transform.matrix = matrix;
593                         return tf;
594                 }
595                 
596                 public function getNodeAt(x:Number, y:Number):Node {
597                         var way:Way=entity as Way;
598                         for (var i:uint = 0; i < way.length; i++) {
599                 var node:Node = way.getNode(i);
600                 var nodeX:Number = paint.map.lon2coord(node.lon);
601                 var nodeY:Number = paint.map.latp2coord(node.latp);
602                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
603                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
604                     return node;
605             }
606             return null;
607                 }
608
609                 // ------------------------------------------------------------------------------------------
610                 /* Interaction */
611         // TODO: can this be sped up? Hit testing for long ways (that go off the screen) seems to be very slow. */
612                 public function hitTest(x:Number, y:Number):Way {
613                         if (hitzone.hitTestPoint(x,y,true)) { return entity as Way; }
614                         return null;
615                 }
616         }
617 }