Skip to main content

sim_engine/mesh3d/
uv.rs

1//! Validated material UV mapping, without changing normalized source UVs.
2
3use crate::Vec2;
4use std::{error::Error, fmt};
5
6/// Addressing of a complete independently filtered texture, not a packed tile.
7#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum TextureAddressMode3d {
10    /// Extends the outer texel to coordinates beyond the image boundary.
11    #[default]
12    Clamp,
13    /// Repeats the complete image using hardware addressing and continuous LOD derivatives.
14    /// Crop packed atlas cells into independent textures before selecting this mode.
15    Repeat,
16}
17
18/// Affine texture coordinates: `sample_uv = source_uv * scale + offset`.
19///
20/// Source coordinates retain their normalized `0..=1` contract. Zero scale is
21/// allowed and selects a constant coordinate; negative scale reverses an axis.
22/// Coefficients must be zero or normal finite values, with absolute values at
23/// most 65536; both transformed axis endpoints must also lie in that range.
24/// These bounds prevent unsafe shader products/sums but do not promise subtexel
25/// precision for arbitrarily large repeat counts. Reduce offset modulo the
26/// intended repeat period on the host when high phase precision matters.
27///
28/// ```
29/// use sim_engine::{TextureAddressMode3d, TextureUvTransform3d, Vec2};
30///
31/// let mapping = TextureUvTransform3d::new(
32///     Vec2::new(-4.0, 2.0),
33///     Vec2::new(0.25, 0.0),
34/// )?;
35/// assert_eq!(mapping.scale(), Vec2::new(-4.0, 2.0));
36/// let addressing = TextureAddressMode3d::Repeat;
37/// # let _ = addressing;
38/// # Ok::<(), Box<dyn std::error::Error>>(())
39/// ```
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct TextureUvTransform3d {
42    scale: Vec2,
43    offset: Vec2,
44}
45
46impl TextureUvTransform3d {
47    /// Identity mapping of normalized source coordinates.
48    pub const IDENTITY: Self = Self {
49        scale: Vec2::new(1.0, 1.0),
50        offset: Vec2::ZERO,
51    };
52    /// Largest accepted coefficient and transformed endpoint magnitude.
53    pub const MAX_MAGNITUDE: f32 = 65_536.0;
54
55    /// Validates coefficients and all endpoint-derived arithmetic before use.
56    pub fn new(scale: Vec2, offset: Vec2) -> Result<Self, TextureUvTransformError> {
57        for (scale, offset) in [(scale.x(), offset.x()), (scale.y(), offset.y())] {
58            for value in [scale, offset] {
59                if !value.is_finite() {
60                    return Err(TextureUvTransformError::NonFinite);
61                }
62                if value != 0.0 && !value.is_normal() {
63                    return Err(TextureUvTransformError::Subnormal);
64                }
65                if value.abs() > Self::MAX_MAGNITUDE {
66                    return Err(TextureUvTransformError::OutOfRange);
67                }
68            }
69            if (f64::from(scale) + f64::from(offset)).abs() > f64::from(Self::MAX_MAGNITUDE) {
70                return Err(TextureUvTransformError::OutOfRange);
71            }
72        }
73        Ok(Self { scale, offset })
74    }
75    /// Returns the componentwise scale applied before offset.
76    pub const fn scale(self) -> Vec2 {
77        self.scale
78    }
79    /// Returns the post-scale offset in complete-image UV units.
80    pub const fn offset(self) -> Vec2 {
81        self.offset
82    }
83}
84impl Default for TextureUvTransform3d {
85    fn default() -> Self {
86        Self::IDENTITY
87    }
88}
89
90/// Rejected UV mapping, never silently clamped into another coordinate system.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum TextureUvTransformError {
94    /// At least one coefficient was NaN or infinite.
95    NonFinite,
96    /// A nonzero coefficient was subnormal and could flush to zero on a backend.
97    Subnormal,
98    /// A coefficient or transformed endpoint exceeds the bounded UV range.
99    OutOfRange,
100}
101impl fmt::Display for TextureUvTransformError {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        formatter.write_str(match self {
104            Self::NonFinite => "3D UV scale and offset must be finite",
105            Self::Subnormal => "3D UV coefficients must be zero or normal finite values",
106            Self::OutOfRange => "3D UV coefficients and endpoints must remain within +/-65536",
107        })
108    }
109}
110impl Error for TextureUvTransformError {}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    #[test]
116    fn affine_uv_bounds_cover_negative_zero_and_extreme_coefficients() {
117        assert!(TextureUvTransform3d::new(Vec2::new(-8.0, 0.0), Vec2::new(3.0, -2.0)).is_ok());
118        for invalid in [f32::MAX, f32::INFINITY, f32::NAN, f32::from_bits(1)] {
119            assert!(TextureUvTransform3d::new(Vec2::new(invalid, 1.0), Vec2::ZERO).is_err());
120        }
121        assert!(TextureUvTransform3d::new(Vec2::new(65536.0, 1.0), Vec2::new(1.0, 0.0)).is_err());
122        assert!(
123            TextureUvTransform3d::new(Vec2::new(65536.0, 1.0), Vec2::new(-65536.0, 0.0)).is_ok()
124        );
125        assert_eq!(
126            TextureUvTransform3d::default(),
127            TextureUvTransform3d::IDENTITY
128        );
129    }
130}