Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
geom_algorithms.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
188#ifndef GEOM_ALGORITHMS_H
189#define GEOM_ALGORITHMS_H
190
191#include <sstream>
192#include <polygon.H>
193#include <htlist.H>
194#include <tpl_dynDlist.H>
195#include <tpl_dynSetTree.H>
196#include <tpl_arrayQueue.H>
197#include <tpl_arrayStack.H>
198#include <tpl_sort_utils.H>
199#include <tpl_2dtree.H>
200#include <ah-errors.H>
201#include <algorithm>
202#include <utility>
203#include <random>
204#include <map>
205#include <set>
206#include <queue>
207#include <memory>
208#include <limits>
209#include <cmath>
210
211#include <ah-unique.H>
212#include <tpl_dynBinHeap.H>
213
214namespace Aleph {
230{
231public:
233 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &poly)
234 {
235 Array<Point> verts;
236 verts.reserve(poly.size());
237 for (Polygon::Vertex_Iterator it(poly); it.has_curr(); it.next_ne())
238 verts.append(it.get_current_vertex());
239 return verts;
240 }
241
247 [[nodiscard]] static Geom_Number signed_double_area(const Array<Point> &verts)
248 {
249 Geom_Number sum = 0;
250 for (size_t i = 0; i < verts.size(); ++i)
251 {
252 const Point &a = verts(i);
253 const Point &b = verts((i + 1) % verts.size());
254 sum += a.get_x() * b.get_y() - a.get_y() * b.get_x();
255 }
256 return sum;
257 }
258
260 [[nodiscard]] static Geom_Number signed_double_area(const Polygon &poly)
261 {
263 }
264
266 [[nodiscard]] static Geom_Number signed_area(const Array<Point> &verts)
267 {
268 return signed_double_area(verts) / 2;
269 }
270
272 [[nodiscard]] static Geom_Number signed_area(const Polygon &poly)
273 {
274 return signed_double_area(poly) / 2;
275 }
276
278 [[nodiscard]] static Geom_Number area(const Array<Point> &verts)
279 {
280 Geom_Number a = signed_area(verts);
281 return a < 0 ? Geom_Number(-a) : a;
282 }
283
285 [[nodiscard]] static Geom_Number area(const Polygon &poly)
286 {
287 Geom_Number a = signed_area(poly);
288 return a < 0 ? Geom_Number(-a) : a;
289 }
290
292 [[nodiscard]] static bool is_convex(const Array<Point> &verts)
293 {
294 if (verts.size() < 3)
295 return true;
296
297 int sign = 0;
298 const size_t n = verts.size();
299 for (size_t i = 0; i < n; ++i)
300 {
301 const Geom_Number turn =
302 area_of_parallelogram(verts(i), verts((i + 1) % n), verts((i + 2) % n));
303 if (turn == 0)
304 continue;
305 const int curr = turn > 0 ? 1 : -1;
306 if (sign == 0)
307 sign = curr;
308 else if (sign != curr)
309 return false;
310 }
311 return true;
312 }
313
314 static void ensure_ccw(Array<Point> &verts)
315 {
316 if (signed_double_area(verts) < 0)
317 for (size_t i = 0; i < verts.size() / 2; ++i)
318 {
319 const Point tmp = verts(i);
320 verts(i) = verts(verts.size() - 1 - i);
321 verts(verts.size() - 1 - i) = tmp;
322 }
323 }
324};
325
338{
339public:
343 struct EdgeRef
344 {
345 size_t u;
346 size_t v;
347 size_t tri;
348 size_t third;
349 };
350
351private:
352 static void append_edge(Array<EdgeRef> &edges, size_t a, size_t b, const size_t tri, const size_t third)
353 {
354 if (a > b)
355 {
356 const size_t tmp = a;
357 a = b;
358 b = tmp;
359 }
360
361 edges.append(EdgeRef{a, b, tri, third});
362 }
363
364public:
365 template <typename TriangleArray, typename GroupFn>
366 static void for_each_sorted_edge_group(const TriangleArray &triangles, GroupFn on_group)
367 {
368 Array<EdgeRef> edges;
369 edges.reserve(triangles.size() * 3);
370 for (size_t tri_idx = 0; tri_idx < triangles.size(); ++tri_idx)
371 {
372 const auto &tri = triangles(tri_idx);
373 append_edge(edges, tri.i, tri.j, tri_idx, tri.k);
374 append_edge(edges, tri.j, tri.k, tri_idx, tri.i);
375 append_edge(edges, tri.k, tri.i, tri_idx, tri.j);
376 }
377
378 quicksort_op(edges, [](const EdgeRef &a, const EdgeRef &b)
379 {
380 if (a.u != b.u)
381 return a.u < b.u;
382 if (a.v != b.v)
383 return a.v < b.v;
384 return a.tri < b.tri;
385 });
386
387 size_t first = 0;
388 while (first < edges.size())
389 {
390 size_t last = first + 1;
391 while (last < edges.size() and edges(last).u == edges(first).u and
392 edges(last).v == edges(first).v)
393 ++last;
394
395 on_group(edges, first, last);
396 first = last;
397 }
398 }
399};
400
405{
406private:
408 {
409 size_t a;
410 size_t b;
411 size_t c;
412 bool alive;
413 };
414
416 {
417 size_t u;
418 size_t v;
419 };
420
422 {
423 bool operator () (const UndirectedEdge &a, const UndirectedEdge &b) const
424 {
425 if (a.u != b.u)
426 return a.u < b.u;
427 return a.v < b.v;
428 }
429 };
430
432
433 static void toggle_edge(EdgeSet &boundary, size_t u, size_t v)
434 {
435 if (u > v)
436 {
437 const size_t tmp = u;
438 u = v;
439 v = tmp;
440 }
441
442 const UndirectedEdge e{u, v};
443 if (const auto *ptr = boundary.search(e); ptr != nullptr)
444 boundary.remove(*ptr);
445 else
446 boundary.insert(e);
447 }
448
449public:
450 template <typename IndexedTriangle, typename InCirclePredicate>
452 const size_t n,
453 InCirclePredicate point_in_circumcircle)
454 {
456 if (n < 3)
457 return out;
458
459 Geom_Number minx = pts(0).get_x();
460 Geom_Number maxx = pts(0).get_x();
461 Geom_Number miny = pts(0).get_y();
462 Geom_Number maxy = pts(0).get_y();
463
464 for (size_t i = 1; i < n; ++i)
465 {
466 if (pts(i).get_x() < minx)
467 minx = pts(i).get_x();
468 if (pts(i).get_x() > maxx)
469 maxx = pts(i).get_x();
470 if (pts(i).get_y() < miny)
471 miny = pts(i).get_y();
472 if (pts(i).get_y() > maxy)
473 maxy = pts(i).get_y();
474 }
475
476 const Geom_Number dx = maxx - minx;
477 const Geom_Number dy = maxy - miny;
478 Geom_Number delta = dx > dy ? dx : dy;
479 if (delta == 0)
480 delta = 1;
481
482 const Geom_Number span = delta * 16 + 1;
483 const Geom_Number two_span = span + span;
484 const Geom_Number midx = (minx + maxx) / 2;
485 const Geom_Number midy = (miny + maxy) / 2;
486
487 const Point s0(midx - two_span, midy - span);
488 const Point s1(midx + two_span, midy - span);
489 const Point s2(midx, midy + two_span);
490
491 pts.append(s0);
492 pts.append(s1);
493 pts.append(s2);
494
495 const size_t i0 = n;
496 const size_t i1 = n + 1;
497 const size_t i2 = n + 2;
498
500 work.append(WorkTriangle{i0, i1, i2, true});
501
502 for (size_t pidx = 0; pidx < n; ++pidx)
503 {
504 Array<size_t> bad;
505 bad.reserve(work.size());
506
507 for (size_t t = 0; t < work.size(); ++t)
508 {
509 const auto &[a, b, c, alive] = work(t);
510 if (not alive)
511 continue;
512
513 if (point_in_circumcircle(pts, a, b, c, pidx))
514 bad.append(t);
515 }
516
517 if (bad.is_empty())
518 continue;
519
520 EdgeSet boundary;
521
522 for (size_t bad_idx = 0; bad_idx < bad.size(); ++bad_idx)
523 {
524 auto &[a, b, c, alive] = work(bad(bad_idx));
525 if (not alive)
526 continue;
527
528 toggle_edge(boundary, a, b);
529 toggle_edge(boundary, b, c);
530 toggle_edge(boundary, c, a);
531 alive = false;
532 }
533
534 boundary.for_each([&](const UndirectedEdge &edge)
535 {
536 size_t u = edge.u;
537 size_t v = edge.v;
538
539 const Orientation o = orientation(pts(u), pts(v), pts(pidx));
540 if (o == Orientation::COLLINEAR)
541 return;
542
543 if (o == Orientation::CW)
544 {
545 const size_t tmp = u;
546 u = v;
547 v = tmp;
548 }
549
550 work.append(WorkTriangle{u, v, pidx, true});
551 });
552
553 Array<WorkTriangle> compacted;
554 compacted.reserve(work.size());
555 for (size_t t = 0; t < work.size(); ++t)
556 if (work(t).alive)
557 compacted.append(work(t));
558 work = std::move(compacted);
559 }
560
561 out.reserve(work.size());
562 for (size_t t = 0; t < work.size(); ++t)
563 {
564 const auto &[a, b, c, alive] = work(t);
565 if (not alive)
566 continue;
567
568 if (a >= n or b >= n or c >= n)
569 continue;
570
571 if (orientation(pts(a), pts(b), pts(c)) == Orientation::COLLINEAR)
572 continue;
573
574 out.append(IndexedTriangle{a, b, c});
575 }
576
577 return out;
578 }
579};
580
581// ============================================================================
582// Triangulation Algorithms
583// ============================================================================
584
638{
640
641 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &p)
642 {
644 }
645
646 [[nodiscard]] static Geom_Number signed_double_area(const Polygon &p)
647 {
649 }
650
651 static void normalize_to_ccw(Polygon &p)
652 {
653 const Geom_Number area2 = signed_double_area(p);
654 ah_domain_error_if(area2 == 0) << "Polygon is degenerate (zero area)";
655 if (area2 > 0)
656 return;
657
658 const Array<Point> verts = extract_vertices(p);
659 Polygon ccw;
660 for (size_t i = verts.size(); i > 0; --i)
661 ccw.add_vertex(verts(i - 1));
662 ccw.close();
663 p = std::move(ccw);
664 }
665
666public:
677 static bool diagonalize(const Polygon &p, const Segment &s)
678 {
679 for (Polygon::Segment_Iterator it(p); it.has_curr(); it.next_ne())
680 if (Segment curr = it.get_current_segment(); curr.get_src_point() != s.get_src_point() and
681 curr.get_tgt_point() != s.get_src_point() and curr.get_src_point() != s.get_tgt_point() and
682 curr.get_tgt_point() != s.get_tgt_point() and s.intersects_with(curr))
683 return false;
684 return true;
685 }
686
697 static bool in_cone(const Polygon &p, const Vertex &a, const Vertex &b)
698 {
699 // a0 -> a -> a1 are consecutive vertices
700 const Vertex &a0 = p.get_prev_vertex(a);
701 const Vertex &a1 = p.get_next_vertex(a);
702
703 if (a0.is_to_left_on_from(a, a1))
704 return a0.is_left_of(a, b) and a1.is_left_of(b, a);
705
706 return not (a1.is_to_left_on_from(a, b) and a0.is_to_left_on_from(b, a));
707 }
708
717 static bool diagonal(const Polygon &p, const Vertex &a, const Vertex &b)
718 {
719 return in_cone(p, a, b) and in_cone(p, b, a) and
720 diagonalize(p, Segment(a.to_point(), b.to_point()));
721 }
722
729 static EarsSet init_ears(const Polygon &p)
730 {
731 EarsSet ret;
732
733 for (Polygon::Vertex_Iterator it(p); it.has_curr(); it.next_ne())
734 {
735 Vertex &curr = it.get_current_vertex();
736 const Vertex &prev = p.get_prev_vertex(curr);
737 if (const Vertex &next = p.get_next_vertex(curr); diagonal(p, prev, next))
738 ret.insert(&curr);
739 }
740
741 return ret;
742 }
743
744public:
757 {
758 ah_domain_error_if(not poly.is_closed()) << "Polygon must be closed";
759 ah_domain_error_if(poly.size() < 3) << "Polygon has less than 3 vertices";
760
761 Polygon p = poly; // work on a copy
763
764 EarsSet ears;
765 if (p.size() > 3)
766 {
767 ears = init_ears(p);
768 ah_domain_error_if(ears.is_empty()) << "No valid ear found; polygon may be non-simple";
769 }
770
772
773 while (p.size() > 3)
774 {
775 ah_domain_error_if(ears.is_empty()) << "No valid ear found during triangulation";
776 const Vertex *curr = ears.remove_pos(0);
777
778 const Vertex &prev = p.get_prev_vertex(*curr);
779 const Vertex &next = p.get_next_vertex(*curr);
780
781 ret.append(Triangle(prev.to_point(), curr->to_point(), next.to_point()));
782 p.remove_vertex(*curr);
783
784 // After removal, prev and next are adjacent; recompute their
785 // outer neighbors for ear tests on the updated topology.
786 const Vertex &new_prev_prev = p.get_prev_vertex(prev);
787 const Vertex &new_next_next = p.get_next_vertex(next);
788
789 if (diagonal(p, new_prev_prev, next))
790 ears.insert(&prev);
791 else
792 ears.remove(&prev);
793
794 if (diagonal(p, prev, new_next_next))
795 ears.insert(&next);
796 else
797 ears.remove(&next);
798 }
799
800 assert(p.size() == 3);
801
802 const Vertex &a = p.get_first_vertex();
803 const Vertex &b = a.next_vertex();
804 const Vertex &c = b.next_vertex();
805
806 ret.append(Triangle(a.to_point(), b.to_point(), c.to_point()));
807
808 return ret;
809 }
810};
811
812// ============================================================================
813// Closest Pair of Points
814// ============================================================================
815
836{
837public:
844
845private:
852 {
853 bool operator () (const Point &p1, const Point &p2) const
854 {
855 if (p1.get_x() < p2.get_x())
856 return true;
857
858 if (p2.get_x() < p1.get_x())
859 return false;
860
861 return p1.get_y() < p2.get_y();
862 }
863 };
864
871 struct ByYCmp
872 {
873 bool operator () (const Point &p1, const Point &p2) const
874 {
875 if (p1.get_y() < p2.get_y())
876 return true;
877
878 if (p2.get_y() < p1.get_y())
879 return false;
880
881 if (p1.get_x() < p2.get_x())
882 return true;
883
884 if (p2.get_x() < p1.get_x())
885 return false;
886
887 return false;
888 }
889 };
890
896 [[nodiscard]] static Geom_Number dist2(const Point &a, const Point &b)
897 {
898 return a.distance_squared_to(b);
899 }
900
904 [[nodiscard]] static Result make_result(const Point &a, const Point &b)
905 {
906 return {a, b, dist2(a, b)};
907 }
908
919 [[nodiscard]] static Result brute_force(const Array<Point> &px, const size_t l, const size_t r)
920 {
921 assert(r - l >= 2);
922
923 Result best = make_result(px(l), px(l + 1));
924
925 for (size_t i = l; i < r; ++i)
926 for (size_t j = i + 1; j < r; ++j)
927 if (Result cand = make_result(px(i), px(j)); cand.distance_squared < best.distance_squared)
928 best = cand;
929
930 return best;
931 }
932
946 [[nodiscard]] static Result recurse(const Array<Point> &px,
947 const size_t l,
948 const size_t r,
949 Array<Point> &py)
950 {
951 const size_t n = r - l;
952 if (n <= 3)
953 return brute_force(px, l, r);
954
955 const size_t mid = l + n / 2;
956 const Point &mid_point = px(mid);
957
958 Array<Point> left_py;
959 Array<Point> right_py;
960 left_py.reserve(mid - l);
961 right_py.reserve(r - mid);
962
963 const size_t left_target = mid - l;
964 for (size_t i = 0; i < py.size(); ++i)
965 {
966 const Point &p = py(i);
967 if (p.get_x() < mid_point.get_x())
968 left_py.append(p);
969 else if (p.get_x() > mid_point.get_x())
970 right_py.append(p);
971 else // tie on x — fill left first, then right
972 {
973 if (left_py.size() < left_target)
974 left_py.append(p);
975 else
976 right_py.append(p);
977 }
978 }
979
980 const Result best_left = recurse(px, l, mid, left_py);
981 const Result best_right = recurse(px, mid, r, right_py);
982 Result best = best_left.distance_squared < best_right.distance_squared ? best_left : best_right;
983
984 Array<Point> strip;
985 strip.reserve(py.size());
986 for (size_t i = 0; i < py.size(); ++i)
987 {
988 const Point &p = py(i);
989 if (const Geom_Number dx = p.get_x() - mid_point.get_x(); dx * dx < best.distance_squared)
990 strip.append(p);
991 }
992
993 for (size_t i = 0; i < strip.size(); ++i)
994 for (size_t j = i + 1; j < strip.size(); ++j)
995 {
996 if (const Geom_Number dy = strip(j).get_y() - strip(i).get_y();
997 dy * dy >= best.distance_squared)
998 break;
999
1000 if (Result cand = make_result(strip(i), strip(j));
1002 best = cand;
1003 }
1004
1005 return best;
1006 }
1007
1008public:
1017 [[nodiscard]] Result operator () (const DynList<Point> &point_set) const
1018 {
1019 Array<Point> px;
1020 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
1021 px.append(it.get_curr());
1022
1023 ah_domain_error_if(px.size() < 2) << "Closest pair requires at least 2 points";
1024
1026
1027 // Early-exit on duplicate points: exact minimum distance is zero.
1028 for (size_t i = 1; i < px.size(); ++i)
1029 if (px(i) == px(i - 1))
1030 return {px(i - 1), px(i), 0};
1031
1032 Array<Point> py = px;
1033 quicksort_op(py, ByYCmp());
1034
1035 return recurse(px, 0, px.size(), py);
1036 }
1037
1044 [[nodiscard]] Segment closest_segment(DynList<Point> &point_set) const
1045 {
1046 Result r = (*this)(point_set);
1047 return {r.first, r.second};
1048 }
1049};
1050
1051// ============================================================================
1052// Minimum Enclosing Circle (Welzl)
1053// ============================================================================
1054
1083{
1084public:
1086 struct Circle
1087 {
1090
1092 [[nodiscard]] Geom_Number radius() const
1093 {
1095 }
1096
1098 [[nodiscard]] bool contains(const Point &p) const
1099 {
1101 }
1102 };
1103
1105 [[nodiscard]] static Circle from_one_point(const Point &a)
1106 {
1107 return {a, 0};
1108 }
1109
1111 [[nodiscard]] static Circle from_two_points(const Point &a, const Point &b)
1112 {
1113 const Point c = a.midpoint(b);
1114 return {c, c.distance_squared_to(a)};
1115 }
1116
1121 [[nodiscard]] static Circle from_three_points(const Point &a, const Point &b, const Point &c)
1122 {
1123 const Geom_Number &ax = a.get_x();
1124 const Geom_Number &ay = a.get_y();
1125 const Geom_Number &bx = b.get_x();
1126 const Geom_Number &by = b.get_y();
1127 const Geom_Number &cx = c.get_x();
1128 const Geom_Number &cy = c.get_y();
1129
1130 const Geom_Number d = ax * (by - cy) + bx * (cy - ay) + cx * (ay - by);
1131
1132 if (d == 0) // collinear — return diameter of farthest pair
1133 {
1134 const Geom_Number d_ab = a.distance_squared_to(b);
1135 const Geom_Number d_bc = b.distance_squared_to(c);
1136 const Geom_Number d_ac = a.distance_squared_to(c);
1137
1138 if (d_ab >= d_bc && d_ab >= d_ac)
1139 return from_two_points(a, b);
1140 if (d_bc >= d_ab && d_bc >= d_ac)
1141 return from_two_points(b, c);
1142 return from_two_points(a, c);
1143 }
1144
1145 const Geom_Number den = d + d;
1146 const Geom_Number a2 = ax * ax + ay * ay;
1147 const Geom_Number b2 = bx * bx + by * by;
1148 const Geom_Number c2 = cx * cx + cy * cy;
1149
1150 const Geom_Number ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / den;
1151 const Geom_Number uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / den;
1152
1153 const Point center{ux, uy};
1154 return {center, center.distance_squared_to(a)};
1155 }
1156
1164 [[nodiscard]] Circle operator () (const DynList<Point> &points) const
1165 {
1166 Array<Point> pts;
1167 for (auto it = points.get_it(); it.has_curr(); it.next_ne())
1168 pts.append(it.get_curr());
1169
1170 ah_domain_error_if(pts.size() == 0) << "MinimumEnclosingCircle: empty point set";
1171
1172 // Fisher-Yates shuffle
1173 {
1174 std::random_device rd;
1175 std::mt19937 gen(rd());
1176 for (size_t i = pts.size() - 1; i > 0; --i)
1177 {
1178 std::uniform_int_distribution<size_t> dist(0, i);
1179 if (const size_t j = dist(gen); i != j)
1180 std::swap(pts(i), pts(j));
1181 }
1182 }
1183
1184 return welzl_iterative(pts);
1185 }
1186
1188 [[nodiscard]] Circle operator () (std::initializer_list<Point> points) const
1189 {
1191 for (const auto &p : points)
1192 l.append(p);
1193 return (*this)(l);
1194 }
1195
1196private:
1198 [[nodiscard]] static Circle mec_with_point(const Array<Point> &pts, size_t n, const Point &p1)
1199 {
1200 Circle d = from_one_point(p1);
1201 for (size_t j = 0; j < n; ++j)
1202 if (not d.contains(pts(j)))
1203 d = mec_with_two_points(pts, j, p1, pts(j));
1204 return d;
1205 }
1206
1208 [[nodiscard]] static Circle mec_with_two_points(const Array<Point> &pts,
1209 size_t n,
1210 const Point &p1,
1211 const Point &p2)
1212 {
1213 Circle d = from_two_points(p1, p2);
1214 for (size_t k = 0; k < n; ++k)
1215 if (not d.contains(pts(k)))
1216 d = from_three_points(p1, p2, pts(k));
1217 return d;
1218 }
1219
1221 [[nodiscard]] static Circle welzl_iterative(const Array<Point> &pts)
1222 {
1223 Circle d = from_one_point(pts(0));
1224
1225 for (size_t i = 1; i < pts.size(); ++i)
1226 if (not d.contains(pts(i)))
1227 d = mec_with_point(pts, i, pts(i));
1228
1229 return d;
1230 }
1231};
1232
1233// ============================================================================
1234// Rotating Calipers (Convex Polygon Metrics)
1235// ============================================================================
1236
1259{
1260public:
1267
1275
1276private:
1286 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &poly)
1287 {
1288 ah_domain_error_if(not poly.is_closed()) << "Polygon must be closed";
1289
1290 ah_domain_error_if(poly.size() < 2) << "Rotating calipers requires at least 2 vertices";
1291
1293 }
1294
1304 [[nodiscard]] static bool is_convex(const Array<Point> &verts)
1305 {
1306 return GeomPolygonUtils::is_convex(verts);
1307 }
1308
1309 [[nodiscard]] static DiameterResult make_diameter(const Point &a, const Point &b)
1310 {
1311 return {a, b, a.distance_squared_to(b)};
1312 }
1313
1314public:
1323 static DiameterResult diameter(const Polygon &poly)
1324 {
1325 const Array<Point> verts = extract_vertices(poly);
1326 ah_domain_error_if(not is_convex(verts)) << "Polygon must be convex";
1327
1328 const size_t n = verts.size();
1329 if (n == 2)
1330 return make_diameter(verts(0), verts(1));
1331
1332 auto edge_area = [&verts, n](const size_t i, const size_t k) -> Geom_Number
1333 {
1334 Geom_Number area = area_of_parallelogram(verts(i), verts((i + 1) % n), verts(k));
1335 if (area < 0)
1336 area = -area;
1337 return area;
1338 };
1339
1340 size_t j = 1;
1341 size_t safety = 0;
1342 while (edge_area(0, (j + 1) % n) > edge_area(0, j) and safety++ < n)
1343 j = (j + 1) % n;
1344
1345 DiameterResult best = make_diameter(verts(0), verts(j));
1346
1347 for (size_t i = 0; i < n; ++i)
1348 {
1349 const size_t ni = (i + 1) % n;
1350 safety = 0;
1351 while (edge_area(i, (j + 1) % n) > edge_area(i, j) and safety++ < n)
1352 j = (j + 1) % n;
1353
1354 if (DiameterResult cand1 = make_diameter(verts(i), verts(j));
1356 best = cand1;
1357
1358 if (DiameterResult cand2 = make_diameter(verts(ni), verts(j));
1360 best = cand2;
1361 }
1362
1363 return best;
1364 }
1365
1380 {
1381 const Array<Point> verts = extract_vertices(poly);
1382 ah_domain_error_if(not is_convex(verts)) << "Polygon must be convex";
1383
1384 const size_t n = verts.size();
1385 if (n == 2)
1386 return {verts(0), verts(1), verts(0), 0};
1387
1388 auto area_to_edge = [&verts, n](const size_t i, const size_t k) -> Geom_Number
1389 {
1390 Geom_Number area = area_of_parallelogram(verts(i), verts((i + 1) % n), verts(k));
1391 if (area < 0)
1392 area = -area;
1393 return area;
1394 };
1395
1396 auto edge_len2 = [&verts, n](const size_t i) -> Geom_Number
1397 {
1398 return verts(i).distance_squared_to(verts((i + 1) % n));
1399 };
1400
1401 size_t best_i = 0;
1402 size_t best_ni = 1;
1403 size_t best_j = 0;
1404 Geom_Number best_width_sq = 0;
1405 bool initialized = false;
1406
1407 // Initialize antipodal index for edge (0,1).
1408 size_t j = 1 % n;
1409 size_t safety = 0;
1410 while (area_to_edge(0, (j + 1) % n) > area_to_edge(0, j) and safety++ < n)
1411 j = (j + 1) % n;
1412
1413 for (size_t i = 0; i < n; ++i)
1414 {
1415 const size_t ni = (i + 1) % n;
1416
1417 const Geom_Number len2 = edge_len2(i);
1418 if (len2 == 0)
1419 continue;
1420
1421 // Advance antipodal index while area increases.
1422 safety = 0;
1423 while (area_to_edge(i, (j + 1) % n) > area_to_edge(i, j) and safety++ < n)
1424 j = (j + 1) % n;
1425
1426 const Geom_Number num = area_to_edge(i, j);
1427 const Geom_Number width_sq = (num * num) / len2;
1428 if (not initialized or width_sq < best_width_sq)
1429 {
1430 best_i = i;
1431 best_ni = ni;
1432 best_j = j;
1433 best_width_sq = width_sq;
1434 initialized = true;
1435 }
1436 }
1437
1438 if (not initialized)
1439 return {verts(0), verts(1), verts(0), 0};
1440
1441 return {verts(best_i), verts(best_ni), verts(best_j), best_width_sq};
1442 }
1443};
1444
1445// ============================================================================
1446// Point-in-Polygon
1447// ============================================================================
1448
1474{
1475public:
1476 enum class Location
1477 {
1478 Outside,
1479 Boundary,
1480 Inside
1481 };
1482
1492 static Location locate(const Polygon &poly, const Point &p)
1493 {
1494 ah_domain_error_if(not poly.is_closed()) << "Polygon must be closed";
1495
1496 ah_domain_error_if(poly.size() < 3) << "Point-in-polygon requires at least 3 vertices";
1497
1498 switch (poly.locate_point(p))
1499 {
1501 return Location::Boundary;
1503 return Location::Inside;
1505 default:
1506 return Location::Outside;
1507 }
1508 }
1509
1517 [[nodiscard]] static bool contains(const Polygon &poly, const Point &p)
1518 {
1519 const Location loc = locate(poly, p);
1520 return loc != Location::Outside;
1521 }
1522
1530 [[nodiscard]] static bool strictly_contains(const Polygon &poly, const Point &p)
1531 {
1532 return locate(poly, p) == Location::Inside;
1533 }
1534};
1535
1536// ============================================================================
1537// Polygon Intersection (Basic)
1538// ============================================================================
1539
1560{
1561 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &poly)
1562 {
1563 ah_domain_error_if(not poly.is_closed()) << "Polygon must be closed";
1564
1565 ah_domain_error_if(poly.size() < 3) << "Polygon must have at least 3 vertices";
1566
1568 }
1569
1570 [[nodiscard]] static Geom_Number signed_double_area(const Array<Point> &verts)
1571 {
1573 }
1574
1575 [[nodiscard]] static bool is_convex(const Array<Point> &verts)
1576 {
1577 if (verts.size() < 3)
1578 return false;
1579 return GeomPolygonUtils::is_convex(verts);
1580 }
1581
1582 [[nodiscard]] static bool inside_half_plane(const Point &p,
1583 const Point &a,
1584 const Point &b,
1585 const bool clip_ccw)
1586 {
1587 const Orientation o = orientation(a, b, p);
1588 return clip_ccw ? o != Orientation::CW : o != Orientation::CCW;
1589 }
1590
1591 [[nodiscard]] static Point line_intersection(const Point &s,
1592 const Point &e,
1593 const Point &a,
1594 const Point &b)
1595 {
1596 const Geom_Number rx = e.get_x() - s.get_x();
1597 const Geom_Number ry = e.get_y() - s.get_y();
1598 const Geom_Number sx = b.get_x() - a.get_x();
1599 const Geom_Number sy = b.get_y() - a.get_y();
1600
1601 const Geom_Number den = rx * sy - ry * sx;
1602 if (den == 0)
1603 {
1604 if (orientation(a, b, s) == Orientation::COLLINEAR)
1605 return s;
1606 if (orientation(a, b, e) == Orientation::COLLINEAR)
1607 return e;
1608 return s;
1609 }
1610
1611 const Geom_Number qpx = a.get_x() - s.get_x();
1612 const Geom_Number qpy = a.get_y() - s.get_y();
1613 const Geom_Number t = (qpx * sy - qpy * sx) / den;
1614
1615 return {s.get_x() + t * rx, s.get_y() + t * ry};
1616 }
1617
1618 static void push_clean(Array<Point> &out, const Point &p)
1619 {
1620 if (out.is_empty())
1621 {
1622 out.append(p);
1623 return;
1624 }
1625
1626 if (out.get_last() == p)
1627 return;
1628
1629 while (out.size() >= 2)
1630 {
1631 const Point &a = out(out.size() - 2);
1632 const Point &b = out(out.size() - 1);
1633 if (orientation(a, b, p) != Orientation::COLLINEAR)
1634 break;
1635
1636 if (const Segment ab(a, b); on_segment(ab, p))
1637 return;
1638
1639 static_cast<void>(out.remove_last());
1640 }
1641
1642 out.append(p);
1643 }
1644
1645 [[nodiscard]] static Array<Point> normalize_vertices(const Array<Point> &pts)
1646 {
1647 Array<Point> ret;
1648 ret.reserve(pts.size());
1649 for (size_t i = 0; i < pts.size(); ++i)
1650 push_clean(ret, pts(i));
1651
1652 if (ret.size() > 1 and ret(0) == ret.get_last())
1653 static_cast<void>(ret.remove_last());
1654
1655 return ret;
1656 }
1657
1658 [[nodiscard]] static Polygon build_polygon(const Array<Point> &pts)
1659 {
1660 Polygon ret;
1661 Array<Point> clean = normalize_vertices(pts);
1662
1663 for (size_t i = 0; i < clean.size(); ++i)
1664 ret.add_vertex(clean(i));
1665
1666 if (ret.size() >= 3)
1667 ret.close();
1668
1669 return ret;
1670 }
1671
1672public:
1682 [[nodiscard]] Polygon operator () (const Polygon &subject, const Polygon &clip) const
1683 {
1684 const Array<Point> subj = extract_vertices(subject);
1685 const Array<Point> clp = extract_vertices(clip);
1686
1687 ah_domain_error_if(not is_convex(subj)) << "Subject polygon must be convex";
1688 ah_domain_error_if(not is_convex(clp)) << "Clip polygon must be convex";
1689
1690 const Geom_Number clip_area2 = signed_double_area(clp);
1691 ah_domain_error_if(clip_area2 == 0) << "Clip polygon is degenerate";
1692
1693 const bool clip_ccw = clip_area2 > 0;
1694
1695 Array<Point> output = subj;
1696
1697 for (size_t i = 0; i < clp.size(); ++i)
1698 {
1699 if (output.is_empty())
1700 break;
1701
1702 const Point &a = clp(i);
1703 const Point &b = clp((i + 1) % clp.size());
1704
1705 const Array<Point> input = output;
1706 output = Array<Point>();
1707 output.reserve(input.size() + 2);
1708
1709 Point s = input.get_last();
1710 bool s_inside = inside_half_plane(s, a, b, clip_ccw);
1711
1712 for (size_t j = 0; j < input.size(); ++j)
1713 {
1714 const Point &e = input(j);
1715 const bool e_inside = inside_half_plane(e, a, b, clip_ccw);
1716
1717 if (e_inside)
1718 {
1719 if (not s_inside)
1720 push_clean(output, line_intersection(s, e, a, b));
1721 push_clean(output, e);
1722 }
1723 else if (s_inside)
1724 push_clean(output, line_intersection(s, e, a, b));
1725
1726 s = e;
1727 s_inside = e_inside;
1728 }
1729
1731 }
1732
1733 return build_polygon(output);
1734 }
1735};
1736
1737// ============================================================================
1738// Half-Plane Intersection
1739// ============================================================================
1740
1758{
1759public:
1761 {
1764
1765 HalfPlane() = default;
1766
1767 HalfPlane(Point p_, Point q_) : p(std::move(p_)), q(std::move(q_)) {}
1768
1769 [[nodiscard]] Geom_Number dx() const
1770 {
1771 return q.get_x() - p.get_x();
1772 }
1773
1774 [[nodiscard]] Geom_Number dy() const
1775 {
1776 return q.get_y() - p.get_y();
1777 }
1778
1779 [[nodiscard]] Geom_Number offset() const
1780 {
1781 // n = (-dy, dx), inequality n.x*x + n.y*y >= offset
1782 return -dy() * p.get_x() + dx() * p.get_y();
1783 }
1784
1785 [[nodiscard]] bool outside(const Point &x) const
1786 {
1787 return orientation(p, q, x) == Orientation::CW;
1788 }
1789 };
1790
1791private:
1792 [[nodiscard]] static Geom_Number signed_double_area(const Array<Point> &verts)
1793 {
1795 }
1796
1797 [[nodiscard]] static bool upper_half(const HalfPlane &h)
1798 {
1799 return h.dy() > 0 or h.dy() == 0 and h.dx() >= 0;
1800 }
1801
1802 [[nodiscard]] static Geom_Number cross_dir(const HalfPlane &a, const HalfPlane &b)
1803 {
1804 return a.dx() * b.dy() - a.dy() * b.dx();
1805 }
1806
1807 [[nodiscard]] static Geom_Number dot_dir(const HalfPlane &a, const HalfPlane &b)
1808 {
1809 return a.dx() * b.dx() + a.dy() * b.dy();
1810 }
1811
1812 [[nodiscard]] static bool same_direction(const HalfPlane &a, const HalfPlane &b)
1813 {
1814 return cross_dir(a, b) == 0 and dot_dir(a, b) > 0;
1815 }
1816
1817 [[nodiscard]] static bool parallel(const HalfPlane &a, const HalfPlane &b)
1818 {
1819 return cross_dir(a, b) == 0;
1820 }
1821
1822 [[nodiscard]] static Point line_intersection(const HalfPlane &a, const HalfPlane &b)
1823 {
1824 const Geom_Number rx = a.dx();
1825 const Geom_Number ry = a.dy();
1826 const Geom_Number sx = b.dx();
1827 const Geom_Number sy = b.dy();
1828
1829 const Geom_Number den = rx * sy - ry * sx;
1830 ah_domain_error_if(den == 0) << "Parallel half-plane boundaries";
1831
1832 const Geom_Number qpx = b.p.get_x() - a.p.get_x();
1833 const Geom_Number qpy = b.p.get_y() - a.p.get_y();
1834 const Geom_Number t = (qpx * sy - qpy * sx) / den;
1835
1836 return {a.p.get_x() + t * rx, a.p.get_y() + t * ry};
1837 }
1838
1839 static void push_clean(Array<Point> &out, const Point &p)
1840 {
1841 if (out.is_empty())
1842 {
1843 out.append(p);
1844 return;
1845 }
1846
1847 if (out.get_last() == p)
1848 return;
1849
1850 while (out.size() >= 2)
1851 {
1852 const Point &a = out(out.size() - 2);
1853 const Point &b = out(out.size() - 1);
1854 if (orientation(a, b, p) != Orientation::COLLINEAR)
1855 break;
1856
1857 if (const Segment ab(a, b); on_segment(ab, p))
1858 return;
1859
1860 static_cast<void>(out.remove_last());
1861 }
1862
1863 out.append(p);
1864 }
1865
1866 [[nodiscard]] static Array<Point> normalize_vertices(const Array<Point> &pts)
1867 {
1868 Array<Point> ret;
1869 ret.reserve(pts.size());
1870 for (size_t i = 0; i < pts.size(); ++i)
1871 push_clean(ret, pts(i));
1872
1873 if (ret.size() > 1 and ret(0) == ret.get_last())
1874 static_cast<void>(ret.remove_last());
1875
1876 return ret;
1877 }
1878
1879 [[nodiscard]] static Polygon build_polygon(const Array<Point> &pts)
1880 {
1881 Polygon ret;
1882 const Array<Point> clean = normalize_vertices(pts);
1883
1884 for (size_t i = 0; i < clean.size(); ++i)
1885 ret.add_vertex(clean(i));
1886
1887 if (ret.size() >= 3)
1888 ret.close();
1889
1890 return ret;
1891 }
1892
1893public:
1903 [[nodiscard]] static Array<HalfPlane> from_convex_polygon(const Polygon &poly)
1904 {
1905 ah_domain_error_if(not poly.is_closed()) << "Polygon must be closed";
1906 ah_domain_error_if(poly.size() < 3) << "Polygon must have at least 3 vertices";
1907
1908 Array<Point> verts;
1909 verts.reserve(poly.size());
1910 for (Polygon::Vertex_Iterator it(poly); it.has_curr(); it.next_ne())
1911 verts.append(it.get_current_vertex());
1912
1913 const Geom_Number area2 = signed_double_area(verts);
1914 ah_domain_error_if(area2 == 0) << "Polygon is degenerate";
1915 const bool ccw = area2 > 0;
1916
1918 hs.reserve(verts.size());
1919 for (size_t i = 0; i < verts.size(); ++i)
1920 {
1921 const Point &a = verts(i);
1922 const Point &b = verts((i + 1) % verts.size());
1923 hs.append(ccw ? HalfPlane(a, b) : HalfPlane(b, a));
1924 }
1925 return hs;
1926 }
1927
1934 [[nodiscard]] Polygon operator () (const Array<HalfPlane> &halfplanes) const
1935 {
1936 if (halfplanes.size() < 3)
1937 return {};
1938
1939 Array<HalfPlane> hps = halfplanes;
1940 quicksort_op(hps, [](const HalfPlane &a, const HalfPlane &b)
1941 {
1942 const bool ha = upper_half(a);
1943 const bool hb = upper_half(b);
1944 if (ha != hb)
1945 return ha and not hb;
1946
1947 if (const Geom_Number cr = cross_dir(a, b); cr != 0)
1948 return cr > 0;
1949
1950 // Same direction: keep stronger constraints first.
1951 return a.offset() > b.offset();
1952 });
1953
1955 unique.reserve(hps.size());
1956 for (size_t i = 0; i < hps.size(); ++i)
1957 {
1958 const HalfPlane &hp = hps(i);
1959 if (unique.is_empty())
1960 {
1961 unique.append(hp);
1962 continue;
1963 }
1964
1965 if (const HalfPlane &last = unique.get_last(); same_direction(last, hp))
1966 {
1967 if (hp.offset() > last.offset())
1968 {
1969 static_cast<void>(unique.remove_last());
1970 unique.append(hp);
1971 }
1972 continue;
1973 }
1974
1975 unique.append(hp);
1976 }
1977
1979 DynDlist<Point> intersections;
1980
1981 for (size_t i = 0; i < unique.size(); ++i)
1982 {
1983 const HalfPlane &hp = unique(i);
1984
1985 while (not intersections.is_empty() and hp.outside(intersections.get_last()))
1986 {
1987 dq.remove_last();
1988 intersections.remove_last();
1989 }
1990
1991 while (not intersections.is_empty() and hp.outside(intersections.get_first()))
1992 {
1993 dq.remove_first();
1994 intersections.remove_first();
1995 }
1996
1997 if (not dq.is_empty() and parallel(dq.get_last(), hp))
1998 {
1999 if (same_direction(dq.get_last(), hp))
2000 {
2001 if (hp.offset() > dq.get_last().offset())
2002 {
2003 dq.remove_last();
2004 if (not intersections.is_empty())
2005 intersections.remove_last();
2006 }
2007 else
2008 continue;
2009 }
2010 else // Opposite parallel boundaries cannot define a bounded polygon here.
2011 return {};
2012 }
2013
2014 if (not dq.is_empty())
2015 intersections.append(line_intersection(dq.get_last(), hp));
2016
2017 dq.append(hp);
2018 }
2019
2020 while (not intersections.is_empty() and dq.get_first().outside(intersections.get_last()))
2021 {
2022 dq.remove_last();
2023 intersections.remove_last();
2024 }
2025
2026 while (not intersections.is_empty() and dq.get_last().outside(intersections.get_first()))
2027 {
2028 dq.remove_first();
2029 intersections.remove_first();
2030 }
2031
2032 if (dq.size() < 3)
2033 return {};
2034
2035 if (parallel(dq.get_last(), dq.get_first()))
2036 return {};
2037
2038 const Point closing = line_intersection(dq.get_last(), dq.get_first());
2039
2040 Array<Point> verts;
2041 verts.reserve(intersections.size() + 1);
2042
2043 DynDlist<Point> tmp = intersections;
2044 while (not tmp.is_empty())
2045 verts.append(tmp.remove_first());
2046 verts.append(closing);
2047
2048 return build_polygon(verts);
2049 }
2050
2057 [[nodiscard]] Polygon operator () (const std::initializer_list<HalfPlane> il) const
2058 {
2059 Array<HalfPlane> hps;
2060 hps.reserve(il.size());
2061 for (const HalfPlane &hp : il)
2062 hps.append(hp);
2063 return (*this)(hps);
2064 }
2065};
2066
2067// ============================================================================
2068// Delaunay Triangulation (Bowyer-Watson)
2069// ============================================================================
2070
2101{
2102public:
2109 {
2110 size_t i;
2111 size_t j;
2112 size_t k;
2113 };
2114
2123
2124private:
2128 [[nodiscard]] static bool lexicographic_less(const Point &p1, const Point &p2)
2129 {
2130 if (p1.get_x() < p2.get_x())
2131 return true;
2132 if (p2.get_x() < p1.get_x())
2133 return false;
2134 return p1.get_y() < p2.get_y();
2135 }
2136
2140 [[nodiscard]] static bool all_collinear(const Array<Point> &pts)
2141 {
2142 if (pts.size() < 3)
2143 return true;
2144
2145 for (size_t i = 2; i < pts.size(); ++i)
2146 if (orientation(pts(0), pts(1), pts(i)) != Orientation::COLLINEAR)
2147 return false;
2148
2149 return true;
2150 }
2151
2155 [[nodiscard]] static bool point_in_circumcircle(const Array<Point> &pts,
2156 const size_t ia,
2157 const size_t ib,
2158 const size_t ic,
2159 const size_t ip)
2160 {
2161 const Point &a = pts(ia);
2162 const Point &b = pts(ib);
2163 const Point &c = pts(ic);
2164 const Point &p = pts(ip);
2165
2166 const Geom_Number det = in_circle_determinant(a, b, c, p);
2167
2168 const Orientation o = orientation(a, b, c);
2169 if (o == Orientation::CCW)
2170 {
2171 if (det > 0)
2172 return true;
2173 if (det < 0)
2174 return false;
2175 }
2176 if (o == Orientation::CW)
2177 {
2178 if (det < 0)
2179 return true;
2180 if (det > 0)
2181 return false;
2182 }
2183
2184 // Cocircular / degenerate tie-break for deterministic output.
2185 size_t max_idx = ia;
2186 if (ib > max_idx)
2187 max_idx = ib;
2188 if (ic > max_idx)
2189 max_idx = ic;
2190 return ip < max_idx;
2191 }
2192
2196 [[nodiscard]] static Array<Point> unique_points(const DynList<Point> &point_set)
2197 {
2199 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
2200 all.append(it.get_curr());
2201
2202 quicksort_op(all, [](const Point &p1, const Point &p2)
2203 {
2204 return lexicographic_less(p1, p2);
2205 });
2206
2207 Array<Point> ret;
2208 ret.reserve(all.size());
2209 for (size_t i = 0; i < all.size(); ++i)
2210 if (ret.is_empty() or ret.get_last() != all(i))
2211 ret.append(all(i));
2212
2213 return ret;
2214 }
2215
2216public:
2223 [[nodiscard]] Result operator () (const DynList<Point> &point_set) const
2224 {
2225 Result ret;
2226 ret.sites = unique_points(point_set);
2227 const size_t n = ret.sites.size();
2228
2229 if (n < 3 or all_collinear(ret.sites))
2230 return ret;
2231
2232 Array<Point> pts = ret.sites;
2233 ret.triangles = GeomBowyerWatsonUtils::triangulate<IndexedTriangle>(
2234 std::move(pts), n,
2235 [](const Array<Point> &all_pts, const size_t ia, const size_t ib, const size_t ic,
2236 const size_t ip)
2237 {
2238 return DelaunayTriangulationBowyerWatson::point_in_circumcircle(all_pts, ia, ib, ic, ip);
2239 });
2240
2241 return ret;
2242 }
2243
2250 [[nodiscard]] Result operator () (const std::initializer_list<Point> il) const
2251 {
2252 DynList<Point> points;
2253 for (const Point &p : il)
2254 points.append(p);
2255 return (*this)(points);
2256 }
2257
2265 {
2267 for (size_t tria_idx = 0; tria_idx < result.triangles.size(); ++tria_idx)
2268 {
2269 const auto &[i, j, k] = result.triangles(tria_idx);
2270 out.append(Triangle(result.sites(i), result.sites(j), result.sites(k)));
2271 }
2272 return out;
2273 }
2274};
2275
2276// ============================================================================
2277// Regular Triangulation (Weighted Delaunay) — Bowyer-Watson
2278// ============================================================================
2279
2315{
2316public:
2323
2325
2331
2332private:
2333 [[nodiscard]] static bool lex_less(const Point &p1, const Point &p2)
2334 {
2335 if (p1.get_x() < p2.get_x())
2336 return true;
2337 if (p2.get_x() < p1.get_x())
2338 return false;
2339 return p1.get_y() < p2.get_y();
2340 }
2341
2342 [[nodiscard]] static bool all_collinear(const Array<WeightedSite> &s)
2343 {
2344 if (s.size() < 3)
2345 return true;
2346
2347 for (size_t i = 2; i < s.size(); ++i)
2348 if (orientation(s(0).position, s(1).position, s(i).position) != Orientation::COLLINEAR)
2349 return false;
2350
2351 return true;
2352 }
2353
2370 [[nodiscard]] static bool point_in_power_circle(const Array<Point> &pts,
2371 const Array<Geom_Number> &wts,
2372 const size_t ia,
2373 const size_t ib,
2374 const size_t ic,
2375 const size_t ip)
2376 {
2377 const Point &a = pts(ia);
2378 const Point &b = pts(ib);
2379 const Point &c = pts(ic);
2380 const Point &p = pts(ip);
2381
2382 const Geom_Number adx = a.get_x() - p.get_x();
2383 const Geom_Number ady = a.get_y() - p.get_y();
2384 const Geom_Number bdx = b.get_x() - p.get_x();
2385 const Geom_Number bdy = b.get_y() - p.get_y();
2386 const Geom_Number cdx = c.get_x() - p.get_x();
2387 const Geom_Number cdy = c.get_y() - p.get_y();
2388
2389 const Geom_Number ad2 = adx * adx + ady * ady - wts(ia) + wts(ip);
2390 const Geom_Number bd2 = bdx * bdx + bdy * bdy - wts(ib) + wts(ip);
2391 const Geom_Number cd2 = cdx * cdx + cdy * cdy - wts(ic) + wts(ip);
2392
2393 const Geom_Number det =
2394 ad2 * (bdx * cdy - bdy * cdx) - bd2 * (adx * cdy - ady * cdx) + cd2 * (adx * bdy - ady * bdx);
2395
2396 const Orientation o = orientation(a, b, c);
2397 if (o == Orientation::CCW)
2398 {
2399 if (det > 0)
2400 return true;
2401 if (det < 0)
2402 return false;
2403 }
2404 if (o == Orientation::CW)
2405 {
2406 if (det < 0)
2407 return true;
2408 if (det > 0)
2409 return false;
2410 }
2411
2412 // Cocircular / degenerate tie-break for deterministic output.
2413 size_t max_idx = ia;
2414 if (ib > max_idx)
2415 max_idx = ib;
2416 if (ic > max_idx)
2417 max_idx = ic;
2418 return ip < max_idx;
2419 }
2420
2427 [[nodiscard]] static Array<WeightedSite> unique_sites(const Array<WeightedSite> &input)
2428 {
2430 all.reserve(input.size());
2431 for (size_t i = 0; i < input.size(); ++i)
2432 all.append(input(i));
2433
2434 quicksort_op(all, [](const WeightedSite &a, const WeightedSite &b)
2435 {
2436 return lex_less(a.position, b.position);
2437 });
2438
2440 ret.reserve(all.size());
2441 for (size_t i = 0; i < all.size(); ++i)
2442 if (ret.is_empty() or ret.get_last().position != all(i).position)
2443 ret.append(all(i));
2444
2445 return ret;
2446 }
2447
2448public:
2455 [[nodiscard]] Result operator () (const Array<WeightedSite> &weighted_sites) const
2456 {
2457 Result ret;
2458 ret.sites = unique_sites(weighted_sites);
2459 const size_t n = ret.sites.size();
2460
2461 if (n < 3 or all_collinear(ret.sites))
2462 return ret;
2463
2464 Array<Point> pts;
2466 pts.reserve(n + 3);
2467 wts.reserve(n + 3);
2468 for (size_t i = 0; i < n; ++i)
2469 {
2470 pts.append(ret.sites(i).position);
2471 wts.append(ret.sites(i).weight);
2472 }
2473 wts.append(Geom_Number(0));
2474 wts.append(Geom_Number(0));
2475 wts.append(Geom_Number(0));
2476 ret.triangles = GeomBowyerWatsonUtils::triangulate<IndexedTriangle>(
2477 std::move(pts), n,
2478 [&wts](const Array<Point> &all_pts, const size_t ia, const size_t ib, const size_t ic,
2479 const size_t ip)
2480 {
2481 return RegularTriangulationBowyerWatson::point_in_power_circle(all_pts, wts, ia, ib, ic, ip);
2482 });
2483
2484 return ret;
2485 }
2486};
2487
2488// ============================================================================
2489// Delaunay Triangulation — Randomized Incremental O(n log n) expected
2490// ============================================================================
2491
2506{
2507public:
2510
2511private:
2512 static constexpr size_t NONE = ~static_cast<size_t>(0);
2513
2514 struct Tri
2515 {
2516 size_t v[3];
2517 size_t adj[3];
2518 bool alive;
2519 };
2520
2521 struct DagNode
2522 {
2523 size_t tri;
2525 };
2526
2528 [[nodiscard]] static size_t local_of(const Tri &t, const size_t id)
2529 {
2530 for (int i = 0; i < 3; ++i)
2531 if (t.v[i] == id)
2532 return static_cast<size_t>(i);
2533 return NONE;
2534 }
2535
2537 [[nodiscard]] static size_t adj_of(const Tri &t, const size_t n)
2538 {
2539 for (int i = 0; i < 3; ++i)
2540 if (t.adj[i] == n)
2541 return static_cast<size_t>(i);
2542 return NONE;
2543 }
2544
2546 [[nodiscard]] static bool point_in_tri(const Array<Point> &pts, const Tri &t, const size_t pidx)
2547 {
2548 const Orientation o0 = orientation(pts(t.v[0]), pts(t.v[1]), pts(pidx));
2549 const Orientation o1 = orientation(pts(t.v[1]), pts(t.v[2]), pts(pidx));
2550 const Orientation o2 = orientation(pts(t.v[2]), pts(t.v[0]), pts(pidx));
2551 const bool has_cw = o0 == Orientation::CW or o1 == Orientation::CW or o2 == Orientation::CW;
2552 const bool has_ccw = o0 == Orientation::CCW or o1 == Orientation::CCW or o2 == Orientation::CCW;
2553 return not (has_cw and has_ccw);
2554 }
2555
2559 [[nodiscard]] static bool in_cc(const Array<Point> &pts,
2560 const size_t ia,
2561 const size_t ib,
2562 const size_t ic,
2563 const size_t ip)
2564 {
2565 const Geom_Number det = in_circle_determinant(pts(ia), pts(ib), pts(ic), pts(ip));
2566 const Orientation o = orientation(pts(ia), pts(ib), pts(ic));
2567 if (o == Orientation::CCW)
2568 {
2569 if (det > 0)
2570 return true;
2571 if (det < 0)
2572 return false;
2573 }
2574 if (o == Orientation::CW)
2575 {
2576 if (det < 0)
2577 return true;
2578 if (det > 0)
2579 return false;
2580 }
2581 size_t mx = ia;
2582 if (ib > mx)
2583 mx = ib;
2584 if (ic > mx)
2585 mx = ic;
2586 return ip < mx;
2587 }
2588
2594 [[nodiscard]] static size_t locate(const Array<Point> &pts,
2595 const Array<Tri> &tris,
2596 const Array<DagNode> &dag,
2597 const size_t pidx,
2598 const size_t root)
2599 {
2600 size_t cur = root;
2601 while (not dag(cur).children.is_empty())
2602 {
2603 bool found = false;
2604 for (size_t c = 0; c < dag(cur).children.size(); ++c)
2605 {
2606 if (const size_t child = dag(cur).children(c); point_in_tri(pts, tris(child), pidx))
2607 {
2608 cur = child;
2609 found = true;
2610 break;
2611 }
2612 }
2613 if (not found)
2614 break;
2615 }
2616 return cur;
2617 }
2618
2620 static void remap_adj(Array<Tri> &tris, const size_t ot, const size_t nt)
2621 {
2622 for (const unsigned long nb : tris(ot).adj)
2623 {
2624 if (nb == NONE)
2625 continue;
2626 if (const size_t li = adj_of(tris(nb), ot); li != NONE)
2627 tris(nb).adj[li] = nt;
2628 }
2629 }
2630
2631public:
2640 [[nodiscard]] Result operator () (const DynList<Point> &point_set) const
2641 {
2642 Result ret;
2643
2644 // Build unique sorted points.
2645 {
2647 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
2648 all.append(it.get_curr());
2649 quicksort_op(all, [](const Point &a, const Point &b)
2650 {
2651 return a.get_x() < b.get_x() or (a.get_x() == b.get_x() and a.get_y() < b.get_y());
2652 });
2653 ret.sites = Array<Point>();
2654 ret.sites.reserve(all.size());
2655 for (size_t i = 0; i < all.size(); ++i)
2656 if (ret.sites.is_empty() or ret.sites.get_last() != all(i))
2657 ret.sites.append(all(i));
2658 }
2659
2660 const size_t n = ret.sites.size();
2661 if (n < 3)
2662 return ret;
2663
2664 // Check all-collinear.
2665 {
2666 bool collinear = true;
2667 for (size_t i = 2; i < n and collinear; ++i)
2668 if (orientation(ret.sites(0), ret.sites(1), ret.sites(i)) != Orientation::COLLINEAR)
2669 collinear = false;
2670 if (collinear)
2671 return ret;
2672 }
2673
2674 // Build pts array with super-triangle appended.
2675 Array<Point> pts = ret.sites;
2676 Geom_Number mnx = pts(0).get_x(), mxx = mnx;
2677 Geom_Number mny = pts(0).get_y(), mxy = mny;
2678 for (size_t i = 1; i < n; ++i)
2679 {
2680 if (pts(i).get_x() < mnx)
2681 mnx = pts(i).get_x();
2682 if (pts(i).get_x() > mxx)
2683 mxx = pts(i).get_x();
2684 if (pts(i).get_y() < mny)
2685 mny = pts(i).get_y();
2686 if (pts(i).get_y() > mxy)
2687 mxy = pts(i).get_y();
2688 }
2689 Geom_Number delta = mxx - mnx > mxy - mny ? mxx - mnx : mxy - mny;
2690 if (delta == 0)
2691 delta = 1;
2692 const Geom_Number sp = delta * 16 + 1;
2693 const Geom_Number cx = (mnx + mxx) / 2, cy = (mny + mxy) / 2;
2694 pts.append(Point(cx - sp - sp, cy - sp));
2695 pts.append(Point(cx + sp + sp, cy - sp));
2696 pts.append(Point(cx, cy + sp + sp));
2697
2698 // Random insertion order for input points [0..n).
2699 Array<size_t> order;
2700 order.reserve(n);
2701 for (size_t i = 0; i < n; ++i)
2702 order.append(i);
2703 // Fisher-Yates shuffle.
2704 {
2705 std::random_device rd;
2706 std::mt19937 gen(rd());
2707 for (size_t i = n - 1; i > 0; --i)
2708 {
2709 std::uniform_int_distribution<size_t> dis(0, i);
2710 const size_t j = dis(gen);
2711 const size_t tmp = order(i);
2712 order(i) = order(j);
2713 order(j) = tmp;
2714 }
2715 }
2716
2717 // Initialize with super-triangle.
2718 Array<Tri> tris;
2719 Array<DagNode> dag;
2720 tris.append(Tri{{n, n + 1, n + 2}, {NONE, NONE, NONE}, true});
2721 dag.append(DagNode{0, Array<size_t>()});
2722
2723 // Insert each point using the local Bowyer-Watson cavity approach.
2724 // 1) Locate containing triangle via DAG — O(log n) expected.
2725 // 2) BFS from it to find all "bad" triangles (circumcircle
2726 // contains the new point).
2727 // 3) Extract the boundary polygon of the cavity.
2728 // 4) Re-triangulate cavity by connecting boundary edges to
2729 // the new point.
2730 // Expected cavity size is O(1) for random insertion order,
2731 // giving O(n log n) total expected time.
2732 for (size_t oi = 0; oi < n; ++oi)
2733 {
2734 const size_t pidx = order(oi);
2735 const size_t ti = locate(pts, tris, dag, pidx, 0);
2736
2737 // --- BFS to find the cavity ---
2738 const size_t ntris_before = tris.size();
2739 Array<bool> is_bad;
2740 is_bad.reserve(ntris_before);
2741 for (size_t i = 0; i < ntris_before; ++i)
2742 is_bad.append(false);
2743
2744 Array<size_t> cavity;
2745 is_bad(ti) = true;
2746 cavity.append(ti);
2747
2748 // Frontier queue: at most one enqueue per triangle.
2749 FixedQueue<size_t> frontier(ntris_before + 1);
2750 frontier.put(ti);
2751 while (not frontier.is_empty())
2752 for (const size_t ct = frontier.get(); unsigned long nb : tris(ct).adj)
2753 {
2754 if (nb == NONE or nb >= ntris_before or not tris(nb).alive or is_bad(nb))
2755 continue;
2756 if (in_cc(pts, tris(nb).v[0], tris(nb).v[1], tris(nb).v[2], pidx))
2757 {
2758 is_bad(nb) = true;
2759 cavity.append(nb);
2760 frontier.put(nb);
2761 }
2762 }
2763
2764 // --- Extract boundary edges ---
2765 // Each boundary edge is an edge of a cavity triangle whose
2766 // neighbor is outside the cavity (or NONE).
2767 struct BEdge
2768 {
2769 size_t u, v, ext, old_ct;
2770 };
2771 Array<BEdge> boundary;
2772 for (size_t ci = 0; ci < cavity.size(); ++ci)
2773 {
2774 const size_t ct = cavity(ci);
2775 for (int e = 0; e < 3; ++e)
2776 {
2777 const size_t nb = tris(ct).adj[e];
2778 if (nb != NONE and nb < ntris_before and is_bad(nb))
2779 continue; // internal cavity edge — skip
2780 // Boundary edge opposite v[e]: vertices (v[(e+1)%3], v[(e+2)%3]).
2781 boundary.append(BEdge{tris(ct).v[(e + 1) % 3], tris(ct).v[(e + 2) % 3], nb, ct});
2782 }
2783 }
2784
2785 // --- Create new triangles ---
2786 // For each boundary edge (u,v) create triangle (u, v, pidx).
2787 // adj[2] (opposite pidx) = external neighbor.
2788 const size_t V = pts.size();
2789 Array<size_t> as_u, as_v; // vertex → new tri where it's u / v
2790 as_u.reserve(V);
2791 as_v.reserve(V);
2792 for (size_t i = 0; i < V; ++i)
2793 {
2794 as_u.append(NONE);
2795 as_v.append(NONE);
2796 }
2797
2798 Array<size_t> new_tris;
2799 new_tris.reserve(boundary.size());
2800
2801 for (size_t bi = 0; bi < boundary.size(); ++bi)
2802 {
2803 size_t u = boundary(bi).u, v = boundary(bi).v;
2804 const size_t ext = boundary(bi).ext;
2805 const size_t old_ct = boundary(bi).old_ct;
2806
2807 // Ensure CCW winding.
2808 if (orientation(pts(u), pts(v), pts(pidx)) != Orientation::CCW)
2809 {
2810 const size_t tmp = u;
2811 u = v;
2812 v = tmp;
2813 }
2814
2815 const size_t nt = tris.size();
2816 tris.append(Tri{{u, v, pidx}, {NONE, NONE, ext}, true});
2817 dag.append(DagNode{nt, Array<size_t>()});
2818 new_tris.append(nt);
2819
2820 as_u(u) = nt;
2821 as_v(v) = nt;
2822
2823 // Remap external neighbor to point to the new triangle.
2824 if (ext != NONE)
2825 if (const size_t li = adj_of(tris(ext), old_ct); li != NONE)
2826 tris(ext).adj[li] = nt;
2827 }
2828
2829 // --- Internal adjacencies between new triangles ---
2830 // Two new triangles share an edge through pidx.
2831 // For triangle (u, v, pidx):
2832 // adj[0] opp u = edge(v, pidx) → the new tri with v as u
2833 // adj[1] opp v = edge(pidx, u) → the new tri with u as v
2834 for (size_t ni = 0; ni < new_tris.size(); ++ni)
2835 {
2836 const size_t nt = new_tris(ni);
2837 const size_t u = tris(nt).v[0];
2838 const size_t v = tris(nt).v[1];
2839 tris(nt).adj[0] = as_u(v); // neighbor across (v, pidx)
2840 tris(nt).adj[1] = as_v(u); // neighbor across (pidx, u)
2841 }
2842
2843 // --- Kill cavity and update DAG ---
2844 for (size_t ci = 0; ci < cavity.size(); ++ci)
2845 {
2846 tris(cavity(ci)).alive = false;
2847 for (size_t ni = 0; ni < new_tris.size(); ++ni)
2848 dag(cavity(ci)).children.append(new_tris(ni));
2849 }
2850 }
2851
2852 // Collect alive triangles that don't reference super-triangle.
2853 ret.triangles.reserve(2 * n);
2854 for (size_t t = 0; t < tris.size(); ++t)
2855 {
2856 const Tri &tr = tris(t);
2857 if (not tr.alive)
2858 continue;
2859 if (tr.v[0] >= n or tr.v[1] >= n or tr.v[2] >= n)
2860 continue;
2861 if (orientation(pts(tr.v[0]), pts(tr.v[1]), pts(tr.v[2])) == Orientation::COLLINEAR)
2862 continue;
2863 ret.triangles.append(IndexedTriangle{tr.v[0], tr.v[1], tr.v[2]});
2864 }
2865
2866 return ret;
2867 }
2868
2875 [[nodiscard]] Result operator () (const std::initializer_list<Point> il) const
2876 {
2877 DynList<Point> points;
2878 for (const Point &p : il)
2879 points.append(p);
2880 return (*this)(points);
2881 }
2882};
2883
2884// ============================================================================
2885// Constrained Delaunay Triangulation (CDT)
2886// ============================================================================
2887
2913{
2914public:
2916
2918 {
2919 size_t u;
2920 size_t v;
2921 };
2922
2929
2930private:
2931 static constexpr size_t NONE = ~static_cast<size_t>(0);
2932
2933 struct Tri
2934 {
2935 size_t v[3];
2936 size_t adj[3];
2937 bool constrained[3];
2938 bool alive;
2939 };
2940
2941 [[nodiscard]] static bool lexicographic_less(const Point &p1, const Point &p2)
2942 {
2943 if (p1.get_x() < p2.get_x())
2944 return true;
2945 if (p2.get_x() < p1.get_x())
2946 return false;
2947 return p1.get_y() < p2.get_y();
2948 }
2949
2951 [[nodiscard]] static size_t find_point_index(const Array<Point> &pts, const Point &p)
2952 {
2953 size_t lo = 0, hi = pts.size();
2954 while (lo < hi)
2955 if (const size_t mid = lo + (hi - lo) / 2; lexicographic_less(pts(mid), p))
2956 lo = mid + 1;
2957 else if (lexicographic_less(p, pts(mid)))
2958 hi = mid;
2959 else
2960 return mid;
2961 return NONE;
2962 }
2963
2965 [[nodiscard]] static size_t local_of(const Tri &t, const size_t id)
2966 {
2967 for (int i = 0; i < 3; ++i)
2968 if (t.v[i] == id)
2969 return static_cast<size_t>(i);
2970 return NONE;
2971 }
2972
2974 [[nodiscard]] static size_t adj_of(const Tri &t, const size_t n)
2975 {
2976 for (int i = 0; i < 3; ++i)
2977 if (t.adj[i] == n)
2978 return static_cast<size_t>(i);
2979 return NONE;
2980 }
2981
2984 [[nodiscard]] static size_t edge_opposite(const Tri &t, const size_t a, const size_t b)
2985 {
2986 for (int i = 0; i < 3; ++i)
2987 {
2988 const size_t e0 = t.v[(i + 1) % 3];
2989 const size_t e1 = t.v[(i + 2) % 3];
2990 if ((e0 == a and e1 == b) or (e0 == b and e1 == a))
2991 return static_cast<size_t>(i);
2992 }
2993 return NONE;
2994 }
2995
2997 static void build_adjacency(Array<Tri> &tris, const Array<IndexedTriangle> &dt_tris)
2998 {
2999 tris.reserve(dt_tris.size());
3000 for (size_t i = 0; i < dt_tris.size(); ++i)
3001 {
3002 const auto &t = dt_tris(i);
3003 tris.append(Tri{{t.i, t.j, t.k}, {NONE, NONE, NONE}, {false, false, false}, true});
3004 }
3005
3007 dt_tris,
3008 [&](const Array<GeomTriangleAdjacencyUtils::EdgeRef> &edges, const size_t first,
3009 const size_t last)
3010 {
3011 if (last - first != 2)
3012 return; // boundary edge (1 tri) or degenerate
3013
3014 const auto &e0 = edges(first);
3015 const auto &e1 = edges(first + 1);
3016
3017 const size_t t0 = e0.tri;
3018 const size_t t1 = e1.tri;
3019 const size_t loc0 = edge_opposite(tris(t0), e0.u, e0.v);
3020 const size_t loc1 = edge_opposite(tris(t1), e1.u, e1.v);
3021
3022 if (loc0 != NONE)
3023 tris(t0).adj[loc0] = t1;
3024 if (loc1 != NONE)
3025 tris(t1).adj[loc1] = t0;
3026 });
3027 }
3028
3030 [[nodiscard]] static bool edge_exists(const Array<Tri> &tris,
3031 const size_t u,
3032 const size_t v,
3033 size_t &out_tri,
3034 size_t &out_local)
3035 {
3036 for (size_t t = 0; t < tris.size(); ++t)
3037 {
3038 if (not tris(t).alive)
3039 continue;
3040
3041 if (const size_t loc = edge_opposite(tris(t), u, v); loc != NONE)
3042 {
3043 out_tri = t;
3044 out_local = loc;
3045 return true;
3046 }
3047 }
3048 return false;
3049 }
3050
3057 [[nodiscard]] static bool is_convex_quad(const Array<Point> &pts,
3058 const size_t a,
3059 const size_t b,
3060 const size_t c,
3061 const size_t d)
3062 {
3063 const Orientation o1 = orientation(pts(a), pts(d), pts(b));
3064 const Orientation o2 = orientation(pts(a), pts(d), pts(c));
3066 return false;
3067 if (o1 == o2)
3068 return false;
3069
3070 const Orientation o3 = orientation(pts(b), pts(c), pts(a));
3071 const Orientation o4 = orientation(pts(b), pts(c), pts(d));
3073 return false;
3074 if (o3 == o4)
3075 return false;
3076
3077 return true;
3078 }
3079
3084 static void flip_edge(Array<Tri> &tris, const size_t tri_a, const size_t tri_b)
3085 {
3086 Tri &ta = tris(tri_a);
3087 Tri &tb = tris(tri_b);
3088
3089 // Identify the shared edge.
3090 const size_t la = adj_of(ta, tri_b);
3091 const size_t lb = adj_of(tb, tri_a);
3092 if (la == NONE or lb == NONE)
3093 return;
3094
3095 // Vertices: a_opp is opposite the shared edge in ta,
3096 // b_opp is opposite the shared edge in tb.
3097 const size_t a_opp = ta.v[la];
3098 const size_t b_opp = tb.v[lb];
3099 const size_t p = ta.v[(la + 1) % 3]; // shared edge start
3100 const size_t q = ta.v[(la + 2) % 3]; // shared edge end
3101
3102 // External neighbors before the flip.
3103 const size_t ext_a1 = ta.adj[(la + 1) % 3]; // neighbor opp p in ta
3104 const size_t ext_a2 = ta.adj[(la + 2) % 3]; // neighbor opp q in ta
3105 const size_t ext_b1 = tb.adj[(lb + 1) % 3]; // neighbor opp p_adj in tb
3106 const size_t ext_b2 = tb.adj[(lb + 2) % 3]; // neighbor opp q_adj in tb
3107
3108 // Constrained flags for external edges.
3109 const bool con_a1 = ta.constrained[(la + 1) % 3];
3110 const bool con_a2 = ta.constrained[(la + 2) % 3];
3111 const bool con_b1 = tb.constrained[(lb + 1) % 3];
3112 const bool con_b2 = tb.constrained[(lb + 2) % 3];
3113
3114 // Identify which external neighbors of tb go with which new triangle.
3115 // tb has vertices: b_opp, p', q' where p' = tb.v[(lb+1)%3], q' = tb.v[(lb+2)%3]
3116 // p' and q' are p and q (in some order).
3117 const size_t bp = tb.v[(lb + 1) % 3]; // one of {p, q}
3118 const size_t bq = tb.v[(lb + 2) % 3]; // the other
3119
3120 // New triangle A: (a_opp, b_opp, q) — uses new diagonal + edge (b_opp, q)
3121 // New triangle B: (b_opp, a_opp, p) — uses new diagonal + edge (a_opp, p)
3122 // Ensure CCW winding.
3123
3124 // After flip, new triangles share edge (a_opp, b_opp).
3125 // tri_a becomes (a_opp, b_opp, q) [CCW if original was CCW]
3126 // tri_b becomes (b_opp, a_opp, p) [CCW if original was CCW]
3127
3128 // New tri_a = (a_opp, b_opp, q):
3129 // - adj[0] opp a_opp = edge(b_opp, q) — this was in tb between b_opp and q
3130 // - adj[1] opp b_opp = edge(q, a_opp) — this was in ta between q and a_opp
3131 // - adj[2] opp q = tri_b (new diagonal)
3132 // New tri_b = (b_opp, a_opp, p):
3133 // - adj[0] opp b_opp = edge(a_opp, p) — this was in ta between a_opp and p
3134 // - adj[1] opp a_opp = edge(p, b_opp) — this was in tb between p and b_opp
3135 // - adj[2] opp p = tri_a (new diagonal)
3136
3137 // Figure out external neighbors and constrained flags.
3138 // From ta: edge opp (la+1)%3 i.e., opp ta.v[(la+1)%3] = opp p = edge(a_opp, q)
3139 // edge opp (la+2)%3 i.e., opp ta.v[(la+2)%3] = opp q = edge(p, a_opp)
3140 // So: ext_a1 is neighbor across edge(a_opp, q), ext_a2 across edge(p, a_opp).
3141 //
3142 // From tb: bp = tb.v[(lb+1)%3], bq = tb.v[(lb+2)%3]
3143 // ext_b1 is neighbor across edge(b_opp, bq), opp bp
3144 // ext_b2 is neighbor across edge(bp, b_opp), opp bq
3145
3146 // New tri_a = (a_opp, b_opp, q):
3147 // adj[0] opp a_opp = edge(b_opp, q): this is from tb. If bq==q, ext_b1; if bp==q, ext_b2
3148 // adj[1] opp b_opp = edge(q, a_opp): this is ext_a1
3149 // adj[2] opp q = tri_b
3150 size_t new_a_adj0;
3151 bool new_a_con0;
3152
3153 const size_t new_a_adj1 = ext_a1; // edge(q, a_opp) was opp p in ta
3154 const bool new_a_con1 = con_a1;
3155 const size_t new_a_adj2 = tri_b;
3156 constexpr bool new_a_con2 = false; // the new diagonal is not constrained
3157
3158 if (bq == q)
3159 {
3160 new_a_adj0 = ext_b1; // edge(b_opp, q) was opp bp in tb
3161 new_a_con0 = con_b1;
3162 }
3163 else
3164 {
3165 new_a_adj0 = ext_b2; // edge(b_opp, q) was opp bq in tb, so bp==q
3166 new_a_con0 = con_b2;
3167 }
3168
3169 // New tri_b = (b_opp, a_opp, p):
3170 // adj[0] opp b_opp = edge(a_opp, p): this is ext_a2
3171 // adj[1] opp a_opp = edge(p, b_opp): from tb. If bp==p, ext_b2; if bq==p, ext_b1
3172 // adj[2] opp p = tri_a
3173 size_t new_b_adj1;
3174 bool new_b_con1;
3175
3176 const size_t new_b_adj0 = ext_a2; // edge(p, a_opp) was opp q in ta
3177 const bool new_b_con0 = con_a2;
3178 const size_t new_b_adj2 = tri_a;
3179 constexpr bool new_b_con2 = false; // new diagonal
3180
3181 if (bp == p)
3182 {
3183 new_b_adj1 = ext_b2; // edge(p, b_opp) was opp bq in tb
3184 new_b_con1 = con_b2;
3185 }
3186 else
3187 {
3188 new_b_adj1 = ext_b1; // edge(p, b_opp) was opp bp in tb, bq==p
3189 new_b_con1 = con_b1;
3190 }
3191
3192 // Write new triangles.
3193 ta.v[0] = a_opp;
3194 ta.v[1] = b_opp;
3195 ta.v[2] = q;
3196 ta.adj[0] = new_a_adj0;
3197 ta.adj[1] = new_a_adj1;
3198 ta.adj[2] = new_a_adj2;
3199 ta.constrained[0] = new_a_con0;
3200 ta.constrained[1] = new_a_con1;
3201 ta.constrained[2] = new_a_con2;
3202
3203 tb.v[0] = b_opp;
3204 tb.v[1] = a_opp;
3205 tb.v[2] = p;
3206 tb.adj[0] = new_b_adj0;
3207 tb.adj[1] = new_b_adj1;
3208 tb.adj[2] = new_b_adj2;
3209 tb.constrained[0] = new_b_con0;
3210 tb.constrained[1] = new_b_con1;
3211 tb.constrained[2] = new_b_con2;
3212
3213 // Remap external neighbors to point to correct new triangle.
3214 if (new_a_adj0 != NONE)
3215 if (const size_t li = adj_of(tris(new_a_adj0), tri_b); li != NONE)
3216 tris(new_a_adj0).adj[li] = tri_a;
3217 if (new_b_adj0 != NONE)
3218 if (const size_t li = adj_of(tris(new_b_adj0), tri_a); li != NONE)
3219 tris(new_b_adj0).adj[li] = tri_b;
3220 if (new_b_adj1 != NONE)
3221 if (const size_t li = adj_of(tris(new_b_adj1), tri_a); li != NONE)
3222 tris(new_b_adj1).adj[li] = tri_b;
3223 if (new_a_adj1 != NONE)
3224 if (const size_t li = adj_of(tris(new_a_adj1), tri_b); li != NONE)
3225 tris(new_a_adj1).adj[li] = tri_a;
3226 }
3227
3231 {
3232 size_t tri;
3233 size_t local;
3234 };
3235
3237 const Array<Tri> &tris,
3238 const size_t u,
3239 const size_t v)
3240 {
3241 Array<CrossingEdge> crossings;
3242 const Segment seg_uv(pts(u), pts(v));
3243
3244 for (size_t t = 0; t < tris.size(); ++t)
3245 {
3246 if (not tris(t).alive)
3247 continue;
3248
3249 for (int e = 0; e < 3; ++e)
3250 {
3251 const size_t w1 = tris(t).v[(e + 1) % 3];
3252 const size_t w2 = tris(t).v[(e + 2) % 3];
3253
3254 // Skip edges incident to u or v (they can't "cross").
3255 if (w1 == u or w1 == v or w2 == u or w2 == v)
3256 continue;
3257
3258 // Only process each undirected edge once (from the triangle
3259 // with the smaller index, or from the boundary side).
3260 const size_t nb = tris(t).adj[e];
3261 if (nb != NONE and nb < t)
3262 continue;
3263
3264 if (const Segment seg_edge(pts(w1), pts(w2)); seg_uv.intersects_properly_with(seg_edge))
3265 {
3266 crossings.append(CrossingEdge{t, static_cast<size_t>(e)});
3267 // Also record from the neighbor's side.
3268 if (nb != NONE and tris(nb).alive)
3269 if (const size_t lb = adj_of(tris(nb), t); lb != NONE)
3270 crossings.append(CrossingEdge{nb, lb});
3271 }
3272 }
3273 }
3274
3275 return crossings;
3276 }
3277
3279 static void mark_constrained(Array<Tri> &tris, const size_t u, const size_t v)
3280 {
3281 for (size_t t = 0; t < tris.size(); ++t)
3282 {
3283 if (not tris(t).alive)
3284 continue;
3285
3286 if (const size_t loc = edge_opposite(tris(t), u, v); loc != NONE)
3287 tris(t).constrained[loc] = true;
3288 }
3289 }
3290
3292 static void enforce_constraint(Array<Point> &pts, Array<Tri> &tris, const size_t u, const size_t v)
3293 {
3294 // Check if edge already in mesh.
3295 size_t et, el;
3296 if (edge_exists(tris, u, v, et, el))
3297 {
3298 mark_constrained(tris, u, v);
3299 return;
3300 }
3301
3302 // Find crossing edges and flip them.
3303 const size_t max_iterations = tris.size() * 4 + 100;
3304 for (size_t iter = 0; iter < max_iterations; ++iter)
3305 {
3306 // Check if the edge now exists.
3307 if (edge_exists(tris, u, v, et, el))
3308 {
3309 mark_constrained(tris, u, v);
3310 return;
3311 }
3312
3313 Array<CrossingEdge> crossings = find_crossing_edges(pts, tris, u, v);
3314 if (crossings.is_empty())
3315 {
3316 // Edge should exist now, or no crossings found.
3317 if (edge_exists(tris, u, v, et, el))
3318 mark_constrained(tris, u, v);
3319 return;
3320 }
3321
3322 bool flipped_any = false;
3323 for (size_t ci = 0; ci < crossings.size(); ++ci)
3324 {
3325 const size_t tri_idx = crossings(ci).tri;
3326 const size_t loc_idx = crossings(ci).local;
3327
3328 if (not tris(tri_idx).alive)
3329 continue;
3330
3331 if (tris(tri_idx).constrained[loc_idx])
3332 continue; // don't flip constrained edges
3333
3334 const size_t nb = tris(tri_idx).adj[loc_idx];
3335 if (nb == NONE or not tris(nb).alive)
3336 continue;
3337
3338 // Get the four vertices of the quadrilateral.
3339 const size_t a = tris(tri_idx).v[loc_idx]; // opposite vertex in tri_idx
3340 const size_t lb = adj_of(tris(nb), tri_idx);
3341 if (lb == NONE)
3342 continue;
3343 const size_t d = tris(nb).v[lb]; // opposite vertex in nb
3344 const size_t b = tris(tri_idx).v[(loc_idx + 1) % 3];
3345 const size_t c = tris(tri_idx).v[(loc_idx + 2) % 3];
3346
3347 if (is_convex_quad(pts, a, b, c, d))
3348 {
3349 flip_edge(tris, tri_idx, nb);
3350 flipped_any = true;
3351 break; // restart since crossings changed
3352 }
3353 }
3354
3355 if (not flipped_any)
3356 {
3357 // Try flipping any crossing edge even non-convex (won't flip but
3358 // we break infinite loop).
3359 break;
3360 }
3361 }
3362
3363 // Final check — mark if the edge appeared.
3364 if (edge_exists(tris, u, v, et, el))
3365 mark_constrained(tris, u, v);
3366 }
3367
3369 static void lawson_flip(const Array<Point> &pts, Array<Tri> &tris)
3370 {
3371 // Collect all non-constrained interior edges.
3372 // Use a simple iterative approach: keep flipping until no more flips.
3373 bool changed = true;
3374 const size_t max_passes = tris.size() * 4 + 100;
3375 size_t pass = 0;
3376
3377 while (changed and pass++ < max_passes)
3378 {
3379 changed = false;
3380
3381 for (size_t t = 0; t < tris.size(); ++t)
3382 {
3383 if (not tris(t).alive)
3384 continue;
3385
3386 for (int e = 0; e < 3; ++e)
3387 {
3388 if (tris(t).constrained[e])
3389 continue; // don't flip constrained edges
3390
3391 const size_t nb = tris(t).adj[e];
3392 if (nb == NONE or nb <= t) // process each pair once
3393 continue;
3394 if (not tris(nb).alive)
3395 continue;
3396
3397 // in-circle test: is the opposite vertex of nb inside
3398 // the circumcircle of t?
3399 const size_t lb = adj_of(tris(nb), t);
3400 if (lb == NONE)
3401 continue;
3402
3403 const size_t d = tris(nb).v[lb]; // opposite vertex in nb
3404
3405 // Check CCW orientation of triangle t
3406 const Orientation o =
3407 orientation(pts(tris(t).v[0]), pts(tris(t).v[1]), pts(tris(t).v[2]));
3408 if (o == Orientation::COLLINEAR)
3409 continue;
3410
3411 const Geom_Number det = in_circle_determinant(pts(tris(t).v[0]), pts(tris(t).v[1]),
3412 pts(tris(t).v[2]), pts(d));
3413
3414 bool violates = false;
3415 if (o == Orientation::CCW and det > 0)
3416 violates = true;
3417 else if (o == Orientation::CW and det < 0)
3418 violates = true;
3419
3420 if (not violates)
3421 continue;
3422
3423 // Check convexity before flipping.
3424 const size_t a = tris(t).v[e];
3425 const size_t b = tris(t).v[(e + 1) % 3];
3426 const size_t c = tris(t).v[(e + 2) % 3];
3427
3428 if (is_convex_quad(pts, a, b, c, d))
3429 {
3430 flip_edge(tris, t, nb);
3431 changed = true;
3432 }
3433 }
3434 }
3435 }
3436 }
3437
3440 [[nodiscard]] static Array<Point> merge_and_deduplicate(const DynList<Point> &points,
3441 const DynList<Segment> &constraints)
3442 {
3444 for (auto it = points.get_it(); it.has_curr(); it.next_ne())
3445 all.append(it.get_curr());
3446
3447 // Collect constraint segments into an array for pairwise checks.
3448 Array<Segment> con_arr;
3449 for (auto it = constraints.get_it(); it.has_curr(); it.next_ne())
3450 {
3451 const Segment &s = it.get_curr();
3452 all.append(s.get_src_point());
3453 all.append(s.get_tgt_point());
3454 con_arr.append(s);
3455 }
3456
3457 // Compute pairwise intersection points of constraints.
3458 for (size_t i = 0; i < con_arr.size(); ++i)
3459 for (size_t j = i + 1; j < con_arr.size(); ++j)
3460 if (con_arr(i).intersects_properly_with(con_arr(j)))
3461 all.append(segment_intersection_point(con_arr(i), con_arr(j)));
3462
3463 quicksort_op(all, [](const Point &a, const Point &b)
3464 {
3465 return lexicographic_less(a, b);
3466 });
3467
3468 Array<Point> ret;
3469 ret.reserve(all.size());
3470 for (size_t i = 0; i < all.size(); ++i)
3471 if (ret.is_empty() or ret.get_last() != all(i))
3472 ret.append(all(i));
3473
3474 return ret;
3475 }
3476
3478 [[nodiscard]] static Array<IndexedEdge> map_constraints(const Array<Point> &sites,
3479 const DynList<Segment> &constraints)
3480 {
3481 Array<IndexedEdge> result;
3482
3483 for (auto it = constraints.get_it(); it.has_curr(); it.next_ne())
3484 {
3485 const Segment &seg = it.get_curr();
3486 const size_t u = find_point_index(sites, seg.get_src_point());
3487 const size_t v = find_point_index(sites, seg.get_tgt_point());
3488
3489 if (u == NONE or v == NONE or u == v)
3490 continue;
3491
3492 // Find interior collinear points and split.
3494 chain.append(u);
3495 for (size_t i = 0; i < sites.size(); ++i)
3496 {
3497 if (i == u or i == v)
3498 continue;
3499 if (seg.contains(sites(i)))
3500 chain.append(i);
3501 }
3502 chain.append(v);
3503
3504 // Sort chain by distance from u.
3505 if (chain.size() > 2)
3506 {
3507 const Point &pu = sites(u);
3508 quicksort_op(chain, [&](const size_t a, const size_t b)
3509 {
3510 const Geom_Number da =
3511 (sites(a).get_x() - pu.get_x()) * (sites(a).get_x() - pu.get_x()) +
3512 (sites(a).get_y() - pu.get_y()) * (sites(a).get_y() - pu.get_y());
3513 const Geom_Number db =
3514 (sites(b).get_x() - pu.get_x()) * (sites(b).get_x() - pu.get_x()) +
3515 (sites(b).get_y() - pu.get_y()) * (sites(b).get_y() - pu.get_y());
3516 return da < db;
3517 });
3518 }
3519
3520 for (size_t i = 0; i + 1 < chain.size(); ++i)
3521 {
3522 const size_t a = chain(i) < chain(i + 1) ? chain(i) : chain(i + 1);
3523 const size_t b = chain(i) < chain(i + 1) ? chain(i + 1) : chain(i);
3524 // Avoid duplicates.
3525 bool dup = false;
3526 for (size_t j = 0; j < result.size(); ++j)
3527 if (result(j).u == a and result(j).v == b)
3528 {
3529 dup = true;
3530 break;
3531 }
3532 if (not dup)
3533 result.append(IndexedEdge{a, b});
3534 }
3535 }
3536
3537 return result;
3538 }
3539
3540public:
3548 [[nodiscard]] Result operator () (const DynList<Point> &points,
3549 const DynList<Segment> &constraints) const
3550 {
3551 Result ret;
3552
3553 // 1. Merge and deduplicate.
3554 ret.sites = merge_and_deduplicate(points, constraints);
3555 const size_t n = ret.sites.size();
3556
3557 if (n < 3)
3558 return ret;
3559
3560 // Check all-collinear.
3561 {
3562 bool collinear = true;
3563 for (size_t i = 2; i < n and collinear; ++i)
3564 if (orientation(ret.sites(0), ret.sites(1), ret.sites(i)) != Orientation::COLLINEAR)
3565 collinear = false;
3566 if (collinear)
3567 return ret;
3568 }
3569
3570 // 2. Compute unconstrained DT.
3571 DynList<Point> site_list;
3572 for (size_t i = 0; i < n; ++i)
3573 site_list.append(ret.sites(i));
3574
3575 constexpr DelaunayTriangulationBowyerWatson dt_algo;
3576 auto [sites, triangles] = dt_algo(site_list);
3577
3578 if (triangles.is_empty())
3579 return ret;
3580
3581 // The DT may have reordered sites. We need to use its sites array
3582 // and remap. Since both are sorted/deduped, they should match.
3583 ret.sites = sites;
3584
3585 // 3. Build adjacency mesh.
3586 Array<Tri> tris;
3587 build_adjacency(tris, triangles);
3588
3589 // 4. Map constraints to index pairs (with splitting).
3590 Array<IndexedEdge> indexed_constraints = map_constraints(ret.sites, constraints);
3591
3592 // 5. Enforce each constraint.
3593 for (size_t i = 0; i < indexed_constraints.size(); ++i)
3594 enforce_constraint(ret.sites, tris, indexed_constraints(i).u, indexed_constraints(i).v);
3595
3596 // 6. Lawson flip pass.
3597 lawson_flip(ret.sites, tris);
3598
3599 // 7. Extract result.
3600 ret.triangles.reserve(tris.size());
3601 for (size_t t = 0; t < tris.size(); ++t)
3602 {
3603 if (not tris(t).alive)
3604 continue;
3605 if (orientation(ret.sites(tris(t).v[0]), ret.sites(tris(t).v[1]), ret.sites(tris(t).v[2])) ==
3607 continue;
3608 ret.triangles.append(IndexedTriangle{tris(t).v[0], tris(t).v[1], tris(t).v[2]});
3609 }
3610
3611 // Collect constrained edges.
3612 ret.constrained_edges.reserve(indexed_constraints.size());
3613 for (size_t i = 0; i < indexed_constraints.size(); ++i)
3614 ret.constrained_edges.append(indexed_constraints(i));
3615
3616 return ret;
3617 }
3618
3622 [[nodiscard]] Result operator () (const std::initializer_list<Point> points,
3623 const std::initializer_list<Segment> constraints) const
3624 {
3625 DynList<Point> pts;
3626 for (const Point &p : points)
3627 pts.append(p);
3628
3629 DynList<Segment> segs;
3630 for (const Segment &s : constraints)
3631 segs.append(s);
3632
3633 return (*this)(pts, segs);
3634 }
3635
3640 {
3642 for (size_t i = 0; i < result.triangles.size(); ++i)
3643 {
3644 const auto &[ii, j, k] = result.triangles(i);
3645 out.append(Triangle(result.sites(ii), result.sites(j), result.sites(k)));
3646 }
3647 return out;
3648 }
3649};
3650
3651// ============================================================================
3652// Voronoi Diagram (Dual of Delaunay)
3653// ============================================================================
3654
3676{
3677public:
3690
3701
3711
3722
3723private:
3725
3729 [[nodiscard]] static Point circumcenter(const Point &a, const Point &b, const Point &c)
3730 {
3731 const Geom_Number &ax = a.get_x();
3732 const Geom_Number &ay = a.get_y();
3733 const Geom_Number &bx = b.get_x();
3734 const Geom_Number &by = b.get_y();
3735 const Geom_Number &cx = c.get_x();
3736 const Geom_Number &cy = c.get_y();
3737
3738 const Geom_Number a2 = ax * ax + ay * ay;
3739 const Geom_Number b2 = bx * bx + by * by;
3740 const Geom_Number c2 = cx * cx + cy * cy;
3741
3742 const Geom_Number d = ax * (by - cy) + bx * (cy - ay) + cx * (ay - by);
3743 ah_domain_error_if(d == 0) << "Circumcenter undefined for collinear points";
3744 const Geom_Number den = d + d;
3745
3746 const Geom_Number ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / den;
3747 const Geom_Number uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / den;
3748
3749 return {ux, uy};
3750 }
3751
3755 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &p)
3756 {
3757 ah_domain_error_if(not p.is_closed()) << "Polygon must be closed";
3758 ah_domain_error_if(p.size() < 3) << "Polygon must have at least 3 vertices";
3759
3761 }
3762
3766 [[nodiscard]] static bool is_convex(const Array<Point> &verts)
3767 {
3768 if (verts.size() < 3)
3769 return false;
3770 return GeomPolygonUtils::is_convex(verts);
3771 }
3772
3777 const Point &t)
3778 {
3779 const Point mid((s.get_x() + t.get_x()) / 2, (s.get_y() + t.get_y()) / 2);
3780
3781 const Geom_Number dx = t.get_x() - s.get_x();
3782 const Geom_Number dy = t.get_y() - s.get_y();
3783 const Point q(mid.get_x() - dy, mid.get_y() + dx);
3784
3785 return {mid, q}; // the left side contains s
3786 }
3787
3788 [[nodiscard]] static Array<ClippedCell> indexed_clipped_cells(const Array<Point> &sites,
3789 const Array<Polygon> &polys)
3790 {
3791 ah_domain_error_if(sites.size() != polys.size()) << "Sites and clipped polygons size mismatch";
3792
3794 ret.reserve(sites.size());
3795
3796 for (size_t i = 0; i < sites.size(); ++i)
3797 {
3799 cell.site_index = i;
3800 cell.site = sites(i);
3801 cell.polygon = polys(i);
3802 ret.append(std::move(cell));
3803 }
3804
3805 return ret;
3806 }
3807
3808public:
3816 {
3817 Result ret;
3818 ret.sites = dt.sites;
3819
3820 if (dt.triangles.is_empty())
3821 return ret;
3822
3823 Array<Point> centers;
3824 centers.reserve(dt.triangles.size());
3825 for (size_t idx = 0; idx < dt.triangles.size(); ++idx)
3826 {
3827 const auto &[i, j, k] = dt.triangles(idx);
3828 centers.append(circumcenter(dt.sites(i), dt.sites(j), dt.sites(k)));
3829 }
3830 ret.vertices = centers;
3831
3832 Array<unsigned char> on_hull;
3833 on_hull.reserve(dt.sites.size());
3834 for (size_t i = 0; i < dt.sites.size(); ++i)
3835 on_hull.append(0);
3836
3838 dt.triangles,
3839 [&](const Array<GeomTriangleAdjacencyUtils::EdgeRef> &edges, const size_t first,
3840 const size_t last)
3841 {
3842 if (const size_t cnt = last - first; cnt >= 2)
3843 {
3844 const Point &p1 = centers(edges(first).tri);
3845 const Point &p2 = centers(edges(first + 1).tri);
3846 ret.edges.append(Edge{edges(first).u, edges(first).v, p1, p2, false, Point()});
3847 return;
3848 }
3849
3850 const auto &edge = edges(first);
3851 const size_t u = edge.u;
3852 const size_t v = edge.v;
3853 const size_t tri = edge.tri;
3854 const size_t third = edge.third;
3855 on_hull(u) = 1;
3856 on_hull(v) = 1;
3857
3858 const Point &pu = dt.sites(u);
3859 const Point &pv = dt.sites(v);
3860 const Point &pw = dt.sites(third);
3861
3862 const Geom_Number ex = pv.get_x() - pu.get_x();
3863 const Geom_Number ey = pv.get_y() - pu.get_y();
3864
3865 Geom_Number dirx = -ey;
3866 Geom_Number diry = ex;
3867 if (orientation(pu, pv, pw) == Orientation::CCW)
3868 {
3869 dirx = ey;
3870 diry = -ex;
3871 }
3872
3873 const Point &src = centers(tri);
3874 ret.edges.append(Edge{u, v, src, src, true, Point(dirx, diry)});
3875 });
3876
3877 // Pre-build site -> incident triangles index (O(T) instead of O(n*T)).
3878 Array<Array<size_t>> incidence;
3879 incidence.reserve(dt.sites.size());
3880 for (size_t s = 0; s < dt.sites.size(); ++s)
3881 incidence.append(Array<size_t>());
3882 for (size_t t = 0; t < dt.triangles.size(); ++t)
3883 {
3884 const auto &[ti, tj, tk] = dt.triangles(t);
3885 incidence(ti).append(t);
3886 incidence(tj).append(t);
3887 incidence(tk).append(t);
3888 }
3889
3890 ret.cells.reserve(dt.sites.size());
3891 for (size_t s = 0; s < dt.sites.size(); ++s)
3892 {
3893 Array<Point> verts;
3894 verts.reserve(incidence(s).size());
3895 for (size_t idx = 0; idx < incidence(s).size(); ++idx)
3896 verts.append(centers(incidence(s)(idx)));
3897
3898 const Point site = dt.sites(s);
3899 if (verts.size() > 1)
3900 {
3901 quicksort_op(verts, [&site](const Point &a, const Point &b)
3902 {
3903 const Geom_Number ax = a.get_x() - site.get_x();
3904 const Geom_Number ay = a.get_y() - site.get_y();
3905 const Geom_Number bx = b.get_x() - site.get_x();
3906 const Geom_Number by = b.get_y() - site.get_y();
3907
3908 const bool au = (ay > 0) or (ay == 0 and ax >= 0);
3909 const bool bu = (by > 0) or (by == 0 and bx >= 0);
3910 if (au != bu)
3911 return au and not bu;
3912
3913 if (const Geom_Number cr = ax * by - ay * bx; cr != 0)
3914 return cr > 0;
3915
3916 return (ax * ax + ay * ay) < (bx * bx + by * by);
3917 });
3918 }
3919
3920 Array<Point> clean;
3921 clean.reserve(verts.size());
3922 for (size_t k = 0; k < verts.size(); ++k)
3923 if (clean.is_empty() or clean.get_last() != verts(k))
3924 clean.append(verts(k));
3925 if (clean.size() > 1 and clean(0) == clean.get_last())
3926 static_cast<void>(clean.remove_last());
3927
3928 Cell cell;
3929 cell.site_index = s;
3930 cell.site = site;
3931 cell.bounded = on_hull(s) == 0;
3932 cell.vertices = clean;
3933 ret.cells.append(std::move(cell));
3934 }
3935
3936 return ret;
3937 }
3938
3945 [[nodiscard]] Result operator () (const DynList<Point> &point_set) const
3946 {
3947 return (*this)(delaunay(point_set));
3948 }
3949
3956 [[nodiscard]] Result operator () (const std::initializer_list<Point> il) const
3957 {
3958 return (*this)(delaunay(il));
3959 }
3960
3973 static Array<Polygon> clipped_cells(const Array<Point> &sites, const Polygon &clip)
3974 {
3975 const Array<Point> clip_verts = extract_vertices(clip);
3976 ah_domain_error_if(not is_convex(clip_verts)) << "Clip polygon must be convex";
3977
3980
3981 const size_t n = sites.size();
3982
3983 // Compute Delaunay to get adjacency: each site's Voronoi cell is
3984 // bounded only by bisectors with its Delaunay neighbors (~6 on avg),
3985 // reducing total complexity from O(n^2 log n) to O(n log n).
3986 constexpr DelaunayTriangulationBowyerWatson dt_algo;
3987 DynList<Point> site_list;
3988 for (size_t i = 0; i < n; ++i)
3989 site_list.append(sites(i));
3990 auto dt = dt_algo(site_list);
3991
3992 // Map Delaunay site indices back to input indices.
3993 // dt.sites may be reordered/deduped, so match by position.
3994 Array<size_t> dt_to_input;
3995 dt_to_input.reserve(dt.sites.size());
3996 for (size_t di = 0; di < dt.sites.size(); ++di)
3997 {
3998 size_t match = 0;
3999 for (size_t oi = 0; oi < n; ++oi)
4000 if (dt.sites(di) == sites(oi))
4001 {
4002 match = oi;
4003 break;
4004 }
4005 dt_to_input.append(match);
4006 }
4007
4008 // Build adjacency lists from Delaunay triangles (in input-index space)
4009 auto adj = Array<DynSetTree<size_t, Treap_Rk>>::create_reserved(n);
4010 for (size_t i = 0; i < n; ++i)
4011 adj.append(DynSetTree<size_t, Treap_Rk>());
4012 for (size_t t = 0; t < dt.triangles.size(); ++t)
4013 {
4014 const size_t a = dt_to_input(dt.triangles(t).i);
4015 const size_t b = dt_to_input(dt.triangles(t).j);
4016 const size_t c = dt_to_input(dt.triangles(t).k);
4017 adj(a).insert(b);
4018 adj(a).insert(c);
4019 adj(b).insert(a);
4020 adj(b).insert(c);
4021 adj(c).insert(a);
4022 adj(c).insert(b);
4023 }
4024
4025 Array<Polygon> ret;
4026 ret.reserve(n);
4027
4028 for (size_t i = 0; i < n; ++i)
4029 {
4032
4033 adj(i).for_each([&](size_t j)
4034 {
4035 if (sites(j) != sites(i))
4036 hps.append(bisector_halfplane_for_site(sites(i), sites(j)));
4037 });
4038
4039 // If a site has no Delaunay neighbors (degenerate case),
4040 // fall back to the clip polygon alone.
4041 ret.append(hpi(hps));
4042 }
4043
4044 return ret;
4045 }
4046
4054 [[nodiscard]] static Array<Polygon> clipped_cells(const Result &vor, const Polygon &clip)
4055 {
4056 return clipped_cells(vor.sites, clip);
4057 }
4058
4066 [[nodiscard]] Array<Polygon> clipped_cells(const DynList<Point> &point_set, const Polygon &clip) const
4067 {
4068 return clipped_cells(delaunay(point_set).sites, clip);
4069 }
4070
4078 [[nodiscard]] Array<Polygon> clipped_cells(const std::initializer_list<Point> il,
4079 const Polygon &clip) const
4080 {
4081 return clipped_cells(delaunay(il).sites, clip);
4082 }
4083
4092 {
4093 return indexed_clipped_cells(sites, clipped_cells(sites, clip));
4094 }
4095
4103 [[nodiscard]] static Array<ClippedCell> clipped_cells_indexed(const Result &vor, const Polygon &clip)
4104 {
4105 return clipped_cells_indexed(vor.sites, clip);
4106 }
4107
4116 const Polygon &clip) const
4117 {
4118 return clipped_cells_indexed(delaunay(point_set).sites, clip);
4119 }
4120
4128 [[nodiscard]] Array<ClippedCell> clipped_cells_indexed(const std::initializer_list<Point> il,
4129 const Polygon &clip) const
4130 {
4131 return clipped_cells_indexed(delaunay(il).sites, clip);
4132 }
4133};
4134
4135// ============================================================================
4136// Voronoi Diagram — O(n log n) via Incremental Delaunay Dual
4137// ============================================================================
4138
4176{
4179
4180public:
4185
4191 [[nodiscard]] Result operator () (const DynList<Point> &pts) const
4192 {
4193 const auto dt = delaunay_(pts);
4194 return voronoi_(dt);
4195 }
4196
4202 [[nodiscard]] Result operator () (const std::initializer_list<Point> il) const
4203 {
4204 DynList<Point> pts;
4205 for (const Point &p : il)
4206 pts.append(p);
4207 return (*this)(pts);
4208 }
4209
4216 [[nodiscard]] Array<ClippedCell> clipped_cells(const DynList<Point> &pts, const Polygon &clip) const
4217 {
4218 auto [sites, triangles] = delaunay_(pts);
4220 }
4221};
4222
4238class [[deprecated("VoronoiDiagramFortune goes in 8.0.0: use VoronoiDiagram, which it calls")]]
4240{
4242
4243public:
4248
4255 [[nodiscard]] Result operator () (const DynList<Point> &pts) const
4256 {
4257 return voronoi_(pts);
4258 }
4259
4265 [[nodiscard]] Result operator () (const std::initializer_list<Point> il) const
4266 {
4267 return voronoi_(il);
4268 }
4269
4276 [[nodiscard]] Array<ClippedCell> clipped_cells(const DynList<Point> &pts, const Polygon &clip) const
4277 {
4278 return voronoi_.clipped_cells(pts, clip);
4279 }
4280
4282 [[nodiscard]] Array<ClippedCell> clipped_cells(const std::initializer_list<Point> il,
4283 const Polygon &clip) const
4284 {
4285 DynList<Point> pts;
4286 for (const Point &p : il)
4287 pts.append(p);
4288 return clipped_cells(pts, clip);
4289 }
4290};
4291
4292// ============================================================================
4293// Convex Hull Algorithms
4294// ============================================================================
4295
4320{
4325 {
4326 bool operator () (const Point &p1, const Point &p2) const
4327 {
4328 if (p1.get_x() < p2.get_x())
4329 return true;
4330
4331 if (p2.get_x() < p1.get_x())
4332 return false;
4333
4334 return p1.get_y() < p2.get_y();
4335 }
4336 };
4337
4342 {
4343 Array<Point> points;
4344 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
4345 points.append(it.get_curr());
4346
4347 if (points.size() <= 1)
4348 return points;
4349
4350 quicksort_op(points, LexicographicCmp());
4351
4353 unique.reserve(points.size());
4354 unique.append(points(0));
4355 for (size_t i = 1; i < points.size(); ++i)
4356 if (points(i) != unique.get_last())
4357 unique.append(points(i));
4358
4359 return unique;
4360 }
4361
4365 [[nodiscard]] static Geom_Number turn(const Point &a, const Point &b, const Point &c)
4366 {
4367 return area_of_parallelogram(a, b, c);
4368 }
4369
4370public:
4377 Polygon operator () (const DynList<Point> &point_set) const
4378 {
4379 Polygon ret;
4380 Array<Point> points = sorted_unique_points(point_set);
4381 const size_t n = points.size();
4382
4383 if (n == 0)
4384 return ret;
4385
4386 if (n == 1)
4387 {
4388 ret.add_vertex(points(0));
4389 return ret;
4390 }
4391
4392 Array<Point> lower;
4393 lower.reserve(n);
4394 for (size_t i = 0; i < n; ++i)
4395 {
4396 while (lower.size() >= 2 &&
4397 turn(lower(lower.size() - 2), lower(lower.size() - 1), points(i)) <= 0)
4398 static_cast<void>(lower.remove_last());
4399 lower.append(points(i));
4400 }
4401
4402 Array<Point> upper;
4403 upper.reserve(n);
4404 for (size_t i = n; i > 0; --i)
4405 {
4406 const Point &p = points(i - 1);
4407 while (upper.size() >= 2 && turn(upper(upper.size() - 2), upper(upper.size() - 1), p) <= 0)
4408 static_cast<void>(upper.remove_last());
4409 upper.append(p);
4410 }
4411
4412 // Remove duplicate endpoints before concatenating chains.
4413 static_cast<void>(lower.remove_last());
4414 static_cast<void>(upper.remove_last());
4415
4416 for (size_t i = 0; i < lower.size(); ++i)
4417 ret.add_vertex(lower(i));
4418
4419 for (size_t i = 0; i < upper.size(); ++i)
4420 ret.add_vertex(upper(i));
4421
4422 if (ret.size() >= 3)
4423 ret.close();
4424
4425 return ret;
4426 }
4427};
4428
4454{
4459 {
4460 bool operator () (const Point &p1, const Point &p2) const
4461 {
4462 if (p1.get_x() < p2.get_x())
4463 return true;
4464
4465 if (p2.get_x() < p1.get_x())
4466 return false;
4467
4468 return p1.get_y() < p2.get_y();
4469 }
4470 };
4471
4476 {
4477 Array<Point> points;
4478 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
4479 points.append(it.get_curr());
4480
4481 if (points.size() <= 1)
4482 return points;
4483
4484 quicksort_op(points, LexicographicCmp());
4485
4487 unique.reserve(points.size());
4488 unique.append(points(0));
4489 for (size_t i = 1; i < points.size(); ++i)
4490 if (points(i) != unique.get_last())
4491 unique.append(points(i));
4492
4493 return unique;
4494 }
4495
4499 [[nodiscard]] static Geom_Number turn(const Point &a, const Point &b, const Point &c)
4500 {
4501 return area_of_parallelogram(a, b, c);
4502 }
4503
4504public:
4511 Polygon operator () (const DynList<Point> &point_set) const
4512 {
4513 Polygon ret;
4514 Array<Point> points = sorted_unique_points(point_set);
4515 const size_t n = points.size();
4516
4517 if (n == 0)
4518 return ret;
4519
4520 if (n == 1)
4521 {
4522 ret.add_vertex(points(0));
4523 return ret;
4524 }
4525
4526 // Pivot = lowest y, and lowest x on ties.
4527 size_t pivot_idx = 0;
4528 for (size_t i = 1; i < n; ++i)
4529 {
4530 if (points(i).get_y() < points(pivot_idx).get_y())
4531 {
4532 pivot_idx = i;
4533 continue;
4534 }
4535
4536 if (points(i).get_y() == points(pivot_idx).get_y() &&
4537 points(i).get_x() < points(pivot_idx).get_x())
4538 pivot_idx = i;
4539 }
4540
4541 const Point pivot = points(pivot_idx);
4542 if (pivot_idx != 0)
4543 {
4544 const Point tmp = points(0);
4545 points(0) = points(pivot_idx);
4546 points(pivot_idx) = tmp;
4547 }
4548
4549 Array<Point> polar;
4550 polar.reserve(n - 1);
4551 for (size_t i = 1; i < n; ++i)
4552 polar.append(points(i));
4553
4554 quicksort_op(polar, [&pivot](const Point &a, const Point &b)
4555 {
4556 const Geom_Number area = area_of_parallelogram(pivot, a, b);
4557 if (area > 0)
4558 return true;
4559 if (area < 0)
4560 return false;
4561
4562 // Same angle: keep nearer first; later we keep only farthest.
4563 return pivot.distance_squared_to(a) < pivot.distance_squared_to(b);
4564 });
4565
4566 // Keep only the farthest point per polar direction.
4567 Array<Point> filtered;
4568 filtered.reserve(polar.size());
4569 for (size_t i = 0; i < polar.size();)
4570 {
4571 size_t j = i;
4572 while (j + 1 < polar.size() && area_of_parallelogram(pivot, polar(j), polar(j + 1)) == 0)
4573 ++j;
4574 filtered.append(polar(j));
4575 i = j + 1;
4576 }
4577
4578 if (filtered.size() == 1)
4579 {
4580 ret.add_vertex(pivot);
4581 ret.add_vertex(filtered(0));
4582 // Cannot close with only 2 vertices - return unclosed degenerate hull
4583 return ret;
4584 }
4585
4586 Array<Point> hull;
4587 hull.reserve(filtered.size() + 1);
4588 hull.append(pivot);
4589 hull.append(filtered(0));
4590
4591 for (size_t i = 1; i < filtered.size(); ++i)
4592 {
4593 const Point &p = filtered(i);
4594 while (hull.size() >= 2 && turn(hull(hull.size() - 2), hull(hull.size() - 1), p) <= 0)
4595 static_cast<void>(hull.remove_last());
4596 hull.append(p);
4597 }
4598
4599 for (size_t i = 0; i < hull.size(); ++i)
4600 ret.add_vertex(hull(i));
4601
4602 if (ret.size() >= 3)
4603 ret.close();
4604
4605 return ret;
4606 }
4607};
4608
4639{
4644 {
4646 static bool cmp_point(const Point &p1, const Point &p2)
4647 {
4648 if (p1.get_x() < p2.get_x())
4649 return true;
4650
4651 return not (p2.get_x() < p1.get_x()) and p1.get_y() < p2.get_y();
4652 }
4653
4655 bool operator () (const Segment &s1, const Segment &s2) const
4656 {
4657 if (cmp_point(s1.get_src_point(), s2.get_src_point()))
4658 return true;
4659
4660 return not (cmp_point(s2.get_src_point(), s1.get_src_point())) and
4662 }
4663 };
4664
4667
4671 static bool are_all_points_on_left(const DynList<Point> &l, const Segment &s)
4672 {
4673 for (auto it = l.get_it(); it.has_curr(); it.next_ne())
4674 if (const Point &p = it.get_curr(); p.is_right_of(s))
4675 return false;
4676
4677 return true;
4678 }
4679
4686 static SegmentSet extreme_edges(const DynList<Point> &point_set)
4687 {
4688 SegmentSet ret;
4689
4690 for (auto i = point_set.get_it(); i.has_curr(); i.next_ne())
4691 {
4692 const Point &p_i = i.get_curr();
4693
4694 for (auto j = point_set.get_it(); j.has_curr(); j.next_ne())
4695 {
4696 const Point &p_j = j.get_curr();
4697
4698 if (p_i == p_j)
4699 continue;
4700
4701 if (Segment s(p_i, p_j); are_all_points_on_left(point_set, s))
4702 ret.insert(s);
4703 }
4704 }
4705
4706 return ret;
4707 }
4708
4709public:
4716 Polygon operator () (const DynList<Point> &point_set) const
4717 {
4718 Polygon ret;
4719
4720 if (point_set.is_empty())
4721 return ret;
4722
4723 auto check_it = point_set.get_it();
4724 const Point first = check_it.get_curr();
4725 bool has_distinct = false;
4726 check_it.next();
4727 for (; check_it.has_curr(); check_it.next_ne())
4728 if (check_it.get_curr() != first)
4729 {
4730 has_distinct = true;
4731 break;
4732 }
4733
4734 if (not has_distinct)
4735 {
4736 ret.add_vertex(first);
4737 return ret;
4738 }
4739
4740 SegmentSet extremes = extreme_edges(point_set);
4741
4742 const Segment first_segment = extremes.remove_pos(0);
4743 ret.add_vertex(first_segment.get_src_point());
4744 ret.add_vertex(first_segment.get_tgt_point());
4745
4746 while (true)
4747 {
4748 const Vertex &last_vertex = ret.get_last_vertex();
4749
4750 const Segment *ptr = extremes.find_ptr([&last_vertex](const Segment &s)
4751 {
4752 return s.get_src_point() == last_vertex;
4753 });
4754
4755 ah_domain_error_if(ptr == nullptr)
4756 << "BruteForceConvexHull: broken chain (degenerate input?)";
4757
4758 if (ptr->get_tgt_point() == ret.get_first_vertex())
4759 break;
4760
4761 ret.add_vertex(ptr->get_tgt_point());
4762
4763 extremes.remove(*ptr);
4764 }
4765
4766 if (ret.size() >= 3)
4767 ret.close();
4768 return ret;
4769 }
4770};
4771
4802{
4806 static const Point *get_lowest_point(const DynList<Point> &point_set)
4807 {
4808 auto it = point_set.get_it();
4809 const Point *ret = &it.get_curr();
4810 it.next();
4811
4812 for (/* nothing */; it.has_curr(); it.next_ne())
4813 {
4814 const Point &p = it.get_curr();
4815 if (p.get_y() < ret->get_y() or (p.get_y() == ret->get_y() and p.get_x() < ret->get_x()))
4816 ret = &p;
4817 }
4818
4819 return ret;
4820 }
4821
4822public:
4833 Polygon operator () (const DynList<Point> &point_set) const
4834 {
4835 Polygon ret;
4836
4837 if (point_set.is_empty())
4838 return ret;
4839
4840 const Point *start = get_lowest_point(point_set);
4841 const Point *current = start;
4842
4843 do
4844 {
4845 ret.add_vertex(*current);
4846 const Point *next = nullptr;
4847
4848 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
4849 {
4850 const Point &candidate = it.get_curr();
4851
4852 if (candidate == *current)
4853 continue;
4854
4855 if (next == nullptr)
4856 {
4857 next = &candidate;
4858 continue;
4859 }
4860
4861 if (const Orientation o = orientation(*current, *next, candidate); o == Orientation::CW)
4862 next = &candidate;
4863 else if (o == Orientation::COLLINEAR and
4864 current->distance_squared_to(candidate) > current->distance_squared_to(*next))
4865 next = &candidate;
4866 }
4867
4868 if (next == nullptr)
4869 break;
4870
4871 current = next;
4872 } while (current != start);
4873
4874 if (ret.size() >= 3)
4875 ret.close();
4876 return ret;
4877 }
4878};
4879
4909{
4926 static Point get_farthest_point(const DynList<Point> &point_set, const Segment &s)
4927 {
4928 // Compare perpendicular distances via |area_of_parallelogram|.
4929 // Since the segment base is constant for all candidates, comparing
4930 // |area| is equivalent to comparing distance (avoids sqrt).
4931 Geom_Number max_area = 0;
4932 Point ret;
4933 const Point &a = s.get_src_point();
4934 const Point &b = s.get_tgt_point();
4935
4936 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
4937 {
4938 const Point &p = it.get_curr();
4939 Geom_Number area = area_of_parallelogram(a, b, p);
4940 if (area < 0)
4941 area = -area;
4942
4943 if (area > max_area)
4944 {
4945 ret = p;
4946 max_area = area;
4947 }
4948 }
4949
4950 return ret;
4951 }
4952
4977 static std::pair<DynList<Point>, DynList<Point>> get_right_points(DynList<Point> &point_set,
4978 const Point &a,
4979 const Point &b,
4980 const Point &c)
4981 {
4982 std::pair<DynList<Point>, DynList<Point>> ret;
4983
4984 while (not point_set.is_empty())
4985 {
4986 Point p = point_set.remove_first();
4987
4988 if (p != a and p != c and area_of_parallelogram(a, c, p) < 0)
4989 {
4990 ret.first.append(p);
4991 continue;
4992 }
4993
4994 if (p != c and p != b and area_of_parallelogram(c, b, p) < 0)
4995 ret.second.append(p);
4996 }
4997
4998 return ret;
4999 }
5000
5014 static DynList<Point> quick_hull(DynList<Point> &point_set, const Point &a, const Point &b)
5015 {
5016 if (point_set.is_empty())
5017 return {};
5018
5019 const Point c = get_farthest_point(point_set, Segment(a, b));
5020
5021 auto [s_ac, s_bc] = get_right_points(point_set, a, b, c);
5022
5023 DynList<Point> ret = quick_hull(s_ac, a, c);
5024 DynList<Point> tmp = quick_hull(s_bc, c, b);
5025 ret.append(c);
5026 ret.concat(tmp);
5027
5028 return ret;
5029 }
5030
5038 static std::pair<Point, Point> search_extremes(const DynList<Point> &point_set)
5039 {
5040 auto it = point_set.get_it();
5041 Point leftmost = it.get_curr();
5042 Point rightmost = it.get_curr();
5043 it.next();
5044
5045 for (/* nothing */; it.has_curr(); it.next_ne())
5046 {
5047 const Point &p = it.get_curr();
5048
5049 if (p.get_x() < leftmost.get_x())
5050 leftmost = p;
5051
5052 if (p.get_x() > rightmost.get_x())
5053 rightmost = p;
5054 }
5055
5056 return std::make_pair(leftmost, rightmost);
5057 }
5058
5069 static std::pair<DynList<Point>, DynList<Point>> partition(const DynList<Point> &point_set,
5070 const Point &a,
5071 const Point &b)
5072 {
5073 std::pair<DynList<Point>, DynList<Point>> ret;
5074
5075 for (auto it = point_set.get_it(); it.has_curr(); it.next_ne())
5076 if (const Point &p = it.get_curr(); area_of_parallelogram(a, b, p) < 0)
5077 ret.first.append(p);
5078 else
5079 ret.second.append(p);
5080
5081 return ret;
5082 }
5083
5084public:
5091 Polygon operator () (const DynList<Point> &point_set) const
5092 {
5093 Polygon ret;
5094
5095 if (point_set.is_empty())
5096 return ret;
5097
5098 const auto [leftmost, rightmost] = search_extremes(point_set);
5099 if (leftmost == rightmost)
5100 {
5101 ret.add_vertex(leftmost);
5102 return ret;
5103 }
5104
5105 auto [right, left_or_collinear] = partition(point_set, leftmost, rightmost);
5106
5107 DynList<Point> s1 = quick_hull(right, leftmost, rightmost);
5108 DynList<Point> s2 = quick_hull(left_or_collinear, rightmost, leftmost);
5109
5110 DynList<Point> convex_set;
5111 convex_set.append(leftmost);
5112 convex_set.concat(s1);
5113 convex_set.append(rightmost);
5114 convex_set.concat(s2);
5115
5116 for (auto it = convex_set.get_it(); it.has_curr(); it.next_ne())
5117 ret.add_vertex(it.get_curr());
5118
5119 if (ret.size() >= 3)
5120 ret.close();
5121 return ret;
5122 }
5123};
5124
5125// ============================================================================
5126// Segment-Segment Intersection (Dedicated O(1))
5127// ============================================================================
5128
5150{
5151public:
5155 enum class Kind
5156 {
5157 NONE,
5158 POINT,
5159 OVERLAP
5160 };
5161
5165 struct Result
5166 {
5170 Segment(Point(0, 0), Point(0, 0));
5171
5173 [[nodiscard]] bool intersects() const noexcept
5174 {
5175 return kind != Kind::NONE;
5176 }
5177 };
5178
5179private:
5180 [[nodiscard]] static bool point_less_on_axis(const Point &a, const Point &b, const bool vertical_axis)
5181 {
5182 if (vertical_axis)
5183 {
5184 if (a.get_y() != b.get_y())
5185 return a.get_y() < b.get_y();
5186 return a.get_x() < b.get_x();
5187 }
5188
5189 if (a.get_x() != b.get_x())
5190 return a.get_x() < b.get_x();
5191 return a.get_y() < b.get_y();
5192 }
5193
5194 [[nodiscard]] static Point point_max_on_axis(const Point &a, const Point &b, const bool vertical_axis)
5195 {
5196 return point_less_on_axis(a, b, vertical_axis) ? b : a;
5197 }
5198
5199 [[nodiscard]] static Point point_min_on_axis(const Point &a, const Point &b, const bool vertical_axis)
5200 {
5201 return point_less_on_axis(a, b, vertical_axis) ? a : b;
5202 }
5203
5204 [[nodiscard]] static Segment collinear_overlap(const Segment &s1, const Segment &s2)
5205 {
5206 const bool vertical_axis = s1.get_src_point().get_x() == s1.get_tgt_point().get_x();
5207
5208 Point a0 = s1.get_src_point();
5209 Point a1 = s1.get_tgt_point();
5210 Point b0 = s2.get_src_point();
5211 Point b1 = s2.get_tgt_point();
5212
5213 if (point_less_on_axis(a1, a0, vertical_axis))
5214 std::swap(a0, a1);
5215 if (point_less_on_axis(b1, b0, vertical_axis))
5216 std::swap(b0, b1);
5217
5218 const Point lo = point_max_on_axis(a0, b0, vertical_axis);
5219 const Point hi = point_min_on_axis(a1, b1, vertical_axis);
5220 return Segment(lo, hi);
5221 }
5222
5223public:
5230 [[nodiscard]] Result operator () (const Segment &s1, const Segment &s2) const
5231 {
5232 Result out;
5233
5234 if (not segments_intersect(s1, s2))
5235 return out;
5236
5237 if (not s1.is_parallel_with(s2))
5238 {
5240 out.point = s1.intersection_with(s2);
5241 return out;
5242 }
5243
5244 out.overlap = collinear_overlap(s1, s2);
5245 if (out.overlap.get_src_point() == out.overlap.get_tgt_point())
5246 {
5247 out.kind = Kind::POINT;
5248 out.point = out.overlap.get_src_point();
5249 return out;
5250 }
5251
5252 out.kind = Kind::OVERLAP;
5253 return out;
5254 }
5255};
5256
5259 const Segment &s2)
5260{
5261 return SegmentSegmentIntersection{}(s1, s2);
5262}
5263
5264// ============================================================================
5265// Line Sweep / Event-Driven Framework
5266// ============================================================================
5267
5311template <typename Event, typename CmpEvent>
5313{
5318 {
5319 Event event;
5320 size_t seq;
5321 };
5322
5327 {
5328 CmpEvent cmp;
5329
5330 bool operator () (const SeqEvent &a, const SeqEvent &b) const
5331 {
5332 if (cmp(a.event, b.event))
5333 return true;
5334 if (cmp(b.event, a.event))
5335 return false;
5336 return a.seq < b.seq;
5337 }
5338 };
5339
5341 size_t seq_ = 0;
5342
5343public:
5345 void enqueue(const Event &e)
5346 {
5347 queue_.insert(SeqEvent{e, seq_++});
5348 }
5349
5351 void enqueue(Event &&e)
5352 {
5353 queue_.insert(SeqEvent{std::move(e), seq_++});
5354 }
5355
5357 [[nodiscard]] bool has_events() const noexcept
5358 {
5359 return not queue_.is_empty();
5360 }
5361
5363 [[nodiscard]] size_t pending() const noexcept
5364 {
5365 return queue_.size();
5366 }
5367
5369 Event dequeue()
5370 {
5371 SeqEvent se = queue_.min();
5372 queue_.remove(se);
5373 return std::move(se.event);
5374 }
5375
5377 [[nodiscard]] const Event &peek() const
5378 {
5379 return queue_.min().event;
5380 }
5381
5383 void clear() noexcept
5384 {
5385 queue_.empty(); // DynSetTree::empty() is a mutator that removes all elements
5386 seq_ = 0;
5387 }
5388
5401 template <typename Handler>
5402 void run(Handler &&handler)
5403 {
5404 while (has_events())
5405 handler(*this, dequeue());
5406 }
5407
5414 template <typename Handler>
5415 void run(Handler &&handler, Array<Event> &out)
5416 {
5417 while (has_events())
5418 {
5419 Event e = dequeue();
5420 out.append(e);
5421 handler(*this, e);
5422 }
5423 }
5424};
5425
5426// ============================================================================
5427// Sweep Line Segment Intersection (Bentley-Ottmann)
5428// ============================================================================
5429
5455{
5456public:
5459 {
5460 size_t seg_i;
5461 size_t seg_j;
5463 };
5464
5465private:
5476 [[nodiscard]] static Geom_Number y_at_x(const Segment &s, const Geom_Number &x)
5477 {
5478 const Geom_Number &x1 = s.get_src_point().get_x();
5479 const Geom_Number &y1 = s.get_src_point().get_y();
5480 const Geom_Number &x2 = s.get_tgt_point().get_x();
5481 const Geom_Number &y2 = s.get_tgt_point().get_y();
5482
5483 if (x1 == x2)
5484 return (y1 + y2) / 2;
5485
5486 return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
5487 }
5488
5499 [[nodiscard]] static Segment canonicalize(const Segment &s)
5500 {
5501 const Point &a = s.get_src_point();
5502 const Point &b = s.get_tgt_point();
5503
5504 if (a.get_x() < b.get_x())
5505 return s;
5506 if (b.get_x() < a.get_x())
5507 return {b, a};
5508 // Vertical: lower endpoint first.
5509 if (a.get_y() < b.get_y())
5510 return s;
5511 return {b, a};
5512 }
5513
5517 enum class EventType
5518 {
5519 LEFT,
5521 RIGHT
5522 };
5523
5527 struct Event
5528 {
5531 size_t seg_a;
5532 size_t seg_b;
5533 };
5534
5543 [[nodiscard]] static bool event_less(const Event &a, const Event &b)
5544 {
5545 if (a.pt.get_x() != b.pt.get_x())
5546 return a.pt.get_x() < b.pt.get_x();
5547 if (a.pt.get_y() != b.pt.get_y())
5548 return a.pt.get_y() < b.pt.get_y();
5549 // LEFT < INTERSECTION < RIGHT for the same point.
5550 return static_cast<int>(a.type) < static_cast<int>(b.type);
5551 }
5552
5555 {
5556 bool operator () (const Event &a, const Event &b) const
5557 {
5558 return event_less(a, b);
5559 }
5560 };
5561
5562 [[nodiscard]] static bool slope_less(const Segment &a, const Segment &b)
5563 {
5564 const Geom_Number adx = a.get_tgt_point().get_x() - a.get_src_point().get_x();
5565 const Geom_Number ady = a.get_tgt_point().get_y() - a.get_src_point().get_y();
5566 const Geom_Number bdx = b.get_tgt_point().get_x() - b.get_src_point().get_x();
5567 const Geom_Number bdy = b.get_tgt_point().get_y() - b.get_src_point().get_y();
5568
5569 if (adx == 0 and bdx == 0)
5570 return ady < bdy;
5571 if (adx == 0)
5572 return false; // +inf slope
5573 if (bdx == 0)
5574 return true;
5575
5576 const Geom_Number lhs = ady * bdx;
5577 const Geom_Number rhs = bdy * adx;
5578 return lhs < rhs;
5579 }
5580
5581 [[nodiscard]] static bool status_less(const size_t lhs,
5582 const size_t rhs,
5583 const Geom_Number &sx,
5584 const Array<Segment> &segs)
5585 {
5586 if (lhs == rhs)
5587 return false;
5588
5589 const Geom_Number yl = y_at_x(segs(lhs), sx);
5590 const Geom_Number yr = y_at_x(segs(rhs), sx);
5591 if (yl != yr)
5592 return yl < yr;
5593
5594 if (slope_less(segs(lhs), segs(rhs)))
5595 return true;
5596 if (slope_less(segs(rhs), segs(lhs)))
5597 return false;
5598
5599 return lhs < rhs;
5600 }
5601
5611 {
5612 struct Node
5613 {
5614 size_t seg;
5616 unsigned priority;
5617 Node *left = nullptr;
5618 Node *right = nullptr;
5619 };
5620
5621 Node *root_ = nullptr;
5623 std::mt19937 rng_{0x5f3759dfu};
5625
5626 [[nodiscard]] static Node *merge(Node *a, Node *b)
5627 {
5628 if (a == nullptr)
5629 return b;
5630 if (b == nullptr)
5631 return a;
5632 if (a->priority < b->priority)
5633 {
5634 a->right = merge(a->right, b);
5635 return a;
5636 }
5637 b->left = merge(a, b->left);
5638 return b;
5639 }
5640
5641 [[nodiscard]] static Node *insert_by_label(Node *root, Node *node)
5642 {
5643 if (root == nullptr)
5644 return node;
5645
5646 if (node->priority < root->priority)
5647 {
5648 Node *left = nullptr;
5649 Node *right = nullptr;
5650 split_by_label(root, node->label, left, right);
5651 node->left = left;
5652 node->right = right;
5653 return node;
5654 }
5655
5656 if (node->label < root->label)
5657 root->left = insert_by_label(root->left, node);
5658 else
5659 root->right = insert_by_label(root->right, node);
5660 return root;
5661 }
5662
5663 static void split_by_label(Node *root, const Geom_Number &label, Node *&left, Node *&right)
5664 {
5665 if (root == nullptr)
5666 {
5667 left = nullptr;
5668 right = nullptr;
5669 return;
5670 }
5671
5672 if (root->label < label)
5673 {
5674 split_by_label(root->right, label, root->right, right);
5675 left = root;
5676 }
5677 else
5678 {
5679 split_by_label(root->left, label, left, root->left);
5680 right = root;
5681 }
5682 }
5683
5684 [[nodiscard]] static Node *erase_by_label(Node *root, const Geom_Number &label, Node *&removed)
5685 {
5686 if (root == nullptr)
5687 return nullptr;
5688
5689 if (label < root->label)
5690 {
5691 root->left = erase_by_label(root->left, label, removed);
5692 return root;
5693 }
5694
5695 if (root->label < label)
5696 {
5697 root->right = erase_by_label(root->right, label, removed);
5698 return root;
5699 }
5700
5701 removed = root;
5702 return merge(root->left, root->right);
5703 }
5704
5705 static void destroy(const Node *n)
5706 {
5707 if (n == nullptr)
5708 return;
5709 destroy(n->left);
5710 destroy(n->right);
5711 delete n;
5712 }
5713
5714 [[nodiscard]] size_t predecessor_for_insert(const size_t seg, const Geom_Number &sx) const
5715 {
5716 size_t pred = SIZE_MAX;
5717 const Node *cur = root_;
5718 while (cur != nullptr)
5719 if (status_less(cur->seg, seg, sx, segs_))
5720 {
5721 pred = cur->seg;
5722 cur = cur->right;
5723 }
5724 else
5725 cur = cur->left;
5726 return pred;
5727 }
5728
5729 [[nodiscard]] size_t successor_for_insert(const size_t seg, const Geom_Number &sx) const
5730 {
5731 size_t succ = SIZE_MAX;
5732 const Node *cur = root_;
5733 while (cur != nullptr)
5734 if (status_less(seg, cur->seg, sx, segs_))
5735 {
5736 succ = cur->seg;
5737 cur = cur->left;
5738 }
5739 else
5740 cur = cur->right;
5741 return succ;
5742 }
5743
5744 [[nodiscard]] Geom_Number fresh_label_between(const size_t pred, const size_t succ) const
5745 {
5746 if (pred != SIZE_MAX and succ != SIZE_MAX)
5747 return (nodes_(pred)->label + nodes_(succ)->label) / Geom_Number(2);
5748 if (pred != SIZE_MAX)
5749 return nodes_(pred)->label + Geom_Number(1);
5750 if (succ != SIZE_MAX)
5751 return nodes_(succ)->label - Geom_Number(1);
5752 return Geom_Number(0);
5753 }
5754
5755 public:
5756 explicit StatusTree(const Array<Segment> &segs) : segs_(segs)
5757 {
5758 nodes_.reserve(segs.size());
5759 for (size_t i = 0; i < segs.size(); ++i)
5760 nodes_.append(nullptr);
5761 }
5762
5764 {
5765 destroy(root_);
5766 }
5767
5768 [[nodiscard]] bool contains(const size_t seg) const
5769 {
5770 return nodes_(seg) != nullptr;
5771 }
5772
5773 void insert(const size_t seg, const Geom_Number &sx)
5774 {
5775 if (contains(seg))
5776 return;
5777
5778 const size_t pred = predecessor_for_insert(seg, sx);
5779 const size_t succ = successor_for_insert(seg, sx);
5780 const auto node = new Node{seg, fresh_label_between(pred, succ),
5781 static_cast<unsigned>(rng_()), nullptr, nullptr};
5782 root_ = insert_by_label(root_, node);
5783 nodes_(seg) = node;
5784 }
5785
5786 void erase(const size_t seg)
5787 {
5788 if (not contains(seg))
5789 return;
5790
5791 Node *removed = nullptr;
5792 root_ = erase_by_label(root_, nodes_(seg)->label, removed);
5793 nodes_(seg) = nullptr;
5794 delete removed;
5795 }
5796
5797 [[nodiscard]] size_t predecessor(const size_t seg) const
5798 {
5799 if (not contains(seg))
5800 return SIZE_MAX;
5801
5802 const Geom_Number &label = nodes_(seg)->label;
5803 const Node *pred = nullptr;
5804 Node *cur = root_;
5805 while (cur != nullptr)
5806 if (cur->label < label)
5807 {
5808 pred = cur;
5809 cur = cur->right;
5810 }
5811 else
5812 cur = cur->left;
5813
5814 return pred == nullptr ? SIZE_MAX : pred->seg;
5815 }
5816
5817 [[nodiscard]] size_t successor(const size_t seg) const
5818 {
5819 if (not contains(seg))
5820 return SIZE_MAX;
5821
5822 const Geom_Number &label = nodes_(seg)->label;
5823 const Node *succ = nullptr;
5824 Node *cur = root_;
5825 while (cur != nullptr)
5826 if (label < cur->label)
5827 {
5828 succ = cur;
5829 cur = cur->left;
5830 }
5831 else
5832 cur = cur->right;
5833
5834 return succ == nullptr ? SIZE_MAX : succ->seg;
5835 }
5836 };
5837
5854 static void check_and_enqueue(const Array<Segment> &segs,
5855 const size_t i,
5856 const size_t j,
5857 const Geom_Number &sx,
5859 DynSetTree<size_t, Treap_Rk> &seen_pairs,
5860 const size_t n)
5861 {
5862 const size_t lo = i < j ? i : j;
5863 const size_t hi = i < j ? j : i;
5864 const size_t key = lo * n + hi;
5865 if (seen_pairs.search(key) != nullptr)
5866 return;
5867
5868 const Segment &sa = segs(lo);
5869 const Segment &sb = segs(hi);
5870 const auto hit = segment_segment_intersection(sa, sb);
5871 if (not hit.intersects())
5872 return;
5873
5875 {
5876 seen_pairs.insert(key);
5877 const Point overlap_start = hit.overlap.get_src_point();
5878 const Point overlap_end = hit.overlap.get_tgt_point();
5879 if (not (overlap_start.get_x() < sx))
5880 eq.enqueue(Event{overlap_start, EventType::INTERSECTION, lo, hi});
5881 if (not (overlap_end.get_x() < sx))
5882 eq.enqueue(Event{overlap_end, EventType::INTERSECTION, lo, hi});
5883 return;
5884 }
5885
5886 const Point ip = hit.point;
5887 if (ip.get_x() < sx)
5888 return; // Intersection is to the left of the sweep.
5889
5890 seen_pairs.insert(key);
5891 eq.enqueue(Event{ip, EventType::INTERSECTION, lo, hi});
5892 }
5893
5894public:
5903 [[nodiscard]] Array<Intersection> operator () (const Array<Segment> &segments) const
5904 {
5905 const size_t n = segments.size();
5906 Array<Intersection> result;
5907
5908 if (n < 2)
5909 return result;
5910
5911 // Canonicalize: src is the left endpoint.
5912 Array<Segment> segs;
5913 segs.reserve(n);
5914 for (size_t i = 0; i < n; ++i)
5915 {
5916 ah_domain_error_if(segments(i).get_src_point() == segments(i).get_tgt_point())
5917 << "Segment " << i << " is degenerate (zero length)";
5918 segs.append(canonicalize(segments(i)));
5919 }
5920
5921 // Build the initial event queue (left + right endpoints).
5923 for (size_t i = 0; i < n; ++i)
5924 {
5925 eq.enqueue(Event{segs(i).get_src_point(), EventType::LEFT, i, 0});
5926 eq.enqueue(Event{segs(i).get_tgt_point(), EventType::RIGHT, i, 0});
5927 }
5928
5929 // Seen intersection pairs (key = lo * n + hi).
5931 DynSetTree<size_t, Treap_Rk> reported_pairs;
5932
5933 auto pair_key = [n](const size_t i, const size_t j)
5934 {
5935 const size_t lo = i < j ? i : j;
5936 const size_t hi = i < j ? j : i;
5937 return lo * n + hi;
5938 };
5939
5940 auto append_intersection =
5941 [&result, &reported_pairs, &pair_key](const size_t i, const size_t j, const Point &p)
5942 {
5943 const size_t key = pair_key(i, j);
5944 if (reported_pairs.search(key) != nullptr)
5945 return;
5946 reported_pairs.insert(key);
5947
5948 const size_t lo = i < j ? i : j;
5949 const size_t hi = i < j ? j : i;
5950 result.append(Intersection{lo, hi, p});
5951 };
5952
5953 // Sweep-line status: balanced tree with O(log n) updates.
5954 StatusTree status(segs);
5955
5956 while (eq.has_events())
5957 {
5958 const Event ev = eq.dequeue();
5959 const Geom_Number sx = ev.pt.get_x();
5960
5961 if (ev.type == EventType::LEFT)
5962 {
5963 const size_t idx = ev.seg_a;
5964 status.insert(idx, sx);
5965
5966 if (const size_t pred = status.predecessor(idx); pred != SIZE_MAX)
5967 check_and_enqueue(segs, pred, idx, sx, eq, seen_pairs, n);
5968 if (const size_t succ = status.successor(idx); succ != SIZE_MAX)
5969 check_and_enqueue(segs, idx, succ, sx, eq, seen_pairs, n);
5970 }
5971 else if (ev.type == EventType::RIGHT)
5972 {
5973 if (const size_t idx = ev.seg_a; status.contains(idx))
5974 {
5975 const size_t pred = status.predecessor(idx);
5976 const size_t succ = status.successor(idx);
5977 if (pred != SIZE_MAX and succ != SIZE_MAX)
5978 check_and_enqueue(segs, pred, succ, sx, eq, seen_pairs, n);
5979 status.erase(idx);
5980 }
5981 }
5982 else // INTERSECTION
5983 {
5984 const size_t a = ev.seg_a;
5985 const size_t b = ev.seg_b;
5986 append_intersection(a, b, ev.pt);
5987
5988 // Walk outward from a (or b) through the status tree to find
5989 // all active segments passing through ev.pt. Segments sharing
5990 // a point are adjacent in sweep-line order, so this is O(k)
5991 // instead of the former O(n) scan.
5992 Array<size_t> block;
5993
5994 // Pick a seed segment that is still in the status tree
5995 size_t seed = SIZE_MAX;
5996 if (status.contains(a) and segs(a).contains(ev.pt))
5997 seed = a;
5998 else if (status.contains(b) and segs(b).contains(ev.pt))
5999 seed = b;
6000
6001 if (seed != SIZE_MAX)
6002 {
6003 block.append(seed);
6004
6005 // Walk predecessors
6006 for (size_t p = status.predecessor(seed); p != SIZE_MAX and segs(p).contains(ev.pt);
6007 p = status.predecessor(p))
6008 block.append(p);
6009
6010 // Walk successors
6011 for (size_t s = status.successor(seed); s != SIZE_MAX and segs(s).contains(ev.pt);
6012 s = status.successor(s))
6013 block.append(s);
6014 }
6015
6016 if (block.size() > 2)
6017 {
6018 for (size_t i = 0; i + 1 < block.size(); ++i)
6019 for (size_t j = i + 1; j < block.size(); ++j)
6020 append_intersection(block(i), block(j), ev.pt);
6021 }
6022
6023 if (block.size() == 0)
6024 {
6025 if (status.contains(a))
6026 block.append(a);
6027 if (status.contains(b) and (block.size() == 0 or block(0) != b))
6028 block.append(b);
6029 }
6030
6031 for (size_t i = 0; i < block.size(); ++i)
6032 status.erase(block(i));
6033 for (size_t i = 0; i < block.size(); ++i)
6034 status.insert(block(i), sx);
6035
6036 for (size_t i = 0; i < block.size(); ++i)
6037 {
6038 const size_t s = block(i);
6039 if (const size_t pred = status.predecessor(s); pred != SIZE_MAX)
6040 check_and_enqueue(segs, pred, s, sx, eq, seen_pairs, n);
6041 if (const size_t succ = status.successor(s); succ != SIZE_MAX)
6042 check_and_enqueue(segs, s, succ, sx, eq, seen_pairs, n);
6043 }
6044 }
6045 }
6046
6047 // Sort results by (x, y).
6048 quicksort_op(result, [](const Intersection &a, const Intersection &b)
6049 {
6050 if (a.point.get_x() != b.point.get_x())
6051 return a.point.get_x() < b.point.get_x();
6052 if (a.point.get_y() != b.point.get_y())
6053 return a.point.get_y() < b.point.get_y();
6054 if (a.seg_i != b.seg_i)
6055 return a.seg_i < b.seg_i;
6056 return a.seg_j < b.seg_j;
6057 });
6058
6059 return result;
6060 }
6061};
6062
6063// ============================================================================
6064// Monotone Polygon Triangulation
6065// ============================================================================
6066
6092{
6093private:
6094 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &p)
6095 {
6097 }
6098
6099 [[nodiscard]] static Geom_Number signed_double_area(const Array<Point> &v)
6100 {
6102 }
6103
6104 static void ensure_ccw(Array<Point> &v)
6105 {
6107 }
6108
6112 enum class VertexType
6113 {
6114 START,
6115 END,
6116 SPLIT,
6117 MERGE,
6118 REGULAR
6119 };
6120
6124 [[nodiscard]] static bool is_above(const Point &a, const Point &b)
6125 {
6126 return a.get_y() > b.get_y() or (a.get_y() == b.get_y() and a.get_x() < b.get_x());
6127 }
6128
6132 [[nodiscard]] static bool is_below(const Point &a, const Point &b)
6133 {
6134 return is_above(b, a);
6135 }
6136
6140 [[nodiscard]] static bool edge_goes_down(const Array<Point> &verts, const size_t edge)
6141 {
6142 return is_below(verts((edge + 1) % verts.size()), verts(edge));
6143 }
6144
6145 [[nodiscard]] static Geom_Number edge_x_at_y(const Array<Point> &verts,
6146 const size_t edge,
6147 const Geom_Number &y)
6148 {
6149 const Point &a = verts(edge);
6150 const Point &b = verts((edge + 1) % verts.size());
6151 if (a.get_y() == b.get_y())
6152 return a.get_x() < b.get_x() ? a.get_x() : b.get_x();
6153
6154 return a.get_x() + (y - a.get_y()) * (b.get_x() - a.get_x()) / (b.get_y() - a.get_y());
6155 }
6156
6157 [[nodiscard]] static bool edge_status_less(const size_t lhs,
6158 const size_t rhs,
6159 const Geom_Number &sweep_y,
6160 const Array<Point> &verts)
6161 {
6162 if (lhs == rhs)
6163 return false;
6164
6165 const Geom_Number xl = edge_x_at_y(verts, lhs, sweep_y);
6166 const Geom_Number xr = edge_x_at_y(verts, rhs, sweep_y);
6167 if (xl != xr)
6168 return xl < xr;
6169 return lhs < rhs;
6170 }
6171
6173 {
6174 struct Node
6175 {
6176 size_t edge;
6178 unsigned priority;
6179 Node *left = nullptr;
6180 Node *right = nullptr;
6181 };
6182
6183 Node *root_ = nullptr;
6185 std::mt19937 rng_{0x31415926u};
6187
6188 static void split_by_label(Node *root, const Geom_Number &label, Node *&left, Node *&right)
6189 {
6190 if (root == nullptr)
6191 {
6192 left = nullptr;
6193 right = nullptr;
6194 return;
6195 }
6196
6197 if (root->label < label)
6198 {
6199 split_by_label(root->right, label, root->right, right);
6200 left = root;
6201 }
6202 else
6203 {
6204 split_by_label(root->left, label, left, root->left);
6205 right = root;
6206 }
6207 }
6208
6209 [[nodiscard]] static Node *merge(Node *a, Node *b)
6210 {
6211 if (a == nullptr)
6212 return b;
6213 if (b == nullptr)
6214 return a;
6215 if (a->priority < b->priority)
6216 {
6217 a->right = merge(a->right, b);
6218 return a;
6219 }
6220 b->left = merge(a, b->left);
6221 return b;
6222 }
6223
6224 [[nodiscard]] static Node *insert_by_label(Node *root, Node *node)
6225 {
6226 if (root == nullptr)
6227 return node;
6228
6229 if (node->priority < root->priority)
6230 {
6231 Node *left = nullptr;
6232 Node *right = nullptr;
6233 split_by_label(root, node->label, left, right);
6234 node->left = left;
6235 node->right = right;
6236 return node;
6237 }
6238
6239 if (node->label < root->label)
6240 root->left = insert_by_label(root->left, node);
6241 else
6242 root->right = insert_by_label(root->right, node);
6243 return root;
6244 }
6245
6246 [[nodiscard]] static Node *erase_by_label(Node *root, const Geom_Number &label, Node *&removed)
6247 {
6248 if (root == nullptr)
6249 return nullptr;
6250
6251 if (label < root->label)
6252 {
6253 root->left = erase_by_label(root->left, label, removed);
6254 return root;
6255 }
6256
6257 if (root->label < label)
6258 {
6259 root->right = erase_by_label(root->right, label, removed);
6260 return root;
6261 }
6262
6263 removed = root;
6264 return merge(root->left, root->right);
6265 }
6266
6267 static void destroy(const Node *n)
6268 {
6269 if (n == nullptr)
6270 return;
6271 destroy(n->left);
6272 destroy(n->right);
6273 delete n;
6274 }
6275
6276 [[nodiscard]] size_t predecessor_for_insert(const size_t edge, const Geom_Number &sweep_y) const
6277 {
6278 size_t pred = SIZE_MAX;
6279 const Node *cur = root_;
6280 while (cur != nullptr)
6281 if (edge_status_less(cur->edge, edge, sweep_y, verts_))
6282 {
6283 pred = cur->edge;
6284 cur = cur->right;
6285 }
6286 else
6287 cur = cur->left;
6288 return pred;
6289 }
6290
6291 [[nodiscard]] size_t successor_for_insert(const size_t edge, const Geom_Number &sweep_y) const
6292 {
6293 size_t succ = SIZE_MAX;
6294 const Node *cur = root_;
6295 while (cur != nullptr)
6296 if (edge_status_less(edge, cur->edge, sweep_y, verts_))
6297 {
6298 succ = cur->edge;
6299 cur = cur->left;
6300 }
6301 else
6302 cur = cur->right;
6303 return succ;
6304 }
6305
6306 [[nodiscard]] Geom_Number fresh_label_between(const size_t pred, const size_t succ) const
6307 {
6308 if (pred != SIZE_MAX and succ != SIZE_MAX)
6309 return (nodes_(pred)->label + nodes_(succ)->label) / Geom_Number(2);
6310 if (pred != SIZE_MAX)
6311 return nodes_(pred)->label + Geom_Number(1);
6312 if (succ != SIZE_MAX)
6313 return nodes_(succ)->label - Geom_Number(1);
6314 return {0};
6315 }
6316
6317 public:
6318 explicit EdgeStatusTree(const Array<Point> &verts) : verts_(verts)
6319 {
6320 nodes_.reserve(verts.size());
6321 for (size_t i = 0; i < verts.size(); ++i)
6322 nodes_.append(nullptr);
6323 }
6324
6326 {
6327 destroy(root_);
6328 }
6329
6330 [[nodiscard]] bool contains(const size_t edge) const
6331 {
6332 return nodes_(edge) != nullptr;
6333 }
6334
6335 void insert(const size_t edge, const Geom_Number &sweep_y)
6336 {
6337 if (contains(edge))
6338 return;
6339
6340 const size_t pred = predecessor_for_insert(edge, sweep_y);
6341 const size_t succ = successor_for_insert(edge, sweep_y);
6342 const auto node = new Node{edge, fresh_label_between(pred, succ),
6343 static_cast<unsigned>(rng_()), nullptr, nullptr};
6344 root_ = insert_by_label(root_, node);
6345 nodes_(edge) = node;
6346 }
6347
6348 void erase(const size_t edge)
6349 {
6350 if (not contains(edge))
6351 return;
6352
6353 Node *removed = nullptr;
6354 root_ = erase_by_label(root_, nodes_(edge)->label, removed);
6355 nodes_(edge) = nullptr;
6356 delete removed;
6357 }
6358
6359 [[nodiscard]] size_t left_edge_of_point(const Point &p, const Geom_Number &sweep_y) const
6360 {
6361 size_t best = SIZE_MAX;
6362 const Node *cur = root_;
6363 while (cur != nullptr)
6364 {
6365 const Geom_Number x = edge_x_at_y(verts_, cur->edge, sweep_y);
6366 if (x < p.get_x())
6367 {
6368 best = cur->edge;
6369 cur = cur->right;
6370 }
6371 else
6372 cur = cur->left;
6373 }
6374 return best;
6375 }
6376 };
6377
6379 [[nodiscard]] static DynList<Triangle> triangulate_monotone(const Array<Point> &verts)
6380 {
6381 DynList<Triangle> result;
6382 const size_t n = verts.size();
6383 if (n < 3)
6384 return result;
6385 if (n == 3)
6386 {
6387 result.append(Triangle(verts(0), verts(1), verts(2)));
6388 return result;
6389 }
6390
6391 // Sort vertex indices by y descending, x ascending for ties.
6392 Array<size_t> sorted;
6393 sorted.reserve(n);
6394 for (size_t i = 0; i < n; ++i)
6395 sorted.append(i);
6396
6397 quicksort_op(sorted, [&verts](const size_t a, const size_t b)
6398 {
6399 if (verts(a).get_y() != verts(b).get_y())
6400 return verts(a).get_y() > verts(b).get_y();
6401 return verts(a).get_x() < verts(b).get_x();
6402 });
6403
6404 // Identify left and right chains.
6405 // Top vertex = sorted(0), bottom vertex = sorted(n-1).
6406 // Left chain: goes from top to bottom counter-clockwise.
6407 const size_t top = sorted(0);
6408 const size_t bot = sorted(n - 1);
6409
6410 Array<bool> on_left;
6411 on_left.reserve(n);
6412 for (size_t i = 0; i < n; ++i)
6413 on_left.append(false);
6414
6415 // Walk from top to bottom going forward in the polygon.
6416 for (size_t i = top; i != bot; i = (i + 1) % n)
6417 on_left(i) = true;
6418 on_left(top) = true; // top is on both; mark left.
6419
6420 // Stack-based triangulation.
6421 FixedStack<size_t> stack(n);
6422 stack.push(sorted(0));
6423 stack.push(sorted(1));
6424
6425 for (size_t i = 2; i < n - 1; ++i)
6426 {
6427 const size_t curr = sorted(i);
6428 const size_t stk_top = stack.top();
6429 if (on_left(curr) != on_left(stk_top))
6430 {
6431 // Different chain: fan triangles from curr to all stack vertices.
6432 while (stack.size() > 1)
6433 {
6434 const size_t a = stack.top();
6435 const size_t b = stack.top(1);
6436 result.append(Triangle(verts(curr), verts(a), verts(b)));
6437 stack.pop();
6438 }
6439 stack.pop();
6440 stack.push(sorted(i - 1));
6441 stack.push(curr);
6442 }
6443 else
6444 {
6445 // Same chain: pop vertices while diagonal is inside.
6446 size_t last_popped = stack.top();
6447 stack.pop();
6448
6449 while (not stack.is_empty())
6450 {
6451 const size_t peek = stack.top();
6452 const Geom_Number area =
6453 area_of_parallelogram(verts(curr), verts(last_popped), verts(peek));
6454
6455 // On the left chain we need CW turn (area < 0);
6456 // on the right chain we need CCW turn (area > 0).
6457 if ((on_left(curr) and area >= 0) or (not on_left(curr) and area <= 0))
6458 break;
6459
6460 result.append(Triangle(verts(curr), verts(last_popped), verts(peek)));
6461 last_popped = peek;
6462 stack.pop();
6463 }
6464
6465 stack.push(last_popped);
6466 stack.push(curr);
6467 }
6468 }
6469
6470 // Process last vertex (bottom): fan to the remaining stack.
6471 const size_t last = sorted(n - 1);
6472 while (stack.size() > 1)
6473 {
6474 const size_t a = stack.top();
6475 const size_t b = stack.top(1);
6476 result.append(Triangle(verts(last), verts(a), verts(b)));
6477 stack.pop();
6478 }
6479
6480 return result;
6481 }
6482
6483 [[nodiscard]] static VertexType classify_vertex(const Array<Point> &v, const size_t i)
6484 {
6485 const size_t n = v.size();
6486 const Point &prev = v((i + n - 1) % n);
6487 const Point &curr = v(i);
6488 const Point &next = v((i + 1) % n);
6489
6490 const bool prev_below = is_below(prev, curr);
6491 const bool next_below = is_below(next, curr);
6492 const bool prev_above = is_above(prev, curr);
6493 const bool next_above = is_above(next, curr);
6494 const bool reflex = orientation(prev, curr, next) == Orientation::CW;
6495
6496 if (prev_below and next_below)
6497 return reflex ? VertexType::SPLIT : VertexType::START;
6498 if (prev_above and next_above)
6499 return reflex ? VertexType::MERGE : VertexType::END;
6500 return VertexType::REGULAR;
6501 }
6502
6503 [[nodiscard]] static bool regular_interior_right(const Array<Point> &v, const size_t i)
6504 {
6505 return is_below(v((i + 1) % v.size()), v(i));
6506 }
6507
6509 const Array<Point> &verts,
6510 const DynSetTree<std::pair<size_t, size_t>> &diagonals)
6511 {
6512 const size_t n = verts.size();
6514 adj.reserve(n);
6515 for (size_t i = 0; i < n; ++i)
6516 adj.append(Array<size_t>());
6517
6518 auto add_undirected_edge = [&adj](const size_t a, const size_t b)
6519 {
6520 adj(a).append(b);
6521 adj(b).append(a);
6522 };
6523
6524 for (size_t i = 0; i < n; ++i)
6525 add_undirected_edge(i, (i + 1) % n);
6526
6527 for (const auto &d : diagonals)
6528 add_undirected_edge(d.first, d.second);
6529
6530 for (size_t v = 0; v < n; ++v)
6531 {
6532 auto &nbrs = adj(v);
6533 in_place_sort(nbrs);
6534 in_place_unique(nbrs);
6535 in_place_sort(nbrs, [&verts, v](const size_t a, const size_t b)
6536 {
6537 const Geom_Number dax = verts(a).get_x() - verts(v).get_x();
6538 const Geom_Number day = verts(a).get_y() - verts(v).get_y();
6539 const Geom_Number dbx = verts(b).get_x() - verts(v).get_x();
6540 const Geom_Number dby = verts(b).get_y() - verts(v).get_y();
6541
6542 const bool upper_a = day > 0 or (day == 0 and dax >= 0);
6543 const bool upper_b = dby > 0 or (dby == 0 and dbx >= 0);
6544 if (upper_a != upper_b)
6545 return upper_a > upper_b;
6546
6547 if (const Geom_Number cross = dax * dby - day * dbx; cross != 0)
6548 return cross > 0;
6549
6550 const Geom_Number da2 = dax * dax + day * day;
6551 const Geom_Number db2 = dbx * dbx + dby * dby;
6552 return da2 < db2;
6553 });
6554 }
6555
6556 using HalfEdge = std::pair<size_t, size_t>;
6557 std::map<HalfEdge, HalfEdge> next_half;
6558 for (size_t v = 0; v < n; ++v)
6559 {
6560 const auto &nbrs = adj(v);
6561 if (nbrs.is_empty())
6562 continue;
6563 for (size_t k = 0; k < nbrs.size(); ++k)
6564 {
6565 const size_t u = nbrs(k);
6566 const size_t pred = nbrs((k + nbrs.size() - 1) % nbrs.size());
6567 next_half[HalfEdge{u, v}] = HalfEdge{v, pred};
6568 }
6569 }
6570
6571 auto face_area2 = [&verts](const Array<size_t> &face)
6572 {
6573 Geom_Number area2 = 0;
6574 for (size_t i = 0; i < face.size(); ++i)
6575 {
6576 const Point &a = verts(face(i));
6577 const Point &b = verts(face((i + 1) % face.size()));
6578 area2 += a.get_x() * b.get_y() - a.get_y() * b.get_x();
6579 }
6580 return area2;
6581 };
6582
6583 DynSetTree<HalfEdge> visited;
6584 Array<Array<size_t>> faces;
6585 for (const auto &[kv, _] : next_half)
6586 {
6587 const HalfEdge start = kv;
6588 if (visited.search(start) != nullptr)
6589 continue;
6590
6591 HalfEdge cur = start;
6592 Array<size_t> face;
6593 while (visited.insert(cur) != nullptr)
6594 {
6595 face.append(cur.first);
6596 auto it_next = next_half.find(cur);
6597 if (it_next == next_half.end())
6598 {
6599 face.empty();
6600 break;
6601 }
6602 cur = it_next->second;
6603 if (cur == start)
6604 break;
6605 }
6606
6607 if (face.is_empty() or cur != start or face.size() < 3)
6608 continue;
6609 if (face_area2(face) <= 0)
6610 continue; // Ignore outer face / degenerate loops.
6611
6612 Array<size_t> poly_idx;
6613 poly_idx.reserve(face.size());
6614 for (const size_t idx : face)
6615 poly_idx.append(idx);
6616 faces.append(poly_idx);
6617 }
6618
6619 return faces;
6620 }
6621
6623 {
6624 const size_t n = verts.size();
6625 Array<Array<size_t>> faces;
6626
6627 if (n < 3)
6628 return faces;
6629
6630 if (is_y_monotone(verts))
6631 {
6632 Array<size_t> one;
6633 one.reserve(n);
6634 for (size_t i = 0; i < n; ++i)
6635 one.append(i);
6636 faces.append(one);
6637 return faces;
6638 }
6639
6640 Array<VertexType> vtype;
6641 vtype.reserve(n);
6642 for (size_t i = 0; i < n; ++i)
6643 vtype.append(classify_vertex(verts, i));
6644
6645 Array<size_t> order;
6646 order.reserve(n);
6647 for (size_t i = 0; i < n; ++i)
6648 order.append(i);
6649 quicksort_op(order, [&verts](const size_t a, const size_t b)
6650 {
6651 if (verts(a).get_y() != verts(b).get_y())
6652 return verts(a).get_y() > verts(b).get_y();
6653 return verts(a).get_x() < verts(b).get_x();
6654 });
6655
6656 Array<size_t> helper;
6657 helper.reserve(n);
6658 for (size_t i = 0; i < n; ++i)
6659 helper.append(SIZE_MAX);
6660
6661 EdgeStatusTree status(verts);
6663
6664 auto add_diagonal = [&](const size_t a, const size_t b)
6665 {
6666 if (a == b or b == SIZE_MAX)
6667 return;
6668 if ((a + 1) % n == b or (b + 1) % n == a)
6669 return;
6670
6671 const size_t lo = a < b ? a : b;
6672 const size_t hi = a < b ? b : a;
6673 diagonals.insert({lo, hi});
6674 };
6675
6676 auto helper_is_merge = [&helper, &vtype](const size_t edge)
6677 {
6678 return helper(edge) != SIZE_MAX and vtype(helper(edge)) == VertexType::MERGE;
6679 };
6680
6681 for (size_t oi = 0; oi < n; ++oi)
6682 {
6683 const size_t vi = order(oi);
6684 const size_t prev = (vi + n - 1) % n;
6685 const size_t e_prev = prev; // edge prev -> vi
6686 const size_t e_curr = vi; // edge vi -> next
6687 const Geom_Number sweep_y = verts(vi).get_y();
6688
6689 switch (vtype(vi))
6690 {
6691 case VertexType::START:
6692 if (edge_goes_down(verts, e_curr))
6693 {
6694 status.insert(e_curr, sweep_y);
6695 helper(e_curr) = vi;
6696 }
6697 break;
6698
6699 case VertexType::END:
6700 if (edge_goes_down(verts, e_prev))
6701 {
6702 if (helper_is_merge(e_prev))
6703 add_diagonal(vi, helper(e_prev));
6704 status.erase(e_prev);
6705 }
6706 break;
6707
6708 case VertexType::SPLIT:
6709 {
6710 if (const size_t left = status.left_edge_of_point(verts(vi), sweep_y); left != SIZE_MAX)
6711 {
6712 add_diagonal(vi, helper(left));
6713 helper(left) = vi;
6714 }
6715
6716 if (edge_goes_down(verts, e_curr))
6717 {
6718 status.insert(e_curr, sweep_y);
6719 helper(e_curr) = vi;
6720 }
6721 }
6722 break;
6723
6724 case VertexType::MERGE:
6725 if (edge_goes_down(verts, e_prev))
6726 {
6727 if (helper_is_merge(e_prev))
6728 add_diagonal(vi, helper(e_prev));
6729 status.erase(e_prev);
6730 }
6731 if (const size_t left = status.left_edge_of_point(verts(vi), sweep_y); left != SIZE_MAX)
6732 {
6733 if (helper_is_merge(left))
6734 add_diagonal(vi, helper(left));
6735 helper(left) = vi;
6736 }
6737 break;
6738
6740 if (regular_interior_right(verts, vi))
6741 {
6742 if (edge_goes_down(verts, e_prev))
6743 {
6744 if (helper_is_merge(e_prev))
6745 add_diagonal(vi, helper(e_prev));
6746 status.erase(e_prev);
6747 }
6748 if (edge_goes_down(verts, e_curr))
6749 {
6750 status.insert(e_curr, sweep_y);
6751 helper(e_curr) = vi;
6752 }
6753 }
6754 else if (const size_t left = status.left_edge_of_point(verts(vi), sweep_y);
6755 left != SIZE_MAX)
6756 {
6757 if (helper_is_merge(left))
6758 add_diagonal(vi, helper(left));
6759 helper(left) = vi;
6760 }
6761 break;
6762 }
6763 }
6764
6765 faces = build_faces_from_diagonals(verts, diagonals);
6766 if (faces.size() == 0)
6767 {
6768 Array<size_t> one;
6769 one.reserve(n);
6770 for (size_t i = 0; i < n; ++i)
6771 one.append(i);
6772 faces.append(one);
6773 }
6774 return faces;
6775 }
6776
6777public:
6796 {
6797 ah_domain_error_if(not p.is_closed()) << "Polygon must be closed";
6798 ah_domain_error_if(p.size() < 3) << "Polygon must have at least 3 vertices";
6799
6800 Array<Point> verts = extract_vertices(p);
6801 ah_domain_error_if(signed_double_area(verts) == 0) << "Polygon is degenerate (zero area)";
6802
6803 ensure_ccw(verts);
6804
6805 // Check if the polygon is y-monotone.
6806 if (is_y_monotone(verts))
6807 return triangulate_monotone(verts);
6808
6810 DynList<Triangle> result;
6811 bool produced_any = false;
6812
6813 for (size_t fi = 0; fi < faces.size(); ++fi)
6814 {
6815 if (faces(fi).size() < 3)
6816 continue;
6817
6818 Array<Point> mono;
6819 mono.reserve(faces(fi).size());
6820 for (size_t i = 0; i < faces(fi).size(); ++i)
6821 mono.append(verts(faces(fi)(i)));
6822
6823 if (signed_double_area(mono) == 0)
6824 continue;
6825 ensure_ccw(mono);
6826
6827 DynList<Triangle> tris;
6828 if (is_y_monotone(mono))
6829 tris = triangulate_monotone(mono);
6830 else
6831 {
6832 // Defensive fallback for degenerate decomposition edge cases.
6833 Polygon piece;
6834 for (size_t i = 0; i < mono.size(); ++i)
6835 piece.add_vertex(mono(i));
6836 if (piece.size() >= 3)
6837 {
6838 piece.close();
6839 constexpr CuttingEarsTriangulation ears;
6840 tris = ears(piece);
6841 }
6842 }
6843
6844 for (auto it = tris.get_it(); it.has_curr(); it.next_ne())
6845 {
6846 result.append(it.get_curr());
6847 produced_any = true;
6848 }
6849 }
6850
6851 if (produced_any)
6852 return result;
6853
6854 // Conservative fallback if decomposition could not produce valid faces.
6855 constexpr CuttingEarsTriangulation ears;
6856 return ears(p);
6857 }
6858
6859private:
6861 [[nodiscard]] static bool is_y_monotone(const Array<Point> &v)
6862 {
6863 const size_t n = v.size();
6864 if (n <= 3)
6865 return true;
6866
6867 // Find topmost and bottommost vertices.
6868 size_t top_idx = 0;
6869 size_t bot_idx = 0;
6870 for (size_t i = 1; i < n; ++i)
6871 {
6872 if (v(i).get_y() > v(top_idx).get_y() or
6873 (v(i).get_y() == v(top_idx).get_y() and v(i).get_x() < v(top_idx).get_x()))
6874 top_idx = i;
6875
6876 if (v(i).get_y() < v(bot_idx).get_y() or
6877 (v(i).get_y() == v(bot_idx).get_y() and v(i).get_x() > v(bot_idx).get_x()))
6878 bot_idx = i;
6879 }
6880
6881 // Walk from top to bottom along the forward chain — y must be
6882 // non-increasing.
6883 for (size_t i = top_idx;;)
6884 {
6885 const size_t next = (i + 1) % n;
6886 if (next == bot_idx)
6887 break;
6888 if (v(next).get_y() > v(i).get_y())
6889 return false;
6890 i = next;
6891 }
6892
6893 // Walk from top to bottom along the backward chain — y must be
6894 // non-increasing.
6895 for (size_t i = top_idx;;)
6896 {
6897 const size_t prev = (i + n - 1) % n;
6898 if (prev == bot_idx)
6899 break;
6900 if (v(prev).get_y() > v(i).get_y())
6901 return false;
6902 i = prev;
6903 }
6904
6905 return true;
6906 }
6907};
6908
6909// ============================================================================
6910// Minkowski Sum for Convex Polygons — O(n + m)
6911// ============================================================================
6912
6946{
6947private:
6948 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &poly)
6949 {
6951 }
6952
6953 [[nodiscard]] static Geom_Number signed_double_area(const Array<Point> &v)
6954 {
6956 }
6957
6958 [[nodiscard]] static bool is_convex(const Array<Point> &verts)
6959 {
6960 if (verts.size() < 3)
6961 return false;
6962 return GeomPolygonUtils::is_convex(verts);
6963 }
6964
6967 {
6969
6970 // Find bottom-most vertex (min y, then min x).
6971 size_t bot = 0;
6972 for (size_t i = 1; i < v.size(); ++i)
6973 if (v(i).get_y() < v(bot).get_y() or
6974 (v(i).get_y() == v(bot).get_y() and v(i).get_x() < v(bot).get_x()))
6975 bot = i;
6976
6977 Array<Point> result;
6978 result.reserve(v.size());
6979 for (size_t i = 0; i < v.size(); ++i)
6980 result.append(v((bot + i) % v.size()));
6981
6982 return result;
6983 }
6984
6985 [[nodiscard]] static Point edge_vec(const Array<Point> &v, const size_t i)
6986 {
6987 const size_t j = (i + 1) % v.size();
6988 return {v(j).get_x() - v(i).get_x(), v(j).get_y() - v(i).get_y()};
6989 }
6990
6991 [[nodiscard]] static Geom_Number cross(const Point &a, const Point &b)
6992 {
6993 return a.get_x() * b.get_y() - a.get_y() * b.get_x();
6994 }
6995
6996public:
7007 [[nodiscard]] Polygon operator () (const Polygon &P, const Polygon &Q) const
7008 {
7009 ah_domain_error_if(not P.is_closed()) << "First polygon must be closed";
7010 ah_domain_error_if(not Q.is_closed()) << "Second polygon must be closed";
7011 ah_domain_error_if(P.size() < 3) << "First polygon must have at least 3 vertices";
7012 ah_domain_error_if(Q.size() < 3) << "Second polygon must have at least 3 vertices";
7013
7016
7017 ah_domain_error_if(not is_convex(pv)) << "First polygon must be convex";
7018 ah_domain_error_if(not is_convex(qv)) << "Second polygon must be convex";
7019
7020 pv = normalize(pv);
7021 qv = normalize(qv);
7022
7023 const size_t np = pv.size();
7024 const size_t nq = qv.size();
7025
7026 Array<Point> result;
7027 result.reserve(np + nq);
7028
7029 size_t ip = 0;
7030 size_t iq = 0;
7031
7032 while (ip < np or iq < nq)
7033 {
7034 result.append(Point(pv(ip % np).get_x() + qv(iq % nq).get_x(),
7035 pv(ip % np).get_y() + qv(iq % nq).get_y()));
7036
7037 if (ip >= np)
7038 {
7039 ++iq;
7040 continue;
7041 }
7042 if (iq >= nq)
7043 {
7044 ++ip;
7045 continue;
7046 }
7047
7048 const Point ep = edge_vec(pv, ip % np);
7049 const Point eq = edge_vec(qv, iq % nq);
7050
7051 if (const Geom_Number cr = cross(ep, eq); cr > 0)
7052 ++ip;
7053 else if (cr < 0)
7054 ++iq;
7055 else
7056 {
7057 ++ip;
7058 ++iq;
7059 } // Parallel edges: advance both.
7060 }
7061
7062 // Remove collinear and duplicate vertices.
7063 Array<Point> clean;
7064 clean.reserve(result.size());
7065 for (size_t i = 0; i < result.size(); ++i)
7066 {
7067 if (clean.is_empty() or clean.get_last() != result(i))
7068 clean.append(result(i));
7069 }
7070 if (clean.size() > 1 and clean(0) == clean.get_last())
7071 static_cast<void>(clean.remove_last());
7072
7073 Polygon ret;
7074 for (size_t i = 0; i < clean.size(); ++i)
7075 ret.add_vertex(clean(i));
7076
7077 if (ret.size() >= 3)
7078 ret.close();
7079
7080 return ret;
7081 }
7082};
7083
7084// ============================================================================
7085// Convex Polygon Distance (GJK) — 2D
7086// ============================================================================
7087
7105{
7106public:
7119
7120private:
7125 {
7129 double vx = 0.0;
7130 double vy = 0.0;
7131 };
7132
7134 {
7135 std::vector<SupportPoint> reduced_simplex;
7136 double cx = 0.0;
7137 double cy = 0.0;
7140 bool contains_origin = false;
7141 };
7142
7143 static constexpr size_t kMaxIters = 64;
7144 static constexpr double kEps = 1e-12;
7145
7146 [[nodiscard]] static double to_double(const Geom_Number &v)
7147 {
7148 return geom_number_to_double(v);
7149 }
7150
7151 [[nodiscard]] static double dot2(const double ax,
7152 const double ay,
7153 const double bx,
7154 const double by) noexcept
7155 {
7156 return ax * bx + ay * by;
7157 }
7158
7159 [[nodiscard]] static double norm2(const double x, const double y) noexcept
7160 {
7161 return dot2(x, y, x, y);
7162 }
7163
7164 [[nodiscard]] static Point point_from_double(const double x, const double y)
7165 {
7166 return {Geom_Number(x), Geom_Number(y)};
7167 }
7168
7169 [[nodiscard]] static Point lerp_point(const Point &a, const Point &b, const double t)
7170 {
7171 const double ax = to_double(a.get_x());
7172 const double ay = to_double(a.get_y());
7173 const double bx = to_double(b.get_x());
7174 const double by = to_double(b.get_y());
7175 return point_from_double((1.0 - t) * ax + t * bx, (1.0 - t) * ay + t * by);
7176 }
7177
7178 [[nodiscard]] static Point centroid_of(const Array<Point> &v)
7179 {
7180 Geom_Number sx = 0;
7181 Geom_Number sy = 0;
7182 for (size_t i = 0; i < v.size(); ++i)
7183 {
7184 sx += v(i).get_x();
7185 sy += v(i).get_y();
7186 }
7187 return {sx / Geom_Number(static_cast<long>(v.size())),
7188 sy / Geom_Number(static_cast<long>(v.size()))};
7189 }
7190
7191 [[nodiscard]] static SupportPoint support(const Array<Point> &p,
7192 const Array<Point> &q,
7193 const double dx,
7194 const double dy)
7195 {
7196 size_t ip = 0;
7197 size_t iq = 0;
7198 double best_p = -std::numeric_limits<double>::infinity();
7199 double best_q = -std::numeric_limits<double>::infinity();
7200
7201 for (size_t i = 0; i < p.size(); ++i)
7202 {
7203 const double proj = dot2(to_double(p(i).get_x()), to_double(p(i).get_y()), dx, dy);
7204 if (proj > best_p)
7205 {
7206 best_p = proj;
7207 ip = i;
7208 }
7209 }
7210
7211 // Support of Minkowski difference uses opposite direction in q.
7212 for (size_t i = 0; i < q.size(); ++i)
7213 {
7214 const double proj = dot2(to_double(q(i).get_x()), to_double(q(i).get_y()), -dx, -dy);
7215 if (proj > best_q)
7216 {
7217 best_q = proj;
7218 iq = i;
7219 }
7220 }
7221
7222 const Point &pa = p(ip);
7223 const Point &pb = q(iq);
7224 const Geom_Number vx = pa.get_x() - pb.get_x();
7225 const Geom_Number vy = pa.get_y() - pb.get_y();
7226 return SupportPoint{pa, pb, Point(vx, vy), to_double(vx), to_double(vy)};
7227 }
7228
7229 [[nodiscard]] static bool polygons_intersect_or_contain(const Polygon &p, const Polygon &q)
7230 {
7231 for (Polygon::Segment_Iterator itp(p); itp.has_curr(); itp.next_ne())
7232 {
7233 const Segment sp = itp.get_current_segment();
7234 for (Polygon::Segment_Iterator itq(q); itq.has_curr(); itq.next_ne())
7235 if (sp.intersects_with(itq.get_current_segment()))
7236 return true;
7237 }
7238
7239 Point vp;
7240 for (Polygon::Vertex_Iterator it(p); it.has_curr(); it.next_ne())
7241 {
7242 vp = it.get_current_vertex().to_point();
7243 break;
7244 }
7245
7246 Point vq;
7247 for (Polygon::Vertex_Iterator it(q); it.has_curr(); it.next_ne())
7248 {
7249 vq = it.get_current_vertex().to_point();
7250 break;
7251 }
7252
7254 }
7255
7256 [[nodiscard]] static ClosestSimplexResult closest_from_simplex(const std::vector<SupportPoint> &simplex)
7257 {
7258 ah_domain_error_if(simplex.empty()) << "GJK simplex cannot be empty";
7259
7261
7262 if (simplex.size() == 1)
7263 {
7264 out.reduced_simplex = simplex;
7265 out.cx = simplex[0].vx;
7266 out.cy = simplex[0].vy;
7267 out.witness_a = simplex[0].a;
7268 out.witness_b = simplex[0].b;
7269 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7270 return out;
7271 }
7272
7273 if (simplex.size() == 2)
7274 {
7275 const SupportPoint &a = simplex[0];
7276 const SupportPoint &b = simplex[1];
7277 const double abx = b.vx - a.vx;
7278 const double aby = b.vy - a.vy;
7279 const double ab2 = norm2(abx, aby);
7280
7281 if (ab2 <= kEps * kEps)
7282 {
7283 out.reduced_simplex = {a};
7284 out.cx = a.vx;
7285 out.cy = a.vy;
7286 out.witness_a = a.a;
7287 out.witness_b = a.b;
7288 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7289 return out;
7290 }
7291
7292 double t = -dot2(a.vx, a.vy, abx, aby) / ab2;
7293 if (t < 0.0)
7294 t = 0.0;
7295 if (t > 1.0)
7296 t = 1.0;
7297
7298 if (t <= kEps)
7299 {
7300 out.reduced_simplex = {a};
7301 out.cx = a.vx;
7302 out.cy = a.vy;
7303 out.witness_a = a.a;
7304 out.witness_b = a.b;
7305 }
7306 else if (t >= 1.0 - kEps)
7307 {
7308 out.reduced_simplex = {b};
7309 out.cx = b.vx;
7310 out.cy = b.vy;
7311 out.witness_a = b.a;
7312 out.witness_b = b.b;
7313 }
7314 else
7315 {
7316 out.reduced_simplex = {a, b};
7317 out.cx = a.vx + t * abx;
7318 out.cy = a.vy + t * aby;
7319 out.witness_a = lerp_point(a.a, b.a, t);
7320 out.witness_b = lerp_point(a.b, b.b, t);
7321 }
7322
7323 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7324 return out;
7325 }
7326
7327 // Triangle case.
7328 const SupportPoint &a = simplex[0];
7329 const SupportPoint &b = simplex[1];
7330 const SupportPoint &c = simplex[2];
7331
7332 const double abx = b.vx - a.vx;
7333 const double aby = b.vy - a.vy;
7334 const double acx = c.vx - a.vx;
7335 const double acy = c.vy - a.vy;
7336 const double apx = -a.vx;
7337 const double apy = -a.vy;
7338
7339 const double d1 = dot2(abx, aby, apx, apy);
7340 const double d2 = dot2(acx, acy, apx, apy);
7341 if (d1 <= 0.0 and d2 <= 0.0)
7342 {
7343 out.reduced_simplex = {a};
7344 out.cx = a.vx;
7345 out.cy = a.vy;
7346 out.witness_a = a.a;
7347 out.witness_b = a.b;
7348 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7349 return out;
7350 }
7351
7352 const double bpx = -b.vx;
7353 const double bpy = -b.vy;
7354 const double d3 = dot2(abx, aby, bpx, bpy);
7355 const double d4 = dot2(acx, acy, bpx, bpy);
7356 if (d3 >= 0.0 and d4 <= d3)
7357 {
7358 out.reduced_simplex = {b};
7359 out.cx = b.vx;
7360 out.cy = b.vy;
7361 out.witness_a = b.a;
7362 out.witness_b = b.b;
7363 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7364 return out;
7365 }
7366
7367 const double vc = d1 * d4 - d3 * d2;
7368 if (vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0)
7369 {
7370 const double t = d1 / (d1 - d3);
7371 out.reduced_simplex = {a, b};
7372 out.cx = a.vx + t * abx;
7373 out.cy = a.vy + t * aby;
7374 out.witness_a = lerp_point(a.a, b.a, t);
7375 out.witness_b = lerp_point(a.b, b.b, t);
7376 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7377 return out;
7378 }
7379
7380 const double cpx = -c.vx;
7381 const double cpy = -c.vy;
7382 const double d5 = dot2(abx, aby, cpx, cpy);
7383 const double d6 = dot2(acx, acy, cpx, cpy);
7384 if (d6 >= 0.0 and d5 <= d6)
7385 {
7386 out.reduced_simplex = {c};
7387 out.cx = c.vx;
7388 out.cy = c.vy;
7389 out.witness_a = c.a;
7390 out.witness_b = c.b;
7391 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7392 return out;
7393 }
7394
7395 const double vb = d5 * d2 - d1 * d6;
7396 if (vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0)
7397 {
7398 const double t = d2 / (d2 - d6);
7399 out.reduced_simplex = {a, c};
7400 out.cx = a.vx + t * acx;
7401 out.cy = a.vy + t * acy;
7402 out.witness_a = lerp_point(a.a, c.a, t);
7403 out.witness_b = lerp_point(a.b, c.b, t);
7404 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7405 return out;
7406 }
7407
7408 const double va = d3 * d6 - d5 * d4;
7409 if (va <= 0.0 and d4 - d3 >= 0.0 and d5 - d6 >= 0.0)
7410 {
7411 const double t = (d4 - d3) / (d4 - d3 + (d5 - d6));
7412 const double bcx = c.vx - b.vx;
7413 const double bcy = c.vy - b.vy;
7414 out.reduced_simplex = {b, c};
7415 out.cx = b.vx + t * bcx;
7416 out.cy = b.vy + t * bcy;
7417 out.witness_a = lerp_point(b.a, c.a, t);
7418 out.witness_b = lerp_point(b.b, c.b, t);
7419 out.contains_origin = norm2(out.cx, out.cy) <= kEps * kEps;
7420 return out;
7421 }
7422
7423 // Origin is inside triangle.
7424 const double denom = va + vb + vc;
7425 if (std::fabs(denom) <= kEps)
7426 {
7427 out.reduced_simplex = {a, b, c};
7428 out.cx = 0.0;
7429 out.cy = 0.0;
7430 out.witness_a = a.a;
7431 out.witness_b = a.b;
7432 out.contains_origin = true;
7433 return out;
7434 }
7435
7436 const double inv = 1.0 / denom;
7437 const double wa = va * inv;
7438 const double wb = vb * inv;
7439 const double wc = vc * inv;
7440 out.reduced_simplex = {a, b, c};
7441 out.cx = 0.0;
7442 out.cy = 0.0;
7443 out.witness_a = point_from_double(
7444 wa * to_double(a.a.get_x()) + wb * to_double(b.a.get_x()) + wc * to_double(c.a.get_x()),
7445 wa * to_double(a.a.get_y()) + wb * to_double(b.a.get_y()) + wc * to_double(c.a.get_y()));
7446 out.witness_b = point_from_double(
7447 wa * to_double(a.b.get_x()) + wb * to_double(b.b.get_x()) + wc * to_double(c.b.get_x()),
7448 wa * to_double(a.b.get_y()) + wb * to_double(b.b.get_y()) + wc * to_double(c.b.get_y()));
7449 out.contains_origin = true;
7450 return out;
7451 }
7452
7453 [[nodiscard]] static Result exact_refine_disjoint(const Polygon &p,
7454 const Polygon &q,
7455 const Array<Point> &pv,
7456 const Array<Point> &qv)
7457 {
7458 Result out;
7459 out.intersects = false;
7460
7462 {
7463 out.distance_squared = 0;
7464 out.distance = 0;
7465 out.closest_on_first = pv(0);
7466 out.closest_on_second = pv(0);
7467 out.intersects = true;
7468 return out;
7469 }
7470
7471 bool has_best = false;
7472 Geom_Number best_d2 = 0;
7473 Point best_a, best_b;
7474
7475 for (size_t i = 0; i < pv.size(); ++i)
7476 {
7477 const Point &pnt = pv(i);
7478 for (size_t j = 0; j < qv.size(); ++j)
7479 {
7480 const Point &q0 = qv(j);
7481 const Point &q1 = qv((j + 1) % qv.size());
7482 const Segment edge(q0, q1);
7483 const Point proj = edge.project(pnt);
7484 if (const Geom_Number d2 = pnt.distance_squared_to(proj); not has_best or d2 < best_d2)
7485 {
7486 has_best = true;
7487 best_d2 = d2;
7488 best_a = pnt;
7489 best_b = proj;
7490 }
7491 }
7492 }
7493
7494 for (size_t i = 0; i < qv.size(); ++i)
7495 {
7496 const Point &pnt = qv(i);
7497 for (size_t j = 0; j < pv.size(); ++j)
7498 {
7499 const Point &p0 = pv(j);
7500 const Point &p1 = pv((j + 1) % pv.size());
7501 const Segment edge(p0, p1);
7502 const Point proj = edge.project(pnt);
7503 if (const Geom_Number d2 = pnt.distance_squared_to(proj); not has_best or d2 < best_d2)
7504 {
7505 has_best = true;
7506 best_d2 = d2;
7507 best_a = proj;
7508 best_b = pnt;
7509 }
7510 }
7511 }
7512
7513 ah_domain_error_if(not has_best) << "Could not compute distance between convex polygons";
7514
7515 out.distance_squared = best_d2;
7516 out.distance = square_root(best_d2);
7517 out.closest_on_first = best_a;
7518 out.closest_on_second = best_b;
7519 out.intersects = (best_d2 == 0);
7520 return out;
7521 }
7522
7523public:
7530 [[nodiscard]] Result operator () (const Polygon &p, const Polygon &q) const
7531 {
7532 ah_domain_error_if(not p.is_closed()) << "First polygon must be closed";
7533 ah_domain_error_if(not q.is_closed()) << "Second polygon must be closed";
7534 ah_domain_error_if(p.size() < 3) << "First polygon must have at least 3 vertices";
7535 ah_domain_error_if(q.size() < 3) << "Second polygon must have at least 3 vertices";
7536
7539
7540 ah_domain_error_if(not GeomPolygonUtils::is_convex(pv)) << "First polygon must be convex";
7541 ah_domain_error_if(not GeomPolygonUtils::is_convex(qv)) << "Second polygon must be convex";
7542
7543 // Fast exact overlap check to avoid unnecessary iterations.
7545 {
7546 Result r;
7547 r.distance_squared = 0;
7548 r.distance = 0;
7549 r.closest_on_first = pv(0);
7550 r.closest_on_second = pv(0);
7551 r.intersects = true;
7552 return r;
7553 }
7554
7555 Point cp = centroid_of(pv);
7556 Point cq = centroid_of(qv);
7557 double dirx = to_double(cp.get_x() - cq.get_x());
7558 double diry = to_double(cp.get_y() - cq.get_y());
7559 if (norm2(dirx, diry) <= kEps * kEps)
7560 {
7561 dirx = 1.0;
7562 diry = 0.0;
7563 }
7564
7565 std::vector<SupportPoint> simplex;
7566 simplex.reserve(3);
7567 simplex.push_back(support(pv, qv, dirx, diry));
7568 dirx = -simplex[0].vx;
7569 diry = -simplex[0].vy;
7570
7571 double prev_d2 = std::numeric_limits<double>::infinity();
7572 size_t iters = 0;
7573
7574 for (; iters < kMaxIters; ++iters)
7575 {
7576 if (norm2(dirx, diry) <= kEps * kEps)
7577 break;
7578
7579 simplex.push_back(support(pv, qv, dirx, diry));
7580 if (simplex.size() > 3)
7581 simplex.erase(simplex.begin());
7582
7584 simplex = std::move(step.reduced_simplex);
7585
7586 const double d2 = norm2(step.cx, step.cy);
7587 if (step.contains_origin or d2 <= kEps * kEps)
7588 {
7589 Result r;
7590 r.distance_squared = 0;
7591 r.distance = 0;
7592 r.closest_on_first = step.witness_a;
7593 r.closest_on_second = step.witness_b;
7594 r.intersects = true;
7595 r.gjk_iterations = iters + 1;
7596 return r;
7597 }
7598
7599 if (prev_d2 - d2 <= kEps * std::max(1.0, prev_d2))
7600 break;
7601
7602 prev_d2 = d2;
7603 dirx = -step.cx;
7604 diry = -step.cy;
7605 }
7606
7607 Result refined = exact_refine_disjoint(p, q, pv, qv);
7608 refined.gjk_iterations = iters;
7609 return refined;
7610 }
7611};
7612
7613// ============================================================================
7614// KD-Tree Point Search — O(log n) Nearest Neighbor
7615// ============================================================================
7616
7645{
7649
7650 [[nodiscard]] static bool lexicographic_less(const Point &a, const Point &b)
7651 {
7652 if (a.get_x() < b.get_x())
7653 return true;
7654 if (b.get_x() < a.get_x())
7655 return false;
7656 return a.get_y() < b.get_y();
7657 }
7658
7659 [[nodiscard]] static Array<Point> unique_points(Array<Point> points)
7660 {
7661 quicksort_op(points, [](const Point &a, const Point &b)
7662 {
7663 return lexicographic_less(a, b);
7664 });
7665 Array<Point> uniq;
7666 uniq.reserve(points.size());
7667 for (size_t i = 0; i < points.size(); ++i)
7668 if (uniq.is_empty() or uniq.get_last() != points(i))
7669 uniq.append(points(i));
7670 return uniq;
7671 }
7672
7675 [[nodiscard]] Rectangle extended_bounds() const
7676 {
7677 Geom_Number xmin = bounds_.get_xmin(), ymin = bounds_.get_ymin();
7678 Geom_Number xmax = bounds_.get_xmax(), ymax = bounds_.get_ymax();
7679 for (size_t i = 0; i < points_.size(); ++i)
7680 {
7681 const Point & p = points_(i);
7682 if (p.get_x() < xmin)
7683 xmin = p.get_x();
7684 if (p.get_x() > xmax)
7685 xmax = p.get_x();
7686 if (p.get_y() < ymin)
7687 ymin = p.get_y();
7688 if (p.get_y() > ymax)
7689 ymax = p.get_y();
7690 }
7691 return {xmin, ymin, xmax, ymax};
7692 }
7693
7694public:
7699 {
7701 bool split_on_x = true;
7703 size_t depth = 0;
7704 bool is_leaf = false;
7706 };
7707
7717
7727 const Geom_Number &ymin,
7728 const Geom_Number &xmax,
7729 const Geom_Number &ymax)
7730 : tree(xmin, ymin, xmax, ymax), bounds_(xmin, ymin, xmax, ymax)
7731 {}
7732
7743 [[nodiscard]] static KDTreePointSearch build(const Array<Point> &points,
7744 const Geom_Number &xmin,
7745 const Geom_Number &ymin,
7746 const Geom_Number &xmax,
7747 const Geom_Number &ymax)
7748 {
7749 KDTreePointSearch kd(xmin, ymin, xmax, ymax);
7750 kd.tree = K2Tree<>::build(points, Point(xmin, ymin), Point(xmax, ymax));
7751 kd.points_ = unique_points(points);
7752 return kd;
7753 }
7754
7756 bool insert(const Point &p)
7757 {
7758 if (not tree.insert(p))
7759 return false;
7760 points_.append(p);
7761 return true;
7762 }
7763
7765 [[nodiscard]] bool contains(const Point &p) const
7766 {
7767 return tree.contains(p);
7768 }
7769
7771 [[nodiscard]] std::optional<Point> nearest(const Point &p) const
7772 {
7773 return tree.nearest(p);
7774 }
7775
7777 void range(const Geom_Number &xmin,
7778 const Geom_Number &ymin,
7779 const Geom_Number &xmax,
7780 const Geom_Number &ymax,
7781 DynList<Point> *out) const
7782 {
7783 tree.range({xmin, ymin, xmax, ymax}, out);
7784 }
7785
7787 [[nodiscard]] size_t size() const noexcept
7788 {
7789 return tree.size();
7790 }
7791
7793 [[nodiscard]] bool is_empty() const noexcept
7794 {
7795 return tree.is_empty();
7796 }
7797
7799 template <typename Op>
7800 void for_each(Op &&op) const
7801 {
7802 tree.for_each(std::forward<Op>(op));
7803 }
7804
7813 [[nodiscard]] DebugSnapshot debug_snapshot() const
7814 {
7815 DebugSnapshot snap;
7816 // Split from the bounds given, a point outside them made a partition
7817 // whose corners were swapped, which threw range_error
7818 snap.bounds = extended_bounds();
7819 snap.points = points_;
7820 if (points_.is_empty())
7821 return snap;
7822
7823 auto recurse = [&](const auto &self, const Array<Point> &pts, const Rectangle &region,
7824 const size_t depth, const bool split_on_x) -> void
7825 {
7826 if (pts.is_empty())
7827 return;
7828
7829 Array<Point> sorted = pts;
7830 quicksort_op(sorted, [split_on_x](const Point &a, const Point &b)
7831 {
7832 if (split_on_x)
7833 {
7834 if (a.get_x() != b.get_x())
7835 return a.get_x() < b.get_x();
7836 return a.get_y() < b.get_y();
7837 }
7838 if (a.get_y() != b.get_y())
7839 return a.get_y() < b.get_y();
7840 return a.get_x() < b.get_x();
7841 });
7842
7843 size_t mid = sorted.size() / 2;
7844 if (mid == 0)
7845 mid = 1;
7846 if (mid >= sorted.size())
7847 mid = sorted.size() - 1;
7848
7849 const Point pivot = sorted(mid);
7850 DebugPartition part;
7851 part.region = region;
7852 part.split_on_x = split_on_x;
7853 part.split_value = split_on_x ? pivot.get_x() : pivot.get_y();
7854 part.depth = depth;
7855 part.is_leaf = sorted.size() == 1;
7856 part.representative = pivot;
7857 snap.partitions.append(part);
7858
7859 if (sorted.size() == 1)
7860 return;
7861
7862 Array<Point> left_pts;
7863 Array<Point> right_pts;
7864 left_pts.reserve(mid);
7865 right_pts.reserve(sorted.size() - mid);
7866 for (size_t i = 0; i < mid; ++i)
7867 left_pts.append(sorted(i));
7868 for (size_t i = mid; i < sorted.size(); ++i)
7869 right_pts.append(sorted(i));
7870
7871 if (split_on_x)
7872 {
7873 Rectangle left(region.get_xmin(), region.get_ymin(), pivot.get_x(), region.get_ymax());
7874 Rectangle right(pivot.get_x(), region.get_ymin(), region.get_xmax(), region.get_ymax());
7875 self(self, left_pts, left, depth + 1, false);
7876 self(self, right_pts, right, depth + 1, false);
7877 }
7878 else
7879 {
7880 Rectangle bottom(region.get_xmin(), region.get_ymin(), region.get_xmax(), pivot.get_y());
7881 Rectangle top(region.get_xmin(), pivot.get_y(), region.get_xmax(), region.get_ymax());
7882 self(self, left_pts, bottom, depth + 1, true);
7883 self(self, right_pts, top, depth + 1, true);
7884 }
7885 };
7886
7887 recurse(recurse, points_, snap.bounds, 0, true);
7888 return snap;
7889 }
7890};
7891
7892// ============================================================================
7893// Convex Polygon Decomposition — Hertel-Mehlhorn
7894// ============================================================================
7895
7929{
7930 static constexpr size_t NONE = ~static_cast<size_t>(0);
7931
7932 [[nodiscard]] static size_t find_pos(const Array<size_t> &face, size_t v)
7933 {
7934 for (size_t i = 0; i < face.size(); ++i)
7935 if (face(i) == v)
7936 return i;
7937 return NONE;
7938 }
7939
7940 [[nodiscard]] static bool is_polygon_edge(size_t u, size_t v, size_t n)
7941 {
7942 if (u > v)
7943 {
7944 const size_t tmp = u;
7945 u = v;
7946 v = tmp;
7947 }
7948 return v == u + 1 or (u == 0 and v == n - 1);
7949 }
7950
7952 [[nodiscard]] static bool can_merge(const Array<Point> &pts,
7953 const Array<size_t> &f1,
7954 const Array<size_t> &f2,
7955 size_t u,
7956 size_t v)
7957 {
7958 const size_t n1 = f1.size();
7959 const size_t n2 = f2.size();
7960
7961 size_t pu1 = find_pos(f1, u);
7962 size_t pv1 = find_pos(f1, v);
7963
7964 // Ensure u is followed by v in f1 (CCW). If not, swap roles.
7965 if ((pu1 + 1) % n1 != pv1)
7966 {
7967 const size_t tmp = u;
7968 u = v;
7969 v = tmp;
7970 pu1 = find_pos(f1, u);
7971 pv1 = find_pos(f1, v);
7972 }
7973
7974 const size_t prev_u = f1((pu1 + n1 - 1) % n1);
7975 const size_t next_v = f1((pv1 + 1) % n1);
7976
7977 const size_t pu2 = find_pos(f2, u);
7978 const size_t pv2 = find_pos(f2, v);
7979
7980 const size_t next_u = f2((pu2 + 1) % n2);
7981 const size_t prev_v = f2((pv2 + n2 - 1) % n2);
7982
7983 if (orientation(pts(prev_u), pts(u), pts(next_u)) == Orientation::CW)
7984 return false;
7985 if (orientation(pts(prev_v), pts(v), pts(next_v)) == Orientation::CW)
7986 return false;
7987
7988 return true;
7989 }
7990
7992 [[nodiscard]] static Array<size_t> merge_faces(const Array<size_t> &f1,
7993 const Array<size_t> &f2,
7994 size_t u,
7995 size_t v)
7996 {
7997 const size_t n1 = f1.size();
7998 const size_t n2 = f2.size();
7999
8000 size_t pu1 = find_pos(f1, u);
8001 size_t pv1 = find_pos(f1, v);
8002
8003 if ((pu1 + 1) % n1 != pv1)
8004 {
8005 const size_t tmp = u;
8006 u = v;
8007 v = tmp;
8008 pv1 = find_pos(f1, v);
8009 }
8010
8011 const size_t pu2 = find_pos(f2, u);
8012
8013 Array<size_t> merged;
8014 merged.reserve(n1 + n2 - 2);
8015
8016 // Part 1: f1 vertices from after v around to u (inclusive), skip v.
8017 for (size_t k = 0; k < n1 - 1; ++k)
8018 merged.append(f1((pv1 + 1 + k) % n1));
8019
8020 // Part 2: f2 vertices from after u around to v (inclusive), skip u.
8021 for (size_t k = 0; k < n2 - 1; ++k)
8022 merged.append(f2((pu2 + 1 + k) % n2));
8023
8024 return merged;
8025 }
8026
8027 [[nodiscard]] static Array<Point> extract_vertices(const Polygon &p)
8028 {
8030 }
8031
8032public:
8039 [[nodiscard]] Array<Polygon> operator () (const Polygon &poly) const
8040 {
8041 ah_domain_error_if(not poly.is_closed()) << "Polygon must be closed";
8042 ah_domain_error_if(poly.size() < 3) << "Polygon must have >= 3 vertices";
8043
8044 const Array<Point> pts = extract_vertices(poly);
8045 const size_t n = pts.size();
8046
8047 if (n == 3)
8048 {
8049 Array<Polygon> result;
8050 result.append(poly);
8051 return result;
8052 }
8053
8054 // Triangulate.
8056 DynList<Triangle> tri_list = triang(poly);
8057
8058 // Build indexed faces from triangles.
8059 Array<Array<size_t>> faces;
8060 for (auto it = tri_list.get_it(); it.has_curr(); it.next_ne())
8061 {
8062 const Triangle &t = it.get_curr();
8063 size_t i0 = NONE, i1 = NONE, i2 = NONE;
8064 for (size_t i = 0; i < n; ++i)
8065 {
8066 if (i0 == NONE and pts(i) == t.get_p1())
8067 i0 = i;
8068 if (i1 == NONE and pts(i) == t.get_p2())
8069 i1 = i;
8070 if (i2 == NONE and pts(i) == t.get_p3())
8071 i2 = i;
8072 }
8073 if (i0 == NONE or i1 == NONE or i2 == NONE)
8074 continue;
8075
8076 if (orientation(pts(i0), pts(i1), pts(i2)) == Orientation::CW)
8077 {
8078 const size_t tmp = i1;
8079 i1 = i2;
8080 i2 = tmp;
8081 }
8082
8083 Array<size_t> face;
8084 face.append(i0);
8085 face.append(i1);
8086 face.append(i2);
8087 faces.append(std::move(face));
8088 }
8089
8090 // Hertel-Mehlhorn: greedily merge across diagonals.
8091 bool changed = true;
8092 while (changed)
8093 {
8094 changed = false;
8095 for (size_t fi = 0; fi < faces.size() and not changed; ++fi)
8096 {
8097 const auto f1 = faces(fi); // copy to avoid dangling when faces mutates
8098 for (size_t k = 0; k < f1.size() and not changed; ++k)
8099 {
8100 const size_t u = f1(k);
8101 const size_t v = f1((k + 1) % f1.size());
8102
8103 if (is_polygon_edge(u, v, n))
8104 continue;
8105
8106 for (size_t fj = fi + 1; fj < faces.size() and not changed; ++fj)
8107 {
8108 const auto f2 = faces(fj); // copy for the same reason
8109 if (find_pos(f2, u) == NONE or find_pos(f2, v) == NONE)
8110 continue;
8111
8112 if (not can_merge(pts, f1, f2, u, v))
8113 continue;
8114
8115 Array<size_t> merged = merge_faces(f1, f2, u, v);
8116
8117 Array<Array<size_t>> new_faces;
8118 new_faces.reserve(faces.size() - 1);
8119 for (size_t i = 0; i < faces.size(); ++i)
8120 {
8121 if (i == fi)
8122 new_faces.append(std::move(merged));
8123 else if (i != fj)
8124 new_faces.append(std::move(faces(i)));
8125 }
8126 faces = std::move(new_faces);
8127 changed = true;
8128 }
8129 }
8130 }
8131 }
8132
8133 // Convert index faces to Polygons.
8134 Array<Polygon> result;
8135 result.reserve(faces.size());
8136 for (size_t fi = 0; fi < faces.size(); ++fi)
8137 {
8138 Polygon p;
8139 for (size_t k = 0; k < faces(fi).size(); ++k)
8140 p.add_vertex(pts(faces(fi)(k)));
8141 if (p.size() >= 3)
8142 {
8143 p.close();
8144 result.append(std::move(p));
8145 }
8146 }
8147
8148 return result;
8149 }
8150};
8151
8152// ============================================================================
8153// Range Tree 2D — Orthogonal Range Queries
8154// ============================================================================
8155
8181{
8182public:
8187 {
8188 size_t tree_index = 0;
8189 size_t lo = 0;
8190 size_t hi = 0;
8191 size_t left = ~static_cast<size_t>(0);
8192 size_t right = ~static_cast<size_t>(0);
8196 size_t y_sorted_size = 0;
8197 bool is_leaf = false;
8198 };
8199
8208
8209private:
8213 struct Node
8214 {
8216 };
8217
8220 size_t n_ = 0;
8221 bool built_ = false;
8222
8224 [[nodiscard]] static size_t lower_bound_y(const Array<Point> &arr, const Geom_Number &ymin)
8225 {
8226 size_t lo = 0, hi = arr.size();
8227 while (lo < hi)
8228 if (const size_t mid = lo + (hi - lo) / 2; arr(mid).get_y() < ymin)
8229 lo = mid + 1;
8230 else
8231 hi = mid;
8232 return lo;
8233 }
8234
8236 [[nodiscard]] static size_t upper_bound_y(const Array<Point> &arr, const Geom_Number &ymax)
8237 {
8238 size_t lo = 0, hi = arr.size();
8239 while (lo < hi)
8240 if (const size_t mid = lo + (hi - lo) / 2; arr(mid).get_y() <= ymax)
8241 lo = mid + 1;
8242 else
8243 hi = mid;
8244 return lo;
8245 }
8246
8248 [[nodiscard]] size_t lower_bound_x(const Geom_Number &xval) const
8249 {
8250 size_t lo = 0, hi = n_;
8251 while (lo < hi)
8252 if (const size_t mid = lo + (hi - lo) / 2; pts_(mid).get_x() < xval)
8253 lo = mid + 1;
8254 else
8255 hi = mid;
8256 return lo;
8257 }
8258
8260 [[nodiscard]] size_t upper_bound_x(const Geom_Number &xval) const
8261 {
8262 size_t lo = 0, hi = n_;
8263 while (lo < hi)
8264 if (const size_t mid = lo + (hi - lo) / 2; pts_(mid).get_x() <= xval)
8265 lo = mid + 1;
8266 else
8267 hi = mid;
8268 return lo;
8269 }
8270
8271 void build_node(const size_t node, const size_t lo, const size_t hi)
8272 {
8273 if (lo == hi)
8274 {
8275 tree_(node).y_sorted.append(pts_(lo));
8276 return;
8277 }
8278
8279 const size_t mid = lo + (hi - lo) / 2;
8280 build_node(2 * node, lo, mid);
8281 build_node(2 * node + 1, mid + 1, hi);
8282
8283 // Merge children's y-sorted arrays.
8284 const auto &left = tree_(2 * node).y_sorted;
8285 const auto &right = tree_(2 * node + 1).y_sorted;
8286 auto &merged = tree_(node).y_sorted;
8287 merged.reserve(left.size() + right.size());
8288
8289 size_t i = 0, j = 0;
8290 while (i < left.size() and j < right.size())
8291 if (left(i).get_y() < right(j).get_y() or
8292 (left(i).get_y() == right(j).get_y() && left(i).get_x() <= right(j).get_x()))
8293 merged.append(left(i++));
8294 else
8295 merged.append(right(j++));
8296 while (i < left.size())
8297 merged.append(left(i++));
8298 while (j < right.size())
8299 merged.append(right(j++));
8300 }
8301
8302 void query_range(const size_t node,
8303 const size_t lo,
8304 const size_t hi,
8305 const size_t qlo,
8306 const size_t qhi,
8307 const Geom_Number &ymin,
8308 const Geom_Number &ymax,
8309 DynList<Point> &out) const
8310 {
8311 if (qlo > qhi or lo > qhi or hi < qlo)
8312 return;
8313
8314 if (qlo <= lo and hi <= qhi)
8315 {
8316 const auto &ys = tree_(node).y_sorted;
8317 const size_t from = lower_bound_y(ys, ymin);
8318 const size_t to = upper_bound_y(ys, ymax);
8319 for (size_t i = from; i < to; ++i)
8320 out.append(ys(i));
8321 return;
8322 }
8323
8324 const size_t mid = lo + (hi - lo) / 2;
8325 query_range(2 * node, lo, mid, qlo, qhi, ymin, ymax, out);
8326 query_range(2 * node + 1, mid + 1, hi, qlo, qhi, ymin, ymax, out);
8327 }
8328
8329public:
8331 RangeTree2D() = default;
8332
8337 RangeTree2D(const RangeTree2D &other) = default;
8338
8348 RangeTree2D(RangeTree2D &&other) noexcept
8349 : pts_(std::move(other.pts_)), tree_(std::move(other.tree_)),
8350 n_(std::exchange(other.n_, 0)), built_(std::exchange(other.built_, false))
8351 {}
8352
8358 RangeTree2D &operator=(const RangeTree2D &other) = default;
8359
8367 {
8368 swap(other);
8369 return *this;
8370 }
8371
8376 void swap(RangeTree2D &other) noexcept
8377 {
8378 pts_.swap(other.pts_);
8379 tree_.swap(other.tree_);
8380 std::swap(n_, other.n_);
8381 std::swap(built_, other.built_);
8382 }
8383
8385 void build(const DynList<Point> &points)
8386 {
8387 pts_ = Array<Point>();
8388 for (auto it = points.get_it(); it.has_curr(); it.next_ne())
8389 pts_.append(it.get_curr());
8390
8391 n_ = pts_.size();
8392 if (n_ == 0)
8393 {
8394 built_ = true;
8395 return;
8396 }
8397
8398 quicksort_op(pts_, [](const Point &a, const Point &b)
8399 {
8400 return a.get_x() < b.get_x() || (a.get_x() == b.get_x() and a.get_y() < b.get_y());
8401 });
8402
8403 tree_ = Array<Node>();
8404 const size_t tree_sz = 4 * n_ + 4;
8405 tree_.reserve(tree_sz);
8406 for (size_t i = 0; i < tree_sz; ++i)
8407 tree_.append(Node{Array<Point>()});
8408
8409 build_node(1, 0, n_ - 1);
8410 built_ = true;
8411 }
8412
8414 [[nodiscard]] DynList<Point> query(const Geom_Number &xmin,
8415 const Geom_Number &xmax,
8416 const Geom_Number &ymin,
8417 const Geom_Number &ymax) const
8418 {
8420 if (not built_ or n_ == 0)
8421 return out;
8422
8423 const size_t qlo = lower_bound_x(xmin);
8424 const size_t qhi = upper_bound_x(xmax);
8425 if (qhi == 0)
8426 return out;
8427
8428 query_range(1, 0, n_ - 1, qlo, qhi - 1, ymin, ymax, out);
8429 return out;
8430 }
8431
8432 [[nodiscard]] size_t size() const noexcept
8433 {
8434 return n_;
8435 }
8436
8437 [[nodiscard]] bool is_empty() const noexcept
8438 {
8439 return n_ == 0;
8440 }
8441
8443 [[nodiscard]] DebugSnapshot debug_snapshot() const
8444 {
8445 DebugSnapshot snap;
8446 snap.x_sorted_points = pts_;
8447 if (not built_ or n_ == 0)
8448 return snap;
8449
8450 // A binary range tree with n leaves has exactly 2n - 1 snapshot nodes.
8451 // Reserving also avoids needless reallocations while the snapshot is built.
8452 const size_t max_size = std::numeric_limits<size_t>::max();
8453 if (n_ <= max_size / 2 + 1)
8454 snap.nodes.reserve(n_ + (n_ - 1));
8455
8456 auto build_debug = [&](const auto &self, const size_t tree_idx, const size_t lo,
8457 const size_t hi) -> size_t
8458 {
8459 const size_t out_idx = snap.nodes.size();
8460 snap.nodes.append(DebugNode{});
8461 snap.nodes(out_idx).tree_index = tree_idx;
8462 snap.nodes(out_idx).lo = lo;
8463 snap.nodes(out_idx).hi = hi;
8464 snap.nodes(out_idx).is_leaf = lo == hi;
8465 snap.nodes(out_idx).xmin = pts_(lo).get_x();
8466 snap.nodes(out_idx).xmax = pts_(hi).get_x();
8467 snap.nodes(out_idx).y_sorted_size = tree_(tree_idx).y_sorted.size();
8468 snap.nodes(out_idx).split_x = pts_((lo + hi) / 2).get_x();
8469
8470 if (lo < hi)
8471 {
8472 const size_t mid = lo + (hi - lo) / 2;
8473 const size_t left = self(self, 2 * tree_idx, lo, mid);
8474 const size_t right = self(self, 2 * tree_idx + 1, mid + 1, hi);
8475 snap.nodes(out_idx).left = left;
8476 snap.nodes(out_idx).right = right;
8477 }
8478
8479 return out_idx;
8480 };
8481
8482 build_debug(build_debug, 1, 0, n_ - 1);
8483 return snap;
8484 }
8485};
8486
8487// ============================================================================
8488// Convex Polygon Offset (Inward / Outward)
8489// ============================================================================
8490
8506{
8507 friend class PolygonOffset;
8508
8509 [[nodiscard]] static Array<Point> extract_verts(const Polygon &poly)
8510 {
8512 }
8513
8514 [[nodiscard]] static Geom_Number signed_double_area(const Array<Point> &v)
8515 {
8517 }
8518
8519 [[nodiscard]] static bool is_convex(const Array<Point> &v)
8520 {
8521 if (v.size() < 3)
8522 return false;
8524 }
8525
8526 static void ensure_ccw(Array<Point> &v)
8527 {
8529 }
8530
8540 static void offset_edge(const Point &a,
8541 const Point &b,
8542 const Geom_Number &d,
8543 const bool inward,
8544 Point &oa,
8545 Point &ob)
8546 {
8547 const mpfr_class dx(b.get_x() - a.get_x());
8548 const mpfr_class dy(b.get_y() - a.get_y());
8549 const mpfr_class len = hypot(dx, dy);
8550 const mpfr_class md(d);
8551
8552 // For CCW polygon: inward normal = (dy, -dx)/len, outward = (-dy, dx)/len
8553 mpfr_class nx, ny;
8554 if (inward)
8555 {
8556 nx = -dy * md / len;
8557 ny = dx * md / len;
8558 }
8559 else
8560 {
8561 nx = dy * md / len;
8562 ny = -dx * md / len;
8563 }
8564
8565 oa = Point(Geom_Number(mpfr_class(a.get_x()) + nx), Geom_Number(mpfr_class(a.get_y()) + ny));
8566 ob = Point(Geom_Number(mpfr_class(b.get_x()) + nx), Geom_Number(mpfr_class(b.get_y()) + ny));
8567 }
8568
8570 [[nodiscard]] static Point line_intersect(const Point &a1,
8571 const Point &a2,
8572 const Point &b1,
8573 const Point &b2)
8574 {
8575 const Geom_Number &a1x = a1.get_x(), &a1y = a1.get_y();
8576 const Geom_Number &a2x = a2.get_x(), &a2y = a2.get_y();
8577 const Geom_Number &b1x = b1.get_x(), &b1y = b1.get_y();
8578 const Geom_Number &b2x = b2.get_x(), &b2y = b2.get_y();
8579
8580 const Geom_Number dax = a2x - a1x, day = a2y - a1y;
8581 const Geom_Number dbx = b2x - b1x, dby = b2y - b1y;
8582 const Geom_Number denom = dax * dby - day * dbx;
8583 if (denom == 0)
8584 {
8585 // Consecutive offset lines can be parallel when the input has a
8586 // collinear triple. In that case, use the shared shifted vertex.
8587 return a2;
8588 }
8589
8590 const Geom_Number t = ((b1x - a1x) * dby - (b1y - a1y) * dbx) / denom;
8591 return {a1x + t * dax, a1y + t * day};
8592 }
8593
8594public:
8602 static Polygon inward(const Polygon &convex_poly, const Geom_Number &distance)
8603 {
8604 ah_domain_error_if(not convex_poly.is_closed()) << "Polygon must be closed";
8605
8606 Array<Point> v = extract_verts(convex_poly);
8607
8608 ah_domain_error_if(v.size() < 3) << "Polygon must have >= 3 vertices";
8609 ah_domain_error_if(not is_convex(v)) << "Polygon must be convex";
8610
8611 if (distance == 0)
8612 return convex_poly;
8613
8614 ensure_ccw(v);
8615 const size_t n = v.size();
8616
8618 hps.reserve(n);
8619
8620 for (size_t i = 0; i < n; ++i)
8621 {
8622 const size_t j = (i + 1) % n;
8623 Point oa, ob;
8624 offset_edge(v(i), v(j), distance, true, oa, ob);
8626 }
8627
8628 constexpr HalfPlaneIntersection hpi;
8629 return hpi(hps);
8630 }
8631
8639 static Polygon outward(const Polygon &convex_poly, const Geom_Number &distance)
8640 {
8641 ah_domain_error_if(not convex_poly.is_closed()) << "Polygon must be closed";
8642
8643 Array<Point> v = extract_verts(convex_poly);
8644
8645 ah_domain_error_if(v.size() < 3) << "Polygon must have >= 3 vertices";
8646 ah_domain_error_if(not is_convex(v)) << "Polygon must be convex";
8647
8648 if (distance == 0)
8649 return convex_poly;
8650
8651 ensure_ccw(v);
8652 const size_t n = v.size();
8653
8654 // Compute offset lines for each edge.
8655 Array<Point> oa, ob; // offset edge endpoints
8656 oa.reserve(n);
8657 ob.reserve(n);
8658 for (size_t i = 0; i < n; ++i)
8659 {
8660 Point a, b;
8661 offset_edge(v(i), v((i + 1) % n), distance, false, a, b);
8662 oa.append(a);
8663 ob.append(b);
8664 }
8665
8666 // Intersect consecutive offset lines → new vertices.
8667 Polygon result;
8668 for (size_t i = 0; i < n; ++i)
8669 {
8670 const size_t j = (i + 1) % n;
8671 const Geom_Number dax = ob(i).get_x() - oa(i).get_x();
8672 const Geom_Number day = ob(i).get_y() - oa(i).get_y();
8673 const Geom_Number dbx = ob(j).get_x() - oa(j).get_x();
8674 const Geom_Number dby = ob(j).get_y() - oa(j).get_y();
8675 if (const Geom_Number denom = dax * dby - day * dbx; denom == 0)
8676 // Collinear triples produce consecutive parallel offset lines:
8677 // there is no corner vertex to add for that junction.
8678 continue;
8679
8680 result.add_vertex(line_intersect(oa(i), ob(i), oa(j), ob(j)));
8681 }
8682 if (result.size() >= 3)
8683 result.close();
8684 return result;
8685 }
8686};
8687
8688// ============================================================================
8689// General Polygon Offset (non-convex)
8690// ============================================================================
8691
8719{
8720public:
8724 enum class JoinType
8725 {
8726 Miter,
8727 Bevel
8728 };
8729
8733 struct Result
8734 {
8736
8740 [[nodiscard]] bool is_empty() const noexcept
8741 {
8742 return polygons.is_empty();
8743 }
8744
8745 [[nodiscard]] size_t size() const noexcept
8746 {
8747 return polygons.size();
8748 }
8749 };
8750
8761 [[nodiscard]] Result operator () (const Polygon &poly,
8762 const Geom_Number &distance,
8764 const Geom_Number &miter_limit = Geom_Number(2)) const
8765 {
8766 ah_domain_error_if(not poly.is_closed()) << "Polygon must be closed";
8767 ah_domain_error_if(poly.size() < 3) << "Polygon must have >= 3 vertices";
8768
8769 if (distance == 0)
8770 {
8771 Result r;
8772 r.polygons.append(poly);
8773 return r;
8774 }
8775
8778
8779 const Array<Point> raw = compute_raw_offset(v, distance, join, miter_limit);
8780
8781 if (raw.size() < 3)
8782 return Result{};
8783
8784 return cleanup(raw);
8785 }
8786
8793 [[nodiscard]] Polygon offset_polygon(const Polygon &poly,
8794 const Geom_Number &distance,
8796 const Geom_Number &miter_limit = Geom_Number(2)) const
8797 {
8798 Result r = (*this)(poly, distance, join, miter_limit);
8799 if (r.is_empty())
8800 return {};
8801
8802 size_t best = 0;
8803 Geom_Number best_area = abs_area(r.polygons(0));
8804 for (size_t i = 1; i < r.polygons.size(); ++i)
8805 if (const Geom_Number a = abs_area(r.polygons(i)); a > best_area)
8806 {
8807 best_area = a;
8808 best = i;
8809 }
8810 return r.polygons(best);
8811 }
8812
8813private:
8814 // ----- helpers -----
8815
8816 [[nodiscard]] static Geom_Number abs_area(const Polygon &p)
8817 {
8819 if (a < 0)
8820 a = -a;
8821 return a;
8822 }
8823
8826 static void offset_edge(const Point &a,
8827 const Point &b,
8828 const Geom_Number &d,
8829 const bool inward,
8830 Point &oa,
8831 Point &ob)
8832 {
8833 ConvexPolygonOffset::offset_edge(a, b, d, inward, oa, ob);
8834 }
8835
8837 [[nodiscard]] static Point line_intersect(const Point &a1,
8838 const Point &a2,
8839 const Point &b1,
8840 const Point &b2)
8841 {
8842 return ConvexPolygonOffset::line_intersect(a1, a2, b1, b2);
8843 }
8844
8845 // ----- Phase 1: raw offset polygon -----
8846
8848 [[nodiscard]] static Geom_Number sq_dist(const Point &a, const Point &b)
8849 {
8850 const Geom_Number dx = b.get_x() - a.get_x();
8851 const Geom_Number dy = b.get_y() - a.get_y();
8852 return dx * dx + dy * dy;
8853 }
8854
8855 [[nodiscard]] static Array<Point> compute_raw_offset(const Array<Point> &v,
8856 const Geom_Number &distance,
8857 const JoinType join,
8858 const Geom_Number &miter_limit)
8859 {
8860 const size_t n = v.size();
8861 const bool inward = distance < 0;
8862 Geom_Number d = distance;
8863 if (inward)
8864 d = -distance;
8865
8866 // Compute offset edge pairs.
8867 Array<Point> oa, ob;
8868 oa.reserve(n);
8869 ob.reserve(n);
8870 for (size_t i = 0; i < n; ++i)
8871 {
8872 Point a, b;
8873 offset_edge(v(i), v((i + 1) % n), d, inward, a, b);
8874 oa.append(a);
8875 ob.append(b);
8876 }
8877
8878 // Join consecutive offset edges, tracking junction boundaries.
8879 const Geom_Number miter_sq = miter_limit * miter_limit * d * d;
8880 Array<Point> raw;
8881 raw.reserve(n * 2);
8882
8883 // junction_first[i] = index in raw where junction i's vertices begin.
8884 // junction_count[i] = number of vertices emitted for junction i.
8885 Array<size_t> junction_first, junction_count;
8886 junction_first.reserve(n);
8887 junction_count.reserve(n);
8888
8889 for (size_t i = 0; i < n; ++i)
8890 {
8891 const size_t j = (i + 1) % n;
8892 junction_first.append(raw.size());
8893
8894 const Geom_Number dax = ob(i).get_x() - oa(i).get_x();
8895 const Geom_Number day = ob(i).get_y() - oa(i).get_y();
8896 const Geom_Number dbx = ob(j).get_x() - oa(j).get_x();
8897 const Geom_Number dby = ob(j).get_y() - oa(j).get_y();
8898
8899 if (const Geom_Number denom = dax * dby - day * dbx; denom == 0)
8900 {
8901 junction_count.append(0);
8902 continue;
8903 }
8904
8905 if (const Point miter = line_intersect(oa(i), ob(i), oa(j), ob(j)); join == JoinType::Bevel or
8906 (join == JoinType::Miter && sq_dist(v((i + 1) % n), miter) > miter_sq))
8907 {
8908 raw.append(ob(i));
8909 raw.append(oa(j));
8910 junction_count.append(2);
8911 }
8912 else
8913 {
8914 raw.append(miter);
8915 junction_count.append(1);
8916 }
8917 }
8918
8919 // Validate edge directions: for each span between consecutive
8920 // junctions, the direction must match the corresponding original edge.
8921 // A reversed direction indicates that the offset has "crossed through"
8922 // the polygon (excessive offset).
8923 for (size_t i = 0; i < n; ++i)
8924 {
8925 const size_t j = (i + 1) % n;
8926 if (junction_count(i) == 0 || junction_count(j) == 0)
8927 continue;
8928
8929 // Span runs from the last vertex of junction i to the first
8930 // vertex of junction j, along offset edge (i+1)%n.
8931 const size_t span_start = junction_first(i) + junction_count(i) - 1;
8932 const size_t span_end = junction_first(j);
8933
8934 const Geom_Number sdx = raw(span_end).get_x() - raw(span_start).get_x();
8935 const Geom_Number sdy = raw(span_end).get_y() - raw(span_start).get_y();
8936
8937 // Direction of original edge (i+1)%n: v(j) → v((j+1)%n).
8938 const Geom_Number edx = v((j + 1) % n).get_x() - v(j).get_x();
8939 const Geom_Number edy = v((j + 1) % n).get_y() - v(j).get_y();
8940
8941 if (sdx * edx + sdy * edy < 0)
8942 return {}; // direction reversed → excessive offset
8943 }
8944
8945 return raw;
8946 }
8947
8948 // ----- Phase 2: self-intersection cleanup -----
8949
8952 {
8955 Geom_Number alpha_i, alpha_j; // parameter along each edge
8956 };
8957
8960 {
8962 bool is_intersection = false;
8963 size_t partner = SIZE_MAX; // index of same point on other edge
8964 bool visited = false;
8966 };
8967
8969 [[nodiscard]] static Geom_Number edge_param(const Point &P, const Point &Q, const Point &I)
8970 {
8971 if (const Geom_Number dx = Q.get_x() - P.get_x(); dx != 0)
8972 return (I.get_x() - P.get_x()) / dx;
8973 return (I.get_y() - P.get_y()) / (Q.get_y() - P.get_y());
8974 }
8975
8978 {
8979 const size_t n = raw.size();
8980 Array<Intersection> isects;
8981
8982 for (size_t i = 0; i < n; ++i)
8983 {
8984 const Point &a0 = raw(i);
8985 const Point &a1 = raw((i + 1) % n);
8986 const Segment sa(a0, a1);
8987
8988 for (size_t j = i + 2; j < n; ++j)
8989 {
8990 // Skip adjacent edges (they share a vertex).
8991 if (j == (i + n - 1) % n)
8992 continue;
8993 if (i == 0 && j == n - 1)
8994 continue;
8995
8996 const Point &b0 = raw(j);
8997 const Point &b1 = raw((j + 1) % n);
8998 const Segment sb(b0, b1);
8999
9000 if (not sa.intersects_properly_with(sb))
9001 continue;
9002
9003 const Point ip = sa.intersection_with(sb);
9004 const Geom_Number ai = edge_param(a0, a1, ip);
9005 const Geom_Number aj = edge_param(b0, b1, ip);
9006 isects.append({ip, i, j, ai, aj});
9007 }
9008 }
9009
9010 return isects;
9011 }
9012
9015 {
9016 for (size_t i = 1; i < idx.size(); ++i)
9017 {
9018 const size_t val = idx(i);
9019 const Geom_Number &key = keys(val);
9020 size_t j = i;
9021 while (j > 0 && keys(idx(j - 1)) > key)
9022 {
9023 idx(j) = idx(j - 1);
9024 --j;
9025 }
9026 idx(j) = val;
9027 }
9028 }
9029
9031 [[nodiscard]] static Array<AugVertex> build_augmented(const Array<Point> &raw,
9032 const Array<Intersection> &isects)
9033 {
9034 const size_t n = raw.size();
9035 const size_t m = isects.size();
9036
9037 // Position in the augmented list for each intersection occurrence.
9038 // Each intersection appears twice (once on each edge).
9039 Array<size_t> pos_i, pos_j;
9040 pos_i.reserve(m);
9041 pos_j.reserve(m);
9042 for (size_t k = 0; k < m; ++k)
9043 {
9044 pos_i.append(0);
9045 pos_j.append(0);
9046 }
9047
9048 Array<AugVertex> aug;
9049 aug.reserve(n + 2 * m);
9050
9051 for (size_t i = 0; i < n; ++i)
9052 {
9053 // Append original vertex.
9054 AugVertex v;
9055 v.pt = raw(i);
9056 aug.append(v);
9057
9058 // Collect intersections on this edge.
9059 Array<size_t> edge_isects;
9060 Array<Geom_Number> edge_alphas;
9061 for (size_t k = 0; k < m; ++k)
9062 {
9063 if (isects(k).edge_i == i)
9064 {
9065 edge_isects.append(k);
9066 edge_alphas.append(isects(k).alpha_i);
9067 }
9068 else if (isects(k).edge_j == i)
9069 {
9070 edge_isects.append(k);
9071 edge_alphas.append(isects(k).alpha_j);
9072 }
9073 }
9074
9075 if (edge_isects.is_empty())
9076 continue;
9077
9078 // Sort by alpha.
9079 Array<size_t> order;
9080 for (size_t p = 0; p < edge_isects.size(); ++p)
9081 order.append(p);
9082 sort_by_alpha(order, edge_alphas);
9083
9084 for (size_t p = 0; p < order.size(); ++p)
9085 {
9086 const size_t k = edge_isects(order(p));
9087 const size_t aug_idx = aug.size();
9088
9089 // Record position for partner linking.
9090 if (isects(k).edge_i == i)
9091 pos_i(k) = aug_idx;
9092 else
9093 pos_j(k) = aug_idx;
9094
9095 AugVertex iv;
9096 iv.pt = isects(k).pt;
9097 iv.is_intersection = true;
9098 iv.alpha = edge_alphas(order(p));
9099 aug.append(iv);
9100 }
9101 }
9102
9103 // Set partner links.
9104 for (size_t k = 0; k < m; ++k)
9105 {
9106 aug(pos_i(k)).partner = pos_j(k);
9107 aug(pos_j(k)).partner = pos_i(k);
9108 }
9109
9110 return aug;
9111 }
9112
9114 [[nodiscard]] static Polygon build_poly(const Array<Point> &pts)
9115 {
9116 Polygon p;
9117 for (size_t i = 0; i < pts.size(); ++i)
9118 p.add_vertex(pts(i));
9119 if (pts.size() >= 3)
9120 p.close();
9121 return p;
9122 }
9123
9131 {
9132 Array<Polygon> result;
9133 const size_t N = aug.size();
9134 const size_t safety = N * 2 + 10;
9135
9136 for (size_t s = 0; s < N; ++s)
9137 {
9138 if (not aug(s).is_intersection || aug(s).visited)
9139 continue;
9140
9141 // Trace one contour starting from intersection s.
9142 // Jump to partner first, then walk forward.
9143 Array<Point> boundary;
9144 size_t steps = 0;
9145
9146 aug(s).visited = true;
9147 if (aug(s).partner != SIZE_MAX)
9148 aug(aug(s).partner).visited = true;
9149
9150 // Jump to partner to enter the "other branch".
9151 size_t idx = (aug(s).partner != SIZE_MAX) ? aug(s).partner : s;
9152 const size_t entry = idx; // we'll loop until we return here
9153
9154 do
9155 {
9156 // Append current vertex and walk forward.
9157 boundary.append(aug(idx).pt);
9158 idx = (idx + 1) % N;
9159
9160 while (not aug(idx).is_intersection)
9161 {
9162 boundary.append(aug(idx).pt);
9163 idx = (idx + 1) % N;
9164 if (++steps > safety)
9165 goto done_contour;
9166 }
9167
9168 // At the next intersection — mark visited and jump to partner.
9169 aug(idx).visited = true;
9170 if (aug(idx).partner != SIZE_MAX)
9171 {
9172 aug(aug(idx).partner).visited = true;
9173 idx = aug(idx).partner;
9174 }
9175
9176 if (++steps > safety)
9177 break;
9178 } while (idx != entry);
9179
9180 done_contour:
9181 if (boundary.size() >= 3)
9182 {
9183 // Keep only CCW contours (positive signed area).
9184 if (const Geom_Number sa = GeomPolygonUtils::signed_double_area(boundary); sa > 0)
9185 result.append(build_poly(boundary));
9186 }
9187 }
9188
9189 return result;
9190 }
9191
9193 static Result cleanup(const Array<Point> &raw)
9194 {
9195 const auto isects = find_self_intersections(raw);
9196
9197 if (isects.is_empty())
9198 {
9199 // No self-intersections — check if the raw polygon is valid CCW.
9201 Result r;
9202 if (sa > 0 && raw.size() >= 3)
9203 r.polygons.append(build_poly(raw));
9204 return r;
9205 }
9206
9207 auto aug = build_augmented(raw, isects);
9208 Result r;
9209 r.polygons = extract_contours(aug);
9210 return r;
9211 }
9212};
9213
9214// ============================================================================
9215// Visibility Polygon
9216// ============================================================================
9217
9241{
9243 [[nodiscard]] static int angle_quadrant(const Geom_Number &dx, const Geom_Number &dy)
9244 {
9245 if (dx > 0 and dy >= 0)
9246 return 0;
9247 if (dx <= 0 and dy > 0)
9248 return 1;
9249 if (dx < 0 and dy <= 0)
9250 return 2;
9251 return 3; // dx >= 0 and dy < 0
9252 }
9253
9255 [[nodiscard]] static bool angle_less(const Point &q, const Point &a, const Point &b)
9256 {
9257 const Geom_Number dax = a.get_x() - q.get_x();
9258 const Geom_Number day = a.get_y() - q.get_y();
9259 const Geom_Number dbx = b.get_x() - q.get_x();
9260 const Geom_Number dby = b.get_y() - q.get_y();
9261
9262 const int qa = angle_quadrant(dax, day);
9263 const int qb = angle_quadrant(dbx, dby);
9264 if (qa != qb)
9265 return qa < qb;
9266
9267 // Same quadrant: cross product. Positive = a is before b (CCW).
9268 if (const Geom_Number cross = dax * dby - day * dbx; cross != 0)
9269 return cross > 0;
9270
9271 // Same angle: closer point first.
9272 return dax * dax + day * day < (dbx * dbx + dby * dby);
9273 }
9274
9277 [[nodiscard]] static Geom_Number ray_param(const Point &q,
9278 const Point &dir,
9279 const Point &e0,
9280 const Point &e1)
9281 {
9282 const Geom_Number rdx = dir.get_x() - q.get_x();
9283 const Geom_Number rdy = dir.get_y() - q.get_y();
9284 const Geom_Number edx = e1.get_x() - e0.get_x();
9285 const Geom_Number edy = e1.get_y() - e0.get_y();
9286 const Geom_Number denom = rdx * edy - rdy * edx;
9287 if (denom == 0)
9288 return {-1};
9289
9290 const Geom_Number dx = e0.get_x() - q.get_x();
9291 const Geom_Number dy = e0.get_y() - q.get_y();
9292 const Geom_Number t = (dx * edy - dy * edx) / denom;
9293 const Geom_Number s = (dx * rdy - dy * rdx) / denom;
9294 if (s < 0 or s > 1 or t < 0)
9295 return {-1};
9296 return t;
9297 }
9298
9300 [[nodiscard]] static Point ray_edge_hit(const Point &q,
9301 const Point &dir,
9302 const Point &e0,
9303 const Point &e1)
9304 {
9305 const Geom_Number t = ray_param(q, dir, e0, e1);
9306 const Geom_Number rdx = dir.get_x() - q.get_x();
9307 const Geom_Number rdy = dir.get_y() - q.get_y();
9308 return {q.get_x() + t * rdx, q.get_y() + t * rdy};
9309 }
9310
9320 {
9321 struct EdgeKey
9322 {
9324 size_t edge;
9325 };
9326
9328 {
9329 bool operator () (const EdgeKey &a, const EdgeKey &b) const
9330 {
9331 if (a.t != b.t)
9332 return a.t < b.t;
9333 return a.edge < b.edge;
9334 }
9335 };
9336
9338 Array<Geom_Number> params_; // edge → ray_param at insertion time
9339 Array<bool> in_tree_; // edge → currently in tree
9341 const size_t n_;
9343
9344 public:
9345 EdgeStatusTree(const Array<Point> &verts, const size_t n, const Point &query)
9346 : verts_(verts), n_(n), query_(query)
9347 {
9348 for (size_t i = 0; i < n; ++i)
9349 {
9350 params_.append(Geom_Number(-1));
9351 in_tree_.append(false);
9352 }
9353 }
9354
9355 void insert(const size_t edge, const Point &dir)
9356 {
9357 if (in_tree_(edge))
9358 return;
9359
9360 const Geom_Number t = ray_param(query_, dir, verts_(edge), verts_((edge + 1) % n_));
9361 params_(edge) = t;
9362 in_tree_(edge) = true;
9363 tree_.insert(EdgeKey{t, edge});
9364 }
9365
9366 void erase(const size_t edge)
9367 {
9368 if (not in_tree_(edge))
9369 return;
9370
9371 tree_.remove(EdgeKey{params_(edge), edge});
9372 in_tree_(edge) = false;
9373 }
9374
9377 [[nodiscard]] size_t min() const
9378 {
9379 if (tree_.is_empty())
9380 return n_;
9381 return tree_.min().edge;
9382 }
9383
9384 [[nodiscard]] bool contains(const size_t edge) const
9385 {
9386 return in_tree_(edge);
9387 }
9388
9389 [[nodiscard]] bool is_empty() const
9390 {
9391 return tree_.is_empty();
9392 }
9393 };
9394
9395public:
9403 [[nodiscard]] Polygon operator () (const Polygon &polygon, const Point &query) const
9404 {
9405 ah_domain_error_if(not polygon.is_closed()) << "Polygon must be closed";
9406 ah_domain_error_if(polygon.size() < 3) << "Polygon must have >= 3 vertices";
9408 << "Query point must be strictly inside the polygon";
9409
9410 // Extract vertices.
9411 Array<Point> verts;
9412 for (Polygon::Vertex_Iterator it(polygon); it.has_curr(); it.next_ne())
9413 verts.append(it.get_current_vertex());
9414 const size_t n = verts.size();
9415
9416 // Sort vertex indices by angle from query.
9417 Array<size_t> order;
9418 order.reserve(n);
9419 for (size_t i = 0; i < n; ++i)
9420 order.append(i);
9421 quicksort_op(order, [&](size_t a, size_t b)
9422 {
9423 return angle_less(query, verts(a), verts(b));
9424 });
9425
9426 // Determine which edges cross the initial ray (wrapping edges).
9427 // Their angular span straddles 0°, so their start/end events must be
9428 // swapped relative to non-wrapping edges.
9429 const Point init_dir(query.get_x() + 1, query.get_y());
9430 Array<bool> wrapping;
9431 wrapping.reserve(n);
9432 for (size_t ei = 0; ei < n; ++ei)
9433 {
9434 const Geom_Number t = ray_param(query, init_dir, verts(ei), verts((ei + 1) % n));
9435 wrapping.append(t > 0);
9436 }
9437
9438 // Build edge event tables: for each vertex, which edges start/end there.
9439 // Edge i goes from verts(i) to verts((i+1)%n).
9440 // For non-wrapping edges: insert at the smaller-angle vertex, remove at
9441 // the larger-angle vertex (normal sweep order).
9442 // For wrapping edges (already in the initial status): remove at the
9443 // smaller-angle vertex (ray exits their span), insert at the
9444 // larger-angle vertex (ray re-enters their span).
9445 Array<DynList<size_t>> starts, ends;
9446 starts.reserve(n);
9447 ends.reserve(n);
9448 for (size_t i = 0; i < n; ++i)
9449 starts.append(DynList<size_t>());
9450 for (size_t i = 0; i < n; ++i)
9451 ends.append(DynList<size_t>());
9452
9453 for (size_t ei = 0; ei < n; ++ei)
9454 {
9455 const size_t a = ei, b = (ei + 1) % n;
9456 const bool a_less = angle_less(query, verts(a), verts(b));
9457 const size_t small_v = a_less ? a : b;
9458 const size_t large_v = a_less ? b : a;
9459
9460 if (wrapping(ei))
9461 {
9462 ends(small_v).append(ei); // remove when ray exits span
9463 starts(large_v).append(ei); // re-insert when ray re-enters
9464 }
9465 else
9466 {
9467 starts(small_v).append(ei); // insert when ray enters span
9468 ends(large_v).append(ei); // remove when ray exits span
9469 }
9470 }
9471
9472 // Initialize status with wrapping edges.
9473 EdgeStatusTree status(verts, n, query);
9474 for (size_t ei = 0; ei < n; ++ei)
9475 if (wrapping(ei))
9476 status.insert(ei, init_dir);
9477
9478 // Build visibility polygon.
9479 Array<Point> vis_pts;
9480
9481 for (size_t oi = 0; oi < n; ++oi)
9482 {
9483 const size_t vi = order(oi);
9484 const Point &v = verts(vi);
9485 const Point dir = v; // ray from query toward v
9486
9487 // Nearest edge BEFORE processing events at this vertex.
9488 const size_t prev_near = status.min();
9489
9490 // Remove ending edges.
9491 for (auto it = ends(vi).get_it(); it.has_curr(); it.next_ne())
9492 status.erase(it.get_curr());
9493
9494 // Insert starting edges.
9495 for (auto it = starts(vi).get_it(); it.has_curr(); it.next_ne())
9496 status.insert(it.get_curr(), dir);
9497
9498 // Nearest edge AFTER processing events.
9499 const size_t curr_near = status.min();
9500
9501 // Determine visibility.
9502 bool v_is_on_edge = false;
9503 if (prev_near < n)
9504 {
9505 const size_t ea = prev_near, eb = (prev_near + 1) % n;
9506 if (vi == ea or vi == eb)
9507 v_is_on_edge = true;
9508 }
9509 if (curr_near < n and not v_is_on_edge)
9510 {
9511 const size_t ea = curr_near, eb = (curr_near + 1) % n;
9512 if (vi == ea or vi == eb)
9513 v_is_on_edge = true;
9514 }
9515
9516 if (v_is_on_edge)
9517 {
9518 // Vertex is on the nearest edge — directly visible.
9519 vis_pts.append(v);
9520 }
9521 else if (prev_near != curr_near)
9522 {
9523 // Nearest edge changed — add intersection with old and new.
9524 if (prev_near < n)
9525 vis_pts.append(ray_edge_hit(query, dir, verts(prev_near), verts((prev_near + 1) % n)));
9526 vis_pts.append(v);
9527 if (curr_near < n)
9528 vis_pts.append(ray_edge_hit(query, dir, verts(curr_near), verts((curr_near + 1) % n)));
9529 }
9530 }
9531
9532 // Remove duplicate consecutive points.
9533 Polygon result;
9534 for (size_t i = 0; i < vis_pts.size(); ++i)
9535 {
9536 if (i > 0 and vis_pts(i) == vis_pts(i - 1))
9537 continue;
9538 result.add_vertex(vis_pts(i));
9539 }
9540 if (result.size() >= 3)
9541 {
9542 // Remove last if the same as first.
9543 Array<Point> rv;
9544 for (Polygon::Vertex_Iterator it(result); it.has_curr(); it.next_ne())
9545 rv.append(it.get_current_vertex());
9546 if (rv.size() >= 2 and rv(0) == rv(rv.size() - 1))
9547 {
9548 Polygon cleaned;
9549 for (size_t i = 0; i + 1 < rv.size(); ++i)
9550 cleaned.add_vertex(rv(i));
9551 if (cleaned.size() >= 3)
9552 cleaned.close();
9553 return cleaned;
9554 }
9555 result.close();
9556 }
9557 return result;
9558 }
9559};
9560
9561// ============================================================================
9562// Shortest Path in Simple Polygon (Lee-Preparata Funnel)
9563// ============================================================================
9564
9589{
9590 static constexpr size_t NONE = ~static_cast<size_t>(0);
9591
9592 struct ITri
9593 {
9594 size_t v[3];
9595 size_t adj[3]; // adj[i] = neighbour sharing edge opposite v[i], or NONE
9596 };
9597
9599 [[nodiscard]] static size_t find_index(const Array<Point> &pts, const Point &p)
9600 {
9601 for (size_t i = 0; i < pts.size(); ++i)
9602 if (pts(i) == p)
9603 return i;
9604 return NONE;
9605 }
9606
9608 [[nodiscard]] static Array<ITri> build_tris(const Array<Point> &pts, const DynList<Triangle> &tl)
9609 {
9610 // Convert to indexed form.
9611 Array<ITri> tris;
9612 for (auto it = tl.get_it(); it.has_curr(); it.next_ne())
9613 {
9614 const Triangle &t = it.get_curr();
9615 ITri ti{};
9616 ti.v[0] = find_index(pts, t.get_p1());
9617 ti.v[1] = find_index(pts, t.get_p2());
9618 ti.v[2] = find_index(pts, t.get_p3());
9619 ti.adj[0] = ti.adj[1] = ti.adj[2] = NONE;
9620 tris.append(ti);
9621 }
9622
9623 // Build adjacency via an edge map.
9624 // Key: (min_idx, max_idx), Value: (triangle_index, local_edge_index)
9625 struct EdgeKey
9626 {
9627 size_t u, v;
9628 };
9629
9630 struct CmpEdge
9631 {
9632 bool operator () (const EdgeKey &a, const EdgeKey &b) const
9633 {
9634 if (a.u != b.u)
9635 return a.u < b.u;
9636 return a.v < b.v;
9637 }
9638 };
9639
9640 struct EdgeVal
9641 {
9642 size_t tri;
9643 size_t local;
9644 };
9645
9647
9648 // We need a separate map. Use parallel arrays since DynSetTree doesn't
9649 // store mapped values. Use a simpler approach: flat array scan.
9650 struct EdgeEntry
9651 {
9652 size_t u, v, tri, local;
9653 };
9654 Array<EdgeEntry> edges;
9655 edges.reserve(tris.size() * 3);
9656
9657 for (size_t ti = 0; ti < tris.size(); ++ti)
9658 for (int e = 0; e < 3; ++e)
9659 {
9660 size_t u = tris(ti).v[(e + 1) % 3];
9661 size_t v = tris(ti).v[(e + 2) % 3];
9662 if (u > v)
9663 {
9664 const size_t tmp = u;
9665 u = v;
9666 v = tmp;
9667 }
9668 edges.append(EdgeEntry{u, v, ti, size_t(e)});
9669 }
9670
9671 // Sort edges and find matching pairs.
9672 quicksort_op(edges, [](const EdgeEntry &a, const EdgeEntry &b)
9673 {
9674 if (a.u != b.u)
9675 return a.u < b.u;
9676 if (a.v != b.v)
9677 return a.v < b.v;
9678 return a.tri < b.tri;
9679 });
9680
9681 for (size_t i = 0; i + 1 < edges.size(); ++i)
9682 if (edges(i).u == edges(i + 1).u and edges(i).v == edges(i + 1).v)
9683 {
9684 const size_t t1 = edges(i).tri, l1 = edges(i).local;
9685 const size_t t2 = edges(i + 1).tri, l2 = edges(i + 1).local;
9686 tris(t1).adj[l1] = t2;
9687 tris(t2).adj[l2] = t1;
9688 ++i; // skip the matched pair
9689 }
9690
9691 return tris;
9692 }
9693
9695 [[nodiscard]] static bool point_in_triangle(const Array<Point> &pts, const ITri &t, const Point &p)
9696 {
9697 const Orientation o0 = orientation(pts(t.v[0]), pts(t.v[1]), p);
9698 const Orientation o1 = orientation(pts(t.v[1]), pts(t.v[2]), p);
9699 const Orientation o2 = orientation(pts(t.v[2]), pts(t.v[0]), p);
9700 const bool has_cw = o0 == Orientation::CW or o1 == Orientation::CW or o2 == Orientation::CW;
9701 const bool has_ccw = o0 == Orientation::CCW or o1 == Orientation::CCW or o2 == Orientation::CCW;
9702 return not (has_cw and has_ccw);
9703 }
9704
9706 [[nodiscard]] static size_t find_tri(const Array<Point> &pts, const Array<ITri> &tris, const Point &p)
9707 {
9708 for (size_t i = 0; i < tris.size(); ++i)
9709 if (point_in_triangle(pts, tris(i), p))
9710 return i;
9711 return NONE;
9712 }
9713
9715 [[nodiscard]] static Array<size_t> find_sleeve(const Array<ITri> &tris,
9716 const size_t src,
9717 const size_t dst)
9718 {
9719 if (src == dst)
9720 {
9721 Array<size_t> s;
9722 s.append(src);
9723 return s;
9724 }
9725
9726 Array<size_t> parent;
9727 parent.reserve(tris.size());
9728 for (size_t i = 0; i < tris.size(); ++i)
9729 parent.append(NONE);
9730 parent(src) = src; // sentinel
9731
9732 DynList<size_t> queue;
9733 queue.append(src);
9734
9735 while (not queue.is_empty())
9736 {
9737 const size_t cur = queue.remove_first();
9738 if (cur == dst)
9739 break;
9740 for (unsigned long nb : tris(cur).adj)
9741 if (nb != NONE and parent(nb) == NONE)
9742 {
9743 parent(nb) = cur;
9744 queue.append(nb);
9745 }
9746 }
9747
9748 // Reconstruct path.
9749 Array<size_t> path;
9750 for (size_t cur = dst; cur != src; cur = parent(cur))
9751 path.append(cur);
9752 path.append(src);
9753
9754 // Reverse.
9755 for (size_t i = 0; i < path.size() / 2; ++i)
9756 {
9757 const size_t tmp = path(i);
9758 path(i) = path(path.size() - 1 - i);
9759 path(path.size() - 1 - i) = tmp;
9760 }
9761 return path;
9762 }
9763
9765 [[nodiscard]] static Geom_Number cross(const Point &a, const Point &b, const Point &c)
9766 {
9767 return (b.get_x() - a.get_x()) * (c.get_y() - a.get_y()) -
9768 (b.get_y() - a.get_y()) * (c.get_x() - a.get_x());
9769 }
9770
9771public:
9780 [[nodiscard]] DynList<Point> operator () (const Polygon &polygon,
9781 const Point &source,
9782 const Point &target) const
9783 {
9784 ah_domain_error_if(not polygon.is_closed()) << "Polygon must be closed";
9785 ah_domain_error_if(polygon.size() < 3) << "Polygon must have >= 3 vertices";
9787 << "Source must be inside the polygon";
9789 << "Target must be inside the polygon";
9790
9791 DynList<Point> result;
9792 if (source == target)
9793 {
9794 result.append(source);
9795 return result;
9796 }
9797
9798 // Check direct line of sight.
9799 {
9800 const Segment seg(source, target);
9801 bool blocked = false;
9802 for (Polygon::Segment_Iterator it(polygon); it.has_curr() and not blocked; it.next_ne())
9803 if (const Segment edge = it.get_current_segment(); seg.intersects_properly_with(edge))
9804 blocked = true;
9805 if (not blocked)
9806 {
9807 result.append(source);
9808 result.append(target);
9809 return result;
9810 }
9811 }
9812
9813 // Extract vertices.
9814 Array<Point> pts;
9815 for (Polygon::Vertex_Iterator it(polygon); it.has_curr(); it.next_ne())
9816 pts.append(it.get_current_vertex());
9817
9818 // Triangulate.
9819 CuttingEarsTriangulation triangulator;
9820 DynList<Triangle> tri_list = triangulator(polygon);
9821
9822 ah_domain_error_if(tri_list.is_empty()) << "Triangulation failed";
9823
9824 // Build indexed triangulation with adjacency.
9825 Array<ITri> tris = build_tris(pts, tri_list);
9826
9827 // Locate source and target triangles.
9828 const size_t src_t = find_tri(pts, tris, source);
9829 const size_t dst_t = find_tri(pts, tris, target);
9830
9831 ah_domain_error_if(src_t == NONE) << "Could not locate source in triangulation";
9832 ah_domain_error_if(dst_t == NONE) << "Could not locate target in triangulation";
9833
9834 // Find sleeve.
9835 Array<size_t> sleeve = find_sleeve(tris, src_t, dst_t);
9836
9837 if (sleeve.size() <= 1)
9838 {
9839 result.append(source);
9840 result.append(target);
9841 return result;
9842 }
9843
9844 // ----------------------------------------------------------------
9845 // Simple Stupid Funnel Algorithm (Mononen / Lee-Preparata).
9846 //
9847 // Build a portal list from the sleeve diagonals, then walk it
9848 // maintaining a funnel (apex, left boundary, right boundary).
9849 // ----------------------------------------------------------------
9850
9851 // A portal is a pair (left, right) as seen when walking from source
9852 // toward target. Portal 0 = (source, source), last = (target, target).
9853 struct Portal
9854 {
9855 Point left;
9856 Point right;
9857 };
9858 Array<Portal> portals;
9859 portals.append(Portal{source, source});
9860
9861 // For each sleeve diagonal, find shared vertices and the "opposite"
9862 // vertex in the current triangle (the one NOT shared with the next).
9863 // Orient the portal using cross(V_prev, s0, s1):
9864 // cross < 0 → left = s0, right = s1
9865 // cross > 0 → left = s1, right = s0
9866 // This is robust regardless of triangulation order.
9867
9868 for (size_t i = 0; i + 1 < sleeve.size(); ++i)
9869 {
9870 size_t s0 = 0, s1 = 0;
9871 size_t v_prev = 0;
9872 {
9873 int sc = 0;
9874 bool found[3] = {false, false, false};
9875 for (int a = 0; a < 3; ++a)
9876 for (unsigned long b : tris(sleeve(i + 1)).v)
9877 if (tris(sleeve(i)).v[a] == b)
9878 {
9879 found[a] = true;
9880 break;
9881 }
9882
9883 for (int a = 0; a < 3; ++a)
9884 {
9885 if (found[a])
9886 {
9887 if (sc == 0)
9888 s0 = tris(sleeve(i)).v[a];
9889 else
9890 s1 = tris(sleeve(i)).v[a];
9891 ++sc;
9892 }
9893 else
9894 v_prev = tris(sleeve(i)).v[a];
9895 }
9896 }
9897
9898 const Geom_Number c = cross(pts(v_prev), pts(s0), pts(s1));
9899 if (c < 0)
9900 portals.append(Portal{pts(s0), pts(s1)});
9901 else
9902 portals.append(Portal{pts(s1), pts(s0)});
9903 }
9904
9905 portals.append(Portal{target, target});
9906
9907 // --- SSFA core ---
9908 Point apex = source;
9909 Point fl = source; // funnel left boundary
9910 Point fr = source; // funnel right boundary
9911 size_t ai = 0, li = 0, ri = 0;
9912
9913 result.append(source);
9914
9915 for (size_t i = 1; i < portals.size(); ++i)
9916 {
9917 const Point &pr = portals(i).right;
9918 const Point &pl = portals(i).left;
9919
9920 // --- tighten right boundary ---
9921 if (cross(apex, fr, pr) >= 0)
9922 {
9923 if (apex == fr or cross(apex, fl, pr) < 0)
9924 {
9925 fr = pr;
9926 ri = i;
9927 }
9928 else
9929 {
9930 // Right crossed over left → left becomes new apex.
9931 result.append(fl);
9932 apex = fl;
9933 ai = li;
9934 fl = apex;
9935 fr = apex;
9936 li = ai;
9937 ri = ai;
9938 i = ai; // loop increments to ai+1
9939 continue;
9940 }
9941 }
9942
9943 // --- tighten left boundary ---
9944 if (cross(apex, fl, pl) <= 0)
9945 {
9946 if (apex == fl or cross(apex, fr, pl) > 0)
9947 {
9948 fl = pl;
9949 li = i;
9950 }
9951 else
9952 {
9953 // Left crossed over right → right becomes new apex.
9954 result.append(fr);
9955 apex = fr;
9956 ai = ri;
9957 fl = apex;
9958 fr = apex;
9959 li = ai;
9960 ri = ai;
9961 i = ai;
9962 continue;
9963 }
9964 }
9965 }
9966
9967 if (result.get_last() != target)
9968 result.append(target);
9969 return result;
9970 }
9971};
9972
9973// ============================================================================
9974// Segment Arrangement — Full Planar Subdivision
9975// ============================================================================
9976
10003{
10004public:
10008 struct ArrEdge
10009 {
10010 size_t src;
10011 size_t tgt;
10012 size_t seg_idx;
10013 };
10014
10018 struct ArrFace
10019 {
10022 };
10023
10033
10034private:
10035 static constexpr size_t NONE = ~static_cast<size_t>(0);
10036
10038 [[nodiscard]] static bool pt_less(const Point &a, const Point &b)
10039 {
10040 if (a.get_x() != b.get_x())
10041 return a.get_x() < b.get_x();
10042 return a.get_y() < b.get_y();
10043 }
10044
10046 [[nodiscard]] static size_t find_vertex(const Array<Point> &verts, const Point &p)
10047 {
10048 size_t lo = 0, hi = verts.size();
10049 while (lo < hi)
10050 if (const size_t mid = lo + (hi - lo) / 2; pt_less(verts(mid), p))
10051 lo = mid + 1;
10052 else if (pt_less(p, verts(mid)))
10053 hi = mid;
10054 else
10055 return mid;
10056 return NONE;
10057 }
10058
10060 [[nodiscard]] static int angle_quad(const Geom_Number &dx, const Geom_Number &dy)
10061 {
10062 if (dx > 0 and dy >= 0)
10063 return 0;
10064 if (dx <= 0 and dy > 0)
10065 return 1;
10066 if (dx < 0 and dy <= 0)
10067 return 2;
10068 return 3;
10069 }
10070
10073 [[nodiscard]] static bool angle_lt(const Geom_Number &dx1,
10074 const Geom_Number &dy1,
10075 const Geom_Number &dx2,
10076 const Geom_Number &dy2)
10077 {
10078 const int q1 = angle_quad(dx1, dy1);
10079 const int q2 = angle_quad(dx2, dy2);
10080 if (q1 != q2)
10081 return q1 < q2;
10082 if (const Geom_Number cross = dx1 * dy2 - dy1 * dx2; cross != 0)
10083 return cross > 0;
10084 return dx1 * dx1 + dy1 * dy1 < (dx2 * dx2 + dy2 * dy2);
10085 }
10086
10091 {
10092 size_t origin;
10093 size_t target;
10094 size_t twin;
10095 size_t next;
10096 size_t face;
10097 size_t edge_idx;
10098 };
10099
10100public:
10107 [[nodiscard]] Result operator () (const Array<Segment> &segments) const
10108 {
10109 Result ret;
10110 const size_t n = segments.size();
10111
10112 if (n == 0)
10113 {
10114 // Single unbounded face.
10115 ArrFace uf;
10116 uf.unbounded = true;
10117 ret.faces.append(uf);
10118 return ret;
10119 }
10120
10121 // --- Step 1: Compute all intersections. ---
10123 auto inters = sweep(segments);
10124
10125 // --- Step 2: Build a deduplicated vertex set. ---
10126 // Collect all endpoints + intersection points.
10127 Array<Point> all_pts;
10128 all_pts.reserve(2 * n + inters.size());
10129 for (size_t i = 0; i < n; ++i)
10130 {
10131 all_pts.append(segments(i).get_src_point());
10132 all_pts.append(segments(i).get_tgt_point());
10133 }
10134 for (size_t i = 0; i < inters.size(); ++i)
10135 all_pts.append(inters(i).point);
10136
10137 // Sort lexicographically.
10138 quicksort_op(all_pts, [](const Point &a, const Point &b)
10139 {
10140 return pt_less(a, b);
10141 });
10142
10143 // Deduplicate.
10144 ret.vertices.reserve(all_pts.size());
10145 for (size_t i = 0; i < all_pts.size(); ++i)
10146 if (ret.vertices.is_empty() or ret.vertices.get_last() != all_pts(i))
10147 ret.vertices.append(all_pts(i));
10148
10149 // --- Step 3: Split segments into sub-edges. ---
10150 // For each segment, collect its vertices and sort along the segment.
10151 for (size_t si = 0; si < n; ++si)
10152 {
10153 const Point &sp = segments(si).get_src_point();
10154 const Point &tp = segments(si).get_tgt_point();
10155
10156 // Collect vertices on this segment.
10157 Array<size_t> on_seg;
10158 on_seg.append(find_vertex(ret.vertices, sp));
10159 on_seg.append(find_vertex(ret.vertices, tp));
10160
10161 // Add intersection points involving this segment.
10162 for (size_t ki = 0; ki < inters.size(); ++ki)
10163 if (inters(ki).seg_i == si or inters(ki).seg_j == si)
10164 if (const size_t vi = find_vertex(ret.vertices, inters(ki).point); vi != NONE)
10165 on_seg.append(vi);
10166
10167 // Deduplicate.
10168 quicksort_op(on_seg, [](const size_t a, const size_t b)
10169 {
10170 return a < b;
10171 });
10172 {
10173 Array<size_t> uniq;
10174 for (size_t i = 0; i < on_seg.size(); ++i)
10175 if (uniq.is_empty() or uniq.get_last() != on_seg(i))
10176 uniq.append(on_seg(i));
10177 on_seg = uniq;
10178 }
10179
10180 // Sort by parametric position along the segment.
10181 // Use the primary direction (x for non-vertical, y for vertical).
10182 const bool vertical = (sp.get_x() == tp.get_x());
10183 const auto &verts = ret.vertices;
10184 if (vertical)
10185 quicksort_op(on_seg, [&](const size_t a, const size_t b)
10186 {
10187 return verts(a).get_y() < verts(b).get_y();
10188 });
10189 else
10190 quicksort_op(on_seg, [&](const size_t a, const size_t b)
10191 {
10192 return verts(a).get_x() < verts(b).get_x();
10193 });
10194
10195 // Create edges between consecutive vertices.
10196 for (size_t i = 0; i + 1 < on_seg.size(); ++i)
10197 ret.edges.append(ArrEdge{on_seg(i), on_seg(i + 1), si});
10198 }
10199
10200 // --- Step 4 + 5: Build half-edges, compute next pointers, find faces. ---
10201 const size_t ne = ret.edges.size();
10202 const size_t nhe = 2 * ne;
10203 const size_t nv = ret.vertices.size();
10204
10205 if (ne == 0)
10206 {
10207 // Only isolated vertices, no edges → one unbounded face.
10208 ArrFace uf;
10209 uf.unbounded = true;
10210 ret.faces.append(uf);
10211 return ret;
10212 }
10213
10214 // Create half-edges: for edge i, half-edge 2*i goes src→tgt,
10215 // half-edge 2*i+1 goes tgt→src.
10216 Array<HalfEdge> he;
10217 he.reserve(nhe);
10218 for (size_t i = 0; i < ne; ++i)
10219 {
10220 he.append(HalfEdge{ret.edges(i).src, ret.edges(i).tgt, 2 * i + 1, NONE, NONE, i});
10221 he.append(HalfEdge{ret.edges(i).tgt, ret.edges(i).src, 2 * i, NONE, NONE, i});
10222 }
10223
10224 // Build incidence: for each vertex, list of outgoing half-edge indices.
10226 inc.reserve(nv);
10227 for (size_t i = 0; i < nv; ++i)
10228 inc.append(Array<size_t>());
10229 for (size_t h = 0; h < nhe; ++h)
10230 inc(he(h).origin).append(h);
10231
10232 // Sort outgoing half-edges at each vertex by angle.
10233 const auto &verts = ret.vertices;
10234 for (size_t v = 0; v < nv; ++v)
10235 {
10236 if (inc(v).size() <= 1)
10237 continue;
10238 quicksort_op(inc(v), [&](size_t a, size_t b)
10239 {
10240 const Geom_Number dxa = verts(he(a).target).get_x() - verts(v).get_x();
10241 const Geom_Number dya = verts(he(a).target).get_y() - verts(v).get_y();
10242 const Geom_Number dxb = verts(he(b).target).get_x() - verts(v).get_x();
10243 const Geom_Number dyb = verts(he(b).target).get_y() - verts(v).get_y();
10244 return angle_lt(dxa, dya, dxb, dyb);
10245 });
10246 }
10247
10248 // Compute "next" pointers.
10249 // For half-edge h = (u→v), the next half-edge around the face is:
10250 // at vertex v, take the twin of h (which is v→u), find its position
10251 // in the sorted incidence list of v, go one step CW (previous in CCW
10252 // order) → that's the next half-edge of the face.
10253 //
10254 // Equivalently: next(h) where h = u→v:
10255 // twin(h) = v→u. Find twin(h) in inc(v). The previous entry in
10256 // inc(v) (wrapping) is the next half-edge of the face.
10257 for (size_t v = 0; v < nv; ++v)
10258 {
10259 const auto &list = inc(v);
10260 const size_t sz = list.size();
10261 if (sz == 0)
10262 continue;
10263
10264 for (size_t i = 0; i < sz; ++i)
10265 {
10266 // Half-edge list(i) leaves v. Its twin arrives at v.
10267 // The twin is the "incoming" half-edge. The face's "next"
10268 // after the twin is the one that comes just before list(i)
10269 // in the CCW angular order, i.e. the one CW from it.
10270 // So: next(twin(list(i))) = list((i+1) % sz)
10271 // wrong — let me re-derive.
10272 //
10273 // We have inc(v) sorted CCW: h0, h1, ..., h_{k-1} (outgoing).
10274 // For outgoing h_i (= v → t_i), twin(h_i) = t_i → v (incoming).
10275 // The face containing twin(h_i) continues with the next outgoing
10276 // half-edge at v going CW from the incoming direction.
10277 //
10278 // Incoming direction of twin(h_i) at v: from t_i toward v.
10279 // This is the reverse of h_i's outgoing direction.
10280 // In the CCW list, h_i is at position i. The CW-next after
10281 // the reversed direction of h_i corresponds to h_{(i-1+k)%k}.
10282 //
10283 // So: next(twin(h_i)) = h_{(i-1+k) % k}.
10284
10285 const size_t prev = (i == 0) ? sz - 1 : i - 1;
10286 he(he(list(i)).twin).next = list(prev);
10287 }
10288 }
10289
10290 // --- Face traversal ---
10291 Array<bool> visited;
10292 visited.reserve(nhe);
10293 for (size_t i = 0; i < nhe; ++i)
10294 visited.append(false);
10295
10296 for (size_t h = 0; h < nhe; ++h)
10297 {
10298 if (visited(h))
10299 continue;
10300
10301 ArrFace face;
10302 face.unbounded = false;
10303
10304 // Trace the face boundary.
10305 size_t cur = h;
10306 Geom_Number signed_area = 0;
10307 do
10308 {
10309 visited(cur) = true;
10310 face.boundary.append(he(cur).origin);
10311
10312 // Accumulate signed area (shoelace).
10313 const Point &p1 = verts(he(cur).origin);
10314 const Point &p2 = verts(he(cur).target);
10315 signed_area += p1.get_x() * p2.get_y() - p2.get_x() * p1.get_y();
10316
10317 cur = he(cur).next;
10318 } while (cur != h and cur != NONE);
10319
10320 // CW winding (negative area) → unbounded face.
10321 if (signed_area < 0)
10322 face.unbounded = true;
10323
10324 ret.faces.append(face);
10325 }
10326
10327 // Ensure exactly one unbounded face is marked.
10328 // If none was found (e.g. all half-edges form CCW cycles, which
10329 // happens when all segments are isolated non-intersecting ones),
10330 // mark the face with the largest absolute signed area as unbounded.
10331 {
10332 bool has_ub = false;
10333 for (size_t i = 0; i < ret.faces.size(); ++i)
10334 if (ret.faces(i).unbounded)
10335 {
10336 has_ub = true;
10337 break;
10338 }
10339 if (not has_ub and not ret.faces.is_empty())
10340 ret.faces(0).unbounded = true;
10341 }
10342
10343 return ret;
10344 }
10345};
10346
10347// ============================================================================
10348// Alpha Shapes — Generalization of Convex Hull
10349// ============================================================================
10350
10384{
10385public:
10396
10407 [[nodiscard]] Result operator () (const DynList<Point> &points, const Geom_Number &alpha_squared) const
10408 {
10409 constexpr DelaunayTriangulationBowyerWatson delaunay;
10410 auto [sites, triangles] = delaunay(points);
10411
10412 Result ret;
10413 ret.sites = sites;
10414
10415 if (triangles.size() == 0)
10416 return ret;
10417
10418 // Filter triangles by circumradius².
10419 Array<bool> kept;
10420 kept.reserve(triangles.size());
10421 for (size_t t = 0; t < triangles.size(); ++t)
10422 {
10423 const auto &tri = triangles(t);
10424 const Point &a = sites(tri.i);
10425 const Point &b = sites(tri.j);
10426 const Point &c = sites(tri.k);
10427
10428 // Circumradius² = (|AB|²|BC|²|CA|²) / (16 * area²)
10429 const Geom_Number ab2 = a.distance_squared_to(b);
10430 const Geom_Number bc2 = b.distance_squared_to(c);
10431 const Geom_Number ca2 = c.distance_squared_to(a);
10432 const Geom_Number area2x = area_of_parallelogram(a, b, c);
10433 const Geom_Number four_area_sq = area2x * area2x;
10434
10435 // circumradius² = ab2 * bc2 * ca2 / (4 * four_area_sq)
10436 // Compare: ab2 * bc2 * ca2 ≤ alpha_squared * 4 * four_area_sq
10437 const bool pass = ab2 * bc2 * ca2 <= alpha_squared * four_area_sq * 4;
10438 kept.append(pass);
10439 if (pass)
10440 ret.triangles.append(tri);
10441 }
10442
10443 // Extract boundary edges: edges appearing in exactly one kept triangle.
10444 // Use a simple count map via sorted edge keys.
10448 struct EdgeKey
10449 {
10450 size_t u, v;
10451
10453 bool operator == (const EdgeKey &o) const
10454 {
10455 return u == o.u and v == o.v;
10456 }
10457
10458 bool operator < (const EdgeKey &o) const
10459 {
10460 return u < o.u or (u == o.u and v < o.v);
10461 }
10462 };
10463
10464 auto make_key = [](const size_t a, const size_t b) -> EdgeKey
10465 {
10466 return a < b ? EdgeKey{a, b} : EdgeKey{b, a};
10467 };
10468
10469 Array<EdgeKey> all_edges;
10470 all_edges.reserve(ret.triangles.size() * 3);
10471 for (size_t t = 0; t < ret.triangles.size(); ++t)
10472 {
10473 const auto &[i, j, k] = ret.triangles(t);
10474 all_edges.append(make_key(i, j));
10475 all_edges.append(make_key(j, k));
10476 all_edges.append(make_key(k, i));
10477 }
10478
10479 quicksort_op(all_edges, [](const EdgeKey &a, const EdgeKey &b)
10480 {
10481 return a < b;
10482 });
10483
10484 for (size_t i = 0; i < all_edges.size();)
10485 {
10486 size_t j = i + 1;
10487 while (j < all_edges.size() and all_edges(j) == all_edges(i))
10488 ++j;
10489 if (j - i == 1) // appears exactly once → boundary
10490 ret.boundary_edges.append(Segment(ret.sites(all_edges(i).u), ret.sites(all_edges(i).v)));
10491 i = j;
10492 }
10493
10494 return ret;
10495 }
10496};
10497
10498// ============================================================================
10499// Power Diagram — Weighted Voronoi
10500// ============================================================================
10501
10545{
10546public:
10555
10560 {
10561 size_t site_u;
10562 size_t site_v;
10567 };
10568
10580
10591
10597 [[nodiscard]] static Point power_center(const WeightedSite &a,
10598 const WeightedSite &b,
10599 const WeightedSite &c)
10600 {
10601 // Power center solves:
10602 // ||p - a||² - wa = ||p - b||² - wb = ||p - c||² - wc
10603 // Expanding: 2(bx-ax)px + 2(by-ay)py = bx²+by²-ax²-ay² - (wb - wa)
10604 // 2(cx-ax)px + 2(cy-ay)py = cx²+cy²-ax²-ay² - (wc - wa)
10605 const Geom_Number &ax = a.position.get_x();
10606 const Geom_Number &ay = a.position.get_y();
10607 const Geom_Number &bx = b.position.get_x();
10608 const Geom_Number &by = b.position.get_y();
10609 const Geom_Number &cx = c.position.get_x();
10610 const Geom_Number &cy = c.position.get_y();
10611
10612 const Geom_Number d1x = bx - ax, d1y = by - ay;
10613 const Geom_Number d2x = cx - ax, d2y = cy - ay;
10614
10615 const Geom_Number rhs1 = (bx * bx + by * by - ax * ax - ay * ay - (b.weight - a.weight)) / 2;
10616 const Geom_Number rhs2 = (cx * cx + cy * cy - ax * ax - ay * ay - (c.weight - a.weight)) / 2;
10617
10618 const Geom_Number det = d1x * d2y - d1y * d2x;
10619 ah_domain_error_if(det == 0) << "Degenerate configuration";
10620
10621 return {(rhs1 * d2y - rhs2 * d1y) / det, (d1x * rhs2 - d2x * rhs1) / det};
10622 }
10623
10633 [[nodiscard]] Result operator () (const Array<WeightedSite> &sites) const
10634 {
10635 Result ret;
10636 const size_t n = sites.size();
10637 if (n == 0)
10638 return ret;
10639
10640 ret.sites = sites;
10641
10642 // Compute regular triangulation (weighted Delaunay).
10644 rt_input.reserve(n);
10645 for (size_t i = 0; i < n; ++i)
10646 rt_input.append({sites(i).position, sites(i).weight});
10647
10648 constexpr RegularTriangulationBowyerWatson reg_tri;
10649 auto rt = reg_tri(rt_input);
10650
10651 if (rt.triangles.size() == 0)
10652 return ret;
10653
10654 // Build a mapping from regular-triangulation site indices to ours.
10655 // rt.sites may have been reordered/deduped, so match by position.
10656 Array<size_t> rt_to_ours;
10657 rt_to_ours.reserve(rt.sites.size());
10658 for (size_t ri = 0; ri < rt.sites.size(); ++ri)
10659 {
10660 size_t match = 0;
10661 for (size_t oi = 0; oi < n; ++oi)
10662 if (rt.sites(ri).position == sites(oi).position)
10663 {
10664 match = oi;
10665 break;
10666 }
10667 rt_to_ours.append(match);
10668 }
10669
10670 // Compute power centers for each regular triangle.
10671 Array<Point> pcenters;
10672 pcenters.reserve(rt.triangles.size());
10673 for (size_t t = 0; t < rt.triangles.size(); ++t)
10674 {
10675 const auto &tri = rt.triangles(t);
10676 pcenters.append(power_center(sites(rt_to_ours(tri.i)), sites(rt_to_ours(tri.j)),
10677 sites(rt_to_ours(tri.k))));
10678 }
10679
10680 ret.vertices = pcenters;
10681
10682 // Identify hull sites: sites on boundary edges (edges shared by
10683 // exactly one triangle) have unbounded power cells.
10685
10687 rt.triangles,
10688 [&](const Array<GeomTriangleAdjacencyUtils::EdgeRef> &edge_refs, const size_t first,
10689 const size_t last)
10690 {
10691 if (last - first == 1)
10692 {
10693 // Boundary edge: both sites are on the convex hull.
10694 hull_sites.insert(rt_to_ours(edge_refs(first).u));
10695 hull_sites.insert(rt_to_ours(edge_refs(first).v));
10696 }
10697
10698 // In a manifold triangulation this group has exactly 1 or 2 refs.
10699 // If degeneracies produce >2, connect all pairs defensively.
10700 if (last - first >= 2)
10701 for (size_t a = first; a + 1 < last; ++a)
10702 for (size_t b = a + 1; b < last; ++b)
10703 {
10704 PowerEdge pe;
10705 pe.site_u = rt_to_ours(edge_refs(first).u);
10706 pe.site_v = rt_to_ours(edge_refs(first).v);
10707 pe.src = pcenters(edge_refs(a).tri);
10708 pe.tgt = pcenters(edge_refs(b).tri);
10709 pe.unbounded = false;
10710 pe.direction = Point(0, 0);
10711 ret.edges.append(pe);
10712 }
10713 });
10714
10715 // Build cells: hull sites have unbounded cells.
10716 ret.cells.reserve(n);
10717 for (size_t s = 0; s < n; ++s)
10718 {
10719 PowerCell cell;
10720 cell.site_index = s;
10721 cell.site = sites(s).position;
10722 cell.weight = sites(s).weight;
10723 cell.bounded = hull_sites.search(s) == nullptr;
10724
10725 // Collect power centers of triangles incident to this site.
10726 for (size_t t = 0; t < rt.triangles.size(); ++t)
10727 {
10728 const auto &[i, j, k] = rt.triangles(t);
10729 if (rt_to_ours(i) == s or rt_to_ours(j) == s or rt_to_ours(k) == s)
10730 cell.vertices.append(pcenters(t));
10731 }
10732
10733 ret.cells.append(cell);
10734 }
10735
10736 return ret;
10737 }
10738};
10739
10740// ============================================================================
10741// Bezier Curves
10742// ============================================================================
10743
10764{
10765public:
10767 [[nodiscard]] static Point quadratic(const Point &p0,
10768 const Point &p1,
10769 const Point &p2,
10770 const Geom_Number &t)
10771 {
10772 const Geom_Number s = Geom_Number(1) - t;
10773 const Geom_Number s2 = s * s;
10774 const Geom_Number t2 = t * t;
10775 const Geom_Number st2 = Geom_Number(2) * s * t;
10776
10777 return {s2 * p0.get_x() + st2 * p1.get_x() + t2 * p2.get_x(),
10778 s2 * p0.get_y() + st2 * p1.get_y() + t2 * p2.get_y()};
10779 }
10780
10782 [[nodiscard]] static Point cubic(const Point &p0,
10783 const Point &p1,
10784 const Point &p2,
10785 const Point &p3,
10786 const Geom_Number &t)
10787 {
10788 const Geom_Number s = Geom_Number(1) - t;
10789 const Geom_Number s2 = s * s;
10790 const Geom_Number s3 = s2 * s;
10791 const Geom_Number t2 = t * t;
10792 const Geom_Number t3 = t2 * t;
10793 const Geom_Number c1 = Geom_Number(3) * s2 * t;
10794 const Geom_Number c2 = Geom_Number(3) * s * t2;
10795
10796 return {s3 * p0.get_x() + c1 * p1.get_x() + c2 * p2.get_x() + t3 * p3.get_x(),
10797 s3 * p0.get_y() + c1 * p1.get_y() + c2 * p2.get_y() + t3 * p3.get_y()};
10798 }
10799
10801 [[nodiscard]] static Array<Point> sample_quadratic(const Point &p0,
10802 const Point &p1,
10803 const Point &p2,
10804 const size_t n)
10805 {
10806 ah_domain_error_if(n == 0) << "Need at least 1 subdivision";
10807 Array<Point> pts;
10808 pts.reserve(n + 1);
10809 for (size_t i = 0; i <= n; ++i)
10810 pts.append(quadratic(p0, p1, p2,
10811 Geom_Number(static_cast<long>(i)) / Geom_Number(static_cast<long>(n))));
10812 return pts;
10813 }
10814
10816 [[nodiscard]] static Array<Point> sample_cubic(const Point &p0,
10817 const Point &p1,
10818 const Point &p2,
10819 const Point &p3,
10820 const size_t n)
10821 {
10822 ah_domain_error_if(n == 0) << "Need at least 1 subdivision";
10823 Array<Point> pts;
10824 pts.reserve(n + 1);
10825 for (size_t i = 0; i <= n; ++i)
10826 pts.append(cubic(p0, p1, p2, p3,
10827 Geom_Number(static_cast<long>(i)) / Geom_Number(static_cast<long>(n))));
10828 return pts;
10829 }
10830
10834 {
10837 };
10838
10839 [[nodiscard]] static SplitResult split_cubic(const Point &p0,
10840 const Point &p1,
10841 const Point &p2,
10842 const Point &p3,
10843 const Geom_Number &t)
10844 {
10845 auto lerp = [&](const Point &a, const Point &b) -> Point
10846 {
10847 const Geom_Number s = Geom_Number(1) - t;
10848 return {s * a.get_x() + t * b.get_x(), s * a.get_y() + t * b.get_y()};
10849 };
10850
10851 const Point q0 = lerp(p0, p1);
10852 const Point q1 = lerp(p1, p2);
10853 const Point q2 = lerp(p2, p3);
10854 const Point r0 = lerp(q0, q1);
10855 const Point r1 = lerp(q1, q2);
10856 const Point s0 = lerp(r0, r1);
10857
10858 SplitResult sr;
10859 sr.left[0] = p0;
10860 sr.left[1] = q0;
10861 sr.left[2] = r0;
10862 sr.left[3] = s0;
10863 sr.right[0] = s0;
10864 sr.right[1] = r1;
10865 sr.right[2] = q2;
10866 sr.right[3] = p3;
10867 return sr;
10868 }
10869
10871 [[nodiscard]] static Rectangle control_bbox(const Point &p0,
10872 const Point &p1,
10873 const Point &p2,
10874 const Point &p3)
10875 {
10876 Geom_Number mnx = p0.get_x(), mxx = p0.get_x();
10877 Geom_Number mny = p0.get_y(), mxy = p0.get_y();
10878 auto update = [&](const Point &p)
10879 {
10880 if (p.get_x() < mnx)
10881 mnx = p.get_x();
10882 if (p.get_x() > mxx)
10883 mxx = p.get_x();
10884 if (p.get_y() < mny)
10885 mny = p.get_y();
10886 if (p.get_y() > mxy)
10887 mxy = p.get_y();
10888 };
10889 update(p1);
10890 update(p2);
10891 update(p3);
10892 return {mnx, mny, mxx, mxy};
10893 }
10894
10896 [[nodiscard]] static Polygon approximate_quadratic(const Point &p0,
10897 const Point &p1,
10898 const Point &p2,
10899 const size_t n)
10900 {
10901 auto pts = sample_quadratic(p0, p1, p2, n);
10902 Polygon poly;
10903 for (size_t i = 0; i < pts.size(); ++i)
10904 poly.add_vertex(pts(i));
10905 return poly;
10906 }
10907
10909 [[nodiscard]] static Polygon approximate_cubic(const Point &p0,
10910 const Point &p1,
10911 const Point &p2,
10912 const Point &p3,
10913 const size_t n)
10914 {
10915 auto pts = sample_cubic(p0, p1, p2, p3, n);
10916 Polygon poly;
10917 for (size_t i = 0; i < pts.size(); ++i)
10918 poly.add_vertex(pts(i));
10919 return poly;
10920 }
10921};
10922
10923// ============================================================================
10924// Boolean Polygon Operations
10925// ============================================================================
10926
10970{
10971public:
10975 enum class Op
10976 {
10977 INTERSECTION,
10978 UNION,
10979 DIFFERENCE
10980 };
10981
10991 [[nodiscard]] Array<Polygon> operator () (const Polygon &a, const Polygon &b, Op op) const
10992 {
10993 ah_domain_error_if(not a.is_closed()) << "First polygon must be closed";
10994 ah_domain_error_if(not b.is_closed()) << "Second polygon must be closed";
10995 ah_domain_error_if(a.size() < 3) << "First polygon must have >= 3 vertices";
10996 ah_domain_error_if(b.size() < 3) << "Second polygon must have >= 3 vertices";
10997
10998 switch (op)
10999 {
11000 case Op::INTERSECTION:
11001 return compute_intersection(a, b);
11002 case Op::UNION:
11003 return compute_union(a, b);
11004 case Op::DIFFERENCE:
11005 return compute_difference(a, b);
11006 }
11007 return {};
11008 }
11009
11011 [[nodiscard]] Array<Polygon> intersection(const Polygon &a, const Polygon &b) const
11012 {
11013 return (*this)(a, b, Op::INTERSECTION);
11014 }
11015
11017 [[nodiscard]] Array<Polygon> polygon_union(const Polygon &a, const Polygon &b) const
11018 {
11019 return (*this)(a, b, Op::UNION);
11020 }
11021
11023 [[nodiscard]] Array<Polygon> difference(const Polygon &a, const Polygon &b) const
11024 {
11025 return (*this)(a, b, Op::DIFFERENCE);
11026 }
11027
11028private:
11029 // ----- Greiner-Hormann node for augmented polygon vertex list -----
11030
11031 struct GHNode
11032 {
11034 bool intersect = false;
11035 bool entering = false;
11036 size_t neighbor = SIZE_MAX; // index in the other polygon's list
11037 bool visited = false;
11038 Geom_Number alpha = 0; // parameter along the original edge
11039 };
11040
11041 // ----- helpers -----
11042
11044 [[nodiscard]] static Array<Point> extract(const Polygon &p)
11045 {
11047 }
11048
11050 static void ensure_ccw(Array<Point> &v)
11051 {
11053 }
11054
11057 {
11058 for (size_t i = 0, j = v.size() - 1; i < j; ++i, --j)
11059 {
11060 const Point tmp = v(i);
11061 v(i) = v(j);
11062 v(j) = tmp;
11063 }
11064 }
11065
11067 [[nodiscard]] static Polygon build_poly(const Array<Point> &pts)
11068 {
11069 Polygon p;
11070 for (size_t i = 0; i < pts.size(); ++i)
11071 p.add_vertex(pts(i));
11072 if (pts.size() >= 3)
11073 p.close();
11074 return p;
11075 }
11076
11078 [[nodiscard]] static Geom_Number edge_param(const Point &P, const Point &Q, const Point &I)
11079 {
11080 const Geom_Number dx = Q.get_x() - P.get_x();
11081 if (dx != 0)
11082 return (I.get_x() - P.get_x()) / dx;
11083 return (I.get_y() - P.get_y()) / (Q.get_y() - P.get_y());
11084 }
11085
11087 [[nodiscard]] static bool point_inside_ccw(const Array<Point> &poly, const Point &p)
11088 {
11089 int winding = 0;
11090 const size_t n = poly.size();
11091 for (size_t i = 0; i < n; ++i)
11092 {
11093 const Point &a = poly(i);
11094 const Point &b = poly((i + 1) % n);
11095 const Segment edge(a, b);
11096 if (edge.contains(p))
11097 return true;
11098 if (a.get_y() <= p.get_y())
11099 {
11100 if (b.get_y() > p.get_y() && area_of_parallelogram(a, b, p) > 0)
11101 ++winding;
11102 }
11103 else
11104 {
11105 if (b.get_y() <= p.get_y() && area_of_parallelogram(a, b, p) < 0)
11106 --winding;
11107 }
11108 }
11109 return winding != 0;
11110 }
11111
11114 {
11115 for (size_t i = 1; i < idx.size(); ++i)
11116 {
11117 const size_t val = idx(i);
11118 const Geom_Number &key = keys(val);
11119 size_t j = i;
11120 while (j > 0 && keys(idx(j - 1)) > key)
11121 {
11122 idx(j) = idx(j - 1);
11123 --j;
11124 }
11125 idx(j) = val;
11126 }
11127 }
11128
11129 // ----- Core Greiner-Hormann algorithm -----
11130
11133 {
11137 };
11138
11144 [[nodiscard]] static Array<Polygon> greiner_hormann(const Array<Point> &va,
11145 const Array<Point> &vb,
11146 bool start_entering)
11147 {
11148 const size_t na = va.size();
11149 const size_t nb = vb.size();
11150
11151 // --- Phase 1: find all proper intersection pairs ---
11152
11153 Array<IsectPair> pairs;
11154
11155 for (size_t i = 0; i < na; ++i)
11156 {
11157 const Point &a0 = va(i);
11158 const Point &a1 = va((i + 1) % na);
11159 const Segment sa(a0, a1);
11160
11161 for (size_t j = 0; j < nb; ++j)
11162 {
11163 const Point &b0 = vb(j);
11164 const Point &b1 = vb((j + 1) % nb);
11165 const Segment sb(b0, b1);
11166
11167 if (not sa.intersects_properly_with(sb))
11168 continue;
11169
11170 const Point ip = sa.intersection_with(sb);
11171 const Geom_Number aa = edge_param(a0, a1, ip);
11172 const Geom_Number ab = edge_param(b0, b1, ip);
11173 pairs.append({ip, i, j, aa, ab});
11174 }
11175 }
11176
11177 // --- Phase 2: build augmented lists ---
11178
11179 Array<GHNode> list_a, list_b;
11180 // pair_idx_a[k] / pair_idx_b[k] = position in list_a / list_b for
11181 // intersection pair k.
11182 Array<size_t> pair_idx_a, pair_idx_b;
11183 pair_idx_a.reserve(pairs.size());
11184 pair_idx_b.reserve(pairs.size());
11185 for (size_t k = 0; k < pairs.size(); ++k)
11186 {
11187 pair_idx_a.append(0);
11188 pair_idx_b.append(0);
11189 }
11190
11191 // Build list_a: for each edge, add original vertex then sorted
11192 // intersections.
11193 for (size_t i = 0; i < na; ++i)
11194 {
11195 GHNode vn;
11196 vn.pt = va(i);
11197 list_a.append(vn);
11198
11199 // Collect pairs on this edge of A.
11200 Array<size_t> edge_pairs;
11201 Array<Geom_Number> edge_alphas;
11202 for (size_t k = 0; k < pairs.size(); ++k)
11203 if (pairs(k).edge_a == i)
11204 {
11205 edge_pairs.append(k);
11206 edge_alphas.append(pairs(k).alpha_a);
11207 }
11208
11209 // Sort by alpha.
11210 Array<size_t> order;
11211 for (size_t p = 0; p < edge_pairs.size(); ++p)
11212 order.append(p);
11213 sort_indices_by_alpha(order, edge_alphas);
11214
11215 for (size_t p = 0; p < order.size(); ++p)
11216 {
11217 const size_t k = edge_pairs(order(p));
11218 pair_idx_a(k) = list_a.size();
11219 GHNode in;
11220 in.pt = pairs(k).pt;
11221 in.intersect = true;
11222 in.alpha = pairs(k).alpha_a;
11223 list_a.append(in);
11224 }
11225 }
11226
11227 // Build list_b analogously.
11228 for (size_t j = 0; j < nb; ++j)
11229 {
11230 GHNode vn;
11231 vn.pt = vb(j);
11232 list_b.append(vn);
11233
11234 Array<size_t> edge_pairs;
11235 Array<Geom_Number> edge_alphas;
11236 for (size_t k = 0; k < pairs.size(); ++k)
11237 if (pairs(k).edge_b == j)
11238 {
11239 edge_pairs.append(k);
11240 edge_alphas.append(pairs(k).alpha_b);
11241 }
11242
11243 Array<size_t> order;
11244 for (size_t p = 0; p < edge_pairs.size(); ++p)
11245 order.append(p);
11246 sort_indices_by_alpha(order, edge_alphas);
11247
11248 for (size_t p = 0; p < order.size(); ++p)
11249 {
11250 const size_t k = edge_pairs(order(p));
11251 pair_idx_b(k) = list_b.size();
11252 GHNode in;
11253 in.pt = pairs(k).pt;
11254 in.intersect = true;
11255 in.alpha = pairs(k).alpha_b;
11256 list_b.append(in);
11257 }
11258 }
11259
11260 // Set neighbor links.
11261 for (size_t k = 0; k < pairs.size(); ++k)
11262 {
11263 list_a(pair_idx_a(k)).neighbor = pair_idx_b(k);
11264 list_b(pair_idx_b(k)).neighbor = pair_idx_a(k);
11265 }
11266
11267 // --- Phase 3: mark entry / exit ---
11268
11269 // Walk list_a; determine if the first original vertex of A is
11270 // inside B.
11271 {
11272 bool inside = point_inside_ccw(vb, va(0));
11273 for (size_t i = 0; i < list_a.size(); ++i)
11274 if (list_a(i).intersect)
11275 {
11276 list_a(i).entering = !inside;
11277 inside = !inside;
11278 }
11279 }
11280
11281 // Walk list_b similarly w.r.t. A.
11282 {
11283 bool inside = point_inside_ccw(va, vb(0));
11284 for (size_t j = 0; j < list_b.size(); ++j)
11285 if (list_b(j).intersect)
11286 {
11287 list_b(j).entering = !inside;
11288 inside = !inside;
11289 }
11290 }
11291
11292 // --- Phase 4: traverse ---
11293
11294 Array<Polygon> result;
11295 const size_t safety_limit = list_a.size() + list_b.size() + pairs.size() * 2;
11296
11297 for (size_t s = 0; s < list_a.size(); ++s)
11298 {
11299 if (not list_a(s).intersect)
11300 continue;
11301 if (list_a(s).visited)
11302 continue;
11303 if (list_a(s).entering != start_entering)
11304 continue;
11305
11306 // Trace one result polygon.
11307 Array<Point> boundary;
11308 bool on_a = true;
11309 size_t idx = s;
11310 size_t steps = 0;
11311
11312 do
11313 {
11314 auto &cur_list = on_a ? list_a : list_b;
11315
11316 // Mark current intersection visited (and its partner).
11317 cur_list(idx).visited = true;
11318 if (cur_list(idx).neighbor != SIZE_MAX)
11319 {
11320 auto &other = on_a ? list_b : list_a;
11321 other(cur_list(idx).neighbor).visited = true;
11322 }
11323
11324 // Record this intersection point.
11325 boundary.append(cur_list(idx).pt);
11326
11327 // Walk forward until the next intersection node.
11328 idx = (idx + 1) % cur_list.size();
11329 while (not cur_list(idx).intersect)
11330 {
11331 boundary.append(cur_list(idx).pt);
11332 idx = (idx + 1) % cur_list.size();
11333 if (++steps > safety_limit)
11334 goto done_poly;
11335 }
11336
11337 // idx is now at the next intersection — mark it and switch.
11338 cur_list(idx).visited = true;
11339 {
11340 auto &other = on_a ? list_b : list_a;
11341 const size_t nbr = cur_list(idx).neighbor;
11342 other(nbr).visited = true;
11343 on_a = !on_a;
11344 idx = nbr;
11345 }
11346
11347 if (++steps > safety_limit)
11348 break;
11349 } while (!(on_a && idx == s));
11350
11351 done_poly:
11352 if (boundary.size() >= 3)
11353 result.append(build_poly(boundary));
11354 }
11355
11356 return result;
11357 }
11358
11359 // ----- Operation dispatchers -----
11360
11371 {
11372 Array<Point> va = extract(a);
11373 Array<Point> vb = extract(b);
11374 ensure_ccw(va);
11375 ensure_ccw(vb);
11376
11377 Array<Polygon> res = greiner_hormann(va, vb, /*start_entering=*/true);
11378
11379 if (not res.is_empty())
11380 return res;
11381
11382 // No proper intersections — check containment.
11383 if (point_inside_ccw(vb, va(0)))
11384 {
11385 // A entirely inside B → intersection is A.
11386 res.append(a);
11387 return res;
11388 }
11389 if (point_inside_ccw(va, vb(0)))
11390 {
11391 // B entirely inside A → intersection is B.
11392 res.append(b);
11393 return res;
11394 }
11395 // Disjoint.
11396 return res;
11397 }
11398
11408 static Array<Polygon> compute_union(const Polygon &a, const Polygon &b)
11409 {
11410 Array<Point> va = extract(a);
11411 Array<Point> vb = extract(b);
11412 ensure_ccw(va);
11413 ensure_ccw(vb);
11414
11415 Array<Polygon> res = greiner_hormann(va, vb, /*start_entering=*/false);
11416
11417 if (!res.is_empty())
11418 return res;
11419
11420 // No proper intersections — check containment.
11421 if (point_inside_ccw(vb, va(0)))
11422 {
11423 // A inside B → union is B.
11424 res.append(b);
11425 return res;
11426 }
11427 if (point_inside_ccw(va, vb(0)))
11428 {
11429 // B inside A → union is A.
11430 res.append(a);
11431 return res;
11432 }
11433 // Disjoint → both.
11434 res.append(a);
11435 res.append(b);
11436 return res;
11437 }
11438
11449 {
11450 Array<Point> va = extract(a);
11451 Array<Point> vb = extract(b);
11452 ensure_ccw(va);
11453 ensure_ccw(vb);
11454
11455 // A \ B = A ∩ complement(B). Reversing B's winding makes
11456 // "inside reversed-B" = "outside B", so intersection with
11457 // reversed-B gives the difference.
11458 reverse_array(vb);
11459
11460 Array<Polygon> res = greiner_hormann(va, vb, /*start_entering=*/true);
11461
11462 if (!res.is_empty())
11463 return res;
11464
11465 // No proper intersections — check containment using ORIGINAL B.
11466 // Reverse vb back to original orientation for the test.
11467 reverse_array(vb);
11468
11469 if (point_inside_ccw(vb, va(0)))
11470 {
11471 // A entirely inside B → difference is empty.
11472 return res;
11473 }
11474 // B inside A → difference has a hole (limitation: return A).
11475 // Disjoint → difference is A.
11476 res.append(a);
11477 return res;
11478 }
11479};
11480
11481// ============================================================================
11482// Serialization — WKT and GeoJSON
11483// ============================================================================
11484
11510{
11514 static std::string dbl(const Geom_Number &n)
11515 {
11516 std::ostringstream os;
11517 os << std::setprecision(15) << geom_number_to_double(n);
11518 return os.str();
11519 }
11520
11521public:
11522 // ---- WKT (Well-Known Text) ----
11523
11527 [[nodiscard]] static std::string to_wkt(const Point &p)
11528 {
11529 return "POINT (" + dbl(p.get_x()) + " " + dbl(p.get_y()) + ")";
11530 }
11531
11535 [[nodiscard]] static std::string to_wkt(const Segment &s)
11536 {
11537 return "LINESTRING (" + dbl(s.get_src_point().get_x()) + " " + dbl(s.get_src_point().get_y()) +
11538 ", " + dbl(s.get_tgt_point().get_x()) + " " + dbl(s.get_tgt_point().get_y()) + ")";
11539 }
11540
11544 [[nodiscard]] static std::string to_wkt(const Triangle &t)
11545 {
11546 auto pt = [](const Point &p)
11547 {
11548 return dbl(p.get_x()) + " " + dbl(p.get_y());
11549 };
11550 return "POLYGON ((" + pt(t.get_p1()) + ", " + pt(t.get_p2()) + ", " + pt(t.get_p3()) + ", " +
11551 pt(t.get_p1()) + "))";
11552 }
11553
11558 [[nodiscard]] static std::string to_wkt(const Rectangle &r)
11559 {
11560 return "POLYGON ((" + dbl(r.get_xmin()) + " " + dbl(r.get_ymin()) + ", " + dbl(r.get_xmax()) +
11561 " " + dbl(r.get_ymin()) + ", " + dbl(r.get_xmax()) + " " + dbl(r.get_ymax()) + ", " +
11562 dbl(r.get_xmin()) + " " + dbl(r.get_ymax()) + ", " + dbl(r.get_xmin()) + " " +
11563 dbl(r.get_ymin()) + "))";
11564 }
11565
11569 [[nodiscard]] static std::string to_wkt(const Polygon &poly)
11570 {
11571 std::ostringstream os;
11572 os << std::setprecision(15) << "POLYGON ((";
11573 bool first = true;
11574 Point first_pt;
11575 for (Polygon::Vertex_Iterator it(poly); it.has_curr(); it.next_ne())
11576 {
11577 const Point &v = it.get_current_vertex();
11578 if (first)
11579 {
11580 first_pt = v;
11581 first = false;
11582 }
11583 else
11584 os << ", ";
11585 os << geom_number_to_double(v.get_x()) << " " << geom_number_to_double(v.get_y());
11586 }
11587 if (not first)
11588 os << ", " << geom_number_to_double(first_pt.get_x()) << " "
11589 << geom_number_to_double(first_pt.get_y());
11590 os << "))";
11591 return os.str();
11592 }
11593
11597 [[nodiscard]] static std::string to_wkt(const Point3D &p)
11598 {
11599 return "POINT Z (" + dbl(p.get_x()) + " " + dbl(p.get_y()) + " " + dbl(p.get_z()) + ")";
11600 }
11601
11602 // ---- GeoJSON ----
11603
11607 [[nodiscard]] static std::string to_geojson(const Point &p)
11608 {
11609 return R"({"type":"Point","coordinates":[)" + dbl(p.get_x()) + "," + dbl(p.get_y()) + "]}";
11610 }
11611
11615 [[nodiscard]] static std::string to_geojson(const Segment &s)
11616 {
11617 return R"({"type":"LineString","coordinates":[[)" + dbl(s.get_src_point().get_x()) + "," +
11618 dbl(s.get_src_point().get_y()) + "],[" + dbl(s.get_tgt_point().get_x()) + "," +
11619 dbl(s.get_tgt_point().get_y()) + "]]}";
11620 }
11621
11623 [[nodiscard]] static std::string to_geojson(const Triangle &t)
11624 {
11625 auto pt = [](const Point &p)
11626 {
11627 return "[" + dbl(p.get_x()) + "," + dbl(p.get_y()) + "]";
11628 };
11629 return R"({"type":"Polygon","coordinates":[[)" + pt(t.get_p1()) + "," + pt(t.get_p2()) + "," +
11630 pt(t.get_p3()) + "," + pt(t.get_p1()) + "]]}";
11631 }
11632
11634 [[nodiscard]] static std::string to_geojson(const Polygon &poly)
11635 {
11636 std::ostringstream os;
11637 os << std::setprecision(15);
11638 os << R"({"type":"Polygon","coordinates":[[)";
11639 bool first = true;
11640 Point first_pt;
11641 for (Polygon::Vertex_Iterator it(poly); it.has_curr(); it.next_ne())
11642 {
11643 const Point &v = it.get_current_vertex();
11644 if (first)
11645 {
11646 first_pt = v;
11647 first = false;
11648 }
11649 else
11650 os << ",";
11651 os << "[" << geom_number_to_double(v.get_x()) << "," << geom_number_to_double(v.get_y())
11652 << "]";
11653 }
11654 if (not first)
11655 os << ",[" << geom_number_to_double(first_pt.get_x()) << ","
11656 << geom_number_to_double(first_pt.get_y()) << "]";
11657 os << "]]}";
11658 return os.str();
11659 }
11660
11662 [[nodiscard]] static std::string to_geojson(const Point3D &p)
11663 {
11664 return R"({"type":"Point","coordinates":[)" + dbl(p.get_x()) + "," + dbl(p.get_y()) + "," +
11665 dbl(p.get_z()) + "]}";
11666 }
11667};
11668
11669// ============================================================================
11670// AABB Tree — Axis-Aligned Bounding Box Tree
11671// ============================================================================
11672
11707{
11708public:
11712 struct Entry
11713 {
11715 size_t index;
11716 };
11717
11722 {
11723 size_t node_index = ~static_cast<size_t>(0);
11725 bool is_leaf = false;
11726 size_t entry_index = ~static_cast<size_t>(0);
11727 size_t user_index = ~static_cast<size_t>(0);
11728 size_t left = ~static_cast<size_t>(0);
11729 size_t right = ~static_cast<size_t>(0);
11730 size_t depth = 0;
11731 };
11732
11737 {
11739 size_t root = ~static_cast<size_t>(0);
11740 };
11741
11742private:
11746 struct Node
11747 {
11749 size_t left = ~static_cast<size_t>(0);
11750 size_t right = ~static_cast<size_t>(0);
11751 size_t entry_idx = ~static_cast<size_t>(0);
11752
11756 [[nodiscard]] bool is_leaf() const
11757 {
11758 return entry_idx != ~static_cast<size_t>(0);
11759 }
11760 };
11761
11764
11765 static constexpr size_t NONE = ~static_cast<size_t>(0);
11766
11770 [[nodiscard]] static Rectangle union_bbox(const Rectangle &a, const Rectangle &b)
11771 {
11772 const Geom_Number xmin = a.get_xmin() < b.get_xmin() ? a.get_xmin() : b.get_xmin();
11773 const Geom_Number ymin = a.get_ymin() < b.get_ymin() ? a.get_ymin() : b.get_ymin();
11774 const Geom_Number xmax = a.get_xmax() > b.get_xmax() ? a.get_xmax() : b.get_xmax();
11775 const Geom_Number ymax = a.get_ymax() > b.get_ymax() ? a.get_ymax() : b.get_ymax();
11776 return {xmin, ymin, xmax, ymax};
11777 }
11778
11782 [[nodiscard]] static bool boxes_overlap(const Rectangle &a, const Rectangle &b)
11783 {
11784 return a.get_xmin() <= b.get_xmax() and a.get_xmax() >= b.get_xmin() and
11785 a.get_ymin() <= b.get_ymax() and a.get_ymax() >= b.get_ymin();
11786 }
11787
11791 [[nodiscard]] static bool box_contains_point(const Rectangle &r, const Point &p)
11792 {
11793 return p.get_x() >= r.get_xmin() and p.get_x() <= r.get_xmax() and p.get_y() >= r.get_ymin() and
11794 p.get_y() <= r.get_ymax();
11795 }
11796
11797 [[nodiscard]] Geom_Number center_coord(const size_t entry_idx, const bool split_x) const
11798 {
11799 return split_x ? entries_(entry_idx).bbox.get_xmin() + entries_(entry_idx).bbox.get_xmax()
11800 : entries_(entry_idx).bbox.get_ymin() + entries_(entry_idx).bbox.get_ymax();
11801 }
11802
11804 const size_t lo,
11805 const size_t hi,
11806 const bool split_x) const
11807 {
11808 for (size_t i = lo + 1; i < hi; ++i)
11809 {
11810 const size_t key = idx(i);
11811 const Geom_Number key_val = center_coord(key, split_x);
11812 size_t j = i;
11813 while (j > lo and center_coord(idx(j - 1), split_x) > key_val)
11814 {
11815 idx(j) = idx(j - 1);
11816 --j;
11817 }
11818 idx(j) = key;
11819 }
11820 }
11821
11822 // Partially reorder idx[lo..hi) so idx[kth] is in its sorted position
11823 // by center along the split axis (expected linear time).
11825 size_t lo,
11826 size_t hi,
11827 const size_t kth,
11828 const bool split_x) const
11829 {
11830 while (hi - lo > 16)
11831 {
11832 const Geom_Number pivot = center_coord(idx(lo + (hi - lo) / 2), split_x);
11833
11834 size_t lt = lo;
11835 size_t i = lo;
11836 size_t gt = hi;
11837 while (i < gt)
11838 {
11839 const Geom_Number val = center_coord(idx(i), split_x);
11840 if (val < pivot)
11841 {
11842 const size_t tmp = idx(lt);
11843 idx(lt) = idx(i);
11844 idx(i) = tmp;
11845 ++lt;
11846 ++i;
11847 }
11848 else if (val > pivot)
11849 {
11850 --gt;
11851 const size_t tmp = idx(gt);
11852 idx(gt) = idx(i);
11853 idx(i) = tmp;
11854 }
11855 else
11856 ++i;
11857 }
11858
11859 if (kth < lt)
11860 hi = lt;
11861 else if (kth >= gt)
11862 lo = gt;
11863 else
11864 return;
11865 }
11866
11867 insertion_sort_by_center(idx, lo, hi, split_x);
11868 }
11869
11870 // Build a subtree for entries[lo..hi) and return its node index.
11871 size_t build(Array<size_t> &idx, const size_t lo, const size_t hi)
11872 {
11873 if (hi - lo == 1)
11874 {
11875 Node n;
11876 n.bbox = entries_(idx(lo)).bbox;
11877 n.entry_idx = idx(lo);
11878 const size_t ni = nodes_.size();
11879 nodes_.append(n);
11880 return ni;
11881 }
11882
11883 // Compute enclosing bbox.
11884 Rectangle total = entries_(idx(lo)).bbox;
11885 for (size_t i = lo + 1; i < hi; ++i)
11886 total = union_bbox(total, entries_(idx(i)).bbox);
11887
11888 // Split along the longest axis.
11889 const Geom_Number dx = total.get_xmax() - total.get_xmin();
11890 const Geom_Number dy = total.get_ymax() - total.get_ymin();
11891 const bool split_x = dx >= dy;
11892
11893 const size_t mid = lo + (hi - lo) / 2;
11894 select_kth_by_center(idx, lo, hi, mid, split_x);
11895
11896 const size_t left = build(idx, lo, mid);
11897 const size_t right = build(idx, mid, hi);
11898
11899 Node n;
11900 n.bbox = union_bbox(nodes_(left).bbox, nodes_(right).bbox);
11901 n.left = left;
11902 n.right = right;
11903 const size_t ni = nodes_.size();
11904 nodes_.append(n);
11905 return ni;
11906 }
11907
11908 void query_impl(const size_t ni, const Rectangle &q, Array<size_t> &results) const
11909 {
11910 if (ni == NONE)
11911 return;
11912 const Node &n = nodes_(ni);
11913 if (not boxes_overlap(n.bbox, q))
11914 return;
11915
11916 if (n.is_leaf())
11917 {
11918 results.append(entries_(n.entry_idx).index);
11919 return;
11920 }
11921
11922 query_impl(n.left, q, results);
11923 query_impl(n.right, q, results);
11924 }
11925
11926 void query_point_impl(const size_t ni, const Point &p, Array<size_t> &results) const
11927 {
11928 if (ni == NONE)
11929 return;
11930 const Node &n = nodes_(ni);
11931 if (not box_contains_point(n.bbox, p))
11932 return;
11933
11934 if (n.is_leaf())
11935 {
11936 if (box_contains_point(entries_(n.entry_idx).bbox, p))
11937 results.append(entries_(n.entry_idx).index);
11938 return;
11939 }
11940
11941 query_point_impl(n.left, p, results);
11942 query_point_impl(n.right, p, results);
11943 }
11944
11945 size_t root_ = NONE;
11946
11947public:
11948 AABBTree() = default;
11949
11954 AABBTree(const AABBTree &other) = default;
11955
11965 AABBTree(AABBTree &&other) noexcept
11966 : nodes_(std::move(other.nodes_)), entries_(std::move(other.entries_)),
11967 root_(std::exchange(other.root_, NONE))
11968 {}
11969
11975 AABBTree &operator=(const AABBTree &other) = default;
11976
11983 AABBTree &operator=(AABBTree &&other) noexcept
11984 {
11985 swap(other);
11986 return *this;
11987 }
11988
11993 void swap(AABBTree &other) noexcept
11994 {
11995 nodes_.swap(other.nodes_);
11996 entries_.swap(other.entries_);
11997 std::swap(root_, other.root_);
11998 }
11999
12005 void build(const Array<Entry> &entries)
12006 {
12007 entries_ = entries;
12008 nodes_ = Array<Node>();
12009 if (entries_.is_empty())
12010 {
12011 root_ = NONE;
12012 return;
12013 }
12014
12015 Array<size_t> idx;
12016 idx.reserve(entries_.size());
12017 for (size_t i = 0; i < entries_.size(); ++i)
12018 idx.append(i);
12019
12020 root_ = build(idx, 0, idx.size());
12021 }
12022
12029 [[nodiscard]] Array<size_t> query(const Rectangle &query) const
12030 {
12031 Array<size_t> results;
12032 if (root_ != NONE)
12033 query_impl(root_, query, results);
12034 return results;
12035 }
12036
12043 [[nodiscard]] Array<size_t> query_point(const Point &p) const
12044 {
12045 Array<size_t> results;
12046 if (root_ != NONE)
12047 query_point_impl(root_, p, results);
12048 return results;
12049 }
12050
12052 [[nodiscard]] Rectangle root_bbox() const
12053 {
12054 ah_domain_error_if(root_ == NONE) << "Empty tree";
12055 return nodes_(root_).bbox;
12056 }
12057
12059 [[nodiscard]] size_t size() const
12060 {
12061 return entries_.size();
12062 }
12063
12065 [[nodiscard]] bool is_empty() const
12066 {
12067 return entries_.is_empty();
12068 }
12069
12071 [[nodiscard]] DebugSnapshot debug_snapshot() const
12072 {
12073 DebugSnapshot snap;
12074 if (root_ == NONE)
12075 return snap;
12076
12077 snap.nodes.reserve(nodes_.size());
12078
12079 auto dfs = [&](const auto &self, const size_t ni, const size_t depth) -> size_t
12080 {
12081 const Node &n = nodes_(ni);
12082 const size_t out_idx = snap.nodes.size();
12083 snap.nodes.append(DebugNode{});
12084 snap.nodes(out_idx).node_index = ni;
12085 snap.nodes(out_idx).bbox = n.bbox;
12086 snap.nodes(out_idx).is_leaf = n.is_leaf();
12087 snap.nodes(out_idx).depth = depth;
12088 if (n.is_leaf())
12089 {
12090 snap.nodes(out_idx).entry_index = n.entry_idx;
12091 snap.nodes(out_idx).user_index = entries_(n.entry_idx).index;
12092 }
12093 else
12094 {
12095 const size_t left = self(self, n.left, depth + 1);
12096 const size_t right = self(self, n.right, depth + 1);
12097 snap.nodes(out_idx).left = left;
12098 snap.nodes(out_idx).right = right;
12099 }
12100 return out_idx;
12101 };
12102
12103 snap.root = dfs(dfs, root_, 0);
12104 return snap;
12105 }
12106};
12107
12108// ============================================================================
12109// Polyline / Polygon Simplification
12110// ============================================================================
12111
12128{
12129 static void dp_recurse(const Array<Point> &pts,
12130 const size_t first,
12131 const size_t last,
12132 const Geom_Number &eps2,
12133 Array<bool> &keep)
12134 {
12135 if (last <= first + 1)
12136 return;
12137
12138 const Segment seg(pts(first), pts(last));
12139 Geom_Number max_dist2 = 0;
12140 size_t max_idx = first;
12141
12142 for (size_t i = first + 1; i < last; ++i)
12143 {
12144 Geom_Number d = seg.distance_to(pts(i));
12145 if (Geom_Number d2 = d * d; d2 > max_dist2)
12146 {
12147 max_dist2 = d2;
12148 max_idx = i;
12149 }
12150 }
12151
12152 if (max_dist2 > eps2)
12153 {
12154 keep(max_idx) = true;
12155 dp_recurse(pts, first, max_idx, eps2, keep);
12156 dp_recurse(pts, max_idx, last, eps2, keep);
12157 }
12158 }
12159
12160public:
12170 [[nodiscard]] Array<Point> operator () (const Array<Point> &polyline, const Geom_Number &epsilon) const
12171 {
12172 const size_t n = polyline.size();
12173 if (n <= 2)
12174 return polyline;
12175
12176 const Geom_Number eps2 = epsilon * epsilon;
12177 auto keep = Array<bool>::create_reserved(n);
12178 for (size_t i = 0; i < n; ++i)
12179 keep.append(false);
12180 keep(0) = true;
12181 keep(n - 1) = true;
12182
12183 dp_recurse(polyline, 0, n - 1, eps2, keep);
12184
12185 Array<Point> result;
12186 for (size_t i = 0; i < n; ++i)
12187 if (keep(i))
12188 result.append(polyline(i));
12189
12190 return result;
12191 }
12192
12194 [[nodiscard]] Array<Point> operator () (const DynList<Point> &polyline,
12195 const Geom_Number &epsilon) const
12196 {
12197 Array<Point> arr;
12198 for (auto it = polyline.get_it(); it.has_curr(); it.next_ne())
12199 arr.append(it.get_curr());
12200 return (*this)(arr, epsilon);
12201 }
12202
12213 [[nodiscard]] Polygon simplify_polygon(const Polygon &poly, const Geom_Number &epsilon) const
12214 {
12215 auto verts = GeomPolygonUtils::extract_vertices(poly);
12216 const size_t n = verts.size();
12217 if (n <= 3)
12218 return poly;
12219
12220 // Find vertex farthest from vertex 0
12221 size_t far_idx = 1;
12222 Geom_Number far_dist2 = 0;
12223 for (size_t i = 1; i < n; ++i)
12224 {
12225 Geom_Number dx = verts(i).get_x() - verts(0).get_x();
12226 Geom_Number dy = verts(i).get_y() - verts(0).get_y();
12227 if (Geom_Number d2 = dx * dx + dy * dy; d2 > far_dist2)
12228 {
12229 far_dist2 = d2;
12230 far_idx = i;
12231 }
12232 }
12233
12234 // Build two open chains sharing endpoints at vertex 0 and far_idx
12235 Array<Point> chain1; // 0 → far_idx
12236 for (size_t i = 0; i <= far_idx; ++i)
12237 chain1.append(verts(i));
12238
12239 Array<Point> chain2; // far_idx → 0 (wrapping around)
12240 for (size_t i = far_idx; i < n; ++i)
12241 chain2.append(verts(i));
12242 chain2.append(verts(0));
12243
12244 auto s1 = (*this)(chain1, epsilon);
12245 auto s2 = (*this)(chain2, epsilon);
12246
12247 // Merge: s1 + s2 without duplicate junction points
12248 Array<Point> merged;
12249 for (size_t i = 0; i < s1.size(); ++i)
12250 merged.append(s1(i));
12251 for (size_t i = 1; i + 1 < s2.size(); ++i) // skip first (dup) & last (dup)
12252 merged.append(s2(i));
12253
12254 if (merged.size() < 3)
12255 return poly;
12256
12257 Polygon result;
12258 for (size_t i = 0; i < merged.size(); ++i)
12259 result.add_vertex(merged(i));
12260 result.close();
12261 return result;
12262 }
12263};
12264
12278{
12282 struct VWEntry
12283 {
12284 size_t idx;
12286
12288 bool operator < (const VWEntry &o) const
12289 {
12290 return area < o.area;
12291 }
12293 bool operator > (const VWEntry &o) const
12294 {
12295 return area > o.area;
12296 }
12297 };
12298
12299 [[nodiscard]] static Geom_Number effective_area(const Point &a, const Point &b, const Point &c)
12300 {
12301 Geom_Number ap = area_of_parallelogram(a, b, c);
12302 if (ap < 0)
12303 ap = -ap;
12304 return ap / 2;
12305 }
12306
12307 [[nodiscard]] static Array<Point> simplify_open_array(const Array<Point> &polyline,
12308 const Geom_Number &area_threshold)
12309 {
12310 const size_t n = polyline.size();
12311 if (n <= 2)
12312 return polyline;
12313
12314 // prev/next linked list (index-based)
12315 auto prev = Array<size_t>::create_reserved(n);
12317 auto alive = Array<bool>::create_reserved(n);
12318 for (size_t i = 0; i < n; ++i)
12319 {
12320 prev.append(i == 0 ? n : i - 1); // n = sentinel for "no prev"
12321 next.append(i == n - 1 ? n : i + 1);
12322 alive.append(true);
12323 }
12324
12325 // Min-heap
12327
12328 // Compute initial areas for interior vertices
12330 for (size_t i = 0; i < n; ++i)
12331 areas.append(Geom_Number(-1));
12332
12333 for (size_t i = 1; i + 1 < n; ++i)
12334 {
12335 areas(i) = effective_area(polyline(prev(i)), polyline(i), polyline(next(i)));
12336 heap.put({i, areas(i)});
12337 }
12338
12339 while (not heap.is_empty())
12340 {
12341 auto [idx, area] = heap.get();
12342
12343 if (not alive(idx))
12344 continue;
12345 if (area != areas(idx))
12346 continue; // stale entry
12347 if (area >= area_threshold)
12348 break;
12349
12350 // Remove this vertex
12351 alive(idx) = false;
12352 const size_t p = prev(idx);
12353 const size_t nx = next(idx);
12354
12355 if (p < n)
12356 next(p) = nx;
12357 if (nx < n)
12358 prev(nx) = p;
12359
12360 // Recompute neighbor areas
12361 if (p < n and p != 0 and prev(p) < n)
12362 {
12363 areas(p) = effective_area(polyline(prev(p)), polyline(p), polyline(next(p)));
12364 heap.put({p, areas(p)});
12365 }
12366 if (nx < n and nx != n - 1 and next(nx) < n)
12367 {
12368 areas(nx) = effective_area(polyline(prev(nx)), polyline(nx), polyline(next(nx)));
12369 heap.put({nx, areas(nx)});
12370 }
12371 }
12372
12373 Array<Point> result;
12374 for (size_t i = 0; i < n; ++i)
12375 if (alive(i))
12376 result.append(polyline(i));
12377
12378 return result;
12379 }
12380
12381public:
12391 [[nodiscard]] Array<Point> operator () (const Array<Point> &polyline,
12392 const Geom_Number &area_threshold) const
12393 {
12394 return simplify_open_array(polyline, area_threshold);
12395 }
12396
12398 [[nodiscard]] Array<Point> operator () (const DynList<Point> &polyline,
12399 const Geom_Number &area_threshold) const
12400 {
12401 Array<Point> arr;
12402 for (auto it = polyline.get_it(); it.has_curr(); it.next_ne())
12403 arr.append(it.get_curr());
12404 return simplify_open_array(arr, area_threshold);
12405 }
12406
12416 [[nodiscard]] static Polygon simplify_polygon(const Polygon &poly, const Geom_Number &area_threshold)
12417 {
12418 auto verts = GeomPolygonUtils::extract_vertices(poly);
12419 const size_t n = verts.size();
12420 if (n <= 3)
12421 return poly;
12422
12423 // Cyclic prev/next linked list
12424 auto prev = Array<size_t>::create_reserved(n);
12426 auto alive = Array<bool>::create_reserved(n);
12427 for (size_t i = 0; i < n; ++i)
12428 {
12429 prev.append(i == 0 ? n - 1 : i - 1);
12430 next.append(i == n - 1 ? 0 : i + 1);
12431 alive.append(true);
12432 }
12433
12435
12437 for (size_t i = 0; i < n; ++i)
12438 {
12439 areas.append(effective_area(verts(prev(i)), verts(i), verts(next(i))));
12440 heap.put({i, areas(i)});
12441 }
12442
12443 size_t remaining = n;
12444 while (not heap.is_empty() and remaining > 3)
12445 {
12446 auto [idx, area] = heap.get();
12447
12448 if (not alive(idx))
12449 continue;
12450 if (area != areas(idx))
12451 continue;
12452 if (area >= area_threshold)
12453 break;
12454
12455 alive(idx) = false;
12456 --remaining;
12457 const size_t p = prev(idx);
12458 const size_t nx = next(idx);
12459
12460 next(p) = nx;
12461 prev(nx) = p;
12462
12463 // Recompute neighbor areas
12464 areas(p) = effective_area(verts(prev(p)), verts(p), verts(next(p)));
12465 heap.put({p, areas(p)});
12466 areas(nx) = effective_area(verts(prev(nx)), verts(nx), verts(next(nx)));
12467 heap.put({nx, areas(nx)});
12468 }
12469
12470 Array<Point> result;
12471 for (size_t i = 0; i < n; ++i)
12472 if (alive(i))
12473 result.append(verts(i));
12474
12475 if (result.size() < 3)
12476 return poly;
12477
12478 Polygon rpoly;
12479 for (size_t i = 0; i < result.size(); ++i)
12480 rpoly.add_vertex(result(i));
12481 rpoly.close();
12482 return rpoly;
12483 }
12484};
12485
12486// ============================================================================
12487// Chaikin Corner-Cutting Subdivision (Polygon Smoothing)
12488// ============================================================================
12489
12505{
12506 [[nodiscard]] static Array<Point> smooth_open_once(const Array<Point> &pts, const Geom_Number &r)
12507 {
12508 const size_t n = pts.size();
12509 Array<Point> result;
12510 result.append(pts(0));
12511 for (size_t i = 0; i + 1 < n; ++i)
12512 {
12513 const auto &p = pts(i);
12514 const auto &q = pts(i + 1);
12515 Geom_Number one_r = Geom_Number(1) - r;
12516 result.append(Point(p.get_x() * one_r + q.get_x() * r, p.get_y() * one_r + q.get_y() * r));
12517 result.append(Point(p.get_x() * r + q.get_x() * one_r, p.get_y() * r + q.get_y() * one_r));
12518 }
12519 result.append(pts(n - 1));
12520 return result;
12521 }
12522
12523 [[nodiscard]] static Array<Point> smooth_closed_once(const Array<Point> &pts, const Geom_Number &r)
12524 {
12525 const size_t n = pts.size();
12526 Array<Point> result;
12527 Geom_Number one_r = Geom_Number(1) - r;
12528 for (size_t i = 0; i < n; ++i)
12529 {
12530 const auto &p = pts(i);
12531 const auto &q = pts((i + 1) % n);
12532 result.append(Point(p.get_x() * one_r + q.get_x() * r, p.get_y() * one_r + q.get_y() * r));
12533 result.append(Point(p.get_x() * r + q.get_x() * one_r, p.get_y() * r + q.get_y() * one_r));
12534 }
12535 return result;
12536 }
12537
12538public:
12549 [[nodiscard]] Array<Point> operator () (const Array<Point> &polyline,
12550 size_t iterations,
12551 const Geom_Number &ratio = Geom_Number(1, 4)) const
12552 {
12553 ah_domain_error_if(iterations == 0) << "iterations must be >= 1";
12554 ah_domain_error_if(ratio <= Geom_Number(0) or ratio >= Geom_Number(1, 2))
12555 << "ratio must be in (0, 0.5)";
12556
12557 Array<Point> cur = polyline;
12558 for (size_t k = 0; k < iterations; ++k)
12559 cur = smooth_open_once(cur, ratio);
12560 return cur;
12561 }
12562
12564 [[nodiscard]] Array<Point> operator () (const DynList<Point> &polyline,
12565 size_t iterations,
12566 const Geom_Number &ratio = Geom_Number(1, 4)) const
12567 {
12568 Array<Point> arr;
12569 for (auto it = polyline.get_it(); it.has_curr(); it.next_ne())
12570 arr.append(it.get_curr());
12571 return (*this)(arr, iterations, ratio);
12572 }
12573
12584 [[nodiscard]] static Polygon smooth_polygon(const Polygon &poly,
12585 size_t iterations,
12586 const Geom_Number &ratio = Geom_Number(1, 4))
12587 {
12588 ah_domain_error_if(iterations == 0) << "iterations must be >= 1";
12589 ah_domain_error_if(ratio <= Geom_Number(0) or ratio >= Geom_Number(1, 2))
12590 << "ratio must be in (0, 0.5)";
12591
12593 for (size_t k = 0; k < iterations; ++k)
12594 cur = smooth_closed_once(cur, ratio);
12595
12596 Polygon rpoly;
12597 for (size_t i = 0; i < cur.size(); ++i)
12598 rpoly.add_vertex(cur(i));
12599 rpoly.close();
12600 return rpoly;
12601 }
12602};
12603
12604// ============================================================================
12605// Trapezoidal Map Point Location
12606// ============================================================================
12607
12661{
12662public:
12663 static constexpr size_t NONE = ~static_cast<size_t>(0);
12664
12672 {
12673 size_t top;
12674 size_t bottom;
12675 size_t leftp;
12676 size_t rightp;
12677 size_t upper_left;
12678 size_t lower_left;
12681 size_t dag_leaf;
12682 bool active;
12683 };
12684
12688 enum class NodeType
12689 {
12690 X_NODE,
12691 Y_NODE,
12692 LEAF
12693 };
12694
12698 struct DagNode
12699 {
12701 size_t index;
12702 size_t left;
12703 size_t right;
12704 };
12705
12709 enum class LocationType
12710 {
12711 TRAPEZOID,
12712 ON_SEGMENT,
12713 ON_POINT
12714 };
12715
12726
12730 struct Result
12731 {
12736 size_t dag_root;
12739
12751 [[nodiscard]] LocationResult locate(const Point &p) const
12752 {
12753 size_t ni = dag_root;
12754 while (true)
12755 {
12756 const auto &[type, index, left, right] = dag(ni);
12757 if (type == NodeType::LEAF)
12758 return {LocationType::TRAPEZOID, index, NONE, NONE};
12759
12760 if (type == NodeType::X_NODE)
12761 {
12762 const Point &xp = points(index);
12763 if (p == xp)
12764 return {LocationType::ON_POINT, NONE, NONE, index};
12765 ni = p < xp ? left : right;
12766 }
12767 else // Y_NODE
12768 {
12769 const Segment &seg = segments(index);
12770 const Geom_Number cross =
12772 if (cross == 0)
12773 {
12774 // the point is on the segment line — check if between endpoints
12775 if (seg.contains(p))
12776 return {LocationType::ON_SEGMENT, NONE, index, NONE};
12777 // collinear but outside the segment extent — go above
12778 ni = left;
12779 }
12780 else if (cross > 0)
12781 ni = left; // above (left of directed segment)
12782 else
12783 ni = right; // below
12784 }
12785 }
12786 }
12787
12798 [[nodiscard]] bool contains(const Point &p) const
12799 {
12800 // Check exact boundary / vertex hits first.
12801 for (size_t i = 0; i < num_input_points; ++i)
12802 if (p == points(i))
12803 return true;
12804 for (size_t i = 0; i < num_input_segments; ++i)
12805 if (segments(i).contains(p))
12806 return true;
12807
12808 // Vertical ray cast downward: count input segments strictly below p
12809 // whose x-range covers p.x (half-open [src.x, tgt.x)).
12810 // Segments are stored left-to-right (src < tgt), so src.x <= tgt.x.
12811 // Vertical segments have empty half-open interval and are skipped.
12812 size_t crossings = 0;
12813 for (size_t i = 0; i < num_input_segments; ++i)
12814 {
12815 const Segment &seg = segments(i);
12816 const Point &a = seg.get_src_point();
12817 const Point &b = seg.get_tgt_point();
12818 if (p.get_x() < a.get_x() or p.get_x() >= b.get_x())
12819 continue;
12820 // y of segment at p.x (b.x != a.x guaranteed by half-open check)
12821 const Geom_Number seg_y =
12822 a.get_y() + (b.get_y() - a.get_y()) * (p.get_x() - a.get_x()) / (b.get_x() - a.get_x());
12823 if (seg_y < p.get_y())
12824 ++crossings;
12825 }
12826 return crossings % 2 == 1;
12827 }
12828 };
12829
12830private:
12832 [[nodiscard]] static bool point_above_segment(const Point &p, const Segment &seg)
12833 {
12834 return area_of_parallelogram(seg.get_src_point(), seg.get_tgt_point(), p) > 0;
12835 }
12836
12838 [[nodiscard]] static size_t dag_locate(const Array<Point> &pts,
12839 const Array<Segment> &segs,
12840 const Array<DagNode> &dag,
12841 const Point &p,
12842 size_t root)
12843 {
12844 size_t ni = root;
12845 while (true)
12846 {
12847 const auto &[type, index, left, right] = dag(ni);
12848 if (type == NodeType::LEAF)
12849 return index;
12850
12851 if (type == NodeType::X_NODE)
12852 {
12853 if (const Point &xp = pts(index); p == xp)
12854 ni = right; // tie-break: go right
12855 else
12856 ni = p < xp ? left : right;
12857 }
12858 else // Y_NODE
12859 {
12860 const Geom_Number cross =
12861 area_of_parallelogram(segs(index).get_src_point(), segs(index).get_tgt_point(), p);
12862 if (cross > 0)
12863 ni = left; // above
12864 else if (cross < 0)
12865 ni = right; // below
12866 else
12867 ni = left; // on segment line → go above
12868 }
12869 }
12870 }
12871
12873 static size_t make_trapezoid(Array<Trapezoid> &traps,
12874 Array<DagNode> &dag,
12875 const size_t top,
12876 const size_t bottom,
12877 const size_t leftp,
12878 const size_t rightp)
12879 {
12880 const size_t ti = traps.size();
12881 const size_t di = dag.size();
12882 traps.append(Trapezoid{top, bottom, leftp, rightp, NONE, NONE, NONE, NONE, di, true});
12884 return ti;
12885 }
12886
12889 const size_t leaf_idx,
12890 const NodeType type,
12891 const size_t index,
12892 const size_t left,
12893 const size_t right)
12894 {
12895 dag(leaf_idx).type = type;
12896 dag(leaf_idx).index = index;
12897 dag(leaf_idx).left = left;
12898 dag(leaf_idx).right = right;
12899 }
12900
12903 const size_t neighbor_idx,
12904 const size_t old_ti,
12905 const size_t new_ti)
12906 {
12907 if (neighbor_idx == NONE)
12908 return;
12909 Trapezoid &nb = traps(neighbor_idx);
12910 if (nb.upper_left == old_ti)
12911 nb.upper_left = new_ti;
12912 if (nb.lower_left == old_ti)
12913 nb.lower_left = new_ti;
12914 if (nb.upper_right == old_ti)
12915 nb.upper_right = new_ti;
12916 if (nb.lower_right == old_ti)
12917 nb.lower_right = new_ti;
12918 }
12919
12922 [[nodiscard]] static Array<size_t> find_crossed_trapezoids(const Array<Point> &pts,
12923 const Array<Segment> &segs,
12924 const Array<Trapezoid> &traps,
12925 const size_t seg_idx,
12926 const size_t start_trap)
12927 {
12928 Array<size_t> crossed;
12929 crossed.append(start_trap);
12930
12931 const Segment &seg = segs(seg_idx);
12932 const Point &rp = seg.get_tgt_point();
12933
12934 size_t ti = start_trap;
12935 while (true)
12936 {
12937 const Trapezoid &t = traps(ti);
12938 const Point &rightp = pts(t.rightp);
12939 // If the right boundary of this trapezoid is at or past the
12940 // segment's right endpoint, we're done.
12941 if (rp < rightp or rp == rightp)
12942 break;
12943
12944 // Go right: the segment exits through the right wall of t.
12945 // If the right endpoint of the segment is above the segment
12946 // at the right boundary x, go to upper_right; else lower_right.
12947 if (t.upper_right != NONE and t.lower_right != NONE)
12948 {
12949 // Test which neighbor the segment enters.
12950 if (point_above_segment(rightp, seg))
12951 ti = t.lower_right;
12952 else
12953 ti = t.upper_right;
12954 }
12955 else if (t.upper_right != NONE)
12956 ti = t.upper_right;
12957 else if (t.lower_right != NONE)
12958 ti = t.lower_right;
12959 else
12960 break; // no right neighbor
12961
12962 crossed.append(ti);
12963 }
12964 return crossed;
12965 }
12966
12969 Array<Segment> &segs,
12970 Array<Trapezoid> &traps,
12971 Array<DagNode> &dag,
12972 const size_t seg_idx,
12973 const size_t trap_idx)
12974 {
12975 const Trapezoid old_t = traps(trap_idx);
12976 const Segment &seg = segs(seg_idx);
12977 const Point &lp = seg.get_src_point();
12978 const Point &rp = seg.get_tgt_point();
12979
12980 // Find point indices.
12981 size_t lp_idx = NONE, rp_idx = NONE;
12982 for (size_t i = 0; i < pts.size(); ++i)
12983 {
12984 if (pts(i) == lp)
12985 lp_idx = i;
12986 if (pts(i) == rp)
12987 rp_idx = i;
12988 }
12989
12990 const bool shared_left = (old_t.leftp == lp_idx);
12991 const bool shared_right = (old_t.rightp == rp_idx);
12992
12993 // Deactivate old trapezoid.
12994 traps(trap_idx).active = false;
12995
12996 // Create new trapezoids:
12997 // A = left of lp (if not shared)
12998 // B = above segment (between lp and rp)
12999 // C = below segment (between lp and rp)
13000 // D = right of rp (if not shared)
13001
13002 const size_t dag_old = old_t.dag_leaf;
13003
13004 size_t a_idx = NONE, d_idx = NONE;
13005
13006 if (not shared_left)
13007 a_idx = make_trapezoid(traps, dag, old_t.top, old_t.bottom, old_t.leftp, lp_idx);
13008 const size_t b_idx = make_trapezoid(traps, dag, old_t.top, seg_idx, lp_idx, rp_idx);
13009 const size_t c_idx = make_trapezoid(traps, dag, seg_idx, old_t.bottom, lp_idx, rp_idx);
13010 if (not shared_right)
13011 d_idx = make_trapezoid(traps, dag, old_t.top, old_t.bottom, rp_idx, old_t.rightp);
13012
13013 // Set neighbor pointers.
13014 // A neighbors:
13015 if (a_idx != NONE)
13016 {
13017 traps(a_idx).upper_left = old_t.upper_left;
13018 traps(a_idx).lower_left = old_t.lower_left;
13019 traps(a_idx).upper_right = b_idx;
13020 traps(a_idx).lower_right = c_idx;
13021 update_neighbor(traps, old_t.upper_left, trap_idx, a_idx);
13022 update_neighbor(traps, old_t.lower_left, trap_idx, a_idx);
13023 }
13024
13025 // B neighbors:
13026 traps(b_idx).upper_left = shared_left ? old_t.upper_left : a_idx;
13027 traps(b_idx).lower_left = shared_left ? old_t.lower_left : a_idx;
13028 traps(b_idx).upper_right = shared_right ? old_t.upper_right : d_idx;
13029 traps(b_idx).lower_right = shared_right ? old_t.lower_right : d_idx;
13030
13031 // C neighbors:
13032 traps(c_idx).upper_left = shared_left ? old_t.upper_left : a_idx;
13033 traps(c_idx).lower_left = shared_left ? old_t.lower_left : a_idx;
13034 traps(c_idx).upper_right = shared_right ? old_t.upper_right : d_idx;
13035 traps(c_idx).lower_right = shared_right ? old_t.lower_right : d_idx;
13036
13037 if (shared_left)
13038 {
13039 update_neighbor(traps, old_t.upper_left, trap_idx, b_idx);
13040 update_neighbor(traps, old_t.lower_left, trap_idx, c_idx);
13041 }
13042
13043 // D neighbors:
13044 if (d_idx != NONE)
13045 {
13046 traps(d_idx).upper_left = b_idx;
13047 traps(d_idx).lower_left = c_idx;
13048 traps(d_idx).upper_right = old_t.upper_right;
13049 traps(d_idx).lower_right = old_t.lower_right;
13050 update_neighbor(traps, old_t.upper_right, trap_idx, d_idx);
13051 update_neighbor(traps, old_t.lower_right, trap_idx, d_idx);
13052 }
13053
13054 if (shared_right)
13055 {
13056 update_neighbor(traps, old_t.upper_right, trap_idx, b_idx);
13057 update_neighbor(traps, old_t.lower_right, trap_idx, c_idx);
13058 }
13059
13060 // Build DAG sub-tree rooted at dag_old.
13061 // Structure depends on shared_left / shared_right.
13062 if (not shared_left and not shared_right)
13063 {
13064 // X(lp) -> left=A, right=X(rp) -> left=Y(seg)->above=B,below=C, right=D
13065 const size_t y_node = dag.size();
13066 dag.append(DagNode{NodeType::Y_NODE, seg_idx, traps(b_idx).dag_leaf, traps(c_idx).dag_leaf});
13067 const size_t x_rp = dag.size();
13068 dag.append(DagNode{NodeType::X_NODE, rp_idx, y_node, traps(d_idx).dag_leaf});
13069 replace_leaf(dag, dag_old, NodeType::X_NODE, lp_idx, traps(a_idx).dag_leaf, x_rp);
13070 }
13071 else if (shared_left and not shared_right)
13072 {
13073 // Y(seg) -> above=B, below=C wrapped in X(rp)->left=Y, right=D
13074 const size_t y_node = dag.size();
13075 dag.append(DagNode{NodeType::Y_NODE, seg_idx, traps(b_idx).dag_leaf, traps(c_idx).dag_leaf});
13076 replace_leaf(dag, dag_old, NodeType::X_NODE, rp_idx, y_node, traps(d_idx).dag_leaf);
13077 }
13078 else if (not shared_left and shared_right)
13079 {
13080 // X(lp) -> left=A, right=Y(seg)->above=B, below=C
13081 const size_t y_node = dag.size();
13082 dag.append(DagNode{NodeType::Y_NODE, seg_idx, traps(b_idx).dag_leaf, traps(c_idx).dag_leaf});
13083 replace_leaf(dag, dag_old, NodeType::X_NODE, lp_idx, traps(a_idx).dag_leaf, y_node);
13084 }
13085 else // both shared
13086 {
13087 // Just Y(seg) -> above=B, below=C
13088 replace_leaf(dag, dag_old, NodeType::Y_NODE, seg_idx, traps(b_idx).dag_leaf,
13089 traps(c_idx).dag_leaf);
13090 }
13091 }
13092
13095 Array<Segment> &segs,
13096 Array<Trapezoid> &traps,
13097 Array<DagNode> &dag,
13098 const size_t seg_idx,
13099 const Array<size_t> &crossed)
13100 {
13101 const Segment &seg = segs(seg_idx);
13102 const Point &lp = seg.get_src_point();
13103 const Point &rp = seg.get_tgt_point();
13104
13105 size_t lp_idx = NONE, rp_idx = NONE;
13106 for (size_t i = 0; i < pts.size(); ++i)
13107 {
13108 if (pts(i) == lp)
13109 lp_idx = i;
13110 if (pts(i) == rp)
13111 rp_idx = i;
13112 }
13113
13114 const size_t nc = crossed.size();
13115
13116 // For each crossed trapezoid, create above/below sub-trapezoids.
13117 // Adjacent above (or below) trapezoids that share the same top (or
13118 // bottom) segment are merged.
13119 Array<size_t> above_traps; // one per crossed, but may be merged
13120 Array<size_t> below_traps;
13121 above_traps.reserve(nc);
13122 below_traps.reserve(nc);
13123
13124 size_t prev_above = NONE, prev_below = NONE;
13125 size_t left_trap = NONE; // left-of-lp trapezoid
13126
13127 for (size_t ci = 0; ci < nc; ++ci)
13128 {
13129 const size_t ti = crossed(ci);
13130 const Trapezoid old_t = traps(ti);
13131 traps(ti).active = false;
13132
13133 const bool is_first = (ci == 0);
13134 const bool is_last = (ci == nc - 1);
13135 const bool shared_left = is_first and (old_t.leftp == lp_idx);
13136 const bool shared_right = is_last and (old_t.rightp == rp_idx);
13137
13138 // Determine the left/right x-boundaries for the new sub-trapezoids.
13139 const size_t new_leftp = is_first ? lp_idx : old_t.leftp;
13140 const size_t new_rightp = is_last ? rp_idx : old_t.rightp;
13141
13142 // Above trapezoid.
13143 bool merged_above = false;
13144 if (prev_above != NONE and traps(prev_above).top == old_t.top)
13145 {
13146 // Merge: extend prev_above to the right.
13147 traps(prev_above).rightp = new_rightp;
13148 above_traps.append(prev_above);
13149 merged_above = true;
13150 }
13151 else
13152 {
13153 const size_t ai = make_trapezoid(traps, dag, old_t.top, seg_idx, new_leftp, new_rightp);
13154 above_traps.append(ai);
13155 prev_above = ai;
13156 }
13157
13158 // Below trapezoid.
13159 bool merged_below = false;
13160 if (prev_below != NONE and traps(prev_below).bottom == old_t.bottom)
13161 {
13162 traps(prev_below).rightp = new_rightp;
13163 below_traps.append(prev_below);
13164 merged_below = true;
13165 }
13166 else
13167 {
13168 const size_t bi =
13169 make_trapezoid(traps, dag, seg_idx, old_t.bottom, new_leftp, new_rightp);
13170 below_traps.append(bi);
13171 prev_below = bi;
13172 }
13173
13174 const size_t cur_above = above_traps(ci);
13175 const size_t cur_below = below_traps(ci);
13176
13177 // Handle the left trapezoid (only for the first crossed trapezoid).
13178 if (is_first and not shared_left)
13179 {
13180 left_trap = make_trapezoid(traps, dag, old_t.top, old_t.bottom, old_t.leftp, lp_idx);
13181 traps(left_trap).upper_left = old_t.upper_left;
13182 traps(left_trap).lower_left = old_t.lower_left;
13183 traps(left_trap).upper_right = cur_above;
13184 traps(left_trap).lower_right = cur_below;
13185 update_neighbor(traps, old_t.upper_left, ti, left_trap);
13186 update_neighbor(traps, old_t.lower_left, ti, left_trap);
13187 }
13188
13189 // Set left neighbors for above/below.
13190 if (is_first)
13191 {
13192 if (not merged_above)
13193 {
13194 if (shared_left)
13195 {
13196 traps(cur_above).upper_left = old_t.upper_left;
13197 traps(cur_above).lower_left = old_t.lower_left;
13198 update_neighbor(traps, old_t.upper_left, ti, cur_above);
13199 }
13200 else
13201 {
13202 traps(cur_above).upper_left = left_trap;
13203 traps(cur_above).lower_left = left_trap;
13204 }
13205 }
13206 if (not merged_below)
13207 {
13208 if (shared_left)
13209 {
13210 traps(cur_below).upper_left = old_t.upper_left;
13211 traps(cur_below).lower_left = old_t.lower_left;
13212 update_neighbor(traps, old_t.lower_left, ti, cur_below);
13213 }
13214 else
13215 {
13216 traps(cur_below).upper_left = left_trap;
13217 traps(cur_below).lower_left = left_trap;
13218 }
13219 }
13220 }
13221 else
13222 {
13223 // Interior crossed trapezoid.
13224 if (not merged_above)
13225 {
13226 // Left neighbor of new above is the previous above.
13227 traps(cur_above).upper_left = above_traps(ci - 1);
13228 traps(cur_above).lower_left = above_traps(ci - 1);
13229 // Also set the previous above's right neighbors.
13230 if (above_traps(ci - 1) != cur_above)
13231 {
13232 traps(above_traps(ci - 1)).upper_right = cur_above;
13233 traps(above_traps(ci - 1)).lower_right = cur_above;
13234 }
13235 }
13236 if (not merged_below)
13237 {
13238 traps(cur_below).upper_left = below_traps(ci - 1);
13239 traps(cur_below).lower_left = below_traps(ci - 1);
13240 if (below_traps(ci - 1) != cur_below)
13241 {
13242 traps(below_traps(ci - 1)).upper_right = cur_below;
13243 traps(below_traps(ci - 1)).lower_right = cur_below;
13244 }
13245 }
13246
13247 // Connect left neighbors from old trapezoid.
13248 if (not merged_above)
13249 if (old_t.upper_left != NONE and old_t.upper_left != crossed(ci - 1))
13250 {
13251 traps(cur_above).upper_left = old_t.upper_left;
13252 update_neighbor(traps, old_t.upper_left, ti, cur_above);
13253 }
13254 if (not merged_below)
13255 if (old_t.lower_left != NONE and old_t.lower_left != crossed(ci - 1))
13256 {
13257 traps(cur_below).lower_left = old_t.lower_left;
13258 update_neighbor(traps, old_t.lower_left, ti, cur_below);
13259 }
13260 }
13261
13262 // Handle right trapezoid (only for last crossed trapezoid).
13263 if (is_last)
13264 {
13265 if (not shared_right)
13266 {
13267 const size_t right_trap =
13268 make_trapezoid(traps, dag, old_t.top, old_t.bottom, rp_idx, old_t.rightp);
13269 traps(right_trap).upper_left = cur_above;
13270 traps(right_trap).lower_left = cur_below;
13271 traps(right_trap).upper_right = old_t.upper_right;
13272 traps(right_trap).lower_right = old_t.lower_right;
13273 update_neighbor(traps, old_t.upper_right, ti, right_trap);
13274 update_neighbor(traps, old_t.lower_right, ti, right_trap);
13275 traps(cur_above).upper_right = right_trap;
13276 traps(cur_above).lower_right = right_trap;
13277 traps(cur_below).upper_right = right_trap;
13278 traps(cur_below).lower_right = right_trap;
13279
13280 // Build DAG for this trapezoid.
13281 const size_t y_node = dag.size();
13282 dag.append(DagNode{NodeType::Y_NODE, seg_idx, traps(cur_above).dag_leaf,
13283 traps(cur_below).dag_leaf});
13284 const size_t dag_old = old_t.dag_leaf;
13285 replace_leaf(dag, dag_old, NodeType::X_NODE, rp_idx, y_node,
13286 traps(right_trap).dag_leaf);
13287 }
13288 else
13289 {
13290 traps(cur_above).upper_right = old_t.upper_right;
13291 traps(cur_above).lower_right = old_t.lower_right;
13292 traps(cur_below).upper_right = old_t.upper_right;
13293 traps(cur_below).lower_right = old_t.lower_right;
13294 update_neighbor(traps, old_t.upper_right, ti, cur_above);
13295 update_neighbor(traps, old_t.lower_right, ti, cur_below);
13296
13297 // Build DAG for this trapezoid.
13298 const size_t dag_old = old_t.dag_leaf;
13299 replace_leaf(dag, dag_old, NodeType::Y_NODE, seg_idx, traps(cur_above).dag_leaf,
13300 traps(cur_below).dag_leaf);
13301 }
13302 }
13303 else if (is_first)
13304 {
13305 // First but not last — build DAG with X-node for left endpoint.
13306 const size_t dag_old = old_t.dag_leaf;
13307 const size_t y_node = dag.size();
13308 dag.append(DagNode{NodeType::Y_NODE, seg_idx, traps(cur_above).dag_leaf,
13309 traps(cur_below).dag_leaf});
13310 if (shared_left)
13311 replace_leaf(dag, dag_old, NodeType::Y_NODE, seg_idx, traps(cur_above).dag_leaf,
13312 traps(cur_below).dag_leaf);
13313 else
13314 replace_leaf(dag, dag_old, NodeType::X_NODE, lp_idx, traps(left_trap).dag_leaf, y_node);
13315 }
13316 else
13317 {
13318 // Middle trapezoid — just a Y-node.
13319 const size_t dag_old = old_t.dag_leaf;
13320 replace_leaf(dag, dag_old, NodeType::Y_NODE, seg_idx, traps(cur_above).dag_leaf,
13321 traps(cur_below).dag_leaf);
13322 }
13323 }
13324 }
13325
13326public:
13335 [[nodiscard]] Result operator () (const Array<Segment> &input_segments) const
13336 {
13337 Result ret;
13338 const size_t n = input_segments.size();
13339 ret.num_input_segments = n;
13340
13341 // Collect unique points from segments.
13342 // Orient all segments left-to-right (src < tgt lexicographically).
13343 ret.segments.reserve(n + 2);
13344 for (size_t i = 0; i < n; ++i)
13345 {
13346 const Point &s = input_segments(i).get_src_point();
13347 const Point &t = input_segments(i).get_tgt_point();
13348 ah_domain_error_if(s == t) << "Degenerate segment (src == tgt) at index " << i;
13349 if (s < t)
13350 ret.segments.append(Segment(s, t));
13351 else
13352 ret.segments.append(Segment(t, s));
13353 }
13354
13355 // Collect and deduplicate points.
13356 {
13357 Array<Point> all_pts;
13358 all_pts.reserve(2 * n);
13359 for (size_t i = 0; i < n; ++i)
13360 {
13361 all_pts.append(ret.segments(i).get_src_point());
13362 all_pts.append(ret.segments(i).get_tgt_point());
13363 }
13364 // Sort lexicographically.
13365 in_place_sort(all_pts);
13366 // Deduplicate.
13367 for (size_t i = 0; i < all_pts.size(); ++i)
13368 {
13369 if (ret.points.is_empty() or not (ret.points(ret.points.size() - 1) == all_pts(i)))
13370 ret.points.append(all_pts(i));
13371 }
13372 }
13373
13374 ret.num_input_points = ret.points.size();
13375
13376 // Compute bounding box with margin.
13377 if (ret.points.is_empty())
13378 {
13379 // No input segments: create a trivial bounding box.
13380 ret.points.append(Point(-1, -1));
13381 ret.points.append(Point(1, -1));
13382 ret.points.append(Point(1, 1));
13383 ret.points.append(Point(-1, 1));
13384 }
13385
13386 Geom_Number mnx = ret.points(0).get_x();
13387 Geom_Number mxx = mnx;
13388 Geom_Number mny = ret.points(0).get_y();
13389 Geom_Number mxy = mny;
13390 for (size_t i = 1; i < ret.points.size(); ++i)
13391 {
13392 if (ret.points(i).get_x() < mnx)
13393 mnx = ret.points(i).get_x();
13394 if (ret.points(i).get_x() > mxx)
13395 mxx = ret.points(i).get_x();
13396 if (ret.points(i).get_y() < mny)
13397 mny = ret.points(i).get_y();
13398 if (ret.points(i).get_y() > mxy)
13399 mxy = ret.points(i).get_y();
13400 }
13401
13402 Geom_Number margin = (mxx - mnx > mxy - mny) ? mxx - mnx : mxy - mny;
13403 if (margin == 0)
13404 margin = 1;
13405 margin = margin + 1;
13406
13407 // Bounding box corner points.
13408 const Point bl(mnx - margin, mny - margin);
13409 const Point br(mxx + margin, mny - margin);
13410 const Point tl(mnx - margin, mxy + margin);
13411 const Point tr(mxx + margin, mxy + margin);
13412
13413 const size_t bl_idx = ret.points.size();
13414 ret.points.append(bl);
13415 ret.points.append(br);
13416 ret.points.append(tl);
13417 const size_t tr_idx = ret.points.size();
13418 ret.points.append(tr);
13419
13420 // Bounding box segments: top (tl→tr) and bottom (bl→br).
13421 const size_t top_seg = ret.segments.size();
13422 ret.segments.append(Segment(tl, tr));
13423 const size_t bot_seg = ret.segments.size();
13424 ret.segments.append(Segment(bl, br));
13425
13426 // Initialize: one trapezoid spanning the bounding box.
13427 ret.dag_root = 0;
13428 const size_t t0 = make_trapezoid(ret.trapezoids, ret.dag, top_seg, bot_seg, bl_idx, tr_idx);
13429 (void) t0;
13430
13431 // Randomized insertion order.
13432 if (n == 0)
13433 return ret;
13434
13435 Array<size_t> order;
13436 order.reserve(n);
13437 for (size_t i = 0; i < n; ++i)
13438 order.append(i);
13439
13440 // Fisher-Yates shuffle.
13441 {
13442 std::random_device rd;
13443 std::mt19937 gen(rd());
13444 for (size_t i = n - 1; i > 0; --i)
13445 {
13446 std::uniform_int_distribution<size_t> dis(0, i);
13447 const size_t j = dis(gen);
13448 const size_t tmp = order(i);
13449 order(i) = order(j);
13450 order(j) = tmp;
13451 }
13452 }
13453
13454 // Insert segments one by one.
13455 for (size_t oi = 0; oi < n; ++oi)
13456 {
13457 const size_t si = order(oi);
13458 const Segment &seg = ret.segments(si);
13459
13460 // Locate the trapezoid containing the left endpoint.
13461 const size_t start =
13462 dag_locate(ret.points, ret.segments, ret.dag, seg.get_src_point(), ret.dag_root);
13463
13464 // Find all trapezoids crossed by this segment.
13465 Array<size_t> crossed =
13466 find_crossed_trapezoids(ret.points, ret.segments, ret.trapezoids, si, start);
13467
13468 if (crossed.size() == 1)
13469 split_single_trapezoid(ret.points, ret.segments, ret.trapezoids, ret.dag, si, crossed(0));
13470 else
13471 split_multiple_trapezoids(ret.points, ret.segments, ret.trapezoids, ret.dag, si, crossed);
13472 }
13473
13474 return ret;
13475 }
13476
13483 [[nodiscard]] Result operator () (const Polygon &polygon) const
13484 {
13485 ah_domain_error_if(not polygon.is_closed()) << "Polygon must be closed";
13486 ah_domain_error_if(polygon.size() < 3) << "Polygon must have at least 3 vertices";
13487
13488 Array<Segment> segs;
13489 for (Polygon::Segment_Iterator it(polygon); it.has_curr(); it.next_ne())
13490 segs.append(it.get_current_segment());
13491 return (*this)(segs);
13492 }
13493
13500 [[nodiscard]] Result operator () (const Array<Polygon> &polygons) const
13501 {
13502 Array<Segment> segs;
13503 for (size_t i = 0; i < polygons.size(); ++i)
13504 {
13505 const Polygon &poly = polygons(i);
13506 ah_domain_error_if(not poly.is_closed()) << "Polygon " << i << " must be closed";
13507 ah_domain_error_if(poly.size() < 3) << "Polygon " << i << " must have at least 3 vertices";
13508 for (Polygon::Segment_Iterator it(poly); it.has_curr(); it.next_ne())
13509 segs.append(it.get_current_segment());
13510 }
13511 return (*this)(segs);
13512 }
13513};
13514
13515// ============================================================================
13516// GeomNumber Concept (C++20)
13517// ============================================================================
13518
13519#if __cplusplus >= 202002L
13520
13521#include <concepts>
13522
13544template <typename T>
13545concept GeomNumberType = requires(T a, T b, int i) {
13546 { T(i) } -> std::convertible_to<T>;
13547 { a + b } -> std::convertible_to<T>;
13548 { a - b } -> std::convertible_to<T>;
13549 { a * b } -> std::convertible_to<T>;
13550 { a / b } -> std::convertible_to<T>;
13551 { a == b } -> std::convertible_to<bool>;
13552 { a != b } -> std::convertible_to<bool>;
13553 { a < b } -> std::convertible_to<bool>;
13554 { a <= b } -> std::convertible_to<bool>;
13555 { a > b } -> std::convertible_to<bool>;
13556 { a >= b } -> std::convertible_to<bool>;
13557 { -a } -> std::convertible_to<T>;
13558};
13559
13560// Verify that Geom_Number satisfies the concept.
13561static_assert(GeomNumberType<Geom_Number>, "Geom_Number must satisfy GeomNumberType");
13562static_assert(GeomNumberType<double>, "double must satisfy GeomNumberType");
13563static_assert(GeomNumberType<long long>, "long long must satisfy GeomNumberType");
13564
13565#endif // C++20
13566} // namespace Aleph
13567
13568#endif // GEOM_ALGORITHMS_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
bool operator==(const Time &l, const Time &r)
Definition ah-time.H:134
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
Deduplicate sequential Aleph containers in-place.
long double h
Definition btreepic.C:154
static int cell(const aleph_ca_engine_t *e, size_t r, size_t c)
Definition c_abi_smoke.c:53
size_t steps
Definition ca-c-api.h:126
size_t size_t int32_t * out
Definition ca-c-api.h:120
Axis-aligned bounding box tree for spatial queries.
Rectangle root_bbox() const
Return the root bounding box (union of all entries).
AABBTree(AABBTree &&other) noexcept
Take the entries and the nodes of another tree, which is left empty.
Array< Entry > entries_
Original entries stored in the tree.
size_t build(Array< size_t > &idx, const size_t lo, const size_t hi)
AABBTree(const AABBTree &other)=default
Copy the entries and the nodes of another tree.
void select_kth_by_center(Array< size_t > &idx, size_t lo, size_t hi, const size_t kth, const bool split_x) const
static bool box_contains_point(const Rectangle &r, const Point &p)
Checks if a rectangle contains a point.
static Rectangle union_bbox(const Rectangle &a, const Rectangle &b)
Computes the union of two axis-aligned bounding boxes.
void swap(AABBTree &other) noexcept
Exchange in O(1) the entries and the nodes of this tree and another.
void query_point_impl(const size_t ni, const Point &p, Array< size_t > &results) const
Geom_Number center_coord(const size_t entry_idx, const bool split_x) const
AABBTree()=default
bool is_empty() const
Whether the tree is empty.
size_t size() const
Number of entries.
void insertion_sort_by_center(Array< size_t > &idx, const size_t lo, const size_t hi, const bool split_x) const
static constexpr size_t NONE
void build(const Array< Entry > &entries)
Build the AABB tree from an array of entries.
DebugSnapshot debug_snapshot() const
Return the full tree structure for visualization/debug.
static bool boxes_overlap(const Rectangle &a, const Rectangle &b)
Checks if two rectangles overlap.
Array< size_t > query(const Rectangle &query) const
Find all entries whose bounding box overlaps the query rectangle.
Array< size_t > query_point(const Point &p) const
Find all entries whose bounding box contains the query point.
Array< Node > nodes_
Internal array storing tree nodes.
AABBTree & operator=(AABBTree &&other) noexcept
Exchange this tree with another, which is left with the previous entries of this one.
AABBTree & operator=(const AABBTree &other)=default
Copy the entries and the nodes of another tree.
void query_impl(const size_t ni, const Rectangle &q, Array< size_t > &results) const
Alpha shape of a point set.
Result operator()(const DynList< Point > &points, const Geom_Number &alpha_squared) const
Compute the α-shape.
Andrew's monotonic chain convex hull algorithm.
Polygon operator()(const DynList< Point > &point_set) const
Compute the convex hull of a point set.
static Array< Point > sorted_unique_points(const DynList< Point > &point_set)
Extracts points from a list, sorts them and removes duplicates.
static Geom_Number turn(const Point &a, const Point &b, const Point &c)
Computes the turn orientation of triple (a, b, c).
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
Definition tpl_array.H:194
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void empty() noexcept
Empties the container.
Definition tpl_array.H:426
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
T & insert(const T &data)
insert a copy of data at the beginning of the array.
Definition tpl_array.H:368
T & get_last()
Return a modifiable reference to the last element.
Definition tpl_array.H:483
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Quadratic and cubic Bézier curves with exact rational arithmetic.
static Polygon approximate_quadratic(const Point &p0, const Point &p1, const Point &p2, const size_t n)
Approximate a quadratic Bézier as a polyline (polygon without closing).
static Array< Point > sample_cubic(const Point &p0, const Point &p1, const Point &p2, const Point &p3, const size_t n)
Sample a cubic Bézier into n+1 points.
static Rectangle control_bbox(const Point &p0, const Point &p1, const Point &p2, const Point &p3)
Compute the bounding box of a cubic Bézier's control polygon.
static Array< Point > sample_quadratic(const Point &p0, const Point &p1, const Point &p2, const size_t n)
Sample a quadratic Bézier into n+1 points (t = 0, 1/n, ..., 1).
static SplitResult split_cubic(const Point &p0, const Point &p1, const Point &p2, const Point &p3, const Geom_Number &t)
static Point quadratic(const Point &p0, const Point &p1, const Point &p2, const Geom_Number &t)
Evaluate a quadratic Bézier at parameter t.
static Polygon approximate_cubic(const Point &p0, const Point &p1, const Point &p2, const Point &p3, const size_t n)
Approximate a cubic Bézier as a polyline.
static Point cubic(const Point &p0, const Point &p1, const Point &p2, const Point &p3, const Geom_Number &t)
Evaluate a cubic Bézier at parameter t.
Boolean operations on simple polygons (union, intersection, difference) using the Greiner-Hormann alg...
static void sort_indices_by_alpha(Array< size_t > &idx, const Array< Geom_Number > &keys)
Insertion-sort indices by a key array.
static Array< Point > extract(const Polygon &p)
Extract vertices from a polygon into an Array.
static void reverse_array(Array< Point > &v)
Reverse a vertex array in place.
static Geom_Number edge_param(const Point &P, const Point &Q, const Point &I)
Compute parameter t of point I along directed edge P→Q.
static Array< Polygon > compute_union(const Polygon &a, const Polygon &b)
Computes the union of two polygons.
Array< Polygon > difference(const Polygon &a, const Polygon &b) const
Convenience: difference (a minus b).
Array< Polygon > polygon_union(const Polygon &a, const Polygon &b) const
Convenience: union.
Array< Polygon > intersection(const Polygon &a, const Polygon &b) const
Convenience: intersection.
Array< Polygon > operator()(const Polygon &a, const Polygon &b, Op op) const
Compute a boolean operation on two simple polygons.
static bool point_inside_ccw(const Array< Point > &poly, const Point &p)
Point-in-polygon test on a CCW vertex array (winding number).
static Array< Polygon > greiner_hormann(const Array< Point > &va, const Array< Point > &vb, bool start_entering)
Run Greiner-Hormann and return result polygons.
Op
Type of Boolean operation to perform.
@ INTERSECTION
Find regions common to both polygons.
@ DIFFERENCE
Find regions in the first polygon not covered by the second.
@ UNION
Find regions covered by either polygon.
static Polygon build_poly(const Array< Point > &pts)
Build a polygon from a vertex array (bypasses colinearity merge).
static Array< Polygon > compute_difference(const Polygon &a, const Polygon &b)
Computes the difference (A \ B) of two polygons.
static void ensure_ccw(Array< Point > &v)
Ensure vertices are in CCW order.
static Array< Polygon > compute_intersection(const Polygon &a, const Polygon &b)
Computes the intersection of two polygons.
Brute force convex hull algorithm.
static SegmentSet extreme_edges(const DynList< Point > &point_set)
Finds the extreme edges of a point set (edges that form the convex hull).
Polygon operator()(const DynList< Point > &point_set) const
Compute the convex hull of a point set.
static bool are_all_points_on_left(const DynList< Point > &l, const Segment &s)
Checks if all points in a list lie to the left of a segment.
Chaikin corner-cutting subdivision for polygon smoothing.
static Array< Point > smooth_closed_once(const Array< Point > &pts, const Geom_Number &r)
static Polygon smooth_polygon(const Polygon &poly, size_t iterations, const Geom_Number &ratio=Geom_Number(1, 4))
Smooth a closed polygon.
Array< Point > operator()(const Array< Point > &polyline, size_t iterations, const Geom_Number &ratio=Geom_Number(1, 4)) const
Smooth an open polyline.
static Array< Point > smooth_open_once(const Array< Point > &pts, const Geom_Number &r)
Closest pair of points via divide and conquer.
static Result make_result(const Point &a, const Point &b)
Construct a Result object for a pair (a,b).
static Result brute_force(const Array< Point > &px, const size_t l, const size_t r)
Brute-force closest pair on a small subarray.
static Geom_Number dist2(const Point &a, const Point &b)
Squared Euclidean distance between two points.
Result operator()(const DynList< Point > &point_set) const
Compute the closest pair of points.
Segment closest_segment(DynList< Point > &point_set) const
Convenience wrapper returning the closest segment.
static Result recurse(const Array< Point > &px, const size_t l, const size_t r, Array< Point > &py)
Recursive divide-and-conquer step.
Constrained Delaunay Triangulation via Sloan's flip-based method.
static void flip_edge(Array< Tri > &tris, const size_t tri_a, const size_t tri_b)
Flip the diagonal of the quad formed by tri_a and tri_b.
static bool lexicographic_less(const Point &p1, const Point &p2)
static Array< Point > merge_and_deduplicate(const DynList< Point > &points, const DynList< Segment > &constraints)
Merge input points, constraint endpoints, and constraint-constraint intersection points; then dedupli...
static size_t adj_of(const Tri &t, const size_t n)
Return the local index of the edge shared with neighbor n.
static bool edge_exists(const Array< Tri > &tris, const size_t u, const size_t v, size_t &out_tri, size_t &out_local)
Check if edge (u,v) already exists in the mesh.
static void build_adjacency(Array< Tri > &tris, const Array< IndexedTriangle > &dt_tris)
Build adjacency mesh from DT output.
static Array< IndexedEdge > map_constraints(const Array< Point > &sites, const DynList< Segment > &constraints)
Split constraints at interior collinear points.
static bool is_convex_quad(const Array< Point > &pts, const size_t a, const size_t b, const size_t c, const size_t d)
True if diagonal (a,d) in quad (a,b,d) + (a,d,c) forms a convex quad.
static void lawson_flip(const Array< Point > &pts, Array< Tri > &tris)
Lawson flip pass: restore Delaunay for non-constrained edges.
static void mark_constrained(Array< Tri > &tris, const size_t u, const size_t v)
Mark edge (u,v) as constrained in the mesh.
static void enforce_constraint(Array< Point > &pts, Array< Tri > &tris, const size_t u, const size_t v)
Enforce a single constraint edge (u,v) using Sloan's flip approach.
static DynList< Triangle > as_triangles(const Result &result)
Convert indexed triangulation to geometric triangles.
static size_t find_point_index(const Array< Point > &pts, const Point &p)
Find index of point p in sorted unique array, or NONE.
static size_t local_of(const Tri &t, const size_t id)
Return local index (0,1,2) of vertex id in triangle t, or NONE.
static Array< CrossingEdge > find_crossing_edges(const Array< Point > &pts, const Array< Tri > &tris, const size_t u, const size_t v)
static size_t edge_opposite(const Tri &t, const size_t a, const size_t b)
Return the local edge index for edge (a,b) in triangle t.
Decompose a simple polygon into convex parts using Hertel-Mehlhorn.
static Array< Point > extract_vertices(const Polygon &p)
static size_t find_pos(const Array< size_t > &face, size_t v)
Array< Polygon > operator()(const Polygon &poly) const
Decompose polygon poly into convex parts.
static bool can_merge(const Array< Point > &pts, const Array< size_t > &f1, const Array< size_t > &f2, size_t u, size_t v)
Check whether merging faces f1 and f2 across diagonal (u,v) is convex.
static Array< size_t > merge_faces(const Array< size_t > &f1, const Array< size_t > &f2, size_t u, size_t v)
Merge f1 and f2 by removing their shared edge (u,v).
static bool is_polygon_edge(size_t u, size_t v, size_t n)
Distance between two closed convex polygons using GJK.
Result operator()(const Polygon &p, const Polygon &q) const
Compute the distance between two closed convex polygons.
static Result exact_refine_disjoint(const Polygon &p, const Polygon &q, const Array< Point > &pv, const Array< Point > &qv)
static double norm2(const double x, const double y) noexcept
static ClosestSimplexResult closest_from_simplex(const std::vector< SupportPoint > &simplex)
static constexpr size_t kMaxIters
static double dot2(const double ax, const double ay, const double bx, const double by) noexcept
static Point point_from_double(const double x, const double y)
static bool polygons_intersect_or_contain(const Polygon &p, const Polygon &q)
static SupportPoint support(const Array< Point > &p, const Array< Point > &q, const double dx, const double dy)
static Point lerp_point(const Point &a, const Point &b, const double t)
static double to_double(const Geom_Number &v)
static Point centroid_of(const Array< Point > &v)
Basic exact intersection for closed convex polygons.
Polygon operator()(const Polygon &subject, const Polygon &clip) const
Intersect two closed convex polygons.
static Array< Point > normalize_vertices(const Array< Point > &pts)
static Point line_intersection(const Point &s, const Point &e, const Point &a, const Point &b)
static Geom_Number signed_double_area(const Array< Point > &verts)
static bool inside_half_plane(const Point &p, const Point &a, const Point &b, const bool clip_ccw)
static Array< Point > extract_vertices(const Polygon &poly)
static void push_clean(Array< Point > &out, const Point &p)
static Polygon build_polygon(const Array< Point > &pts)
static bool is_convex(const Array< Point > &verts)
Inward (erosion) and outward (dilation) offset of convex polygons.
static Point line_intersect(const Point &a1, const Point &a2, const Point &b1, const Point &b2)
Line-line intersection of (a1,a2) and (b1,b2).
static bool is_convex(const Array< Point > &v)
static void ensure_ccw(Array< Point > &v)
static Geom_Number signed_double_area(const Array< Point > &v)
static void offset_edge(const Point &a, const Point &b, const Geom_Number &d, const bool inward, Point &oa, Point &ob)
Compute two points on the offset line of edge (a, b) moved by distance d along its outward (or inward...
static Polygon outward(const Polygon &convex_poly, const Geom_Number &distance)
Outward offset (dilation) of a convex polygon.
static Array< Point > extract_verts(const Polygon &poly)
static Polygon inward(const Polygon &convex_poly, const Geom_Number &distance)
Inward offset (erosion) of a convex polygon.
Polygon triangulation using the ear-cutting algorithm.
static Geom_Number signed_double_area(const Polygon &p)
static Array< Point > extract_vertices(const Polygon &p)
static bool diagonal(const Polygon &p, const Vertex &a, const Vertex &b)
Check if segment (a, b) is a valid internal diagonal.
static EarsSet init_ears(const Polygon &p)
Initialize the set of ear vertices.
static void normalize_to_ccw(Polygon &p)
static bool in_cone(const Polygon &p, const Vertex &a, const Vertex &b)
Check if vertex b is inside the cone formed at vertex a.
static bool diagonalize(const Polygon &p, const Segment &s)
Check if a segment is a valid diagonal of the polygon.
DynList< Triangle > operator()(const Polygon &poly) const
Triangulate the polygon.
Exact Delaunay triangulation using the Bowyer-Watson incremental algorithm.
static bool all_collinear(const Array< Point > &pts)
Check if all points in an array are collinear.
Result operator()(const DynList< Point > &point_set) const
Compute Delaunay triangulation of a point set.
static bool point_in_circumcircle(const Array< Point > &pts, const size_t ia, const size_t ib, const size_t ic, const size_t ip)
Predicate to check if a point lies inside the circumcircle of a triangle.
static DynList< Triangle > as_triangles(const Result &result)
Convert indexed triangulation to geometric triangles.
static Array< Point > unique_points(const DynList< Point > &point_set)
Extracts unique points from a list and sorts them lexicographically.
static bool lexicographic_less(const Point &p1, const Point &p2)
Lexicographical comparison for points.
O(n log n) expected-time Delaunay's triangulation.
static bool in_cc(const Array< Point > &pts, const size_t ia, const size_t ib, const size_t ic, const size_t ip)
Standard in-circumcircle test using exact in_circle_determinant.
static void remap_adj(Array< Tri > &tris, const size_t ot, const size_t nt)
Update neighbor n of the old triangle ot to point to a new triangle nt.
static bool point_in_tri(const Array< Point > &pts, const Tri &t, const size_t pidx)
True if point p is inside or on triangle t (using orientation tests).
static size_t adj_of(const Tri &t, const size_t n)
Return the local index of the edge shared with neighbor n.
static size_t locate(const Array< Point > &pts, const Array< Tri > &tris, const Array< DagNode > &dag, const size_t pidx, const size_t root)
Locate the leaf triangle containing point pidx via a DAG walk.
static size_t local_of(const Tri &t, const size_t id)
Return local index (0,1,2) of vertex id in triangle t, or NONE.
Result operator()(const DynList< Point > &point_set) const
Computes the Delaunay triangulation of a set of points.
Douglas-Peucker polyline simplification.
static void dp_recurse(const Array< Point > &pts, const size_t first, const size_t last, const Geom_Number &eps2, Array< bool > &keep)
Polygon simplify_polygon(const Polygon &poly, const Geom_Number &epsilon) const
Simplify a closed polygon.
Array< Point > operator()(const Array< Point > &polyline, const Geom_Number &epsilon) const
Simplify an open polyline.
Dynamic heap of elements of type T ordered by a comparison functor.
T get()
Alias for getMin().
T & put(const T &item)
Synonym of insert().
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
T & get_first()
Return a modifiable reference to first item in the list.
T remove_first()
Remove the first item of the list; return a copy of removed item.
T & append(const T &item)
Append a copied item at the end of the list.
T & get_last()
Return a modifiable reference to last item in the list.
T remove_last()
Remove the last item of the list; return a copy of removed item.
Iterator on the items of list.
Definition htlist.H:1614
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
void concat(DynList &l) noexcept
Append the items of l to this, in constant time; l becomes empty.
Definition htlist.H:1947
T & get_last()
Return the last item of the list.
Definition htlist.H:1529
T remove_first()
See remove().
Definition htlist.H:1473
Dynamic set backed by balanced binary search trees with automatic memory management.
long position(const Key &key) const
Returns the infix (ordered) position of the key.
Key remove_pos(const size_t i)
Removes the key at the inorder position i.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
size_t remove(const Key &key)
Removes a key from the dynamic set.
Key * search(const Key &key)
Find an element in the set.
bool is_empty() const
returns true if the set is empty
Very simple queue implemented with a contiguous array.
T & put(const T &item) noexcept
Put an item into the queue by copy.
constexpr bool is_empty() const noexcept
Return true if the queue is empty.
T get() noexcept
Remove the oldest item of the queue.
Fixed length stack.
size_t size() const noexcept
Return the number of elements stored in the stack.
bool is_empty() const noexcept
Return true if stack is empty.
T pop() noexcept
Pop by moving the top of stack.
T & top() noexcept
Return a modifiable reference to stack's top.
T & push(const T &data) noexcept(std::is_nothrow_copy_assignable_v< T >)
Push a copy of data
bool is_empty() const noexcept
Shared Bowyer-Watson core parameterized by in-circle predicate.
static Array< IndexedTriangle > triangulate(Array< Point > pts, const size_t n, InCirclePredicate point_in_circumcircle)
static void toggle_edge(EdgeSet &boundary, size_t u, size_t v)
Shared polygon helpers used across multiple geometry algorithms.
static Geom_Number area(const Array< Point > &verts)
Compute the absolute area of a vertex array.
static Geom_Number signed_double_area(const Polygon &poly)
Compute twice the signed area of a polygon.
static Geom_Number signed_area(const Polygon &poly)
Compute the actual signed area of a polygon.
static bool is_convex(const Array< Point > &verts)
Check if a vertex array forms a convex polygon.
static Geom_Number signed_double_area(const Array< Point > &verts)
Compute twice the signed area (shoelace formula without division).
static void ensure_ccw(Array< Point > &verts)
static Geom_Number signed_area(const Array< Point > &verts)
Compute the actual signed area of a vertex array.
static Geom_Number area(const Polygon &poly)
Compute the absolute area of a polygon.
static Array< Point > extract_vertices(const Polygon &poly)
Extract vertices from a polygon into an array for indexed access.
Serialization utilities for geometry objects.
static std::string to_geojson(const Triangle &t)
Triangle → GeoJSON Polygon.
static std::string to_wkt(const Point3D &p)
Converts a Point3D to WKT format: "POINT Z (x y z)".
static std::string to_geojson(const Polygon &poly)
Polygon → GeoJSON Polygon.
static std::string to_wkt(const Polygon &poly)
Converts a Polygon to WKT format: "POLYGON ((x1 y1, x2 y2, ..., x1 y1))".
static std::string to_wkt(const Rectangle &r)
Converts a Rectangle to WKT format: "POLYGON ((xmin ymin, xmax ymin, xmax ymax, xmin ymax,...
static std::string to_wkt(const Triangle &t)
Converts a Triangle to WKT format: "POLYGON ((x1 y1, x2 y2, x3 y3, x1 y1))".
static std::string dbl(const Geom_Number &n)
Formats a Geom_Number as a string with high precision.
static std::string to_geojson(const Segment &s)
Converts a Segment to a GeoJSON LineString.
static std::string to_wkt(const Segment &s)
Converts a Segment to WKT format: "LINESTRING (x1 y1, x2 y2)".
static std::string to_geojson(const Point &p)
Converts a Point to a GeoJSON geometry object.
static std::string to_wkt(const Point &p)
Converts a Point to WKT format: "POINT (x y)".
static std::string to_geojson(const Point3D &p)
Point3D → GeoJSON Point with Z.
Shared edge-group extraction for triangle meshes.
static void append_edge(Array< EdgeRef > &edges, size_t a, size_t b, const size_t tri, const size_t third)
static void for_each_sorted_edge_group(const TriangleArray &triangles, GroupFn on_group)
Gift wrapping (Jarvis march) convex hull algorithm.
static const Point * get_lowest_point(const DynList< Point > &point_set)
Finds the point with the minimum y-coordinate (and minimum x on ties).
Polygon operator()(const DynList< Point > &point_set) const
Compute the convex hull of a point set.
Graham scan convex hull algorithm.
static Array< Point > sorted_unique_points(const DynList< Point > &point_set)
Extracts points from a list, sorts them and removes duplicates.
static Geom_Number turn(const Point &a, const Point &b, const Point &c)
Computes the turn orientation of triple (a, b, c).
Polygon operator()(const DynList< Point > &point_set) const
Compute the convex hull of a point set.
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Exact bounded intersection of half-planes.
static Point line_intersection(const HalfPlane &a, const HalfPlane &b)
static Geom_Number cross_dir(const HalfPlane &a, const HalfPlane &b)
static Geom_Number dot_dir(const HalfPlane &a, const HalfPlane &b)
static Polygon build_polygon(const Array< Point > &pts)
static bool parallel(const HalfPlane &a, const HalfPlane &b)
static bool upper_half(const HalfPlane &h)
static Geom_Number signed_double_area(const Array< Point > &verts)
static bool same_direction(const HalfPlane &a, const HalfPlane &b)
static void push_clean(Array< Point > &out, const Point &p)
static Array< HalfPlane > from_convex_polygon(const Polygon &poly)
Build half-planes from the edges of a closed convex polygon.
static Array< Point > normalize_vertices(const Array< Point > &pts)
Polygon operator()(const Array< HalfPlane > &halfplanes) const
Intersect half-planes and return bounded feasible polygon.
Spatial point index for O(log n) nearest-neighbor queries.
DebugSnapshot debug_snapshot() const
Build a deterministic geometric partition snapshot for visualization.
Rectangle extended_bounds() const
The bounds, extended to the points outside them, as the tree extends its region to them.
bool is_empty() const noexcept
Return true if the tree is empty.
static KDTreePointSearch build(const Array< Point > &points, const Geom_Number &xmin, const Geom_Number &ymin, const Geom_Number &xmax, const Geom_Number &ymax)
Build a balanced KD-tree from a point array.
size_t size() const noexcept
Return the number of points in the tree.
bool contains(const Point &p) const
Check if a point exists in the tree.
static bool lexicographic_less(const Point &a, const Point &b)
KDTreePointSearch(const Geom_Number &xmin, const Geom_Number &ymin, const Geom_Number &xmax, const Geom_Number &ymax)
Construct an empty KD-tree for the given bounding region.
std::optional< Point > nearest(const Point &p) const
Find the nearest neighbor to query point p.
void range(const Geom_Number &xmin, const Geom_Number &ymin, const Geom_Number &xmax, const Geom_Number &ymax, DynList< Point > *out) const
Collect all points inside the given rectangle.
static Array< Point > unique_points(Array< Point > points)
bool insert(const Point &p)
Insert a point. Returns true if inserted, false if duplicate.
void for_each(Op &&op) const
Apply an operation to every point (inorder traversal).
Reusable event-driven sweep line framework.
DynSetTree< SeqEvent, Avl_Tree, CmpSeqEvent > queue_
void enqueue(Event &&e)
Enqueue an event (move version).
bool has_events() const noexcept
True if the event queue is non-empty.
Event dequeue()
Remove and return the next (minimum) event.
void enqueue(const Event &e)
Enqueue an event.
void run(Handler &&handler)
Run the sweep: process every event through handler.
size_t pending() const noexcept
Number of pending events.
void run(Handler &&handler, Array< Event > &out)
Run the sweep, collecting every event into out.
const Event & peek() const
Peek at the next event without removing it.
void clear() noexcept
Discard all pending events.
Smallest circle enclosing a point set (Welzl's algorithm).
Circle operator()(const DynList< Point > &points) const
Compute the minimum enclosing circle of a point set.
static Circle from_two_points(const Point &a, const Point &b)
Smallest circle with a and b on its boundary (diameter).
static Circle from_one_point(const Point &a)
Circle through a single point (degenerate, radius = 0).
static Circle mec_with_two_points(const Array< Point > &pts, size_t n, const Point &p1, const Point &p2)
Minimum enclosing circle with boundary points p1 and p2.
static Circle welzl_iterative(const Array< Point > &pts)
Iterative Welzl: three nested loops.
static Circle from_three_points(const Point &a, const Point &b, const Point &c)
Circumscribed circle through three points.
static Circle mec_with_point(const Array< Point > &pts, size_t n, const Point &p1)
Minimum enclosing circle with boundary point p1.
Exact Minkowski sum of two closed convex polygons.
static Array< Point > normalize(Array< Point > v)
Ensure CCW and rotate so that the bottom-most vertex is first.
static Array< Point > extract_vertices(const Polygon &poly)
static Geom_Number signed_double_area(const Array< Point > &v)
Polygon operator()(const Polygon &P, const Polygon &Q) const
Compute the Minkowski sum of two convex polygons.
static Point edge_vec(const Array< Point > &v, const size_t i)
static bool is_convex(const Array< Point > &verts)
static Geom_Number cross(const Point &a, const Point &b)
size_t left_edge_of_point(const Point &p, const Geom_Number &sweep_y) const
static void split_by_label(Node *root, const Geom_Number &label, Node *&left, Node *&right)
size_t successor_for_insert(const size_t edge, const Geom_Number &sweep_y) const
static Node * insert_by_label(Node *root, Node *node)
Geom_Number fresh_label_between(const size_t pred, const size_t succ) const
size_t predecessor_for_insert(const size_t edge, const Geom_Number &sweep_y) const
void insert(const size_t edge, const Geom_Number &sweep_y)
static Node * erase_by_label(Node *root, const Geom_Number &label, Node *&removed)
O(n log n) triangulation of simple polygons via y-monotone partition + linear-time monotone triangula...
static Geom_Number signed_double_area(const Array< Point > &v)
static void ensure_ccw(Array< Point > &v)
static bool is_below(const Point &a, const Point &b)
Lexicographical "below" comparison.
static bool is_above(const Point &a, const Point &b)
Lexicographical "above" comparison (y primary, x secondary).
static bool edge_status_less(const size_t lhs, const size_t rhs, const Geom_Number &sweep_y, const Array< Point > &verts)
static Array< Array< size_t > > build_faces_from_diagonals(const Array< Point > &verts, const DynSetTree< std::pair< size_t, size_t > > &diagonals)
VertexType
Classification of vertices for y-monotone decomposition.
static bool is_y_monotone(const Array< Point > &v)
Check if a CCW polygon vertex array is y-monotone.
static Array< Array< size_t > > decompose_to_monotone_faces(const Array< Point > &verts)
DynList< Triangle > operator()(Polygon p) const
Triangulate a simple polygon.
static DynList< Triangle > triangulate_monotone(const Array< Point > &verts)
Triangulate a y-monotone polygon given as a vertex array.
static bool edge_goes_down(const Array< Point > &verts, const size_t edge)
Check if the edge starting at edge points downwards.
static VertexType classify_vertex(const Array< Point > &v, const size_t i)
static Array< Point > extract_vertices(const Polygon &p)
static Geom_Number edge_x_at_y(const Array< Point > &verts, const size_t edge, const Geom_Number &y)
static bool regular_interior_right(const Array< Point > &v, const size_t i)
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Represents a point in 3D space with exact rational coordinates.
Definition point.H:3054
const Geom_Number & get_z() const
Gets the z-coordinate.
Definition point.H:3086
const Geom_Number & get_x() const
Gets the x-coordinate.
Definition point.H:3076
const Geom_Number & get_y() const
Gets the y-coordinate.
Definition point.H:3081
Exact point-in-polygon classification via winding number.
static bool strictly_contains(const Polygon &poly, const Point &p)
Return true only for strict interior points.
static Location locate(const Polygon &poly, const Point &p)
Classify point location with respect to a polygon.
static bool contains(const Polygon &poly, const Point &p)
Return true if the point is inside or on the boundary.
Represents a point with rectangular coordinates in a 2D plane.
Definition point.H:221
const Geom_Number & get_x() const noexcept
Gets the x-coordinate value.
Definition point.H:448
const Geom_Number & get_y() const noexcept
Gets the y-coordinate value.
Definition point.H:457
Point midpoint(const Point &other) const
Calculates the midpoint between this point and another.
Definition point.H:439
bool is_to_left_on_from(const Point &p1, const Point &p2) const
Checks if this point is to the left of or on the line from p1 to p2.
Definition point.H:515
bool is_right_of(const Segment &s) const
Checks if this point is to the right of a directed segment.
Definition point.H:1478
bool is_left_of(const Point &p1, const Point &p2) const
Checks if this point is to the left of the directed line from p1 to p2.
Definition point.H:486
Geom_Number distance_squared_to(const Point &that) const
Calculates the squared Euclidean distance to another point.
Definition point.H:1490
Offset (inflate/deflate) an arbitrary simple polygon.
static Result cleanup(const Array< Point > &raw)
Full cleanup pipeline.
Result operator()(const Polygon &poly, const Geom_Number &distance, const JoinType join=JoinType::Miter, const Geom_Number &miter_limit=Geom_Number(2)) const
Offset a simple polygon by the given distance.
static Array< Polygon > extract_contours(Array< AugVertex > &aug)
Walk the augmented polygon and extract valid CCW contours.
JoinType
Strategy for connecting offset edges at vertices.
@ Bevel
Connect edge endpoints with a straight line.
@ Miter
Extend edges until they intersect.
static void sort_by_alpha(Array< size_t > &idx, const Array< Geom_Number > &keys)
Insertion-sort indices by alpha key.
Polygon offset_polygon(const Polygon &poly, const Geom_Number &distance, JoinType join=JoinType::Miter, const Geom_Number &miter_limit=Geom_Number(2)) const
Convenience: return the single largest-area result polygon.
static Polygon build_poly(const Array< Point > &pts)
Build a polygon from a point array.
static void offset_edge(const Point &a, const Point &b, const Geom_Number &d, const bool inward, Point &oa, Point &ob)
Compute two points on the offset line of edge (a→b) shifted by |d| along its outward or inward normal...
static Array< Point > compute_raw_offset(const Array< Point > &v, const Geom_Number &distance, const JoinType join, const Geom_Number &miter_limit)
static Array< Intersection > find_self_intersections(const Array< Point > &raw)
O(n²) scan for all proper self-intersections.
static Geom_Number abs_area(const Polygon &p)
static Array< AugVertex > build_augmented(const Array< Point > &raw, const Array< Intersection > &isects)
Build the augmented vertex list with crossing links.
static Point line_intersect(const Point &a1, const Point &a2, const Point &b1, const Point &b2)
Line–line intersection of (a1,a2) and (b1,b2).
static Geom_Number sq_dist(const Point &a, const Point &b)
Compute the squared distance between two points.
static Geom_Number edge_param(const Point &P, const Point &Q, const Point &I)
Compute parameter t of point I along directed edge P→Q.
Iterator over the edges (segments) of a polygon.
Definition polygon.H:529
bool has_curr() const
Check if there is a current segment.
Definition polygon.H:546
A general (irregular) 2D polygon defined by a sequence of vertices.
Definition polygon.H:247
const Vertex & get_next_vertex(const Vertex &v) const
Get the vertex following v in the polygon.
Definition polygon.H:610
const Vertex & get_prev_vertex(const Vertex &v) const
Get the vertex preceding v in the polygon.
Definition polygon.H:624
void remove_vertex(const Vertex &v)
Remove a vertex from the polygon.
Definition polygon.H:786
PointLocation locate_point(const Point &p) const
Classify a point against this closed polygon.
Definition polygon.H:895
const Vertex & get_first_vertex() const
Get the first vertex of the polygon.
Definition polygon.H:587
const Vertex & get_last_vertex() const
Get the last vertex of the polygon.
Definition polygon.H:597
void add_vertex(const Point &point)
Add a vertex to the polygon.
Definition polygon.H:686
void close()
Close the polygon.
Definition polygon.H:851
const bool & is_closed() const
Check if the polygon is closed.
Definition polygon.H:482
const size_t & size() const
Get the number of vertices.
Definition polygon.H:486
Power diagram (weighted Voronoi diagram).
static Point power_center(const WeightedSite &a, const WeightedSite &b, const WeightedSite &c)
Compute the power center of three weighted sites.
Result operator()(const Array< WeightedSite > &sites) const
Compute the power diagram.
QuickHull convex hull algorithm.
static std::pair< DynList< Point >, DynList< Point > > partition(const DynList< Point > &point_set, const Point &a, const Point &b)
Split points by the line through directed segment (a,b).
Polygon operator()(const DynList< Point > &point_set) const
Compute the convex hull of a point set.
static std::pair< Point, Point > search_extremes(const DynList< Point > &point_set)
Find leftmost and rightmost points by x coordinate.
static DynList< Point > quick_hull(DynList< Point > &point_set, const Point &a, const Point &b)
Recursive QuickHull step for a directed edge (a,b).
static std::pair< DynList< Point >, DynList< Point > > get_right_points(DynList< Point > &point_set, const Point &a, const Point &b, const Point &c)
Partition points to the right of edges (a,c) and (c,b).
static Point get_farthest_point(const DynList< Point > &point_set, const Segment &s)
Return the point in point_set farthest from segment s.
Static 2D range tree for orthogonal range queries.
void build_node(const size_t node, const size_t lo, const size_t hi)
RangeTree2D(const RangeTree2D &other)=default
Copy the points and the tree of another range tree.
void swap(RangeTree2D &other) noexcept
Exchange in O(1) the points and the tree of this range tree and another.
bool is_empty() const noexcept
DynList< Point > query(const Geom_Number &xmin, const Geom_Number &xmax, const Geom_Number &ymin, const Geom_Number &ymax) const
Query: return all points inside [xmin,xmax] × [ymin,ymax].
Array< Point > pts_
points sorted by x (primary key)
Array< Node > tree_
implicit binary tree (1-indexed)
size_t size() const noexcept
RangeTree2D(RangeTree2D &&other) noexcept
Take the points and the tree of another range tree, which is left empty.
size_t lower_bound_x(const Geom_Number &xval) const
Binary search: first index i in pts_ where pts_(i).get_x() >= xval.
static size_t lower_bound_y(const Array< Point > &arr, const Geom_Number &ymin)
Binary search: first index i in arr where arr(i).get_y() >= ymin.
void query_range(const size_t node, const size_t lo, const size_t hi, const size_t qlo, const size_t qhi, const Geom_Number &ymin, const Geom_Number &ymax, DynList< Point > &out) const
size_t upper_bound_x(const Geom_Number &xval) const
Binary search: first index i in pts_ where pts_(i).get_x() > xval.
RangeTree2D & operator=(const RangeTree2D &other)=default
Copy the points and the tree of another range tree.
void build(const DynList< Point > &points)
Build the range tree from a point set.
RangeTree2D & operator=(RangeTree2D &&other) noexcept
Exchange this range tree with another, which is left with the previous points of this one.
static size_t upper_bound_y(const Array< Point > &arr, const Geom_Number &ymax)
Binary search: first index i in arr where arr(i).get_y() > ymax.
DebugSnapshot debug_snapshot() const
Return structural snapshot for visualization/debug.
RangeTree2D()=default
Build an empty range tree; build() fills it.
An axis-aligned rectangle.
Definition point.H:1789
const Geom_Number & get_xmin() const
Gets the minimum x-coordinate.
Definition point.H:1815
const Geom_Number & get_ymax() const
Gets the maximum y-coordinate.
Definition point.H:1830
const Geom_Number & get_ymin() const
Gets the minimum y-coordinate.
Definition point.H:1820
const Geom_Number & get_xmax() const
Gets the maximum x-coordinate.
Definition point.H:1825
Exact regular triangulation (weighted Delaunay) via Bowyer-Watson.
static bool all_collinear(const Array< WeightedSite > &s)
static bool point_in_power_circle(const Array< Point > &pts, const Array< Geom_Number > &wts, const size_t ia, const size_t ib, const size_t ic, const size_t ip)
Weighted in-circle (power) predicate.
static bool lex_less(const Point &p1, const Point &p2)
static Array< WeightedSite > unique_sites(const Array< WeightedSite > &input)
Deduplicates and sorts an array of weighted sites.
Result operator()(const Array< WeightedSite > &weighted_sites) const
Compute the regular triangulation of a weighted point set.
Rotating calipers metrics for convex polygons.
static DiameterResult make_diameter(const Point &a, const Point &b)
static Array< Point > extract_vertices(const Polygon &poly)
Extract polygon vertices into an array.
static DiameterResult diameter(const Polygon &poly)
Compute convex polygon diameter (farthest vertex pair).
static WidthResult minimum_width(const Polygon &poly)
Compute the minimum width of a closed convex polygon.
static bool is_convex(const Array< Point > &verts)
Check if a polygon vertex cycle is convex.
Compute the full planar subdivision induced by a set of segments.
static size_t find_vertex(const Array< Point > &verts, const Point &p)
Find the index of point p in a sorted vertex array (binary search).
static bool angle_lt(const Geom_Number &dx1, const Geom_Number &dy1, const Geom_Number &dx2, const Geom_Number &dy2)
Compare two directions from the same origin by angle (exact).
static constexpr size_t NONE
static int angle_quad(const Geom_Number &dx, const Geom_Number &dy)
Angular quadrant of direction (dx, dy).
Result operator()(const Array< Segment > &segments) const
Compute the arrangement of a set of segments.
static bool pt_less(const Point &a, const Point &b)
Lexicographic point comparison.
Dedicated exact intersection for a single pair of segments.
Kind
Types of intersection between two segments.
@ OVERLAP
Intersection over a collinear interval.
@ POINT
Intersection at a single point.
static Segment collinear_overlap(const Segment &s1, const Segment &s2)
static Point point_max_on_axis(const Point &a, const Point &b, const bool vertical_axis)
static bool point_less_on_axis(const Point &a, const Point &b, const bool vertical_axis)
Result operator()(const Segment &s1, const Segment &s2) const
Computes the intersection of two line segments.
static Point point_min_on_axis(const Point &a, const Point &b, const bool vertical_axis)
Represents a line segment between two points.
Definition point.H:837
bool intersects_properly_with(const Segment &s) const
Checks if this segment properly intersects another segment.
Definition point.H:1241
Point intersection_with(const Segment &s) const
Computes the intersection point of the infinite lines defined by two segments.
Definition point.H:1334
bool intersects_with(const Segment &s) const
Checks if this segment intersects another one (including endpoints and collinear overlap).
Definition point.H:1291
Point project(const Point &p) const
Orthogonal projection of a point onto this segment's infinite line, clamped to the segment's endpoint...
Definition point.H:1161
Geom_Number distance_to(const Point &p) const
Calculates the Euclidean distance from a point to this segment.
Definition point.H:1183
bool contains(const Point &p) const
Checks if a point lies on this segment.
Definition point.H:1259
const Point & get_tgt_point() const noexcept
Gets the target point of the segment.
Definition point.H:933
bool is_parallel_with(const Segment &s) const
Checks if this segment is parallel to another one.
Definition point.H:1323
const Point & get_src_point() const noexcept
Gets the source point of the segment.
Definition point.H:924
Compute the shortest Euclidean path between two points inside a simple polygon.
static size_t find_tri(const Array< Point > &pts, const Array< ITri > &tris, const Point &p)
Find a triangle containing point p.
static constexpr size_t NONE
static Array< size_t > find_sleeve(const Array< ITri > &tris, const size_t src, const size_t dst)
BFS on dual graph → sleeve.
static Array< ITri > build_tris(const Array< Point > &pts, const DynList< Triangle > &tl)
Build indexed triangulation with adjacency.
static Geom_Number cross(const Point &a, const Point &b, const Point &c)
Cross product (b-a) x (c-a).
DynList< Point > operator()(const Polygon &polygon, const Point &source, const Point &target) const
Compute the shortest path between two points in a simple polygon.
static bool point_in_triangle(const Array< Point > &pts, const ITri &t, const Point &p)
Point-in-triangle test.
static size_t find_index(const Array< Point > &pts, const Point &p)
Match a Point from a Triangle to an index in pts (exact comparison).
Sweep-line status as a balanced tree with O(log n) updates.
size_t predecessor_for_insert(const size_t seg, const Geom_Number &sx) const
static Node * insert_by_label(Node *root, Node *node)
Geom_Number fresh_label_between(const size_t pred, const size_t succ) const
void insert(const size_t seg, const Geom_Number &sx)
size_t successor_for_insert(const size_t seg, const Geom_Number &sx) const
static void split_by_label(Node *root, const Geom_Number &label, Node *&left, Node *&right)
static Node * erase_by_label(Node *root, const Geom_Number &label, Node *&removed)
Report all pairwise intersection points among a set of segments.
static bool status_less(const size_t lhs, const size_t rhs, const Geom_Number &sx, const Array< Segment > &segs)
static void check_and_enqueue(const Array< Segment > &segs, const size_t i, const size_t j, const Geom_Number &sx, LineSweepFramework< Event, EventLess > &eq, DynSetTree< size_t, Treap_Rk > &seen_pairs, const size_t n)
Detect an intersection and enqueue it as a future event.
static bool slope_less(const Segment &a, const Segment &b)
static Segment canonicalize(const Segment &s)
Canonicalize a segment so its src is the "left" endpoint.
Array< Intersection > operator()(const Array< Segment > &segments) const
Find all pairwise segment intersection points.
static bool event_less(const Event &a, const Event &b)
Ordering for events in the sweep queue.
static Geom_Number y_at_x(const Segment &s, const Geom_Number &x)
Evaluate the y-coordinate of segment s at x = x.
EventType
Types of events in the Bentley-Ottmann sweep.
O(log n) point location via trapezoidal map with DAG search.
static void split_multiple_trapezoids(Array< Point > &pts, Array< Segment > &segs, Array< Trapezoid > &traps, Array< DagNode > &dag, const size_t seg_idx, const Array< size_t > &crossed)
Handle the case where a segment crosses multiple trapezoids.
LocationType
Classification of a point location query result.
@ TRAPEZOID
The point is strictly inside a trapezoid.
@ ON_POINT
The point coincides with a segment endpoint.
@ ON_SEGMENT
The point lies on a segment boundary.
static void update_neighbor(Array< Trapezoid > &traps, const size_t neighbor_idx, const size_t old_ti, const size_t new_ti)
Update all neighbor pointers that referenced old_ti to point to new_ti.
static size_t dag_locate(const Array< Point > &pts, const Array< Segment > &segs, const Array< DagNode > &dag, const Point &p, size_t root)
Locate the DAG leaf (trapezoid) containing point p.
static Array< size_t > find_crossed_trapezoids(const Array< Point > &pts, const Array< Segment > &segs, const Array< Trapezoid > &traps, const size_t seg_idx, const size_t start_trap)
Find all trapezoids crossed by segment seg_idx, starting from the trapezoid containing the left endpo...
static bool point_above_segment(const Point &p, const Segment &seg)
Test if point p is above segment seg (left of the directed segment).
static size_t make_trapezoid(Array< Trapezoid > &traps, Array< DagNode > &dag, const size_t top, const size_t bottom, const size_t leftp, const size_t rightp)
Create a new trapezoid and a DAG leaf for it.
Result operator()(const Array< Segment > &input_segments) const
Build a trapezoidal map from a set of non-crossing segments.
static void split_single_trapezoid(Array< Point > &pts, Array< Segment > &segs, Array< Trapezoid > &traps, Array< DagNode > &dag, const size_t seg_idx, const size_t trap_idx)
Handle the case where a segment is fully contained in one trapezoid.
static void replace_leaf(Array< DagNode > &dag, const size_t leaf_idx, const NodeType type, const size_t index, const size_t left, const size_t right)
Replace a DAG leaf with an internal node (X or Y).
NodeType
Types of nodes in the search DAG.
@ X_NODE
A node that splits the search space by an X-coordinate.
@ LEAF
A leaf node representing a trapezoid.
@ Y_NODE
A node that splits the search space by a segment (Y-direction).
A non-degenerate triangle defined by three points.
Definition point.H:1512
const Point & get_p3() const
Gets the third vertex.
Definition point.H:1629
const Point & get_p2() const
Gets the second vertex.
Definition point.H:1624
const Point & get_p1() const
Gets the first vertex.
Definition point.H:1619
A vertex in a polygon's doubly linked vertex list.
Definition polygon.H:120
const Vertex & next_vertex() const
Get the next vertex in the polygon.
Definition polygon.H:190
Point to_point() const
Return this vertex as a plain Point value.
Definition polygon.H:151
BST-based sweep status for active edges, ordered by ray-intersection distance.
size_t min() const
Return the nearest edge (smallest ray_param).
DynSetTree< EdgeKey, Treap, EdgeKeyCmp > tree_
EdgeStatusTree(const Array< Point > &verts, const size_t n, const Point &query)
bool contains(const size_t edge) const
void insert(const size_t edge, const Point &dir)
Compute the visibility polygon from a point inside a simple polygon.
static bool angle_less(const Point &q, const Point &a, const Point &b)
True if direction (a - q) has a smaller angle than (b - q).
static Point ray_edge_hit(const Point &q, const Point &dir, const Point &e0, const Point &e1)
Intersection point of ray from q through dir with edge (e0, e1).
Polygon operator()(const Polygon &polygon, const Point &query) const
Compute the visibility polygon.
static int angle_quadrant(const Geom_Number &dx, const Geom_Number &dy)
Quadrant of direction (dx, dy): 0 = +x+y, 1 = -x+y, 2 = -x-y, 3 = +x-y.
static Geom_Number ray_param(const Point &q, const Point &dir, const Point &e0, const Point &e1)
Parametric t along ray q + t*(dir-q) for intersection with edge (e0,e1).
Visvalingam-Whyatt polyline simplification.
static Array< Point > simplify_open_array(const Array< Point > &polyline, const Geom_Number &area_threshold)
Array< Point > operator()(const Array< Point > &polyline, const Geom_Number &area_threshold) const
Simplify an open polyline.
static Geom_Number effective_area(const Point &a, const Point &b, const Point &c)
static Polygon simplify_polygon(const Polygon &poly, const Geom_Number &area_threshold)
Simplify a closed polygon.
The Voronoi diagram, as VoronoiDiagram computes it.
Array< ClippedCell > clipped_cells(const DynList< Point > &pts, const Polygon &clip) const
Compute Voronoi cells clipped to a bounding polygon.
VoronoiDiagram voronoi_
The diagram that it computes.
Array< ClippedCell > clipped_cells(const std::initializer_list< Point > il, const Polygon &clip) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
Voronoi diagram derived as the dual of a Delaunay triangulation.
static Array< ClippedCell > indexed_clipped_cells(const Array< Point > &sites, const Array< Polygon > &polys)
Array< ClippedCell > clipped_cells_indexed(const std::initializer_list< Point > il, const Polygon &clip) const
Convenience overload with initializer-list input.
static Point circumcenter(const Point &a, const Point &b, const Point &c)
Computes the circumcenter of three points.
Result operator()(const DelaunayTriangulationBowyerWatson::Result &dt) const
Build Voronoi from a precomputed Delaunay triangulation.
static HalfPlaneIntersection::HalfPlane bisector_halfplane_for_site(const Point &s, const Point &t)
Creates a half-plane from a directed edge.
static bool is_convex(const Array< Point > &verts)
Checks if a vertex set forms a convex polygon.
static Array< ClippedCell > clipped_cells_indexed(const Array< Point > &sites, const Polygon &clip)
Clip Voronoi cells and return explicit site-indexed records.
Array< Polygon > clipped_cells(const std::initializer_list< Point > il, const Polygon &clip) const
Convenience overload with initializer-list input.
Array< ClippedCell > clipped_cells_indexed(const DynList< Point > &point_set, const Polygon &clip) const
Compute/clip Voronoi cells and return site-indexed records.
static Array< Polygon > clipped_cells(const Array< Point > &sites, const Polygon &clip)
Clip Voronoi cells against a closed convex polygon.
static Array< ClippedCell > clipped_cells_indexed(const Result &vor, const Polygon &clip)
Clip Voronoi cells (from result) into site-indexed records.
static Array< Point > extract_vertices(const Polygon &p)
Extracts vertices from a closed polygon.
Array< Polygon > clipped_cells(const DynList< Point > &point_set, const Polygon &clip) const
Compute Voronoi and clip its cells against a closed convex polygon.
DelaunayTriangulationBowyerWatson delaunay
Internal Delaunay triangulator.
static Array< Polygon > clipped_cells(const Result &vor, const Polygon &clip)
Clip Voronoi cells against a closed convex polygon.
O(n log n) Voronoi diagram construction.
VoronoiDiagramFromDelaunay voronoi_
Internal dual builder.
VoronoiDiagramFromDelaunay::Result Result
Complete result structure.
VoronoiDiagramFromDelaunay::Cell Cell
Type for Voronoi cells.
Array< ClippedCell > clipped_cells(const DynList< Point > &pts, const Polygon &clip) const
Compute Voronoi cells clipped to a bounding polygon.
DelaunayTriangulationRandomizedIncremental delaunay_
Internal Delaunay triangulator.
VoronoiDiagramFromDelaunay::Edge Edge
Type for Voronoi edges.
Result operator()(const DynList< Point > &pts) const
Compute the Voronoi diagram for a list of points.
VoronoiDiagramFromDelaunay::ClippedCell ClippedCell
Type for clipped Voronoi cells.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
2D k-d tree for efficient spatial point operations.
Definition tpl_2dtree.H:136
bool insert(const Point &p)
Insert a point into the tree.
Definition tpl_2dtree.H:414
constexpr size_t size() const noexcept
Get the number of points in the tree.
Definition tpl_2dtree.H:243
static void range(Node *root, const Rectangle &rect, DynList< Point > *q)
Recursively find points within a rectangle.
Definition tpl_2dtree.H:492
void for_each(Op &&op) const
Apply an operation to every point in the tree (inorder).
Definition tpl_2dtree.H:627
static K2Tree build(Array< Point > points, const Point &pmin, const Point &pmax)
Build a balanced k-d tree from an array of points.
Definition tpl_2dtree.H:650
bool contains(const Point &p) const noexcept
Check if the tree contains a point.
Definition tpl_2dtree.H:480
std::optional< Point > nearest(const Point &p) const noexcept
Find the nearest point to a query point.
Definition tpl_2dtree.H:607
constexpr bool is_empty() const noexcept
Check if the tree is empty.
Definition tpl_2dtree.H:240
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
and Aleph::dry_detail::MutablyTraversable< typename Aleph::concepts_detail::defer< Container, Operation >::type, Type > Type * find_ptr(Operation &operation) noexcept(mutable_search_is_noexcept< Operation >())
Find a pointer to an item in the container according to a searching criterion.
Definition ah-dry.H:825
bool contains(const Type &item) const
Test if an item is present in the container using equality.
Definition ah-dry.H:1074
pair< size_t, string > P
#define N
Definition fib.C:294
static Tree_Node< int > * chain(size_t n)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_hypot_function > > hypot(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4190
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_y1_function > > y1(const __gmp_expr< T, U > &expr)
Definition gmpfrxx.h:4181
__gmp_expr< mpfr_t, mpfr_t > mpfr_class
Definition gmpfrxx.h:2516
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
bool vertical
If true, use vertical layout (default).
Singly linked list implementations with head-tail access.
Freq_Node * pred
Predecessor node in level-order traversal.
static int initialized
Definition mpfr_mul_d.c:4
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
void in_place_unique(Container &c, Compare cmp={})
Remove duplicates in-place preserving first occurrence order.
Definition ah-unique.H:74
Orientation
Classification of three-point orientation.
Definition point.H:2894
Geom_Number in_circle_determinant(const Point &a, const Point &b, const Point &c, const Point &p)
Return the exact in-circle determinant for (a,b,c,p).
Definition point.H:2923
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
Geom_Number area_of_parallelogram(const Point &a, const Point &b, const Point &c)
Compute the signed area of the parallelogram defined by vectors a->b and a->c.
Definition point.H:2886
Itor unique(Itor __first, Itor __last, BinaryPredicate __binary_pred=BinaryPredicate())
Remove consecutive duplicates in place.
Definition ahAlgo.H:1058
bool on_segment(const Segment &s, const Point &p)
Return true if p lies on segment s (exact).
Definition point.H:2961
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool segments_intersect(const Segment &s1, const Segment &s2)
Return true if segments s1 and s2 intersect (including endpoints).
Definition point.H:2967
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
Point segment_intersection_point(const Segment &s1, const Segment &s2)
Compute the exact intersection point of segments s1 and s2.
Definition point.H:2982
bool contains(const std::string_view &str, const std::string_view &substr)
Check if substr appears inside str.
DynArray< T > & in_place_sort(DynArray< T > &c, Cmp cmp=Cmp())
Sorts a DynArray in place.
Definition ahSort.H:328
Geom_Number square_root(const Geom_Number &x)
Square root of x (wrapper over mpfr).
Definition point.H:197
double geom_number_to_double(const Geom_Number &n)
Converts a Geom_Number to its double precision representation.
Definition point.H:120
and
Check uniqueness with explicit hash + equality functors.
Orientation orientation(const Point &a, const Point &b, const Point &c)
Return the orientation of the triple (a, b, c).
Definition point.H:2902
mpq_class Geom_Number
Numeric type used by the geometry module.
Definition point.H:113
SegmentSegmentIntersection::Result segment_segment_intersection(const Segment &s1, const Segment &s2)
Convenience free-function wrapper for SegmentSegmentIntersection.
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
void quicksort_op(C< T > &a, const Compare &cmp=Compare(), const size_t threshold=Quicksort_Threshold)
Optimized quicksort for containers using operator().
STL namespace.
2D polygon representation and geometric operations.
Structure used for debugging and visualizing the tree structure.
size_t user_index
Entry::index.
size_t node_index
Index of the node.
size_t entry_index
Index in entries_ array.
size_t right
Right child index.
size_t left
Left child index.
Rectangle bbox
Bounding box of the node.
size_t depth
Depth in the tree.
bool is_leaf
True if it's a leaf node.
A snapshot of the entire tree for debugging.
size_t root
Index of the root node.
Array< DebugNode > nodes
Array of all nodes in debug format.
An entry in the tree, consisting of a bounding box and a user-defined index.
size_t index
User-defined identifier for the entry.
Rectangle bbox
The axis-aligned bounding box.
Internal tree node structure.
bool is_leaf() const
Checks if this node is a leaf.
Rectangle bbox
Bounding box enclosing all descendants.
size_t entry_idx
Index in entries_ (leaf only).
size_t left
Left child index.
size_t right
Right child index.
Result of an alpha-shape computation.
Array< DelaunayTriangulationBowyerWatson::IndexedTriangle > triangles
Triangles that satisfy the alpha criterion.
Array< Point > sites
Deduplicated and sorted input sites.
Array< Segment > boundary_edges
Segments forming the boundary of the alpha-shape.
Lexicographical comparison for points (x primary, y secondary).
bool operator()(const Point &p1, const Point &p2) const
De Casteljau subdivision: split a cubic Bézier at parameter t into two cubic Béziers (left and right)...
Intersection pair found between edge i of A and edge j of B.
Comparator for segments to ensure strict weak ordering in sets.
bool operator()(const Segment &s1, const Segment &s2) const
Compares two segments lexicographically.
static bool cmp_point(const Point &p1, const Point &p2)
Strict lexicographical comparison for points.
Strict weak order for sorting points by (y,x).
bool operator()(const Point &p1, const Point &p2) const
Strict weak order for sorting points lexicographically by (x,y).
bool operator()(const Point &p1, const Point &p2) const
Collect edges that cross segment (u,v) by scanning all mesh edges.
size_t local
local index in tri (opposite vertex)
size_t adj[3]
adj[i] = neighbor across edge opposite v[i]
bool constrained[3]
constrained[i] = edge opp v[i] is constrained
Holds the results of the distance computation.
Geom_Number distance
The minimum Euclidean distance.
Geom_Number distance_squared
The minimum squared distance.
Point closest_on_second
Witness point on the second polygon.
bool intersects
True if the polygons overlap.
Point closest_on_first
Witness point on the first polygon.
size_t gjk_iterations
Count of iterations performed.
A point in the Minkowski difference and its source components.
Point a
Contributing point from the first polygon.
Point b
Contributing point from the second polygon.
Point v
Resulting point in Minkowski difference (a - b).
double vy
Double-precision cache for faster predicates.
double vx
Double-precision cache for faster predicates.
Represents a triangle by the indices of its three vertices.
The result of a Delaunay triangulation.
Array< IndexedTriangle > triangles
Triangles forming the Delaunay triangulation.
Array< Point > sites
Unique, sorted input points used for triangulation.
size_t adj[3]
adj[i] = neighbor across edge opposite v[i]
bool operator()(const UndirectedEdge &a, const UndirectedEdge &b) const
Represents a reference to a triangle edge.
size_t v
Index of the second vertex of the edge (u < v).
size_t third
Index of the third vertex in the triangle (not on the edge).
size_t u
Index of the first vertex of the edge (u < v).
size_t tri
Index of the triangle containing this edge.
Lexicographical comparison for points.
bool operator()(const Point &p1, const Point &p2) const
Represents a spatial partition or leaf in the KD-tree.
bool split_on_x
True if split is vertical, false if horizontal.
Rectangle region
Geometric region covered by this node.
Geom_Number split_value
The coordinate value of the split.
Point representative
Point stored in the leaf.
bool is_leaf
True if it's a leaf node.
size_t depth
Depth of the node in the tree.
A complete snapshot of the tree for debugging.
Array< DebugPartition > partitions
List of all internal and leaf partitions.
Array< Point > points
All points stored in the tree.
Rectangle bounds
Bounds of the tree, extended to the points outside them.
Comparator for SeqEvent, ensuring a strict weak ordering.
CmpEvent cmp
The user-provided base comparator.
bool operator()(const SeqEvent &a, const SeqEvent &b) const
Internal event wrapper that adds a sequence number for tie-breaking.
size_t seq
Insertion sequence number.
Event event
The user-defined event payload.
Result type: a circle defined by center and squared radius.
Geom_Number radius() const
Exact radius (square root of radius_squared).
bool contains(const Point &p) const
True if point p lies inside or on the circle boundary.
Augmented vertex in the cleaned polygon.
Intersection found between edge i and edge j of the raw polygon.
The result of an offset operation, which may produce multiple polygons.
Array< Polygon > polygons
Set of resulting simple polygons.
size_t size() const noexcept
bool is_empty() const noexcept
Checks if the result contains no polygons.
Iterator over the vertices of a polygon.
Definition polygon.H:498
Represents a cell in the power diagram.
size_t site_index
Index of the site this cell belongs to.
bool bounded
True if the cell is completely bounded.
Array< Point > vertices
Vertices of the cell in CCW order.
Point site
Coordinates of the site.
Geom_Number weight
Weight of the site.
Represents an edge in the power diagram.
size_t site_v
Index of the second site sharing this edge.
Point tgt
Target point of the edge (if not unbounded).
size_t site_u
Index of the first site sharing this edge.
Point direction
Direction vector for unbounded rays.
bool unbounded
True if the edge is an unbounded ray.
Point src
Source point of the edge.
Complete result of a power diagram computation.
Array< PowerCell > cells
Cells of the power diagram.
Array< Point > vertices
Vertices of the power diagram.
Array< WeightedSite > sites
Sorted and unique input sites.
Array< PowerEdge > edges
Edges of the power diagram.
A site with an associated weight (squared radius).
Geom_Number weight
Weight of the site.
Point position
Coordinates of the site.
Represents a node in the range tree for debugging.
size_t left
Left child tree index.
size_t y_sorted_size
Number of points in the y-sorted secondary structure.
size_t right
Right child tree index.
Geom_Number split_x
X-coordinate used to split this node.
bool is_leaf
True if this is a leaf node.
Geom_Number xmin
Minimum x-coordinate in this subtree.
size_t tree_index
Implicit tree index (1-based).
size_t lo
Lower index into the x-sorted point array.
Geom_Number xmax
Maximum x-coordinate in this subtree.
size_t hi
Upper index into the x-sorted point array.
A complete snapshot of the range tree for debugging.
Array< DebugNode > nodes
List of all nodes in debug format.
Array< Point > x_sorted_points
The underlying x-sorted point array.
Internal node structure containing the y-sorted secondary array.
Array< Point > y_sorted
Points in this node's x-range, sorted by y.
A 2-D site with an associated weight (squared radius).
Represents an edge in the planar subdivision.
size_t tgt
Index of the target vertex.
size_t src
Index of the source vertex.
size_t seg_idx
Index of the original segment that generated this edge.
Represents a face (region) in the planar subdivision.
bool unbounded
True if this is the infinite outer face.
DynList< size_t > boundary
Ordered indices of vertices forming the face boundary.
Internal half-edge structure used for face traversal.
size_t edge_idx
Index of the corresponding undirected edge.
size_t twin
Index of the twin half-edge going in the opposite direction.
size_t next
Index of the next half-edge in CCW order around the face.
size_t origin
Index of the vertex where this half-edge starts.
size_t face
Index of the face this half-edge borders.
size_t target
Index of the vertex where this half-edge ends.
The complete result of the segment arrangement computation.
Array< Point > vertices
Unique vertices (endpoints and intersection points).
Array< ArrEdge > edges
Sub-segments forming the arrangement graph.
Array< ArrFace > faces
Faces defined by the arrangement.
Detailed result of a segment-segment intersection test.
bool intersects() const noexcept
Returns true if any intersection exists.
Point point
The intersection point (if kind is POINT).
Segment overlap
The overlap segment (if kind is OVERLAP).
Functor wrapper for event_less (used by LineSweepFramework).
bool operator()(const Event &a, const Event &b) const
Represents an event in the sweep-line algorithm.
size_t seg_b
Index of the second segment (only for INTERSECTION).
size_t seg_a
Index of the first segment involved.
size_t seg_j
Index of second segment (seg_i < seg_j).
A node in the search Directed Acyclic Graph (DAG).
size_t index
Index into points, segments, or trapezoids depending on type.
size_t right
Index of the right child (or above/right child).
size_t left
Index of the left child (or below/left child).
size_t segment_index
Index of the segment the point lies on.
size_t trapezoid_index
Index of the containing trapezoid (if any).
size_t point_index
Index of the point the query point coincides with.
LocationType type
Classification of the point location.
The trapezoidal map and DAG search structure.
Array< Trapezoid > trapezoids
All trapezoids created during construction.
Array< Segment > segments
Input segments.
Array< DagNode > dag
The search directed acyclic graph.
LocationResult locate(const Point &p) const
Locate a point in the trapezoidal map.
size_t num_input_points
Number of unique points derived from segments.
Array< Point > points
Unique endpoints of all segments.
size_t num_input_segments
Number of segments originally provided.
size_t dag_root
Index of the DAG root node.
bool contains(const Point &p) const
Check if point is inside any input polygon.
size_t leftp
Index into points array (left vertical wall).
size_t dag_leaf
Back-pointer to the corresponding DAG leaf node.
size_t lower_left
Neighbor trapezoid to the lower left.
size_t rightp
Index into points array (right vertical wall).
size_t upper_right
Neighbor trapezoid to the upper right.
bool active
True if this trapezoid is part of the current map.
size_t lower_right
Neighbor trapezoid to the lower right.
size_t upper_left
Neighbor trapezoid to the upper left.
size_t bottom
Index into segments array (lower boundary).
size_t top
Index into segments array (upper boundary).
bool operator()(const EdgeKey &a, const EdgeKey &b) const
Entry in the priority queue for vertex removal.
size_t idx
Index of the vertex in the polyline.
bool operator<(const VWEntry &o) const
Comparison based on effective area.
Geom_Number area
Effective area of the triangle formed with its neighbors.
bool operator>(const VWEntry &o) const
Comparison based on effective area.
size_t site_index
Index of the site this cell belongs to.
Array< Point > vertices
Vertices of the cell in CCW order.
Point site
Coordinates of the site.
bool bounded
True if the cell is completely bounded.
Represents a Voronoi cell clipped by a bounding polygon.
Polygon polygon
Clipped convex polygon representing the cell.
Represents an edge in the Voronoi diagram.
Point tgt
Target point of the edge (only if not unbounded).
Point src
Source point of the edge.
size_t site_v
Index of the second site sharing this edge.
Point direction
Direction vector for unbounded rays.
size_t site_u
Index of the first site sharing this edge.
bool unbounded
True if the edge is an unbounded ray.
The complete result of a Voronoi diagram computation.
Array< Point > vertices
Voronoi vertices.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
size_t V
DynList< int > l1
DynList< int > l2
int keys[]
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
2D k-d tree implementation for spatial point indexing.
Circular queue implementations backed by arrays.
Stack implementations backed by dynamic or fixed arrays.
Dynamic binary heap with node-based storage.
Dynamic doubly linked list implementation.
Dynamic set implementations based on balanced binary search trees.
Comprehensive sorting algorithms and search utilities for Aleph-w.
DynList< int > l
ofstream output
Definition writeHeap.C:215