manifold-csg 0.1.4

Safe Rust bindings to manifold3d — f64-precision CSG booleans, 2D cross-sections, extrusion, SDF, and OBJ I/O with Send safety and automatic memory management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Safe wrappers for manifold3d mesh data types.
//!
//! [`MeshGL`] wraps f32 mesh data, [`MeshGL64`] wraps f64 mesh data.
//! These are primarily used for constructing [`Manifold`](crate::Manifold)
//! objects and extracting mesh data from them.

use manifold_csg_sys::*;

/// Safe wrapper around a manifold3d MeshGL object (f32 vertices, u32 indices).
///
/// See the [upstream `MeshGL` docs](https://elalish.github.io/manifold/docs/html/structmanifold_1_1_mesh_g_l_p.html)
/// for field semantics (run indices, merge vectors, tangents, etc.).
pub struct MeshGL {
    ptr: *mut ManifoldMeshGL,
}

// SAFETY: MeshGL owns its heap allocation with no thread-local state.
unsafe impl Send for MeshGL {}

// SAFETY: MeshGL is a pure data container (vertex arrays, index arrays) with no
// lazy evaluation or mutable internal state. Concurrent read access is safe.
unsafe impl Sync for MeshGL {}

impl Drop for MeshGL {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            // SAFETY: self.ptr was allocated by manifold_alloc_meshgl.
            unsafe { manifold_delete_meshgl(self.ptr) };
        }
    }
}

impl MeshGL {
    /// Create a MeshGL from f32 vertex properties and u32 triangle indices.
    ///
    /// `vert_props` is a flat array with `n_props` values per vertex
    /// (minimum 3 for x, y, z). `tri_indices` has 3 values per triangle.
    ///
    /// # Panics
    ///
    /// Panics if `n_props < 3`, if `vert_props.len()` is not divisible by
    /// `n_props`, or if `tri_indices.len()` is not divisible by 3.
    #[must_use]
    pub fn new(vert_props: &[f32], n_props: usize, tri_indices: &[u32]) -> Self {
        assert!(n_props >= 3, "n_props must be >= 3");
        assert!(
            vert_props.len() % n_props == 0,
            "vert_props length must be divisible by n_props"
        );
        assert!(
            tri_indices.len() % 3 == 0,
            "tri_indices length must be divisible by 3"
        );
        let n_verts = vert_props.len() / n_props;
        let n_tris = tri_indices.len() / 3;

        // SAFETY: manifold_alloc_meshgl returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl() };
        // SAFETY: ptr is valid, slices are valid with correct lengths.
        unsafe {
            manifold_meshgl(
                ptr,
                vert_props.as_ptr(),
                n_verts,
                n_props,
                tri_indices.as_ptr(),
                n_tris,
            );
        }
        Self { ptr }
    }

    /// Create a MeshGL with halfedge tangent data.
    ///
    /// `halfedge_tangent` must have `num_tri * 3 * 4` elements (4 floats per
    /// halfedge, 3 halfedges per triangle).
    ///
    /// # Panics
    ///
    /// Same as [`new`](Self::new).
    #[must_use]
    pub fn new_with_tangents(
        vert_props: &[f32],
        n_props: usize,
        tri_indices: &[u32],
        halfedge_tangent: &[f32],
    ) -> Self {
        assert!(n_props >= 3, "n_props must be >= 3");
        assert!(vert_props.len() % n_props == 0);
        assert!(tri_indices.len() % 3 == 0);
        let n_verts = vert_props.len() / n_props;
        let n_tris = tri_indices.len() / 3;

        // SAFETY: manifold_alloc_meshgl returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl() };
        // SAFETY: ptr valid, all slices valid with correct lengths.
        unsafe {
            manifold_meshgl_w_tangents(
                ptr,
                vert_props.as_ptr(),
                n_verts,
                n_props,
                tri_indices.as_ptr(),
                n_tris,
                halfedge_tangent.as_ptr(),
            );
        }
        Self { ptr }
    }

