add node drawing + dragging & highlight selected way using stylesheet
[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             for (var i:uint = 0; i < way.length; i++ ) {
43                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
44             }
45                 }
46                 
47         private function wayTagChanged(event:TagEvent):void {
48             redraw();
49         }
50         private function nodeMoved(event:NodeMovedEvent):void {
51             redraw();
52         }
53
54                 private function init():void {
55                         recalculate();
56                         redraw();
57                         // updateBbox(lon, lat);
58                         // ** various other stuff
59                 }
60
61                 // ------------------------------------------------------------------------------------------
62                 // Calculate length etc.
63                 // ** this could be made scale-independent - would speed up redraw
64                 
65                 public function recalculate():void {
66                         var lx:Number, ly:Number, sc:Number;
67                         var cx:Number=0, cy:Number=0;
68                         pathlength=0;
69                         patharea=0;
70                         
71                         lx = way.getNode(way.length-1).lon;
72                         ly = way.getNode(way.length-1).latp;
73                         for ( var i:uint = 0; i < way.length; i++ ) {
74                 var node:Node = way.getNode(i);
75                 var latp:Number = node.latp;
76                 var lon:Number  = node.lon;
77                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
78                                 sc = (lx*latp-lon*ly)*map.scalefactor;
79                                 cx += (lx+lon)*sc;
80                                 cy += (ly+latp)*sc;
81                                 patharea += sc;
82                                 lx=lon; ly=latp;
83                         }
84
85                         pathlength*=map.scalefactor;
86                         patharea/=2;
87                         if (patharea!=0 && way.isArea()) {
88                                 centroid_x=map.lon2coord(cx/patharea/6);
89                                 centroid_y=map.latp2coord(cy/patharea/6);
90                         } else if (pathlength>0) {
91                                 var c:Array=pointAt(0.5);
92                                 centroid_x=c[0];
93                                 centroid_y=c[1];
94                         }
95                 }
96
97                 // ------------------------------------------------------------------------------------------
98                 // Redraw
99
100                 public function redraw():void {
101             var tags:Object = way.getTagsCopy();
102             // add states to the tags -- we should probably treat these
103             // more explicitly, but if Richard is still playing with styles
104             // this will work for now
105             for ( var stateKey:String in stateClasses ) {
106                 tags["__state__"+stateKey] = stateKey;
107             }
108
109                         // remove all currently existing sprites
110                         while (sprites.length>0) {
111                                 var d:DisplayObject=sprites.pop(); d.parent.removeChild(d);
112                         }
113
114                         // which layer?
115                         layer=5;
116                         if ( tags['layer'] )
117                 layer=Math.min(Math.max(tags['layer']+5,-5),5)+5;
118
119                         // set style
120                         var styles:Array=map.ruleset.getStyles(false, tags, map.scale);
121                         for each (var s:* in styles) {
122
123                                 if (s is ShapeStyle) {
124                                         var stroke:Shape, fill:Shape, roadname:Sprite, f:Graphics, g:Graphics;
125                                         var doStroke:Boolean=false, doDashed:Boolean=false;
126                                         var doFill:Boolean=false, fill_colour:uint, fill_opacity:Number;
127                                         var doCasing:Boolean=false, doDashedCasing:Boolean=false;
128
129                                         // Set stroke style
130                                         if (s.isStroked)  {
131                                                 stroke=new Shape(); addToLayer(stroke,1,s.sublayer); g=stroke.graphics;
132                                 g.moveTo(map.lon2coord(way.getNode(0).lon), map.latp2coord(way.getNode(0).latp));
133                                                 g.lineStyle(s.stroke_width, s.stroke_colour, s.stroke_opacity/100,
134                                                                         false, "normal", s.stroke_linecap, s.stroke_linejoin);
135                                         }
136
137                                         // Set fill and casing style
138                                         if (s.isFilled || s.isCased) {
139                                                 fill=new Shape(); addToLayer(fill,0); f=fill.graphics;
140                                 f.moveTo(map.lon2coord(way.getNode(0).lon), map.latp2coord(way.getNode(0).latp));
141                                                 if (s.isCased)  { f.lineStyle(s.casing_width, s.casing_colour, s.casing_opacity/100,
142                                                                                   false, "normal", s.stroke_linecap, s.stroke_linejoin); }
143                                                 if (s.isFilled) { f.beginFill(s.fill_colour,s.fill_opacity/100); }
144                                         }
145
146                                         // Draw stroke
147                                         if (s.stroke_dashArray.length>0) { dashedLine(g,s.stroke_dashArray); }
148                                                            else if (s.isStroked) { solidLine(g); }
149                         
150                                         // Draw fill and casing
151                                         if (s.casing_dashArray.length>0) { dashedLine(f,s.casing_dashArray); f.lineStyle(); }
152                                         if (s.isFilled)                                  { f.beginFill(s.fill_colour,s.fill_opacity/100); 
153                                                                                                            solidLine(f); f.endFill(); }
154                                         else if (s.isCased && s.casing_dashArray.length==0) { solidLine(f); }
155
156
157                                 } else if (s is TextStyle && s.tag && tags[s.tag]) {
158                                         roadname=new Sprite(); addToLayer(roadname,2);
159                                         nameformat = s.getTextFormat();
160                                         var a:String=tags[s.tag]; if (s.font_caps) { a=a.toUpperCase(); }
161                                         if (s.isLine) {
162                                                 writeNameOnPath(roadname,a,s.text_offset ? s.text_offset : 0);
163                                                 if (s.pullout_radius>0) { roadname.filters=s.getPulloutFilter(); }
164                                         } else if (centroid_x) {
165                                                 s.writeNameLabel(roadname,tags[s.tag],centroid_x,centroid_y);
166                                         }
167
168
169                                 } else if (s is ShieldStyle) {
170                                         // ** to do
171                                 }
172                         }
173
174             if ( styles.length == 0 ) {
175                 // there's no styles... so add a thin trace
176                 var def:Sprite = new Sprite();
177                 def.graphics.lineStyle(0.5, 0x808080, 1, false, "normal");
178                 solidLine(def.graphics);
179                 addToLayer(def, 1);
180             }
181             
182             if ( stateClasses["showNodes"] != null ) {
183                 var nodes:Sprite = new Sprite();
184                 drawNodes(nodes.graphics);
185                 addToLayer(nodes, 2);
186             }
187
188             // create a generic "way" hitzone sprite
189             hitzone = new Sprite();
190             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
191             solidLine(hitzone.graphics);
192             addToLayer(hitzone, 3);
193             hitzone.visible = false;
194
195             if ( listenSprite == null ) {
196                 listenSprite = new Sprite();
197                 listenSprite.addEventListener(MouseEvent.CLICK, mouseEvent);
198                 listenSprite.addEventListener(MouseEvent.DOUBLE_CLICK, mouseEvent);
199                 listenSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseEvent);
200                 listenSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseEvent);
201                 listenSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseEvent);
202                 listenSprite.addEventListener(MouseEvent.MOUSE_UP, mouseEvent);
203                 listenSprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseEvent);
204             }
205             listenSprite.hitArea = hitzone;
206             addToLayer(listenSprite, 3);
207             listenSprite.buttonMode = true;
208             listenSprite.mouseEnabled = true;
209
210                 }
211                 
212                 // ------------------------------------------------------------------------------------------
213                 // Drawing support functions
214
215                 private function drawNodes(g:Graphics):void {
216             g.lineStyle(1, 0xff0000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
217                         for (var i:uint = 0; i < way.length; i++) {
218                 var node:Node = way.getNode(i);
219                 var x:Number = map.lon2coord(node.lon);
220                 var y:Number = map.latp2coord(node.latp);
221                 g.moveTo(x-2, y-2);
222                 g.lineTo(x+2, y-2);
223                 g.lineTo(x+2, y+2);
224                 g.lineTo(x-2, y+2);
225                 g.lineTo(x-2, y-2);
226                         }
227                 }
228
229                 // Draw solid polyline
230                 
231                 private function solidLine(g:Graphics):void {
232             var node:Node = way.getNode(0);
233                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
234                         for (var i:uint = 1; i < way.length; i++) {
235                 node = way.getNode(i);
236                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
237                         }
238                 }
239
240                 // Draw dashed polyline
241                 
242                 private function dashedLine(g:Graphics,dashes:Array):void {
243                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
244                         var a:Number, xc:Number, yc:Number;
245                         var curx:Number, cury:Number;
246                         var dx:Number, dy:Number, segleft:Number=0;
247                         var i:int=0;
248
249             var node:Node = way.getNode(0);
250             var nextNode:Node = way.getNode(0);
251                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
252                         while (i < way.length-1 || segleft>0) {
253                                 if (dashleft<=0) {      // should be ==0
254                                         if (dc.length==0) { dc=dashes.slice(0); }
255                                         dashleft=dc.shift();
256                                         draw=!draw;
257                                 }
258                                 if (segleft<=0) {       // should be ==0
259                     node = way.getNode(i);
260                     nextNode = way.getNode(i+1);
261                                         curx=map.lon2coord(node.lon);
262                     dx=map.lon2coord(nextNode.lon)-curx;
263                                         cury=map.latp2coord(node.latp);
264                     dy=map.latp2coord(nextNode.latp)-cury;
265                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
266                                         segleft=Math.sqrt(dx*dx+dy*dy);
267                                         i++;
268                                 }
269
270                                 if (segleft<=dashleft) {
271                                         // the path segment is shorter than the dash
272                                         curx+=dx; cury+=dy;
273                                         moveLine(g,curx,cury,draw);
274                                         dashleft-=segleft; segleft=0;
275                                 } else {
276                                         // the path segment is longer than the dash
277                                         curx+=dashleft*xc; dx-=dashleft*xc;
278                                         cury+=dashleft*yc; dy-=dashleft*yc;
279                                         moveLine(g,curx,cury,draw);
280                                         segleft-=dashleft; dashleft=0;
281                                 }
282                         }
283                 }
284
285                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
286                         if (draw) { g.lineTo(x,y); }
287                                  else { g.moveTo(x,y); }
288                 }
289
290                 
291                 // Find point partway (0-1) along a path
292                 // returns (x,y,angle)
293                 // inspired by senocular's Path.as
294                 
295                 private function pointAt(t:Number):Array {
296                         var totallen:Number = t*pathlength;
297                         var curlen:Number = 0;
298                         var dx:Number, dy:Number, seglen:Number;
299                         for (var i:int = 1; i < way.length; i++){
300                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
301                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
302                                 seglen=Math.sqrt(dx*dx+dy*dy);
303                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
304                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
305                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
306                                                                  Math.atan2(dy,dx));
307                         }
308                         return new Array(0, 0, 0);
309                 }
310
311                 // Draw name along path
312                 // based on code by Tom Carden
313                 // ** needs styling
314                 
315                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
316
317                         // make a dummy textfield so we can measure its width
318                         var tf:TextField = new TextField();
319                         tf.defaultTextFormat = nameformat;
320                         tf.text = a;
321                         tf.width = tf.textWidth+4;
322                         tf.height = tf.textHeight+4;
323                         if (pathlength<tf.width) { return; }    // no room for text?
324
325                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
326                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
327
328                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
329                         var offsetSign:Number;  // -1 if we're starting at t2
330                         var tStart:Number;      // t1 or t2
331
332                         // make sure text doesn't run right->left or upside down
333                         if (p1[0] < p2[0] && 
334                                 p1[2] < Math.PI/2 &&
335                                 p1[2] > -Math.PI/2) {
336                                 angleOffset = 0; offsetSign = 1; tStart = t1;
337                         } else {
338                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
339                         } 
340
341                         // make a textfield for each char, centered on the line,
342                         // using getCharBoundaries to rotate it around its center point
343                         var chars:Array = a.split('');
344                         for (var i:int = 0; i < chars.length; i++) {
345                                 var rect:Rectangle = tf.getCharBoundaries(i);
346                                 if (rect) {
347                                         s.addChild(rotatedLetter(chars[i],
348                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
349                                                                                          rect.width, tf.height, angleOffset, textOffset));
350                                 }
351                         }
352                 }
353
354                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
355                         var tf:TextField = new TextField();
356             tf.mouseEnabled = false;
357             tf.mouseWheelEnabled = false;
358                         tf.defaultTextFormat = nameformat;
359                         tf.embedFonts = true;
360                         tf.text = char;
361                         tf.width = tf.textWidth+4;
362                         tf.height = tf.textHeight+4;
363
364                         var p:Array=pointAt(t);
365                         var matrix:Matrix = new Matrix();
366                         matrix.translate(-w/2, -h/2-o);
367                         // ** add (say) -4 to the height to move it up by 4px
368                         matrix.rotate(p[2]+a);
369                         matrix.translate(p[0], p[1]);
370                         tf.transform.matrix = matrix;
371                         return tf;
372                 }
373                 
374                 // Add object (stroke/fill/roadname) to layer sprite
375                 
376                 private function addToLayer(s:DisplayObject,t:uint,sublayer:int=-1):void {
377                         var l:DisplayObject=Map(map).getChildAt(layer);
378                         var o:DisplayObject=Sprite(l).getChildAt(t);
379                         if (sublayer!=-1) { o=Sprite(o).getChildAt(sublayer); }
380                         Sprite(o).addChild(s);
381                         sprites.push(s);
382             if ( s is Sprite ) {
383                 Sprite(s).mouseEnabled = false;
384                 Sprite(s).mouseChildren = false;
385             }
386                 }
387
388                 public function getNodeAt(x:Number, y:Number):Node {
389                         for (var i:uint = 0; i < way.length; i++) {
390                 var node:Node = way.getNode(i);
391                 var nodeX:Number = map.lon2coord(node.lon);
392                 var nodeY:Number = map.latp2coord(node.latp);
393                 if ( nodeX >= x-2 && nodeX <= x+2 &&
394                      nodeY >= y-2 && nodeY <= y+2 )
395                     return node;
396             }
397             return null;
398                 }
399
400         private function mouseEvent(event:MouseEvent):void {
401             var node:Node = getNodeAt(event.localX, event.localY);
402             if ( node == null )
403                 map.entityMouseEvent(event, way);
404             else
405                 map.entityMouseEvent(event, node);
406         }
407
408         public function setHighlight(stateType:String, isOn:Boolean):void {
409             if ( isOn && stateClasses[stateType] == null ) {
410                 stateClasses[stateType] = true;
411                 redraw();
412             } else if ( !isOn && stateClasses[stateType] != null ) {
413                 delete stateClasses[stateType];
414                 redraw();
415             }
416         }
417         }
418 }