nalgebra/examples/dimensional_genericity.rs

61 lines
2.0 KiB
Rust
Raw Permalink Normal View History

2017-02-13 01:17:09 +08:00
extern crate nalgebra as na;
use na::allocator::Allocator;
use na::dimension::Dim;
2021-04-11 17:00:38 +08:00
use na::{DefaultAllocator, OVector, RealField, Unit, Vector2, Vector3};
2017-02-13 01:17:09 +08:00
/// Reflects a vector wrt. the hyperplane with normal `plane_normal`.
2021-04-11 17:00:38 +08:00
fn reflect_wrt_hyperplane_with_dimensional_genericity<T: RealField, D: Dim>(
plane_normal: &Unit<OVector<T, D>>,
vector: &OVector<T, D>,
) -> OVector<T, D>
2018-02-02 19:26:35 +08:00
where
2021-04-11 17:00:38 +08:00
T: RealField,
2018-02-02 19:26:35 +08:00
D: Dim,
DefaultAllocator: Allocator<D>,
2018-02-02 19:26:35 +08:00
{
2017-02-13 01:17:09 +08:00
let n = plane_normal.as_ref(); // Get the underlying V.
vector - n * (n.dot(vector) * na::convert(2.0))
}
/// Reflects a 2D vector wrt. the 2D line with normal `plane_normal`.
2021-04-11 17:00:38 +08:00
fn reflect_wrt_hyperplane2<T>(plane_normal: &Unit<Vector2<T>>, vector: &Vector2<T>) -> Vector2<T>
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
T: RealField,
2020-04-06 00:49:48 +08:00
{
2017-02-13 01:17:09 +08:00
let n = plane_normal.as_ref(); // Get the underlying Vector2
vector - n * (n.dot(vector) * na::convert(2.0))
}
/// Reflects a 3D vector wrt. the 3D plane with normal `plane_normal`.
2023-10-08 01:13:25 +08:00
/// /!\ This is an exact replicate of `reflect_wrt_hyperplane2`, but for 3D.
2021-04-11 17:00:38 +08:00
fn reflect_wrt_hyperplane3<T>(plane_normal: &Unit<Vector3<T>>, vector: &Vector3<T>) -> Vector3<T>
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
T: RealField,
2020-04-06 00:49:48 +08:00
{
2017-02-13 01:17:09 +08:00
let n = plane_normal.as_ref(); // Get the underlying Vector3
vector - n * (n.dot(vector) * na::convert(2.0))
}
fn main() {
let plane2 = Vector2::y_axis(); // 2D plane normal.
let plane3 = Vector3::y_axis(); // 3D plane normal.
2018-02-02 19:26:35 +08:00
let v2 = Vector2::new(1.0, 2.0); // 2D vector to be reflected.
2017-02-13 01:17:09 +08:00
let v3 = Vector3::new(1.0, 2.0, 3.0); // 3D vector to be reflected.
// We can call the same function for 2D and 3D.
2018-02-02 19:26:35 +08:00
assert_eq!(
reflect_wrt_hyperplane_with_dimensional_genericity(&plane2, &v2).y,
-2.0
);
assert_eq!(
reflect_wrt_hyperplane_with_dimensional_genericity(&plane3, &v3).y,
-2.0
);
2017-02-13 01:17:09 +08:00
// Call each specific implementation depending on the dimension.
assert_eq!(reflect_wrt_hyperplane2(&plane2, &v2).y, -2.0);
assert_eq!(reflect_wrt_hyperplane3(&plane3, &v3).y, -2.0);
}