Skip to main content

oa/core/vlm/
affine.rs

1use super::matrix::{Mat3, Mat4};
2use super::quaternion::Quat;
3use super::scalar::{Float, approx, valid_tolerance};
4use super::vector::Vec3;
5
6/// Translation, rotation, signed scale, and reflection extracted from a strict TRS matrix.
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub struct TrsDecomposition<T: Float = f32> {
9	pub translation: Vec3<T>,
10	pub rotation: Quat<T>,
11	pub scale: Vec3<T>,
12	pub reflected: bool,
13}
14
15/// Translation, rotation, signed scale, row-basis shear, and reflection.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct AffineDecomposition<T: Float = f32> {
18	pub translation: Vec3<T>,
19	pub rotation: Quat<T>,
20	pub scale: Vec3<T>,
21	/// Dimensionless XY, XZ, and YZ row-basis shear factors.
22	pub shear: Vec3<T>,
23	pub reflected: bool,
24}
25
26pub type DTrsDecomposition = TrsDecomposition<f64>;
27pub type DAffineDecomposition = AffineDecomposition<f64>;
28
29impl<T: Float> Default for TrsDecomposition<T> {
30	fn default() -> Self {
31		Self {
32			translation: Vec3::default(),
33			rotation: Quat::identity(),
34			scale: Vec3 {
35				x: T::ONE,
36				y: T::ONE,
37				z: T::ONE,
38			},
39			reflected: false,
40		}
41	}
42}
43
44impl<T: Float> Default for AffineDecomposition<T> {
45	fn default() -> Self {
46		Self {
47			translation: Vec3::default(),
48			rotation: Quat::identity(),
49			scale: Vec3 {
50				x: T::ONE,
51				y: T::ONE,
52				z: T::ONE,
53			},
54			shear: Vec3::default(),
55			reflected: false,
56		}
57	}
58}
59
60impl<T: Float> Mat3<T> {
61	pub fn is_identity(self, tolerance: T) -> bool {
62		self.approximately_equal(Self::identity(), tolerance, tolerance)
63	}
64
65	pub fn is_orthonormal(self, tolerance: T) -> bool {
66		if !valid_tolerance(tolerance) {
67			return false;
68		}
69		let x = Vec3 {
70			x: self.m[0][0],
71			y: self.m[0][1],
72			z: self.m[0][2],
73		};
74		let y = Vec3 {
75			x: self.m[1][0],
76			y: self.m[1][1],
77			z: self.m[1][2],
78		};
79		let z = Vec3 {
80			x: self.m[2][0],
81			y: self.m[2][1],
82			z: self.m[2][2],
83		};
84		x.is_finite()
85			&& y.is_finite()
86			&& z.is_finite()
87			&& approx(x.length_squared(), T::ONE, tolerance, tolerance)
88			&& approx(y.length_squared(), T::ONE, tolerance, tolerance)
89			&& approx(z.length_squared(), T::ONE, tolerance, tolerance)
90			&& approx(x.dot(y), T::ZERO, tolerance, T::ZERO)
91			&& approx(x.dot(z), T::ZERO, tolerance, T::ZERO)
92			&& approx(y.dot(z), T::ZERO, tolerance, T::ZERO)
93	}
94
95	pub fn is_proper_rotation(self, tolerance: T) -> bool {
96		self.is_orthonormal(tolerance) && approx(self.determinant(), T::ONE, tolerance, tolerance)
97	}
98
99	pub fn try_orthonormal_basis(first: Vec3<T>, second: Vec3<T>, tolerance: T) -> Option<Self> {
100		if !valid_tolerance(tolerance) || first.length() <= tolerance {
101			return None;
102		}
103		let first = first.try_normalized()?;
104		let rejected = second.try_reject_from(first, tolerance)?;
105		if rejected.length() <= tolerance {
106			return None;
107		}
108		let second = rejected.try_normalized()?;
109		let third = first.cross(second);
110		let basis = Self {
111			m: [
112				[first.x, first.y, first.z],
113				[second.x, second.y, second.z],
114				[third.x, third.y, third.z],
115			],
116		};
117		basis
118			.is_proper_rotation(tolerance * T::from_f64(8.0))
119			.then_some(basis)
120	}
121
122	pub fn try_transform_normal(self, normal: Vec3<T>, tolerance: T) -> Option<Vec3<T>> {
123		let transformed = normal * self;
124		if !valid_tolerance(tolerance) || transformed.length() <= tolerance {
125			return None;
126		}
127		transformed.try_normalized()
128	}
129}
130
131impl<T: Float> Mat4<T> {
132	pub fn is_identity(self, tolerance: T) -> bool {
133		self.approximately_equal(Self::identity(), tolerance, tolerance)
134	}
135
136	pub fn try_view_from_pose(position: Vec3<T>, rotation: Quat<T>, tolerance: T) -> Option<Self> {
137		if !valid_tolerance(tolerance) || !position.is_finite() {
138			return None;
139		}
140		let inverse_rotation = rotation.conjugate().try_normalized()?;
141		let view = Self::translation(-position) * Self::try_from_quaternion(inverse_rotation)?;
142		view.is_finite().then_some(view)
143	}
144
145	#[inline]
146	pub fn try_look_at(
147		eye: Vec3<T>,
148		target: Vec3<T>,
149		world_up: Vec3<T>,
150		tolerance: T,
151	) -> Option<Self> {
152		if !valid_tolerance(tolerance)
153			|| !eye.is_finite()
154			|| !target.is_finite()
155			|| !world_up.is_finite()
156		{
157			return None;
158		}
159		let forward_value = target - eye;
160		if forward_value.length() <= tolerance {
161			return None;
162		}
163		let forward = forward_value.try_normalized()?;
164		let right_value = forward.cross(world_up);
165		if right_value.length() <= tolerance {
166			return None;
167		}
168		let right = right_value.try_normalized()?;
169		let up = right.cross(forward);
170		let basis = Mat3 {
171			m: [
172				[right.x, up.x, -forward.x],
173				[right.y, up.y, -forward.y],
174				[right.z, up.z, -forward.z],
175			],
176		};
177		let translation = Vec3 {
178			x: -right.dot(eye),
179			y: -up.dot(eye),
180			z: forward.dot(eye),
181		};
182		let view = Self::new_from_affine(basis, translation);
183		view.is_finite().then_some(view)
184	}
185
186	pub fn compose_affine(decomposition: AffineDecomposition<T>) -> Option<Self> {
187		if !decomposition.translation.is_finite()
188			|| !decomposition.scale.is_finite()
189			|| !decomposition.shear.is_finite()
190		{
191			return None;
192		}
193		let rotation = Self::try_from_quaternion(decomposition.rotation)?.linear_part();
194		let x = Vec3 {
195			x: rotation.m[0][0],
196			y: rotation.m[0][1],
197			z: rotation.m[0][2],
198		};
199		let y = Vec3 {
200			x: rotation.m[1][0],
201			y: rotation.m[1][1],
202			z: rotation.m[1][2],
203		};
204		let z = Vec3 {
205			x: rotation.m[2][0],
206			y: rotation.m[2][1],
207			z: rotation.m[2][2],
208		};
209		let row_x = x * decomposition.scale.x;
210		let row_y = (y + x * decomposition.shear.x) * decomposition.scale.y;
211		let row_z = (z + x * decomposition.shear.y + y * decomposition.shear.z) * decomposition.scale.z;
212		Some(Self::new_from_affine(
213			Mat3 {
214				m: [
215					[row_x.x, row_x.y, row_x.z],
216					[row_y.x, row_y.y, row_y.z],
217					[row_z.x, row_z.y, row_z.z],
218				],
219			},
220			decomposition.translation,
221		))
222	}
223
224	pub fn try_decompose_affine(self, tolerance: T) -> Option<AffineDecomposition<T>> {
225		if !valid_tolerance(tolerance) || !self.is_affine(tolerance) {
226			return None;
227		}
228		let linear = self.linear_part();
229		let mut x = Vec3 {
230			x: linear.m[0][0],
231			y: linear.m[0][1],
232			z: linear.m[0][2],
233		};
234		let mut y = Vec3 {
235			x: linear.m[1][0],
236			y: linear.m[1][1],
237			z: linear.m[1][2],
238		};
239		let mut z = Vec3 {
240			x: linear.m[2][0],
241			y: linear.m[2][1],
242			z: linear.m[2][2],
243		};
244		let mut scale_x = x.length();
245		if !scale_x.is_finite() || scale_x <= tolerance {
246			return None;
247		}
248		x /= scale_x;
249		let mut shear_xy = x.dot(y);
250		y -= x * shear_xy;
251		let scale_y = y.length();
252		if !scale_y.is_finite() || scale_y <= tolerance {
253			return None;
254		}
255		y /= scale_y;
256		shear_xy = shear_xy / scale_y;
257
258		let mut shear_xz = x.dot(z);
259		z -= x * shear_xz;
260		let mut shear_yz = y.dot(z);
261		z -= y * shear_yz;
262		let scale_z = z.length();
263		if !scale_z.is_finite() || scale_z <= tolerance {
264			return None;
265		}
266		z /= scale_z;
267		shear_xz = shear_xz / scale_z;
268		shear_yz = shear_yz / scale_z;
269		if !shear_xy.is_finite() || !shear_xz.is_finite() || !shear_yz.is_finite() {
270			return None;
271		}
272		let orientation = x.cross(y).dot(z);
273		let orientation_tolerance = tolerance * T::from_f64(8.0);
274		if !orientation.is_finite()
275			|| !approx(
276				orientation.abs(),
277				T::ONE,
278				orientation_tolerance,
279				orientation_tolerance,
280			) {
281			return None;
282		}
283		let reflected = orientation < T::ZERO;
284		if reflected {
285			x = -x;
286			scale_x = -scale_x;
287			shear_xy = -shear_xy;
288			shear_xz = -shear_xz;
289		}
290		let rotation = Quat::try_from_rotation_matrix(
291			Mat3 {
292				m: [[x.x, x.y, x.z], [y.x, y.y, y.z], [z.x, z.y, z.z]],
293			},
294			orientation_tolerance,
295		)?;
296		Some(AffineDecomposition {
297			translation: self.translation_part(),
298			rotation,
299			scale: Vec3 {
300				x: scale_x,
301				y: scale_y,
302				z: scale_z,
303			},
304			shear: Vec3 {
305				x: shear_xy,
306				y: shear_xz,
307				z: shear_yz,
308			},
309			reflected,
310		})
311	}
312
313	pub fn try_decompose_trs(self, tolerance: T) -> Option<TrsDecomposition<T>> {
314		let affine = self.try_decompose_affine(tolerance)?;
315		let shear_tolerance = tolerance * T::from_f64(8.0);
316		if affine.shear.x.abs() > shear_tolerance
317			|| affine.shear.y.abs() > shear_tolerance
318			|| affine.shear.z.abs() > shear_tolerance
319		{
320			return None;
321		}
322		Some(TrsDecomposition {
323			translation: affine.translation,
324			rotation: affine.rotation,
325			scale: affine.scale,
326			reflected: affine.reflected,
327		})
328	}
329}
330
331impl<T: Float> Quat<T> {
332	pub fn try_from_rotation_matrix(matrix: Mat3<T>, tolerance: T) -> Option<Self> {
333		if !valid_tolerance(tolerance) || !matrix.is_proper_rotation(tolerance) {
334			return None;
335		}
336		quaternion_from_rotation_matrix_unchecked(Mat4::new_from_affine(matrix, Vec3::default()))
337	}
338
339	pub fn try_from_rotation_matrix4(matrix: Mat4<T>, tolerance: T) -> Option<Self> {
340		if !matrix.is_affine(tolerance) {
341			return None;
342		}
343		Self::try_from_rotation_matrix(matrix.linear_part(), tolerance)
344	}
345
346	pub fn try_from_to(from: Vec3<T>, to: Vec3<T>, tolerance: T) -> Option<Self> {
347		if !valid_tolerance(tolerance) || from.length() <= tolerance || to.length() <= tolerance {
348			return None;
349		}
350		let from = from.try_normalized()?;
351		let to = to.try_normalized()?;
352		let cosine = from.dot(to).max(-T::ONE).min(T::ONE);
353		if cosine >= T::ONE - tolerance {
354			return Some(Self::identity());
355		}
356		if cosine <= -T::ONE + tolerance {
357			return Self::try_from_axis_angle(from.try_perpendicular(tolerance)?, T::PI);
358		}
359		let axis = from.cross(to);
360		Self {
361			x: axis.x,
362			y: axis.y,
363			z: axis.z,
364			w: T::ONE + cosine,
365		}
366		.try_normalized()
367	}
368
369	pub fn try_look_rotation(forward: Vec3<T>, world_up: Vec3<T>, tolerance: T) -> Option<Self> {
370		let view = Mat4::try_look_at(Vec3::default(), forward, world_up, tolerance)?;
371		Self::try_from_rotation_matrix(view.linear_part().transpose(), tolerance * T::from_f64(8.0))
372	}
373}
374
375fn quaternion_from_rotation_matrix_unchecked<T: Float>(matrix: Mat4<T>) -> Option<Quat<T>> {
376	let at = |row: usize, column: usize| matrix.m[column][row];
377	let m00 = at(0, 0);
378	let m11 = at(1, 1);
379	let m22 = at(2, 2);
380	let trace = m00 + m11 + m22;
381	let mut result = Quat::identity();
382	if trace > T::ZERO {
383		let scale = (trace + T::ONE).sqrt() * T::TWO;
384		result.w = T::from_f64(0.25) * scale;
385		result.x = (at(2, 1) - at(1, 2)) / scale;
386		result.y = (at(0, 2) - at(2, 0)) / scale;
387		result.z = (at(1, 0) - at(0, 1)) / scale;
388	} else if m00 > m11 && m00 > m22 {
389		let scale = (T::ONE + m00 - m11 - m22).sqrt() * T::TWO;
390		result.w = (at(2, 1) - at(1, 2)) / scale;
391		result.x = T::from_f64(0.25) * scale;
392		result.y = (at(0, 1) + at(1, 0)) / scale;
393		result.z = (at(0, 2) + at(2, 0)) / scale;
394	} else if m11 > m22 {
395		let scale = (T::ONE + m11 - m00 - m22).sqrt() * T::TWO;
396		result.w = (at(0, 2) - at(2, 0)) / scale;
397		result.x = (at(0, 1) + at(1, 0)) / scale;
398		result.y = T::from_f64(0.25) * scale;
399		result.z = (at(1, 2) + at(2, 1)) / scale;
400	} else {
401		let scale = (T::ONE + m22 - m00 - m11).sqrt() * T::TWO;
402		result.w = (at(1, 0) - at(0, 1)) / scale;
403		result.x = (at(0, 2) + at(2, 0)) / scale;
404		result.y = (at(1, 2) + at(2, 1)) / scale;
405		result.z = T::from_f64(0.25) * scale;
406	}
407	result.try_normalized()
408}