sim-engine 0.2.0

A validated high-performance visualization engine for simulations
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
use std::{error::Error, fmt, sync::Arc};

use crate::{Color, LogicalPixels, Vec3};

const MAX_LOGICAL_EDGE_METRIC: f32 = 1_048_576.0;

/// Surface material for one retained 3D instance.
///
/// The representation is private so translucent and hatched section modes can
/// be added without changing `Mesh3dInstance` construction. The first renderer
/// slice supports only opaque color/depth-writing surfaces.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SurfaceStyle3d {
    color: Color,
}

impl SurfaceStyle3d {
    /// Creates an opaque linear-RGBA surface.
    pub fn opaque(color: Color) -> Result<Self, Mesh3dStyleError> {
        if !color.is_normalized() || color.alpha() != 1.0 {
            return Err(Mesh3dStyleError::InvalidSurfaceColor);
        }
        Ok(Self { color })
    }

    /// Returns the opaque linear-RGBA color used by the current surface pass.
    pub const fn color(self) -> Color {
        self.color
    }
}

/// Extensible visual material bundle for a retained 3D object.
///
/// Surface and wireframe presentation are independent. Edge-only construction
/// geometry uses `surface = None`; future section materials can extend
/// [`SurfaceStyle3d`] without changing scene insertion or object addressing.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeshStyle3d {
    surface: Option<SurfaceStyle3d>,
    wireframe: Option<WireframeStyle3d>,
}

impl MeshStyle3d {
    /// Creates an object with an opaque surface and no display edges.
    pub const fn surface(surface: SurfaceStyle3d) -> Self {
        Self {
            surface: Some(surface),
            wireframe: None,
        }
    }

    /// Creates display edges without a surface/depth-writing face pass.
    pub const fn wireframe(wireframe: WireframeStyle3d) -> Self {
        Self {
            surface: None,
            wireframe: Some(wireframe),
        }
    }

    /// Adds or replaces display-edge presentation.
    pub const fn with_wireframe(mut self, wireframe: WireframeStyle3d) -> Self {
        self.wireframe = Some(wireframe);
        self
    }

    /// Returns the optional surface material.
    pub const fn surface_style(self) -> Option<SurfaceStyle3d> {
        self.surface
    }

    /// Returns the optional edge presentation.
    pub const fn wireframe_style(self) -> Option<WireframeStyle3d> {
        self.wireframe
    }
}

/// Logical-screen presentation for explicit mathematical mesh edges.
///
/// Visible fragments are solid. Fragments occluded beyond the depth buffer's
/// conservative coplanar tolerance may be drawn with a logical-pixel dash/gap
/// pattern. Classification uses one implementation depth unit away from the
/// camera for hidden fragments and one unit toward it for visible fragments,
/// with visible fragments rendered last. Therefore coplanar and
/// sub-depth-resolution separations intentionally resolve as visible; this is
/// raster visibility, not exact analytic solid geometry.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WireframeStyle3d {
    visible_color: Color,
    visible_width: LogicalPixels,
    hidden: Option<HiddenEdgeStyle3d>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct HiddenEdgeStyle3d {
    color: Color,
    width: LogicalPixels,
    dash_length: LogicalPixels,
    gap_length: LogicalPixels,
}

impl WireframeStyle3d {
    /// Largest accepted width, dash, or gap in logical pixels.
    ///
    /// The bound keeps every style-derived shader operation inside the
    /// cross-backend arithmetic envelope.
    pub const MAX_LOGICAL_PIXELS: f32 = MAX_LOGICAL_EDGE_METRIC;

    /// Creates solid visible edges with hidden fragments disabled.
    pub fn visible(color: Color, width: LogicalPixels) -> Result<Self, Mesh3dStyleError> {
        validate_edge_color_width(color, width)?;
        Ok(Self {
            visible_color: color,
            visible_width: width,
            hidden: None,
        })
    }

    /// Enables dashed depth-occluded fragments in logical screen pixels.
    ///
    /// Occlusion must exceed the conservative two-unit coplanar tolerance
    /// documented on [`WireframeStyle3d`] before a fragment resolves hidden.
    pub fn with_hidden(
        mut self,
        color: Color,
        width: LogicalPixels,
        dash_length: LogicalPixels,
        gap_length: LogicalPixels,
    ) -> Result<Self, Mesh3dStyleError> {
        validate_edge_color_width(color, width)?;
        if !is_stable_edge_metric(dash_length.get())
            || !is_stable_edge_metric(gap_length.get())
            || !(dash_length.get() + gap_length.get()).is_finite()
        {
            return Err(Mesh3dStyleError::InvalidDashPattern);
        }
        self.hidden = Some(HiddenEdgeStyle3d {
            color,
            width,
            dash_length,
            gap_length,
        });
        Ok(self)
    }

