Skip to main content

sim_logic/rendering/three_d/
visual.rs

1use std::{error::Error, fmt};
2
3use bevy_ecs::prelude::Component;
4#[cfg(feature = "desktop")]
5use sim_engine::MeshStyle3d;
6use sim_engine::{
7    Color, Mesh3dStyleError, Pseudo3dError, Rotation3d, SurfaceStyle3d, Transform3d, Vec3,
8    WireframeStyle3d,
9};
10
11use super::{CORNERS, TRIANGLES};
12
13/// One opaque, independently transformed solid cuboid in a managed World.
14///
15/// Size is the full extent along local axes, before rotation. There is no
16/// physics, lighting, interpolation, mesh import, or screen-layer sorting.
17/// Hardware depth resolves overlap; stable managed identity orders CPU records.
18/// FrameUpdate may change this presentation component. Hidden cuboids
19/// and disabled entities consume no extracted 3D object or triangle budget.
20#[derive(Debug, Clone, Copy, PartialEq, Component)]
21pub struct CuboidVisual3d {
22    transform: Transform3d,
23    color: Color,
24    wireframe: Option<WireframeStyle3d>,
25    visible: bool,
26}
27
28impl CuboidVisual3d {
29    /// Creates an axis-aligned cuboid with finite, representable solid geometry.
30    ///
31    /// Every size component must be positive; color must be normalized and
32    /// fully opaque. Invalid values allocate no renderer resources.
33    pub fn new(center: Vec3, size: Vec3, color: Color) -> Result<Self, CuboidVisualError> {
34        let visual = Self {
35            transform: Transform3d::new(center, Rotation3d::IDENTITY, size)?,
36            color,
37            wireframe: None,
38            visible: true,
39        };
40        visual.validate()?;
41        Ok(visual)
42    }
43
44    /// Returns the unit cube's world transform.
45    pub const fn transform(self) -> Transform3d {
46        self.transform
47    }
48
49    /// Returns the normalized opaque surface color.
50    pub const fn color(self) -> Color {
51        self.color
52    }
53
54    /// Returns the optional retained outer-edge style.
55    pub const fn wireframe(self) -> Option<WireframeStyle3d> {
56        self.wireframe
57    }
58
59    /// Reports whether this cuboid participates in enabled 3D extraction.
60    pub const fn visible(self) -> bool {
61        self.visible
62    }
63
64    /// Replaces translation, rotation, and positive scale atomically.
65    ///
66    /// Overflow and floating-point collapse of any filled triangle leave the
67    /// previous transform unchanged. Frustum portability is checked by Engine
68    /// at submission, not by this viewport-independent setter.
69    pub fn set_transform(&mut self, transform: Transform3d) -> Result<(), CuboidVisualError> {
70        let proposed = Self { transform, ..*self };
71        proposed.validate()?;
72        *self = proposed;
73        Ok(())
74    }
75
76    /// Replaces the normalized opaque surface color, or changes nothing.
77    pub fn set_color(&mut self, color: Color) -> Result<(), CuboidVisualError> {
78        SurfaceStyle3d::opaque(color)?;
79        self.color = color;
80        Ok(())
81    }
82
83    /// Selects an already validated wireframe style for the twelve outer edges.
84    ///
85    /// Wireframe adds bounded edge draws, not additional surface triangles.
86    pub fn set_wireframe(&mut self, wireframe: Option<WireframeStyle3d>) {
87        self.wireframe = wireframe;
88    }
89
90    /// Changes extraction visibility without changing geometry or style.
91    pub fn set_visible(&mut self, visible: bool) {
92        self.visible = visible;
93    }
94
95    /// Returns all eight world-space corners for bounds and camera-fit checks.
96    pub fn corners(self) -> Result<[Vec3; 8], CuboidVisualError> {
97        let mut corners = [Vec3::ZERO; 8];
98        for (corner, [x, y, z]) in corners.iter_mut().zip(CORNERS) {
99            *corner = self.transform.transform_point(Vec3::new(x, y, z)?)?;
100        }
101        Ok(corners)
102    }
103
104    pub(crate) fn validate(self) -> Result<(), CuboidVisualError> {
105        SurfaceStyle3d::opaque(self.color)?;
106        let corners = self.corners()?;
107        for triangle in TRIANGLES.chunks_exact(3) {
108            let a = coordinates(corners[triangle[0] as usize]);
109            let b = coordinates(corners[triangle[1] as usize]);
110            let c = coordinates(corners[triangle[2] as usize]);
111            let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
112            let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
113            let cross = [
114                u[1] * v[2] - u[2] * v[1],
115                u[2] * v[0] - u[0] * v[2],
116                u[0] * v[1] - u[1] * v[0],
117            ];
118            if cross == [0.0; 3] {
119                return Err(CuboidVisualError::CollapsedGeometry);
120            }
121        }
122        Ok(())
123    }
124
125    #[cfg(feature = "desktop")]
126    pub(crate) fn style(self) -> Result<MeshStyle3d, CuboidVisualError> {
127        let style = MeshStyle3d::surface(SurfaceStyle3d::opaque(self.color)?);
128        Ok(match self.wireframe {
129            Some(wireframe) => style.with_wireframe(wireframe),
130            None => style,
131        })
132    }
133}
134
135fn coordinates(point: Vec3) -> [f64; 3] {
136    [
137        f64::from(point.x()),
138        f64::from(point.y()),
139        f64::from(point.z()),
140    ]
141}
142
143/// A cuboid value could not represent supported solid opaque geometry.
144#[derive(Debug, Clone, Copy, PartialEq)]
145pub enum CuboidVisualError {
146    /// Invalid or overflowing 3D arithmetic.
147    Geometry(Pseudo3dError),
148    /// Surface color was not normalized and opaque.
149    Style(Mesh3dStyleError),
150    /// Transformed floating-point corners collapsed a filled triangle.
151    CollapsedGeometry,
152}
153
154impl From<Pseudo3dError> for CuboidVisualError {
155    fn from(error: Pseudo3dError) -> Self {
156        Self::Geometry(error)
157    }
158}
159
160impl From<Mesh3dStyleError> for CuboidVisualError {
161    fn from(error: Mesh3dStyleError) -> Self {
162        Self::Style(error)
163    }
164}
165
166impl fmt::Display for CuboidVisualError {
167    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
168        match self {
169            Self::Geometry(error) => write!(formatter, "invalid cuboid geometry: {error}"),
170            Self::Style(error) => write!(formatter, "invalid cuboid style: {error}"),
171            Self::CollapsedGeometry => formatter.write_str("cuboid geometry collapses in f32"),
172        }
173    }
174}
175
176impl Error for CuboidVisualError {
177    fn source(&self) -> Option<&(dyn Error + 'static)> {
178        match self {
179            Self::Geometry(error) => Some(error),
180            Self::Style(error) => Some(error),
181            Self::CollapsedGeometry => None,
182        }
183    }
184}