summaryrefslogtreecommitdiff
path: root/Source/Main.hx
blob: 1a7eba9b17c60854af991f442bff5299467218d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
package;

import haxe.ds.Option;
import motion.Actuate;
import openfl.display.GraphicsPath;
import openfl.display.SimpleButton;
import openfl.display.Sprite;
import openfl.events.Event;
import openfl.events.KeyboardEvent;
import openfl.events.MouseEvent;
import openfl.events.TimerEvent;
import openfl.geom.Point;
import openfl.geom.Rectangle;
import openfl.text.TextField;
import openfl.text.TextFormat;
import openfl.ui.Keyboard;
import openfl.utils.Timer;

using Lambda;

typedef PointType = { x:Float, y:Float};
typedef HasVelocity =  {velocity: PointType};
typedef Circle = PointType & {radius:Float};
typedef HasColor = {color: Int};
typedef ColoredCircle = HasColor & Circle;

typedef RectType = PointType & {width:Float,height:Float};

typedef SkeletonNode =
  {
  startAngle: Float,          // the angle between this end point and its join's parent bone.
  butt: PointType,           // the end of the bone
  followers: Array<PointType>  // array of points that will move in sync with this bone
  };

class Button extends SimpleButton
{
  static var overColor:Int = 0xdddddd;
  static var upColor:Int = 0xeeeeee;
  static var downColor:Int = 0xcccccc;

  static function textBox
  (text:String,
   bgColor:Int = 0xFFFFFF,
   ?textFormat:TextFormat,
   ?borderRadius:Float = 0.0,
   ?padding:Float = 40.0,
   ?borderThickness:Float = 0.0,
   ?borderColor:Int = 0
  ):Sprite
  {
    var tf = new TextField();
    tf.multiline = false;
    tf.autoSize = openfl.text.TextFieldAutoSize.CENTER;
    tf.selectable = false;
    tf.text = text;

    if (textFormat != null)
      tf.setTextFormat( textFormat );

    var s = new Sprite();
    s.graphics.beginFill( bgColor );

    if (borderThickness > 0)
      s.graphics.lineStyle( borderThickness, borderColor);

    s.graphics.drawRoundRect(0, 0,
                             tf.textWidth + padding,
                             tf.textHeight + padding,
                             borderRadius,
                             borderRadius );
    s.graphics.endFill();

    tf.x = (s.width - tf.textWidth) / 2;
    tf.y = (s.height - tf.textHeight) / 2;

    s.addChild( tf );
    return s;
  }
  
  public function new (text:String)
  {
    var textFormat = new TextFormat(null, 25);

    var over = textBox(text, overColor, textFormat, 10.0, 50, 2 );
    var up = textBox(text, upColor, textFormat, 10.0, 50, 2);
    var down = textBox(text, downColor, textFormat, 10.0, 50, 2);

    super( up , over, down, over);
    this.enabled = true;
  }

}

class Wiggler extends Sprite
{
  static inline var RADIUS_DRAW_THRESHHOLD = 25;
  static inline var BRANCHING_FACTOR = 5;
  static inline var QUADRANT_COEFF = 1.2;

  var path:Array<Point> = [];

  var radiusGradient:Float = 3.0;
  var radiiSizes:Int = 25;

  var dontDrawLargerThanFactor = 0.2;
  var circles:Array<ColoredCircle> = [];

  var bones:Map<PointType, Array<SkeletonNode>>;
  
  public function new (path:Array<Point>)
  {
    super();
    this.path = Util.translatePathToOrigin( path );
    addCircles();
    addBones();

    render();
  }

  // A circle is valid if it is contained within the boundary of the
  // path and if it does not intersect any other circles.
  function isValidCircle( circ:ColoredCircle ): Bool
  {
    return circleInsideClosedPath( circ) &&
      !circleIntersectsCircles( circ );
  }

  function circleInsideClosedPath( circ ): Bool
  {
    return Util.pointInsideClosedPath( circ, path) &&
      !Util.circleIntersectsPath(circ, path);
  }
  