    /// Returns the solid visible-edge color in linear RGBA.
    pub const fn visible_color(self) -> Color {
        self.visible_color
    }

    /// Returns visible-edge width in logical screen pixels.
    pub const fn visible_width(self) -> LogicalPixels {
        self.visible_width
    }

    /// Returns whether depth-occluded edge fragments should be drawn.
    pub const fn hidden_enabled(self) -> bool {
        self.hidden.is_some()
    }

    /// Returns hidden-edge color when enabled.
    pub const fn hidden_color(self) -> Option<Color> {
        match self.hidden {
            Some(hidden) => Some(hidden.color),
            None => None,
        }
    }

    /// Returns hidden-edge width in logical screen pixels when enabled.
    pub const fn hidden_width(self) -> Option<LogicalPixels> {
        match self.hidden {
            Some(hidden) => Some(hidden.width),
            None => None,
        }
    }

    /// Returns hidden dash and gap lengths in logical screen pixels.
    pub const fn hidden_pattern(self) -> Option<(LogicalPixels, LogicalPixels)> {
        match self.hidden {
            Some(hidden) => Some((hidden.dash_length, hidden.gap_length)),
            None => None,
        }
    }
}

/// Rejection reason for logical-screen 3D edge presentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mesh3dStyleError {
    /// Surface color must be normalized and opaque in the initial material mode.
    InvalidSurfaceColor,
    /// Edge color must be normalized and opaque, and width must be a normal
    /// positive value no greater than [`WireframeStyle3d::MAX_LOGICAL_PIXELS`].
    InvalidColorOrWidth,
    /// Hidden dash and gap must be normal positive values, each no greater than
    /// [`WireframeStyle3d::MAX_LOGICAL_PIXELS`], with a finite sum.
    InvalidDashPattern,
}

impl fmt::Display for Mesh3dStyleError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidSurfaceColor => write!(formatter, "3D surface color must be opaque"),
            Self::InvalidColorOrWidth => {
                write!(
                    formatter,
                    "3D edge color must be opaque and width must be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels"
                )
            }
            Self::InvalidDashPattern => {
                write!(
                    formatter,
                    "3D hidden-edge dash and gap must each be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels with a finite sum"
                )
            }
        }
    }
}

impl Error for Mesh3dStyleError {}

fn validate_edge_color_width(color: Color, width: LogicalPixels) -> Result<(), Mesh3dStyleError> {
    if color.is_normalized() && color.alpha() == 1.0 && is_stable_edge_metric(width.get()) {
        Ok(())
    } else {
        Err(Mesh3dStyleError::InvalidColorOrWidth)
    }
}

fn is_stable_edge_metric(value: f32) -> bool {
    value.is_normal() && value <= MAX_LOGICAL_EDGE_METRIC
}

/// One explicit display edge in a retained 3D mesh.
///
/// Endpoints index the mesh vertex array. A mesh validates the indices and
/// rejects repeated or zero-length edges when it is constructed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct MeshEdge3d {
    start: u32,
    end: u32,
}

impl MeshEdge3d {
    /// Describes an edge between two distinct vertex indices.
    pub fn new(start: u32, end: u32) -> Result<Self, Mesh3dError> {
        if start == end {
            return Err(Mesh3dError::DegenerateDisplayEdge { start, end });
        }
        Ok(Self { start, end })
    }

    /// Returns the first mesh vertex index.
    pub const fn start(self) -> u32 {
        self.start
    }

    /// Returns the second mesh vertex index.
    pub const fn end(self) -> u32 {
        self.end
    }

    fn canonical(self) -> (u32, u32) {
        if self.start < self.end {
            (self.start, self.end)
        } else {
            (self.end, self.start)
        }
    }
}

#[derive(Debug, PartialEq)]
struct Mesh3dStorage {
    vertices: Vec<Vec3>,
    triangle_indices: Vec<u32>,
    display_edges: Vec<MeshEdge3d>,
}

