Skip to main content

tess2_rust/mesh/
mod.rs

1// Copyright 2025 Lars Brubaker
2// License: SGI Free Software License B (MIT-compatible)
3//
4// Port of libtess2 mesh.c/h
5//
6// The mesh is a half-edge data structure (similar to Guibas/Stolfi quad-edge).
7// All pointers from the C code are replaced with u32 indices into Vec arenas.
8//
9// Design:
10//   - INVALID: u32::MAX  (null pointer equivalent)
11//   - Half-edges allocated in pairs: edges[i] and edges[i^1] are always a pair.
12//     sym(e) = e ^ 1.  Even index = e, odd index = eSym.
13//   - Sentinel/dummy nodes:
14//     - verts[0] = vHead (dummy vertex)
15//     - faces[0] = fHead (dummy face)
16//     - edges[0] = eHead, edges[1] = eHeadSym (dummy edge pair)
17
18mod delaunay;
19
20use crate::geom::{vert_ccw, Real};
21
22pub const INVALID: u32 = u32::MAX;
23
24/// Index into Mesh::verts
25pub type VertIdx = u32;
26/// Index into Mesh::faces
27pub type FaceIdx = u32;
28/// Index into Mesh::edges
29pub type EdgeIdx = u32;
30
31/// Compute the symmetric half-edge index (always the other half of the pair).
32#[inline(always)]
33pub fn sym(e: EdgeIdx) -> EdgeIdx {
34    e ^ 1
35}
36
37#[derive(Clone, Debug)]
38pub struct Vertex {
39    pub next: VertIdx,
40    pub prev: VertIdx,
41    pub an_edge: EdgeIdx,
42    pub coords: [Real; 3],
43    pub s: Real,
44    pub t: Real,
45    pub pq_handle: i32,
46    pub n: u32,
47    pub idx: u32,
48}
49
50impl Default for Vertex {
51    fn default() -> Self {
52        Self {
53            next: INVALID,
54            prev: INVALID,
55            an_edge: INVALID,
56            coords: [0.0; 3],
57            s: 0.0,
58            t: 0.0,
59            pq_handle: 0,
60            n: INVALID,
61            idx: INVALID,
62        }
63    }
64}
65
66#[derive(Clone, Debug)]
67pub struct Face {
68    pub next: FaceIdx,
69    pub prev: FaceIdx,
70    pub an_edge: EdgeIdx,
71    pub trail: FaceIdx,
72    pub n: u32,
73    pub marked: bool,
74    pub inside: bool,
75}
76
77impl Default for Face {
78    fn default() -> Self {
79        Self {
80            next: INVALID,
81            prev: INVALID,
82            an_edge: INVALID,
83            trail: INVALID,
84            n: INVALID,
85            marked: false,
86            inside: false,
87        }
88    }
89}
90
91#[derive(Clone, Debug)]
92pub struct HalfEdge {
93    /// Next in the global edge list (even-indexed edges link to even-indexed edges,
94    /// odd-indexed edges link to odd-indexed edges).
95    pub next: EdgeIdx,
96    /// Next edge CCW around the origin vertex.
97    pub onext: EdgeIdx,
98    /// Next edge CCW around the left face.
99    pub lnext: EdgeIdx,
100    /// Origin vertex index.
101    pub org: VertIdx,
102    /// Left face index.
103    pub lface: FaceIdx,
104    /// Active region index (INVALID if not in the edge dictionary).
105    pub active_region: u32,
106    /// Winding number change when crossing this edge.
107    pub winding: i32,
108    /// Used by edge flip (Delaunay refinement).
109    pub mark: bool,
110}
111
112impl Default for HalfEdge {
113    fn default() -> Self {
114        Self {
115            next: INVALID,
116            onext: INVALID,
117            lnext: INVALID,
118            org: INVALID,
119            lface: INVALID,
120            active_region: INVALID,
121            winding: 0,
122            mark: false,
123        }
124    }
125}
126
127/// The half-edge mesh.
128pub struct Mesh {
129    pub verts: Vec<Vertex>,
130    pub faces: Vec<Face>,
131    pub edges: Vec<HalfEdge>,
132}
133
134// ──────────────────────────────── Sentinel indices ────────────────────────────
135pub const V_HEAD: VertIdx = 0;
136pub const F_HEAD: FaceIdx = 0;
137pub const E_HEAD: EdgeIdx = 0;
138pub const E_HEAD_SYM: EdgeIdx = 1;
139
140impl Mesh {
141    /// Create a new empty mesh with dummy sentinel nodes.
142    pub fn new() -> Self {
143        let mut m = Mesh {
144            verts: Vec::new(),
145            faces: Vec::new(),
146            edges: Vec::new(),
147        };
148
149        // vHead (index 0) -- dummy vertex
150        let mut v_head = Vertex::default();
151        v_head.next = V_HEAD;
152        v_head.prev = V_HEAD;
153        v_head.an_edge = INVALID;
154        m.verts.push(v_head);
155
156        // fHead (index 0) -- dummy face
157        let mut f_head = Face::default();
158        f_head.next = F_HEAD;
159        f_head.prev = F_HEAD;
160        f_head.an_edge = INVALID;
161        f_head.trail = INVALID;
162        f_head.marked = false;
163        f_head.inside = false;
164        m.faces.push(f_head);
165
166        // eHead (index 0), eHeadSym (index 1) -- dummy edge pair
167        let mut e_head = HalfEdge::default();
168        e_head.next = E_HEAD;
169        e_head.onext = INVALID;
170        e_head.lnext = INVALID;
171        e_head.org = INVALID;
172        e_head.lface = INVALID;
173        e_head.winding = 0;
174        e_head.active_region = INVALID;
175
176        let mut e_head_sym = HalfEdge::default();
177        e_head_sym.next = E_HEAD_SYM;
178        e_head_sym.onext = INVALID;
179        e_head_sym.lnext = INVALID;
180        e_head_sym.org = INVALID;
181        e_head_sym.lface = INVALID;
182        e_head_sym.winding = 0;
183        e_head_sym.active_region = INVALID;
184
185        m.edges.push(e_head);
186        m.edges.push(e_head_sym);
187
188        m
189    }
190
191    // ──────────────── Navigation helpers (C macro translations) ────────────────
192
193    /// Symmetric half-edge (always the other element of the pair).
194    #[inline(always)]
195    pub fn esym(&self, e: EdgeIdx) -> EdgeIdx {
196        e ^ 1
197    }
198
199    /// Right face of e (= lface of Sym).
200    #[inline]
201    pub fn rface(&self, e: EdgeIdx) -> FaceIdx {
202        self.edges[(e ^ 1) as usize].lface
203    }
204
205    /// Destination vertex of e (= org of Sym).
206    #[inline]
207    pub fn dst(&self, e: EdgeIdx) -> VertIdx {
208        self.edges[(e ^ 1) as usize].org
209    }
210
211    /// Oprev: Sym->Lnext
212    #[inline]
213    pub fn oprev(&self, e: EdgeIdx) -> EdgeIdx {
214        self.edges[(e ^ 1) as usize].lnext
215    }
216
217    /// Lprev: Onext->Sym
218    #[inline]
219    pub fn lprev(&self, e: EdgeIdx) -> EdgeIdx {
220        self.edges[e as usize].onext ^ 1
221    }
222
223    /// Dprev: Lnext->Sym
224    #[inline]
225    pub fn dprev(&self, e: EdgeIdx) -> EdgeIdx {
226        self.edges[e as usize].lnext ^ 1
227    }
228
229    /// Rprev: Sym->Onext
230    #[inline]
231    pub fn rprev(&self, e: EdgeIdx) -> EdgeIdx {
232        self.edges[(e ^ 1) as usize].onext
233    }
234
235    /// Dnext: Rprev->Sym = (Sym->Onext)->Sym
236    #[inline]
237    pub fn dnext(&self, e: EdgeIdx) -> EdgeIdx {
238        self.edges[(e ^ 1) as usize].onext ^ 1
239    }
240
241    /// Rnext: Oprev->Sym = (Sym->Lnext)->Sym
242    #[inline]
243    pub fn rnext(&self, e: EdgeIdx) -> EdgeIdx {
244        self.edges[(e ^ 1) as usize].lnext ^ 1
245    }
246
247    /// EdgeGoesLeft: VertLeq(Dst, Org)
248    #[inline]
249    pub fn edge_goes_left(&self, e: EdgeIdx) -> bool {
250        let dst = self.dst(e);
251        let org = self.edges[e as usize].org;
252        let ds = self.verts[dst as usize].s;
253        let dt = self.verts[dst as usize].t;
254        let os = self.verts[org as usize].s;
255        let ot = self.verts[org as usize].t;
256        crate::geom::vert_leq(ds, dt, os, ot)
257    }
258
259    /// EdgeGoesRight: VertLeq(Org, Dst)
260    #[inline]
261    pub fn edge_goes_right(&self, e: EdgeIdx) -> bool {
262        let org = self.edges[e as usize].org;
263        let dst = self.dst(e);
264        let os = self.verts[org as usize].s;
265        let ot = self.verts[org as usize].t;
266        let ds = self.verts[dst as usize].s;
267        let dt = self.verts[dst as usize].t;
268        crate::geom::vert_leq(os, ot, ds, dt)
269    }
270
271    /// EdgeIsInternal: e->Rface && e->Rface->inside
272    #[inline]
273    pub fn edge_is_internal(&self, e: EdgeIdx) -> bool {
274        let rf = self.rface(e);
275        rf != INVALID && self.faces[rf as usize].inside
276    }
277
278    // ──────────────────────── Private allocation helpers ─────────────────────
279
280    /// Allocate a new half-edge pair.  Returns the index of `e` (even); sym is `e ^ 1`.
281    /// The new pair is inserted in the global edge list before `e_next`.
282    fn make_edge_pair(&mut self, e_next: EdgeIdx) -> EdgeIdx {
283        // Normalize: e_next must be the even half (e, not eSym)
284        let e_next = if e_next & 1 != 0 { e_next ^ 1 } else { e_next };
285
286        // Validate e_next
287        let e_next_sym = e_next ^ 1;
288        if (e_next as usize) >= self.edges.len() || (e_next_sym as usize) >= self.edges.len() {
289            return INVALID;
290        }
291
292        let e_new = self.edges.len() as EdgeIdx;
293        let e_sym = e_new ^ 1;
294
295        // ePrev = eNext->Sym->next
296        let e_prev = self.edges[(e_next ^ 1) as usize].next;
297        if e_prev == INVALID {
298            return INVALID;
299        }
300
301        // Insert new pair between ePrev and eNext in the global edge list.
302        // List A (even edges): ePrev ← e_new → e_next (forward)
303        // List B (odd edges): ePrev^1 ← e_sym → e_next^1
304        let mut e = HalfEdge::default();
305        e.next = e_next;
306        let mut e_s = HalfEdge::default();
307        e_s.next = e_prev;
308
309        self.edges.push(e); // index e_new
310        self.edges.push(e_s); // index e_sym
311
312        // ePrev->Sym->next = e_new  →  edges[e_prev^1].next = e_new
313        self.edges[(e_prev ^ 1) as usize].next = e_new;
314        // eNext->Sym->next = e_sym  →  edges[e_next^1].next = e_sym
315        self.edges[(e_next ^ 1) as usize].next = e_sym;
316
317        // Initialize edge fields
318        self.edges[e_new as usize].onext = e_new;
319        self.edges[e_new as usize].lnext = e_sym;
320        self.edges[e_new as usize].org = INVALID;
321        self.edges[e_new as usize].lface = INVALID;
322        self.edges[e_new as usize].winding = 0;
323        self.edges[e_new as usize].active_region = INVALID;
324        self.edges[e_new as usize].mark = false;
325
326        self.edges[e_sym as usize].onext = e_sym;
327        self.edges[e_sym as usize].lnext = e_new;
328        self.edges[e_sym as usize].org = INVALID;
329        self.edges[e_sym as usize].lface = INVALID;
330        self.edges[e_sym as usize].winding = 0;
331        self.edges[e_sym as usize].active_region = INVALID;
332        self.edges[e_sym as usize].mark = false;
333
334        e_new
335    }
336
337    /// Allocate a new vertex and insert it before `v_next` in the vertex list.
338    ///
339    /// Returns `INVALID` if `v_next` itself is `INVALID` (or out of bounds),
340    /// which happens when a caller hands us an edge whose sym-side origin
341    /// has been killed.  We propagate `INVALID` rather than crash so the
342    /// caller can decide whether to abort or continue.
343    fn make_vertex(&mut self, e_orig: EdgeIdx, v_next: VertIdx) -> VertIdx {
344        if v_next == INVALID || (v_next as usize) >= self.verts.len() {
345            return INVALID;
346        }
347        let v_new = self.verts.len() as VertIdx;
348        let v_prev = self.verts[v_next as usize].prev;
349        if v_prev == INVALID || (v_prev as usize) >= self.verts.len() {
350            return INVALID;
351        }
352
353        let mut v = Vertex::default();
354        v.prev = v_prev;
355        v.next = v_next;
356        v.an_edge = e_orig;
357        self.verts.push(v);
358
359        self.verts[v_prev as usize].next = v_new;
360        self.verts[v_next as usize].prev = v_new;
361
362        // Set all edges in the origin ring to point to v_new
363        let mut e = e_orig;
364        loop {
365            self.edges[e as usize].org = v_new;
366            e = self.edges[e as usize].onext;
367            if e == e_orig {
368                break;
369            }
370        }
371
372        v_new
373    }
374
375    /// Allocate a new face and insert it before `f_next` in the face list.
376    fn make_face(&mut self, e_orig: EdgeIdx, f_next: FaceIdx) -> FaceIdx {
377        if f_next == INVALID || (f_next as usize) >= self.faces.len() {
378            return INVALID;
379        }
380        let f_new = self.faces.len() as FaceIdx;
381        let f_prev = self.faces[f_next as usize].prev;
382        if f_prev == INVALID || (f_prev as usize) >= self.faces.len() {
383            return INVALID;
384        }
385
386        let inside_val = self.faces[f_next as usize].inside;
387
388        let mut f = Face::default();
389        f.prev = f_prev;
390        f.next = f_next;
391        f.an_edge = e_orig;
392        f.trail = INVALID;
393        f.marked = false;
394        f.inside = inside_val;
395        self.faces.push(f);
396
397        self.faces[f_prev as usize].next = f_new;
398        self.faces[f_next as usize].prev = f_new;
399
400        // Set all edges in the face loop to point to f_new
401        let mut e = e_orig;
402        loop {
403            self.edges[e as usize].lface = f_new;
404            e = self.edges[e as usize].lnext;
405            if e == e_orig {
406                break;
407            }
408        }
409
410        f_new
411    }
412
413    /// Kill (remove) a vertex from the global vertex list and update its edges to point to `new_org`.
414    ///
415    /// Defensive against `v_del == INVALID` and out-of-bounds:
416    /// callers reach this through edge `org` fields, which can be
417    /// `INVALID` after a partially-built mesh hits a degenerate region.
418    /// Forwarding the panic instead of returning made `wasm32` builds
419    /// crash with `index out of bounds: the len is N but the index is
420    /// 4294967295` on real-world tessellation inputs.
421    fn kill_vertex(&mut self, v_del: VertIdx, new_org: VertIdx) {
422        if v_del == INVALID || (v_del as usize) >= self.verts.len() {
423            return;
424        }
425        let e_start = self.verts[v_del as usize].an_edge;
426        if e_start != INVALID && (e_start as usize) < self.edges.len() {
427            let mut e = e_start;
428            loop {
429                self.edges[e as usize].org = new_org;
430                e = self.edges[e as usize].onext;
431                if e == INVALID || (e as usize) >= self.edges.len() || e == e_start {
432                    break;
433                }
434            }
435        }
436
437        let v_prev = self.verts[v_del as usize].prev;
438        let v_next = self.verts[v_del as usize].next;
439        if v_prev != INVALID && (v_prev as usize) < self.verts.len() {
440            self.verts[v_prev as usize].next = v_next;
441        }
442        if v_next != INVALID && (v_next as usize) < self.verts.len() {
443            self.verts[v_next as usize].prev = v_prev;
444        }
445
446        self.verts[v_del as usize].next = INVALID;
447        self.verts[v_del as usize].prev = INVALID;
448        self.verts[v_del as usize].an_edge = INVALID;
449    }
450
451    /// Kill (remove) a face from the global face list and update its edges to point to `new_lface`.
452    ///
453    /// Defensive against `f_del == INVALID` and out-of-bounds: see
454    /// [`Self::kill_vertex`] — `connect` can legitimately pass an
455    /// invalid `e_dst_lface` when only one side of the new edge has a
456    /// real face, and the original direct index panicked the wasm
457    /// build at `mesh/mod.rs:446: index out of bounds`.
458    fn kill_face(&mut self, f_del: FaceIdx, new_lface: FaceIdx) {
459        if f_del == INVALID || (f_del as usize) >= self.faces.len() {
460            return;
461        }
462        let e_start = self.faces[f_del as usize].an_edge;
463        if e_start != INVALID && (e_start as usize) < self.edges.len() {
464            let mut e = e_start;
465            loop {
466                self.edges[e as usize].lface = new_lface;
467                e = self.edges[e as usize].lnext;
468                if e == INVALID || (e as usize) >= self.edges.len() || e == e_start {
469                    break;
470                }
471            }
472        }
473
474        let f_prev = self.faces[f_del as usize].prev;
475        let f_next = self.faces[f_del as usize].next;
476        if f_prev != INVALID && (f_prev as usize) < self.faces.len() {
477            self.faces[f_prev as usize].next = f_next;
478        }
479        if f_next != INVALID && (f_next as usize) < self.faces.len() {
480            self.faces[f_next as usize].prev = f_prev;
481        }
482
483        self.faces[f_del as usize].next = INVALID;
484        self.faces[f_del as usize].prev = INVALID;
485        self.faces[f_del as usize].an_edge = INVALID;
486    }
487
488    /// Kill (remove) an edge pair from the global edge list.
489    ///
490    /// Defensive against `e_del == INVALID` and out-of-bounds — same
491    /// reasoning as the sibling `kill_vertex`/`kill_face` guards.
492    fn kill_edge(&mut self, e_del: EdgeIdx) {
493        if e_del == INVALID {
494            return;
495        }
496        let e_del = if e_del & 1 != 0 { e_del ^ 1 } else { e_del };
497        let nlen = self.edges.len() as u32;
498        if e_del >= nlen || (e_del ^ 1) >= nlen {
499            return;
500        }
501        let e_next = self.edges[e_del as usize].next;
502        let e_prev = self.edges[(e_del ^ 1) as usize].next;
503
504        if e_next != INVALID && (e_next ^ 1) < nlen {
505            self.edges[(e_next ^ 1) as usize].next = e_prev;
506        }
507        if e_prev != INVALID && (e_prev ^ 1) < nlen {
508            self.edges[(e_prev ^ 1) as usize].next = e_next;
509        }
510
511        self.edges[e_del as usize].next = INVALID;
512        self.edges[(e_del ^ 1) as usize].next = INVALID;
513    }
514
515    // ──────────────────────── Public mesh operations ──────────────────────────
516
517    /// tessMeshMakeEdge: creates one edge, two vertices, and a loop (face).
518    pub fn make_edge(&mut self) -> Option<EdgeIdx> {
519        let e = self.make_edge_pair(E_HEAD);
520        let e_sym = e ^ 1;
521
522        let v1 = self.make_vertex(e, V_HEAD);
523        let v2 = self.make_vertex(e_sym, V_HEAD);
524        let _f = self.make_face(e, F_HEAD);
525
526        self.edges[e as usize].org = v1;
527        self.edges[e_sym as usize].org = v2;
528
529        Some(e)
530    }
531
532    /// tessMeshSplice: the fundamental connectivity-changing operation.
533    /// Exchanges eOrg->Onext and eDst->Onext.
534    pub fn splice(&mut self, e_org: EdgeIdx, e_dst: EdgeIdx) -> bool {
535        if e_org == e_dst {
536            return true;
537        }
538
539        let org_org = self.edges[e_org as usize].org;
540        let dst_org = self.edges[e_dst as usize].org;
541        let org_lface = self.edges[e_org as usize].lface;
542        let dst_lface = self.edges[e_dst as usize].lface;
543
544        let joining_vertices = dst_org != org_org;
545        let joining_loops = dst_lface != org_lface;
546
547        if joining_vertices {
548            self.kill_vertex(dst_org, org_org);
549        }
550        if joining_loops {
551            self.kill_face(dst_lface, org_lface);
552        }
553
554        Mesh::do_splice(&mut self.edges, e_org, e_dst);
555
556        if !joining_vertices {
557            let new_v = self.make_vertex(e_dst, org_org);
558            // make sure old vertex still has a valid half-edge
559            self.edges[e_org as usize].org = org_org; // org unchanged
560            self.verts[org_org as usize].an_edge = e_org;
561            let _ = new_v;
562        }
563        if !joining_loops {
564            let new_f = self.make_face(e_dst, org_lface);
565            self.verts[org_org as usize].an_edge = e_org; // leave org alone
566            self.faces[org_lface as usize].an_edge = e_org;
567            let _ = new_f;
568        }
569
570        true
571    }
572
573    fn do_splice(edges: &mut Vec<HalfEdge>, a: EdgeIdx, b: EdgeIdx) {
574        let a_onext = edges[a as usize].onext;
575        let b_onext = edges[b as usize].onext;
576        edges[(a_onext ^ 1) as usize].lnext = b;
577        edges[(b_onext ^ 1) as usize].lnext = a;
578        edges[a as usize].onext = b_onext;
579        edges[b as usize].onext = a_onext;
580    }
581
582    /// tessMeshDelete: remove edge eDel.
583    pub fn delete_edge(&mut self, e_del: EdgeIdx) -> bool {
584        let e_del_sym = e_del ^ 1;
585
586        let e_del_lface = self.edges[e_del as usize].lface;
587        let e_del_rface = self.rface(e_del);
588        let joining_loops = e_del_lface != e_del_rface;
589
590        if joining_loops {
591            self.kill_face(e_del_lface, e_del_rface);
592        }
593
594        let e_del_onext = self.edges[e_del as usize].onext;
595        if e_del_onext == e_del {
596            let e_del_org = self.edges[e_del as usize].org;
597            self.kill_vertex(e_del_org, INVALID);
598        } else {
599            // Make sure eDel->Org and eDel->Rface point to valid half-edges
600            let e_del_oprev = self.oprev(e_del);
601            let e_del_rface2 = self.rface(e_del);
602            self.faces[e_del_rface2 as usize].an_edge = e_del_oprev;
603            let e_del_org2 = self.edges[e_del as usize].org;
604            self.verts[e_del_org2 as usize].an_edge = e_del_onext;
605
606            Mesh::do_splice(&mut self.edges, e_del, e_del_oprev);
607
608            if !joining_loops {
609                let new_f = self.make_face(e_del, e_del_lface);
610                let _ = new_f;
611            }
612        }
613
614        let e_del_sym_onext = self.edges[e_del_sym as usize].onext;
615        if e_del_sym_onext == e_del_sym {
616            let e_del_sym_org = self.edges[e_del_sym as usize].org;
617            self.kill_vertex(e_del_sym_org, INVALID);
618            let e_del_lface2 = self.edges[e_del as usize].lface;
619            self.kill_face(e_del_lface2, INVALID);
620        } else {
621            let e_del_lface3 = self.edges[e_del as usize].lface;
622            let e_del_sym_oprev = self.oprev(e_del_sym);
623            self.faces[e_del_lface3 as usize].an_edge = e_del_sym_oprev;
624            let e_del_sym_org2 = self.edges[e_del_sym as usize].org;
625            self.verts[e_del_sym_org2 as usize].an_edge = e_del_sym_onext;
626            Mesh::do_splice(&mut self.edges, e_del_sym, e_del_sym_oprev);
627        }
628
629        self.kill_edge(e_del);
630        true
631    }
632
633    /// tessMeshAddEdgeVertex: create a new edge eNew = eOrg->Lnext,
634    /// and eNew->Dst is a new vertex. eOrg and eNew share the same left face.
635    pub fn add_edge_vertex(&mut self, e_org: EdgeIdx) -> Option<EdgeIdx> {
636        let e_new = self.make_edge_pair(e_org);
637        if e_new == INVALID {
638            return None;
639        }
640        let e_new_sym = e_new ^ 1;
641
642        // Connect: eNew is inserted after eOrg in the Lnext ring
643        let e_org_lnext = self.edges[e_org as usize].lnext;
644        Mesh::do_splice(&mut self.edges, e_new, e_org_lnext);
645
646        // Set origin of eNew to eOrg->Dst
647        let e_org_dst = self.dst(e_org);
648        self.edges[e_new as usize].org = e_org_dst;
649
650        // Create new vertex at the other end.  If `e_org`'s Dst has been
651        // killed upstream (`dst(e_org)` == INVALID) we can't build a valid
652        // vertex for the new edge — bail instead of indexing INVALID into
653        // `self.verts`.  This can occur when the sweep deletes edges in a
654        // different order than libtess2 expects for some self-intersecting
655        // inputs.
656        let v_new = self.make_vertex(e_new_sym, e_org_dst);
657        if v_new == INVALID {
658            return None;
659        }
660
661        // Both eNew and eNewSym share the same left face as eOrg
662        let e_org_lface = self.edges[e_org as usize].lface;
663        self.edges[e_new as usize].lface = e_org_lface;
664        self.edges[e_new_sym as usize].lface = e_org_lface;
665
666        Some(e_new)
667    }
668
669    /// tessMeshSplitEdge: split eOrg into eOrg and eNew, with eNew = eOrg->Lnext.
670    pub fn split_edge(&mut self, e_org: EdgeIdx) -> Option<EdgeIdx> {
671        let temp = self.add_edge_vertex(e_org)?;
672        let e_new = temp ^ 1;
673
674        // Disconnect eOrg from eOrg->Dst and reconnect to eNew->Org
675        let e_org_sym = e_org ^ 1;
676        let e_org_sym_oprev = self.oprev(e_org_sym);
677        Mesh::do_splice(&mut self.edges, e_org_sym, e_org_sym_oprev);
678        Mesh::do_splice(&mut self.edges, e_org_sym, e_new);
679
680        // Update vertex/face pointers
681        let e_new_org = self.edges[e_new as usize].org;
682        let e_org_dst_idx = e_org ^ 1; // sym
683        self.edges[e_org_dst_idx as usize].org = e_new_org;
684        let e_new_dst = self.dst(e_new);
685        self.verts[e_new_dst as usize].an_edge = e_new ^ 1;
686
687        let e_org_rface = self.rface(e_org);
688        self.edges[(e_new ^ 1) as usize].lface = e_org_rface; // eNew->Rface = eOrg->Rface (Rface = Sym->Lface)
689        let e_org_winding = self.edges[e_org as usize].winding;
690        let e_org_sym_winding = self.edges[e_org_sym as usize].winding;
691        self.edges[e_new as usize].winding = e_org_winding;
692        self.edges[(e_new ^ 1) as usize].winding = e_org_sym_winding;
693
694        Some(e_new)
695    }
696
697    /// tessMeshConnect: create a new edge from eOrg->Dst to eDst->Org.
698    /// Returns the new half-edge.
699    pub fn connect(&mut self, e_org: EdgeIdx, e_dst: EdgeIdx) -> Option<EdgeIdx> {
700        let e_new = self.make_edge_pair(e_org);
701        // If `make_edge_pair` couldn't allocate (out-of-bounds seed, broken
702        // `next` chain on the sym side), bail.  Forwarding the `INVALID`
703        // into the subsequent `do_splice`/`kill_face` was the root cause of
704        // the lion-polygon `INVALID do_splice` panic.  Returning `None`
705        // lets `tessellate_mono_region` skip this triangulation step; the
706        // face is then marked non-inside so no degenerate output slips
707        // through (see `tessellate_interior`'s fallback).
708        if e_new == INVALID { return None; }
709        let e_new_sym = e_new ^ 1;
710
711        let e_dst_lface = self.edges[e_dst as usize].lface;
712        let e_org_lface = self.edges[e_org as usize].lface;
713        let joining_loops = e_dst_lface != e_org_lface;
714
715        if joining_loops {
716            self.kill_face(e_dst_lface, e_org_lface);
717        }
718
719        // Connect: Splice(eNew, eOrg->Lnext); Splice(eNewSym, eDst)
720        let e_org_lnext = self.edges[e_org as usize].lnext;
721        Mesh::do_splice(&mut self.edges, e_new, e_org_lnext);
722        Mesh::do_splice(&mut self.edges, e_new_sym, e_dst);
723
724        // Set vertex/face
725        let e_org_dst = self.dst(e_org);
726        self.edges[e_new as usize].org = e_org_dst;
727        let e_dst_org = self.edges[e_dst as usize].org;
728        self.edges[e_new_sym as usize].org = e_dst_org;
729        self.edges[e_new as usize].lface = e_org_lface;
730        self.edges[e_new_sym as usize].lface = e_org_lface;
731
732        // Make sure the old face points to a valid half-edge
733        self.faces[e_org_lface as usize].an_edge = e_new_sym;
734
735        if !joining_loops {
736            let new_f = self.make_face(e_new, e_org_lface);
737            let _ = new_f;
738        }
739
740        Some(e_new)
741    }
742
743    /// tessMeshZapFace: destroy a face and remove it from the global face list.
744    /// All edges of fZap get lface = INVALID. Edges whose rface is also INVALID
745    /// are deleted entirely.
746    pub fn zap_face(&mut self, f_zap: FaceIdx) {
747        if f_zap == INVALID || (f_zap as usize) >= self.faces.len() {
748            return;
749        }
750        let e_start = self.faces[f_zap as usize].an_edge;
751        if e_start == INVALID || (e_start as usize) >= self.edges.len() {
752            return;
753        }
754        let mut e_next = self.edges[e_start as usize].lnext;
755
756        loop {
757            let e = e_next;
758            e_next = self.edges[e as usize].lnext;
759
760            self.edges[e as usize].lface = INVALID;
761
762            let e_rface = self.rface(e);
763            if e_rface == INVALID {
764                // Delete the edge
765                let e_onext = self.edges[e as usize].onext;
766                if e_onext == e {
767                    let e_org = self.edges[e as usize].org;
768                    if e_org != INVALID {
769                        self.kill_vertex(e_org, INVALID);
770                    }
771                } else {
772                    let e_org = self.edges[e as usize].org;
773                    if e_org != INVALID {
774                        self.verts[e_org as usize].an_edge = e_onext;
775                    }
776                    let e_oprev = self.oprev(e);
777                    Mesh::do_splice(&mut self.edges, e, e_oprev);
778                }
779
780                let e_sym = e ^ 1;
781                let e_sym_onext = self.edges[e_sym as usize].onext;
782                if e_sym_onext == e_sym {
783                    let e_sym_org = self.edges[e_sym as usize].org;
784                    if e_sym_org != INVALID {
785                        self.kill_vertex(e_sym_org, INVALID);
786                    }
787                } else {
788                    let e_sym_org = self.edges[e_sym as usize].org;
789                    if e_sym_org != INVALID {
790                        self.verts[e_sym_org as usize].an_edge = e_sym_onext;
791                    }
792                    let e_sym_oprev = self.oprev(e_sym);
793                    Mesh::do_splice(&mut self.edges, e_sym, e_sym_oprev);
794                }
795
796                self.kill_edge(e);
797            }
798
799            if e == e_start {
800                break;
801            }
802        }
803
804        let f_prev = self.faces[f_zap as usize].prev;
805        let f_next = self.faces[f_zap as usize].next;
806        if f_prev != INVALID && (f_prev as usize) < self.faces.len() {
807            self.faces[f_prev as usize].next = f_next;
808        }
809        if f_next != INVALID && (f_next as usize) < self.faces.len() {
810            self.faces[f_next as usize].prev = f_prev;
811        }
812        self.faces[f_zap as usize].next = INVALID;
813        self.faces[f_zap as usize].prev = INVALID;
814        self.faces[f_zap as usize].an_edge = INVALID;
815    }
816
817    /// Count vertices in a face loop.
818    pub fn count_face_verts(&self, f: FaceIdx) -> usize {
819        let e_start = self.faces[f as usize].an_edge;
820        let mut e = e_start;
821        let mut n = 0;
822        loop {
823            n += 1;
824            e = self.edges[e as usize].lnext;
825            if e == e_start {
826                break;
827            }
828        }
829        n
830    }
831
832    /// tessMeshMergeConvexFaces: merge convex adjacent faces if the result
833    /// would have <= maxVertsPerFace vertices.
834    pub fn merge_convex_faces(&mut self, max_verts_per_face: usize) -> bool {
835        let mut e = self.edges[E_HEAD as usize].next;
836        while e != E_HEAD {
837            let e_next = self.edges[e as usize].next;
838            let e_sym = e ^ 1;
839
840            let e_lface = self.edges[e as usize].lface;
841            let e_sym_lface = self.edges[e_sym as usize].lface;
842
843            if e_lface == INVALID
844                || !self.faces[e_lface as usize].inside
845                || e_sym_lface == INVALID
846                || !self.faces[e_sym_lface as usize].inside
847            {
848                e = e_next;
849                continue;
850            }
851
852            let left_nv = self.count_face_verts(e_lface);
853            let right_nv = self.count_face_verts(e_sym_lface);
854            if left_nv + right_nv - 2 > max_verts_per_face {
855                e = e_next;
856                continue;
857            }
858
859            // Check convexity: va--vb--vc and vd--ve--vf must be CCW
860            let va = self.edges[self.lprev(e) as usize].org;
861            let vb = self.edges[e as usize].org;
862            let vc_edge = self.edges[e_sym as usize].lnext;
863            let vc = self.dst(vc_edge);
864
865            let vd = self.edges[self.lprev(e_sym) as usize].org;
866            let ve = self.edges[e_sym as usize].org;
867            let vf_edge = self.edges[e as usize].lnext;
868            let vf = self.dst(vf_edge);
869
870            let convex = vert_ccw(
871                self.verts[va as usize].s,
872                self.verts[va as usize].t,
873                self.verts[vb as usize].s,
874                self.verts[vb as usize].t,
875                self.verts[vc as usize].s,
876                self.verts[vc as usize].t,
877            ) && vert_ccw(
878                self.verts[vd as usize].s,
879                self.verts[vd as usize].t,
880                self.verts[ve as usize].s,
881                self.verts[ve as usize].t,
882                self.verts[vf as usize].s,
883                self.verts[vf as usize].t,
884            );
885
886            if convex {
887                let actual_next = if e == e_next || e == e_next ^ 1 {
888                    self.edges[e_next as usize].next
889                } else {
890                    e_next
891                };
892                if !self.delete_edge(e) {
893                    return false;
894                }
895                e = actual_next;
896                continue;
897            }
898
899            e = e_next;
900        }
901        true
902    }
903
904    /// tessMeshFlipEdge: flip an internal edge (used for Delaunay refinement).
905    pub fn flip_edge(&mut self, edge: EdgeIdx) {
906        let a0 = edge;
907        let a1 = self.edges[a0 as usize].lnext;
908        let a2 = self.edges[a1 as usize].lnext;
909        let b0 = edge ^ 1;
910        let b1 = self.edges[b0 as usize].lnext;
911        let b2 = self.edges[b1 as usize].lnext;
912
913        let a_org = self.edges[a0 as usize].org;
914        let a_opp = self.edges[a2 as usize].org;
915        let b_org = self.edges[b0 as usize].org;
916        let b_opp = self.edges[b2 as usize].org;
917
918        let fa = self.edges[a0 as usize].lface;
919        let fb = self.edges[b0 as usize].lface;
920
921        self.edges[a0 as usize].org = b_opp;
922        self.edges[a0 as usize].onext = self.edges[b1 as usize].onext ^ 1; // b1->Sym
923        self.edges[b0 as usize].org = a_opp;
924        self.edges[b0 as usize].onext = self.edges[a1 as usize].onext ^ 1; // a1->Sym
925        self.edges[a2 as usize].onext = b0;
926        self.edges[b2 as usize].onext = a0;
927        self.edges[b1 as usize].onext = self.edges[a2 as usize].onext ^ 1; // a2->Sym... wait
928
929        // Redo using correct flip logic from C code:
930        self.edges[a0 as usize].lnext = a2;
931        self.edges[a2 as usize].lnext = b1;
932        self.edges[b1 as usize].lnext = a0;
933
934        self.edges[b0 as usize].lnext = b2;
935        self.edges[b2 as usize].lnext = a1;
936        self.edges[a1 as usize].lnext = b0;
937
938        self.edges[a1 as usize].lface = fb;
939        self.edges[b1 as usize].lface = fa;
940
941        self.faces[fa as usize].an_edge = a0;
942        self.faces[fb as usize].an_edge = b0;
943
944        if self.verts[a_org as usize].an_edge == a0 {
945            self.verts[a_org as usize].an_edge = b1;
946        }
947        if self.verts[b_org as usize].an_edge == b0 {
948            self.verts[b_org as usize].an_edge = a1;
949        }
950    }
951
952    /// tessMeshSetWindingNumber: reset winding numbers.
953    pub fn set_winding_number(&mut self, value: i32, keep_only_boundary: bool) -> bool {
954        let mut e = self.edges[E_HEAD as usize].next;
955        while e != E_HEAD {
956            let e_next = self.edges[e as usize].next;
957            let e_lface = self.edges[e as usize].lface;
958            let e_rface = self.rface(e);
959
960            let lf_inside = if e_lface != INVALID {
961                self.faces[e_lface as usize].inside
962            } else {
963                false
964            };
965            let rf_inside = if e_rface != INVALID {
966                self.faces[e_rface as usize].inside
967            } else {
968                false
969            };
970
971            if rf_inside != lf_inside {
972                self.edges[e as usize].winding = if lf_inside { value } else { -value };
973            } else if !keep_only_boundary {
974                self.edges[e as usize].winding = 0;
975            } else if !self.delete_edge(e) {
976                return false;
977            }
978
979            e = e_next;
980        }
981        true
982    }
983
984    /// Discard all exterior faces (zap them).
985    pub fn discard_exterior(&mut self) {
986        let mut f = self.faces[F_HEAD as usize].next;
987        while f != F_HEAD {
988            let next = self.faces[f as usize].next;
989            if !self.faces[f as usize].inside {
990                self.zap_face(f);
991            }
992            f = next;
993        }
994    }
995
996}
997
998mod tessellate;
999
1000impl Default for Mesh {
1001    fn default() -> Self {
1002        Self::new()
1003    }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008    use super::*;
1009
1010    #[test]
1011    fn make_edge_creates_single_edge() {
1012        let mut mesh = Mesh::new();
1013        let e = mesh.make_edge().unwrap();
1014        // Should have 3 vertices (vHead + 2 new), 2 faces (fHead + 1 new), 4 edges (eHead pair + 1 pair)
1015        assert_eq!(mesh.verts.len(), 3);
1016        assert_eq!(mesh.faces.len(), 2);
1017        assert_eq!(mesh.edges.len(), 4);
1018        // Edge and its sym should have different orgs
1019        let org1 = mesh.edges[e as usize].org;
1020        let org2 = mesh.edges[(e ^ 1) as usize].org;
1021        assert_ne!(org1, org2);
1022        assert_ne!(org1, INVALID);
1023        assert_ne!(org2, INVALID);
1024    }
1025
1026    #[test]
1027    fn sym_involution() {
1028        // sym(sym(e)) == e
1029        for e in 0u32..16 {
1030            assert_eq!(sym(sym(e)), e);
1031        }
1032    }
1033
1034    #[test]
1035    fn vertex_list_circular() {
1036        let mut mesh = Mesh::new();
1037        mesh.make_edge().unwrap();
1038        // vHead.next.next should eventually circle back
1039        let first = mesh.verts[V_HEAD as usize].next;
1040        assert_ne!(first, V_HEAD);
1041        let second = mesh.verts[first as usize].next;
1042        assert_ne!(second, INVALID);
1043    }
1044
1045    /// Regression: `kill_face`, `kill_vertex`, and `kill_edge` used to
1046    /// index `self.faces[INVALID as usize]` directly, panicking the
1047    /// wasm32 build with `index out of bounds: the len is N but the
1048    /// index is 4294967295` when `connect()` joined a real face to an
1049    /// `INVALID` neighbour.  These now early-return for `INVALID` /
1050    /// out-of-range targets so partially-built meshes degrade
1051    /// gracefully instead of crashing the host.
1052    #[test]
1053    fn kill_helpers_tolerate_invalid_index() {
1054        let mut mesh = Mesh::new();
1055        mesh.kill_vertex(INVALID, INVALID);
1056        mesh.kill_face(INVALID, INVALID);
1057        mesh.kill_edge(INVALID);
1058        mesh.kill_vertex(u32::MAX - 1, INVALID);
1059        mesh.kill_face(u32::MAX - 1, INVALID);
1060        mesh.kill_edge(u32::MAX - 1);
1061        mesh.zap_face(INVALID);
1062        mesh.zap_face(u32::MAX - 1);
1063    }
1064}