use crate::Vec2;
use std::{error::Error, fmt};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TextureAddressMode3d {
#[default]
Clamp,
Repeat,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextureUvTransform3d {
scale: Vec2,
offset: Vec2,
}
impl TextureUvTransform3d {
pub const IDENTITY: Self = Self {
scale: Vec2::new(1.0, 1.0),
offset: Vec2::ZERO,
};
pub const MAX_MAGNITUDE: f32 = 65_536.0;
pub fn new(scale: Vec2, offset: Vec2) -> Result<Self, TextureUvTransformError> {
for (scale, offset) in [(scale.x(), offset.x()), (scale.y(), offset.y())] {
for value in [scale, offset] {
if !value.is_finite() {
return Err(TextureUvTransformError::NonFinite);
}
if value != 0.0 && !value.is_normal() {
return Err(TextureUvTransformError::Subnormal);
}
if value.abs() > Self::MAX_MAGNITUDE {
return Err(TextureUvTransformError::OutOfRange);
}
}
if (f64::from(scale) + f64::from(offset)).abs() > f64::from(Self::MAX_MAGNITUDE) {
return Err(TextureUvTransformError::OutOfRange);
}
}
Ok(Self { scale, offset })
}
pub const fn scale(self) -> Vec2 {
self.scale
}
pub const fn offset(self) -> Vec2 {
self.offset
}
}
impl Default for TextureUvTransform3d {
fn default() -> Self {
Self::IDENTITY
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TextureUvTransformError {
NonFinite,
Subnormal,
OutOfRange,
}
impl fmt::Display for TextureUvTransformError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::NonFinite => "3D UV scale and offset must be finite",
Self::Subnormal => "3D UV coefficients must be zero or normal finite values",
Self::OutOfRange => "3D UV coefficients and endpoints must remain within +/-65536",
})
}
}
impl Error for TextureUvTransformError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn affine_uv_bounds_cover_negative_zero_and_extreme_coefficients() {
assert!(TextureUvTransform3d::new(Vec2::new(-8.0, 0.0), Vec2::new(3.0, -2.0)).is_ok());
for invalid in [f32::MAX, f32::INFINITY, f32::NAN, f32::from_bits(1)] {
assert!(TextureUvTransform3d::new(Vec2::new(invalid, 1.0), Vec2::ZERO).is_err());
}
assert!(TextureUvTransform3d::new(Vec2::new(65536.0, 1.0), Vec2::new(1.0, 0.0)).is_err());
assert!(
TextureUvTransform3d::new(Vec2::new(65536.0, 1.0), Vec2::new(-65536.0, 0.0)).is_ok()
);
assert_eq!(
TextureUvTransform3d::default(),
TextureUvTransform3d::IDENTITY
);
}
}