-
Notifications
You must be signed in to change notification settings - Fork 3
/
ProGeo.js
1441 lines (1221 loc) · 40.4 KB
/
ProGeo.js
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma strict
import System.Collections.Generic;
//----------------------------------------
// Various procedural geometry tools
//----------------------------------------
//----------------------------------------
// This only exists because Unity's Mesh class has a lot of overhead
// when reading its read-only buffers. So keep a copy in this class, modify it,
// then copy it to the Mesh when you're done.
//----------------------------------------
class MeshBuffer
{
var vertices:Vector3[] = null;
var uv:Vector2[] = null;
var normals:Vector3[] = null;
var triangles:int[];
function Allocate( numVerts:int, numTris:int )
{
vertices = new Vector3[ numVerts ];
uv = new Vector2[ numVerts ];
normals = new Vector3[ numVerts ];
triangles = new int[ 3*numTris ];
}
function CopyToMesh( to:Mesh )
{
// as of Unity 3.5.4, it actually checks for integrity, so we need to clear the mesh's tris before setting other stuff
to.triangles = null;
to.vertices = vertices;
to.uv = uv;
to.normals = normals;
to.triangles = triangles;
}
function SetAllNormals(n:Vector3)
{
for( var i = 0; i < normals.length; i++ )
{
normals[i] = n;
}
}
}
//----------------------------------------
// Works in the XY plane, and basically uses XY position as UVs
// TODO - have two radii - left and right radius
//----------------------------------------
static function Stroke2D(
ctrlPts:Vector2[],
ctrlPtTexVs:float[], // texture coordinate (V's)
firstCtrl:int, lastCtrl:int, // use first/lastCtrl to select a sub-array of ctrlPts.
isLoop:boolean, // whether or not it's a closed loop, ie. we should connect the last ctrl to the first one
width:float, mesh:MeshBuffer,
firstVert:int, firstTri:int // use firstVert/Tri to tell Stroke2D where to output in the mesh. firstTri should be the index/3
)
{
if( lastCtrl <= firstCtrl ) {
Debug.LogError('need at least 2 points to build stroke geometry!');
return;
}
var nctrls = lastCtrl-firstCtrl+1;
var radius : float = width/2.0;
var nsegs = ( isLoop ? nctrls : nctrls-1 );
var ntris = 2*nsegs;
// make sure buffers are large enough
if( (firstVert + 2*nctrls) > mesh.vertices.length ) {
Debug.LogError('not enough vertices allocated in mesh for '+nctrls+' control points!');
return;
}
if( 3*(firstTri + ntris) > mesh.triangles.length ) {
Debug.LogError('not enough triangle space allocated in mesh for '+nctrls+' control points!');
return;
}
// first ctrl
if( !isLoop )
{
var a = ctrlPts[firstCtrl];
var b = ctrlPts[firstCtrl+1];
var e0 = b-a;
var n = Math2D.PerpCCW( e0 ).normalized;
mesh.vertices[firstVert+0] = a + n*radius;
mesh.vertices[firstVert+1] = a - n*radius;
var v = ctrlPtTexVs[ firstCtrl ];
mesh.uv[ firstVert+0 ] = Vector2( 0, v );
mesh.uv[ firstVert+1 ] = Vector2( 1, v );
}
for( var i = (isLoop ? firstCtrl : firstCtrl+1);
i < (isLoop ? lastCtrl+1 : lastCtrl); i++ )
{
var p0 = ctrlPts[(nctrls+i-1) % nctrls];
var p1 = ctrlPts[i % nctrls];
var p2 = ctrlPts[(i+1) % nctrls];
e0 = p1-p0;
var e1 = p2-p1;
var n0 = Math2D.PerpCCW(e0.normalized);
var n1 = Math2D.PerpCCW(e1.normalized);
var theta = Mathf.Acos(Vector2.Dot(n0,n1)) * 0.5;
var cosTheta = Mathf.Cos(theta);
var diagLen = radius;
var diagDir = ((n0+n1) * 0.5).normalized;
if( cosTheta >= 1e-7 )
{
diagLen = radius / cosTheta;
}
var vi0 = firstVert + 2*i + 0;
var vi1 = firstVert + 2*i + 1;
mesh.vertices[ vi0 ] = p1 + diagDir*diagLen;
mesh.vertices[ vi1 ] = p1 - diagDir*diagLen;
// FIXME: there's a bug with UVs.. the first seg gets a full 0-1
v = ctrlPtTexVs[ i % nctrls ];
mesh.uv[ vi0 ] = Vector2( 0, v );
mesh.uv[ vi1 ] = Vector2( 1, v );
}
// last one
if( !isLoop ) {
a = ctrlPts[ lastCtrl-1 ];
b = ctrlPts[ lastCtrl ];
e0 = b-a;
n = Math2D.PerpCCW( e0 ).normalized;
mesh.vertices[ firstVert+2*nctrls-2 ] = b + n*radius;
mesh.vertices[ firstVert+2*nctrls-1 ] = b - n*radius;
v = ctrlPtTexVs[ lastCtrl ];
mesh.uv[ firstVert+2*nctrls-2 ] = Vector2( 0, v );
mesh.uv[ firstVert+2*nctrls-1 ] = Vector2( 1, v );
}
//----------------------------------------
// Triangles
//----------------------------------------
for( i = 0; i < (nctrls-1); i++ )
{
mesh.triangles[ 3*firstTri + 6*i + 0 ] = firstVert + 2 * i + 0;
mesh.triangles[ 3*firstTri + 6*i + 1 ] = firstVert + 2 * i + 2;
mesh.triangles[ 3*firstTri + 6*i + 2 ] = firstVert + 2 * i + 1;
mesh.triangles[ 3*firstTri + 6*i + 3 ] = firstVert + 2 * i + 1;
mesh.triangles[ 3*firstTri + 6*i + 4 ] = firstVert + 2 * i + 2;
mesh.triangles[ 3*firstTri + 6*i + 5 ] = firstVert + 2 * i + 3;
/*
DebugTriangle(
mesh.vertices[ firstVert + 2 * i + 0 ],
mesh.vertices[ firstVert + 2 * i + 2 ],
mesh.vertices[ firstVert + 2 * i + 1 ], Color.red);
DebugTriangle(
mesh.vertices[ firstVert + 2 * i + 1 ],
mesh.vertices[ firstVert + 2 * i + 2 ],
mesh.vertices[ firstVert + 2 * i + 3 ], Color.blue);
*/
}
if( isLoop )
{
i = nctrls-1;
mesh.triangles[ 3*firstTri + 6*i + 0 ] = firstVert + 2 * i + 0;
mesh.triangles[ 3*firstTri + 6*i + 1 ] = firstVert + 2 * 0 + 0;
mesh.triangles[ 3*firstTri + 6*i + 2 ] = firstVert + 2 * i + 1;
mesh.triangles[ 3*firstTri + 6*i + 3 ] = firstVert + 2 * i + 1;
mesh.triangles[ 3*firstTri + 6*i + 4 ] = firstVert + 2 * 0 + 0;
mesh.triangles[ 3*firstTri + 6*i + 5 ] = firstVert + 2 * 0 + 1;
}
}
static function DebugTriangle( p0:Vector3, p1:Vector3, p2:Vector3, c:Color )
{
Debug.DrawLine(p0, p1, c);
Debug.DrawLine(p1, p2, c);
Debug.DrawLine(p2, p0, c);
}
//----------------------------------------
// pts - the ordered points of a closed polygon
//----------------------------------------
static function ClipByLine(
pts:Vector2[],
l0:Vector2,
l1:Vector2,
keepRight:boolean )
: Array
{
var npts = pts.length;
if( !keepRight )
{
// just swap the two
var temp = l0;
l0 = l1;
l1 = temp;
}
var lineDir = (l1-l0).normalized;
var rightDir = -1 * Math2D.PerpCCW( lineDir ).normalized;
// figure out which line segs cross the line
var ptIsOnRight = new boolean[ npts ];
for( var i = 0; i < npts; i++ )
{
var toPt = (pts[i] - l0).normalized;
ptIsOnRight[i] = (Vector2.Dot( toPt, rightDir ) > 0 );
}
var segCrosses = new boolean[npts];
for( i = 0; i < npts; i++ )
{
if( ptIsOnRight[i] != ptIsOnRight[(i+1)%npts] )
segCrosses[i] = true;
else
segCrosses[i] = false;
}
//----------------------------------------
// Now perform the generation of the new polygon
// Pretty simple logic.
//----------------------------------------
var newPts = new Array();
for( i = 0; i < npts; i++ )
{
if( ptIsOnRight[i] )
newPts.Push( pts[i] );
if( segCrosses[i] )
{
// add the intersection point
var p0 = pts[i];
var p1 = pts[(i+1)%npts];
var intx = Math2D.Intersect2DLines( l0, l1, p0, p1 );
newPts.Push(intx);
}
}
return newPts;
}
static function CompareByXThenY( a:Vector2, b:Vector2 )
{
if( a.x == b.x ) {
// order by Y coordinate instead
return Mathf.RoundToInt( Mathf.Sign( a.y - b.y ) );
}
else
return Mathf.RoundToInt( Mathf.Sign( a.x - b.x ) );
}
//----------------------------------------
// For Moments of Reflection, perhaps the best rep of the level geometry is a SET of polygons rather than a single polygon (which is wrong) or a 2D mesh (which is overly general)
//----------------------------------------
class Mesh2D
{
var pts : Vector2[] = null;
var edgeA : int[] = null;
var edgeB : int[] = null;
function Duplicate() : Mesh2D
{
var dupe = new Mesh2D();
dupe.pts = Utils.Duplicate( pts );
dupe.edgeA = Utils.Duplicate( edgeA );
dupe.edgeB = Utils.Duplicate( edgeB );
return dupe;
}
function GetNumVertices() : int { return pts.length; }
function GetNumEdges() : int { return edgeA.length; }
function GetEdgeStart(edge:int) : Vector2 { return pts[ edgeA[edge] ]; }
function GetEdgeEnd(edge:int) : Vector2 { return pts[ edgeB[edge] ]; }
function DebugDraw( color:Color, dur:float )
{
for( var e = 0; e < edgeA.length; e++ )
{
var a = edgeA[e];
var b = edgeB[e];
Debug.DrawLine( Utils.ToVector3( pts[a]), Utils.ToVector3(pts[b]), color, dur, false );
}
}
function ScalePoints( s:float )
{
if( pts != null ) {
for( var i = 0; i < pts.length; i++ )
pts[i] *= s;
}
}
//----------------------------------------
// Reflects along the given line
// keepRight - which side of the line should be kept
// This adds new edges with proper orientation
// mirrorOrientation - if true, then orientation will be _mirrored_ instead of consistent
//----------------------------------------
function Reflect( l0:Vector2, l1:Vector2, keepRight:boolean, mirrorOrientation:boolean )
{
var npts = pts.length;
var i = 0;
if( !keepRight )
{
// just swap the two
var temp = l0;
l0 = l1;
l1 = temp;
}
var lineDir = (l1-l0).normalized;
var rightDir = -1 * Math2D.PerpCCW( lineDir ).normalized;
// see which points are on the right side
var ptIsOnRight = new boolean[ npts ];
for( i = 0; i < npts; i++ )
{
var toPt = (pts[i] - l0).normalized;
var dotp = Vector2.Dot( toPt, rightDir );
if( Mathf.Abs(dotp) < 1e-4)
{
ptIsOnRight[i] = false;
// nudge it into the left half-space a little bit to avoid creating self-intersecting polygons
pts[i] -= rightDir*1e-4;
}
else
ptIsOnRight[i] = (dotp > 0 );
}
// keep right points and add their reflections
var newPts = new Array();
var old2ref = new int[ npts ];
var old2new = new int[ npts ];
for( i = 0; i < npts; i++ )
{
if( ptIsOnRight[i] )
{
newPts.Push( pts[i] );
old2new[i] = newPts.length-1;
// add reflection
newPts.Push( Math2D.Reflect2D( pts[i], l0, l1 ) );
old2ref[i] = newPts.length-1;
}
}
// go through edges
var newA = new Array();
var newB = new Array();
for( i = 0; i < edgeA.length; i++ )
{
var a = edgeA[i];
var b = edgeB[i];
if( ptIsOnRight[a] && ptIsOnRight[b] )
{
// yay add both this one and its reflection
newA.Push( old2new[a] );
newB.Push( old2new[b] );
if( mirrorOrientation ) {
newB.Push( old2ref[b] );
newA.Push( old2ref[a] );
}
else {
// note the opposite direction
newA.Push( old2ref[b] );
newB.Push( old2ref[a] );
}
}
else if( ptIsOnRight[a] && !ptIsOnRight[b] )
{
// add the intersection point
var intx = Math2D.Intersect2DLines( l0, l1, pts[a], pts[b] );
newPts.Push( intx );
var c = newPts.length-1;
// register new edges
newA.Push( old2new[a] );
newB.Push( c );
// now its reflection with opposite direction
if( mirrorOrientation ) {
newB.Push( c );
newA.Push( old2ref[a] );
}
else {
newA.Push( c );
newB.Push( old2ref[a] );
}
}
else if( !ptIsOnRight[a] && ptIsOnRight[b] )
{
// add the intersection point
intx = Math2D.Intersect2DLines( l0, l1, pts[a], pts[b] );
newPts.Push( intx );
c = newPts.length-1;
// left to center
if( mirrorOrientation ) {
newB.Push( old2ref[b] );
newA.Push( c );
}
else {
newA.Push( old2ref[b] );
newB.Push( c );
}
// center to original
newA.Push( c );
newB.Push( old2new[b] );
}
else
{
// edge is completely on left side - ignore
}
}
pts = newPts.ToBuiltin(Vector2);
edgeA = newA.ToBuiltin(int);
edgeB = newB.ToBuiltin(int);
}
function Reflect( l0:Vector2, l1:Vector2, keepRight:boolean )
{
Reflect( l0, l1, keepRight, false );
}
function Append( other:Mesh2D )
{
if( pts == null ) pts = new Vector2[0];
if( edgeA == null ) edgeA = new int[0];
if( edgeB == null ) edgeB = new int[0];
var oldNumPts = pts.length;
var oldNumEdges = edgeA.length;
pts = Utils.Concatenate( pts, other.pts );
edgeA = Utils.Concatenate( edgeA, other.edgeA );
edgeB = Utils.Concatenate( edgeB, other.edgeB );
// need to increment other edge indices
for( var i = 0; i < other.edgeA.length; i++ )
{
edgeA[ oldNumEdges + i ] += oldNumPts;
edgeB[ oldNumEdges + i ] += oldNumPts;
}
}
//----------------------------------------
// This just does a per-point test, which is necessary and sufficient for
// complete containment
//----------------------------------------
function ContainedBy( r:Rect ) : boolean
{
for( var i = 0; i < pts.length; i++ ) {
if( !r.Contains( pts[i] ) )
return false;
}
return true;
}
//----------------------------------------
// Assumes that the current mesh is "manifold", ie. each vertex has exactly 2 incident edges
//----------------------------------------
function GetEdgeLoop( startEid:int ) : List.<int>
{
var loop = new List.<int>();
loop.Add( startEid );
var prevEid = startEid;
while( true ) {
// check if we're complete yet
if( edgeA[startEid] == edgeB[prevEid] )
// done - found the whole loop
break;
for( var nextEid = 0; nextEid < edgeA.length; nextEid++ ) {
if( edgeA[nextEid] == edgeB[prevEid] ) {
// got next one
loop.Add(nextEid);
prevEid = nextEid;
break;
}
}
}
return loop;
}
}
//----------------------------------------
// For efficient vertex-neighbor queries
//----------------------------------------
class PolyVertexNbors
{
private var data:int[];
function GetPrev( vid:int ):int { return data[ 2*vid + 0 ]; }
function GetNext( vid:int ):int { return data[ 2*vid + 1 ]; }
function SetPrev( vid:int, nbor:int ) { data[ 2*vid + 0 ] = nbor; }
function SetNext( vid:int, nbor:int ) { data[ 2*vid + 1 ] = nbor; }
function AreNeighbors( a:int, b:int ) {
return GetPrev( a ) == b || GetPrev( b ) == a;
}
function IsUsed( vid:int ) { return data[2*vid+0] != -1; }
function Reset( poly:Mesh2D, isClockwise:boolean )
{
data = new int[ 2*poly.GetNumVertices() ];
for( var i = 0; i < data.length; i++ )
data[i] = -1;
for( var eid = 0; eid < poly.GetNumEdges(); eid++ )
{
var a = poly.edgeA[ eid ];
var b = poly.edgeB[ eid ];
if( isClockwise ) {
a = poly.edgeB[ eid ];
b = poly.edgeA[ eid ];
}
SetPrev( b, a );
SetNext( a, b );
}
}
// a variant for a sub-polygon
function Reset( numVerts:int, edge2verts:List.<int>, activeEdges:List.<int> )
{
data = new int[ 2*numVerts ];
for( var i = 0; i < 2*numVerts; i++ )
data[i] = -1;
for( var edgeNum = 0; edgeNum < activeEdges.Count; edgeNum++ ) {
var eid = activeEdges[edgeNum];
var a = edge2verts[ 2*eid+0 ];
var b = edge2verts[ 2*eid+1 ];
SetPrev( b, a );
SetNext( a, b );
}
}
}
class Vector2IdPair {
var v : Vector2;
var id : int;
static function CompareByX( a:Vector2IdPair, b:Vector2IdPair ) : int {
return ProGeo.CompareByXThenY( a.v, b.v );
}
}
class TriIndices {
var verts = new int[3];
}
//----------------------------------------
// Helper class for simple poly triangulation
//----------------------------------------
class MonotoneDecomposition
{
enum VertType { REGULAR_TOP, REGULAR_BOTTOM, START, END, MERGE, SPLIT };
//----------------------------------------
// Pointers to helper info
//----------------------------------------
private var poly:Mesh2D;
private var edge2verts:List.<int>;
private var sortedVerts:List.<Vector2IdPair>;
private var nbors:PolyVertexNbors;
//----------------------------------------
// Internal state
//----------------------------------------
class HelperInfo {
var vid:int;
var type:VertType;
var topPieceId:int;
var botPieceId:int;
function IsMerge() : boolean { return type == VertType.MERGE; }
}
private var edgeHelper:List.<HelperInfo> = null;
private var edgePieceId:List.<int> = null;
private var numPieces:int = 0;
private var vert2prevEdge = new List.<int>();
private var vert2nextEdge = new List.<int>();
private var vert2type = new List.<String>();
private var currSid:int;
function GetVertexType(vid:int) : String { return vert2type[vid]; }
function GetNumPieces() { return numPieces; }
function GetEdgePieceId(eid:int)
{
Utils.Assert(eid < edgePieceId.Count );
return edgePieceId[eid];
}
//----------------------------------------
// Performs the plane sweep algorithm and adds edges for a
// monotone-polygon decompostion of the given polygon
//----------------------------------------
function Reset(
_poly:Mesh2D,
_edge2verts:List.<int>, // this will be modified with new edges
_sortedVerts:List.<Vector2IdPair>,
_nbors:PolyVertexNbors )
{
poly = _poly;
edge2verts = _edge2verts;
sortedVerts = _sortedVerts;
nbors = _nbors;
currSid = 0;
//----------------------------------------
// Build vert2edge tables
//----------------------------------------
var NE = edge2verts.Count/2;
var NV = poly.pts.length;
vert2prevEdge = new List.<int>(NV);
vert2nextEdge = new List.<int>(NV);
vert2type = new List.<String>(NV);
for( var i = 0; i < NV; i++ ) {
vert2prevEdge.Add(-1);
vert2nextEdge.Add(-1);
vert2type.Add("-");
}
for( var eid = 0; eid < NE; eid++ ) {
vert2nextEdge[ edge2verts[ 2*eid + 0 ] ] = eid;
vert2prevEdge[ edge2verts[ 2*eid + 1 ] ] = eid;
}
// check
for( i = 0; i < NV; i++ ) {
Utils.Assert( vert2nextEdge[i] != -1, 'vert '+i+' does not have a next!');
Utils.Assert( vert2prevEdge[i] != -1, 'vert '+i+' does not have a prev!');
}
//----------------------------------------
// Init swept edges table
//----------------------------------------
edgeHelper = new List.<HelperInfo>(NE);
edgePieceId = new List.<int>(NE);
for( eid = 0; eid < NE; eid++ ) {
edgeHelper.Add(null);
edgePieceId.Add(-1);
}
numPieces = 0;
}
function GetEdgeStart( eid:int ) { return poly.pts[ edge2verts[2*eid+0] ]; }
function GetEdgeEnd( eid:int ) { return poly.pts[ edge2verts[2*eid+1] ]; }
//----------------------------------------
// TODO - this could be optimized...somehow?
//----------------------------------------
function FindEdgeAbove( p:Vector2 ) : int
{
var bestEid = -1;
var bestDist = 0.0;
for( var eid = 0; eid < edgeHelper.Count; eid++ ) {
if( edgeHelper[eid] != null ) {
// edge is still in sweep
var y = Math2D.EvalLineAtX( GetEdgeStart(eid), GetEdgeEnd(eid), p.x );
if( y > p.y ) {
var dist = y-p.y;
if( bestEid == -1 || dist < bestDist ) {
bestEid = eid;
bestDist = dist;
}
}
}
}
return bestEid;
}
//----------------------------------------
//
//----------------------------------------
function DebugDrawActiveEdges( c:Color, diagColor:Color )
{
// draw active edges
for( var eid = 0; eid < edgeHelper.Count; eid++ ) {
if( edgeHelper[eid] != null ) {
Debug.DrawLine( GetEdgeStart(eid), GetEdgeEnd(eid), c );
}
}
// draw added diagonals
for( eid = edgeHelper.Count; eid < edge2verts.Count/2; eid++ ) {
Debug.DrawLine( GetEdgeStart(eid), GetEdgeEnd(eid), diagColor );
}
}
//----------------------------------------
// Stuff for polygon triangulation
//----------------------------------------
function EvalVertType( vid:int ) : VertType
{
var pos = poly.pts[ vid ];
var prevPos = poly.pts[ nbors.GetPrev( vid ) ];
var nextPos = poly.pts[ nbors.GetNext( vid ) ];
var prevCmp = ProGeo.CompareByXThenY( prevPos, pos );
var nextCmp = ProGeo.CompareByXThenY( nextPos, pos );
if( prevCmp == nextCmp ) {
// both on same "side", cannot be colinear
if( prevCmp < 0 ) {
// both on left
// assume CCW
if( Math2D.IsLeftOfLine( nextPos, prevPos, pos ) ) {
return VertType.END;
} else {
return VertType.MERGE;
}
} else {
// both on right
if( Math2D.IsLeftOfLine( nextPos, prevPos, pos ) ) {
return VertType.START;
} else {
return VertType.SPLIT;
}
}
} else {
if( prevCmp < 0 )
return VertType.REGULAR_BOTTOM;
else
return VertType.REGULAR_TOP;
}
}
// Returns the piece ID of the BOTTOM piece if diagonals were added. Otherwise, -1
private function AddDiagonalIfMergeHelper( eid:int, otherVid:int, returnBot:boolean ) : int
{
if( !Utils.Assert( eid < edgeHelper.Count, "edgeId = " +eid+ " edgeHelper.Count = "+edgeHelper.Count ) )
return -1;
if( !Utils.Assert( eid >= 0, "edgeId = "+eid ) )
return -1;
if( edgeHelper[ eid ] != null && edgeHelper[ eid ].IsMerge() )
{
var helper = GetHelper(eid);
Utils.Assert( helper.topPieceId != -1 );
Utils.Assert( helper.botPieceId != -1 );
AddDoubledDiagonal( helper.vid, otherVid, helper.topPieceId, helper.botPieceId );
if( returnBot )
return helper.botPieceId;
else
return helper.topPieceId;
}
else
return -1;
}
private function AddDiagonalIfMergeHelper( eid:int, otherVid:int )
{
AddDiagonalIfMergeHelper( eid, otherVid, false );
}
private function SetHelper( eid:int, vid:int, type:VertType, topPid:int, botPid:int )
{
var info = edgeHelper[eid];
if( info == null )
{
info = new HelperInfo();
edgeHelper[eid] = info;
}
info.vid = vid;
info.type = type;
info.topPieceId = topPid;
info.botPieceId = botPid;
}
private function GetHelper(eid:int)
{
return edgeHelper[eid];
}
private function DeactivateEdge( eid:int )
{
edgeHelper[ eid ] = null;
}
// The top/bot terminology assumes v1->v2 is left->right
private function AddDoubledDiagonal( v1:int, v2:int, topPieceId:int, botPieceId:int )
{
edge2verts.Add( v1 );
edge2verts.Add( v2 );
edge2verts.Add( v2 );
edge2verts.Add( v1 );
edgePieceId.Add( topPieceId );
edgePieceId.Add( botPieceId );
}
//----------------------------------------
// Performs one step of the plane sweep algo.
// Returns true if more steps are needed
//----------------------------------------
function Step( verbose:boolean ) : boolean
{
// safety
if( currSid >= sortedVerts.Count )
return false;
var NV = poly.pts.length;
var currVid = sortedVerts[ currSid ].id;
var currType = EvalVertType( currVid );
var e1 = vert2prevEdge[currVid];
var e2 = vert2nextEdge[currVid];
var aboveEdge = -1;
var botPieceId = -1;
var topPieceId = -1;
var pieceId = -1;
if( currType == VertType.START )
{
vert2type[currVid] = "S";
Utils.Assert( edgePieceId[e1] == -1 );
Utils.Assert( edgePieceId[e2] == -1 );
pieceId = numPieces++;
SetHelper( e1, currVid, currType, pieceId, pieceId );
edgePieceId[e1] = pieceId;
edgePieceId[e2] = pieceId;
}
else if( currType == VertType.END )
{
vert2type[currVid] = "E";
Utils.Assert( edgePieceId[e1] != -1 );
Utils.Assert( edgePieceId[e2] != -1 );
if( GetHelper(e1) != null && GetHelper(e1).IsMerge() )
{
Utils.Assert( edgePieceId[e1] == GetHelper(e1).botPieceId );
Utils.Assert( edgePieceId[e2] == GetHelper(e1).topPieceId );
}
// I don't think e1 should ever be active, since it's a "bottom" edge
Utils.Assert( GetHelper(e1) == null );
//AddDiagonalIfMergeHelper( e1, currVid );
//DeactivateEdge( e1 );
AddDiagonalIfMergeHelper( e2, currVid );
DeactivateEdge( e2 );
}
else if( currType == VertType.SPLIT ) {
vert2type[currVid] = "P";
Utils.Assert( edgePieceId[e1] == -1 );
Utils.Assert( edgePieceId[e2] == -1 );
aboveEdge = FindEdgeAbove( poly.pts[currVid] );
Utils.Assert( aboveEdge != -1 );
var helper = GetHelper(aboveEdge);
Utils.Assert( helper.topPieceId != -1 );
Utils.Assert( helper.botPieceId != -1 );
Utils.Assert( helper.type != VertType.END );
if( helper.type == VertType.MERGE )
{
Utils.Assert( helper.topPieceId != helper.botPieceId );
AddDoubledDiagonal( helper.vid, currVid, helper.topPieceId, helper.botPieceId );
edgePieceId[e1] = helper.botPieceId;
edgePieceId[e2] = helper.topPieceId;
SetHelper( aboveEdge, currVid, currType, helper.topPieceId, helper.topPieceId );
SetHelper( e1, currVid, currType, edgePieceId[e1], edgePieceId[e1] );
}
else if( vert2prevEdge[helper.vid] == aboveEdge )
{
Utils.Assert( helper.type == VertType.REGULAR_TOP || helper.type == VertType.START || helper.type == VertType.SPLIT );
pieceId = numPieces++;
AddDoubledDiagonal( helper.vid, currVid, pieceId, helper.botPieceId );
edgePieceId[ aboveEdge ] = pieceId;
edgePieceId[e1] = helper.botPieceId;
edgePieceId[e2] = pieceId;
SetHelper( aboveEdge, currVid, currType, pieceId, pieceId );
SetHelper( e1, currVid, currType, edgePieceId[e1], edgePieceId[e1] );
}
else
{
Utils.Assert( helper.type == VertType.REGULAR_BOTTOM || helper.type == VertType.SPLIT );
pieceId = numPieces++;
AddDoubledDiagonal( helper.vid, currVid, helper.topPieceId, pieceId );
edgePieceId[ vert2nextEdge[helper.vid] ] = pieceId;
edgePieceId[e1] = pieceId;
edgePieceId[e2] = helper.topPieceId;
SetHelper( aboveEdge, currVid, currType, helper.topPieceId, helper.topPieceId );
SetHelper( e1, currVid, currType, edgePieceId[e1], edgePieceId[e1] );
}
}
else if( currType == VertType.MERGE ) {
vert2type[currVid] = "M";
Utils.Assert( edgePieceId[e1] != -1 );
Utils.Assert( edgePieceId[e2] != -1 );
Utils.Assert( edgePieceId[e1] != edgePieceId[e2] );
// e1 is a bottom edge, so never should be active
Utils.Assert( GetHelper(e1) == null );
//AddDiagonalIfMergeHelper( e1, currVid );
//DeactivateEdge( e1 );
// Handle bottom side
botPieceId = AddDiagonalIfMergeHelper( e2, currVid, true );
DeactivateEdge( e2 );
if( botPieceId == -1 )
botPieceId = edgePieceId[e2];
// Handle top side
aboveEdge = FindEdgeAbove( poly.pts[currVid] );
topPieceId = AddDiagonalIfMergeHelper( aboveEdge, currVid, false );
if( topPieceId == -1 )
topPieceId = edgePieceId[e1];
SetHelper( aboveEdge, currVid, currType, topPieceId, botPieceId );
}
else if( currType == VertType.REGULAR_TOP ) {
vert2type[currVid] = "T";
Utils.Assert( edgePieceId[e1] == -1 );
Utils.Assert( edgePieceId[e2] != -1 );
botPieceId = AddDiagonalIfMergeHelper( e2, currVid, true );
DeactivateEdge( e2 );
if( botPieceId == -1 )
botPieceId = edgePieceId[e2];
edgePieceId[e1] = botPieceId;
SetHelper(e1, currVid, currType, botPieceId, botPieceId);
}
else if( currType == VertType.REGULAR_BOTTOM ) {
vert2type[currVid] = "B";
Utils.Assert( edgePieceId[e1] != -1 );
Utils.Assert( edgePieceId[e2] == -1 );
Utils.Assert( GetHelper(e1) == null );
Utils.Assert( GetHelper(e2) == null );
//topPieceId = AddDiagonalIfMergeHelper( e1, currVid, false );
//DeactivateEdge( e1 );
//if( topPieceId == -1 )
//edgePieceId[e2] = edgePieceId[e1];
//else
//{
//Utils.Assert(false, "I don't ever expect this to happen, since merge-helpers are only ever added to 'above' edges");
// If this actually does happen, then I need to handle the fixing of prev/next edges for this helper
//edgePieceId[e2] = topPieceId;
//}
// Steve: This is my "bug fix" that both algo descriptions seem to ignore, but it's necessary to keep the helper invariant
aboveEdge = FindEdgeAbove( poly.pts[currVid] );
topPieceId = AddDiagonalIfMergeHelper( aboveEdge, currVid, false );
if( topPieceId == -1 )
topPieceId = edgePieceId[e1];
edgePieceId[e2] = topPieceId;
SetHelper( aboveEdge, currVid, currType, topPieceId, topPieceId );
}
vert2type[currVid] += "-"+currSid;
// step
currSid++;
var moreSteps = currSid < sortedVerts.Count;