| 1 |
extern crate nalgebra as na; |
| 2 |
|
| 3 |
use na::allocator::Allocator; |
| 4 |
use na::dimension::Dim; |
| 5 |
use na::{DefaultAllocator, OVector, RealField, Unit, Vector2, Vector3}; |
| 6 |
|
| 7 |
/// Reflects a vector wrt. the hyperplane with normal `plane_normal`. |
| 8 |
fn reflect_wrt_hyperplane_with_dimensional_genericity<T: RealField, D: Dim>( |
| 9 |
plane_normal: &Unit<OVector<T, D>>, |
| 10 |
vector: &OVector<T, D>, |
| 11 |
) -> OVector<T, D> |
| 12 |
where |
| 13 |
T: RealField, |
| 14 |
D: Dim, |
| 15 |
DefaultAllocator: Allocator<D>, |
| 16 |
{ |
| 17 |
let n = plane_normal.as_ref(); // Get the underlying V. |
| 18 |
vector - n * (n.dot(vector) * na::convert(2.0)) |
| 19 |
} |
| 20 |
|
| 21 |
/// Reflects a 2D vector wrt. the 2D line with normal `plane_normal`. |
| 22 |
fn reflect_wrt_hyperplane2<T>(plane_normal: &Unit<Vector2<T>>, vector: &Vector2<T>) -> Vector2<T> |
| 23 |
where |
| 24 |
T: RealField, |
| 25 |
{ |
| 26 |
let n = plane_normal.as_ref(); // Get the underlying Vector2 |
| 27 |
vector - n * (n.dot(vector) * na::convert(2.0)) |
| 28 |
} |
| 29 |
|
| 30 |
/// Reflects a 3D vector wrt. the 3D plane with normal `plane_normal`. |
| 31 |
/// /!\ This is an exact replicate of `reflect_wrt_hyperplane2`, but for 3D. |
| 32 |
fn reflect_wrt_hyperplane3<T>(plane_normal: &Unit<Vector3<T>>, vector: &Vector3<T>) -> Vector3<T> |
| 33 |
where |
| 34 |
T: RealField, |
| 35 |
{ |
| 36 |
let n = plane_normal.as_ref(); // Get the underlying Vector3 |
| 37 |
vector - n * (n.dot(vector) * na::convert(2.0)) |
| 38 |
} |
| 39 |
|
| 40 |
fn main() { |
| 41 |
let plane2 = Vector2::y_axis(); // 2D plane normal. |
| 42 |
let plane3 = Vector3::y_axis(); // 3D plane normal. |
| 43 |
|
| 44 |
let v2 = Vector2::new(1.0, 2.0); // 2D vector to be reflected. |
| 45 |
let v3 = Vector3::new(1.0, 2.0, 3.0); // 3D vector to be reflected. |
| 46 |
|
| 47 |
// We can call the same function for 2D and 3D. |
| 48 |
assert_eq!( |
| 49 |
reflect_wrt_hyperplane_with_dimensional_genericity(&plane2, &v2).y, |
| 50 |
-2.0 |
| 51 |
); |
| 52 |
assert_eq!( |
| 53 |
reflect_wrt_hyperplane_with_dimensional_genericity(&plane3, &v3).y, |
| 54 |
-2.0 |
| 55 |
); |
| 56 |
|
| 57 |
// Call each specific implementation depending on the dimension. |
| 58 |
assert_eq!(reflect_wrt_hyperplane2(&plane2, &v2).y, -2.0); |
| 59 |
assert_eq!(reflect_wrt_hyperplane3(&plane3, &v3).y, -2.0); |
| 60 |
} |