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