Merge remote-tracking branch 'systemed/filebank' into filebank
[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.FileBank;
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                         patharea=Math.abs(patharea);
222                 }
223
224                 // ------------------------------------------------------------------------------------------
225         
226                 /** Go through the complex process of drawing this way, including applying styles, casings, fills, fonts... */
227                 override public function doRedraw():Boolean {
228                         interactive=false;
229                         removeSprites();
230                         if (Way(entity).length==0) { return false; }
231                         if (!paint.ready) { return false; }
232
233             // Copy tags object, and add states
234             var tags:Object = entity.getTagsCopy();
235             setStateClass('area', Way(entity).isArea());
236             setStateClass('background', paint.isBackground);
237             setStateClass('tiger', (entity.isUneditedTiger() && Globals.vars.highlightTiger));
238             tags=applyStateClasses(tags);
239                         if (entity.status) { tags['_status']=entity.status; }
240
241                         // Keep track of maximum stroke width for hitzone
242                         var maxwidth:Number=4;
243
244                         // Create styleList if not already drawn
245                         if (!styleList || !styleList.isValidAt(paint.map.scale)) {
246                                 styleList=paint.ruleset.getStyles(entity, tags, paint.map.scale);
247                         }
248
249                         // Which layer?
250                         layer=styleList.layerOverride();
251                         if (isNaN(layer)) {
252                                 layer=0;
253                                 if (tags['layer']) { layer=Math.min(Math.max(tags['layer'],paint.minlayer),paint.maxlayer); }
254                         }
255
256                         // Do we have to draw all nodes in the way?
257                         var hasFills:Boolean=styleList.hasFills();
258                         if (isNaN(drawOnly) || hasFills) {
259                                 indexStart=0; indexEnd=Way(entity).length; 
260                         } else {
261                                 indexStart=Math.max(0,drawOnly-1);
262                                 indexEnd  =Math.min(drawOnly+2,Way(entity).length);
263                         }
264
265                         // Iterate through each subpart, drawing any styles on that layer
266                         var drawn:Boolean;
267                         var multis:Array=entity.findParentRelationsOfType('multipolygon','outer');
268                         var inners:Array=[];
269                         for each (var m:Relation in multis) {
270                                 inners=inners.concat(m.findMembersByRole('inner',Way));
271                         }
272
273                         for each (var subpart:String in styleList.subparts) {
274                                 if (styleList.shapeStyles[subpart]) {
275                                         var s:ShapeStyle=styleList.shapeStyles[subpart];
276                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
277                                         var x0:Number=paint.map.lon2coord(Way(entity).getNode(0).lon);
278                                         var y0:Number=paint.map.latp2coord(Way(entity).getNode(0).latp);
279                                         interactive||=s.interactive;
280
281                                         // Stroke
282                                         if (s.width)  {
283                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,s.sublayer);
284                                                 stroke.graphics.moveTo(x0,y0);
285                                                 s.applyStrokeStyle(stroke.graphics);
286                                                 if (s.dashes && s.dashes.length>0) {
287                                                         var segments:Array=dashedLine(stroke.graphics,s.dashes); 
288                                                         if (s.line_style) { lineDecoration(stroke.graphics,s,segments); }
289                                                 } else { solidLines(stroke.graphics,inners); }
290                                                 drawn=true;
291                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.width); }
292                                         }
293
294                                         // Fill
295                                         if ((!isNaN(s.fill_color) || s.fill_image) && entity.findParentRelationsOfType('multipolygon','inner').length==0 && isNaN(drawExcept)) {
296                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE,s.sublayer);
297                                                 fill.graphics.moveTo(x0,y0);
298                                                 if (s.fill_image) {
299                                                         fill.graphics.beginBitmapFill(FileBank.getInstance().getAsBitmapData(s.fill_image));
300                                                 } else {
301                                                         s.applyFill(fill.graphics);
302                                                 }
303                                                 solidLines(fill.graphics,inners);
304                                                 fill.graphics.endFill();
305                                                 drawn=true;
306                                         }
307
308                                         // Casing
309                                         if (s.casing_width) { 
310                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
311                                                 casing.graphics.moveTo(x0,y0);
312                                                 s.applyCasingStyle(casing.graphics);
313                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
314                                                                                                                                         else { solidLines(casing.graphics,inners); }
315                                                 drawn=true;
316                                                 if (s.interactive) { maxwidth=Math.max(maxwidth,s.casing_width); }
317                                         }
318                                 }
319                                 
320                                 if (styleList.textStyles[subpart] && isNaN(drawExcept)) {
321                                         var t:TextStyle=styleList.textStyles[subpart];
322                                         interactive||=t.interactive;
323                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
324                                         nameformat = t.getTextFormat();
325                                         var a:String=tags[t.text];
326                                         if (a) {
327                                                 if (t.font_caps) { a=a.toUpperCase(); }
328                                                 if (t.text_center && centroid_x) {
329                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
330                                                 } else {
331                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
332                                                 }
333                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
334                                         }
335                                 }
336                                 
337                                 // ** ShieldStyle to do
338                         }
339
340                         // Draw icons
341                         var r:Number;
342                         var nodeSelected:int=stateClasses["nodeSelected"];
343                         for (var i:uint = indexStart; i < indexEnd; i++) {
344                 var node:Node = Way(entity).getNode(i);
345                                 var nodeStateClasses:Object={};
346 //                              if (i==0) { nodetags['_heading']= heading[i]; }
347 //                                   else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
348                                 // ** FIXME - heading isn't currently applied
349                                 nodeStateClasses['junction']=(node.numParentWays>1);
350                                 paint.createNodeUI(node,false,r,layer,nodeStateClasses);
351                         }
352                         if (!drawn) { return false; } // If not visible, no hitzone.
353                         
354             // create a generic "way" hitzone sprite
355                         if (interactive && drawn) {
356                     hitzone = new Sprite();
357                     hitzone.graphics.lineStyle(maxwidth, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
358                     solidLines(hitzone.graphics,[]);
359                     hitzone.visible = false;
360                                 setListenSprite();
361                         }
362
363                         return true;
364                 }
365                 
366                 // ------------------------------------------------------------------------------------------
367                 // Drawing support functions
368
369                 /** Draw solid polyline */
370                 
371                 public function solidLines(g:Graphics,inners:Array):void {
372                         solidLine(g);
373                         for each (var w:Way in inners) { solidLineOtherWay(g,w); }
374                 }
375
376                 private function solidLine(g:Graphics):void {
377                         if (indexEnd==0) { return; }
378                         var way:Way=entity as Way;
379                         
380             var node:Node = way.getNode(indexStart);
381                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
382                         for (var i:uint = indexStart+1; i < indexEnd; i++) {
383                 node = way.getNode(i);
384                                 if (!isNaN(drawExcept) && (i-1==drawExcept || i==drawExcept)) {
385                                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
386                                 } else {
387                                         g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
388                                 }
389                         }
390                 }
391
392                 private function solidLineOtherWay(g:Graphics,way:Way):void {
393                         if (way.length==0) { return; }
394                         
395                         var node:Node = way.getNode(0);
396                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
397                         for (var i:uint = 1; i < way.length; i++) {
398                                 node = way.getNode(i);
399                                 g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
400                         }
401                 }
402
403                 /** Draw dashed polyline */
404                 
405                 private function dashedLine(g:Graphics,dashes:Array):Array {
406                         var way:Way=entity as Way;
407                         var segments:Array=[]; // array of dash locations being constructed for later arrow drawing
408                         var draw:Boolean=false; // are we drawing or marking empty space till next dash
409                         var dashleft:Number=0; // how much of current dash is left
410                         var dc:Array=new Array(); // copy of dashes, gets consumed then replaced
411                         var xc:Number, yc:Number; // normalised vector coordinates of direction to next node 
412                         var curx:Number, cury:Number; // current drawing location
413                         var dx:Number, dy:Number, segleft:Number=0; // distance remaining until next node
414                         var i:int=indexStart; // node index
415                         var dashstartx:int, dashstarty:int; // needed to draw reverse arrows
416                         var dashstartxc: Number, dashstartyc: Number;
417
418             var node:Node = way.getNode(i);
419             var nextNode:Node = way.getNode(i);
420                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
421                         while (i < indexEnd-1 || segleft>0) {
422                                 if (dashleft<=0) {      // should be ==0
423                                     // finished drawing current dash, pop another one off the pattern, looping if necessary
424                                         if (dc.length==0) { dc=dashes.slice(0); }
425                                         dashleft=dc.shift();
426                                         if (draw) { segments.push([curx,cury,xc,yc, dashstartx, dashstarty, dashstartxc, dashstartyc]); }
427                                         draw=!draw;
428                                         // record start of each dash, if we need to draw a reverse arrow head later
429                                         dashstartx = curx; dashstarty = cury;
430                                         dashstartxc = xc; dashstartyc = yc;
431                                 }
432                                 if (i==drawExcept || i==drawExcept+1) { draw=false; }
433                                 if (segleft<=0) {       // should be ==0
434                     // arrived at target node. calculate direction to next node.
435                     node = way.getNode(i);
436                     nextNode = way.getNode(i+1);
437                                         curx=paint.map.lon2coord(node.lon);
438                     dx=paint.map.lon2coord(nextNode.lon)-curx;
439                                         cury=paint.map.latp2coord(node.latp);
440                     dy=paint.map.latp2coord(nextNode.latp)-cury;
441                                         segleft=Math.sqrt(dx*dx+dy*dy);
442                                         xc = dx/segleft;
443                                         yc = dy/segleft;
444                                         if (i==0) {
445                         // record start location of very first dash
446                         dashstartx = curx; dashstarty = cury;
447                         dashstartxc = xc; dashstartyc = yc;
448                                         }
449                                         i++;
450                                 }
451
452                                 if (segleft<=dashleft) {
453                                         // the path segment is shorter than the dash: draw to end of segment
454                                         curx+=dx; cury+=dy;
455                                         moveLine(g,curx,cury,draw);
456                                         dashleft-=segleft; segleft=0;
457                                 } else {
458                                         // draw whole dash, then loop
459                                         curx+=dashleft*xc; dx-=dashleft*xc;
460                                         cury+=dashleft*yc; dy-=dashleft*yc;
461                                         moveLine(g,curx,cury,draw);
462                                         segleft-=dashleft; dashleft=0;
463                                 }
464                         }
465                         return segments;
466                 }
467
468                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
469                         if (draw) { g.lineTo(x,y); }
470                                  else { g.moveTo(x,y); }
471                 }
472
473                 /** Draw decoration (arrows etc.) */
474                 
475                 private function lineDecoration(g:Graphics,s:ShapeStyle,segments:Array):void {
476                         var c:int=s.color ? s.color : 0;
477                         switch (s.line_style.toLowerCase()) {
478
479                                 case 'arrows':; case 'arrows-reversed':
480                                         var w:Number=s.width*1.5;  // width of arrow
481                                         var l:Number=s.width*2;    // length of arrow
482                                         g.lineStyle(1,c);
483                                         for each (var seg:Array in segments) {
484                                                 g.beginFill(c);
485                                                 // seg: {dashendx, dashendy, dx, dy, dashstartx, dashstarty, dashstartdx, dashstartdy} 
486                                                 // where dx is normalised x component of direction vector
487                                                 // note that a dash can go around a corner, so the info is not redundant
488                                                 
489                                                 if (s.line_style.toLowerCase() == "arrows-reversed") {
490                                 g.moveTo(seg[4]-l*seg[6], seg[5]-l*seg[7]); // note reversed arrow head
491                                 g.lineTo(seg[4]-w*seg[7], seg[5]+w*seg[6]);
492                                 g.lineTo(seg[4]+w*seg[7], seg[5]-w*seg[6]);
493                                                 } else {
494                                                         g.moveTo(seg[0]+l*seg[2], seg[1]+l*seg[3]);
495                                 g.lineTo(seg[0]-w*seg[3], seg[1]+w*seg[2]);
496                                 g.lineTo(seg[0]+w*seg[3], seg[1]-w*seg[2]);
497                             }
498                                                 g.endFill();
499                                         }
500                                         break;
501                 case 'triangle':
502                     w=s.width*10;   //triangle egde
503                     g.lineStyle(1,c);
504                     for each (seg in segments) {
505                         g.beginFill(c);
506                         var angle0:Number = -Math.atan2(seg[3], seg[2]) + Math.PI / 2; //0
507                         var angle1:Number = -Math.atan2(seg[3], seg[2]) - Math.PI/6;       //60
508                         g.moveTo(seg[0], seg[1]);//start 0,0
509                         g.lineTo(seg[0] - w * Math.sin(angle0), seg[1] - w * Math.cos(angle0));
510                         g.lineTo(seg[0] + w * Math.sin(angle1), seg[1] + w * Math.cos(angle1));
511                         g.endFill();
512                     }
513                     break;
514                                 }
515                 }
516                 
517                 /** Find point partway (0-1) along a path
518                   * @return (x,y,angle)
519                   * inspired by senocular's Path.as */
520                 
521                 private function pointAt(t:Number):Array {
522                         var way:Way=entity as Way;
523                         var totallen:Number = t*pathlength;
524                         var curlen:Number = 0;
525                         var dx:Number, dy:Number, seglen:Number;
526                         for (var i:int = 1; i < way.length; i++){
527                                 dx=paint.map.lon2coord(way.getNode(i).lon)-paint.map.lon2coord(way.getNode(i-1).lon);
528                                 dy=paint.map.latp2coord(way.getNode(i).latp)-paint.map.latp2coord(way.getNode(i-1).latp);
529                                 seglen=Math.sqrt(dx*dx+dy*dy);
530                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
531                                 return new Array(paint.map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
532                                                                  paint.map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
533                                                                  Math.atan2(dy,dx));
534                         }
535                         return new Array(0, 0, 0);
536                 }
537
538                 /** Draw name along path
539                  * based on code by Tom Carden
540                  * */
541                 
542                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
543
544                         // make a dummy textfield so we can measure its width
545                         var tf:TextField = new TextField();
546                         tf.defaultTextFormat = nameformat;
547                         tf.text = a;
548                         tf.width = tf.textWidth+4;
549                         tf.height = tf.textHeight+4;
550                         if (pathlength<tf.width) { return; }    // no room for text?
551
552                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
553                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
554
555                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
556                         var offsetSign:Number;  // -1 if we're starting at t2
557                         var tStart:Number;      // t1 or t2
558
559                         // make sure text doesn't run right->left or upside down
560                         if (p1[0] < p2[0] && 
561                                 p1[2] < Math.PI/2 &&
562                                 p1[2] > -Math.PI/2) {
563                                 angleOffset = 0; offsetSign = 1; tStart = t1;
564                         } else {
565                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
566                         } 
567
568                         // make a textfield for each char, centered on the line,
569                         // using getCharBoundaries to rotate it around its center point
570                         var chars:Array = a.split('');
571                         for (var i:int = 0; i < chars.length; i++) {
572                                 var rect:Rectangle = tf.getCharBoundaries(i);
573                                 if (rect) {
574                                         s.addChild(rotatedLetter(chars[i],
575                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
576                                                                                          rect.width, tf.height, angleOffset, textOffset));
577                                 }
578                         }
579                 }
580
581                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
582                         var tf:TextField = new TextField();
583             tf.mouseEnabled = false;
584             tf.mouseWheelEnabled = false;
585                         tf.defaultTextFormat = nameformat;
586                         tf.embedFonts = true;
587                         tf.text = char;
588                         tf.width = tf.textWidth+4;
589                         tf.height = tf.textHeight+4;
590
591                         var p:Array=pointAt(t);
592                         var matrix:Matrix = new Matrix();
593                         matrix.translate(-w/2, -h/2-o);
594                         // ** add (say) -4 to the height to move it up by 4px
595                         matrix.rotate(p[2]+a);
596                         matrix.translate(p[0], p[1]);
597                         tf.transform.matrix = matrix;
598                         return tf;
599                 }
600                 
601                 public function getNodeAt(x:Number, y:Number):Node {
602                         var way:Way=entity as Way;
603                         for (var i:uint = 0; i < way.length; i++) {
604                 var node:Node = way.getNode(i);
605                 var nodeX:Number = paint.map.lon2coord(node.lon);
606                 var nodeY:Number = paint.map.latp2coord(node.latp);
607                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
608                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
609                     return node;
610             }
611             return null;
612                 }
613
614                 // ------------------------------------------------------------------------------------------
615                 /* Interaction */
616         // TODO: can this be sped up? Hit testing for long ways (that go off the screen) seems to be very slow. */
617                 public function hitTest(x:Number, y:Number):Way {
618                         if (hitzone && hitzone.hitTestPoint(x,y,true)) { return entity as Way; }
619                         return null;
620                 }
621         }
622 }