  function circleIntersectsCircles( circ ): Bool
  {
    for (c in circles)
      if (Util.circlesIntersect( c, circ))
        return true;

    return false;
  }

  function randomCircle( box:Rectangle, radius:Float): ColoredCircle
  {
    var pt = Util.randomPointInRect( box );
    return {x:pt.x, y:pt.y, color: Std.int(Math.random() * 0xFFFFFF), radius:radius};
  }

  function addCircles()
  {
    circles = [];
    if (path.length > 2)
      {
        var bbox = Util.pathBoundingBox( path );
        var rad = radiusGradient * radiiSizes;
        var step = 1.25;
        while (rad > 0)
          {
            for (cx in 0...Std.int(bbox.width / (step * rad)))
              for (cy in 0...Std.int(bbox.height / (step * rad)))
                {
                  var circ = {
                  x: cx * step * rad,
                  y:cy * step * rad,
                  radius:rad,
                  color: Std.int(Math.random() * 0xFFFFFF)
                  };

                  if (isValidCircle( circ )) circles.push( circ );
                }
            rad -= radiusGradient;
          }
      }
  }

  function segmentIntersectsBones(p1,p2):Bool
  {
    for (hinge => nodes in bones)
      for (node in nodes)
        if (Util.segmentsIntersect(p1, p2, hinge, node.butt ))
          return true;

    return false;
  }

  function biggestCircleInQuadrant(rect:Rectangle)
  {
    var biggest:ColoredCircle = null;
    for (c in circles)
      if (Util.pointInRectangle(c,rect))
        biggest = if (biggest == null || biggest.radius < c.radius) c else biggest;

    return biggest;
  }

  function associatePtWithNearestBone<P:PointType>(pt:P)
  {
    if (bones.exists( pt )) return;

    var dist:Float = 100000;
    var nearNode:SkeletonNode = null;

    for ( hinge => nodes in bones)
      for (node in nodes)
        {
          var tmpDist = Math.min(Util.dist(pt, hinge), Util.dist(pt, node.butt));
          if (pt == node.butt)
            return;               // exit if pt is a butt
          else if ( nearNode == null )
            {
              nearNode = node;
              dist = tmpDist;
            }
          else if (tmpDist < dist)
            {
              nearNode = node;
              dist = tmpDist;
            }
        }

    if (nearNode != null)
      nearNode.followers.push( pt );
  }

  function addBones ()
  {
    bones = new Map();
    var candidates = circles.copy();
    candidates.sort( (a,b) -> Std.int(b.radius - a.radius));
    
    var frontier = [];

    // start the frontier with the largest circle in each "quadrant"
    var bbox = Util.pathBoundingBox( path );
    var quad = new Rectangle(0,0,
                             radiusGradient * radiiSizes * QUADRANT_COEFF,
                             radiusGradient * radiiSizes * QUADRANT_COEFF );

    for (ix in 0...Math.floor( bbox.width / quad.width))
      for (iy in 0...Math.floor( bbox.height / quad.height))
        {
          quad.x = ix * quad.width;
          quad.y = iy * quad.height;
          var circ = biggestCircleInQuadrant( quad );
          if (circ != null)
            {
              frontier.push( circ );
              candidates.remove( circ );
            }
        }

    // add bones
    while (frontier.length > 0)
      {
        var node = frontier.shift();
        var validNeighbors =
          candidates.filter( n -> n.radius <= node.radius
                             && !Util.segmentIntersectsPath(node, n, path)
                             && !segmentIntersectsBones(node, n));

        var toBranch = Math.ceil(Math.random() * BRANCHING_FACTOR);
        var newNbrs = validNeighbors.slice(0, toBranch);

        newNbrs.sort( (a,b) -> Std.int(Util.dist(a, node) - Util.dist(b, node)));

        bones[node] = 
          newNbrs.map( nbr -> ({ butt: nbr,  startAngle: 0,  followers: [] } : SkeletonNode));

        for (nbr in newNbrs)
          {
            candidates.remove( nbr );
            frontier.push( nbr );
          }

        candidates = candidates
          .filter( circ -> {
              for (nbr in newNbrs)
                if (Util.circleIntersectsLineSegment( circ, node, nbr))
                  return false;
              return true;
            });
      }

    // associate path points and circles with a bone
    for (pt in circles)
      associatePtWithNearestBone(pt);
    for (pt in path)
     associatePtWithNearestBone(pt);
  }


