use crate::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Rotated {
Gradients,
ThermodynamicForces,
TangentOperator,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Frame {
Global,
Material,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rotation {
pub(crate) matrix: [[f64; 3]; 3],
}
impl Rotation {
pub fn new(matrix: [[f64; 3]; 3]) -> Result<Rotation, Error> {
let column = |j: usize| [matrix[0][j], matrix[1][j], matrix[2][j]];
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
let tolerance = 100.0 * f64::EPSILON;
if !(0..3).all(|j| (dot(column(j), column(j)).sqrt() - 1.0).abs() <= tolerance) {
return Err(Error::InvalidRotation {
reason: "a column is not of unit length",
});
}
if ![(0, 1), (0, 2), (1, 2)]
.iter()
.all(|&(a, b)| dot(column(a), column(b)).abs() <= tolerance)
{
return Err(Error::InvalidRotation {
reason: "two columns are not orthogonal",
});
}
Ok(Rotation { matrix })
}
pub fn from_axes(axis1: [f64; 3], axis2: [f64; 3]) -> Result<Rotation, Error> {
let norm = |v: [f64; 3]| (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
let n1 = norm(axis1);
if !(n1 > 0.0 && n1.is_finite()) {
return Err(Error::InvalidRotation {
reason: "the first axis is zero or not finite",
});
}
let a = axis1.map(|x| x / n1);
let projection = a[0] * axis2[0] + a[1] * axis2[1] + a[2] * axis2[2];
let b = [0, 1, 2].map(|i| axis2[i] - projection * a[i]);
let n2 = norm(b);
let b = b.map(|x| x / n2);
let c = [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
Rotation::new([0, 1, 2].map(|i| [a[i], b[i], c[i]])).map_err(|_| Error::InvalidRotation {
reason: "the second axis is zero, parallel to the first, or not finite",
})
}
}