Lagrange
Loading...
Searching...
No Matches
earcut.h
1// Source: https://github.com/mapbox/earcut.hpp
2// SPDX-License-Identifier: ISC
3//
4// This file has been modified by Adobe.
5//
6// All modifications are Copyright 2022 Adobe.
7#pragma once
8
9#include <algorithm>
10#include <cassert>
11#include <cmath>
12#include <cstddef>
13#include <cstdint>
14#include <limits>
15#include <memory>
16#include <type_traits>
17#include <utility>
18#include <vector>
19
20namespace lagrange {
21
22namespace mapbox {
23
24namespace util {
25
26template <std::size_t I, typename T>
27struct nth
28{
29 inline static typename std::tuple_element<I, T>::type get(const T& t)
30 {
31 return std::get<I>(t);
32 };
33};
34
35} // namespace util
36
37namespace detail {
38
39template <typename N = uint32_t>
40class Earcut
41{
42public:
43 std::vector<N> indices;
44 std::size_t vertices = 0;
45
46 template <typename Polygon>
47 void operator()(const Polygon& points);
48
49private:
50 struct Node
51 {
52 // i is a (bits(N)-1)-wide field packed alongside the 1-bit steiner flag; mask index to that
53 // width so it fits without a narrowing warning (a no-op for any real vertex index).
54 Node(N index, double x_, double y_)
55 : x(x_)
56 , y(y_)
57 , i(index & ((N(1) << (sizeof(N) * 8 - 1)) - 1))
58 , steiner(0)
59 {}
60 Node(const Node&) = delete;
61 Node& operator=(const Node&) = delete;
62 Node(Node&&) = delete;
63 Node& operator=(Node&&) = delete;
64
65 const double x;
66 const double y;
67
68 // previous and next vertice nodes in a polygon ring
69 Node* prev = nullptr;
70 Node* next = nullptr;
71
72 // z-order curve value
73 int32_t z = 0;
74
75 // original index in polygon
76 const N i : (sizeof(N) * 8 - 1);
77
78 // indicates whether this is a steiner point
79 N steiner : 1;
80
81 // previous and next nodes in z-order
82 Node* prevZ = nullptr;
83 Node* nextZ = nullptr;
84 };
85
86 // Cache-optimized Triangle structure for repeated geometric tests
87 struct Triangle
88 {
89 const double ax, ay;
90 const double bx, by;
91 const double cx, cy;
92 // triangle bounding box, used to cheaply reject most candidate points before the
93 // full point-in-triangle test (which is 6 multiplies)
94 const double minX, minY, maxX, maxY;
95
96 Triangle(const Node* a, const Node* b, const Node* c)
97 : ax(a->x)
98 , ay(a->y)
99 , bx(b->x)
100 , by(b->y)
101 , cx(c->x)
102 , cy(c->y)
103 , minX(std::min<double>(ax, std::min<double>(bx, cx)))
104 , minY(std::min<double>(ay, std::min<double>(by, cy)))
105 , maxX(std::max<double>(ax, std::max<double>(bx, cx)))
106 , maxY(std::max<double>(ay, std::max<double>(by, cy)))
107 {}
108
109 inline double area() const { return (by - ay) * (cx - bx) - (bx - ax) * (cy - by); }
110
111 inline bool inBBox(double px, double py) const
112 {
113 return px >= minX && px <= maxX && py >= minY && py <= maxY;
114 }
115
116 inline bool containsPoint(double px, double py) const
117 {
118 return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
119 (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
120 (bx - px) * (cy - py) >= (cx - px) * (by - py);
121 }
122
123 // as containsPoint, but false when the point coincides with the triangle's first vertex (a)
124 inline bool containsPointExceptFirst(double px, double py) const
125 {
126 return !(ax == px && ay == py) && containsPoint(px, py);
127 }
128 };
129
130 template <typename Ring>
131 Node* linkedList(const Ring& points, const bool clockwise);
132 Node* filterPoints(Node* start, Node* end = nullptr);
133 void earcutLinked(Node* ear);
134 bool isEar(Node* ear);
135 bool isEarHashed(Node* ear);
136 Node* cureLocalIntersections(Node* start);
137 void splitEarcut(Node* start);
138 template <typename Polygon>
139 Node* eliminateHoles(const Polygon& points, Node* outerNode);
140 Node* eliminateHole(Node* hole, Node* outerNode);
141 Node* findHoleBridge(Node* hole, Node* outerNode);
142 void buildBlockIndex(std::size_t maxNodes, std::size_t numHoles);
143 void indexSegment(Node* head, Node* stop);
144 void growBlock(Node* head, Node* tail);
145 Node* liveBlockHead(std::size_t b);
146 Node* liveBlockStop(std::size_t b);
147 bool sectorContainsSector(const Node* m, const Node* p);
148 void indexCurve(Node* start);
149 Node* sortLinked(Node* list);
150 int32_t zOrder(const double x_, const double y_);
151 Node* getLeftmost(Node* start);
152 bool pointInTriangle(
153 double ax,
154 double ay,
155 double bx,
156 double by,
157 double cx,
158 double cy,
159 double px,
160 double py) const;
161 bool isValidDiagonal(Node* a, Node* b);
162 double area(const Node* p, const Node* q, const Node* r) const;
163 bool equals(const Node* p1, const Node* p2);
164 bool intersects(
165 const Node* p1,
166 const Node* q1,
167 const Node* p2,
168 const Node* q2,
169 bool includeBoundary = true);
170 bool onSegment(const Node* p, const Node* q, const Node* r);
171 bool intersectsPolygon(const Node* a, const Node* b);
172 bool locallyInside(const Node* a, const Node* b);
173 bool middleInside(const Node* a, const Node* b);
174 Node* splitPolygon(Node* a, Node* b);
175 template <typename Point>
176 Node* insertNode(std::size_t i, const Point& p, Node* last);
177 void removeNode(Node* p);
178
179 bool hashing;
180 // set by filterPoints whenever it removes at least one node; read by earcutLinked's stall
181 // handler to decide whether another clip pass is worth attempting before the costlier stages
182 bool filteredOut = false;
183 double minX, maxX;
184 double minY, maxY;
185 double inv_size = 0;
186
187 template <typename T, typename Alloc = std::allocator<T>>
188 class ObjectPool
189 {
190 public:
191 ObjectPool(std::size_t blockSize_)
192 : baseBlockSize(std::max<std::size_t>(blockSize_, 256))
193 {
194 allocateNewBlock();
195 }
196 ~ObjectPool() { clear(); }
197 template <typename... Args>
198 T* construct(Args&&... args)
199 {
200 // If current block is full, move to next block or allocate new one
201 if (currentIndex >= baseBlockSize) {
202 currentBlockIndex++;
203 if (currentBlockIndex < memoryBlocks.size()) {
204 // Reuse existing block
205 currentIndex = 0;
206 } else {
207 // Allocate a new one
208 allocateNewBlock();
209 }
210 }
211
212 T* object = memoryBlocks[currentBlockIndex].get() + currentIndex;
213 alloc_traits::construct(alloc, object, std::forward<Args>(args)...);
214 totalObjects++;
215 currentIndex++;
216 return object;
217 }
218 void clear()
219 {
220 // Destroy all objects, but keep blocks allocated for reuse
221 std::size_t objectsDestroyed = 0;
222 for (std::size_t blockIdx = 0;
223 blockIdx < memoryBlocks.size() && objectsDestroyed < totalObjects;
224 ++blockIdx) {
225 // check if we are in the last block
226 std::size_t objectsInThisBlock =
227 std::min(baseBlockSize, totalObjects - objectsDestroyed);
228 for (std::size_t i = 0; i < objectsInThisBlock; ++i) {
229 T* object = memoryBlocks[blockIdx].get() + i;
230 alloc_traits::destroy(alloc, object);
231 }
232 objectsDestroyed += objectsInThisBlock;
233 }
234 // Reset to start from first block again
235 currentBlockIndex = 0;
236 currentIndex = 0;
237 totalObjects = 0;
238 }
239
240 private:
241 Alloc alloc;
242 typedef typename std::allocator_traits<Alloc> alloc_traits;
243
244 // Custom deleter that uses the allocator
245 struct AllocDeleter
246 {
247 Alloc alloc;
248 std::size_t capacity;
249 void operator()(T* ptr) { alloc_traits::deallocate(alloc, ptr, capacity); }
250 };
251
252 std::vector<std::unique_ptr<T[], AllocDeleter>> memoryBlocks;
253 std::size_t currentBlockIndex = 0;
254 std::size_t currentIndex = 0;
255 std::size_t totalObjects = 0;
256 const std::size_t baseBlockSize;
257
258 void allocateNewBlock()
259 {
260 T* rawMemory = alloc_traits::allocate(alloc, baseBlockSize);
261 auto newBlock =
262 std::unique_ptr<T[], AllocDeleter>(rawMemory, AllocDeleter{alloc, baseBlockSize});
263 memoryBlocks.push_back(std::move(newBlock));
264 currentBlockIndex = memoryBlocks.size() - 1;
265 currentIndex = 0;
266 }
267 };
268
269 std::unique_ptr<ObjectPool<Node>> nodes;
270 std::vector<Node*> holeQueue;
271 // reused scratch buffer for sortLinked: materialize the z-linked ring, std::sort, relink
272 std::vector<Node*> sortBuffer;
273
274 // Block-bbox index for findHoleBridge (issue #183): one [minX,minY,maxX,maxY] bbox per K
275 // consecutive ring edges, so the leftward-ray scan can skip whole blocks in O(1) instead of
276 // walking the whole merged ring. Grown append-only — the outer ring seeds it, then each merged
277 // hole appends a segment (head node, stop node, K-blocks over head..stop); independent
278 // segments,
279 // not a ring tiling, since splices land mid-ring. Buffers reused/grown across calls.
280 //
281 // filterPoints only drops collinear/coincident points, so a stale bbox stays a conservative
282 // superset of its live edges (never a false skip); the scan skips dead nodes (p->prev->next !=
283 // p)
284 // and lazily advances a dead head/stop. Blocks are scanned in append (not ring) order, so the
285 // chosen bridge can differ from the un-indexed code — a different but equally valid result.
286 static constexpr int32_t K = 16; // edges per block
287 std::vector<double> blockBBox; // [minX,minY,maxX,maxY] per block
288 std::vector<Node*> blockHead; // first node of each block's segment
289 std::vector<Node*> blockStop; // node just past each block's segment (exclusive walk bound)
290 std::size_t numBlocks = 0;
291 // true only while eliminateHoles merges holes, so removeNode keeps the block index live
292 // (growBlock)
293 bool indexActive = false;
294};
295
296template <typename N>
297template <typename Polygon>
298void Earcut<N>::operator()(const Polygon& points)
299{
300 // reset
301 indices.clear();
302 vertices = 0;
303
304 if (points.empty()) return;
305
306 double x;
307 double y;
308 int threshold = 80;
309 std::size_t len = 0;
310
311 const std::size_t numRings = static_cast<std::size_t>(points.size());
312 for (std::size_t i = 0; threshold >= 0 && i < numRings; i++) {
313 threshold -= static_cast<int>(points[i].size());
314 len += static_cast<std::size_t>(points[i].size());
315 }
316
317 // estimate size of nodes and indices
318 if (!nodes) {
319 std::size_t estimatedNodes = len * 3 / 2;
320 nodes = std::make_unique<ObjectPool<Node>>(std::max<std::size_t>(estimatedNodes, 256));
321 }
322 indices.reserve(len + static_cast<std::size_t>(points[0].size()));
323
324 Node* outerNode = linkedList(points[0], true);
325 if (!outerNode || outerNode->prev == outerNode->next) return;
326
327 if (points.size() > 1) outerNode = eliminateHoles(points, outerNode);
328
329 // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
330 hashing = threshold < 0;
331 if (hashing) {
332 Node* p = outerNode->next;
333 minX = maxX = outerNode->x;
334 minY = maxY = outerNode->y;
335 do {
336 x = p->x;
337 y = p->y;
338 minX = std::min<double>(minX, x);
339 minY = std::min<double>(minY, y);
340 maxX = std::max<double>(maxX, x);
341 maxY = std::max<double>(maxY, y);
342 p = p->next;
343 } while (p != outerNode);
344
345 // minX, minY and inv_size are later used to transform coords into integers for z-order
346 // calculation
347 inv_size = std::max<double>(maxX - minX, maxY - minY);
348 inv_size = inv_size != .0 ? (32767. / inv_size) : .0;
349 }
350
351 earcutLinked(outerNode);
352
353 nodes->clear();
354 holeQueue.clear();
355}
356
357// create a circular doubly linked list from polygon points in the specified winding order
358template <typename N>
359template <typename Ring>
360typename Earcut<N>::Node* Earcut<N>::linkedList(const Ring& points, const bool clockwise)
361{
362 using Point = typename Ring::value_type;
363 double sum = 0;
364 const std::size_t len = static_cast<std::size_t>(points.size());
365 std::size_t i, j;
366 Node* last = nullptr;
367
368 // calculate original winding order of a polygon ring
369 for (i = 0, j = len > 0 ? len - 1 : 0; i < len; j = i++) {
370 const auto& p1 = points[i];
371 const auto& p2 = points[j];
372 const double p20 = util::nth<0, Point>::get(p2);
373 const double p10 = util::nth<0, Point>::get(p1);
374 const double p11 = util::nth<1, Point>::get(p1);
375 const double p21 = util::nth<1, Point>::get(p2);
376 sum += (p20 - p10) * (p11 + p21);
377 }
378
379 // link points into circular doubly-linked list in the specified winding order
380 if (clockwise == (sum > 0)) {
381 for (i = 0; i < len; i++) last = insertNode(vertices + i, points[i], last);
382 } else {
383 for (i = len; i-- > 0;) last = insertNode(vertices + i, points[i], last);
384 }
385
386 if (last && equals(last, last->next)) {
387 removeNode(last);
388 last = last->next;
389 }
390
391 vertices += len;
392
393 return last;
394}
395
396// Remove collinear or coincident points; removability depends only on a node's immediate
397// neighbors, so we sweep forward and re-check the predecessor after each removal. With no `end`
398// we sweep the whole ring, lapping until nothing is removable (the fixpoint the clipper needs).
399// With an explicit `end` we heal only the dirty window around a bridge/diagonal cut, stopping at
400// `end` rather than lapping — O(window) instead of O(ring).
401template <typename N>
402typename Earcut<N>::Node* Earcut<N>::filterPoints(Node* start, Node* end)
403{
404 if (!start) return start;
405 const bool full = !end;
406 if (full) end = start;
407
408 Node* p = start;
409 bool again;
410 do {
411 again = false;
412 if (p != p->next && !p->steiner && (equals(p, p->next) || area(p->prev, p, p->next) == 0)) {
413 if (full || p == end) end = p->prev; // pull the stop bound back past the removal
414 filteredOut = true;
415 removeNode(p);
416 p = p->prev; // re-check the predecessor
417 again = true;
418 } else if (full || p != end) {
419 p = p->next;
420 again = !full; // local heal: keep looping until the sweep reaches end
421 }
422 } while (again || p != end);
423
424 return end;
425}
426
427// main ear slicing loop which triangulates a polygon (given as a linked list)
428template <typename N>
429void Earcut<N>::earcutLinked(Node* ear)
430{
431 if (!ear) return;
432
433 // interlink polygon nodes in z-order
434 if (hashing) indexCurve(ear);
435
436 Node* stop = ear;
437 Node* prev;
438 Node* next;
439 bool cured = false;
440
441 // iterate through ears, slicing them one by one
442 while (ear->prev != ear->next) {
443 prev = ear->prev;
444 next = ear->next;
445
446 // reflex check is hoisted here to avoid constructing the Triangle for reflex corners
447 if (area(prev, ear, next) < 0 && (hashing ? isEarHashed(ear) : isEar(ear))) {
448 // cut off the triangle
449 indices.emplace_back(prev->i);
450 indices.emplace_back(ear->i);
451 indices.emplace_back(next->i);
452
453 removeNode(ear);
454
455 ear = next;
456 stop = next;
457
458 continue;
459 }
460
461 ear = next;
462
463 // if we looped through the whole remaining polygon and can't find any more ears
464 if (ear == stop) {
465 // try filtering collinear/coincident points and slicing again — repeat as long as
466 // filtering actually removes nodes, since each removal can expose new ears
467 filteredOut = false;
468 ear = filterPoints(ear);
469 if (filteredOut) {
470 stop = ear;
471 continue;
472 }
473
474 // filtering is exhausted: cure small local self-intersections once, then retry
475 if (!cured) {
476 ear = cureLocalIntersections(ear);
477 stop = ear;
478 cured = true;
479 continue;
480 }
481
482 // as a last resort, try splitting the remaining polygon into two
483 splitEarcut(ear);
484 break;
485 }
486 }
487}
488
489// check whether a polygon node forms a valid ear with adjacent nodes
490template <typename N>
491bool Earcut<N>::isEar(Node* ear)
492{
493 const Node* a = ear->prev;
494 const Node* b = ear;
495 const Node* c = ear->next;
496
497 // reflex check is hoisted into the earcutLinked caller
498 const Triangle tri(a, b, c);
499
500 // now make sure we don't have other points inside the potential ear
501 Node* p = ear->next->next;
502
503 while (p != ear->prev) {
504 if (tri.inBBox(p->x, p->y) && tri.containsPointExceptFirst(p->x, p->y) &&
505 area(p->prev, p, p->next) >= 0)
506 return false;
507 p = p->next;
508 }
509
510 return true;
511}
512
513template <typename N>
514bool Earcut<N>::isEarHashed(Node* ear)
515{
516 const Node* a = ear->prev;
517 const Node* b = ear;
518 const Node* c = ear->next;
519
520 // reflex check is hoisted into the earcutLinked caller
521 const Triangle tri(a, b, c);
522
523 // z-order range for the current triangle bbox;
524 const int32_t minZ = zOrder(tri.minX, tri.minY);
525 const int32_t maxZ = zOrder(tri.maxX, tri.maxY);
526
527 // first look for points inside the triangle in increasing z-order
528 Node* p = ear->nextZ;
529
530 while (p && p->z <= maxZ) {
531 if (p != ear->next && tri.inBBox(p->x, p->y) && tri.containsPointExceptFirst(p->x, p->y) &&
532 area(p->prev, p, p->next) >= 0)
533 return false;
534 p = p->nextZ;
535 }
536
537 // then look for points in decreasing z-order
538 p = ear->prevZ;
539
540 while (p && p->z >= minZ) {
541 if (p != ear->next && tri.inBBox(p->x, p->y) && tri.containsPointExceptFirst(p->x, p->y) &&
542 area(p->prev, p, p->next) >= 0)
543 return false;
544 p = p->prevZ;
545 }
546
547 return true;
548}
549
550// go through all polygon nodes and cure small local self-intersections
551template <typename N>
552typename Earcut<N>::Node* Earcut<N>::cureLocalIntersections(Node* start)
553{
554 Node* p = start;
555 bool cured = false;
556 do {
557 Node* a = p->prev;
558 Node* b = p->next->next;
559
560 // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]);
561 // includeBoundary=false so a mere collinear touch isn't treated as a crossing
562 if (intersects(a, p, p->next, b, false) && locallyInside(a, b) && locallyInside(b, a)) {
563 indices.emplace_back(a->i);
564 indices.emplace_back(p->i);
565 indices.emplace_back(b->i);
566
567 // remove two nodes involved
568 removeNode(p);
569 removeNode(p->next);
570
571 p = start = b;
572 cured = true;
573 }
574 p = p->next;
575 } while (p != start);
576
577 return cured ? filterPoints(p) : p;
578}
579
580// try splitting polygon into two and triangulate them independently
581template <typename N>
582void Earcut<N>::splitEarcut(Node* start)
583{
584 // look for a valid diagonal that divides the polygon into two
585 Node* a = start;
586 do {
587 Node* b = a->next->next;
588 while (b != a->prev) {
589 if (a->i != b->i && isValidDiagonal(a, b)) {
590 // split the polygon in two by the diagonal
591 Node* c = splitPolygon(a, b);
592
593 // filter colinear points around the cuts
594 a = filterPoints(a, a->next);
595 c = filterPoints(c, c->next);
596
597 // run earcut on each half
598 earcutLinked(a);
599 earcutLinked(c);
600 return;
601 }
602 b = b->next;
603 }
604 a = a->next;
605 } while (a != start);
606}
607
608// link every hole into the outer loop, producing a single-ring polygon without holes
609template <typename N>
610template <typename Polygon>
611typename Earcut<N>::Node* Earcut<N>::eliminateHoles(const Polygon& points, Node* outerNode)
612{
613 const size_t len = static_cast<std::size_t>(points.size());
614
615 holeQueue.clear();
616 for (size_t i = 1; i < len; i++) {
617 Node* list = linkedList(points[i], false);
618 if (list) {
619 if (list == list->next) list->steiner = true;
620 holeQueue.push_back(getLeftmost(list));
621 }
622 }
623 // compareXYSlope: sort by x, then y, then slope. When two holes' leftmost points coincide, the
624 // slope tiebreak makes the bridge land on the shared vertex instead of bridging the wrong hole.
625 std::sort(holeQueue.begin(), holeQueue.end(), [](const Node* a, const Node* b) {
626 if (a->x != b->x) return a->x < b->x;
627 if (a->y != b->y) return a->y < b->y;
628 const double adx = a->next->x - a->x, ady = a->next->y - a->y;
629 const double bdx = b->next->x - b->x, bdy = b->next->y - b->y;
630 const bool aDegenerate = adx == 0 && ady == 0;
631 const bool bDegenerate = bdx == 0 && bdy == 0;
632 if (aDegenerate != bDegenerate) return aDegenerate;
633 return ady * bdx < bdy * adx;
634 });
635
636 // block-bbox index for findHoleBridge, grown append-only as holes merge. Seed it with the
637 // outer ring, then append each merged hole.
638 buildBlockIndex(vertices, holeQueue.size());
639 indexSegment(outerNode, outerNode);
640
641 // process holes from left to right; indexActive lets removeNode keep block bboxes live as
642 // filterPoints heals edges during merges (see growBlock)
643 indexActive = true;
644 for (size_t i = 0; i < holeQueue.size(); i++) {
645 outerNode = eliminateHole(holeQueue[i], outerNode);
646 }
647 indexActive = false;
648
649 // collapse collinear/coincident points across the whole merged ring once before clipping
650 return filterPoints(outerNode);
651}
652
653// find a bridge between vertices that connects hole with an outer ring and and link it
654template <typename N>
655typename Earcut<N>::Node* Earcut<N>::eliminateHole(Node* hole, Node* outerNode)
656{
657 Node* bridge = findHoleBridge(hole, outerNode);
658 if (!bridge) {
659 return outerNode;
660 }
661
662 Node* bridgeReverse = splitPolygon(bridge, hole);
663
664 // index the merged-in segment before filtering: in ring order the splice runs
665 // bridge -> hole -> bridgeReverse -> bridge2 -> (bridge's old next), covering the hole's edges
666 // and both new slit edges. filterPoints below only drops collinear/coincident points, so these
667 // bboxes stay valid (conservative) supersets.
668 Node* bridge2 = bridgeReverse->next;
669 indexSegment(bridge, bridge2->next);
670
671 // heal collinear/coincident points around the two new slit edges
672 filterPoints(bridgeReverse, bridgeReverse->next);
673 return filterPoints(bridge, bridge->next);
674}
675
676// David Eberly's algorithm for finding a bridge between hole and outer polygon
677template <typename N>
678typename Earcut<N>::Node* Earcut<N>::findHoleBridge(Node* hole, Node* outerNode)
679{
680 Node* p = outerNode;
681 double hx = hole->x;
682 double hy = hole->y;
683 double qx = -std::numeric_limits<double>::max();
684 Node* m = nullptr;
685
686 // find a segment intersected by a ray from the hole's leftmost Vertex to the left;
687 // segment's endpoint with lesser x will be potential connection Vertex,
688 // unless they intersect at a vertex, then choose the vertex
689 if (equals(hole, p)) return p;
690
691 // scan blocks; skip any whose bbox can't hold a crossing that beats qx and lies left of hx
692 // (the prune Morton order can't express — explicit per-axis [minY,maxY]/[minX,maxX])
693 for (std::size_t b = 0, g = 0; b < numBlocks; b++, g += 4) {
694 if (hy < blockBBox[g + 1] || hy > blockBBox[g + 3] || blockBBox[g] > hx ||
695 blockBBox[g + 2] <= qx)
696 continue;
697
698 // ensure the walk's exclusive bound is live so we don't overrun into other blocks
699 const Node* stop = liveBlockStop(b);
700 p = liveBlockHead(b);
701 do {
702 if (p->prev->next == p) { // skip nodes removed by filterPoints (stale in the index)
703 if (equals(hole, p->next))
704 return p->next;
705 else if (hy <= p->y && hy >= p->next->y && p->next->y != p->y) {
706 double x = p->x + (hy - p->y) * (p->next->x - p->x) / (p->next->y - p->y);
707 if (x <= hx && x > qx) {
708 qx = x;
709 m = p->x < p->next->x ? p : p->next;
710 if (x == hx) return m; // hole touches outer segment; pick leftmost endpoint
711 }
712 }
713 }
714 p = p->next;
715 } while (p != stop);
716 }
717
718 if (!m) return 0;
719
720 // look for points inside the triangle of hole Vertex, segment intersection and endpoint;
721 // if there are no points found, we have a valid connection;
722 // otherwise choose the Vertex of the minimum angle with the ray as connection Vertex
723
724 const double mx = m->x;
725 const double my = m->y;
726 const double tminY = std::min<double>(hy, my); // the triangle's y span; x span is [mx, hx]
727 const double tmaxY = std::max<double>(hy, my);
728 double tanMin = std::numeric_limits<double>::max();
729
730 // scan the same blocks; skip any whose bbox can't overlap the triangle's [mx,hx]x[tminY,tmaxY]
731 // box
732 for (std::size_t b = 0, g = 0; b < numBlocks; b++, g += 4) {
733 if (blockBBox[g + 2] < mx || blockBBox[g] > hx || blockBBox[g + 3] < tminY ||
734 blockBBox[g + 1] > tmaxY)
735 continue;
736
737 const Node* stop = liveBlockStop(b);
738 p = liveBlockHead(b);
739 do {
740 if (p->prev->next == p && hx >= p->x && p->x >= mx && hx != p->x && // skip dead nodes
741 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p->x, p->y)) {
742 const double tanCur = std::abs(hy - p->y) / (hx - p->x); // tangential
743
744 // if hole point sits on p's horizontal edge (T-junction touch): the bridge runs
745 // along that edge — locallyInside rejects it as collinear, but it's valid
746 if ((locallyInside(p, hole) ||
747 (p->y == hy && p->next->y == hy && p->next->x > hx)) &&
748 (tanCur < tanMin ||
749 (tanCur == tanMin &&
750 (p->x > m->x || (p->x == m->x && sectorContainsSector(m, p)))))) {
751 m = p;
752 tanMin = tanCur;
753 }
754 }
755 p = p->next;
756 } while (p != stop);
757 }
758
759 return m;
760}
761
762// Block-bbox index buffers: size once from the input upper bound and reuse across calls.
763template <typename N>
764void Earcut<N>::buildBlockIndex(std::size_t maxNodes, std::size_t numHoles)
765{
766 // upper bound: every input node indexed once, +2 bridge nodes per hole, plus a partial
767 // trailing block per appended segment (outer ring + one per hole)
768 const std::size_t maxBlocks = (maxNodes + 2 * numHoles + K - 1) / K + numHoles + 2;
769 if (blockBBox.size() < maxBlocks * 4) blockBBox.resize(maxBlocks * 4);
770 if (blockHead.size() < maxBlocks) {
771 blockHead.resize(maxBlocks);
772 blockStop.resize(maxBlocks);
773 }
774 numBlocks = 0;
775}
776
777// index the ring run head..stop (exclusive) as ceil(len / K) blocks; head == stop means the whole
778// ring. each block's bbox covers both endpoints of every edge it owns.
779template <typename N>
780void Earcut<N>::indexSegment(Node* head, Node* stop)
781{
782 Node* p = head;
783 do {
784 const std::size_t b = numBlocks++;
785 blockHead[b] = p;
786 double bMinX = std::numeric_limits<double>::max();
787 double bMinY = std::numeric_limits<double>::max();
788 double bMaxX = std::numeric_limits<double>::lowest();
789 double bMaxY = std::numeric_limits<double>::lowest();
790 int32_t k = 0;
791 do {
792 Node* c = p->next; // edge p->c; bbox must bound both endpoints
793 p->z = static_cast<int32_t>(
794 b); // reuse z as the owning block during eliminateHoles (see growBlock)
795 if (p->x < bMinX) bMinX = p->x;
796 if (p->x > bMaxX) bMaxX = p->x;
797 if (p->y < bMinY) bMinY = p->y;
798 if (p->y > bMaxY) bMaxY = p->y;
799 if (c->x < bMinX) bMinX = c->x;
800 if (c->x > bMaxX) bMaxX = c->x;
801 if (c->y < bMinY) bMinY = c->y;
802 if (c->y > bMaxY) bMaxY = c->y;
803 p = c;
804 } while (++k < K && p != stop);
805 blockStop[b] = p;
806 const std::size_t g = b * 4;
807 blockBBox[g] = bMinX;
808 blockBBox[g + 1] = bMinY;
809 blockBBox[g + 2] = bMaxX;
810 blockBBox[g + 3] = bMaxY;
811 } while (p != stop);
812}
813
814// when filterPoints heals an edge head->tail (removing the collinear node between them), the healed
815// edge can extend past head's frozen block bbox if its old far endpoint lived in another block;
816// grow head's block bbox to cover tail so the leftward-ray prune can't false-skip it.
817template <typename N>
818void Earcut<N>::growBlock(Node* head, Node* tail)
819{
820 const std::size_t g = static_cast<std::size_t>(head->z) * 4;
821 if (tail->x < blockBBox[g]) blockBBox[g] = tail->x;
822 if (tail->y < blockBBox[g + 1]) blockBBox[g + 1] = tail->y;
823 if (tail->x > blockBBox[g + 2]) blockBBox[g + 2] = tail->x;
824 if (tail->y > blockBBox[g + 3]) blockBBox[g + 3] = tail->y;
825}
826
827// the block's head node can be removed by filterPoints during merges; advance it to the next live
828// node so the walk doesn't start on (and immediately terminate at) a dead node. For the single
829// full-ring seed block (head == stop) the same forward advance keeps them equal, so the do-while
830// still laps the whole ring instead of collapsing to an empty walk.
831template <typename N>
832typename Earcut<N>::Node* Earcut<N>::liveBlockHead(std::size_t b)
833{
834 Node* head = blockHead[b];
835 while (head->prev->next != head) head = head->next;
836 blockHead[b] = head;
837 return head;
838}
839
840template <typename N>
841typename Earcut<N>::Node* Earcut<N>::liveBlockStop(std::size_t b)
842{
843 Node* stop = blockStop[b];
844 while (stop->prev->next != stop) stop = stop->next;
845 blockStop[b] = stop;
846 return stop;
847}
848
849// whether sector in vertex m contains sector in vertex p in the same coordinates
850template <typename N>
851bool Earcut<N>::sectorContainsSector(const Node* m, const Node* p)
852{
853 return area(m->prev, m, p->prev) < 0 && area(p->next, m, m->next) < 0;
854}
855
856// interlink polygon nodes in z-order
857template <typename N>
858void Earcut<N>::indexCurve(Node* start)
859{
860 assert(start);
861 Node* p = start;
862
863 do {
864 // always (re)compute: z may still hold a block index left over from eliminateHoles
865 p->z = zOrder(p->x, p->y);
866 p->prevZ = p->prev;
867 p->nextZ = p->next;
868 p = p->next;
869 } while (p != start);
870
871 p->prevZ->nextZ = nullptr;
872 p->prevZ = nullptr;
873
874 sortLinked(p);
875}
876
877// Sort the z-linked ring by z-order. Upstream earcut replaced its linked merge sort with an
878// array sort (materialize node refs → sort → relink); in C++ std::sort over a contiguous
879// Node* buffer inlines the comparator fully and beats both a linked merge sort and a hand radix
880// (measured on the MVT tiles fixture) — JS's rejection of native Array.sort does not transfer.
881template <typename N>
882typename Earcut<N>::Node* Earcut<N>::sortLinked(Node* list)
883{
884 assert(list);
885 // list is a null-terminated nextZ chain (see indexCurve); walk it into the scratch buffer
886 sortBuffer.clear();
887 for (Node* p = list; p; p = p->nextZ) sortBuffer.push_back(p);
888
889 std::sort(sortBuffer.begin(), sortBuffer.end(), [](const Node* a, const Node* b) {
890 return a->z < b->z;
891 });
892
893 // relink in sorted order
894 Node* prev = nullptr;
895 for (Node* p : sortBuffer) {
896 p->prevZ = prev;
897 if (prev) prev->nextZ = p;
898 prev = p;
899 }
900 prev->nextZ = nullptr;
901 return sortBuffer.front();
902}
903
904// z-order of a Vertex given coords and size of the data bounding box
905template <typename N>
906int32_t Earcut<N>::zOrder(const double x_, const double y_)
907{
908 // coords are transformed into non-negative 15-bit integer range
909 int32_t x = static_cast<int32_t>((x_ - minX) * inv_size);
910 int32_t y = static_cast<int32_t>((y_ - minY) * inv_size);
911
912 x = (x | (x << 8)) & 0x00FF00FF;
913 x = (x | (x << 4)) & 0x0F0F0F0F;
914 x = (x | (x << 2)) & 0x33333333;
915 x = (x | (x << 1)) & 0x55555555;
916
917 y = (y | (y << 8)) & 0x00FF00FF;
918 y = (y | (y << 4)) & 0x0F0F0F0F;
919 y = (y | (y << 2)) & 0x33333333;
920 y = (y | (y << 1)) & 0x55555555;
921
922 return x | (y << 1);
923}
924
925// find the leftmost node of a polygon ring
926template <typename N>
927typename Earcut<N>::Node* Earcut<N>::getLeftmost(Node* start)
928{
929 Node* p = start;
930 Node* leftmost = start;
931 do {
932 if (p->x < leftmost->x || (p->x == leftmost->x && p->y < leftmost->y)) leftmost = p;
933 p = p->next;
934 } while (p != start);
935
936 return leftmost;
937}
938
939// check if a point lies within a convex triangle
940template <typename N>
941bool Earcut<N>::pointInTriangle(
942 double ax,
943 double ay,
944 double bx,
945 double by,
946 double cx,
947 double cy,
948 double px,
949 double py) const
950{
951 return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
952 (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
953 (bx - px) * (cy - py) >= (cx - px) * (by - py);
954}
955
956// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
957template <typename N>
958bool Earcut<N>::isValidDiagonal(Node* a, Node* b)
959{
960 // degenerate zero-length case
961 const bool zeroLength =
962 equals(a, b) && area(a->prev, a, a->next) > 0 && area(b->prev, b, b->next) > 0;
963 return a->next->i != b->i &&
964 (zeroLength || (locallyInside(a, b) && locallyInside(b, a) && // locally visible
965 (area(a->prev, a, b->prev) != 0.0 ||
966 area(a, b->prev, b) != 0.0))) && // no opposite-facing sectors
967 !intersectsPolygon(a, b) && // doesn't intersect other edges
968 (zeroLength || middleInside(a, b)); // diagonal inside polygon
969}
970
971// signed area of a triangle
972template <typename N>
973double Earcut<N>::area(const Node* p, const Node* q, const Node* r) const
974{
975 return (q->y - p->y) * (r->x - q->x) - (q->x - p->x) * (r->y - q->y);
976}
977
978// check if two points are equal
979template <typename N>
980bool Earcut<N>::equals(const Node* p1, const Node* p2)
981{
982 return p1->x == p2->x && p1->y == p2->y;
983}
984
985// check if two segments intersect; by default includes collinear boundary touches
986template <typename N>
987bool Earcut<N>::intersects(
988 const Node* p1,
989 const Node* q1,
990 const Node* p2,
991 const Node* q2,
992 bool includeBoundary)
993{
994 const double o1 = area(p1, q1, p2);
995 const double o2 = area(p1, q1, q2);
996 const double o3 = area(p2, q2, p1);
997 const double o4 = area(p2, q2, q1);
998
999 // general case: the two segments straddle each other (proper crossing)
1000 if (((o1 > 0 && o2 < 0) || (o1 < 0 && o2 > 0)) && ((o3 > 0 && o4 < 0) || (o3 < 0 && o4 > 0)))
1001 return true;
1002
1003 if (!includeBoundary) return false;
1004
1005 if (o1 == 0 && onSegment(p1, p2, q1))
1006 return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
1007 if (o2 == 0 && onSegment(p1, q2, q1))
1008 return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
1009 if (o3 == 0 && onSegment(p2, p1, q2))
1010 return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
1011 if (o4 == 0 && onSegment(p2, q1, q2))
1012 return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
1013
1014 return false;
1015}
1016
1017// for collinear points p, q, r, check if point q lies on segment pr
1018template <typename N>
1019bool Earcut<N>::onSegment(const Node* p, const Node* q, const Node* r)
1020{
1021 return q->x <= std::max<double>(p->x, r->x) && q->x >= std::min<double>(p->x, r->x) &&
1022 q->y <= std::max<double>(p->y, r->y) && q->y >= std::min<double>(p->y, r->y);
1023}
1024
1025// check if a polygon diagonal intersects any polygon segments
1026template <typename N>
1027bool Earcut<N>::intersectsPolygon(const Node* a, const Node* b)
1028{
1029 // diagonal bbox; an edge whose bbox can't overlap it can't intersect it, so
1030 // skip the orientation test for those (the common case — the diagonal is short)
1031 const double diagMinX = std::min<double>(a->x, b->x);
1032 const double diagMaxX = std::max<double>(a->x, b->x);
1033 const double diagMinY = std::min<double>(a->y, b->y);
1034 const double diagMaxY = std::max<double>(a->y, b->y);
1035
1036 const Node* p = a;
1037 do {
1038 const Node* n = p->next;
1039 if ((p->x > diagMaxX && n->x > diagMaxX) || (p->x < diagMinX && n->x < diagMinX) ||
1040 (p->y > diagMaxY && n->y > diagMaxY) || (p->y < diagMinY && n->y < diagMinY)) {
1041 p = n;
1042 continue;
1043 }
1044 if (p->i != a->i && n->i != a->i && p->i != b->i && n->i != b->i && intersects(p, n, a, b))
1045 return true;
1046 p = n;
1047 } while (p != a);
1048
1049 return false;
1050}
1051
1052// check if a polygon diagonal is locally inside the polygon
1053template <typename N>
1054bool Earcut<N>::locallyInside(const Node* a, const Node* b)
1055{
1056 return area(a->prev, a, a->next) < 0 ? area(a, b, a->next) >= 0 && area(a, a->prev, b) >= 0
1057 : area(a, b, a->prev) < 0 || area(a, a->next, b) < 0;
1058}
1059
1060// check if the middle Vertex of a polygon diagonal is inside the polygon
1061template <typename N>
1062bool Earcut<N>::middleInside(const Node* a, const Node* b)
1063{
1064 const Node* p = a;
1065 bool inside = false;
1066 double px = (a->x + b->x) / 2;
1067 double py = (a->y + b->y) / 2;
1068 do {
1069 const Node* n = p->next;
1070 if (((p->y > py) != (n->y > py)) &&
1071 (px < (n->x - p->x) * (py - p->y) / (n->y - p->y) + p->x))
1072 inside = !inside;
1073 p = n;
1074 } while (p != a);
1075
1076 return inside;
1077}
1078
1079// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits
1080// polygon into two; if one belongs to the outer ring and another to a hole, it merges it into a
1081// single ring
1082template <typename N>
1083typename Earcut<N>::Node* Earcut<N>::splitPolygon(Node* a, Node* b)
1084{
1085 Node* a2 = nodes->construct(a->i, a->x, a->y);
1086 Node* b2 = nodes->construct(b->i, b->x, b->y);
1087 Node* an = a->next;
1088 Node* bp = b->prev;
1089
1090 a->next = b;
1091 b->prev = a;
1092
1093 a2->next = an;
1094 an->prev = a2;
1095
1096 b2->next = a2;
1097 a2->prev = b2;
1098
1099 bp->next = b2;
1100 b2->prev = bp;
1101
1102 return b2;
1103}
1104
1105// create a node and util::optionally link it with previous one (in a circular doubly linked list)
1106template <typename N>
1107template <typename Point>
1108typename Earcut<N>::Node* Earcut<N>::insertNode(std::size_t i, const Point& pt, Node* last)
1109{
1110 Node* p = nodes->construct(
1111 static_cast<N>(i),
1112 util::nth<0, Point>::get(pt),
1113 util::nth<1, Point>::get(pt));
1114
1115 if (!last) {
1116 p->prev = p;
1117 p->next = p;
1118
1119 } else {
1120 assert(last);
1121 p->next = last->next;
1122 p->prev = last;
1123 last->next->prev = p;
1124 last->next = p;
1125 }
1126 return p;
1127}
1128
1129template <typename N>
1130void Earcut<N>::removeNode(Node* p)
1131{
1132 p->next->prev = p->prev;
1133 p->prev->next = p->next;
1134
1135 if (p->prevZ) p->prevZ->nextZ = p->nextZ;
1136 if (p->nextZ) p->nextZ->prevZ = p->prevZ;
1137
1138 // keep the hole-bridge index's block bboxes covering the healed prev->next edge
1139 if (indexActive) growBlock(p->prev, p->next);
1140}
1141} // namespace detail
1142
1143template <typename N = uint32_t, typename Polygon>
1144std::vector<N> earcut(const Polygon& poly)
1145{
1146 mapbox::detail::Earcut<N> earcut;
1147 earcut(poly);
1148 return std::move(earcut.indices);
1149}
1150
1151namespace detail {
1152
1153// Refine a triangulation toward the constrained Delaunay triangulation by legalizing every interior
1154// edge in place with Lawson flips — maximizing the minimum angle and removing most slivers. Adapted
1155// from delaunator's edge legalization. Uses non-robust predicates: float input is fine, and the
1156// worst case is a not-quite-Delaunay edge, never an invalid mesh. Ported from earcut v3.2.3.
1157template <typename N>
1159{
1160public:
1161 // triangles: triangle indices as returned by earcut, mutated in place.
1162 // coords: random-access container of points, indexed by vertex index (coords[i] -> point i),
1163 // read through the same util::nth<0>/<1> accessors as earcut's input.
1164 template <typename Coords>
1165 void operator()(std::vector<N>& triangles, const Coords& coords)
1166 {
1167 using Point = typename std::decay<decltype(coords[0])>::type;
1168 const int n = static_cast<int>(triangles.size());
1169 if (n < 6) return;
1170 ensureScratch(static_cast<std::size_t>(n));
1171 gen++; // bumping the generation logically empties the hash (no clearing)
1172 std::fill(heVec.begin(), heVec.begin() + n, -1);
1173
1174 // Raw pointers into the scratch: indexed by the int/uint half-edge and hash indices below,
1175 // where operator[]'s size_type would trip -Wsign-conversion on every subscript.
1176 N* t = triangles.data();
1177 int32_t* he = heVec.data();
1178 int32_t* edgeStack = edgeStackVec.data();
1179 int32_t* hTable = hTableVec.data();
1180 uint32_t* hStamp = hStampVec.data();
1181 uint8_t* edgeStamp = edgeStampVec.data();
1182
1183 auto X = [&](N p) -> double {
1184 return static_cast<double>(util::nth<0, Point>::get(coords[p]));
1185 };
1186 auto Y = [&](N p) -> double {
1187 return static_cast<double>(util::nth<1, Point>::get(coords[p]));
1188 };
1189
1190 // Build half-edge twins with an undirected-edge hash; consumed slots mark linked pairs. As
1191 // each pair is linked we seed the stack with one representative (s, the earlier-inserted
1192 // edge) — this fuses the initial "push every interior edge" pass into the build, saving a
1193 // full O(n) scan. edgeStamp is all-zero here (balanced push/pop leaves it clean) and each
1194 // pair links once, so the seed write needs no dedup guard.
1195 int i = 0;
1196 for (int e = 0; e < n; e++) {
1197 const N a = t[e], b = t[nextHE(e)];
1198 const N lo = a < b ? a : b, hi = a < b ? b : a;
1199 uint32_t h = (uint32_t(lo) * 0x9e3779b1u ^ uint32_t(hi) * 0x85ebca6bu) & hMask;
1200 while (hStamp[h] == gen) {
1201 const int32_t s = hTable[h];
1202 // s == -1 marks a consumed slot (a pair already linked) — skip past it
1203 if (s != -1) {
1204 const N sa = t[s], sb = t[nextHE(s)];
1205 if ((sa == lo && sb == hi) || (sa == hi && sb == lo)) {
1206 he[e] = s;
1207 he[s] = e;
1208 hTable[h] = -1; // link, then consume the slot
1209 edgeStamp[s] = 1;
1210 edgeStack[i++] = s; // seed the interior edge for the cascade
1211 break;
1212 }
1213 }
1214 h = (h + 1) & hMask;
1215 }
1216 if (hStamp[h] != gen) {
1217 hTable[h] = e;
1218 hStamp[h] = gen;
1219 } // first occurrence: insert
1220 }
1221
1222 while (i > 0) {
1223 const int a = edgeStack[--i];
1224 edgeStamp[a] = 0;
1225 const int b = he[a];
1226 if (b == -1) continue;
1227
1228 const int a0 = a - a % 3;
1229 const int b0 = b - b % 3;
1230 const int ar = a0 + (a + 2) % 3;
1231 const int al = a0 + (a + 1) % 3;
1232 const int bl = b0 + (b + 2) % 3;
1233 const int br = b0 + (b + 1) % 3;
1234 const N p0 = t[ar], pr = t[a], pl = t[al], p1 = t[bl];
1235
1236 const double x0 = X(p0), y0 = Y(p0);
1237 const double xr = X(pr), yr = Y(pr);
1238 const double xl = X(pl), yl = Y(pl);
1239 const double x1 = X(p1), y1 = Y(p1);
1240
1241 // Test inCircle first: most interior edges are already Delaunay (inCircle true → no
1242 // flip), so this short-circuits before the two convexity orients on the common path.
1243 // The quad must also be convex (both new triangles CCW) — flipping a reflex quad would
1244 // push
1245 // a triangle outside the polygon. Boundary/hole edges self-protect via he == -1.
1246 if (!inCircle(x0, y0, xr, yr, xl, yl, x1, y1) && orient(x0, y0, xr, yr, x1, y1) > 0 &&
1247 orient(x0, y0, x1, y1, xl, yl) > 0) {
1248 t[a] = p1;
1249 t[b] = p0;
1250 const int32_t hbl = he[bl], har = he[ar];
1251 he[a] = hbl;
1252 if (hbl != -1) he[hbl] = a;
1253 he[b] = har;
1254 if (har != -1) he[har] = b;
1255 he[ar] = bl;
1256 he[bl] = ar;
1257
1258 // re-check the quad's four outer edges; skip boundary edges (he == -1) and any
1259 // already queued (edgeStamp), which also keeps the stack bounded by n.
1260 if (hbl != -1 && edgeStamp[a] == 0) {
1261 edgeStamp[a] = 1;
1262 edgeStack[i++] = a;
1263 }
1264 if (har != -1 && edgeStamp[b] == 0) {
1265 edgeStamp[b] = 1;
1266 edgeStack[i++] = b;
1267 }
1268 if (he[al] != -1 && edgeStamp[al] == 0) {
1269 edgeStamp[al] = 1;
1270 edgeStack[i++] = al;
1271 }
1272 if (he[br] != -1 && edgeStamp[br] == 0) {
1273 edgeStamp[br] = 1;
1274 edgeStack[i++] = br;
1275 }
1276 }
1277 }
1278 }
1279
1280private:
1281 // Reusable scratch, grown on demand like earcut's z-order arrays and reused across calls:
1282 // he = twin half-edge of each edge, or -1 on the polygon boundary
1283 // hTable = open-addressing hash, slot -> half-edge index, valid iff hStamp[slot] == gen
1284 // edgeStamp = pending-in-stack flag, cleared when the edge is popped
1285 std::vector<int32_t> heVec, edgeStackVec, hTableVec;
1286 std::vector<uint32_t> hStampVec;
1287 std::vector<uint8_t> edgeStampVec;
1288 uint32_t hMask = 0, gen = 0;
1289
1290 static int nextHE(int e) { return e - e % 3 + (e + 1) % 3; } // next half-edge in same triangle
1291
1292 static double orient(double ax, double ay, double bx, double by, double cx, double cy)
1293 {
1294 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
1295 }
1296
1297 // Whether p is inside or exactly on the circumcircle of triangle (a, b, c). Sign is negated vs
1298 // the usual predicate to match earcut's CCW winding — the standard sign builds the
1299 // anti-Delaunay mesh. Cocircular quads are legal ties, so refine only flips when this returns
1300 // false.
1301 static bool
1302 inCircle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py)
1303 {
1304 const double dx = ax - px, dy = ay - py, ex = bx - px, ey = by - py, fx = cx - px,
1305 fy = cy - py;
1306 const double ap = dx * dx + dy * dy, bp = ex * ex + ey * ey, cp = fx * fx + fy * fy;
1307 // A near-cocircular quad is a legal Delaunay tie, but roundoff can flag both an edge and
1308 // its flip as illegal, cascading into an endless flip loop (#205) — so treat a determinant
1309 // within a small margin of zero as a tie. The determinant's worst-case roundoff error is
1310 // provably below 9e-16·(ap+bp+cp)² (Shewchuk-style bound), so the margin guarantees every
1311 // executed flip is illegal in exact arithmetic, and Lawson flipping always terminates.
1312 const double s = ap + bp + cp;
1313 return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) <=
1314 1e-13 * s * s;
1315 }
1316
1317 void ensureScratch(std::size_t n)
1318 {
1319 // edgeStack holds at most one entry per half-edge (edgeStamp dedups), so n is a safe cap.
1320 if (edgeStackVec.size() < n) edgeStackVec.resize(n);
1321 if (heVec.size() < n) heVec.resize(n);
1322 if (edgeStampVec.size() < n) edgeStampVec.resize(n, 0);
1323 std::size_t size = 1;
1324 while (size < n * 4) size <<= 1; // power-of-two table, load factor <= 0.25
1325 if (hTableVec.size() < size) {
1326 hTableVec.resize(size);
1327 hStampVec.resize(size, 0);
1328 }
1329 hMask = uint32_t(size) - 1;
1330 }
1331};
1332
1333} // namespace detail
1334
1335// Opt-in Delaunay-refinement post-pass for earcut() output (or any manifold triangle-index array).
1336// Legalizes every interior edge in place with Lawson flips. See detail::Refiner. `coords` is a
1337// random-access container of points indexed by vertex index; `triangles` is mutated in place.
1338template <typename N, typename Coords>
1339void refine(std::vector<N>& triangles, const Coords& coords)
1340{
1341 static thread_local mapbox::detail::Refiner<N> refiner;
1342 refiner(triangles, coords);
1343}
1344
1345} // namespace mapbox
1346
1347} // namespace lagrange
Definition earcut.h:41
Definition earcut.h:1159
Main namespace for Lagrange.
Definition project.cpp:27
Definition earcut.h:28