  public function render ()
  {
    if (path.length == 0) return;

    graphics.clear();

    var graphicsPath = new GraphicsPath();
    graphicsPath.moveTo( path[0].x, path[0].y);
    for (i in 1...path.length)
      graphicsPath.lineTo( path[i].x, path[i].y);

    graphics.beginFill(0xfaeeee);
    graphics.lineStyle(8.0);
    graphicsPath.lineTo( path[0].x, path[0].y);
    graphics.drawPath( graphicsPath.commands, graphicsPath.data );

    var dontDrawLargerThan = radiiSizes * radiusGradient * dontDrawLargerThanFactor;
    graphics.lineStyle(0.0);
    for (circ in circles)
      if (circ.radius <= dontDrawLargerThan)
        {
          graphics.beginFill( circ.color, 0.5);
          graphics.drawCircle( circ.x, circ.y, circ.radius);
        }    
    
    // for (hinge => nodes in bones)
    //   for (node in nodes)
    //     {
    //       graphics.lineStyle(1,0xff0000);
    //       graphics.moveTo(hinge.x, hinge.y);
    //       graphics.lineTo(node.butt.x, node.butt.y);
    //       graphics.lineStyle(4, Std.int(Math.random() * 0xffffff));
    //       //graphics.lineStyle(1,0x0000ff);
    //       var mid = {x: (hinge.x + node.butt.x)/2, y:(hinge.y + node.butt.y)/2};
    //       for (follower in node.followers)
    //         {
    //           graphics.moveTo( mid.x, mid.y);
    //           graphics.lineTo( follower.x, follower.y);
    //         }
    //     }
    
  }

}

class DrawingScreen extends Sprite
{

  /* the prupose of which is to produce a path of a closed polygon
     suitable for passing in as the "skin" of a wiggler. */
  
  var path: Array<Point> = [];

  var candidateWiggler:Wiggler;

  var holdPath:Bool = false;

  public function new ()
  {
    super();
    addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
    addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
    addEventListener(MouseEvent.MOUSE_OUT, onMouseUp);
    addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
    addEventListener(Event.ADDED_TO_STAGE, maximizeHitArea);
  }

  /* Event Handling */
  
  static inline var sampleRate:Float = 0.01;
  static inline var sampleGap:Float = 5.0;
  static inline var bgColor:Int = 0xFFFFFF;

  var drawing = false;
  var timestamp:Float;

  function maximizeHitArea(e)
  {
    var hitBox = new Sprite();
    hitBox.graphics.beginFill(0);
    hitBox.graphics.drawRect( 0, 0, stage.stageWidth, stage.stageHeight);
    hitBox.mouseEnabled = false;
    this.hitArea = hitBox;
  }

  function onMouseDown (e)
  {
    refresh();
    drawing = true;
    timestamp = haxe.Timer.stamp();
    path = [ new Point(e.localX, e.localY) ];

    graphics.lineStyle(2, 0);
    graphics.moveTo( path[0].x, path[0].y );
  }

  function refresh ()
  {
    Actuate.stop(this); 
    if (candidateWiggler != null)
      {
        removeChild( candidateWiggler );
        candidateWiggler = null;
      }
    graphics.clear();
    alpha = 1.0;
    visible = true;
    path = [];
    holdPath = false;
  }

  function fadeAndRefresh()
  {
    Actuate
      .tween(this, 0.5, {alpha: 0})
      .onComplete( refresh );
  }

  function onMouseUp (e)
  {
    drawing = false;
    if (!holdPath) fadeAndRefresh();
  }
  