/// Immutable validated topology for retained stereometry rendering.
///
/// Vertices use caller-defined model-space world units. Triangle indices are a
/// flat triangle list. Winding is preserved but deliberately not interpreted:
/// the current surface pass disables face culling, and a global
/// "counter-clockwise" rule is meaningless without a declared outward side.
/// Optional display edges identify the mathematical edges that a later
/// visible/hidden-line pass should draw; they are not inferred from triangle
/// adjacency because triangulation diagonals are not necessarily meaningful
/// construction edges. A mesh may contain surfaces, display edges, or both.
#[derive(Debug, Clone, PartialEq)]
pub struct Mesh3d {
    storage: Arc<Mesh3dStorage>,
    bounds_min: Vec3,
    bounds_max: Vec3,
}

impl Mesh3d {
    /// Builds a surface mesh without explicit display edges.
    pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
        Self::with_display_edges(vertices, triangle_indices, Vec::new())
    }

    /// Builds a mesh with explicit mathematical display edges.
    ///
    /// Construction rejects an empty vertex set, geometry with neither
    /// triangles nor display edges, incomplete triangle lists, out-of-range
    /// indices, repeated/collinear triangle vertices, duplicate display edges,
    /// display edges with coincident endpoints, and display edges outside the
    /// vertex array.
    pub fn with_display_edges(
        vertices: Vec<Vec3>,
        triangle_indices: Vec<u32>,
        display_edges: Vec<MeshEdge3d>,
    ) -> Result<Self, Mesh3dError> {
        if vertices.is_empty() {
            return Err(Mesh3dError::EmptyVertices);
        }
        if triangle_indices.is_empty() && display_edges.is_empty() {
            return Err(Mesh3dError::EmptyGeometry);
        }
        if !triangle_indices.len().is_multiple_of(3) {
            return Err(Mesh3dError::InvalidTriangleIndexCount {
                index_count: triangle_indices.len(),
            });
        }

        for (triangle, indices) in triangle_indices.chunks_exact(3).enumerate() {
            let [first, second, third] = [indices[0], indices[1], indices[2]];
            validate_index(first, vertices.len())?;
            validate_index(second, vertices.len())?;
            validate_index(third, vertices.len())?;
            if first == second
                || second == third
                || first == third
                || triangle_is_degenerate(
                    vertices[first as usize],
                    vertices[second as usize],
                    vertices[third as usize],
                )
            {
                return Err(Mesh3dError::DegenerateTriangle { triangle });
            }
        }

        for edge in &display_edges {
            validate_index(edge.start, vertices.len())?;
            validate_index(edge.end, vertices.len())?;
            if vertices[edge.start as usize] == vertices[edge.end as usize] {
                return Err(Mesh3dError::DegenerateDisplayEdge {
                    start: edge.start,
                    end: edge.end,
                });
            }
        }

        let canonical_bytes = display_edges
            .len()
            .checked_mul(std::mem::size_of::<((u32, u32), usize)>())
            .ok_or(Mesh3dError::AllocationFailed {
                requested_bytes: usize::MAX,
            })?;
        let mut canonical_edges = Vec::new();
        canonical_edges
            .try_reserve_exact(display_edges.len())
            .map_err(|_| Mesh3dError::AllocationFailed {
                requested_bytes: canonical_bytes,
            })?;
        for (index, edge) in display_edges.iter().enumerate() {
            canonical_edges.push((edge.canonical(), index));
        }
        canonical_edges.sort_unstable_by_key(|entry| entry.0);
        if let Some(pair) = canonical_edges
            .windows(2)
            .find(|pair| pair[0].0 == pair[1].0)
        {
            let duplicate = display_edges[pair[0].1.max(pair[1].1)];
            return Err(Mesh3dError::DuplicateDisplayEdge {
                start: duplicate.start,
                end: duplicate.end,
            });
        }

        let (bounds_min, bounds_max) = mesh_bounds(&vertices);
        Ok(Self {
            // One fixed-size Arc control block makes Mesh3d cloning O(1)
            // without copying any caller-scale topology buffers.
            storage: Arc::new(Mesh3dStorage {
                vertices,
                triangle_indices,
                display_edges,
            }),
            bounds_min,
            bounds_max,
        })
    }

    /// Returns immutable model-space vertices.
    pub fn vertices(&self) -> &[Vec3] {
        &self.storage.vertices
    }

    /// Returns the flat host-wound triangle index list.
    pub fn triangle_indices(&self) -> &[u32] {
        &self.storage.triangle_indices
    }

    /// Returns explicit mathematical edges, excluding triangulation diagonals.
    pub fn display_edges(&self) -> &[MeshEdge3d] {
        &self.storage.display_edges
    }

    /// Returns the number of retained triangles.
    pub fn triangle_count(&self) -> usize {
        self.storage.triangle_indices.len() / 3
    }

    /// Returns the inclusive model-space lower bound.
    pub const fn bounds_min(&self) -> Vec3 {
        self.bounds_min
    }

    /// Returns the inclusive model-space upper bound.
    pub const fn bounds_max(&self) -> Vec3 {
        self.bounds_max
    }

    /// Returns retained CPU bytes used by vertices, indices, and display edges.
    pub fn recovery_memory_bytes(&self) -> usize {
        self.storage
            .vertices
            .capacity()
            .saturating_mul(std::mem::size_of::<Vec3>())
            .saturating_add(
                self.storage
                    .triangle_indices
                    .capacity()
                    .saturating_mul(std::mem::size_of::<u32>()),
            )
            .saturating_add(
                self.storage
                    .display_edges
                    .capacity()
                    .saturating_mul(std::mem::size_of::<MeshEdge3d>()),
            )
    }
}

