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