-
Notifications
You must be signed in to change notification settings - Fork 16
/
tessellator.zig
1930 lines (1742 loc) · 81.3 KB
/
tessellator.zig
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
const std = @import("std");
const stdx = @import("stdx");
const builtin = @import("builtin");
const t = stdx.testing;
const Vec2 = stdx.math.Vec2;
const vec2 = Vec2.init;
const RbTree = stdx.ds.RbTree;
const dassert = stdx.debug.dassert;
const PooledHandleSLLBuffer = stdx.ds.PooledHandleSLLBuffer;
const trace = stdx.debug.tracy.trace;
const log_ = stdx.log.scoped(.tessellator);
const DeferredVertexNodeId = u16;
const NullId = stdx.ds.CompactNull(DeferredVertexNodeId);
const EventQueue = std.PriorityQueue(u32, *std.ArrayList(Event), compareEventIdx);
const debug = false and builtin.mode == .Debug;
pub fn log(comptime format: []const u8, args: anytype) void {
if (debug) {
log_.debug(format, args);
}
}
pub const Tessellator = struct {
/// Buffers.
verts: std.ArrayList(InternalVertex),
events: std.ArrayList(Event),
event_q: EventQueue,
sweep_edges: RbTree(u16, SweepEdge, Event, compareSweepEdge),
deferred_verts: PooledHandleSLLBuffer(DeferredVertexNodeId, DeferredVertexNode),
/// Verts to output.
/// No duplicate verts will be outputed to reduce size footprint.
/// Since some verts won't be discovered until during the processing of events (edge intersections),
/// verts are added as the events are processed. As a result, the verts are also in order y-asc and x-asc.
out_verts: std.ArrayList(Vec2),
/// Triangles to output are triplets of indexes that point to verts. They are in ccw direction.
out_idxes: std.ArrayList(u16),
cur_x: f32,
cur_y: f32,
cur_out_vert_idx: u16,
pub fn init(self: *Tessellator, alloc: std.mem.Allocator) void {
self.* = .{
.verts = std.ArrayList(InternalVertex).init(alloc),
.events = std.ArrayList(Event).init(alloc),
.event_q = undefined,
.sweep_edges = RbTree(u16, SweepEdge, Event, compareSweepEdge).init(alloc, undefined),
.deferred_verts = PooledHandleSLLBuffer(DeferredVertexNodeId, DeferredVertexNode).init(alloc),
.out_verts = std.ArrayList(Vec2).init(alloc),
.out_idxes = std.ArrayList(u16).init(alloc),
.cur_x = undefined,
.cur_y = undefined,
.cur_out_vert_idx = undefined,
};
self.event_q = EventQueue.init(alloc, &self.events);
}
pub fn deinit(self: *Tessellator) void {
self.verts.deinit();
self.events.deinit();
self.event_q.deinit();
self.sweep_edges.deinit();
self.deferred_verts.deinit();
self.out_verts.deinit();
self.out_idxes.deinit();
}
pub fn clearBuffers(self: *Tessellator) void {
self.verts.clearRetainingCapacity();
self.events.clearRetainingCapacity();
self.event_q.len = 0;
self.sweep_edges.clearRetainingCapacity();
self.deferred_verts.clearRetainingCapacity();
self.out_verts.clearRetainingCapacity();
self.out_idxes.clearRetainingCapacity();
}
pub fn triangulatePolygon(self: *Tessellator, polygon: []const Vec2) !void {
try self.triangulatePolygons(&.{polygon});
}
/// Perform a plane sweep to triangulate a complex polygon in one pass.
/// The output returns ccw triangle vertices and indexes ready to be fed into the gpu.
/// This uses Bentley-Ottmann to handle self intersecting edges.
/// Rules are followed to partition into y-monotone polygons and triangulate them.
/// This is ported from the JS implementation (tessellator.js) where it is easier to prototype.
/// Since the number of verts and indexes is not known beforehand, the output is an ArrayList.
/// TODO: See if inline callbacks would be faster to directly push data to the batcher buffer.
pub fn triangulatePolygons(self: *Tessellator, polygons: []const []const Vec2) !void {
// Construct the initial events by traversing the polygon.
for (polygons) |polygon| {
try self.initEvents(polygon, false);
}
self.startProcessEvents() catch |err| {
for (polygons) |polygon| {
dumpPolygon(polygon);
}
return err;
};
}
/// Uses index slice as polygons.
pub fn triangulatePolygons2(self: *Tessellator, pts: []const Vec2, polygons: []const stdx.IndexSlice(u32)) !void {
for (polygons) |slice| {
const polygon = pts[slice.start..slice.end];
try self.initEvents(polygon, false);
}
self.startProcessEvents() catch |err| {
for (polygons) |slice| {
dumpPolygon(pts[slice.start..slice.end]);
}
return err;
};
}
fn startProcessEvents(self: *Tessellator) !void {
self.cur_x = std.math.f32_min;
self.cur_y = std.math.f32_min;
self.cur_out_vert_idx = std.math.maxInt(u16);
// Process events.
while (self.event_q.removeOrNull()) |e_id| {
try self.processEvent(e_id, false);
}
}
/// Initializes the events only.
pub fn debugTriangulatePolygons(self: *Tessellator, polygons: []const []const Vec2) !void {
for (polygons) |polygon| {
try self.initEvents(polygon, true);
}
self.cur_x = std.math.f32_min;
self.cur_y = std.math.f32_min;
self.cur_out_vert_idx = std.math.maxInt(u16);
}
pub fn debugTriangulatePolygons2(self: *Tessellator, pts: []const Vec2, polygons: []const stdx.IndexSlice(u32)) !void {
for (polygons) |slice| {
const polygon = pts[slice.start..slice.end];
try self.initEvents(polygon, true);
}
self.cur_x = std.math.f32_min;
self.cur_y = std.math.f32_min;
self.cur_out_vert_idx = std.math.maxInt(u16);
}
/// Process the next event. This can be used with debugTriangulatePolygons.
pub fn debugProcessNext(self: *Tessellator, alloc: std.mem.Allocator) !?DebugTriangulateStepResult {
const e_id = self.event_q.removeOrNull() orelse return null;
self.processEvent(e_id, true) catch {
return DebugTriangulateStepResult{
.has_error = true,
.event = self.events.items[e_id],
.sweep_edges = self.sweep_edges.allocValuesInOrder(alloc),
.out_verts = try alloc.dupe(Vec2, self.out_verts.items),
.out_idxes = try alloc.dupe(u16, self.out_idxes.items),
.verts = try alloc.dupe(InternalVertex, self.verts.items),
.deferred_verts = try alloc.dupe(PooledHandleSLLBuffer(DeferredVertexNodeId, DeferredVertexNode).Node, self.deferred_verts.nodes.buf.items),
};
};
return DebugTriangulateStepResult{
.has_error = false,
.event = self.events.items[e_id],
.sweep_edges = self.sweep_edges.allocValuesInOrder(alloc),
.out_verts = try alloc.dupe(Vec2, self.out_verts.items),
.out_idxes = try alloc.dupe(u16, self.out_idxes.items),
.verts = try alloc.dupe(InternalVertex, self.verts.items),
.deferred_verts = try alloc.dupe(PooledHandleSLLBuffer(DeferredVertexNodeId, DeferredVertexNode).Node, self.deferred_verts.nodes.buf.items),
};
}
fn processEvent(self: *Tessellator, e_id: u32, comptime Debug: bool) !void {
_ = Debug;
const t_ = trace(@src());
defer t_.end();
const sweep_edges = &self.sweep_edges;
const e = self.events.items[e_id];
// If the point changed, allocate a new out vertex index.
if (e.vert_x != self.cur_x or e.vert_y != self.cur_y) {
self.out_verts.append(vec2(e.vert_x, e.vert_y)) catch unreachable;
self.cur_out_vert_idx +%= 1;
self.cur_x = e.vert_x;
self.cur_y = e.vert_y;
}
// Set the out vertex index on the event.
self.verts.items[e.vert_idx].out_idx = self.cur_out_vert_idx;
if (debug) {
const tag_str: []const u8 = if (e.tag == .Start) "Start" else "End";
log("--process event {}, ({},{}) {s} {s}", .{e.vert_idx, e.vert_x, e.vert_y, tag_str, edgeToString(e.edge)});
log("sweep edges: ", .{});
var mb_cur = sweep_edges.first();
while (mb_cur) |cur| {
const se = sweep_edges.get(cur).?;
log("{} -> {}", .{se.edge.start_idx, se.edge.end_idx});
mb_cur = sweep_edges.getNext(cur);
}
}
if (e.tag == .Start) {
// Check to remove a previous left edge and continue it's sub-polygon vertex queue.
sweep_edges.ctx = e;
const new_id = sweep_edges.insert(SweepEdge.init(e, self.verts.items)) catch unreachable;
const new = sweep_edges.getPtr(new_id).?;
log("start new sweep edge {}", .{new_id});
var mb_left_id = sweep_edges.getPrev(new_id);
// Update winding based on what is to the left.
if (mb_left_id == null) {
new.interior_is_left = false;
} else {
new.interior_is_left = !sweep_edges.get(mb_left_id.?).?.interior_is_left;
}
if (new.interior_is_left) {
log("initially interior to the left", .{});
// Initially appears to be a right edge but if it connects to the previous left, it becomes a left edge.
var left = sweep_edges.getPtrNoCheck(mb_left_id.?);
const e_vert_out_idx = self.verts.items[e.vert_idx].out_idx;
if (left.end_event_vert_uniq_idx == e_vert_out_idx) {
// Remove the previous ended edge, and takes it's place as the left edge.
defer sweep_edges.remove(mb_left_id.?) catch unreachable;
new.interior_is_left = false;
log("continuation from prev edge, interior to the right", .{});
// Previous left edge and this new edge forms a regular left angle.
// Check for bad up cusp.
if (left.bad_up_cusp_uniq_idx != NullId) {
// This monotone polygon (a) should already have run it's triangulate steps from the left edge's end event.
// \ /
// a \/ b
// ^ Bad cusp.
// \_
// ^ End event from left edge happened before, currently processing start event for the new connected edge.
// A line is connected from this vertex to the bad cusp to ensure that polygon (a) is monotone and polygon (b) is monotone.
// Since polygon (a) already ran it's triangulate step, it's done from this side of the polygon.
// This start event will create a new sweep edge, so transfer the deferred queue from the bad cusp's right side. (it is now the queue for this new left edge).
const bad_right = sweep_edges.getNoCheck(left.bad_up_cusp_right_sweep_edge_id);
bad_right.dumpQueue(self);
new.deferred_queue = bad_right.deferred_queue;
new.deferred_queue_size = bad_right.deferred_queue_size;
new.cur_side = bad_right.cur_side;
// Also run triangulate on polygon (b) for the new vertex since the end event was already run for polygon (a).
self.triangulateLeftStep(new, e.vert_idx, self.verts.items[e.vert_idx]);
left.bad_up_cusp_uniq_idx = NullId;
sweep_edges.removeDetached(left.bad_up_cusp_right_sweep_edge_id);
log("FIX BAD UP CUSP", .{});
new.dumpQueue(self);
} else {
new.deferred_queue = left.deferred_queue;
new.deferred_queue_size = left.deferred_queue_size;
new.cur_side = left.cur_side;
}
} else if (left.start_event_vert_uniq_idx == e_vert_out_idx) {
// Down cusp.
log("DOWN CUSP", .{});
}
} else {
log("initially interior to the right", .{});
// Initially appears to be a left edge but if it connects to a previous right, it becomes a right edge.
if (mb_left_id != null) {
const vert = self.verts.items[e.vert_idx];
// left edge has interior to the left.
var left = sweep_edges.get(mb_left_id.?).?;
if (left.end_event_vert_uniq_idx == vert.out_idx) {
// Remove previous ended edge.
sweep_edges.remove(mb_left_id.?) catch unreachable;
new.interior_is_left = true;
log("changed to interior is left", .{});
} else if (left.start_event_vert_uniq_idx == vert.out_idx) {
// Linked to previous start event's vertex.
// Handle bad down cusp.
// \ \/
// \ b
// \--a
// \ v Bad down cusp.
// \ /\ /
// \ / \ /
// The bad cusp is linked to the lowest visible right vertex seen from the left edge.
// If vertex (a) exists that would be connected to the cusp.
// If it didn't exist the next lowest would be (b) a bad up cusp.
const left_left_id = sweep_edges.getPrev(mb_left_id.?).?;
const left_left = sweep_edges.getPtrNoCheck(left_left_id);
log("handle bad down cusp {}", .{left_left.lowest_right_vert_idx});
if (left_left.lowest_right_vert_idx == NullId) {
log("expected lowest right vert", .{});
return error.InvalidState;
}
const low_poly_edge = sweep_edges.getPtrNoCheck(left_left.lowest_right_vert_sweep_edge_id);
if (left_left_id == left_left.lowest_right_vert_sweep_edge_id) {
// Lowest right point has a monotone subpolygon to the right.
if (left_left.lowest_right_vert_idx == left_left.vert_idx) {
// Pass on the vertex queue.
new.deferred_queue = low_poly_edge.deferred_queue;
new.deferred_queue_size = low_poly_edge.deferred_queue_size;
new.cur_side = low_poly_edge.cur_side;
low_poly_edge.deferred_queue = NullId;
low_poly_edge.deferred_queue_size = 0;
self.triangulateLeftStep(new, e.vert_idx, vert);
// Cut off the existing left monotone polygon.
left_left.deferred_queue = NullId;
left_left.deferred_queue_size = 0;
left_left.cur_side = .Right;
left_left.enqueueDeferred(left_left.lowest_right_vert_idx, self.verts.items[left_left.lowest_right_vert_idx], self);
if (vert.out_idx != self.verts.items[left_left.lowest_right_vert_idx].out_idx) {
left_left.enqueueDeferred(e.vert_idx, vert, self);
}
left_left.lowest_right_vert_idx = e.vert_idx;
} else {
// Initialize a new right side monotone polygon.
new.enqueueDeferred(left_left.lowest_right_vert_idx, self.verts.items[left_left.lowest_right_vert_idx], self);
new.enqueueDeferred(e.vert_idx, vert, self);
new.cur_side = .Left;
// Triangulate on the monotone polygon to the left of the lowest right point.
self.triangulateRightStep(left_left, e.vert_idx, vert);
left_left.lowest_right_vert_idx = e.vert_idx;
}
} else {
// Lowest right point has a monotone subpolygon to the left and right.
// Most likely a bad up cusp as well, so reset it since connecting to the lowest right fixes it.
left_left.bad_up_cusp_uniq_idx = NullId;
self.triangulateLeftStep(low_poly_edge, e.vert_idx, vert);
// Pass on the vertex queue.
new.deferred_queue = low_poly_edge.deferred_queue;
new.deferred_queue_size = low_poly_edge.deferred_queue_size;
new.cur_side = low_poly_edge.cur_side;
low_poly_edge.deferred_queue = NullId;
low_poly_edge.deferred_queue_size = 0;
// Triangulate on the monotone polygon to the left of the lowest right point.
self.triangulateRightStep(left_left, e.vert_idx, vert);
left_left.lowest_right_vert_idx = e.vert_idx;
left_left.lowest_right_vert_sweep_edge_id = left_left_id;
}
}
}
}
if (!new.interior_is_left) {
// Even-odd rule.
// Interior is to the right.
const vert = self.verts.items[e.vert_idx];
// Initialize the deferred queue.
if (new.deferred_queue == NullId) {
new.enqueueDeferred(e.vert_idx, vert, self);
new.cur_side = .Left;
log("initialize queue", .{});
new.dumpQueue(self);
}
// The lowest right vert is set initializes to itself.
new.lowest_right_vert_idx = e.vert_idx;
new.lowest_right_vert_sweep_edge_id = new_id;
} else {
// Interior is to the left.
}
// Check intersection with the left. Fetch left again since it could be removed from an up cusp.
mb_left_id = sweep_edges.getPrev(new_id);
if (mb_left_id != null) {
log("check left intersect", .{});
var left = sweep_edges.getPtrNoCheck(mb_left_id.?);
const res = computeTwoEdgeIntersect(new.edge, left.edge);
log("{},{}->{},{} {},{}->{},{} {} {}", .{new.edge.start_pos.x, new.edge.start_pos.y, new.edge.end_pos.x, new.edge.end_pos.y, left.edge.start_pos.x, left.edge.start_pos.y, left.edge.end_pos.x, left.edge.end_pos.y, res.has_intersect, res.t});
if (res.has_intersect and res.t > 0 and res.t < 1) {
self.handleIntersectForStartEvent(new, left, res, vec2(e.vert_x, e.vert_y));
}
}
const mb_right_id = sweep_edges.getNext(new_id);
if (mb_right_id != null) {
// Check for intersection with the edge to the right.
log("check right intersect", .{});
// TODO: Is there a preliminary check to avoid doing the math? One idea is to check the x_slopes but it would need to know
// if the compared edge is pointing down or up.
const right = sweep_edges.getPtrNoCheck(mb_right_id.?);
const res = computeTwoEdgeIntersect(new.edge, right.edge);
if (res.has_intersect and res.t > 0 and res.t < 1) {
self.handleIntersectForStartEvent(new, right, res, vec2(e.vert_x, e.vert_y));
}
}
} else {
// End event.
if (e.invalidated) {
// This end event was invalidated from an intersection event.
return;
}
const active_id = findSweepEdgeForEndEvent(sweep_edges, e) orelse return error.MissingActiveEdge;
const active = sweep_edges.getPtrNoCheck(active_id);
log("active {} {}", .{active.vert_idx, active.to_vert_idx});
const vert = self.verts.items[e.vert_idx];
if (active.interior_is_left) {
// Interior is to the left.
log("interior to the left {}", .{active_id});
const left_id = sweep_edges.getPrev(active_id).?;
const left = sweep_edges.getPtrNoCheck(left_id);
// Check if it has closed the polygon. (up cusp)
if (vert.out_idx == left.end_event_vert_uniq_idx) {
// Check for bad up cusp.
if (left.bad_up_cusp_uniq_idx != NullId) {
const bad_right = sweep_edges.getPtrNoCheck(left.bad_up_cusp_right_sweep_edge_id);
// Close off monotone polygon to the right of the bad up cusp.
self.triangulateLeftStep(bad_right, e.vert_idx, vert);
sweep_edges.removeDetached(left.bad_up_cusp_right_sweep_edge_id);
left.bad_up_cusp_uniq_idx = NullId;
left.lowest_right_vert_idx = e.vert_idx;
left.lowest_right_vert_sweep_edge_id = left_id;
if (bad_right.deferred_queue_size >= 3) {
log("{any}", .{self.out_idxes.items});
bad_right.dumpQueue(self);
stdx.panic("did not expect left over vertices");
}
}
if (left.deferred_queue_size >= 3) {
log("{} {any}", .{left_id, self.out_idxes.items});
left.dumpQueue(self);
stdx.panic("did not expect left over vertices");
}
// Remove the left edge and this edge.
sweep_edges.remove(left_id) catch unreachable;
sweep_edges.remove(active_id) catch unreachable;
} else {
// Regular right side vertex.
// Check for bad up cusp.
if (left.bad_up_cusp_uniq_idx != NullId) {
const bad_right = sweep_edges.getPtrNoCheck(left.bad_up_cusp_right_sweep_edge_id);
// Close off monotone polygon to the right of the bad up cusp.
self.triangulateRightStep(bad_right, e.vert_idx, vert);
left.lowest_right_vert_idx = e.vert_idx;
left.lowest_right_vert_sweep_edge_id = left_id;
sweep_edges.removeDetached(left.bad_up_cusp_right_sweep_edge_id);
left.bad_up_cusp_uniq_idx = NullId;
if (bad_right.deferred_queue_size >= 3) {
log("{any}", .{self.out_idxes.items});
bad_right.dumpQueue(self);
stdx.panic("did not expect left over vertices");
}
}
// Left belongs to the same monotone polygon.
self.triangulateRightStep(left, e.vert_idx, vert);
// Edge is only removed by the next connecting edge.
active.end_event_vert_uniq_idx = vert.out_idx;
}
} else {
// Interior is to the right.
log("interior to the right {}", .{active_id});
const mb_left_id = sweep_edges.getPrev(active_id);
// Check to fix a bad up cusp to the right.
if (active.bad_up_cusp_uniq_idx != NullId) {
const bad_right = sweep_edges.getPtrNoCheck(active.bad_up_cusp_right_sweep_edge_id);
// Close off monotone polygon in between this active edge and the bad up cusp.
self.triangulateLeftStep(active, e.vert_idx, vert);
if (active.deferred_queue_size >= 3) {
log("{any}", .{self.out_idxes.items});
active.dumpQueue(self);
stdx.panic("did not expect left over vertices");
}
active.lowest_right_vert_idx = NullId;
active.lowest_right_vert_sweep_edge_id = NullId;
sweep_edges.removeDetached(active.bad_up_cusp_right_sweep_edge_id);
active.bad_up_cusp_uniq_idx = NullId;
// Extend the monotone polygon to the right of the bad up cusp to this vertex.
self.triangulateLeftStep(bad_right, e.vert_idx, vert);
active.deferred_queue = bad_right.deferred_queue;
active.deferred_queue_size = bad_right.deferred_queue_size;
} else {
active.dumpQueue(self);
self.triangulateLeftStep(active, e.vert_idx, vert);
active.dumpQueue(self);
}
// Check if this forms a bad up cusp with the right edge to the left monotone polygon.
var removed = false;
if (mb_left_id != null) {
log("check to set bad up cusp", .{});
const left = sweep_edges.getNoCheck(mb_left_id.?);
// dump(edgeToString(left_right_edge.edge))
if (vert.out_idx == left.end_event_vert_uniq_idx) {
const left_left_id = sweep_edges.getPrev(mb_left_id.?).?;
const left_left = sweep_edges.getPtrNoCheck(left_left_id);
// Bad up cusp.
left_left.bad_up_cusp_uniq_idx = vert.out_idx;
left_left.bad_up_cusp_right_sweep_edge_id = active_id;
left_left.lowest_right_vert_idx = e.vert_idx;
left_left.lowest_right_vert_sweep_edge_id = active_id;
// Remove the left edge.
sweep_edges.remove(mb_left_id.?) catch unreachable;
// Detach this edge, remove it when the bad up cusp is fixed.
sweep_edges.detach(active_id) catch unreachable;
removed = true;
// Continue.
}
}
if (!removed) {
// Don't remove the left edge of this sub-polygon yet.
// Record the end event's vert so the next start event that continues from this vert can persist the deferred vertices and remove this sweep edge.
// It can also be removed by a End right edge.
active.end_event_vert_uniq_idx = vert.out_idx;
}
}
}
}
inline fn addTriangle(self: *Tessellator, v1_out: u16, v2_out: u16, v3_out: u16) void {
log("triangle {} {} {}", .{v1_out, v2_out, v3_out});
self.out_idxes.appendSlice(&.{v1_out, v2_out, v3_out}) catch unreachable;
}
/// Parses the polygon pts and adds the initial events into the priority queue.
fn initEvents(self: *Tessellator, polygon: []const Vec2, comptime Debug: bool) !void {
_ = Debug;
const t_ = trace(@src());
defer t_.end();
// Allocate enough space for verts.
try self.verts.ensureUnusedCapacity(polygon.len);
// Find the starting point that is not equal to the last vertex point.
// Since we are adding events to a priority queue, we need to make sure each add is final.
const offset_idx = @intCast(u16, self.verts.items.len);
var i: u16 = 0;
const last_pt = polygon[polygon.len-1];
while (i < polygon.len) : (i += 1) {
const pt = polygon[i];
// Add internal vertex even though we are skipping events for it to keep the idxes consistent with the input.
const v_idx = @intCast(u16, self.verts.items.len);
const v = InternalVertex{
.pos = pt,
.src_idx = i,
};
self.verts.appendAssumeCapacity(v);
if (@fabs(last_pt.x - pt.x) > 1e-4 or @fabs(last_pt.y - pt.y) > 1e-4) {
break;
} else {
self.verts.items[v_idx].src_idx = NullId;
}
}
const first_vidx = offset_idx + i;
// Didn't find start point. All points in the polygon are the same.
if (first_vidx == self.verts.items.len) {
return;
}
var last_v = self.verts.items[first_vidx]; // out of bounds
var last_v_idx = first_vidx;
i += 1;
while (i < polygon.len) : (i += 1) {
const v_idx = @intCast(u16, self.verts.items.len);
const v = InternalVertex{
.pos = polygon[i],
.src_idx = i,
};
self.verts.appendAssumeCapacity(v);
if (@fabs(last_v.pos.x - v.pos.x) < 1e-4 and @fabs(last_v.pos.y - v.pos.y) < 1e-4) {
// Don't connect two vertices that are on top of each other.
// Allowing this would require edge cases during event processing to make sure things don't break.
// Push the vertex in anyway so there is consistency with the input.
self.verts.items[self.verts.items.len-1].src_idx = NullId;
continue;
}
const prev_edge = Edge.init(last_v_idx, last_v, v_idx, v);
const event1_idx = @intCast(u32, self.events.items.len);
var event1: Event = undefined;
var event2: Event = undefined;
if (Event.isStartEvent(last_v_idx, prev_edge, self.verts.items)) {
event1 = Event.init(last_v_idx, last_v, prev_edge, .Start);
event2 = Event.init(v_idx, v, prev_edge, .End);
event1.end_event_idx = event1_idx + 1;
} else {
event1 = Event.init(last_v_idx, last_v, prev_edge, .End);
event2 = Event.init(v_idx, v, prev_edge, .Start);
event2.end_event_idx = event1_idx;
}
self.events.append(event1) catch unreachable;
self.event_q.add(event1_idx) catch unreachable;
self.events.append(event2) catch unreachable;
self.event_q.add(event1_idx + 1) catch unreachable;
last_v = v;
last_v_idx = v_idx;
}
// Link last pt to start pt.
const edge = Edge.init(last_v_idx, last_v, first_vidx, self.verts.items[first_vidx]);
const event1_idx = @intCast(u32, self.events.items.len);
var event1: Event = undefined;
var event2: Event = undefined;
if (Event.isStartEvent(last_v_idx, edge, self.verts.items)) {
event1 = Event.init(last_v_idx, last_v, edge, .Start);
event2 = Event.init(first_vidx, self.verts.items[first_vidx], edge, .End);
event1.end_event_idx = event1_idx + 1;
} else {
event1 = Event.init(last_v_idx, last_v, edge, .End);
event2 = Event.init(first_vidx, self.verts.items[first_vidx], edge, .Start);
event2.end_event_idx = event1_idx;
}
self.events.append(event1) catch unreachable;
self.event_q.add(event1_idx) catch unreachable;
self.events.append(event2) catch unreachable;
self.event_q.add(event1_idx + 1) catch unreachable;
}
fn triangulateLeftStep(self: *Tessellator, left: *SweepEdge, vert_idx: u16, vert: InternalVertex) void {
if (left.cur_side == .Left) {
log("same left side", .{});
left.dumpQueue(self);
// Same side.
if (left.deferred_queue_size >= 2) {
var last_id = left.deferred_queue;
var last = self.deferred_verts.getNoCheck(last_id);
if (last.vert_out_idx == vert.out_idx) {
// Ignore this point since it is the same as the last.
return;
}
var cur_id = self.deferred_verts.getNextNoCheck(last_id);
var i: u16 = 0;
while (i < left.deferred_queue_size-1) : (i += 1) {
log("check to add inward tri {} {}", .{last_id, cur_id});
const cur = self.deferred_verts.getNoCheck(cur_id);
const cxp = vec2(last.vert_x - cur.vert_x, last.vert_y - cur.vert_y).cross(vec2(vert.pos.x - last.vert_x, vert.pos.y - last.vert_y));
if (cxp < 0) {
// Bends inwards. Fill triangles until we aren't bending inward.
self.addTriangle(vert.out_idx, cur.vert_out_idx, last.vert_out_idx);
self.deferred_verts.removeAssumeNoPrev(last_id) catch unreachable;
} else {
break;
}
last_id = cur_id;
last = cur;
cur_id = self.deferred_verts.getNextNoCheck(cur_id);
}
if (i > 0) {
const d_vert = self.deferred_verts.insertBeforeHeadNoCheck(last_id, DeferredVertexNode.init(vert_idx, vert)) catch unreachable;
left.deferred_queue = d_vert;
left.deferred_queue_size = left.deferred_queue_size - i + 1;
} else {
left.enqueueDeferred(vert_idx, vert, self);
}
} else {
left.enqueueDeferred(vert_idx, vert, self);
}
} else {
log("changed to left side", .{});
// Changed to left side.
// Automatically create queue size - 1 triangles.
var last_id = left.deferred_queue;
var last = self.deferred_verts.getNoCheck(last_id);
var cur_id = self.deferred_verts.getNextNoCheck(last_id);
var i: u32 = 0;
while (i < left.deferred_queue_size-1) : (i += 1) {
const cur = self.deferred_verts.getNoCheck(cur_id);
self.addTriangle(vert.out_idx, last.vert_out_idx, cur.vert_out_idx);
last_id = cur_id;
last = cur;
cur_id = self.deferred_verts.getNextNoCheck(cur_id);
// Delete last after it's assigned to current.
self.deferred_verts.removeAssumeNoPrev(last_id) catch unreachable;
}
left.dumpQueue(self);
self.deferred_verts.getNodePtrNoCheck(left.deferred_queue).next = NullId;
left.deferred_queue_size = 1;
left.enqueueDeferred(vert_idx, vert, self);
left.cur_side = .Left;
left.dumpQueue(self);
}
}
fn triangulateRightStep(self: *Tessellator, left: *SweepEdge, vert_idx: u16, vert: InternalVertex) void {
if (left.cur_side == .Right) {
log("right side", .{});
// Same side.
if (left.deferred_queue_size >= 2) {
var last_id = left.deferred_queue;
var last = self.deferred_verts.getNoCheck(last_id);
if (last.vert_out_idx == vert.out_idx) {
// Ignore this point since it is the same as the last.
return;
}
var cur_id = self.deferred_verts.getNextNoCheck(last_id);
var i: u16 = 0;
while (i < left.deferred_queue_size-1) : (i += 1) {
const cur = self.deferred_verts.getNoCheck(cur_id);
const cxp = vec2(last.vert_x - cur.vert_x, last.vert_y - cur.vert_y).cross(vec2(vert.pos.x - last.vert_x, vert.pos.y - last.vert_y));
if (cxp > 0) {
// Bends inwards. Fill triangles until we aren't bending inward.
self.addTriangle(vert.out_idx, last.vert_out_idx, cur.vert_out_idx);
self.deferred_verts.removeAssumeNoPrev(last_id) catch unreachable;
} else {
break;
}
last_id = cur_id;
last = cur;
cur_id = self.deferred_verts.getNextNoCheck(cur_id);
}
if (i > 0) {
const d_vert = self.deferred_verts.insertBeforeHeadNoCheck(last_id, DeferredVertexNode.init(vert_idx, vert)) catch unreachable;
left.deferred_queue = d_vert;
left.deferred_queue_size = left.deferred_queue_size - i + 1;
} else {
left.enqueueDeferred(vert_idx, vert, self);
}
} else {
left.enqueueDeferred(vert_idx, vert, self);
}
} else {
log("changed to right side", .{});
var last_id = left.deferred_queue;
var last = self.deferred_verts.getNoCheck(last_id);
var cur_id = self.deferred_verts.getNextNoCheck(last_id);
var i: u32 = 0;
while (i < left.deferred_queue_size-1) : (i += 1) {
const cur = self.deferred_verts.getNoCheck(cur_id);
self.addTriangle(vert.out_idx, cur.vert_out_idx, last.vert_out_idx);
last_id = cur_id;
last = cur;
cur_id = self.deferred_verts.getNextNoCheck(cur_id);
// Delete last after it's assigned to current.
self.deferred_verts.removeAssumeNoPrev(last_id) catch unreachable;
}
self.deferred_verts.getNodePtrNoCheck(left.deferred_queue).next = NullId;
left.deferred_queue_size = 1;
left.enqueueDeferred(vert_idx, vert, self);
left.cur_side = .Right;
left.dumpQueue(self);
}
}
/// Splits two edges at an intersect point.
/// Assumes sweep edges have not processed their end events so they can be reinserted.
/// Does not add new events if an event already exists to the intersect point.
fn handleIntersectForStartEvent(self: *Tessellator, sweep_edge_a: *SweepEdge, sweep_edge_b: *SweepEdge, intersect: IntersectResult, sweep_vert: Vec2) void {
log("split intersect {}", .{intersect});
// The intersect point must lie after the sweep_vert.
if (intersect.y < sweep_vert.y or (intersect.y == sweep_vert.y and intersect.x <= sweep_vert.x)) {
return;
}
var added_events = false;
// Create new intersect vertex.
const intersect_idx = @intCast(u16, self.verts.items.len);
const intersect_v = InternalVertex{
.pos = vec2(intersect.x, intersect.y),
// Generated pt. Doesn't map back to a source pt.
.src_idx = NullId,
};
self.verts.append(intersect_v) catch unreachable;
// TODO: Account for floating point error.
const a_to_vert = self.verts.items[sweep_edge_a.to_vert_idx];
if (a_to_vert.pos.x != intersect.x or a_to_vert.pos.y != intersect.y) {
// log(edgeToString(sweep_edge_a.edge))
log("adding edge a {} to {},{}", .{sweep_edge_a.vert_idx, intersect.x, intersect.y});
added_events = true;
// Invalidate sweep_edge_a's end event since the priority queue can not be modified.
self.events.items[sweep_edge_a.end_event_idx].invalidated = true;
// Keep original edge orientation when doing the split.
var first_edge: Edge = undefined;
var second_edge: Edge = undefined;
const start = self.verts.items[sweep_edge_a.edge.start_idx];
const end = self.verts.items[sweep_edge_a.edge.end_idx];
if (sweep_edge_a.to_vert_idx == sweep_edge_a.edge.start_idx) {
first_edge = Edge.init(intersect_idx, intersect_v, sweep_edge_a.edge.end_idx, end);
second_edge = Edge.init(sweep_edge_a.edge.start_idx, start, intersect_idx, intersect_v);
} else {
first_edge = Edge.init(sweep_edge_a.edge.start_idx, start, intersect_idx, intersect_v);
second_edge = Edge.init(intersect_idx, intersect_v, sweep_edge_a.edge.end_idx, end);
}
// Update sweep_edge_a to end at the intersect.
sweep_edge_a.edge = first_edge;
const a_orig_to_vert = sweep_edge_a.to_vert_idx;
sweep_edge_a.to_vert_idx = intersect_idx;
// Insert new sweep_edge_a end event.
const evt_idx = @intCast(u32, self.events.items.len);
var new_evt = Event.init(intersect_idx, intersect_v, first_edge, .End);
self.events.append(new_evt) catch unreachable;
self.event_q.add(evt_idx) catch unreachable;
// Insert start/end event from the intersect to the end of the original sweep_edge_a.
var event1: Event = undefined;
var event2: Event = undefined;
if (Event.isStartEvent(intersect_idx, second_edge, self.verts.items)) {
event1 = Event.init(intersect_idx, intersect_v, second_edge, .Start);
event2 = Event.init(a_orig_to_vert, self.verts.items[a_orig_to_vert], second_edge, .End);
event1.end_event_idx = evt_idx + 2;
} else {
event1 = Event.init(intersect_idx, intersect_v, second_edge, .End);
event2 = Event.init(a_orig_to_vert, self.verts.items[a_orig_to_vert], second_edge, .Start);
event2.end_event_idx = evt_idx + 1;
}
self.events.append(event1) catch unreachable;
self.event_q.add(evt_idx + 1) catch unreachable;
self.events.append(event2) catch unreachable;
self.event_q.add(evt_idx + 2) catch unreachable;
}
const b_to_vert = self.verts.items[sweep_edge_b.to_vert_idx];
if (b_to_vert.pos.x != intersect.x or b_to_vert.pos.y != intersect.y) {
log("adding edge b {} to {},{}", .{sweep_edge_b.vert_idx, intersect.x, intersect.y});
added_events = true;
// Invalidate sweep_edge_b's end event since the priority queue can not be modified.
log("invalidate: {} {}", .{sweep_edge_b.end_event_idx, self.events.items.len});
self.events.items[sweep_edge_b.end_event_idx].invalidated = true;
// Keep original edge orientation when doing the split.
var first_edge: Edge = undefined;
var second_edge: Edge = undefined;
const start = self.verts.items[sweep_edge_b.edge.start_idx];
const end = self.verts.items[sweep_edge_b.edge.end_idx];
if (sweep_edge_b.to_vert_idx == sweep_edge_b.edge.start_idx) {
first_edge = Edge.init(intersect_idx, intersect_v, sweep_edge_b.edge.end_idx, end);
second_edge = Edge.init(sweep_edge_b.edge.start_idx, start, intersect_idx, intersect_v);
} else {
first_edge = Edge.init(sweep_edge_b.edge.start_idx, start, intersect_idx, intersect_v);
second_edge = Edge.init(intersect_idx, intersect_v, sweep_edge_b.edge.end_idx, end);
}
// Update sweep_edge_b to end at the intersect.
sweep_edge_b.edge = first_edge;
const b_orig_to_vert = sweep_edge_b.to_vert_idx;
sweep_edge_b.to_vert_idx = intersect_idx;
// Insert new sweep_edge_b end event.
const evt_idx = @intCast(u32, self.events.items.len);
var new_evt = Event.init(intersect_idx, intersect_v, first_edge, .End);
self.events.append(new_evt) catch unreachable;
self.event_q.add(evt_idx) catch unreachable;
// Insert start/end event from the intersect to the end of the original sweep_edge_b.
var event1: Event = undefined;
var event2: Event = undefined;
if (Event.isStartEvent(intersect_idx, second_edge, self.verts.items)) {
event1 = Event.init(intersect_idx, intersect_v, second_edge, .Start);
event2 = Event.init(b_orig_to_vert, self.verts.items[b_orig_to_vert], second_edge, .End);
event1.end_event_idx = evt_idx + 2;
} else {
event1 = Event.init(intersect_idx, intersect_v, second_edge, .End);
event2 = Event.init(b_orig_to_vert, self.verts.items[b_orig_to_vert], second_edge, .Start);
event2.end_event_idx = evt_idx + 1;
}
self.events.append(event1) catch unreachable;
self.event_q.add(evt_idx + 1) catch unreachable;
self.events.append(event2) catch unreachable;
self.event_q.add(evt_idx + 2) catch unreachable;
}
if (!added_events) {
// No events were added, revert adding intersect point.
_ = self.verts.pop();
}
}
};
fn edgeToString(edge: Edge) []const u8 {
const S = struct {
var buf: [100]u8 = undefined;
};
return std.fmt.bufPrint(&S.buf, "{} ({},{}) -> {} ({},{})", .{edge.start_idx, edge.start_pos.x, edge.start_pos.y, edge.end_idx, edge.end_pos.x, edge.end_pos.y}) catch unreachable;
}
fn compareEventIdx(events: *std.ArrayList(Event), a: u32, b: u32) std.math.Order {
return compareEvent(events.items[a], events.items[b]);
}
/// Sort verts by y asc then x asc. Resolve same position by looking at the edge's xslope and whether it is active.
fn compareEvent(a: Event, b: Event) std.math.Order {
if (a.vert_y < b.vert_y) {
return .lt;
} else if (a.vert_y > b.vert_y) {
return .gt;
} else {
if (a.vert_x < b.vert_x) {
return .lt;
} else if (a.vert_x > b.vert_x) {
return .gt;
} else {
if (a.tag == .End and b.tag == .Start) {
return .lt;
} else if (a.tag == .Start and b.tag == .End) {
return .gt;
} else if (a.tag == .End and b.tag == .End) {
if (a.edge.x_slope > b.edge.x_slope) {
return .lt;
} else if (a.edge.x_slope < b.edge.x_slope) {
return .gt;
} else {
return .eq;
}
} else {
if (a.edge.x_slope < b.edge.x_slope) {
return .lt;
} else if (a.edge.x_slope > b.edge.x_slope) {
return .gt;
} else {
return .eq;
}
}
}
}
}
/// Compare SweepEdges for insertion. Each sweep edge should be unique since the rb tree doesn't support duplicate values.
/// The slopes from the current sweep edges are used to find their x-intersect along the event's y line.
/// If compared sweep edge is a horizontal line, return gt so it's inserted after it. The horizontal edge can be assumed to intersect with the target event or it wouldn't be in the sweep edges.
fn compareSweepEdge(_: SweepEdge, b: SweepEdge, evt: Event) std.math.Order {
if (!b.edge.is_horiz) {
const x_intersect = b.edge.x_slope * (evt.vert_y - b.edge.start_pos.y) + b.edge.start_pos.x;
if (@fabs(evt.vert_x - x_intersect) < SweepEdgeApproxEpsilon) {
// Since there is a chance of having floating point error, check with an epsilon.
// Always return .gt so the left sweep edge can be reliably checked for a joining edge.
return .gt;
} else {
if (evt.vert_x < x_intersect) {
return .lt;
} else if (evt.vert_x > x_intersect) {
return .gt;
} else {
unreachable;
}
}
} else {
return .gt;
}
}
fn findSweepEdgeForEndEvent(sweep_edges: *RbTree(u16, SweepEdge, Event, compareSweepEdge), e: Event) ?u16 {
const target = vec2(e.vert_x, e.vert_y);
const dummy = SweepEdge{
.edge = undefined,
.start_event_vert_uniq_idx = undefined,
.vert_idx = undefined,
.to_vert_idx = undefined,
.end_event_vert_uniq_idx = undefined,
.deferred_queue = undefined,
.deferred_queue_size = undefined,
.cur_side = undefined,
.bad_up_cusp_uniq_idx = undefined,
.bad_up_cusp_right_sweep_edge_id = undefined,
.lowest_right_vert_idx = undefined,
.lowest_right_vert_sweep_edge_id = undefined,
.interior_is_left = undefined,
.end_event_idx = undefined,