/// Rejection reason for retained 3D topology.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mesh3dError {
    /// A retained mesh requires at least one model-space vertex.
    EmptyVertices,
    /// A retained mesh requires at least one triangle or display edge.
    EmptyGeometry,
    /// The triangle index list was not divisible by three.
    InvalidTriangleIndexCount {
        /// Rejected number of indices.
        index_count: usize,
    },
    /// A triangle or display edge referenced a missing vertex.
    IndexOutOfBounds {
        /// Rejected vertex index.
        index: u32,
        /// Number of vertices available in the mesh.
        vertex_count: usize,
    },
    /// A triangle repeated a vertex or had zero model-space area.
    DegenerateTriangle {
        /// Zero-based triangle number in the index list.
        triangle: usize,
    },
    /// A display edge used one index twice or referenced coincident vertices.
    DegenerateDisplayEdge {
        /// First endpoint in the rejected declaration.
        start: u32,
        /// Second endpoint in the rejected declaration.
        end: u32,
    },
    /// The same undirected display edge appeared more than once.
    DuplicateDisplayEdge {
        /// First endpoint in the rejected declaration.
        start: u32,
        /// Second endpoint in the rejected declaration.
        end: u32,
    },
    /// Temporary validation storage could not be reserved.
    AllocationFailed {
        /// Bytes requested for duplicate-edge validation.
        requested_bytes: usize,
    },
}

impl fmt::Display for Mesh3dError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyVertices => write!(formatter, "3D mesh requires at least one vertex"),
            Self::EmptyGeometry => {
                write!(formatter, "3D mesh requires triangles or display edges")
            }
            Self::InvalidTriangleIndexCount { index_count } => write!(
                formatter,
                "3D mesh triangle index count, when present, must be divisible by three, got {index_count}"
            ),
            Self::IndexOutOfBounds {
                index,
                vertex_count,
            } => write!(
                formatter,
                "3D mesh index {index} is outside {vertex_count} vertices"
            ),
            Self::DegenerateTriangle { triangle } => {
                write!(formatter, "3D mesh triangle {triangle} has zero area")
            }
            Self::DegenerateDisplayEdge { start, end } => {
                write!(formatter, "3D display edge {start}-{end} has zero length")
            }
            Self::DuplicateDisplayEdge { start, end } => {
                write!(formatter, "3D display edge {start}-{end} is duplicated")
            }
            Self::AllocationFailed { requested_bytes } => write!(
                formatter,
                "could not reserve {requested_bytes} bytes for 3D mesh validation"
            ),
        }
    }
}

impl Error for Mesh3dError {}

fn validate_index(index: u32, vertex_count: usize) -> Result<(), Mesh3dError> {
    ((index as u64) < vertex_count as u64)
        .then_some(())
        .ok_or(Mesh3dError::IndexOutOfBounds {
            index,
            vertex_count,
        })
}

