working (though incomplete) 900913;
[potlatch2.git] / net / systemeD / halcyon / WayUI.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.geom.Matrix;
5         import flash.geom.Point;
6         import flash.geom.Rectangle;
7         import flash.text.AntiAliasType;
8         import flash.text.GridFitType;
9         import flash.text.TextField;
10         import flash.text.TextFormat;
11         import flash.events.*;
12         import net.systemeD.halcyon.styleparser.*;
13     import net.systemeD.halcyon.connection.*;
14
15         public class WayUI {
16         private var way:Way;
17
18                 public var pathlength:Number;                           // length of path
19                 public var patharea:Number;                                     // area of path
20                 public var centroid_x:Number;                           // centroid
21                 public var centroid_y:Number;                           //  |
22                 public var layer:int=0;                                         // map layer
23                 public var map:Map;                                                     // reference to parent map
24                 public var sprites:Array=new Array();           // instances in display list
25                 private var stateClasses:Object = new Object();
26         private var hitzone:Sprite;
27         private var listenSprite:Sprite;
28
29                 public static const DEFAULT_TEXTFIELD_PARAMS:Object = {
30                         embedFonts: true,
31                         antiAliasType: AntiAliasType.ADVANCED,
32                         gridFitType: GridFitType.NONE
33                 };
34                 public var nameformat:TextFormat;
35
36
37                 public function WayUI(way:Way, map:Map) {
38                         this.way = way;
39                         this.map = map;
40             init();
41             way.addEventListener(Connection.TAG_CHANGE, wayTagChanged);
42             way.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
43             way.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
44             attachNodeListeners();
45                 }
46                 
47                 private function attachNodeListeners():void {
48             for (var i:uint = 0; i < way.length; i++ ) {
49                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
50             }
51                 }
52                 
53                 private function wayNodeAdded(event:WayNodeEvent):void {
54                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved);
55                     redraw();
56                 }
57                     
58                 private function wayNodeRemoved(event:WayNodeEvent):void {
59                     event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
60                     redraw();
61                 }
62                     
63         private function wayTagChanged(event:TagEvent):void {
64             redraw();
65         }
66         private function nodeMoved(event:NodeMovedEvent):void {
67             redraw();
68         }
69
70                 private function init():void {
71                         recalculate();
72                         redraw();
73                         // updateBbox(lon, lat);
74                         // ** various other stuff
75                 }
76
77                 // ------------------------------------------------------------------------------------------
78                 // Calculate length etc.
79                 // ** this could be made scale-independent - would speed up redraw
80                 
81                 public function recalculate():void {
82                         var lx:Number, ly:Number, sc:Number;
83                         var cx:Number=0, cy:Number=0;
84                         pathlength=0;
85                         patharea=0;
86                         
87                         lx = way.getNode(way.length-1).lon;
88                         ly = way.getNode(way.length-1).latp;
89                         for ( var i:uint = 0; i < way.length; i++ ) {
90                 var node:Node = way.getNode(i);
91                 var latp:Number = node.latp;
92                 var lon:Number  = node.lon;
93                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
94                                 sc = (lx*latp-lon*ly)*map.scalefactor;
95                                 cx += (lx+lon)*sc;
96                                 cy += (ly+latp)*sc;
97                                 patharea += sc;
98                                 lx=lon; ly=latp;
99                         }
100
101                         pathlength*=map.scalefactor;
102                         patharea/=2;
103                         if (patharea!=0 && way.isArea()) {
104                                 centroid_x=map.lon2coord(cx/patharea/6);
105                                 centroid_y=map.latp2coord(cy/patharea/6);
106                         } else if (pathlength>0) {
107                                 var c:Array=pointAt(0.5);
108                                 centroid_x=c[0];
109                                 centroid_y=c[1];
110                         }
111                 }
112
113                 // ------------------------------------------------------------------------------------------
114                 // Redraw
115
116                 public function redraw():void {
117             // Copy tags object, and add states
118             var tags:Object = way.getTagsCopy();
119             for (var stateKey:String in stateClasses) {
120                 tags[":"+stateKey] = stateKey;
121             }
122
123                         // Remove all currently existing sprites
124                         while (sprites.length>0) {
125                                 var d:DisplayObject=sprites.pop(); d.parent.removeChild(d);
126                         }
127
128                         // Which layer?
129                         layer=5;
130                         if ( tags['layer'] )
131                 layer=Math.min(Math.max(tags['layer']+5,-5),5)+5;
132
133                         // Iterate through each sublayer, drawing any styles on that layer
134                         var sl:StyleList=map.ruleset.getStyles(this.way, tags);
135                         var drawn:Boolean;
136                         for (var sublayer:uint=0; sublayer<11; sublayer++) {
137                                 if (sl.shapeStyles[sublayer]) {
138                                         var s:ShapeStyle=sl.shapeStyles[sublayer];
139                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
140                                         var x0:Number=map.lon2coord(way.getNode(0).lon);
141                                         var y0:Number=map.latp2coord(way.getNode(0).latp);
142
143                                         // Stroke
144                                         if (s.width)  {
145                                                 stroke=new Shape(); addToLayer(stroke,2,sublayer);
146                                                 stroke.graphics.moveTo(x0,y0);
147                                                 s.applyStrokeStyle(stroke.graphics);
148                                                 if (s.dashes && s.dashes.length>0) { dashedLine(stroke.graphics,s.dashes); }
149                                                                                                           else { solidLine(stroke.graphics); }
150                                                 drawn=true;
151                                         }
152
153                                         // Fill
154                                         if (s.fill_color || s.fill_image) {
155                                                 fill=new Shape(); addToLayer(fill,0);
156                                                 fill.graphics.moveTo(x0,y0);
157                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
158                                                                          else { s.applyFill(fill.graphics); }
159                                                 solidLine(fill.graphics);
160                                                 fill.graphics.endFill();
161                                                 drawn=true;
162                                         }
163
164                                         // Casing
165                                         if (s.casing_width) { 
166                                                 casing=new Shape(); addToLayer(casing,1);
167                                                 casing.graphics.moveTo(x0,y0);
168                                                 s.applyCasingStyle(casing.graphics);
169                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
170                                                                                                                                         else { solidLine(casing.graphics); }
171                                                 drawn=true;
172                                         }
173                                 }
174                                 
175                                 if (sl.textStyles[sublayer]) {
176                                         var t:TextStyle=sl.textStyles[sublayer];
177                                         roadname=new Sprite(); addToLayer(roadname,3);
178                                         nameformat = t.getTextFormat();
179                                         var a:String=tags[t.text];
180                                         if (a) {
181                                                 if (t.font_caps) { a=a.toUpperCase(); }
182                                                 if (t.text_center && centroid_x) {
183                                                         t.writeNameLabel(roadname,tags[t.text],centroid_x,centroid_y);
184                                                 } else {
185                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
186                                                 }
187                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
188                                         }
189                                 }
190                                 
191                                 // ** ShieldStyle to do
192                         }
193
194                         // No styles, so add a thin trace
195             if (!drawn && map.showall) {
196                 var def:Sprite = new Sprite();
197                 def.graphics.lineStyle(0.5, 0x808080, 1, false, "normal");
198                 solidLine(def.graphics);
199                 addToLayer(def, 2);
200                                 drawn=true;
201             }
202             
203             if ( stateClasses["showNodes"] != null ) {
204                 var nodes:Sprite = new Sprite();
205                 drawNodes(nodes.graphics);
206                 addToLayer(nodes, 3);
207             }
208
209                         if (!drawn) { return; }
210                         
211             // create a generic "way" hitzone sprite
212             hitzone = new Sprite();
213             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
214             solidLine(hitzone.graphics);
215             addToLayer(hitzone, 4);
216             hitzone.visible = false;
217
218             if ( listenSprite == null ) {
219                 listenSprite = new Sprite();
220                 listenSprite.addEventListener(MouseEvent.CLICK, mouseEvent);
221                 listenSprite.addEventListener(MouseEvent.DOUBLE_CLICK, mouseEvent);
222                 listenSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseEvent);
223                 listenSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseEvent);
224                 listenSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseEvent);
225                 listenSprite.addEventListener(MouseEvent.MOUSE_UP, mouseEvent);
226                 listenSprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseEvent);
227             }
228             listenSprite.hitArea = hitzone;
229             addToLayer(listenSprite, 4);
230             listenSprite.buttonMode = true;
231             listenSprite.mouseEnabled = true;
232
233                 }
234                 
235                 // ------------------------------------------------------------------------------------------
236                 // Drawing support functions
237
238                 private function drawNodes(g:Graphics):void {
239             g.lineStyle(1, 0xff0000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
240                         for (var i:uint = 0; i < way.length; i++) {
241                 var node:Node = way.getNode(i);
242                 var x:Number = map.lon2coord(node.lon);
243                 var y:Number = map.latp2coord(node.latp);
244                 g.moveTo(x-2, y-2);
245                 g.lineTo(x+2, y-2);
246                 g.lineTo(x+2, y+2);
247                 g.lineTo(x-2, y+2);
248                 g.lineTo(x-2, y-2);
249                         }
250                 }
251
252                 // Draw solid polyline
253                 
254                 public function solidLine(g:Graphics):void {
255             var node:Node = way.getNode(0);
256                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
257                         for (var i:uint = 1; i < way.length; i++) {
258                 node = way.getNode(i);
259                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
260                         }
261                 }
262
263                 // Draw dashed polyline
264                 
265                 private function dashedLine(g:Graphics,dashes:Array):void {
266                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
267                         var a:Number, xc:Number, yc:Number;
268                         var curx:Number, cury:Number;
269                         var dx:Number, dy:Number, segleft:Number=0;
270                         var i:int=0;
271
272             var node:Node = way.getNode(0);
273             var nextNode:Node = way.getNode(0);
274                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
275                         while (i < way.length-1 || segleft>0) {
276                                 if (dashleft<=0) {      // should be ==0
277                                         if (dc.length==0) { dc=dashes.slice(0); }
278                                         dashleft=dc.shift();
279                                         draw=!draw;
280                                 }
281                                 if (segleft<=0) {       // should be ==0
282                     node = way.getNode(i);
283                     nextNode = way.getNode(i+1);
284                                         curx=map.lon2coord(node.lon);
285                     dx=map.lon2coord(nextNode.lon)-curx;
286                                         cury=map.latp2coord(node.latp);
287                     dy=map.latp2coord(nextNode.latp)-cury;
288                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
289                                         segleft=Math.sqrt(dx*dx+dy*dy);
290                                         i++;
291                                 }
292
293                                 if (segleft<=dashleft) {
294                                         // the path segment is shorter than the dash
295                                         curx+=dx; cury+=dy;
296                                         moveLine(g,curx,cury,draw);
297                                         dashleft-=segleft; segleft=0;
298                                 } else {
299                                         // the path segment is longer than the dash
300                                         curx+=dashleft*xc; dx-=dashleft*xc;
301                                         cury+=dashleft*yc; dy-=dashleft*yc;
302                                         moveLine(g,curx,cury,draw);
303                                         segleft-=dashleft; dashleft=0;
304                                 }
305                         }
306                 }
307
308                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
309                         if (draw) { g.lineTo(x,y); }
310                                  else { g.moveTo(x,y); }
311                 }
312
313                 
314                 // Find point partway (0-1) along a path
315                 // returns (x,y,angle)
316                 // inspired by senocular's Path.as
317                 
318                 private function pointAt(t:Number):Array {
319                         var totallen:Number = t*pathlength;
320                         var curlen:Number = 0;
321                         var dx:Number, dy:Number, seglen:Number;
322                         for (var i:int = 1; i < way.length; i++){
323                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
324                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
325                                 seglen=Math.sqrt(dx*dx+dy*dy);
326                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
327                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
328                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
329                                                                  Math.atan2(dy,dx));
330                         }
331                         return new Array(0, 0, 0);
332                 }
333
334                 // Draw name along path
335                 // based on code by Tom Carden
336                 // ** needs styling
337                 
338                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
339
340                         // make a dummy textfield so we can measure its width
341                         var tf:TextField = new TextField();
342                         tf.defaultTextFormat = nameformat;
343                         tf.text = a;
344                         tf.width = tf.textWidth+4;
345                         tf.height = tf.textHeight+4;
346                         if (pathlength<tf.width) { return; }    // no room for text?
347
348                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
349                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
350
351                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
352                         var offsetSign:Number;  // -1 if we're starting at t2
353                         var tStart:Number;      // t1 or t2
354
355                         // make sure text doesn't run right->left or upside down
356                         if (p1[0] < p2[0] && 
357                                 p1[2] < Math.PI/2 &&
358                                 p1[2] > -Math.PI/2) {
359                                 angleOffset = 0; offsetSign = 1; tStart = t1;
360                         } else {
361                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
362                         } 
363
364                         // make a textfield for each char, centered on the line,
365                         // using getCharBoundaries to rotate it around its center point
366                         var chars:Array = a.split('');
367                         for (var i:int = 0; i < chars.length; i++) {
368                                 var rect:Rectangle = tf.getCharBoundaries(i);
369                                 if (rect) {
370                                         s.addChild(rotatedLetter(chars[i],
371                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
372                                                                                          rect.width, tf.height, angleOffset, textOffset));
373                                 }
374                         }
375                 }
376
377                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
378                         var tf:TextField = new TextField();
379             tf.mouseEnabled = false;
380             tf.mouseWheelEnabled = false;
381                         tf.defaultTextFormat = nameformat;
382                         tf.embedFonts = true;
383                         tf.text = char;
384                         tf.width = tf.textWidth+4;
385                         tf.height = tf.textHeight+4;
386
387                         var p:Array=pointAt(t);
388                         var matrix:Matrix = new Matrix();
389                         matrix.translate(-w/2, -h/2-o);
390                         // ** add (say) -4 to the height to move it up by 4px
391                         matrix.rotate(p[2]+a);
392                         matrix.translate(p[0], p[1]);
393                         tf.transform.matrix = matrix;
394                         return tf;
395                 }
396                 
397                 // Add object (stroke/fill/roadname) to layer sprite
398                 
399                 private function addToLayer(s:DisplayObject,t:uint,sublayer:int=-1):void {
400                         var l:DisplayObject=Map(map).getChildAt(map.WAYSPRITE+layer);
401                         var o:DisplayObject=Sprite(l).getChildAt(t);
402                         if (sublayer!=-1) { o=Sprite(o).getChildAt(sublayer); }
403                         Sprite(o).addChild(s);
404                         sprites.push(s);
405             if ( s is Sprite ) {
406                 Sprite(s).mouseEnabled = false;
407                 Sprite(s).mouseChildren = false;
408             }
409                 }
410
411                 public function getNodeAt(x:Number, y:Number):Node {
412                         for (var i:uint = 0; i < way.length; i++) {
413                 var node:Node = way.getNode(i);
414                 var nodeX:Number = map.lon2coord(node.lon);
415                 var nodeY:Number = map.latp2coord(node.latp);
416                 if ( nodeX >= x-3 && nodeX <= x+3 &&
417                      nodeY >= y-3 && nodeY <= y+3 )
418                     return node;
419             }
420             return null;
421                 }
422
423         private function mouseEvent(event:MouseEvent):void {
424             var node:Node = getNodeAt(event.localX, event.localY);
425             if ( node == null )
426                 map.entityMouseEvent(event, way);
427             else
428                 map.entityMouseEvent(event, node);
429         }
430
431         public function setHighlight(stateType:String, isOn:Boolean):void {
432             if ( isOn && stateClasses[stateType] == null ) {
433                 stateClasses[stateType] = true;
434                 redraw();
435             } else if ( !isOn && stateClasses[stateType] != null ) {
436                 delete stateClasses[stateType];
437                 redraw();
438             }
439         }
440         }
441 }