  function clearAndRenderPath()
  {
    graphics.clear();
    graphics.lineStyle(2, 0);
    graphics.moveTo(path[0].x, path[0].y);
    for (i in 1...path.length)
      graphics.lineTo(path[i].x, path[i].y);
    graphics.lineTo(path[0].x, path[0].y);
  }

  function onMouseMove (e)
  {
    if (!drawing) return;

    var stamp = haxe.Timer.stamp();
    var pt = new Point( e.localX, e.localY);
    if ((stamp - timestamp > sampleRate) &&
        Point.distance(pt, path[path.length - 1]) >= sampleGap)
      {
        var intersectIndex = Util.findSelfIntersection( path, pt );
        if (intersectIndex != null)
          {
            drawing = false;
            holdPath = true;
            var intersectionPt =
              Util.linesIntersectAt( path[intersectIndex],
                                          path[intersectIndex + 1],
                                          path[path.length -1], pt);

            path = path.slice( intersectIndex );

            if (intersectionPt != null)
              {
                path.push(intersectionPt);
                graphics.lineTo( intersectionPt.x, intersectionPt.y);
              }
            else
              graphics.lineTo( pt.x, pt.y );

            //clearAndRenderPath();
            createAndPresentWiggler();
            return; // to return early
          }

        timestamp = stamp;
        path.push( pt );
        graphics.lineTo( pt.x, pt.y);
      }
  }


  function createAndPresentWiggler()
  {
    clearAndRenderPath();

    var bbox = Util.pathBoundingBox( path );

    candidateWiggler = new Wiggler( path );
    candidateWiggler.x = bbox.x;
    candidateWiggler.y = bbox.y;

    //graphics.clear();

    addChild( candidateWiggler );

  }
}

enum Line {
  Vertical(xVal:Float);
  Horizontal(yVal:Float);
  Sloped(slop:Float,yIntercept:Float);
}

class Util
{

  public static function dotProduct<P1:PointType, P2:PointType>(p1:P1,p2:P2):Float
  {
    return p1.x * p2.x + p1.y * p2.y;
  }

  public static function distanceToSegment
  <P1:PointType, P2:PointType, P3:PointType>
    (p:P1, a:P2, b:P3):Float
  {
    var ab = {x: b.x - a.x, y: b.y - a.y};
    var bp = {x: p.x - b.x, y: p.y - b.y};

    if ( dotProduct( ab, bp ) > 0)
      return dist(b, p);

    var ba = {x: a.x - b.x, y: a.y - b.y};
    var pb = {x: b.x - p.x, y: b.y - p.y};

    if ( dotProduct( ba, pb) > 0 )
      return dist(a, p);

    switch (lineOfSegment(a, b))
      {
      case Vertical( xVal ):
        return Math.abs( xVal - p.x );

      case Horizontal( yVal ):
        return Math.abs( yVal - p.y );

      case Sloped(m,intercept):
        // l1: y = m * x + intercept
        // l2: p.y = -1 * p.x / m + intercept2
        var intercept2 =  p.y + p.x / m;
        // -1 * sx / m + intercept2 = m * sx + intercept
        // intercept2 - intercept = m * sx + sx / m
        // intercept2 - intercept = sx * (m + 1/m)
        var sx = (intercept2 - intercept) / (m + 1 / m);
        var sy = m * sx + intercept;
        return dist( {x:sx,y:sy}, p);
      }

  }

  public static function pointInRectangle<P:PointType,R:RectType>(p:P,r:R):Bool
  {
    return isBetween(r.x, p.x, r.x + r.width) && isBetween(r.y, p.y, r.y + r.height);
  }

  public static function randomBetween(lo:Float,hi:Float):Float
  {
    if (hi < lo) return randomBetween(hi, lo);

    return Math.random() * (hi - lo) + lo;   
  }

  public static function circlesIntersect<C1:Circle,C2:Circle>(c1:C1,c2:C2):Bool
  {
    var d = dist(c1,c2);
    return d < c1.radius + c2.radius;
  }

