basic multipolygon rendering
[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.TextField;
8         import flash.text.TextFormat;
9         import flash.events.*;
10         import net.systemeD.halcyon.styleparser.*;
11     import net.systemeD.halcyon.connection.*;
12         import net.systemeD.halcyon.Globals;
13
14         public class WayUI extends EntityUI {
15
16         private var way:Way;
17                 public var pathlength:Number;                           // length of path
18                 public var patharea:Number;                                     // area of path
19                 public var centroid_x:Number;                           // centroid
20                 public var centroid_y:Number;                           //  |
21                 public var heading:Array=new Array();           // angle at each node
22         private var hitzone:Sprite;
23                 public var nameformat:TextFormat;
24
25                 private const NODESIZE:uint=6;
26
27                 public function WayUI(way:Way, paint:MapPaint, interactive:Boolean=true) {
28                         super();
29                         this.way = way;
30                         this.paint = paint;
31                         this.ruleset = ruleset;
32                         this.interactive = interactive;
33             init();
34             way.addEventListener(Connection.TAG_CHANGED, wayTagChanged);
35             way.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
36             way.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
37             way.addEventListener(Connection.WAY_REORDERED, wayReordered);
38                         way.addEventListener(Connection.WAY_DELETED, wayDeleted);
39             way.addEventListener(Connection.WAY_DRAGGED, wayDragged);
40                         way.addEventListener(Connection.ADDED_TO_RELATION, wayRelationAdded);
41                         way.addEventListener(Connection.REMOVED_FROM_RELATION, wayRelationRemoved);
42                         way.addEventListener(Connection.SUSPEND_REDRAW, suspendRedraw);
43                         way.addEventListener(Connection.RESUME_REDRAW, resumeRedraw);
44             attachNodeListeners();
45             attachRelationListeners();
46                 }
47                 
48                 private function attachNodeListeners():void {
49             for (var i:uint = 0; i < way.length; i++ ) {
50                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
51             }
52                 }
53
54                 private function attachRelationListeners():void {
55                     var relations:Array = way.parentRelations;
56             for each(var relation:Relation in relations ) {
57                 relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
58             }
59                 }
60                 
61                 private function wayRelationAdded(event:RelationMemberEvent):void {
62                     event.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
63                     redraw();
64                 }
65                 
66                 private function wayRelationRemoved(event:RelationMemberEvent):void {
67                     event.relation.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
68                     redraw();
69                 }
70                 
71                 private function wayNodeAdded(event:WayNodeEvent):void {
72                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved);
73                     redraw();
74                 }
75                     
76                 private function wayNodeRemoved(event:WayNodeEvent):void {
77                     event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
78                         if (paint.nodeuis[event.node.id]) {
79                                 paint.nodeuis[event.node.id].redraw();
80                         }
81                     redraw();
82                 }
83                     
84         private function wayTagChanged(event:TagEvent):void {
85             redraw();
86         }
87         private function relationTagChanged(event:TagEvent):void {
88             redraw();
89         }
90         private function nodeMoved(event:NodeMovedEvent):void {
91             redraw();
92         }
93                 private function wayDeleted(event:EntityEvent):void {
94                         redraw();
95                 }
96         private function wayReordered(event:EntityEvent):void {
97             redraw();
98         }
99                 private function wayDragged(event:WayDraggedEvent):void {
100                         offsetSprites(event.xDelta,event.yDelta);
101                 }
102
103                 private function init():void {
104                         recalculate();
105                         redraw();
106                         // updateBbox(lon, lat);
107                         // ** various other stuff
108                 }
109
110                 // ------------------------------------------------------------------------------------------
111                 // Calculate length etc.
112                 // ** this could be made scale-independent - would speed up redraw
113                 
114                 public function recalculate():void {
115                         var lx:Number, ly:Number, sc:Number;
116                         var node:Node, latp:Number, lon:Number;
117                         var cx:Number=0, cy:Number=0;
118                         pathlength=0;
119                         patharea=0;
120                         if (way.length==0) { return; }
121                         
122                         lx = way.getNode(way.length-1).lon;
123                         ly = way.getNode(way.length-1).latp;
124                         for ( var i:uint = 0; i < way.length; i++ ) {
125                 node = way.getNode(i);
126                 latp = node.latp;
127                 lon  = node.lon;
128
129                                 // length and area
130                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
131                                 sc = (lx*latp-lon*ly)*paint.map.scalefactor;
132                                 cx += (lx+lon)*sc;
133                                 cy += (ly+latp)*sc;
134                                 patharea += sc;
135                                 
136                                 // heading
137                                 if (i>0) { heading[i-1]=Math.atan2((lon-lx),(latp-ly)); }
138
139                                 lx=lon; ly=latp;
140                         }
141                         heading[way.length-1]=heading[way.length-2];
142
143                         pathlength*=paint.map.scalefactor;
144                         patharea/=2;
145                         if (patharea!=0 && way.isArea()) {
146                                 centroid_x=paint.map.lon2coord(cx/patharea/6);
147                                 centroid_y=paint.map.latp2coord(cy/patharea/6);
148                         } else if (pathlength>0) {
149                                 var c:Array=pointAt(0.5);
150                                 centroid_x=c[0];
151                                 centroid_y=c[1];
152                         }
153                 }
154
155                 // ------------------------------------------------------------------------------------------
156                 // Redraw
157
158                 override public function doRedraw(sl:StyleList):Boolean {
159                         removeSprites();
160                         if (way.length==0) { return false; }
161                         if (!paint.ready) { return false; }
162
163             // Copy tags object, and add states
164             var tags:Object = way.getTagsCopy();
165                         tags=applyStateClasses(tags);
166                         if (way.isArea()) { tags[':area']='yes'; }
167
168                         // Which layer?
169                         layer=0;
170                         if (tags['layer']) { layer=Math.min(Math.max(tags['layer'],paint.minlayer),paint.maxlayer); }
171
172                         // Iterate through each sublayer, drawing any styles on that layer
173                         if (!sl) { sl=paint.ruleset.getStyles(this.way, tags); }
174                         var drawn:Boolean;
175                         var multis:Array=way.findParentRelationsOfType('multipolygon','outer');
176                         var inners:Array=[];
177                         for each (var m:Relation in multis) {
178                                 inners=inners.concat(m.findMembersByRole('inner'));
179                         }
180                         for (var sublayer:int=10; sublayer>=0; sublayer--) {
181                                 if (sl.shapeStyles[sublayer]) {
182                                         var s:ShapeStyle=sl.shapeStyles[sublayer];
183                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
184                                         var x0:Number=paint.map.lon2coord(way.getNode(0).lon);
185                                         var y0:Number=paint.map.latp2coord(way.getNode(0).latp);
186
187                                         // Stroke
188                                         if (s.width)  {
189                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,sublayer);
190                                                 stroke.graphics.moveTo(x0,y0);
191                                                 s.applyStrokeStyle(stroke.graphics);
192                                                 if (s.dashes && s.dashes.length>0) {
193                                                         var segments:Array=dashedLine(stroke.graphics,s.dashes); 
194                                                         if (s.line_style) { lineDecoration(stroke.graphics,s,segments); }
195                                                 } else { solidLines(stroke.graphics,inners); }
196                                                 drawn=true;
197                                         }
198
199                                         // Fill
200                                         if ((s.fill_color || s.fill_image) && way.findParentRelationsOfType('multipolygon','inner').length==0) {
201                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE);
202                                                 fill.graphics.moveTo(x0,y0);
203                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
204                                                                          else { s.applyFill(fill.graphics); }
205                                                 solidLines(fill.graphics,inners);
206                                                 fill.graphics.endFill();
207                                                 drawn=true;
208                                         }
209
210                                         // Casing
211                                         if (s.casing_width) { 
212                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
213                                                 casing.graphics.moveTo(x0,y0);
214                                                 s.applyCasingStyle(casing.graphics);
215                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
216                                                                                                                                         else { solidLines(casing.graphics,inners); }
217                                                 drawn=true;
218                                         }
219                                 }
220                                 
221                                 if (sl.textStyles[sublayer]) {
222                                         var t:TextStyle=sl.textStyles[sublayer];
223                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
224                                         nameformat = t.getTextFormat();
225                                         var a:String=tags[t.text];
226                                         if (a) {
227                                                 if (t.font_caps) { a=a.toUpperCase(); }
228                                                 if (t.text_center && centroid_x) {
229                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
230                                                 } else {
231                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
232                                                 }
233                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
234                                         }
235                                 }
236                                 
237                                 // ** ShieldStyle to do
238                         }
239
240                         // Draw icons
241                         // ** there should be huge potential to optimise this - at present we're
242                         //    running getStyles for every node in the way on every redraw
243                         // ** fix r/heading behaviour - that doesn't look right
244                         var r:Number;
245                         var nodetags:Object;
246                         var nodeSelected:int=stateClasses["nodeSelected"];
247                         for (var i:uint = 0; i < way.length; i++) {
248                 var node:Node = way.getNode(i);
249                                 nodetags=node.getTagsCopy();
250                                 if (i==0) { nodetags['_heading']= heading[i]; }
251                                      else { nodetags['_heading']=(heading[i]+heading[i-1])/2; }
252                                 if (stateClasses["showNodes"]) { nodetags[':selectedway']='yes'; }
253                                 if (stateClasses["showNodesHover"]) { nodetags[':hoverway']='yes'; }
254                                 if (node.id==nodeSelected) { nodetags[':selected']='yes'; }
255                                 if (node.numParentWays>1) { nodetags[':junction']='yes'; }
256                                 sl=paint.ruleset.getStyles(node,nodetags);
257                                 if (sl.hasStyles()) {
258                                         if (!paint.nodeuis[node.id]) {
259                                                 paint.nodeuis[node.id]=new NodeUI(node,paint,r);
260                                         }
261                                         paint.nodeuis[node.id].redraw(sl);
262                                 } else if (paint.nodeuis[node.id]) {
263                                         paint.nodeuis[node.id].removeSprites();
264                                         delete paint.nodeuis[node.id];
265                                 }
266                         }
267                         if (!drawn) { return false; }
268                         
269             // create a generic "way" hitzone sprite
270             hitzone = new Sprite();
271             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
272             solidLines(hitzone.graphics,[]);
273             addToLayer(hitzone, CLICKSPRITE);
274             hitzone.visible = false;
275                         setListenSprite(hitzone);
276
277                         return true;
278                 }
279                 
280                 // ------------------------------------------------------------------------------------------
281                 // Drawing support functions
282
283                 // Draw solid polyline
284                 
285                 public function solidLines(g:Graphics,inners:Array):void {
286                         solidLine(g,this.way);
287                         for each (var w:Way in inners) { solidLine(g,w); }
288                 }
289
290                 private function solidLine(g:Graphics,w:Way):void {
291             var node:Node = w.getNode(0);
292                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
293                         for (var i:uint = 1; i < way.length; i++) {
294                 node = w.getNode(i);
295                                 g.lineTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
296                         }
297                 }
298
299                 // Draw dashed polyline
300                 
301                 private function dashedLine(g:Graphics,dashes:Array):Array {
302                         var segments:Array=[];
303                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
304                         var a:Number, xc:Number, yc:Number;
305                         var curx:Number, cury:Number;
306                         var dx:Number, dy:Number, segleft:Number=0;
307                         var i:int=0;
308
309             var node:Node = way.getNode(0);
310             var nextNode:Node = way.getNode(0);
311                         g.moveTo(paint.map.lon2coord(node.lon), paint.map.latp2coord(node.latp));
312                         while (i < way.length-1 || segleft>0) {
313                                 if (dashleft<=0) {      // should be ==0
314                                         if (dc.length==0) { dc=dashes.slice(0); }
315                                         dashleft=dc.shift();
316                                         if (draw) { segments.push([curx,cury,dx,dy]); }
317                                         draw=!draw;
318                                 }
319                                 if (segleft<=0) {       // should be ==0
320                     node = way.getNode(i);
321                     nextNode = way.getNode(i+1);
322                                         curx=paint.map.lon2coord(node.lon);
323                     dx=paint.map.lon2coord(nextNode.lon)-curx;
324                                         cury=paint.map.latp2coord(node.latp);
325                     dy=paint.map.latp2coord(nextNode.latp)-cury;
326                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
327                                         segleft=Math.sqrt(dx*dx+dy*dy);
328                                         i++;
329                                 }
330
331                                 if (segleft<=dashleft) {
332                                         // the path segment is shorter than the dash
333                                         curx+=dx; cury+=dy;
334                                         moveLine(g,curx,cury,draw);
335                                         dashleft-=segleft; segleft=0;
336                                 } else {
337                                         // the path segment is longer than the dash
338                                         curx+=dashleft*xc; dx-=dashleft*xc;
339                                         cury+=dashleft*yc; dy-=dashleft*yc;
340                                         moveLine(g,curx,cury,draw);
341                                         segleft-=dashleft; dashleft=0;
342                                 }
343                         }
344                         return segments;
345                 }
346
347                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
348                         if (draw) { g.lineTo(x,y); }
349                                  else { g.moveTo(x,y); }
350                 }
351
352                 // Draw decoration (arrows etc.)
353                 
354                 private function lineDecoration(g:Graphics,s:ShapeStyle,segments:Array):void {
355                         var c:int=s.color ? s.color : 0;
356                         switch (s.line_style.toLowerCase()) {
357
358                                 case 'arrows':
359                                         var w:Number=s.width*1.5;       // width of arrow
360                                         var l:Number=s.width*2;         // length of arrow
361                                         var angle0:Number, angle1:Number, angle2:Number;
362                                         g.lineStyle(1,c);
363                                         for each (var seg:Array in segments) {
364                                                 g.beginFill(c);
365                                                 angle0= Math.atan2(seg[3],seg[2]);
366                                                 angle1=-Math.atan2(seg[3],seg[2]);
367                                                 angle2=-Math.atan2(seg[3],seg[2])-Math.PI;
368                                                 g.moveTo(seg[0]+l*Math.cos(angle0),
369                                                          seg[1]+l*Math.sin(angle0));
370                                                 g.lineTo(seg[0]+w*Math.sin(angle1),
371                                                          seg[1]+w*Math.cos(angle1));
372                                                 g.lineTo(seg[0]+w*Math.sin(angle2),
373                                                          seg[1]+w*Math.cos(angle2));
374                                                 g.endFill();
375                                         }
376                                         break;
377                                 }
378                 }
379
380                 
381                 // Find point partway (0-1) along a path
382                 // returns (x,y,angle)
383                 // inspired by senocular's Path.as
384                 
385                 private function pointAt(t:Number):Array {
386                         var totallen:Number = t*pathlength;
387                         var curlen:Number = 0;
388                         var dx:Number, dy:Number, seglen:Number;
389                         for (var i:int = 1; i < way.length; i++){
390                                 dx=paint.map.lon2coord(way.getNode(i).lon)-paint.map.lon2coord(way.getNode(i-1).lon);
391                                 dy=paint.map.latp2coord(way.getNode(i).latp)-paint.map.latp2coord(way.getNode(i-1).latp);
392                                 seglen=Math.sqrt(dx*dx+dy*dy);
393                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
394                                 return new Array(paint.map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
395                                                                  paint.map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
396                                                                  Math.atan2(dy,dx));
397                         }
398                         return new Array(0, 0, 0);
399                 }
400
401                 // Draw name along path
402                 // based on code by Tom Carden
403                 
404                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
405
406                         // make a dummy textfield so we can measure its width
407                         var tf:TextField = new TextField();
408                         tf.defaultTextFormat = nameformat;
409                         tf.text = a;
410                         tf.width = tf.textWidth+4;
411                         tf.height = tf.textHeight+4;
412                         if (pathlength<tf.width) { return; }    // no room for text?
413
414                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
415                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
416
417                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
418                         var offsetSign:Number;  // -1 if we're starting at t2
419                         var tStart:Number;      // t1 or t2
420
421                         // make sure text doesn't run right->left or upside down
422                         if (p1[0] < p2[0] && 
423                                 p1[2] < Math.PI/2 &&
424                                 p1[2] > -Math.PI/2) {
425                                 angleOffset = 0; offsetSign = 1; tStart = t1;
426                         } else {
427                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
428                         } 
429
430                         // make a textfield for each char, centered on the line,
431                         // using getCharBoundaries to rotate it around its center point
432                         var chars:Array = a.split('');
433                         for (var i:int = 0; i < chars.length; i++) {
434                                 var rect:Rectangle = tf.getCharBoundaries(i);
435                                 if (rect) {
436                                         s.addChild(rotatedLetter(chars[i],
437                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
438                                                                                          rect.width, tf.height, angleOffset, textOffset));
439                                 }
440                         }
441                 }
442
443                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
444                         var tf:TextField = new TextField();
445             tf.mouseEnabled = false;
446             tf.mouseWheelEnabled = false;
447                         tf.defaultTextFormat = nameformat;
448                         tf.embedFonts = true;
449                         tf.text = char;
450                         tf.width = tf.textWidth+4;
451                         tf.height = tf.textHeight+4;
452
453                         var p:Array=pointAt(t);
454                         var matrix:Matrix = new Matrix();
455                         matrix.translate(-w/2, -h/2-o);
456                         // ** add (say) -4 to the height to move it up by 4px
457                         matrix.rotate(p[2]+a);
458                         matrix.translate(p[0], p[1]);
459                         tf.transform.matrix = matrix;
460                         return tf;
461                 }
462                 
463                 public function getNodeAt(x:Number, y:Number):Node {
464                         for (var i:uint = 0; i < way.length; i++) {
465                 var node:Node = way.getNode(i);
466                 var nodeX:Number = paint.map.lon2coord(node.lon);
467                 var nodeY:Number = paint.map.latp2coord(node.latp);
468                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
469                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
470                     return node;
471             }
472             return null;
473                 }
474
475                 // ------------------------------------------------------------------------------------------
476                 // Interaction
477
478         override protected function mouseEvent(event:MouseEvent):void {
479                         paint.map.entityMouseEvent(event, way);
480         }
481
482                 public function hitTest(x:Number, y:Number):Way {
483                         if (hitzone.hitTestPoint(x,y,true)) { return way; }
484                         return null;
485                 }
486
487         }
488 }