ferravex_math/affine.rs
1//! Checked, reusable affine point, vector and normal transformation.
2//!
3//! [`PreparedAffine3D`] accepts an existing [`Mat4`]; it does not author another
4//! TRS/scene hierarchy. Preparation checks finite coefficients, the exact affine
5//! row `(0, 0, 0, 1)` and a representable inverse of the linear part. Translation
6//! is excluded from inversion, so an unrepresentable inverse translation does
7//! not prevent forward transformation. No projective division is performed.
8//!
9//! Normals use the inverse transpose, including for nonuniform scale and shear.
10//! Reflections are accepted. Normals retain their covector orientation: there
11//! is **no** extra determinant-sign flip. For a mirrored model, a transformed
12//! triangle's edge cross product points opposite its transformed authored
13//! normal. Use [`PreparedAffine3D::is_reflected`] to choose a winding/culling
14//! policy, or explicitly negate the returned normal when matching that cross
15//! product is intended. The cached normal matrix follows the same policy.
16//!
17//! Scalar operations reject nonfinite inputs. Points/vectors use f64 dot
18//! products and reject outputs that round to nonfinite f32. Normals rescale
19//! wide dot products before using [`Vec3::try_normalize`], allowing a unit
20//! result even when an unnormalized component would overflow/underflow f32.
21//! A zero input or a transformed normal that collapses to zero is an error.
22//! Ordinary f32 rounding and the conditioning limits of
23//! [`Mat4::checked_inverse`] remain; success is not an accuracy certificate.
24//!
25//! Slice operations require enough caller storage, process the entire input
26//! (never truncate), and leave **all** output elements unchanged on any error.
27//! On success only the input-length prefix is written. They use two passes,
28//! O(n) work, O(1) stack storage and no heap allocations. Callers impose their
29//! own input/work bound. Separate calls are separate transactions.
30//!
31//! # Runnable mesh preparation recipe
32//!
33//! Prepare once when an authored model changes, then reuse for mesh positions,
34//! directions and lighting normals. This recipe uses a mirrored, sheared model
35//! and caller-owned output arrays; it does not replace a renderer.
36//!
37//! ```rust
38//! use ferravex_math::{Mat4, Vec3, Vec4, vec3, vec4};
39//! use ferravex_math::affine::PreparedAffine3D;
40//!
41//! fn main() -> Result<(), Box<dyn std::error::Error>> {
42//! let model = Mat4::from_cols(
43//! vec4(-2.0, 0.0, 0.0, 0.0),
44//! vec4(1.0, 3.0, 0.0, 0.0),
45//! vec4(0.0, 0.0, 0.5, 0.0),
46//! vec3(10.0, 2.0, -1.0).extend(1.0),
47//! );
48//! let mut prepared = PreparedAffine3D::try_new(model)?;
49//! assert_eq!(prepared.model(), model);
50//! assert!(prepared.is_reflected()); // renderer chooses winding explicitly
51//! let local_positions = [Vec3::ZERO, Vec3::X, Vec3::Y];
52//! let mut world_positions = [Vec3::ZERO; 3];
53//! let mut world_normals = [Vec3::ZERO; 3];
54//! prepared.transform_points_into(&local_positions, &mut world_positions)?;
55//! prepared.transform_normals_into(&[Vec3::Z; 3], &mut world_normals)?;
56//! let edge = prepared.transform_vector(Vec3::X)?;
57//! assert!(edge.dot(world_normals[0]).abs() < 1.0e-6);
58//! let winding_normal = (world_positions[1] - world_positions[0])
59//! .cross(world_positions[2] - world_positions[0]).normalize();
60//! assert!(winding_normal.dot(world_normals[0]) < -0.999);
61//! assert_eq!(prepared.normal_matrix().transform_vector3(Vec3::Z), Vec3::Z * 2.0);
62//! assert_eq!(prepared.transform_point(Vec3::ZERO)?, model.w_axis.truncate());
63//! let mut directions = [Vec3::ZERO];
64//! prepared.transform_vectors_into(&[Vec3::X], &mut directions)?;
65//! assert_eq!(directions[0], edge);
66//! let retained = prepared;
67//! assert!(prepared.try_update(Mat4::from_scale(Vec3::ZERO)).is_err());
68//! assert_eq!(prepared, retained); // failed edits retain the last good cache
69//! prepared.try_update(Mat4::IDENTITY)?;
70//! assert!(!prepared.is_reflected());
71//! assert_eq!(prepared.normal_matrix(), Mat4::IDENTITY);
72//! assert_eq!(prepared.transform_normal(Vec3::Z)?, Vec3::Z);
73//! assert_eq!(prepared.model().w_axis, Vec4::W);
74//! Ok(())
75//! }
76//! ```
77
78use crate::{Mat4, MatrixError, Vec3, Vec4};
79
80/// Failure from preparation or one scalar affine operation.
81/// No identity, zero normal or other fallback is substituted.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83#[non_exhaustive]
84pub enum AffineError {
85 /// A model coefficient, point, vector or normal is NaN/infinite.
86 NonFiniteInput { input: &'static str },
87 /// The bottom row must equal `(0, 0, 0, 1)` exactly; signed zero is accepted.
88 NonAffine,
89 /// Checked inversion of the translation-free linear matrix failed.
90 Matrix(MatrixError),
91 /// A point/vector output cannot round to finite f32.
92 ResultOutOfRange,
93 /// An input normal is zero, or its cached inverse-transpose image is zero.
94 DegenerateNormal,
95}
96
97impl std::fmt::Display for AffineError {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 match self {
100 Self::NonFiniteInput { input } => write!(f, "affine {input} must be finite"),
101 Self::NonAffine => f.write_str("model bottom row must equal (0, 0, 0, 1)"),
102 Self::Matrix(error) => write!(f, "affine linear inverse: {error}"),
103 Self::ResultOutOfRange => f.write_str("affine output exceeds finite f32 range"),
104 Self::DegenerateNormal => {
105 f.write_str("normal must have a nonzero transformed direction")
106 }
107 }
108 }
109}
110
111impl std::error::Error for AffineError {
112 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
113 match self {
114 Self::Matrix(error) => Some(error),
115 _ => None,
116 }
117 }
118}
119
120impl From<MatrixError> for AffineError {
121 fn from(value: MatrixError) -> Self {
122 Self::Matrix(value)
123 }
124}
125
126/// An atomic slice operation failed before writing any output.
127/// Capacity is checked first; otherwise the first failing input index wins.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129#[non_exhaustive]
130pub enum AffineSliceError {
131 /// Output must hold the entire input, not a truncated prefix.
132 InsufficientCapacity { required: usize, available: usize },
133 /// A zero-based element failed scalar validation.
134 Element { index: usize, source: AffineError },
135}
136
137impl std::fmt::Display for AffineSliceError {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 match self {
140 Self::InsufficientCapacity {
141 required,
142 available,
143 } => {
144 write!(f, "affine output needs {required} slots, has {available}")
145 }
146 Self::Element { index, source } => write!(f, "affine input[{index}]: {source}"),
147 }
148 }
149}
150
151impl std::error::Error for AffineSliceError {
152 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
153 match self {
154 Self::Element { source, .. } => Some(source),
155 _ => None,
156 }
157 }
158}
159
160/// Validated immutable cache of an affine model, linear inverse transpose and
161/// orientation. All accessors return copies, preserving cache invariants.
162///
163/// Use the [module recipe](self) for scalar, bounded batch and update examples.
164#[derive(Clone, Copy, Debug, PartialEq)]
165pub struct PreparedAffine3D {
166 model: Mat4,
167 normal_matrix: Mat4,
168 reflected: bool,
169}
170
171impl PreparedAffine3D {
172 /// Checks finiteness, exact affine row, then the linear checked inverse.
173 /// Singular models and inverses outside f32 range are rejected. There is no
174 /// epsilon cutoff or implicit repair of a nearly affine row.
175 pub fn try_new(model: Mat4) -> Result<Self, AffineError> {
176 if !model.is_finite() {
177 return Err(AffineError::NonFiniteInput { input: "model" });
178 }
179 if model.row(3) != Vec4::W {
180 return Err(AffineError::NonAffine);
181 }
182 let linear = Mat4::from_cols(model.x_axis, model.y_axis, model.z_axis, Vec4::W);
183 let normal_matrix = linear.checked_inverse()?.transpose();
184 // determinant() uses f64 elimination before its f32 cast. Signed zero
185 // preserves orientation when magnitude underflows; +/-infinity also
186 // preserves sign when magnitude overflows. No second inverse is needed.
187 let reflected = linear.determinant().is_sign_negative();
188 Ok(Self {
189 model,
190 normal_matrix,
191 reflected,
192 })
193 }
194
195 /// Atomically replaces all cached state. Failure leaves `self` unchanged.
196 /// Updating to identity resets the transform; there is no hidden history.
197 pub fn try_update(&mut self, model: Mat4) -> Result<(), AffineError> {
198 *self = Self::try_new(model)?;
199 Ok(())
200 }
201
202 /// The exact finite affine model supplied at the last successful preparation.
203 pub const fn model(&self) -> Mat4 {
204 self.model
205 }
206
207 /// Linear inverse transpose in a Mat4 with zero translation and affine row.
208 /// Its `transform_vector3` gives an **unnormalized**, unchecked normal.
209 /// Prefer [`Self::transform_normal`] for checked, normalized results.
210 pub const fn normal_matrix(&self) -> Mat4 {
211 self.normal_matrix
212 }
213
214 /// Whether the computed linear determinant is negative (a mirror).
215 /// This uses its sign even when f32 magnitude overflows or underflows.
216 /// Like the checked inverse, it is not an exact-arithmetic rank or
217 /// conditioning certificate for nearly dependent axes.
218 pub const fn is_reflected(&self) -> bool {
219 self.reflected
220 }
221
222 /// Transforms a finite position with translation, without projective divide.
223 /// Returns a finite f32 result or an error; coordinate underflow is allowed.
224 pub fn transform_point(&self, point: Vec3) -> Result<Vec3, AffineError> {
225 finite_vector(point, "point")?;
226 finite_output(transform_wide(self.model, point, true))
227 }
228
229 /// Transforms a finite direction/displacement without translation.
230 /// Zero vectors are valid. Does not normalize or preserve length.
231 pub fn transform_vector(&self, vector: Vec3) -> Result<Vec3, AffineError> {
232 finite_vector(vector, "vector")?;
233 finite_output(transform_wide(self.model, vector, false))
234 }
235
236 /// Returns a unit inverse-transpose normal, with no determinant-sign flip.
237 /// Nonunit finite inputs are allowed; zero/nonfinite normals fail.
238 /// Wide rescaling avoids intermediate f32 overflow/underflow. Component
239 /// quantization and rounded inverse coefficients can still affect direction.
240 pub fn transform_normal(&self, normal: Vec3) -> Result<Vec3, AffineError> {
241 finite_vector(normal, "normal")?;
242 let wide = transform_wide(self.normal_matrix, normal, false);
243 let scale = wide.into_iter().map(f64::abs).fold(0.0, f64::max);
244 if scale == 0.0 {
245 return Err(AffineError::DegenerateNormal);
246 }
247 Vec3::from_array(wide.map(|v| (v / scale) as f32))
248 .try_normalize()
249 .ok_or(AffineError::DegenerateNormal)
250 }
251
252 /// Transforms every input point into the output prefix, atomically.
253 /// Empty input succeeds; unused output tail is retained. See module bounds.
254 pub fn transform_points_into(
255 &self,
256 input: &[Vec3],
257 output: &mut [Vec3],
258 ) -> Result<(), AffineSliceError> {
259 transform_slice(input, output, |v| self.transform_point(v))
260 }
261
262 /// Transforms every input vector into the output prefix, atomically.
263 /// Zero vectors are accepted; capacity/element errors retain the whole output.
264 pub fn transform_vectors_into(
265 &self,
266 input: &[Vec3],
267 output: &mut [Vec3],
268 ) -> Result<(), AffineSliceError> {
269 transform_slice(input, output, |v| self.transform_vector(v))
270 }
271
272 /// Transforms and normalizes every normal into the output prefix, atomically.
273 /// A zero/nonfinite/collapsed normal fails with its input index. No fallback
274 /// normal is inserted, and even earlier valid elements are left unwritten.
275 pub fn transform_normals_into(
276 &self,
277 input: &[Vec3],
278 output: &mut [Vec3],
279 ) -> Result<(), AffineSliceError> {
280 transform_slice(input, output, |v| self.transform_normal(v))
281 }
282}
283
284fn finite_vector(value: Vec3, input: &'static str) -> Result<(), AffineError> {
285 if value.is_finite() {
286 Ok(())
287 } else {
288 Err(AffineError::NonFiniteInput { input })
289 }
290}
291
292fn transform_wide(matrix: Mat4, value: Vec3, translate: bool) -> [f64; 3] {
293 std::array::from_fn(|row| {
294 let linear = f64::from(matrix.x_axis[row]) * f64::from(value.x)
295 + f64::from(matrix.y_axis[row]) * f64::from(value.y)
296 + f64::from(matrix.z_axis[row]) * f64::from(value.z);
297 linear
298 + if translate {
299 f64::from(matrix.w_axis[row])
300 } else {
301 0.0
302 }
303 })
304}
305
306fn finite_output(value: [f64; 3]) -> Result<Vec3, AffineError> {
307 let result = Vec3::from_array(value.map(|v| v as f32));
308 if result.is_finite() {
309 Ok(result)
310 } else {
311 Err(AffineError::ResultOutOfRange)
312 }
313}
314
315// Private callers supply only pure operations over immutable prepared state.
316// No caller callback, mutable input or external state can change between passes.
317fn transform_slice(
318 input: &[Vec3],
319 output: &mut [Vec3],
320 transform: impl Fn(Vec3) -> Result<Vec3, AffineError>,
321) -> Result<(), AffineSliceError> {
322 if output.len() < input.len() {
323 return Err(AffineSliceError::InsufficientCapacity {
324 required: input.len(),
325 available: output.len(),
326 });
327 }
328 for (index, &value) in input.iter().enumerate() {
329 transform(value).map_err(|source| AffineSliceError::Element { index, source })?;
330 }
331 for (&value, slot) in input.iter().zip(output) {
332 *slot = transform(value).expect("immutable affine operation already validated");
333 }
334 Ok(())
335}