    /// Number of vertices.
    #[must_use]
    pub fn num_vert(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl_num_vert(self.ptr) }
    }

    /// Number of triangles.
    #[must_use]
    pub fn num_tri(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl_num_tri(self.ptr) }
    }

    /// Number of properties per vertex.
    #[must_use]
    pub fn num_prop(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl_num_prop(self.ptr) }
    }

    /// Copy vertex properties out as a flat f32 array.
    #[must_use]
    pub fn vert_properties(&self) -> Vec<f32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_vert_properties_length(self.ptr) };
        let mut buf = vec![0.0f32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_vert_properties(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy triangle indices out as a flat u32 array.
    #[must_use]
    pub fn tri_verts(&self) -> Vec<u32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_tri_length(self.ptr) };
        let mut buf = vec![0u32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_tri_verts(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Merge coincident vertices, returning a new mesh.
    ///
    /// Processes the mesh's merge vectors to weld vertices that share
    /// the same position. Returns a new mesh (the original is unchanged).
    #[must_use]
    pub fn merge(&self) -> Self {
        // SAFETY: manifold_alloc_meshgl returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl() };
        // SAFETY: ptr and self.ptr are valid.
        unsafe { manifold_meshgl_merge(ptr, self.ptr) };
        Self { ptr }
    }

    /// Copy merge-from vertex indices out as a flat u32 array.
    #[must_use]
    pub fn merge_from_vert(&self) -> Vec<u32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_merge_length(self.ptr) };
        let mut buf = vec![0u32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_merge_from_vert(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy merge-to vertex indices out as a flat u32 array.
    #[must_use]
    pub fn merge_to_vert(&self) -> Vec<u32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_merge_length(self.ptr) };
        let mut buf = vec![0u32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_merge_to_vert(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy run indices out as a flat u32 array.
    #[must_use]
    pub fn run_index(&self) -> Vec<u32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_run_index_length(self.ptr) };
        let mut buf = vec![0u32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_run_index(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy run original IDs out as a flat u32 array.
    #[must_use]
    pub fn run_original_id(&self) -> Vec<u32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_run_original_id_length(self.ptr) };
        let mut buf = vec![0u32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_run_original_id(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy run transforms out as a flat f32 array (4x3 matrices, 12 floats each).
    #[must_use]
    pub fn run_transform(&self) -> Vec<f32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_run_transform_length(self.ptr) };
        let mut buf = vec![0.0f32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_run_transform(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy face IDs out as a flat u32 array.
    #[must_use]
    pub fn face_id(&self) -> Vec<u32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_face_id_length(self.ptr) };
        let mut buf = vec![0u32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_face_id(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy halfedge tangents out as a flat f32 array (4 floats per halfedge).
    #[must_use]
    pub fn halfedge_tangent(&self) -> Vec<f32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_tangent_length(self.ptr) };
        let mut buf = vec![0.0f32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_halfedge_tangent(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Tolerance used for merging and vertex welding.
    #[must_use]
    pub fn tolerance(&self) -> f32 {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl_tolerance(self.ptr) }
    }

    /// Number of triangle runs.
    #[must_use]
    pub fn num_run(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl_num_run(self.ptr) }
    }

    /// Copy run flags out as a u8 array (one per triangle run).
    #[must_use]
    pub fn run_flags(&self) -> Vec<u8> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl_run_flags_length(self.ptr) };
        let mut buf = vec![0u8; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl_run_flags(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Update normals based on run transforms and backside flags, then clear
    /// those fields to avoid double-applying on round-trip.
    ///
    /// `normal_idx` specifies the first of three consecutive property channels
    /// forming the (x, y, z) normals. Must be >= 3 and `num_prop` must be at
    /// least `normal_idx + 3`.
    pub fn update_normals(&mut self, normal_idx: i32) {
        // SAFETY: self.ptr is valid (invariant), mutation is exclusive via &mut self.
        unsafe { manifold_meshgl_update_normals(self.ptr, normal_idx) };
    }
}

impl Clone for MeshGL {
    fn clone(&self) -> Self {
        // SAFETY: manifold_alloc_meshgl returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl() };
        // SAFETY: ptr and self.ptr are valid.
        unsafe { manifold_meshgl_copy(ptr, self.ptr) };
        Self { ptr }
    }
}

/// Safe wrapper around a manifold3d MeshGL64 object (f64 vertices, u64 indices).
///
/// This is the high-precision variant — use this when sub-mm features matter
/// at large coordinates (e.g., 0.6mm indents at z=128mm).
///
/// See the [upstream `MeshGL` docs](https://elalish.github.io/manifold/docs/html/structmanifold_1_1_mesh_g_l_p.html)
/// for field semantics (run indices, merge vectors, tangents, etc.).
pub struct MeshGL64 {
    ptr: *mut ManifoldMeshGL64,
}

// SAFETY: MeshGL64 owns its heap allocation with no thread-local state.
unsafe impl Send for MeshGL64 {}

// SAFETY: MeshGL64 is a pure data container (vertex arrays, index arrays) with
// no lazy evaluation or mutable internal state. Concurrent read access is safe.
unsafe impl Sync for MeshGL64 {}

impl Drop for MeshGL64 {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            // SAFETY: self.ptr was allocated by manifold_alloc_meshgl64.
            unsafe { manifold_delete_meshgl64(self.ptr) };
        }
    }
}

impl MeshGL64 {
    /// Create a MeshGL64 from f64 vertex properties and u64 triangle indices.
    ///
    /// # Panics
    ///
    /// Panics if `n_props < 3`, if `vert_props.len()` is not divisible by
    /// `n_props`, or if `tri_indices.len()` is not divisible by 3.
    #[must_use]
    pub fn new(vert_props: &[f64], n_props: usize, tri_indices: &[u64]) -> Self {
        assert!(n_props >= 3, "n_props must be >= 3");
        assert!(
            vert_props.len() % n_props == 0,
            "vert_props length must be divisible by n_props"
        );
        assert!(
            tri_indices.len() % 3 == 0,
            "tri_indices length must be divisible by 3"
        );
        let n_verts = vert_props.len() / n_props;
        let n_tris = tri_indices.len() / 3;

        // SAFETY: manifold_alloc_meshgl64 returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl64() };
        // SAFETY: ptr is valid, slices are valid with correct lengths.
        unsafe {
            manifold_meshgl64(
                ptr,
                vert_props.as_ptr(),
                n_verts,
                n_props,
                tri_indices.as_ptr(),
                n_tris,
            );
        }
        Self { ptr }
    }

    /// Create a MeshGL64 with halfedge tangent data.
    ///
    /// See [`MeshGL::new_with_tangents`] for details.
    #[must_use]
    pub fn new_with_tangents(
        vert_props: &[f64],
        n_props: usize,
        tri_indices: &[u64],
        halfedge_tangent: &[f64],
    ) -> Self {
        assert!(n_props >= 3, "n_props must be >= 3");
        assert!(vert_props.len() % n_props == 0);
        assert!(tri_indices.len() % 3 == 0);
        let n_verts = vert_props.len() / n_props;
        let n_tris = tri_indices.len() / 3;

        // SAFETY: manifold_alloc_meshgl64 returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl64() };
        // SAFETY: ptr valid, all slices valid with correct lengths.
        unsafe {
            manifold_meshgl64_w_tangents(
                ptr,
                vert_props.as_ptr(),
                n_verts,
                n_props,
                tri_indices.as_ptr(),
                n_tris,
                halfedge_tangent.as_ptr(),
            );
        }
        Self { ptr }
    }

    /// Number of vertices.
    #[must_use]
    pub fn num_vert(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl64_num_vert(self.ptr) }
    }

    /// Number of triangles.
    #[must_use]
    pub fn num_tri(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl64_num_tri(self.ptr) }
    }

    /// Number of properties per vertex.
    #[must_use]
    pub fn num_prop(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl64_num_prop(self.ptr) }
    }

    /// Copy vertex properties out as a flat f64 array.
    #[must_use]
    pub fn vert_properties(&self) -> Vec<f64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_vert_properties_length(self.ptr) };
        let mut buf = vec![0.0f64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_vert_properties(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy triangle indices out as a flat u64 array.
    #[must_use]
    pub fn tri_verts(&self) -> Vec<u64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_tri_length(self.ptr) };
        let mut buf = vec![0u64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_tri_verts(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Merge coincident vertices, returning a new mesh.
    ///
    /// Processes the mesh's merge vectors to weld vertices that share
    /// the same position. Returns a new mesh (the original is unchanged).
    #[must_use]
    pub fn merge(&self) -> Self {
        // SAFETY: manifold_alloc_meshgl64 returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl64() };
        // SAFETY: ptr and self.ptr are valid.
        unsafe { manifold_meshgl64_merge(ptr, self.ptr) };
        Self { ptr }
    }

    /// Copy merge-from vertex indices out as a flat u64 array.
    #[must_use]
    pub fn merge_from_vert(&self) -> Vec<u64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_merge_length(self.ptr) };
        let mut buf = vec![0u64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_merge_from_vert(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy merge-to vertex indices out as a flat u64 array.
    #[must_use]
    pub fn merge_to_vert(&self) -> Vec<u64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_merge_length(self.ptr) };
        let mut buf = vec![0u64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_merge_to_vert(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy run indices out as a flat u64 array.
    #[must_use]
    pub fn run_index(&self) -> Vec<u64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_run_index_length(self.ptr) };
        let mut buf = vec![0u64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_run_index(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy run original IDs out as a flat u32 array.
    #[must_use]
    pub fn run_original_id(&self) -> Vec<u32> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_run_original_id_length(self.ptr) };
        let mut buf = vec![0u32; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_run_original_id(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy run transforms out as a flat f64 array (4x3 matrices, 12 doubles each).
    #[must_use]
    pub fn run_transform(&self) -> Vec<f64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_run_transform_length(self.ptr) };
        let mut buf = vec![0.0f64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_run_transform(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy face IDs out as a flat u64 array.
    #[must_use]
    pub fn face_id(&self) -> Vec<u64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_face_id_length(self.ptr) };
        let mut buf = vec![0u64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_face_id(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Copy halfedge tangents out as a flat f64 array (4 doubles per halfedge).
    #[must_use]
    pub fn halfedge_tangent(&self) -> Vec<f64> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_tangent_length(self.ptr) };
        let mut buf = vec![0.0f64; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_halfedge_tangent(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Tolerance used for merging and vertex welding.
    #[must_use]
    pub fn tolerance(&self) -> f64 {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl64_tolerance(self.ptr) }
    }

    /// Number of triangle runs.
    #[must_use]
    pub fn num_run(&self) -> usize {
        // SAFETY: self.ptr is valid (invariant).
        unsafe { manifold_meshgl64_num_run(self.ptr) }
    }

    /// Copy run flags out as a u8 array (one per triangle run).
    #[must_use]
    pub fn run_flags(&self) -> Vec<u8> {
        // SAFETY: self.ptr is valid (invariant).
        let len = unsafe { manifold_meshgl64_run_flags_length(self.ptr) };
        let mut buf = vec![0u8; len];
        // SAFETY: buf has capacity len, self.ptr is valid.
        unsafe { manifold_meshgl64_run_flags(buf.as_mut_ptr(), self.ptr) };
        buf
    }

    /// Update normals based on run transforms and backside flags, then clear
    /// those fields to avoid double-applying on round-trip.
    ///
    /// `normal_idx` specifies the first of three consecutive property channels
    /// forming the (x, y, z) normals. Must be >= 3 and `num_prop` must be at
    /// least `normal_idx + 3`.
    pub fn update_normals(&mut self, normal_idx: i32) {
        // SAFETY: self.ptr is valid (invariant), mutation is exclusive via &mut self.
        unsafe { manifold_meshgl64_update_normals(self.ptr, normal_idx) };
    }

    /// Read a MeshGL64 from a Wavefront OBJ string.
    pub fn from_obj(obj_content: &str) -> Result<Self, crate::types::CsgError> {
        let c_str = std::ffi::CString::new(obj_content).map_err(|_| {
            crate::types::CsgError::InvalidInput("OBJ content contains null byte".into())
        })?;
        // SAFETY: manifold_alloc_meshgl64 returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl64() };
        // SAFETY: ptr valid from alloc, c_str.as_ptr() is a valid null-terminated string.
        unsafe { manifold_meshgl64_read_obj(ptr, c_str.as_ptr()) };
        Ok(Self { ptr })
    }

    /// Export this mesh as a Wavefront OBJ string.
    #[must_use]
    pub fn to_obj(&self) -> String {
        let mut result = String::new();

        unsafe extern "C" fn callback(data: *mut std::ffi::c_char, ctx: *mut std::ffi::c_void) {
            // Catch panics to prevent UB from unwinding through C stack frames.
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                // SAFETY: ctx was created from a &mut String and is valid for the call.
                let result = unsafe { &mut *(ctx as *mut String) };
                // SAFETY: data is a null-terminated C string provided by manifold3d.
                let c_str = unsafe { std::ffi::CStr::from_ptr(data) };
                *result = c_str.to_string_lossy().into_owned();
            }));
        }

        let ctx = &mut result as *mut String as *mut std::ffi::c_void;
        // SAFETY: self.ptr is valid (invariant), callback and ctx are valid for the call.
        unsafe { manifold_meshgl64_write_obj(self.ptr, Some(callback), ctx) };
        result
    }
}

impl Clone for MeshGL64 {
    fn clone(&self) -> Self {
        // SAFETY: manifold_alloc_meshgl64 returns a valid handle.
        let ptr = unsafe { manifold_alloc_meshgl64() };
        // SAFETY: ptr and self.ptr are valid.
        unsafe { manifold_meshgl64_copy(ptr, self.ptr) };
        Self { ptr }
    }
}