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