  public static function pathBoundingBox( path:Array<Point> ):Null<Rectangle>
  {
    if (path.length ==0) return null;
    var left  = path[0].x;
    var right = left;
    var top = path[0].y;
    var bottom = top;

    for (pt in path)
      {
        left = Math.min( left, pt.x);
        right = Math.max( right, pt.x);
        top = Math.min( top, pt.y);
        bottom = Math.max( bottom, pt.y);
      }
    return new Rectangle(left, top, right - left, bottom - top);
  }

  public static function randomPointInRect( rect:Rectangle):Point
  {
    return new Point( Math.random() * rect.width + rect.x,
                      Math.random() * rect.height + rect.y);    
  }

  // a point is inside a closed path if, when a linesegment connecting
  // that point to the origin is drawn, the number of intersections
  // of that line and the path is odd.
  public static function pointInsideClosedPath< T: PointType> (pt: T, path:Array<Point>):Bool
  {
    if (path.length < 2) return false;
    
    var intersections = 0;
    var origin : PointType = {x:0, y:0};

    for (i in 0...path.length - 1)
      if (segmentsIntersect( origin, pt, path[i], path[i + 1]))
        intersections += 1;

    if (segmentsIntersect( origin, pt, path[path.length - 1], path[0]))
      intersections += 1;

    return intersections % 2 == 1;
  }

  public static function circleIntersectsPath<T:Circle>
  ( circ:T, path:Array<Point>):Bool
  {
    for (i in 0...path.length - 1)
      {
        if (circleContainsPt( circ, path[i]) ||
            circleContainsPt( circ, path[i + 1]))
          return true;

        if (circleIntersectsLineSegment(circ, path[i], path[i+1]))
          return true;
      }
    return false;
  }

  public static function isBetween( a:Float, b:Float, c:Float):Bool
  {
    return (a <= b && b <= c) || (c <= b && b <= a);
  }

  // choosing to do this b/c it will benefit from any efficiency gains that
  // may be introduced into openfl's Point.distance method in the future:
  static var distPt1:Point;
  static var distPt2:Point;
  public static function dist<P1:PointType, P2:PointType>(p1:P1,p2:P2):Float
  {
    if (distPt1 == null)
      {
        distPt1 = new Point();
        distPt2 = new Point();
      }

    distPt1.x = p1.x;
    distPt1.y = p1.y;

    distPt2.x = p2.x;
    distPt2.y = p2.y;

    return Point.distance( distPt1, distPt2);
  }

  public static function circleContainsPt<C:Circle,P:PointType>
    (circ:C, pt:P):Bool
  {
    return dist(circ, pt) <= circ.radius;
  }

  public static function circleIntersectsLineSegment
  <C:Circle, P1:PointType, P2:PointType>
    ( circ: C, p1:P1, p2:P2):Bool
  {
    // if either enddpoint is in the circle, then we count an
    // intersection.  note, that this means that even if the circle
    // contains the whole segment, we count this as an intersection.
    if (circleContainsPt(circ,p1) || circleContainsPt(circ, p2))
      return true;

    switch (lineOfSegment(p1, p2))
      {
      case null:
        return false;

      case Vertical(xVal):
        return Math.abs(circ.x - xVal) <= circ.radius && isBetween(p1.y, circ.y, p2.y);

      case Horizontal(yVal):
        return Math.abs(circ.y - yVal) <= circ.radius && isBetween(p1.x, circ.x, p2.x);

      case Sloped(m, yInt):
        var a = m * m + 1;
        var k = yInt - circ.y;
        var b = 2 * (m*k - circ.x);
        var c = k * k + circ.x * circ.x - circ.radius * circ.radius;

        var discriminant = b * b - 4 * a * c;
        return discriminant >= 0;
      }
  }

  public static function ptEquals<P1:PointType, P2:PointType>(a:P1,b:P2):Bool
  {
    return a.x == b.x && a.y == b.y;
  }