fn triangle_is_degenerate(first: Vec3, second: Vec3, third: Vec3) -> bool {
    let ab = (
        second.x() as f64 - first.x() as f64,
        second.y() as f64 - first.y() as f64,
        second.z() as f64 - first.z() as f64,
    );
    let ac = (
        third.x() as f64 - first.x() as f64,
        third.y() as f64 - first.y() as f64,
        third.z() as f64 - first.z() as f64,
    );
    let cross = (
        ab.1 * ac.2 - ab.2 * ac.1,
        ab.2 * ac.0 - ab.0 * ac.2,
        ab.0 * ac.1 - ab.1 * ac.0,
    );
    cross.0 == 0.0 && cross.1 == 0.0 && cross.2 == 0.0
}

fn mesh_bounds(vertices: &[Vec3]) -> (Vec3, Vec3) {
    let first = vertices[0];
    let mut minimum = [first.x(), first.y(), first.z()];
    let mut maximum = minimum;
    for vertex in &vertices[1..] {
        let components = [vertex.x(), vertex.y(), vertex.z()];
        for axis in 0..3 {
            minimum[axis] = minimum[axis].min(components[axis]);
            maximum[axis] = maximum[axis].max(components[axis]);
        }
    }
    (
        Vec3::new_unchecked(minimum[0], minimum[1], minimum[2]),
        Vec3::new_unchecked(maximum[0], maximum[1], maximum[2]),
    )
}

#[cfg(test)]
mod tests {
    use super::{
        Mesh3d, Mesh3dError, Mesh3dStyleError, MeshEdge3d, MeshStyle3d, SurfaceStyle3d,
        WireframeStyle3d,
    };
    use crate::{Color, LogicalPixels, UnitError, Vec3};

    fn vector(x: f32, y: f32, z: f32) -> Vec3 {
        Vec3::new(x, y, z).unwrap()
    }

    fn logical(value: f32) -> LogicalPixels {
        LogicalPixels::new(value).unwrap()
    }

    #[test]
    fn mesh_validates_topology_and_preserves_explicit_edges() {
        let mesh = Mesh3d::with_display_edges(
            vec![
                vector(-1.0, -1.0, 0.0),
                vector(1.0, -1.0, 0.0),
                vector(0.0, 1.0, 0.0),
            ],
            vec![0, 1, 2],
            vec![
                MeshEdge3d::new(0, 1).unwrap(),
                MeshEdge3d::new(1, 2).unwrap(),
            ],
        )
        .unwrap();
        assert_eq!(mesh.triangle_count(), 1);
        assert_eq!(mesh.display_edges().len(), 2);
        assert_eq!(mesh.bounds_min(), vector(-1.0, -1.0, 0.0));
        assert_eq!(mesh.bounds_max(), vector(1.0, 1.0, 0.0));
    }

    #[test]
    fn mesh_rejects_invalid_and_degenerate_topology() {
        assert_eq!(
            Mesh3d::new(Vec::new(), vec![0, 1, 2]),
            Err(Mesh3dError::EmptyVertices)
        );
        let vertices = vec![
            vector(0.0, 0.0, 0.0),
            vector(1.0, 0.0, 0.0),
            vector(2.0, 0.0, 0.0),
        ];
        assert_eq!(
            Mesh3d::new(vertices.clone(), vec![0, 1]),
            Err(Mesh3dError::InvalidTriangleIndexCount { index_count: 2 })
        );
        assert_eq!(
            Mesh3d::new(vertices.clone(), vec![0, 1, 3]),
            Err(Mesh3dError::IndexOutOfBounds {
                index: 3,
                vertex_count: 3,
            })
        );
        assert_eq!(
            Mesh3d::new(vertices, vec![0, 1, 2]),
            Err(Mesh3dError::DegenerateTriangle { triangle: 0 })
        );
    }

    #[test]
    fn mesh_rejects_duplicate_undirected_display_edges() {
        let vertices = vec![
            vector(0.0, 0.0, 0.0),
            vector(1.0, 0.0, 0.0),
            vector(0.0, 1.0, 0.0),
        ];
        assert_eq!(
            Mesh3d::with_display_edges(
                vertices,
                vec![0, 1, 2],
                vec![
                    MeshEdge3d::new(0, 1).unwrap(),
                    MeshEdge3d::new(1, 0).unwrap(),
                ],
            ),
            Err(Mesh3dError::DuplicateDisplayEdge { start: 1, end: 0 })
        );
        assert_eq!(
            MeshEdge3d::new(2, 2),
            Err(Mesh3dError::DegenerateDisplayEdge { start: 2, end: 2 })
        );
    }

