use std::{error::Error, fmt, sync::Arc};
use crate::{Color, LogicalPixels, Vec3};
const MAX_LOGICAL_EDGE_METRIC: f32 = 1_048_576.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SurfaceStyle3d {
color: Color,
}
impl SurfaceStyle3d {
pub fn opaque(color: Color) -> Result<Self, Mesh3dStyleError> {
if !color.is_normalized() || color.alpha() != 1.0 {
return Err(Mesh3dStyleError::InvalidSurfaceColor);
}
Ok(Self { color })
}
pub const fn color(self) -> Color {
self.color
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeshStyle3d {
surface: Option<SurfaceStyle3d>,
wireframe: Option<WireframeStyle3d>,
}
impl MeshStyle3d {
pub const fn surface(surface: SurfaceStyle3d) -> Self {
Self {
surface: Some(surface),
wireframe: None,
}
}
pub const fn wireframe(wireframe: WireframeStyle3d) -> Self {
Self {
surface: None,
wireframe: Some(wireframe),
}
}
pub const fn with_wireframe(mut self, wireframe: WireframeStyle3d) -> Self {
self.wireframe = Some(wireframe);
self
}
pub const fn surface_style(self) -> Option<SurfaceStyle3d> {
self.surface
}
pub const fn wireframe_style(self) -> Option<WireframeStyle3d> {
self.wireframe
}
}
#[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 {
pub const MAX_LOGICAL_PIXELS: f32 = MAX_LOGICAL_EDGE_METRIC;
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,
})
}
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)
}
pub const fn visible_color(self) -> Color {
self.visible_color
}
pub const fn visible_width(self) -> LogicalPixels {
self.visible_width
}
pub const fn hidden_enabled(self) -> bool {
self.hidden.is_some()
}
pub const fn hidden_color(self) -> Option<Color> {
match self.hidden {
Some(hidden) => Some(hidden.color),
None => None,
}
}
pub const fn hidden_width(self) -> Option<LogicalPixels> {
match self.hidden {
Some(hidden) => Some(hidden.width),
None => None,
}
}
pub const fn hidden_pattern(self) -> Option<(LogicalPixels, LogicalPixels)> {
match self.hidden {
Some(hidden) => Some((hidden.dash_length, hidden.gap_length)),
None => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mesh3dStyleError {
InvalidSurfaceColor,
InvalidColorOrWidth,
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
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct MeshEdge3d {
start: u32,
end: u32,
}
impl MeshEdge3d {
pub fn new(start: u32, end: u32) -> Result<Self, Mesh3dError> {
if start == end {
return Err(Mesh3dError::DegenerateDisplayEdge { start, end });
}
Ok(Self { start, end })
}
pub const fn start(self) -> u32 {
self.start
}
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>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Mesh3d {
storage: Arc<Mesh3dStorage>,
bounds_min: Vec3,
bounds_max: Vec3,
}
impl Mesh3d {
pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
Self::with_display_edges(vertices, triangle_indices, Vec::new())
}
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 {
storage: Arc::new(Mesh3dStorage {
vertices,
triangle_indices,
display_edges,
}),
bounds_min,
bounds_max,
})
}
pub fn vertices(&self) -> &[Vec3] {
&self.storage.vertices
}
pub fn triangle_indices(&self) -> &[u32] {
&self.storage.triangle_indices
}
pub fn display_edges(&self) -> &[MeshEdge3d] {
&self.storage.display_edges
}
pub fn triangle_count(&self) -> usize {
self.storage.triangle_indices.len() / 3
}
pub const fn bounds_min(&self) -> Vec3 {
self.bounds_min
}
pub const fn bounds_max(&self) -> Vec3 {
self.bounds_max
}
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>()),
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mesh3dError {
EmptyVertices,
EmptyGeometry,
InvalidTriangleIndexCount {
index_count: usize,
},
IndexOutOfBounds {
index: u32,
vertex_count: usize,
},
DegenerateTriangle {
triangle: usize,
},
DegenerateDisplayEdge {
start: u32,
end: u32,
},
DuplicateDisplayEdge {
start: u32,
end: u32,
},
AllocationFailed {
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);
}
}