  public static function lineOfSegment<P1:PointType, P2:PointType> ( a:P1, b:P2 ): Null<Line>
  {
    if (ptEquals(a, b )) return null;
    if (a.x == b.x) return Vertical(a.x);
    if (a.y == b.y) return Horizontal(a.y);

    var slope = (b.y - a.y) / (b.x - a.x);
    var yIntercept = a.y - slope * a.x;
    return Sloped(slope, yIntercept);
  }

  public static function isCounterClockwiseOrder
  <P1:PointType,P2:PointType,P3:PointType>
  (a:P1,b:P2,c:P3):Bool {
    return (b.x - a.x) * (c.y - a.y) > (b.y - a.y) * (c.x - a.x);
  }

  public static function segmentsIntersect
  <P1:PointType,P2:PointType,P3:PointType,P4:PointType>
  (a:P1,b:P2,c:P3,d:P4):Bool
  {
    return (isCounterClockwiseOrder( a, c, d) != isCounterClockwiseOrder(b, c, d)) &&
      (isCounterClockwiseOrder( a ,b, c) != isCounterClockwiseOrder(a, b, d));
  }


  public static function pathIsCounterClockwise( path: Array<Point> ) : Bool
  {
    return path.length > 2 && isCounterClockwiseOrder(path[0], path[1], path[2]);
  }


  public static function linesIntersectAt
  <P1:PointType,P2:PointType,P3:PointType,P4:PointType>
    (a:P1,b:P2,c:P3,d:P4):Null<Point>
  {
    var segments = [lineOfSegment(a, b), lineOfSegment(c, d)];
    switch (segments)
      {
      case [Sloped(m1,b1), Sloped(m2,b2)]:
        var x = (b2 - b1) / (m1 - m2);
        var y = m1 * x + b1;
        return new Point(x, y);

      case [Sloped(m,b), Horizontal(y)] | [Horizontal(y) , Sloped(m, b)]:
        var x = (y - b) / m;
        return new Point(x,y);

      case [Sloped(m,b), Vertical(x)] | [Vertical(x), Sloped(m,b)]:
        var y = m * x + b;
        return new Point(x, y);

      case [Horizontal(y), Vertical(x)] | [Vertical(x), Horizontal(y)]:
        return new Point(x, y);

      default:
        return null;
      }
  }

  // given a path and a point, check of the line between the last
  // point in tha path and the provided point intersects the path.  If
  // it does, the last index in the path checked is returned.
  public static function findSelfIntersection
  ( path:Array<Point>, pt:Point ) : Null<Int>
  {
    if (path != null && path.length > 0)
      {
        var last = path.length -1;
        for (i in 1...last)
          if ( segmentsIntersect( path[i-1], path[i], path[last], pt) )
            return i;
      }
    return null;
  }

  public static function segmentIntersectsPath
  <P1:PointType, P2:PointType, P3:PointType> 
    (p1:P1, p2:P2, path:Array<P3>) : Bool
  {
    if (path.length > 1)
      for (i in 1...path.length)
        if (segmentsIntersect( p1 , p2, path[i-1], path[i]))
          return true;

    return segmentsIntersect( p1, p2, path[path.length - 1], path[0]);    
  }

  // useful for "shrinking" a path so that, when drawn via a Graphics
  // object, the Sprite will remain small. 
  public static function translatePathToOrigin (path:Array<Point>) : Array<Point>
  {
    if (path.length == 0) return [];

    var minX = path[0].x;
    var minY = path[0].y;

    for (pt in path)
      {
        minX = Math.min( minX, pt.x);
        minY = Math.min( minY, pt.y);
      }

    // non-destructive w/rspct to path
    return path.map( pt -> new Point(pt.x - minX, pt.y - minY)); 
  }
  
}

class Main extends Sprite
{
  public function new()
  {
    super();
    addEventListener(Event.ADDED_TO_STAGE, onInit);
  }

  function onInit (e)
  {
    var screen = new DrawingScreen();
    addChild( screen );
  }
  
}