    #[test]
    fn mesh_rejects_geometrically_zero_length_display_edges() {
        assert_eq!(
            Mesh3d::with_display_edges(
                vec![vector(1.0, 2.0, 3.0), vector(1.0, 2.0, 3.0)],
                Vec::new(),
                vec![MeshEdge3d::new(0, 1).unwrap()],
            ),
            Err(Mesh3dError::DegenerateDisplayEdge { start: 0, end: 1 })
        );
    }

    #[test]
    fn mesh_accepts_edge_only_construction_geometry() {
        let mesh = Mesh3d::with_display_edges(
            vec![vector(0.0, 0.0, 0.0), vector(1.0, 0.0, 0.0)],
            Vec::new(),
            vec![MeshEdge3d::new(0, 1).unwrap()],
        )
        .unwrap();
        assert_eq!(mesh.triangle_count(), 0);
        assert_eq!(mesh.display_edges().len(), 1);
        assert_eq!(
            Mesh3d::new(vec![vector(0.0, 0.0, 0.0)], Vec::new()),
            Err(Mesh3dError::EmptyGeometry)
        );
    }

    #[test]
    fn wireframe_style_validates_logical_pixel_contract() {
        let style = WireframeStyle3d::visible(Color::WHITE, logical(2.0))
            .unwrap()
            .with_hidden(
                Color::rgba(0.5, 0.5, 0.5, 1.0),
                logical(1.5),
                logical(6.0),
                logical(4.0),
            )
            .unwrap();
        assert_eq!(style.visible_width(), logical(2.0));
        assert_eq!(style.hidden_pattern(), Some((logical(6.0), logical(4.0))));
        assert_eq!(
            LogicalPixels::new(0.0),
            Err(UnitError::InvalidLogicalPixels { value: 0.0 })
        );
        assert_eq!(
            WireframeStyle3d::visible(Color::WHITE, logical(f32::MAX)),
            Err(Mesh3dStyleError::InvalidColorOrWidth)
        );
        assert_eq!(
            WireframeStyle3d::visible(Color::WHITE, logical(f32::MIN_POSITIVE / 2.0)),
            Err(Mesh3dStyleError::InvalidColorOrWidth)
        );
        assert_eq!(
            WireframeStyle3d::visible(Color::rgb(-0.01, 0.0, 0.0), logical(1.0)),
            Err(Mesh3dStyleError::InvalidColorOrWidth)
        );
        assert_eq!(
            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
                .unwrap()
                .with_hidden(Color::WHITE, logical(1.0), logical(f32::MAX), logical(2.0),),
            Err(Mesh3dStyleError::InvalidDashPattern)
        );
        assert_eq!(
            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
                .unwrap()
                .with_hidden(
                    Color::WHITE,
                    logical(1.0),
                    logical(f32::MIN_POSITIVE / 2.0),
                    logical(2.0),
                ),
            Err(Mesh3dStyleError::InvalidDashPattern)
        );
        assert_eq!(
            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
                .unwrap()
                .with_hidden(
                    Color::WHITE,
                    logical(1.0),
                    logical(f32::MAX),
                    logical(f32::MAX),
                ),
            Err(Mesh3dStyleError::InvalidDashPattern)
        );
    }

    #[test]
    fn mesh_style_keeps_surface_and_wireframe_extensible() {
        let surface = SurfaceStyle3d::opaque(Color::rgb(0.2, 0.3, 0.4)).unwrap();
        let wireframe = WireframeStyle3d::visible(Color::WHITE, logical(2.0)).unwrap();
        let style = MeshStyle3d::surface(surface).with_wireframe(wireframe);
        assert_eq!(style.surface_style(), Some(surface));
        assert_eq!(style.wireframe_style(), Some(wireframe));
        assert_eq!(
            SurfaceStyle3d::opaque(Color::rgba(1.0, 1.0, 1.0, 0.5)),
            Err(Mesh3dStyleError::InvalidSurfaceColor)
        );
        assert_eq!(
            SurfaceStyle3d::opaque(Color::rgb(1.01, 0.0, 0.0)),
            Err(Mesh3dStyleError::InvalidSurfaceColor)
        );
        assert_eq!(MeshStyle3d::wireframe(wireframe).surface_style(), None);
    }
}