sim_logic/rendering/three_d/
visual.rs1use 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#[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 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 pub const fn transform(self) -> Transform3d {
46 self.transform
47 }
48
49 pub const fn color(self) -> Color {
51 self.color
52 }
53
54 pub const fn wireframe(self) -> Option<WireframeStyle3d> {
56 self.wireframe
57 }
58
59 pub const fn visible(self) -> bool {
61 self.visible
62 }
63
64 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 pub fn set_color(&mut self, color: Color) -> Result<(), CuboidVisualError> {
78 SurfaceStyle3d::opaque(color)?;
79 self.color = color;
80 Ok(())
81 }
82
83 pub fn set_wireframe(&mut self, wireframe: Option<WireframeStyle3d>) {
87 self.wireframe = wireframe;
88 }
89
90 pub fn set_visible(&mut self, visible: bool) {
92 self.visible = visible;
93 }
94
95 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#[derive(Debug, Clone, Copy, PartialEq)]
145pub enum CuboidVisualError {
146 Geometry(Pseudo3dError),
148 Style(Mesh3dStyleError),
150 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}