Merge pull request #218 from sebcrozet/nexgen

Release v0.11.0
This commit is contained in:
Sébastien Crozet 2017-02-15 22:49:26 +01:00 committed by GitHub
commit 1471031ac4
169 changed files with 21159 additions and 14484 deletions

View File

@ -1,7 +1,20 @@
sudo: false
language: rust language: rust
matrix:
include:
- rust: nightly
env: TEST_SUITE=suite_nightly
- rust: beta
env: TEST_SUITE=suite_beta
- rust: stable
env: TEST_SUITE=suite_stable
allow_failures:
- rust: nightly
- rust: beta
script: script:
- rustc --version - rustc --version
- cargo --version - cargo --version
- cargo build --verbose --features "arbitrary generic_sizes" - cargo build --verbose
- cargo test --verbose --features arbitrary - cargo build --verbose --features arbitrary
- cargo build --verbose --features serde-serialize
- cargo test --verbose --features "arbitrary serde-serialize"

View File

@ -4,6 +4,106 @@ documented here.
This project adheres to [Semantic Versioning](http://semver.org/). This project adheres to [Semantic Versioning](http://semver.org/).
## [0.11.0]
The [website](http://nalgebra.org) has been fully rewritten and gives a good
overview of all the added/modified features.
This version is a major rewrite of the library. Major changes are:
* Algebraic traits are now defined by the [alga](https://crates.io/crates/alga) crate.
All other mathematical traits, except `Axpy` have been removed from
**nalgebra**.
* Methods are now preferred to free functions because they do not require any
trait to be used any more.
* Most algebraic entities can be parametrized by type-level integers
to specify their dimensions. Using `Dynamic` instead of a type-level
integer indicates that the dimension known at run-time only.
* Statically-sized **rectangular** matrices.
* More transformation types have been added: unit-sized complex numbers (for
2D rotations), affine/projective/general transformations with `Affine2/3`,
`Projective2/3`, and `Transform2/3`.
* Serde serialization is now supported instead of `rustc_serialize`. Enable
it with the `serde-serialize` feature.
* Matrix **slices** are now implemented.
### Added
Lots of features including rectangular matrices, slices, and Serde
serialization. Refer to the brand new [website](http://nalgebra.org) for more
details. The following free-functions have been added as well:
* `::id()` that returns the universal [identity element](http://nalgebra.org/performance_tricks/#the-id-type)
of type `Id`.
* `::inf_sup()` that returns both the infimum and supremum of a value at the
same time.
* `::partial_sort2()` that attempts to sort two values in increasing order.
* `::wrap()` that moves a value to the given interval by adding or removing
the interval width to it.
### Modified
* `::cast` -> `::convert`
* `point.as_vector()` -> `point.coords`
* `na::origin` -> `P::origin()`
* `na::is_zero` -> `.is_zero()` (from num::Zero)
* `.transform` -> `.transform_point`/`.transform_vector`
* `.translate` -> `.translate_point`
* `::dimension::<P>` -> `::dimension::<P::Vector>`
* `::angle_between` -> `::angle`
The following free-functions are now replaced by methods (with the same names)
only:
`::cross`, `::cholesky`, `::determinant`, `::diagonal`, `::eigen_qr` (becomes
`.eig`), `::hessenberg`, `::qr`, `::to_homogeneous`, `::to_rotation_matrix`,
`::transpose`, `::shape`.
The following free-functions are now replaced by static methods only:
* `::householder_matrix` under the name `::new_householder_generic`
* `::identity`
* `::new_identity` under the name `::identity`
* `::from_homogeneous`
* `::repeat` under the name `::from_element`
The following free-function are now replaced methods accessible through traits
only:
* `::transform` -> methods `.transform_point` and `.transform_vector` of the `alga::linear::Transformation` trait.
* `::inverse_transform` -> methods `.inverse_transform_point` and
`.inverse_transform_vector` of the `alga::linear::ProjectiveTransformation`
trait.
* `::translate`, `::inverse_translate`, `::rotate`, `::inverse_rotate` ->
methods from the `alga::linear::Similarity` trait instead. Those have the
same names but end with `_point` or `_vector`, e.g., `.translate_point` and
`.translate_vector`.
* `::orthonormal_subspace_basis` -> method with the same name from
`alga::linear::FiniteDimInnerSpace`.
* `::canonical_basis_element` and `::canonical_basis` -> methods with the
same names from `alga::linear::FiniteDimVectorSpace`.
* `::rotation_between` -> method with the same name from the
`alga::linear::Rotation` trait.
* `::is_zero` -> method with the same name from `num::Zero`.
### Removed
* The free functions `::prepend_rotation`, `::append_rotation`,
`::append_rotation_wrt_center`, `::append_rotation_wrt_point`,
`::append_transformation`, and `::append_translation ` have been removed.
Instead create the rotation or translation object explicitly and use
multiplication to compose it with anything else.
* The free function `::outer` has been removed. Use column-vector ×
row-vector multiplication instead.
* `::approx_eq`, `::approx_eq_eps` have been removed. Use the `relative_eq!`
macro from the [approx](https://crates.io/crates/approx) crate instead.
* `::covariance` has been removed. There is no replacement for now.
* `::mean` has been removed. There is no replacement for now.
* `::sample_sphere` has been removed. There is no replacement for now.
* `::cross_matrix` has been removed. There is no replacement for now.
* `::absolute_rotate` has been removed. There is no replacement for now.
* `::rotation`, `::transformation`, `::translation`, `::inverse_rotation`,
`::inverse_transformation`, `::inverse_translation` have been removed. Use
the appropriate methods/field of each transformation type, e.g.,
`rotation.angle()` and `rotation.axis()`.
## [0.10.0] ## [0.10.0]
### Added ### Added
Binary operations are now allowed between references as well. For example Binary operations are now allowed between references as well. For example

View File

@ -1,7 +1,7 @@
[package] [package]
name = "nalgebra" name = "nalgebra"
version = "0.10.1" version = "0.11.0"
authors = [ "Sébastien Crozet <developer@crozet.re>" ] # FIXME: add the contributors. authors = [ "Sébastien Crozet <developer@crozet.re>" ]
description = "Linear algebra library for computer physics, computer graphics and general low-dimensional linear algebra for Rust." description = "Linear algebra library for computer physics, computer graphics and general low-dimensional linear algebra for Rust."
documentation = "http://nalgebra.org/doc/nalgebra/index.html" documentation = "http://nalgebra.org/doc/nalgebra/index.html"
@ -16,28 +16,24 @@ name = "nalgebra"
path = "src/lib.rs" path = "src/lib.rs"
[features] [features]
# Generate arbitrary instances of nalgebra types for testing with quickcheck
arbitrary = [ "quickcheck" ] arbitrary = [ "quickcheck" ]
generic_sizes = [ "generic-array", "typenum" ] serde-serialize = [ "serde", "serde_derive" ]
abstract_algebra = [ "algebra" ]
[dependencies] [dependencies]
rustc-serialize = "0.3.*" typenum = "1.4"
rand = "0.3.*" generic-array = "0.2"
num = "0.1.*" rand = "0.3"
num-traits = "0.1"
[dependencies.generic-array] num-complex = "0.1"
optional = true approx = "0.1"
version = "0.2.*" alga = "0.5"
serde = { version = "0.9", optional = true }
[dependencies.typenum] serde_derive = { version = "0.9", optional = true }
optional = true # clippy = "*"
version = "1.3.*"
[dependencies.quickcheck] [dependencies.quickcheck]
optional = true optional = true
version = "0.2.*" version = "0.3"
[dependencies.algebra] [dev-dependencies]
optional = true serde_json = "0.9"
version = "0.2.*"

View File

@ -1,30 +1,11 @@
tmp=_git_distcheck
all: all:
cargo build --release --features "arbitrary generic_sizes abstract_algebra" CARGO_INCREMENTAL=1 cargo build --features "arbitrary serde-serialize"
test:
cargo test --features "arbitrary generic_sizes abstract_algebra"
bench:
cargo bench --features "arbitrary generic_sizes abstract_algebra"
doc: doc:
cargo doc --no-deps --features "arbitrary generic_sizes abstract_algebra" CARGO_INCREMENTAL=1 cargo doc --no-deps --features "arbitrary serde-serialize"
bench:
cargo bench
clean: test:
cargo clean CARGO_INCREMENTAL=1 cargo test --features "arbitrary serde-serialize"
distcheck:
rm -rf $(tmp)
git clone --recursive . $(tmp)
make -C $(tmp)
make -C $(tmp) test
make -C $(tmp) bench
rm -rf $(tmp)
.PHONY:doc
.PHONY:test

View File

@ -1,82 +1,26 @@
<p align="center"> <p align="center">
<img src="http://nalgebra.org/img/logo_nalgebra.svg" alt="crates.io">
</p>
<p align="center">
<a href="https://travis-ci.org/sebcrozet/nalgebra">
<img src="https://travis-ci.org/sebcrozet/nalgebra.svg?branch=master" alt="Build status">
</a>
<a href="https://crates.io/crates/nalgebra"> <a href="https://crates.io/crates/nalgebra">
<img src="http://meritbadge.herokuapp.com/nalgebra?style=flat-square" alt="crates.io"> <img src="http://meritbadge.herokuapp.com/nalgebra?style=flat-square" alt="crates.io">
</a> </a>
<a href="https://travis-ci.org/sebcrozet/nalgebra"> <a href="https://opensource.org/licenses/BSD-3-Clause">
<img src="https://travis-ci.org/sebcrozet/nalgebra.svg?branch=master" alt="Build status"> <img src="https://img.shields.io/badge/license-BSD%203--Clause-blue.svg?style=flat">
</a> </a>
</p> </p>
<p align = "center"> <p align = "center">
<strong> <strong>
<a href="http://nalgebra.org/doc/nalgebra">Documentation</a> | <a href="http://users.nphysics.org">Forum</a> <a href="http://nalgebra.org">Users guide</a> | <a href="http://nalgebra.org/rustdoc/nalgebra/index.html">Documentation</a> | <a href="http://users.nphysics.org/c/nalgebra">Forum</a>
</strong> </strong>
</p> </p>
nalgebra -----
========
**nalgebra** is a low-dimensional linear algebra library written for Rust targeting: <p align = "center">
<b>Linear algebra library</b>
* General-purpose linear algebra (still lacks a lot of features…) <i>for the Rust programming language.</i>
* Real time computer graphics. </p>
* Real time computer physics.
## Using **nalgebra**
You will need the last stable build of the [rust compiler](http://www.rust-lang.org)
and the official package manager: [cargo](https://github.com/rust-lang/cargo).
Simply add the following to your `Cargo.toml` file:
```.ignore
[dependencies]
nalgebra = "0.10.*"
```
All the functionality of **nalgebra** is grouped in one place: the root module `nalgebra::`. This
module re-exports everything and includes free functions for all traits methods performing
out-of-place operations.
Thus, you can import the whole prelude using:
```.ignore
use nalgebra::*;
```
However, the recommended way to use **nalgebra** is to import types and traits
explicitly, and call free-functions using the `na::` prefix:
```.rust
extern crate nalgebra as na;
use na::{Vector3, Rotation3, Rotation};
fn main() {
let a = Vector3::new(1.0f64, 1.0, 1.0);
let mut b = Rotation3::new(na::zero());
b.append_rotation_mut(&a);
assert!(na::approx_eq(&na::rotation(&b), &a));
}
```
## Features
**nalgebra** is meant to be a general-purpose, low-dimensional, linear algebra library, with
an optimized set of tools for computer graphics and physics. Those features include:
* Vectors with predefined static sizes: `Vector1`, `Vector2`, `Vector3`, `Vector4`, `Vector5`, `Vector6`.
* Vector with a user-defined static size: `VectorN` (available only with the `generic_sizes` feature).
* Points with static sizes: `Point1`, `Point2`, `Point3`, `Point4`, `Point5`, `Point6`.
* Square matrices with static sizes: `Matrix1`, `Matrix2`, `Matrix3`, `Matrix4`, `Matrix5`, `Matrix6 `.
* Rotation matrices: `Rotation2`, `Rotation3`
* Quaternions: `Quaternion`, `Unit<Quaternion>`.
* Unit-sized values (unit vectors, unit quaternions, etc.): `Unit<T>`, e.g., `Unit<Vector3<f32>>`.
* Isometries (translation rotation): `Isometry2`, `Isometry3`
* Similarity transformations (translation rotation uniform scale): `Similarity2`, `Similarity3`.
* 3D projections for computer graphics: `Persp3`, `PerspMatrix3`, `Ortho3`, `OrthoMatrix3`.
* Dynamically sized heap-allocated vector: `DVector`.
* Dynamically sized stack-allocated vectors with a maximum size: `DVector1` to `DVector6`.
* Dynamically sized heap-allocated (square or rectangular) matrix: `DMatrix`.
* Linear algebra and data analysis operators: `Covariance`, `Mean`, `qr`, `cholesky`.
* Almost one trait per functionality: useful for generic programming.

View File

@ -16,7 +16,30 @@ macro_rules! bench_binop(
i = (i + 1) & (LEN - 1); i = (i + 1) & (LEN - 1);
unsafe { unsafe {
test::black_box((*elems1.get_unchecked(i)).$binop(*elems2.get_unchecked(i))) test::black_box(elems1.get_unchecked(i).$binop(*elems2.get_unchecked(i)))
}
})
}
}
);
macro_rules! bench_binop_ref(
($name: ident, $t1: ty, $t2: ty, $binop: ident) => {
#[bench]
fn $name(bh: &mut Bencher) {
const LEN: usize = 1 << 13;
let mut rng = IsaacRng::new_unseeded();
let elems1: Vec<$t1> = (0usize .. LEN).map(|_| rng.gen::<$t1>()).collect();
let elems2: Vec<$t2> = (0usize .. LEN).map(|_| rng.gen::<$t2>()).collect();
let mut i = 0;
bh.iter(|| {
i = (i + 1) & (LEN - 1);
unsafe {
test::black_box(elems1.get_unchecked(i).$binop(elems2.get_unchecked(i)))
} }
}) })
} }
@ -46,7 +69,7 @@ macro_rules! bench_binop_na(
} }
); );
macro_rules! bench_unop( macro_rules! bench_unop_na(
($name: ident, $t: ty, $unop: ident) => { ($name: ident, $t: ty, $unop: ident) => {
#[bench] #[bench]
fn $name(bh: &mut Bencher) { fn $name(bh: &mut Bencher) {
@ -68,7 +91,7 @@ macro_rules! bench_unop(
} }
); );
macro_rules! bench_unop_self( macro_rules! bench_unop(
($name: ident, $t: ty, $unop: ident) => { ($name: ident, $t: ty, $unop: ident) => {
#[bench] #[bench]
fn $name(bh: &mut Bencher) { fn $name(bh: &mut Bencher) {

View File

@ -1,19 +0,0 @@
#![feature(test)]
extern crate test;
extern crate rand;
extern crate nalgebra as na;
use rand::{IsaacRng, Rng};
use test::Bencher;
use na::{UnitQuaternion, Rotation2, Rotation3, Vector1, Vector3};
#[path="common/macros.rs"]
mod macros;
bench_construction!(_bench_quaternion_from_axisangle, UnitQuaternion::from_scaled_axis, axisangle: Vector3<f32>);
bench_construction!(_bench_rot2_from_axisangle, Rotation2::new, axisangle: Vector1<f32>);
bench_construction!(_bench_rot3_from_axisangle, Rotation3::new, axisangle: Vector3<f32>);
bench_construction!(_bench_quaternion_from_euler_angles, UnitQuaternion::from_euler_angles, roll: f32, pitch: f32, yaw: f32);
bench_construction!(_bench_rot3_from_euler_angles, Rotation3::from_euler_angles, roll: f32, pitch: f32, yaw: f32);

View File

@ -1,90 +0,0 @@
#![feature(test)]
extern crate test;
extern crate nalgebra as na;
use test::Bencher;
use na::{DVector, DMatrix};
macro_rules! bench_mul_dmatrix(
($bh: expr, $nrows: expr, $ncols: expr) => {
{
$bh.iter(|| {
let a: DMatrix<f64> = DMatrix::new_random($nrows, $ncols);
let mut b: DMatrix<f64> = DMatrix::new_random($nrows, $ncols);
for _ in 0usize .. 1000 {
// XXX: the clone here is highly undesirable!
b = a.clone() * b;
}
})
}
}
);
#[bench]
fn bench_mul_dmat2(bh: &mut Bencher) {
bench_mul_dmatrix!(bh, 2, 2);
}
#[bench]
fn bench_mul_dmat3(bh: &mut Bencher) {
bench_mul_dmatrix!(bh, 3, 3);
}
#[bench]
fn bench_mul_dmat4(bh: &mut Bencher) {
bench_mul_dmatrix!(bh, 4, 4);
}
#[bench]
fn bench_mul_dmat5(bh: &mut Bencher) {
bench_mul_dmatrix!(bh, 5, 5);
}
#[bench]
fn bench_mul_dmat6(bh: &mut Bencher) {
bench_mul_dmatrix!(bh, 6, 6);
}
macro_rules! bench_mul_dmat_dvector(
($bh: expr, $nrows: expr, $ncols: expr) => {
{
$bh.iter(|| {
let m : DMatrix<f64> = DMatrix::new_random($nrows, $ncols);
let mut v : DVector<f64> = DVector::new_random($ncols);
for _ in 0usize .. 1000 {
// XXX: the clone here is highly undesirable!
v = m.clone() * v
}
})
}
}
);
#[bench]
fn bench_mul_dmat_dvec2(bh: &mut Bencher) {
bench_mul_dmat_dvector!(bh, 2, 2);
}
#[bench]
fn bench_mul_dmat_dvec3(bh: &mut Bencher) {
bench_mul_dmat_dvector!(bh, 3, 3);
}
#[bench]
fn bench_mul_dmat_dvec4(bh: &mut Bencher) {
bench_mul_dmat_dvector!(bh, 4, 4);
}
#[bench]
fn bench_mul_dmat_dvec5(bh: &mut Bencher) {
bench_mul_dmat_dvector!(bh, 5, 5);
}
#[bench]
fn bench_mul_dmat_dvec6(bh: &mut Bencher) {
bench_mul_dmat_dvector!(bh, 6, 6);
}

View File

@ -16,6 +16,10 @@ bench_binop!(_bench_mat2_mul_m, Matrix2<f32>, Matrix2<f32>, mul);
bench_binop!(_bench_mat3_mul_m, Matrix3<f32>, Matrix3<f32>, mul); bench_binop!(_bench_mat3_mul_m, Matrix3<f32>, Matrix3<f32>, mul);
bench_binop!(_bench_mat4_mul_m, Matrix4<f32>, Matrix4<f32>, mul); bench_binop!(_bench_mat4_mul_m, Matrix4<f32>, Matrix4<f32>, mul);
bench_binop_ref!(_bench_mat2_tr_mul_m, Matrix2<f32>, Matrix2<f32>, tr_mul);
bench_binop_ref!(_bench_mat3_tr_mul_m, Matrix3<f32>, Matrix3<f32>, tr_mul);
bench_binop_ref!(_bench_mat4_tr_mul_m, Matrix4<f32>, Matrix4<f32>, tr_mul);
bench_binop!(_bench_mat2_add_m, Matrix2<f32>, Matrix2<f32>, add); bench_binop!(_bench_mat2_add_m, Matrix2<f32>, Matrix2<f32>, add);
bench_binop!(_bench_mat3_add_m, Matrix3<f32>, Matrix3<f32>, add); bench_binop!(_bench_mat3_add_m, Matrix3<f32>, Matrix3<f32>, add);
bench_binop!(_bench_mat4_add_m, Matrix4<f32>, Matrix4<f32>, add); bench_binop!(_bench_mat4_add_m, Matrix4<f32>, Matrix4<f32>, add);
@ -28,6 +32,10 @@ bench_binop!(_bench_mat2_mul_v, Matrix2<f32>, Vector2<f32>, mul);
bench_binop!(_bench_mat3_mul_v, Matrix3<f32>, Vector3<f32>, mul); bench_binop!(_bench_mat3_mul_v, Matrix3<f32>, Vector3<f32>, mul);
bench_binop!(_bench_mat4_mul_v, Matrix4<f32>, Vector4<f32>, mul); bench_binop!(_bench_mat4_mul_v, Matrix4<f32>, Vector4<f32>, mul);
bench_binop_ref!(_bench_mat2_tr_mul_v, Matrix2<f32>, Vector2<f32>, tr_mul);
bench_binop_ref!(_bench_mat3_tr_mul_v, Matrix3<f32>, Vector3<f32>, tr_mul);
bench_binop_ref!(_bench_mat4_tr_mul_v, Matrix4<f32>, Vector4<f32>, tr_mul);
bench_binop!(_bench_mat2_mul_s, Matrix2<f32>, f32, mul); bench_binop!(_bench_mat2_mul_s, Matrix2<f32>, f32, mul);
bench_binop!(_bench_mat3_mul_s, Matrix3<f32>, f32, mul); bench_binop!(_bench_mat3_mul_s, Matrix3<f32>, f32, mul);
bench_binop!(_bench_mat4_mul_s, Matrix4<f32>, f32, mul); bench_binop!(_bench_mat4_mul_s, Matrix4<f32>, f32, mul);
@ -36,9 +44,9 @@ bench_binop!(_bench_mat2_div_s, Matrix2<f32>, f32, div);
bench_binop!(_bench_mat3_div_s, Matrix3<f32>, f32, div); bench_binop!(_bench_mat3_div_s, Matrix3<f32>, f32, div);
bench_binop!(_bench_mat4_div_s, Matrix4<f32>, f32, div); bench_binop!(_bench_mat4_div_s, Matrix4<f32>, f32, div);
bench_unop!(_bench_mat2_inv, Matrix2<f32>, inverse); bench_unop!(_bench_mat2_inv, Matrix2<f32>, try_inverse);
bench_unop!(_bench_mat3_inv, Matrix3<f32>, inverse); bench_unop!(_bench_mat3_inv, Matrix3<f32>, try_inverse);
bench_unop!(_bench_mat4_inv, Matrix4<f32>, inverse); bench_unop!(_bench_mat4_inv, Matrix4<f32>, try_inverse);
bench_unop!(_bench_mat2_transpose, Matrix2<f32>, transpose); bench_unop!(_bench_mat2_transpose, Matrix2<f32>, transpose);
bench_unop!(_bench_mat3_transpose, Matrix3<f32>, transpose); bench_unop!(_bench_mat3_transpose, Matrix3<f32>, transpose);

View File

@ -15,10 +15,14 @@ mod macros;
bench_binop!(_bench_quaternion_add_q, Quaternion<f32>, Quaternion<f32>, add); bench_binop!(_bench_quaternion_add_q, Quaternion<f32>, Quaternion<f32>, add);
bench_binop!(_bench_quaternion_sub_q, Quaternion<f32>, Quaternion<f32>, sub); bench_binop!(_bench_quaternion_sub_q, Quaternion<f32>, Quaternion<f32>, sub);
bench_binop!(_bench_quaternion_mul_q, Quaternion<f32>, Quaternion<f32>, mul); bench_binop!(_bench_quaternion_mul_q, Quaternion<f32>, Quaternion<f32>, mul);
// bench_binop!(_bench_quaternion_div_q, Quaternion<f32>, Quaternion<f32>, div)
bench_binop!(_bench_quaternion_mul_v, UnitQuaternion<f32>, Vector3<f32>, mul); bench_binop!(_bench_unit_quaternion_mul_v, UnitQuaternion<f32>, Vector3<f32>, mul);
bench_binop!(_bench_quaternion_mul_s, Quaternion<f32>, f32, mul); bench_binop!(_bench_quaternion_mul_s, Quaternion<f32>, f32, mul);
bench_binop!(_bench_quaternion_div_s, Quaternion<f32>, f32, div); bench_binop!(_bench_quaternion_div_s, Quaternion<f32>, f32, div);
bench_unop!(_bench_quaternion_inv, Quaternion<f32>, inverse);
bench_unop_self!(_bench_quaternion_conjugate, Quaternion<f32>, conjugate); bench_unop!(_bench_quaternion_inv, Quaternion<f32>, try_inverse);
bench_unop!(_bench_quaternion_normalize, Quaternion<f32>, normalize); bench_unop!(_bench_unit_quaternion_inv, UnitQuaternion<f32>, inverse);
// bench_unop_self!(_bench_quaternion_conjugate, Quaternion<f32>, conjugate);
// bench_unop!(_bench_quaternion_normalize, Quaternion<f32>, normalize);

View File

@ -1,119 +0,0 @@
#![feature(test)]
#[cfg(feature = "generic_sizes")]
extern crate typenum;
extern crate test;
extern crate rand;
extern crate nalgebra as na;
use rand::{IsaacRng, Rng};
use test::Bencher;
use na::{Vector2, Vector3, Vector4};
use std::ops::{Add, Sub, Mul, Div};
#[path="common/macros.rs"]
mod macros;
bench_binop!(_bench_vec2_add_v, Vector2<f32>, Vector2<f32>, add);
bench_binop!(_bench_vec3_add_v, Vector3<f32>, Vector3<f32>, add);
bench_binop!(_bench_vec4_add_v, Vector4<f32>, Vector4<f32>, add);
bench_binop!(_bench_vec2_sub_v, Vector2<f32>, Vector2<f32>, sub);
bench_binop!(_bench_vec3_sub_v, Vector3<f32>, Vector3<f32>, sub);
bench_binop!(_bench_vec4_sub_v, Vector4<f32>, Vector4<f32>, sub);
bench_binop!(_bench_vec2_mul_v, Vector2<f32>, Vector2<f32>, mul);
bench_binop!(_bench_vec3_mul_v, Vector3<f32>, Vector3<f32>, mul);
bench_binop!(_bench_vec4_mul_v, Vector4<f32>, Vector4<f32>, mul);
bench_binop!(_bench_vec2_div_v, Vector2<f32>, Vector2<f32>, div);
bench_binop!(_bench_vec3_div_v, Vector3<f32>, Vector3<f32>, div);
bench_binop!(_bench_vec4_div_v, Vector4<f32>, Vector4<f32>, div);
bench_binop!(_bench_vec2_add_s, Vector2<f32>, f32, add);
bench_binop!(_bench_vec3_add_s, Vector3<f32>, f32, add);
bench_binop!(_bench_vec4_add_s, Vector4<f32>, f32, add);
bench_binop!(_bench_vec2_sub_s, Vector2<f32>, f32, sub);
bench_binop!(_bench_vec3_sub_s, Vector3<f32>, f32, sub);
bench_binop!(_bench_vec4_sub_s, Vector4<f32>, f32, sub);
bench_binop!(_bench_vec2_mul_s, Vector2<f32>, f32, mul);
bench_binop!(_bench_vec3_mul_s, Vector3<f32>, f32, mul);
bench_binop!(_bench_vec4_mul_s, Vector4<f32>, f32, mul);
bench_binop!(_bench_vec2_div_s, Vector2<f32>, f32, div);
bench_binop!(_bench_vec3_div_s, Vector3<f32>, f32, div);
bench_binop!(_bench_vec4_div_s, Vector4<f32>, f32, div);
bench_binop_na!(_bench_vec2_dot, Vector2<f32>, Vector2<f32>, dot);
bench_binop_na!(_bench_vec3_dot, Vector3<f32>, Vector3<f32>, dot);
bench_binop_na!(_bench_vec4_dot, Vector4<f32>, Vector4<f32>, dot);
bench_binop_na!(_bench_vec3_cross, Vector3<f32>, Vector3<f32>, cross);
bench_unop!(_bench_vec2_norm, Vector2<f32>, norm);
bench_unop!(_bench_vec3_norm, Vector3<f32>, norm);
bench_unop!(_bench_vec4_norm, Vector4<f32>, norm);
bench_unop!(_bench_vec2_normalize, Vector2<f32>, normalize);
bench_unop!(_bench_vec3_normalize, Vector3<f32>, normalize);
bench_unop!(_bench_vec4_normalize, Vector4<f32>, normalize);
#[cfg(feature = "generic_sizes")]
mod bench_vecn {
extern crate test;
extern crate rand;
extern crate nalgebra as na;
use rand::{IsaacRng, Rng};
use test::Bencher;
use std::ops::{Add, Sub, Mul, Div};
use typenum::{U2, U3, U4};
use na::VectorN;
bench_binop!(_bench_vecn2_add_v, VectorN<f32, U2>, VectorN<f32, U2>, add);
bench_binop!(_bench_vecn3_add_v, VectorN<f32, U3>, VectorN<f32, U3>, add);
bench_binop!(_bench_vecn4_add_v, VectorN<f32, U4>, VectorN<f32, U4>, add);
bench_binop!(_bench_vecn2_sub_v, VectorN<f32, U2>, VectorN<f32, U2>, sub);
bench_binop!(_bench_vecn3_sub_v, VectorN<f32, U3>, VectorN<f32, U3>, sub);
bench_binop!(_bench_vecn4_sub_v, VectorN<f32, U4>, VectorN<f32, U4>, sub);
bench_binop!(_bench_vecn2_mul_v, VectorN<f32, U2>, VectorN<f32, U2>, mul);
bench_binop!(_bench_vecn3_mul_v, VectorN<f32, U3>, VectorN<f32, U3>, mul);
bench_binop!(_bench_vecn4_mul_v, VectorN<f32, U4>, VectorN<f32, U4>, mul);
bench_binop!(_bench_vecn2_div_v, VectorN<f32, U2>, VectorN<f32, U2>, div);
bench_binop!(_bench_vecn3_div_v, VectorN<f32, U3>, VectorN<f32, U3>, div);
bench_binop!(_bench_vecn4_div_v, VectorN<f32, U4>, VectorN<f32, U4>, div);
bench_binop!(_bench_vecn2_add_s, VectorN<f32, U2>, f32, add);
bench_binop!(_bench_vecn3_add_s, VectorN<f32, U3>, f32, add);
bench_binop!(_bench_vecn4_add_s, VectorN<f32, U4>, f32, add);
bench_binop!(_bench_vecn2_sub_s, VectorN<f32, U2>, f32, sub);
bench_binop!(_bench_vecn3_sub_s, VectorN<f32, U3>, f32, sub);
bench_binop!(_bench_vecn4_sub_s, VectorN<f32, U4>, f32, sub);
bench_binop!(_bench_vecn2_mul_s, VectorN<f32, U2>, f32, mul);
bench_binop!(_bench_vecn3_mul_s, VectorN<f32, U3>, f32, mul);
bench_binop!(_bench_vecn4_mul_s, VectorN<f32, U4>, f32, mul);
bench_binop!(_bench_vecn2_div_s, VectorN<f32, U2>, f32, div);
bench_binop!(_bench_vecn3_div_s, VectorN<f32, U3>, f32, div);
bench_binop!(_bench_vecn4_div_s, VectorN<f32, U4>, f32, div);
bench_binop_na!(_bench_vecn2_dot, VectorN<f32, U2>, VectorN<f32, U2>, dot);
bench_binop_na!(_bench_vecn3_dot, VectorN<f32, U3>, VectorN<f32, U3>, dot);
bench_binop_na!(_bench_vecn4_dot, VectorN<f32, U4>, VectorN<f32, U4>, dot);
bench_unop!(_bench_vecn2_norm, VectorN<f32, U2>, norm);
bench_unop!(_bench_vecn3_norm, VectorN<f32, U3>, norm);
bench_unop!(_bench_vecn4_norm, VectorN<f32, U4>, norm);
bench_unop!(_bench_vecn2_normalize, VectorN<f32, U2>, normalize);
bench_unop!(_bench_vecn3_normalize, VectorN<f32, U3>, normalize);
bench_unop!(_bench_vecn4_normalize, VectorN<f32, U4>, normalize);
}

43
benches/vector.rs Normal file
View File

@ -0,0 +1,43 @@
#![feature(test)]
extern crate test;
extern crate rand;
extern crate nalgebra as na;
use rand::{IsaacRng, Rng};
use test::Bencher;
use na::{Vector2, Vector3, Vector4};
use std::ops::{Add, Sub, Mul, Div};
#[path="common/macros.rs"]
mod macros;
bench_binop!(_bench_vec2_add_v, Vector2<f32>, Vector2<f32>, add);
bench_binop!(_bench_vec3_add_v, Vector3<f32>, Vector3<f32>, add);
bench_binop!(_bench_vec4_add_v, Vector4<f32>, Vector4<f32>, add);
bench_binop!(_bench_vec2_sub_v, Vector2<f32>, Vector2<f32>, sub);
bench_binop!(_bench_vec3_sub_v, Vector3<f32>, Vector3<f32>, sub);
bench_binop!(_bench_vec4_sub_v, Vector4<f32>, Vector4<f32>, sub);
bench_binop!(_bench_vec2_mul_s, Vector2<f32>, f32, mul);
bench_binop!(_bench_vec3_mul_s, Vector3<f32>, f32, mul);
bench_binop!(_bench_vec4_mul_s, Vector4<f32>, f32, mul);
bench_binop!(_bench_vec2_div_s, Vector2<f32>, f32, div);
bench_binop!(_bench_vec3_div_s, Vector3<f32>, f32, div);
bench_binop!(_bench_vec4_div_s, Vector4<f32>, f32, div);
bench_binop_ref!(_bench_vec2_dot, Vector2<f32>, Vector2<f32>, dot);
bench_binop_ref!(_bench_vec3_dot, Vector3<f32>, Vector3<f32>, dot);
bench_binop_ref!(_bench_vec4_dot, Vector4<f32>, Vector4<f32>, dot);
bench_binop_ref!(_bench_vec3_cross, Vector3<f32>, Vector3<f32>, cross);
bench_unop!(_bench_vec2_norm, Vector2<f32>, norm);
bench_unop!(_bench_vec3_norm, Vector3<f32>, norm);
bench_unop!(_bench_vec4_norm, Vector4<f32>, norm);
bench_unop!(_bench_vec2_normalize, Vector2<f32>, normalize);
bench_unop!(_bench_vec3_normalize, Vector3<f32>, normalize);
bench_unop!(_bench_vec4_normalize, Vector4<f32>, normalize);

View File

@ -0,0 +1,66 @@
extern crate alga;
extern crate nalgebra as na;
use alga::general::Real;
use alga::linear::FiniteDimInnerSpace;
use na::{Unit, ColumnVector, OwnedColumnVector, Vector2, Vector3};
use na::storage::Storage;
use na::dimension::{DimName, U1};
/// Reflects a vector wrt. the hyperplane with normal `plane_normal`.
fn reflect_wrt_hyperplane_with_algebraic_genericity<V>(plane_normal: &Unit<V>, vector: &V) -> V
where V: FiniteDimInnerSpace + Copy {
let n = plane_normal.as_ref(); // Get the underlying vector of type `V`.
*vector - *n * (n.dot(vector) * na::convert(2.0))
}
/// Reflects a vector wrt. the hyperplane with normal `plane_normal`.
fn reflect_wrt_hyperplane_with_structural_genericity<N, D, S>(plane_normal: &Unit<ColumnVector<N, D, S>>,
vector: &ColumnVector<N, D, S>)
-> OwnedColumnVector<N, D, S::Alloc>
where N: Real,
D: DimName,
S: Storage<N, D, U1> {
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`.
fn reflect_wrt_hyperplane2<N>(plane_normal: &Unit<Vector2<N>>,
vector: &Vector2<N>)
-> Vector2<N>
where N: Real {
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`.
/// /!\ This is an exact replicate of `reflect_wrt_hyperplane2, but for 3D.
fn reflect_wrt_hyperplane3<N>(plane_normal: &Unit<Vector3<N>>,
vector: &Vector3<N>)
-> Vector3<N>
where N: Real {
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.
let v2 = Vector2::new(1.0, 2.0); // 2D vector to be reflected.
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.
assert_eq!(reflect_wrt_hyperplane_with_algebraic_genericity(&plane2, &v2).y, -2.0);
assert_eq!(reflect_wrt_hyperplane_with_algebraic_genericity(&plane3, &v3).y, -2.0);
assert_eq!(reflect_wrt_hyperplane_with_structural_genericity(&plane2, &v2).y, -2.0);
assert_eq!(reflect_wrt_hyperplane_with_structural_genericity(&plane3, &v3).y, -2.0);
// 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);
}

View File

@ -0,0 +1,45 @@
#[macro_use]
extern crate approx;
extern crate nalgebra as na;
use std::f32;
use na::{Vector2, Point2, Isometry2};
fn use_dedicated_types() {
let iso = Isometry2::new(Vector2::new(1.0, 1.0), f32::consts::PI);
let pt = Point2::new(1.0, 0.0);
let vec = Vector2::x();
let transformed_pt = iso * pt;
let transformed_vec = iso * vec;
assert_relative_eq!(transformed_pt, Point2::new(0.0, 1.0));
assert_relative_eq!(transformed_vec, Vector2::new(-1.0, 0.0));
}
fn use_homogeneous_coordinates() {
let iso = Isometry2::new(Vector2::new(1.0, 1.0), f32::consts::PI);
let pt = Point2::new(1.0, 0.0);
let vec = Vector2::x();
// Compute using homogeneous coordinates.
let hom_iso = iso.to_homogeneous();
let hom_pt = pt.to_homogeneous();
let hom_vec = vec.to_homogeneous();
let hom_transformed_pt = hom_iso * hom_pt;
let hom_transformed_vec = hom_iso * hom_vec;
// Convert back to the cartesian coordinates.
let transformed_pt = Point2::from_homogeneous(hom_transformed_pt).unwrap();
let transformed_vec = Vector2::from_homogeneous(hom_transformed_vec).unwrap();
assert_relative_eq!(transformed_pt, Point2::new(0.0, 1.0));
assert_relative_eq!(transformed_vec, Vector2::new(-1.0, 0.0));
}
fn main() {
use_dedicated_types();
use_homogeneous_coordinates();
}

42
examples/identity.rs Normal file
View File

@ -0,0 +1,42 @@
extern crate alga;
extern crate nalgebra as na;
use alga::linear::Transformation;
use na::{Id, Vector3, Point3, Isometry3};
/*
* Applies `n` times the transformation `t` to the vector `v` and sum each
* intermediate value.
*/
fn complicated_algorithm<T>(v: &Vector3<f32>, t: &T, n: usize) -> Vector3<f32>
where T: Transformation<Point3<f32>> {
let mut result = *v;
// Do lots of operations involving t.
for _ in 0 .. n {
result = v + t.transform_vector(&result);
}
result
}
/*
* The two following calls are equivalent in term of result.
*/
fn main() {
let v = Vector3::new(1.0, 2.0, 3.0);
// The specialization generated by the compiler will do vector additions only.
let result1 = complicated_algorithm(&v, &Id::new(), 100000);
// The specialization generated by the compiler will also include matrix multiplications.
let iso = Isometry3::identity();
let result2 = complicated_algorithm(&v, &iso, 100000);
// They both return the same result.
assert!(result1 == Vector3::new(100001.0, 200002.0, 300003.0));
assert!(result2 == Vector3::new(100001.0, 200002.0, 300003.0));
}

View File

@ -0,0 +1,62 @@
extern crate nalgebra as na;
use na::{Vector2, RowVector3, Matrix2x3, DMatrix};
fn main() {
// All the following matrices are equal but constructed in different ways.
let m = Matrix2x3::new(1.1, 1.2, 1.3,
2.1, 2.2, 2.3);
let m1 = Matrix2x3::from_rows(&[
RowVector3::new(1.1, 1.2, 1.3),
RowVector3::new(2.1, 2.2, 2.3)
]);
let m2 = Matrix2x3::from_columns(&[
Vector2::new(1.1, 2.1),
Vector2::new(1.2, 2.2),
Vector2::new(1.3, 2.3)
]);
let m3 = Matrix2x3::from_row_slice(&[
1.1, 1.2, 1.3,
2.1, 2.2, 2.3
]);
let m4 = Matrix2x3::from_column_slice(&[
1.1, 2.1,
1.2, 2.2,
1.3, 2.3
]);
let m5 = Matrix2x3::from_fn(|r, c| (r + 1) as f32 + (c + 1) as f32 / 10.0);
let m6 = Matrix2x3::from_iterator([ 1.1f32, 2.1, 1.2, 2.2, 1.3, 2.3 ].iter().cloned());
assert_eq!(m, m1); assert_eq!(m, m2); assert_eq!(m, m3);
assert_eq!(m, m4); assert_eq!(m, m5); assert_eq!(m, m6);
// All the following matrices are equal but constructed in different ways.
// This time, we used a dynamically-sized matrix to show the extra arguments
// for the matrix shape.
let dm = DMatrix::from_row_slice(4, 3, &[
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 0.0, 0.0
]);
let dm1 = DMatrix::from_diagonal_element(4, 3, 1.0);
let dm2 = DMatrix::identity(4, 3);
let dm3 = DMatrix::from_fn(4, 3, |r, c| if r == c { 1.0 } else { 0.0 });
let dm4 = DMatrix::from_iterator(4, 3, [
// Components listed column-by-column.
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0
].iter().cloned());
assert_eq!(dm, dm1); assert_eq!(dm, dm2);
assert_eq!(dm, dm3); assert_eq!(dm, dm4);
}

28
examples/mvp.rs Normal file
View File

@ -0,0 +1,28 @@
#![allow(unused_variables)]
extern crate nalgebra as na;
use na::{Vector3, Point3, Isometry3, Perspective3};
fn main() {
// Our object is translated along the x axis.
let model = Isometry3::new(Vector3::x(), na::zero());
// Our camera looks toward the point (1.0, 0.0, 0.0).
// It is located at (0.0, 0.0, 1.0).
let eye = Point3::new(0.0, 0.0, 1.0);
let target = Point3::new(1.0, 0.0, 0.0);
let view = Isometry3::look_at_rh(&eye, &target, &Vector3::y());
// A perspective projection.
let projection = Perspective3::new(16.0 / 9.0, 3.14 / 2.0, 1.0, 1000.0);
// The combination of the model with the view is still an isometry.
let model_view = model * view;
// Convert everything to a `Matrix4` so that they can be combined.
let mat_model_view = model_view.to_homogeneous();
// Combine everything.
let model_view_projection = projection.as_matrix() * mat_model_view;
}

35
examples/raw_pointer.rs Normal file
View File

@ -0,0 +1,35 @@
extern crate nalgebra as na;
use na::{Vector3, Point3, Matrix3};
fn main() {
let v = Vector3::new(1.0f32, 0.0, 1.0);
let p = Point3::new(1.0f32, 0.0, 1.0);
let m = na::one::<Matrix3<f32>>();
// Convert to arrays.
let v_array = v.as_slice();
let p_array = p.coords.as_slice();
let m_array = m.as_slice();
// Get data pointers.
let v_pointer = v_array.as_ptr();
let p_pointer = p_array.as_ptr();
let m_pointer = m_array.as_ptr();
/* Then pass the raw pointers to some graphics API. */
unsafe {
assert_eq!(*v_pointer, 1.0);
assert_eq!(*v_pointer.offset(1), 0.0);
assert_eq!(*v_pointer.offset(2), 1.0);
assert_eq!(*p_pointer, 1.0);
assert_eq!(*p_pointer.offset(1), 0.0);
assert_eq!(*p_pointer.offset(2), 1.0);
assert_eq!(*m_pointer, 1.0);
assert_eq!(*m_pointer.offset(4), 1.0);
assert_eq!(*m_pointer.offset(8), 1.0);
}
}

View File

@ -0,0 +1,33 @@
extern crate alga;
extern crate nalgebra as na;
use alga::general::{RingCommutative, Real};
use na::{Vector3, Scalar};
fn print_vector<N: Scalar>(m: &Vector3<N>) {
println!("{:?}", m)
}
fn print_squared_norm<N: Scalar + RingCommutative>(v: &Vector3<N>) {
// NOTE: alternatively, nalgebra already defines `v.squared_norm()`.
let sqnorm = v.dot(v);
println!("{:?}", sqnorm);
}
fn print_norm<N: Real>(v: &Vector3<N>) {
// NOTE: alternatively, nalgebra already defines `v.norm()`.
let norm = v.dot(v).sqrt();
// The Real bound implies that N is Display so we can
// use "{}" instead of "{:?}" for the format string.
println!("{}", norm)
}
fn main() {
let v1 = Vector3::new(1, 2, 3);
let v2 = Vector3::new(1.0, 2.0, 3.0);
print_vector(&v1);
print_squared_norm(&v1);
print_norm(&v2);
}

View File

@ -0,0 +1,24 @@
#![allow(unused_variables)]
extern crate nalgebra as na;
use na::{Point2, Point3, Perspective3, Unit};
fn main() {
let projection = Perspective3::new(800.0 / 600.0, 3.14 / 2.0, 1.0, 1000.0);
let screen_point = Point2::new(10.0f32, 20.0);
// Compute two points in clip-space.
// "ndc" = normalized device coordinates.
let near_ndc_point = Point3::new(screen_point.x / 800.0, screen_point.y / 600.0, -1.0);
let far_ndc_point = Point3::new(screen_point.x / 800.0, screen_point.y / 600.0, 1.0);
// Unproject them to view-space.
let near_view_point = projection.unproject_point(&near_ndc_point);
let far_view_point = projection.unproject_point(&far_ndc_point);
// Compute the view-space line parameters.
let line_location = near_view_point;
let line_direction = Unit::new_normalize(far_view_point - near_view_point);
}

View File

@ -0,0 +1,23 @@
extern crate nalgebra as na;
use na::{Vector2, Isometry2, Similarity2};
fn main() {
// Isometry -> Similarity conversion always succeeds.
let iso = Isometry2::new(Vector2::new(1.0f32, 2.0), na::zero());
let _: Similarity2<f32> = na::convert(iso);
// Similarity -> Isometry conversion fails if the scaling factor is not 1.0.
let sim_without_scaling = Similarity2::new(Vector2::new(1.0f32, 2.0), 3.14, 1.0);
let sim_with_scaling = Similarity2::new(Vector2::new(1.0f32, 2.0), 3.14, 2.0);
let iso_success: Option<Isometry2<f32>> = na::try_convert(sim_without_scaling);
let iso_fail: Option<Isometry2<f32>> = na::try_convert(sim_with_scaling);
assert!(iso_success.is_some());
assert!(iso_fail.is_none());
// Similarity -> Isometry conversion can be forced at your own risks.
let iso_forced: Isometry2<f32> = unsafe { na::convert_unchecked(sim_with_scaling) };
assert_eq!(iso_success.unwrap(), iso_forced);
}

View File

@ -0,0 +1,39 @@
#[macro_use]
extern crate approx;
extern crate alga;
extern crate nalgebra as na;
use alga::linear::Transformation;
use na::{Vector3, Point3, Matrix4};
fn main() {
// Create a uniform scaling matrix with scaling factor 2.
let mut m = Matrix4::new_scaling(2.0);
assert_eq!(m.transform_vector(&Vector3::x()), Vector3::x() * 2.0);
assert_eq!(m.transform_vector(&Vector3::y()), Vector3::y() * 2.0);
assert_eq!(m.transform_vector(&Vector3::z()), Vector3::z() * 2.0);
// Append a nonuniform scaling in-place.
m.append_nonuniform_scaling_mut(&Vector3::new(1.0, 2.0, 3.0));
assert_eq!(m.transform_vector(&Vector3::x()), Vector3::x() * 2.0);
assert_eq!(m.transform_vector(&Vector3::y()), Vector3::y() * 4.0);
assert_eq!(m.transform_vector(&Vector3::z()), Vector3::z() * 6.0);
// Append a translation out-of-place.
let m2 = m.append_translation(&Vector3::new(42.0, 0.0, 0.0));
assert_eq!(m2.transform_point(&Point3::new(1.0, 1.0, 1.0)), Point3::new(42.0 + 2.0, 4.0, 6.0));
// Create rotation.
let rot = Matrix4::from_scaled_axis(&Vector3::x() * 3.14);
let rot_then_m = m * rot; // Right-multiplication is equivalent to prepending `rot` to `m`.
let m_then_rot = rot * m; // Left-multiplication is equivalent to appending `rot` to `m`.
let pt = Point3::new(1.0, 2.0, 3.0);
assert_relative_eq!(m.transform_point(&rot.transform_point(&pt)), rot_then_m.transform_point(&pt));
assert_relative_eq!(rot.transform_point(&m.transform_point(&pt)), m_then_rot.transform_point(&pt));
}

View File

@ -0,0 +1,20 @@
#[macro_use]
extern crate approx;
extern crate nalgebra as na;
use std::f32;
use na::{Vector2, Point2, Isometry2};
fn main() {
let t = Isometry2::new(Vector2::new(1.0, 1.0), f32::consts::PI);
let p = Point2::new(1.0, 0.0); // Will be affected by te rotation and the translation.
let v = Vector2::x(); // Will *not* be affected by the translation.
assert_relative_eq!(t * p, Point2::new(-1.0 + 1.0, 1.0));
// ^^^^ │ ^^^^^^^^
// rotated │ translated
assert_relative_eq!(t * v, Vector2::new(-1.0, 0.0));
// ^^^^^
// rotated only
}

View File

@ -0,0 +1,27 @@
extern crate alga;
extern crate nalgebra as na;
use alga::linear::Transformation;
use na::{Vector3, Vector4, Point3, Matrix4};
fn main() {
let mut m = Matrix4::new_rotation_wrt_point(Vector3::x() * 1.57, Point3::new(1.0, 2.0, 1.0));
m.append_scaling_mut(2.0);
let point1 = Point3::new(2.0, 3.0, 4.0);
let homogeneous_point2 = Vector4::new(2.0, 3.0, 4.0, 1.0);
// First option: use the dedicated `.transform_point(...)` method.
let transformed_point1 = m.transform_point(&point1);
// Second option: use the homogeneous coordinates of the point.
let transformed_homogeneous_point2 = m * homogeneous_point2;
// Recover the 3D point from its 4D homogeneous coordinates.
let transformed_point2 = Point3::from_homogeneous(transformed_homogeneous_point2);
// Check that transforming the 3D point with the `.transform_point` method is
// indeed equivalent to multiplying its 4D homogeneous coordinates by the 4x4
// matrix.
assert_eq!(transformed_point1, transformed_point2.unwrap());
}

View File

@ -0,0 +1,25 @@
extern crate nalgebra as na;
use na::{Vector3, Isometry3};
fn main() {
let iso = Isometry3::new(Vector3::new(1.0f32, 0.0, 1.0), na::zero());
// Compute the homogeneous coordinates first.
let iso_matrix = iso.to_homogeneous();
let iso_array = iso_matrix.as_slice();
let iso_pointer = iso_array.as_ptr();
/* Then pass the raw pointer to some graphics API. */
unsafe {
assert_eq!(*iso_pointer, 1.0);
assert_eq!(*iso_pointer.offset(5), 1.0);
assert_eq!(*iso_pointer.offset(10), 1.0);
assert_eq!(*iso_pointer.offset(15), 1.0);
assert_eq!(*iso_pointer.offset(12), 1.0);
assert_eq!(*iso_pointer.offset(13), 0.0);
assert_eq!(*iso_pointer.offset(14), 1.0);
}
}

30
examples/unit_wrapper.rs Normal file
View File

@ -0,0 +1,30 @@
extern crate nalgebra as na;
use na::{Unit, Vector3};
fn length_on_direction_with_unit(v: &Vector3<f32>, dir: &Unit<Vector3<f32>>) -> f32 {
// No need to normalize `dir`: we know that it is non-zero and normalized.
v.dot(dir.as_ref())
}
fn length_on_direction_without_unit(v: &Vector3<f32>, dir: &Vector3<f32>) -> f32 {
// Obligatory normalization of the direction vector (and test, for robustness).
if let Some(unit_dir) = dir.try_normalize(1.0e-6) {
v.dot(&unit_dir)
}
else {
// Normalization failed because the norm was too small.
panic!("Invalid input direction.")
}
}
fn main() {
let v = Vector3::new(1.0, 2.0, 3.0);
let l1 = length_on_direction_with_unit(&v, &Vector3::y_axis());
let l2 = length_on_direction_without_unit(&v, &Vector3::y());
assert_eq!(l1, l2)
}

158
src/core/alias.rs Normal file
View File

@ -0,0 +1,158 @@
use core::Matrix;
use core::dimension::{Dynamic, U1, U2, U3, U4, U5, U6};
use core::matrix_array::MatrixArray;
use core::matrix_vec::MatrixVec;
/*
*
*
* Column-major matrices.
*
*
*/
/// A dynamically sized column-major matrix.
pub type DMatrix<N> = Matrix<N, Dynamic, Dynamic, MatrixVec<N, Dynamic, Dynamic>>;
/// A staticaly sized column-major matrix with `R` rows and `C` columns.
pub type MatrixNM<N, R, C> = Matrix<N, R, C, MatrixArray<N, R, C>>;
/// A staticaly sized column-major square matrix with `D` rows and columns.
pub type MatrixN<N, D> = MatrixNM<N, D, D>;
/// A stack-allocated, column-major, 1x1 square matrix.
pub type Matrix1<N> = MatrixN<N, U1>;
/// A stack-allocated, column-major, 2x2 square matrix.
pub type Matrix2<N> = MatrixN<N, U2>;
/// A stack-allocated, column-major, 3x3 square matrix.
pub type Matrix3<N> = MatrixN<N, U3>;
/// A stack-allocated, column-major, 4x4 square matrix.
pub type Matrix4<N> = MatrixN<N, U4>;
/// A stack-allocated, column-major, 5x5 square matrix.
pub type Matrix5<N> = MatrixN<N, U5>;
/// A stack-allocated, column-major, 6x6 square matrix.
pub type Matrix6<N> = MatrixN<N, U6>;
/// A stack-allocated, column-major, 1x2 square matrix.
pub type Matrix1x2<N> = MatrixNM<N, U1, U2>;
/// A stack-allocated, column-major, 1x3 square matrix.
pub type Matrix1x3<N> = MatrixNM<N, U1, U3>;
/// A stack-allocated, column-major, 1x4 square matrix.
pub type Matrix1x4<N> = MatrixNM<N, U1, U4>;
/// A stack-allocated, column-major, 1x5 square matrix.
pub type Matrix1x5<N> = MatrixNM<N, U1, U5>;
/// A stack-allocated, column-major, 1x6 square matrix.
pub type Matrix1x6<N> = MatrixNM<N, U1, U6>;
/// A stack-allocated, column-major, 2x3 square matrix.
pub type Matrix2x3<N> = MatrixNM<N, U2, U3>;
/// A stack-allocated, column-major, 2x4 square matrix.
pub type Matrix2x4<N> = MatrixNM<N, U2, U4>;
/// A stack-allocated, column-major, 2x5 square matrix.
pub type Matrix2x5<N> = MatrixNM<N, U2, U5>;
/// A stack-allocated, column-major, 2x6 square matrix.
pub type Matrix2x6<N> = MatrixNM<N, U2, U6>;
/// A stack-allocated, column-major, 3x4 square matrix.
pub type Matrix3x4<N> = MatrixNM<N, U3, U4>;
/// A stack-allocated, column-major, 3x5 square matrix.
pub type Matrix3x5<N> = MatrixNM<N, U3, U5>;
/// A stack-allocated, column-major, 3x6 square matrix.
pub type Matrix3x6<N> = MatrixNM<N, U3, U6>;
/// A stack-allocated, column-major, 4x5 square matrix.
pub type Matrix4x5<N> = MatrixNM<N, U4, U5>;
/// A stack-allocated, column-major, 4x6 square matrix.
pub type Matrix4x6<N> = MatrixNM<N, U4, U6>;
/// A stack-allocated, column-major, 5x6 square matrix.
pub type Matrix5x6<N> = MatrixNM<N, U5, U6>;
/// A stack-allocated, column-major, 2x1 square matrix.
pub type Matrix2x1<N> = MatrixNM<N, U2, U1>;
/// A stack-allocated, column-major, 3x1 square matrix.
pub type Matrix3x1<N> = MatrixNM<N, U3, U1>;
/// A stack-allocated, column-major, 4x1 square matrix.
pub type Matrix4x1<N> = MatrixNM<N, U4, U1>;
/// A stack-allocated, column-major, 5x1 square matrix.
pub type Matrix5x1<N> = MatrixNM<N, U5, U1>;
/// A stack-allocated, column-major, 6x1 square matrix.
pub type Matrix6x1<N> = MatrixNM<N, U6, U1>;
/// A stack-allocated, column-major, 3x2 square matrix.
pub type Matrix3x2<N> = MatrixNM<N, U3, U2>;
/// A stack-allocated, column-major, 4x2 square matrix.
pub type Matrix4x2<N> = MatrixNM<N, U4, U2>;
/// A stack-allocated, column-major, 5x2 square matrix.
pub type Matrix5x2<N> = MatrixNM<N, U5, U2>;
/// A stack-allocated, column-major, 6x2 square matrix.
pub type Matrix6x2<N> = MatrixNM<N, U6, U2>;
/// A stack-allocated, column-major, 4x3 square matrix.
pub type Matrix4x3<N> = MatrixNM<N, U4, U3>;
/// A stack-allocated, column-major, 5x3 square matrix.
pub type Matrix5x3<N> = MatrixNM<N, U5, U3>;
/// A stack-allocated, column-major, 6x3 square matrix.
pub type Matrix6x3<N> = MatrixNM<N, U6, U3>;
/// A stack-allocated, column-major, 5x4 square matrix.
pub type Matrix5x4<N> = MatrixNM<N, U5, U4>;
/// A stack-allocated, column-major, 6x4 square matrix.
pub type Matrix6x4<N> = MatrixNM<N, U6, U4>;
/// A stack-allocated, column-major, 6x5 square matrix.
pub type Matrix6x5<N> = MatrixNM<N, U6, U5>;
/*
*
*
* Column vectors.
*
*
*/
/// A dynamically sized column vector.
pub type DVector<N> = Matrix<N, Dynamic, U1, MatrixVec<N, Dynamic, U1>>;
/// A statically sized D-dimensional column vector.
pub type VectorN<N, D> = MatrixNM<N, D, U1>;
/// A stack-allocated, 1-dimensional column vector.
pub type Vector1<N> = VectorN<N, U1>;
/// A stack-allocated, 2-dimensional column vector.
pub type Vector2<N> = VectorN<N, U2>;
/// A stack-allocated, 3-dimensional column vector.
pub type Vector3<N> = VectorN<N, U3>;
/// A stack-allocated, 4-dimensional column vector.
pub type Vector4<N> = VectorN<N, U4>;
/// A stack-allocated, 5-dimensional column vector.
pub type Vector5<N> = VectorN<N, U5>;
/// A stack-allocated, 6-dimensional column vector.
pub type Vector6<N> = VectorN<N, U6>;
/*
*
*
* Row vectors.
*
*
*/
/// A dynamically sized row vector.
pub type RowDVector<N> = Matrix<N, U1, Dynamic, MatrixVec<N, U1, Dynamic>>;
/// A statically sized D-dimensional row vector.
pub type RowVectorN<N, D> = MatrixNM<N, U1, D>;
/// A stack-allocated, 1-dimensional row vector.
pub type RowVector1<N> = RowVectorN<N, U1>;
/// A stack-allocated, 2-dimensional row vector.
pub type RowVector2<N> = RowVectorN<N, U2>;
/// A stack-allocated, 3-dimensional row vector.
pub type RowVector3<N> = RowVectorN<N, U3>;
/// A stack-allocated, 4-dimensional row vector.
pub type RowVector4<N> = RowVectorN<N, U4>;
/// A stack-allocated, 5-dimensional row vector.
pub type RowVector5<N> = RowVectorN<N, U5>;
/// A stack-allocated, 6-dimensional row vector.
pub type RowVector6<N> = RowVectorN<N, U6>;

89
src/core/allocator.rs Normal file
View File

@ -0,0 +1,89 @@
//! Abstract definition of a matrix data storage allocator.
use std::any::Any;
use core::Scalar;
use core::constraint::{SameNumberOfRows, SameNumberOfColumns, ShapeConstraint};
use core::dimension::{Dim, U1};
use core::storage::{Storage, OwnedStorage};
/// A matrix allocator of a memory buffer that may contain `R::to_usize() * C::to_usize()`
/// elements of type `N`.
///
/// An allocator is said to be:
/// static: if `R` and `C` both implement `DimName`.
/// dynamic: if either one (or both) of `R` or `C` is equal to `Dynamic`.
///
/// Every allocator must be both static and dynamic. Though not all implementations may share the
/// same `Buffer` type.
pub trait Allocator<N: Scalar, R: Dim, C: Dim>: Any + Sized {
/// The type of buffer this allocator can instanciate.
type Buffer: OwnedStorage<N, R, C, Alloc = Self>;
/// Allocates a buffer with the given number of rows and columns without initializing its content.
unsafe fn allocate_uninitialized(nrows: R, ncols: C) -> Self::Buffer;
/// Allocates a buffer initialized with the content of the given iterator.
fn allocate_from_iterator<I: IntoIterator<Item = N>>(nrows: R, ncols: C, iter: I) -> Self::Buffer;
}
/// A matrix data allocator dedicated to the given owned matrix storage.
pub trait OwnedAllocator<N: Scalar, R: Dim, C: Dim, S: OwnedStorage<N, R, C, Alloc = Self>>:
Allocator<N, R, C, Buffer = S> {
}
impl<N, R, C, T, S> OwnedAllocator<N, R, C, S> for T
where N: Scalar, R: Dim, C: Dim,
T: Allocator<N, R, C, Buffer = S>,
S: OwnedStorage<N, R, C, Alloc = T> {
}
/// The number of rows of the result of a componentwise operation on two matrices.
pub type SameShapeR<R1, R2> = <ShapeConstraint as SameNumberOfRows<R1, R2>>::Representative;
/// The number of columns of the result of a componentwise operation on two matrices.
pub type SameShapeC<C1, C2> = <ShapeConstraint as SameNumberOfColumns<C1, C2>>::Representative;
// FIXME: Bad name.
/// Restricts the given number of rows and columns to be respectively the same. Can only be used
/// when `Self = SA::Alloc`.
pub trait SameShapeAllocator<N, R1, C1, R2, C2, SA>:
Allocator<N, R1, C1> +
Allocator<N, SameShapeR<R1, R2>, SameShapeC<C1, C2>>
where R1: Dim, R2: Dim, C1: Dim, C2: Dim,
N: Scalar,
SA: Storage<N, R1, C1, Alloc = Self>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
}
impl<N, R1, R2, C1, C2, SA> SameShapeAllocator<N, R1, C1, R2, C2, SA> for SA::Alloc
where R1: Dim, R2: Dim, C1: Dim, C2: Dim,
N: Scalar,
SA: Storage<N, R1, C1>,
SA::Alloc:
Allocator<N, R1, C1> +
Allocator<N, SameShapeR<R1, R2>, SameShapeC<C1, C2>>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
}
// XXX: Bad name.
/// Restricts the given number of rows to be equal. Can only be used when `Self = SA::Alloc`.
pub trait SameShapeColumnVectorAllocator<N, R1, R2, SA>:
Allocator<N, R1, U1> +
Allocator<N, SameShapeR<R1, R2>, U1> +
SameShapeAllocator<N, R1, U1, R2, U1, SA>
where R1: Dim, R2: Dim,
N: Scalar,
SA: Storage<N, R1, U1, Alloc = Self>,
ShapeConstraint: SameNumberOfRows<R1, R2> {
}
impl<N, R1, R2, SA> SameShapeColumnVectorAllocator<N, R1, R2, SA> for SA::Alloc
where R1: Dim, R2: Dim,
N: Scalar,
SA: Storage<N, R1, U1>,
SA::Alloc:
Allocator<N, R1, U1> +
Allocator<N, SameShapeR<R1, R2>, U1>,
ShapeConstraint: SameNumberOfRows<R1, R2> {
}

376
src/core/cg.rs Normal file
View File

@ -0,0 +1,376 @@
/*
*
* Computer-graphics specific implementations.
* Currently, it is mostly implemented for homogeneous matrices in 2- and 3-space.
*
*/
use num::One;
use core::{Scalar, SquareMatrix, OwnedSquareMatrix, ColumnVector, Unit};
use core::dimension::{DimName, DimNameSub, DimNameDiff, U1, U2, U3, U4};
use core::storage::{Storage, StorageMut, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, OrthographicBase, PerspectiveBase, IsometryBase, OwnedRotation, OwnedPoint};
use alga::general::{Real, Field};
use alga::linear::Transformation;
impl<N, D: DimName, S> SquareMatrix<N, D, S>
where N: Scalar + Field,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
/// Creates a new homogeneous matrix that applies the same scaling factor on each dimension.
#[inline]
pub fn new_scaling(scaling: N) -> Self {
let mut res = Self::from_diagonal_element(scaling);
res[(D::dim() - 1, D::dim() - 1)] = N::one();
res
}
/// Creates a new homogeneous matrix that applies a distinct scaling factor for each dimension.
#[inline]
pub fn new_nonuniform_scaling<SB>(scaling: &ColumnVector<N, DimNameDiff<D, U1>, SB>) -> Self
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1> {
let mut res = Self::one();
for i in 0 .. scaling.len() {
res[(i, i)] = scaling[i];
}
res
}
/// Creates a new homogeneous matrix that applies a pure translation.
#[inline]
pub fn new_translation<SB>(translation: &ColumnVector<N, DimNameDiff<D, U1>, SB>) -> Self
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, DimNameDiff<D, U1>, U1> {
let mut res = Self::one();
res.fixed_slice_mut::<DimNameDiff<D, U1>, U1>(0, D::dim() - 1).copy_from(translation);
res
}
}
impl<N, S> SquareMatrix<N, U3, S>
where N: Real,
S: OwnedStorage<N, U3, U3>,
S::Alloc: OwnedAllocator<N, U3, U3, S> {
/// Builds a 2 dimensional homogeneous rotation matrix from an angle in radian.
#[inline]
pub fn new_rotation(angle: N) -> Self
where S::Alloc: Allocator<N, U2, U2> {
OwnedRotation::<N, U2, S::Alloc>::new(angle).to_homogeneous()
}
}
impl<N, S> SquareMatrix<N, U4, S>
where N: Real,
S: OwnedStorage<N, U4, U4>,
S::Alloc: OwnedAllocator<N, U4, U4, S> {
/// Builds a 3D homogeneous rotation matrix from an axis and an angle (multiplied together).
///
/// Returns the identity matrix if the given argument is zero.
#[inline]
pub fn new_rotation<SB>(axisangle: ColumnVector<N, U3, SB>) -> Self
where SB: Storage<N, U3, U1>,
S::Alloc: Allocator<N, U3, U3> {
OwnedRotation::<N, U3, S::Alloc>::new(axisangle).to_homogeneous()
}
/// Builds a 3D homogeneous rotation matrix from an axis and an angle (multiplied together).
///
/// Returns the identity matrix if the given argument is zero.
#[inline]
pub fn new_rotation_wrt_point<SB>(axisangle: ColumnVector<N, U3, SB>, pt: OwnedPoint<N, U3, S::Alloc>) -> Self
where SB: Storage<N, U3, U1>,
S::Alloc: Allocator<N, U3, U3> +
Allocator<N, U3, U1> +
Allocator<N, U1, U3> {
let rot = OwnedRotation::<N, U3, S::Alloc>::from_scaled_axis(axisangle);
IsometryBase::rotation_wrt_point(rot, pt).to_homogeneous()
}
/// Builds a 3D homogeneous rotation matrix from an axis and an angle (multiplied together).
///
/// Returns the identity matrix if the given argument is zero.
/// This is identical to `Self::new_rotation`.
#[inline]
pub fn from_scaled_axis<SB>(axisangle: ColumnVector<N, U3, SB>) -> Self
where SB: Storage<N, U3, U1>,
S::Alloc: Allocator<N, U3, U3> {
OwnedRotation::<N, U3, S::Alloc>::from_scaled_axis(axisangle).to_homogeneous()
}
/// Creates a new rotation from Euler angles.
///
/// The primitive rotations are applied in order: 1 roll 2 pitch 3 yaw.
pub fn from_euler_angles(roll: N, pitch: N, yaw: N) -> Self
where S::Alloc: Allocator<N, U3, U3> {
OwnedRotation::<N, U3, S::Alloc>::from_euler_angles(roll, pitch, yaw).to_homogeneous()
}
/// Builds a 3D homogeneous rotation matrix from an axis and a rotation angle.
pub fn from_axis_angle<SB>(axis: &Unit<ColumnVector<N, U3, SB>>, angle: N) -> Self
where SB: Storage<N, U3, U1>,
S::Alloc: Allocator<N, U3, U3> {
OwnedRotation::<N, U3, S::Alloc>::from_axis_angle(axis, angle).to_homogeneous()
}
/// Creates a new homogeneous matrix for an orthographic projection.
#[inline]
pub fn new_orthographic(left: N, right: N, bottom: N, top: N, znear: N, zfar: N) -> Self {
OrthographicBase::new(left, right, bottom, top, znear, zfar).unwrap()
}
/// Creates a new homogeneous matrix for a perspective projection.
#[inline]
pub fn new_perspective(aspect: N, fovy: N, znear: N, zfar: N) -> Self {
PerspectiveBase::new(aspect, fovy, znear, zfar).unwrap()
}
/// Creates an isometry that corresponds to the local frame of an observer standing at the
/// point `eye` and looking toward `target`.
///
/// It maps the view direction `target - eye` to the positive `z` axis and the origin to the
/// `eye`.
#[inline]
pub fn new_observer_frame<SB>(eye: &PointBase<N, U3, SB>,
target: &PointBase<N, U3, SB>,
up: &ColumnVector<N, U3, SB>)
-> Self
where SB: OwnedStorage<N, U3, U1, Alloc = S::Alloc>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> +
Allocator<N, U1, U3> +
Allocator<N, U3, U3> {
IsometryBase::<N, U3, SB, OwnedRotation<N, U3, SB::Alloc>>
::new_observer_frame(eye, target, up).to_homogeneous()
}
/// Builds a right-handed look-at view matrix.
#[inline]
pub fn look_at_rh<SB>(eye: &PointBase<N, U3, SB>,
target: &PointBase<N, U3, SB>,
up: &ColumnVector<N, U3, SB>)
-> Self
where SB: OwnedStorage<N, U3, U1, Alloc = S::Alloc>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> +
Allocator<N, U1, U3> +
Allocator<N, U3, U3> {
IsometryBase::<N, U3, SB, OwnedRotation<N, U3, SB::Alloc>>
::look_at_rh(eye, target, up).to_homogeneous()
}
/// Builds a left-handed look-at view matrix.
#[inline]
pub fn look_at_lh<SB>(eye: &PointBase<N, U3, SB>,
target: &PointBase<N, U3, SB>,
up: &ColumnVector<N, U3, SB>)
-> Self
where SB: OwnedStorage<N, U3, U1, Alloc = S::Alloc>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> +
Allocator<N, U1, U3> +
Allocator<N, U3, U3> {
IsometryBase::<N, U3, SB, OwnedRotation<N, U3, SB::Alloc>>
::look_at_lh(eye, target, up).to_homogeneous()
}
}
impl<N, D: DimName, S> SquareMatrix<N, D, S>
where N: Scalar + Field,
S: Storage<N, D, D> {
/// Computes the transformation equal to `self` followed by an uniform scaling factor.
#[inline]
pub fn append_scaling(&self, scaling: N) -> OwnedSquareMatrix<N, D, S::Alloc>
where D: DimNameSub<U1>,
S::Alloc: Allocator<N, DimNameDiff<D, U1>, D> {
let mut res = self.clone_owned();
res.append_scaling_mut(scaling);
res
}
/// Computes the transformation equal to an uniform scaling factor followed by `self`.
#[inline]
pub fn prepend_scaling(&self, scaling: N) -> OwnedSquareMatrix<N, D, S::Alloc>
where D: DimNameSub<U1>,
S::Alloc: Allocator<N, D, DimNameDiff<D, U1>> {
let mut res = self.clone_owned();
res.prepend_scaling_mut(scaling);
res
}
/// Computes the transformation equal to `self` followed by a non-uniform scaling factor.
#[inline]
pub fn append_nonuniform_scaling<SB>(&self, scaling: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
-> OwnedSquareMatrix<N, D, S::Alloc>
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, U1, D> {
let mut res = self.clone_owned();
res.append_nonuniform_scaling_mut(scaling);
res
}
/// Computes the transformation equal to a non-uniform scaling factor followed by `self`.
#[inline]
pub fn prepend_nonuniform_scaling<SB>(&self, scaling: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
-> OwnedSquareMatrix<N, D, S::Alloc>
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, D, U1> {
let mut res = self.clone_owned();
res.prepend_nonuniform_scaling_mut(scaling);
res
}
/// Computes the transformation equal to `self` followed by a translation.
#[inline]
pub fn append_translation<SB>(&self, shift: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
-> OwnedSquareMatrix<N, D, S::Alloc>
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, DimNameDiff<D, U1>, U1> {
let mut res = self.clone_owned();
res.append_translation_mut(shift);
res
}
/// Computes the transformation equal to a translation followed by `self`.
#[inline]
pub fn prepend_translation<SB>(&self, shift: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
-> OwnedSquareMatrix<N, D, S::Alloc>
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, DimNameDiff<D, U1>, U1> +
Allocator<N, DimNameDiff<D, U1>, DimNameDiff<D, U1>> +
Allocator<N, U1, DimNameDiff<D, U1>> {
let mut res = self.clone_owned();
res.prepend_translation_mut(shift);
res
}
}
impl<N, D: DimName, S> SquareMatrix<N, D, S>
where N: Scalar + Field,
S: StorageMut<N, D, D> {
/// Computes in-place the transformation equal to `self` followed by an uniform scaling factor.
#[inline]
pub fn append_scaling_mut(&mut self, scaling: N)
where D: DimNameSub<U1>,
S::Alloc: Allocator<N, DimNameDiff<D, U1>, D> {
let mut to_scale = self.fixed_rows_mut::<DimNameDiff<D, U1>>(0);
to_scale *= scaling;
}
/// Computes in-place the transformation equal to an uniform scaling factor followed by `self`.
#[inline]
pub fn prepend_scaling_mut(&mut self, scaling: N)
where D: DimNameSub<U1>,
S::Alloc: Allocator<N, D, DimNameDiff<D, U1>> {
let mut to_scale = self.fixed_columns_mut::<DimNameDiff<D, U1>>(0);
to_scale *= scaling;
}
/// Computes in-place the transformation equal to `self` followed by a non-uniform scaling factor.
#[inline]
pub fn append_nonuniform_scaling_mut<SB>(&mut self, scaling: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, U1, D> {
for i in 0 .. scaling.len() {
let mut to_scale = self.fixed_rows_mut::<U1>(i);
to_scale *= scaling[i];
}
}
/// Computes in-place the transformation equal to a non-uniform scaling factor followed by `self`.
#[inline]
pub fn prepend_nonuniform_scaling_mut<SB>(&mut self, scaling: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, D, U1> {
for i in 0 .. scaling.len() {
let mut to_scale = self.fixed_columns_mut::<U1>(i);
to_scale *= scaling[i];
}
}
/// Computes the transformation equal to `self` followed by a translation.
#[inline]
pub fn append_translation_mut<SB>(&mut self, shift: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, DimNameDiff<D, U1>, U1> {
for i in 0 .. D::dim() {
for j in 0 .. D::dim() - 1 {
self[(j, i)] += shift[j] * self[(D::dim() - 1, i)];
}
}
}
/// Computes the transformation equal to a translation followed by `self`.
#[inline]
pub fn prepend_translation_mut<SB>(&mut self, shift: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
where D: DimNameSub<U1>,
SB: Storage<N, DimNameDiff<D, U1>, U1>,
S::Alloc: Allocator<N, DimNameDiff<D, U1>, U1> +
Allocator<N, DimNameDiff<D, U1>, DimNameDiff<D, U1>> +
Allocator<N, U1, DimNameDiff<D, U1>> {
let scale = self.fixed_slice::<U1, DimNameDiff<D, U1>>(D::dim() - 1, 0).tr_dot(&shift);
let post_translation = self.fixed_slice::<DimNameDiff<D, U1>, DimNameDiff<D, U1>>(0, 0) * shift;
self[(D::dim() - 1, D::dim() - 1)] += scale;
let mut translation = self.fixed_slice_mut::<DimNameDiff<D, U1>, U1>(0, D::dim() - 1);
translation += post_translation;
}
}
impl<N, D, SA, SB> Transformation<PointBase<N, DimNameDiff<D, U1>, SB>> for SquareMatrix<N, D, SA>
where N: Real,
D: DimNameSub<U1>,
SA: OwnedStorage<N, D, D>,
SB: OwnedStorage<N, DimNameDiff<D, U1>, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, D, D, SA> +
Allocator<N, DimNameDiff<D, U1>, DimNameDiff<D, U1>> +
Allocator<N, DimNameDiff<D, U1>, U1> +
Allocator<N, U1, DimNameDiff<D, U1>>,
SB::Alloc: OwnedAllocator<N, DimNameDiff<D, U1>, U1, SB> {
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, DimNameDiff<D, U1>, SB>)
-> ColumnVector<N, DimNameDiff<D, U1>, SB> {
let transform = self.fixed_slice::<DimNameDiff<D, U1>, DimNameDiff<D, U1>>(0, 0);
let normalizer = self.fixed_slice::<U1, DimNameDiff<D, U1>>(D::dim() - 1, 0);
let n = normalizer.tr_dot(&v);
if !n.is_zero() {
return transform * (v / n);
}
transform * v
}
#[inline]
fn transform_point(&self, pt: &PointBase<N, DimNameDiff<D, U1>, SB>)
-> PointBase<N, DimNameDiff<D, U1>, SB> {
let transform = self.fixed_slice::<DimNameDiff<D, U1>, DimNameDiff<D, U1>>(0, 0);
let translation = self.fixed_slice::<DimNameDiff<D, U1>, U1>(0, D::dim() - 1);
let normalizer = self.fixed_slice::<U1, DimNameDiff<D, U1>>(D::dim() - 1, 0);
let n = normalizer.tr_dot(&pt.coords) + unsafe { *self.get_unchecked(D::dim() - 1, D::dim() - 1) };
if !n.is_zero() {
return transform * (pt / n) + translation;
}
transform * pt + translation
}
}

77
src/core/componentwise.rs Normal file
View File

@ -0,0 +1,77 @@
// Non-convensional componentwise operators.
use num::Signed;
use alga::general::{ClosedMul, ClosedDiv};
use core::{Scalar, Matrix, OwnedMatrix, MatrixSum};
use core::dimension::Dim;
use core::storage::{Storage, StorageMut};
use core::allocator::SameShapeAllocator;
use core::constraint::{ShapeConstraint, SameNumberOfRows, SameNumberOfColumns};
/// The type of the result of a matrix componentwise operation.
pub type MatrixComponentOp<N, R1, C1, R2, C2, SA> = MatrixSum<N, R1, C1, R2, C2, SA>;
impl<N: Scalar, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S> {
/// Computes the componentwise absolute value.
#[inline]
pub fn abs(&self) -> OwnedMatrix<N, R, C, S::Alloc>
where N: Signed {
let mut res = self.clone_owned();
for e in res.iter_mut() {
*e = e.abs();
}
res
}
// FIXME: add other operators like component_ln, component_pow, etc. ?
}
macro_rules! component_binop_impl(
($($binop: ident, $binop_mut: ident, $Trait: ident . $binop_assign: ident);* $(;)*) => {$(
impl<N: Scalar, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S> {
/// Componentwise matrix multiplication.
#[inline]
pub fn $binop<R2, C2, SB>(&self, rhs: &Matrix<N, R2, C2, SB>) -> MatrixComponentOp<N, R, C, R2, C2, S>
where N: $Trait,
R2: Dim, C2: Dim,
SB: Storage<N, R2, C2>,
S::Alloc: SameShapeAllocator<N, R, C, R2, C2, S>,
ShapeConstraint: SameNumberOfRows<R, R2> + SameNumberOfColumns<C, C2> {
let mut res = self.clone_owned_sum();
for (res, rhs) in res.iter_mut().zip(rhs.iter()) {
res.$binop_assign(*rhs);
}
res
}
}
impl<N: Scalar, R: Dim, C: Dim, S: StorageMut<N, R, C>> Matrix<N, R, C, S> {
/// Componentwise matrix multiplication.
#[inline]
pub fn $binop_mut<R2, C2, SB>(&mut self, rhs: &Matrix<N, R2, C2, SB>)
where N: $Trait,
R2: Dim,
C2: Dim,
SB: Storage<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R, R2> + SameNumberOfColumns<C, C2> {
for (me, rhs) in self.iter_mut().zip(rhs.iter()) {
me.$binop_assign(*rhs);
}
}
}
)*}
);
component_binop_impl!(
component_mul, component_mul_mut, ClosedMul.mul_assign;
component_div, component_div_mut, ClosedDiv.div_assign;
// FIXME: add other operators like bitshift, etc. ?
);

75
src/core/constraint.rs Normal file
View File

@ -0,0 +1,75 @@
//! Compatibility constraints between matrix shapes, e.g., for addition or multiplication.
use core::dimension::{Dim, DimName, Dynamic};
/// A type used in `where` clauses for enforcing constraints.
pub struct ShapeConstraint;
/// Constraints `C1` and `R2` to be equivalent.
pub trait AreMultipliable<R1: Dim, C1: Dim,
R2: Dim, C2: Dim> {
}
impl<R1: Dim, C1: Dim, R2: Dim, C2: Dim> AreMultipliable<R1, C1, R2, C2> for ShapeConstraint
where ShapeConstraint: DimEq<C1, R2> {
}
macro_rules! equality_trait_decl(
($($doc: expr, $Trait: ident),* $(,)*) => {$(
// XXX: we can't do something like `DimEq<D1> for D2` because we would require a blancket impl…
#[doc = $doc]
pub trait $Trait<D1: Dim, D2: Dim> {
/// This is either equal to `D1` or `D2`, always choosing the one (if any) which is a type-level
/// constant.
type Representative: Dim;
}
impl<D: Dim> $Trait<D, D> for ShapeConstraint {
type Representative = D;
}
impl<D: DimName> $Trait<D, Dynamic> for ShapeConstraint {
type Representative = D;
}
impl<D: DimName> $Trait<Dynamic, D> for ShapeConstraint {
type Representative = D;
}
)*}
);
equality_trait_decl!(
"Constraints `D1` and `D2` to be equivalent.",
DimEq,
"Constraints `D1` and `D2` to be equivalent. \
They are both assumed to be the number of \
rows of a matrix.",
SameNumberOfRows,
"Constraints `D1` and `D2` to be equivalent. \
They are both assumed to be the number of \
columns of a matrix.",
SameNumberOfColumns
);
/// Constraints D1 and D2 to be equivalent, where they both designate dimensions of algebraic
/// entities (e.g. square matrices).
pub trait SameDimension<D1: Dim, D2: Dim>: SameNumberOfRows<D1, D2> + SameNumberOfColumns<D1, D2> {
/// This is either equal to `D1` or `D2`, always choosing the one (if any) which is a type-level
/// constant.
type Representative: Dim;
}
impl<D: Dim> SameDimension<D, D> for ShapeConstraint {
type Representative = D;
}
impl<D: DimName> SameDimension<D, Dynamic> for ShapeConstraint {
type Representative = D;
}
impl<D: DimName> SameDimension<Dynamic, D> for ShapeConstraint {
type Representative = D;
}

657
src/core/construction.rs Normal file
View File

@ -0,0 +1,657 @@
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use std::iter;
use num::{Zero, One, Bounded};
use rand::{self, Rand, Rng};
use typenum::{self, Cmp, Greater};
use alga::general::{ClosedAdd, ClosedMul};
use core::{Scalar, Matrix, SquareMatrix, ColumnVector, Unit};
use core::dimension::{Dim, DimName, Dynamic, U1, U2, U3, U4, U5, U6};
use core::allocator::{Allocator, OwnedAllocator};
use core::storage::{Storage, OwnedStorage};
/*
*
* Generic constructors.
*
*/
impl<N: Scalar, R: Dim, C: Dim, S: OwnedStorage<N, R, C>> Matrix<N, R, C, S>
// XXX: needed because of a compiler bug. See the rust compiler issue #26026.
where S::Alloc: OwnedAllocator<N, R, C, S> {
/// Creates a new uninitialized matrix. If the matrix has a compile-time dimension, this panics
/// if `nrows != R::to_usize()` or `ncols != C::to_usize()`.
#[inline]
pub unsafe fn new_uninitialized_generic(nrows: R, ncols: C) -> Matrix<N, R, C, S> {
Matrix::from_data(S::Alloc::allocate_uninitialized(nrows, ncols))
}
/// Creates a matrix with all its elements set to `elem`.
#[inline]
pub fn from_element_generic(nrows: R, ncols: C, elem: N) -> Matrix<N, R, C, S> {
let len = nrows.value() * ncols.value();
Matrix::from_iterator_generic(nrows, ncols, iter::repeat(elem).take(len))
}
/// Creates a matrix with all its elements filled by an iterator.
#[inline]
pub fn from_iterator_generic<I>(nrows: R, ncols: C, iter: I) -> Matrix<N, R, C, S>
where I: IntoIterator<Item = N> {
Matrix::from_data(S::Alloc::allocate_from_iterator(nrows, ncols, iter))
}
/// Creates a matrix with its elements filled with the components provided by a slice in
/// row-major order.
///
/// The order of elements in the slice must follow the usual mathematic writing, i.e.,
/// row-by-row.
#[inline]
pub fn from_row_slice_generic(nrows: R, ncols: C, slice: &[N]) -> Matrix<N, R, C, S> {
assert!(slice.len() == nrows.value() * ncols.value(),
"Matrix init. error: the slice did not contain the right number of elements.");
let mut res = unsafe { Self::new_uninitialized_generic(nrows, ncols) };
let mut iter = slice.iter();
for i in 0 .. nrows.value() {
for j in 0 .. ncols.value() {
unsafe {
*res.get_unchecked_mut(i, j) = *iter.next().unwrap()
}
}
}
res
}
/// Creates a matrix with its elements filled with the components provided by a slice. The
/// components must have the same layout as the matrix data storage (i.e. row-major or column-major).
#[inline]
pub fn from_column_slice_generic(nrows: R, ncols: C, slice: &[N]) -> Matrix<N, R, C, S> {
Matrix::from_iterator_generic(nrows, ncols, slice.iter().cloned())
}
/// Creates a matrix filled with the results of a function applied to each of its component
/// coordinates.
#[inline]
pub fn from_fn_generic<F>(nrows: R, ncols: C, mut f: F) -> Matrix<N, R, C, S>
where F: FnMut(usize, usize) -> N {
let mut res = unsafe { Self::new_uninitialized_generic(nrows, ncols) };
for i in 0 .. nrows.value() {
for j in 0 .. ncols.value() {
unsafe { *res.get_unchecked_mut(i, j) = f(i, j) }
}
}
res
}
/// Creates a new indentity matrix.
///
/// If the matrix is not square, the largest square submatrix starting at index `(0, 0)` is set
/// to the identity matrix. All other entries are set to zero.
#[inline]
pub fn identity_generic(nrows: R, ncols: C) -> Matrix<N, R, C, S>
where N: Zero + One {
Self::from_diagonal_element_generic(nrows, ncols, N::one())
}
/// Creates a new matrix with its diagonal filled with copies of `elt`.
///
/// If the matrix is not square, the largest square submatrix starting at index `(0, 0)` is set
/// to the identity matrix. All other entries are set to zero.
#[inline]
pub fn from_diagonal_element_generic(nrows: R, ncols: C, elt: N) -> Matrix<N, R, C, S>
where N: Zero + One {
let mut res = unsafe { Self::new_uninitialized_generic(nrows, ncols) };
res.fill(N::zero());
for i in 0 .. ::min(nrows.value(), ncols.value()) {
unsafe { *res.get_unchecked_mut(i, i) = elt }
}
res
}
/// Builds a new matrix from its rows.
///
/// Panics if not enough rows are provided (for statically-sized matrices), or if all rows do
/// not have the same dimensions.
#[inline]
pub fn from_rows<SB>(rows: &[Matrix<N, U1, C, SB>]) -> Matrix<N, R, C, S>
where SB: Storage<N, U1, C> {
assert!(rows.len() > 0, "At least one row must be given.");
let nrows = R::try_to_usize().unwrap_or(rows.len());
let ncols = rows[0].len();
assert!(rows.len() == nrows, "Invalid number of rows provided to build this matrix.");
if C::try_to_usize().is_none() {
assert!(rows.iter().all(|r| r.len() == ncols),
"The provided rows must all have the same dimension.");
}
// FIXME: optimize that.
Self::from_fn_generic(R::from_usize(nrows), C::from_usize(ncols), |i, j| rows[i][(0, j)])
}
/// Builds a new matrix from its columns.
///
/// Panics if not enough columns are provided (for statically-sized matrices), or if all
/// columns do not have the same dimensions.
#[inline]
pub fn from_columns<SB>(columns: &[ColumnVector<N, R, SB>]) -> Matrix<N, R, C, S>
where SB: Storage<N, R, U1> {
assert!(columns.len() > 0, "At least one column must be given.");
let ncols = C::try_to_usize().unwrap_or(columns.len());
let nrows = columns[0].len();
assert!(columns.len() == ncols, "Invalid number of columns provided to build this matrix.");
if R::try_to_usize().is_none() {
assert!(columns.iter().all(|r| r.len() == nrows),
"The columns provided must all have the same dimension.");
}
// FIXME: optimize that.
Self::from_fn_generic(R::from_usize(nrows), C::from_usize(ncols), |i, j| columns[j][i])
}
}
impl<N, R: Dim, C: Dim, S> Matrix<N, R, C, S>
where N: Scalar + Rand,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
/// Creates a matrix filled with random values.
#[inline]
pub fn new_random_generic(nrows: R, ncols: C) -> Matrix<N, R, C, S> {
Matrix::from_fn_generic(nrows, ncols, |_, _| rand::random())
}
}
impl<N, D: Dim, S> SquareMatrix<N, D, S>
where N: Scalar + Zero,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
/// Creates a square matrix with its diagonal set to `diag` and all other entries set to 0.
#[inline]
pub fn from_diagonal<SB: Storage<N, D, U1>>(diag: &ColumnVector<N, D, SB>) -> Self {
let (dim, _) = diag.data.shape();
let mut res = Self::from_element_generic(dim, dim, N::zero());
for i in 0 .. diag.len() {
unsafe { *res.get_unchecked_mut(i, i) = *diag.get_unchecked(i, 0); }
}
res
}
}
/*
*
* Generate constructors with varying number of arguments, depending on the object type.
*
*/
macro_rules! impl_constructors(
($($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr),*; $($args: ident),*) => {
impl<N: Scalar, $($DimIdent: $DimBound, )* S> Matrix<N $(, $Dims)*, S>
where S: OwnedStorage<N $(, $Dims)*>,
S::Alloc: OwnedAllocator<N $(, $Dims)*, S> {
/// Creates a new uninitialized matrix.
#[inline]
pub unsafe fn new_uninitialized($($args: usize),*) -> Matrix<N $(, $Dims)*, S> {
Self::new_uninitialized_generic($($gargs),*)
}
/// Creates a matrix with all its elements set to `elem`.
#[inline]
pub fn from_element($($args: usize,)* elem: N) -> Matrix<N $(, $Dims)*, S> {
Self::from_element_generic($($gargs, )* elem)
}
/// Creates a matrix with all its elements filled by an iterator.
#[inline]
pub fn from_iterator<I>($($args: usize,)* iter: I) -> Matrix<N $(, $Dims)*, S>
where I: IntoIterator<Item = N> {
Self::from_iterator_generic($($gargs, )* iter)
}
/// Creates a matrix with its elements filled with the components provided by a slice
/// in row-major order.
///
/// The order of elements in the slice must follow the usual mathematic writing, i.e.,
/// row-by-row.
#[inline]
pub fn from_row_slice($($args: usize,)* slice: &[N]) -> Matrix<N $(, $Dims)*, S> {
Self::from_row_slice_generic($($gargs, )* slice)
}
/// Creates a matrix with its elements filled with the components provided by a slice
/// in column-major order.
#[inline]
pub fn from_column_slice($($args: usize,)* slice: &[N]) -> Matrix<N $(, $Dims)*, S> {
Self::from_column_slice_generic($($gargs, )* slice)
}
/// Creates a matrix filled with the results of a function applied to each of its
/// component coordinates.
// FIXME: don't take a dimension of the matrix is statically sized.
#[inline]
pub fn from_fn<F>($($args: usize,)* f: F) -> Matrix<N $(, $Dims)*, S>
where F: FnMut(usize, usize) -> N {
Self::from_fn_generic($($gargs, )* f)
}
/// Creates an identity matrix. If the matrix is not square, the largest square
/// submatrix (starting at the first row and column) is set to the identity while all
/// other entries are set to zero.
#[inline]
pub fn identity($($args: usize,)*) -> Matrix<N $(, $Dims)*, S>
where N: Zero + One {
Self::identity_generic($($gargs),* )
}
/// Creates a matrix filled with its diagonal filled with `elt` and all other
/// components set to zero.
#[inline]
pub fn from_diagonal_element($($args: usize,)* elt: N) -> Matrix<N $(, $Dims)*, S>
where N: Zero + One {
Self::from_diagonal_element_generic($($gargs, )* elt)
}
}
impl<N: Scalar + Rand, $($DimIdent: $DimBound, )* S> Matrix<N $(, $Dims)*, S>
where S: OwnedStorage<N $(, $Dims)*>,
S::Alloc: OwnedAllocator<N $(, $Dims)*, S> {
/// Creates a matrix filled with random values.
#[inline]
pub fn new_random($($args: usize),*) -> Matrix<N $(, $Dims)*, S> {
Self::new_random_generic($($gargs),*)
}
}
}
);
// FIXME: this is not very pretty. We could find a better call syntax.
impl_constructors!(R, C; // Arguments for Matrix<N, ..., S>
=> R: DimName, => C: DimName; // Type parameters for impl<N, ..., S>
R::name(), C::name(); // Arguments for `_generic` constructors.
); // Arguments for non-generic constructors.
impl_constructors!(R, Dynamic;
=> R: DimName;
R::name(), Dynamic::new(ncols);
ncols);
impl_constructors!(Dynamic, C;
=> C: DimName;
Dynamic::new(nrows), C::name();
nrows);
impl_constructors!(Dynamic, Dynamic;
;
Dynamic::new(nrows), Dynamic::new(ncols);
nrows, ncols);
/*
*
* Zero, One, Rand traits.
*
*/
impl<N, R: DimName, C: DimName, S> Zero for Matrix<N, R, C, S>
where N: Scalar + Zero + ClosedAdd,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn zero() -> Self {
Self::from_element(N::zero())
}
#[inline]
fn is_zero(&self) -> bool {
self.iter().all(|e| e.is_zero())
}
}
impl<N, D: DimName, S> One for Matrix<N, D, D, S>
where N: Scalar + Zero + One + ClosedMul + ClosedAdd,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
#[inline]
fn one() -> Self {
Self::identity()
}
}
impl<N, R: DimName, C: DimName, S> Bounded for Matrix<N, R, C, S>
where N: Scalar + Bounded,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn max_value() -> Self {
Self::from_element(N::max_value())
}
#[inline]
fn min_value() -> Self {
Self::from_element(N::min_value())
}
}
impl<N: Scalar + Rand, R: Dim, C: Dim, S> Rand for Matrix<N, R, C, S>
where S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn rand<G: Rng>(rng: &mut G) -> Self {
let nrows = R::try_to_usize().unwrap_or(rng.gen_range(0, 10));
let ncols = C::try_to_usize().unwrap_or(rng.gen_range(0, 10));
Self::from_fn_generic(R::from_usize(nrows), C::from_usize(ncols), |_, _| rng.gen())
}
}
#[cfg(feature = "arbitrary")]
impl<N, R, C, S> Arbitrary for Matrix<N, R, C, S>
where R: Dim, C: Dim,
N: Scalar + Arbitrary + Send,
S: OwnedStorage<N, R, C> + Send,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let nrows = R::try_to_usize().unwrap_or(g.gen_range(0, 10));
let ncols = C::try_to_usize().unwrap_or(g.gen_range(0, 10));
Self::from_fn_generic(R::from_usize(nrows), C::from_usize(ncols), |_, _| N::arbitrary(g))
}
}
/*
*
* Constructors for small matrices and vectors.
*
*/
macro_rules! componentwise_constructors_impl(
($($R: ty, $C: ty, $($args: ident:($irow: expr,$icol: expr)),*);* $(;)*) => {$(
impl<N, S> Matrix<N, $R, $C, S>
where N: Scalar,
S: OwnedStorage<N, $R, $C>,
S::Alloc: OwnedAllocator<N, $R, $C, S> {
/// Initializes this matrix from its components.
#[inline]
pub fn new($($args: N),*) -> Matrix<N, $R, $C, S> {
unsafe {
let mut res = Self::new_uninitialized();
$( *res.get_unchecked_mut($irow, $icol) = $args; )*
res
}
}
}
)*}
);
componentwise_constructors_impl!(
/*
* Square matrices 1 .. 6.
*/
U2, U2, m11:(0,0), m12:(0,1),
m21:(1,0), m22:(1,1);
U3, U3, m11:(0,0), m12:(0,1), m13:(0,2),
m21:(1,0), m22:(1,1), m23:(1,2),
m31:(2,0), m32:(2,1), m33:(2,2);
U4, U4, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3);
U5, U5, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3), m45:(3,4),
m51:(4,0), m52:(4,1), m53:(4,2), m54:(4,3), m55:(4,4);
U6, U6, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4), m16:(0,5),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4), m26:(1,5),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4), m36:(2,5),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3), m45:(3,4), m46:(3,5),
m51:(4,0), m52:(4,1), m53:(4,2), m54:(4,3), m55:(4,4), m56:(4,5),
m61:(5,0), m62:(5,1), m63:(5,2), m64:(5,3), m65:(5,4), m66:(5,5);
/*
* Rectangular matrices with 2 rows.
*/
U2, U3, m11:(0,0), m12:(0,1), m13:(0,2),
m21:(1,0), m22:(1,1), m23:(1,2);
U2, U4, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3);
U2, U5, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4);
U2, U6, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4), m16:(0,5),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4), m26:(1,5);
/*
* Rectangular matrices with 3 rows.
*/
U3, U2, m11:(0,0), m12:(0,1),
m21:(1,0), m22:(1,1),
m31:(2,0), m32:(2,1);
U3, U4, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3);
U3, U5, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4);
U3, U6, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4), m16:(0,5),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4), m26:(1,5),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4), m36:(2,5);
/*
* Rectangular matrices with 4 rows.
*/
U4, U2, m11:(0,0), m12:(0,1),
m21:(1,0), m22:(1,1),
m31:(2,0), m32:(2,1),
m41:(3,0), m42:(3,1);
U4, U3, m11:(0,0), m12:(0,1), m13:(0,2),
m21:(1,0), m22:(1,1), m23:(1,2),
m31:(2,0), m32:(2,1), m33:(2,2),
m41:(3,0), m42:(3,1), m43:(3,2);
U4, U5, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3), m45:(3,4);
U4, U6, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4), m16:(0,5),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4), m26:(1,5),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4), m36:(2,5),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3), m45:(3,4), m46:(3,5);
/*
* Rectangular matrices with 5 rows.
*/
U5, U2, m11:(0,0), m12:(0,1),
m21:(1,0), m22:(1,1),
m31:(2,0), m32:(2,1),
m41:(3,0), m42:(3,1),
m51:(4,0), m52:(4,1);
U5, U3, m11:(0,0), m12:(0,1), m13:(0,2),
m21:(1,0), m22:(1,1), m23:(1,2),
m31:(2,0), m32:(2,1), m33:(2,2),
m41:(3,0), m42:(3,1), m43:(3,2),
m51:(4,0), m52:(4,1), m53:(4,2);
U5, U4, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3),
m51:(4,0), m52:(4,1), m53:(4,2), m54:(4,3);
U5, U6, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4), m16:(0,5),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4), m26:(1,5),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4), m36:(2,5),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3), m45:(3,4), m46:(3,5),
m51:(4,0), m52:(4,1), m53:(4,2), m54:(4,3), m55:(4,4), m56:(4,5);
/*
* Rectangular matrices with 6 rows.
*/
U6, U2, m11:(0,0), m12:(0,1),
m21:(1,0), m22:(1,1),
m31:(2,0), m32:(2,1),
m41:(3,0), m42:(3,1),
m51:(4,0), m52:(4,1),
m61:(5,0), m62:(5,1);
U6, U3, m11:(0,0), m12:(0,1), m13:(0,2),
m21:(1,0), m22:(1,1), m23:(1,2),
m31:(2,0), m32:(2,1), m33:(2,2),
m41:(3,0), m42:(3,1), m43:(3,2),
m51:(4,0), m52:(4,1), m53:(4,2),
m61:(5,0), m62:(5,1), m63:(5,2);
U6, U4, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3),
m51:(4,0), m52:(4,1), m53:(4,2), m54:(4,3),
m61:(5,0), m62:(5,1), m63:(5,2), m64:(5,3);
U6, U5, m11:(0,0), m12:(0,1), m13:(0,2), m14:(0,3), m15:(0,4),
m21:(1,0), m22:(1,1), m23:(1,2), m24:(1,3), m25:(1,4),
m31:(2,0), m32:(2,1), m33:(2,2), m34:(2,3), m35:(2,4),
m41:(3,0), m42:(3,1), m43:(3,2), m44:(3,3), m45:(3,4),
m51:(4,0), m52:(4,1), m53:(4,2), m54:(4,3), m55:(4,4),
m61:(5,0), m62:(5,1), m63:(5,2), m64:(5,3), m65:(5,4);
/*
* Row vectors 1 .. 6.
*/
U1, U1, x:(0,0);
U1, U2, x:(0,0), y:(0,1);
U1, U3, x:(0,0), y:(0,1), z:(0,2);
U1, U4, x:(0,0), y:(0,1), z:(0,2), w:(0,3);
U1, U5, x:(0,0), y:(0,1), z:(0,2), w:(0,3), a:(0,4);
U1, U6, x:(0,0), y:(0,1), z:(0,2), w:(0,3), a:(0,4), b:(0,5);
/*
* Column vectors 1 .. 6.
*/
U2, U1, x:(0,0), y:(1,0);
U3, U1, x:(0,0), y:(1,0), z:(2,0);
U4, U1, x:(0,0), y:(1,0), z:(2,0), w:(3,0);
U5, U1, x:(0,0), y:(1,0), z:(2,0), w:(3,0), a:(4,0);
U6, U1, x:(0,0), y:(1,0), z:(2,0), w:(3,0), a:(4,0), b:(5,0);
);
/*
*
* Axis constructors.
*
*/
impl<N, R: DimName, S> ColumnVector<N, R, S>
where N: Scalar + Zero + One,
S: OwnedStorage<N, R, U1>,
S::Alloc: OwnedAllocator<N, R, U1, S> {
/// The column vector with a 1 as its first component, and zero elsewhere.
#[inline]
pub fn x() -> Self
where R::Value: Cmp<typenum::U0, Output = Greater> {
let mut res = Self::from_element(N::zero());
unsafe { *res.get_unchecked_mut(0, 0) = N::one(); }
res
}
/// The column vector with a 1 as its second component, and zero elsewhere.
#[inline]
pub fn y() -> Self
where R::Value: Cmp<typenum::U1, Output = Greater> {
let mut res = Self::from_element(N::zero());
unsafe { *res.get_unchecked_mut(1, 0) = N::one(); }
res
}
/// The column vector with a 1 as its third component, and zero elsewhere.
#[inline]
pub fn z() -> Self
where R::Value: Cmp<typenum::U2, Output = Greater> {
let mut res = Self::from_element(N::zero());
unsafe { *res.get_unchecked_mut(2, 0) = N::one(); }
res
}
/// The column vector with a 1 as its fourth component, and zero elsewhere.
#[inline]
pub fn w() -> Self
where R::Value: Cmp<typenum::U3, Output = Greater> {
let mut res = Self::from_element(N::zero());
unsafe { *res.get_unchecked_mut(3, 0) = N::one(); }
res
}
/// The column vector with a 1 as its fifth component, and zero elsewhere.
#[inline]
pub fn a() -> Self
where R::Value: Cmp<typenum::U4, Output = Greater> {
let mut res = Self::from_element(N::zero());
unsafe { *res.get_unchecked_mut(4, 0) = N::one(); }
res
}
/// The column vector with a 1 as its sixth component, and zero elsewhere.
#[inline]
pub fn b() -> Self
where R::Value: Cmp<typenum::U5, Output = Greater> {
let mut res = Self::from_element(N::zero());
unsafe { *res.get_unchecked_mut(5, 0) = N::one(); }
res
}
/// The unit column vector with a 1 as its first component, and zero elsewhere.
#[inline]
pub fn x_axis() -> Unit<Self>
where R::Value: Cmp<typenum::U0, Output = Greater> {
Unit::new_unchecked(Self::x())
}
/// The unit column vector with a 1 as its second component, and zero elsewhere.
#[inline]
pub fn y_axis() -> Unit<Self>
where R::Value: Cmp<typenum::U1, Output = Greater> {
Unit::new_unchecked(Self::y())
}
/// The unit column vector with a 1 as its third component, and zero elsewhere.
#[inline]
pub fn z_axis() -> Unit<Self>
where R::Value: Cmp<typenum::U2, Output = Greater> {
Unit::new_unchecked(Self::z())
}
/// The unit column vector with a 1 as its fourth component, and zero elsewhere.
#[inline]
pub fn w_axis() -> Unit<Self>
where R::Value: Cmp<typenum::U3, Output = Greater> {
Unit::new_unchecked(Self::w())
}
/// The unit column vector with a 1 as its fifth component, and zero elsewhere.
#[inline]
pub fn a_axis() -> Unit<Self>
where R::Value: Cmp<typenum::U4, Output = Greater> {
Unit::new_unchecked(Self::a())
}
/// The unit column vector with a 1 as its sixth component, and zero elsewhere.
#[inline]
pub fn b_axis() -> Unit<Self>
where R::Value: Cmp<typenum::U5, Output = Greater> {
Unit::new_unchecked(Self::b())
}
}

59
src/core/conversion.rs Normal file
View File

@ -0,0 +1,59 @@
use alga::general::{SubsetOf, SupersetOf};
use core::{Scalar, Matrix};
use core::dimension::Dim;
use core::constraint::{ShapeConstraint, SameNumberOfRows, SameNumberOfColumns};
use core::storage::OwnedStorage;
use core::allocator::{OwnedAllocator, SameShapeAllocator};
// FIXME: too bad this won't work allo slice conversions.
impl<N1, N2, R1, C1, R2, C2, SA, SB> SubsetOf<Matrix<N2, R2, C2, SB>> for Matrix<N1, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim, C2: Dim,
N1: Scalar,
N2: Scalar + SupersetOf<N1>,
SA: OwnedStorage<N1, R1, C1>,
SB: OwnedStorage<N2, R2, C2>,
SB::Alloc: OwnedAllocator<N2, R2, C2, SB>,
SA::Alloc: OwnedAllocator<N1, R1, C1, SA> +
SameShapeAllocator<N1, R1, C1, R2, C2, SA>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
#[inline]
fn to_superset(&self) -> Matrix<N2, R2, C2, SB> {
let (nrows, ncols) = self.shape();
let nrows2 = R2::from_usize(nrows);
let ncols2 = C2::from_usize(ncols);
let mut res = unsafe { Matrix::<N2, R2, C2, SB>::new_uninitialized_generic(nrows2, ncols2) };
for i in 0 .. nrows {
for j in 0 .. ncols {
unsafe {
*res.get_unchecked_mut(i, j) = N2::from_subset(self.get_unchecked(i, j))
}
}
}
res
}
#[inline]
fn is_in_subset(m: &Matrix<N2, R2, C2, SB>) -> bool {
m.iter().all(|e| e.is_in_subset())
}
#[inline]
unsafe fn from_superset_unchecked(m: &Matrix<N2, R2, C2, SB>) -> Self {
let (nrows2, ncols2) = m.shape();
let nrows = R1::from_usize(nrows2);
let ncols = C1::from_usize(ncols2);
let mut res = Self::new_uninitialized_generic(nrows, ncols);
for i in 0 .. nrows2 {
for j in 0 .. ncols2 {
*res.get_unchecked_mut(i, j) = m.get_unchecked(i, j).to_subset_unchecked()
}
}
res
}
}

239
src/core/coordinates.rs Normal file
View File

@ -0,0 +1,239 @@
#![allow(missing_docs)]
//! Structures to which matrices and vector can be auto-dereferenced (through `Deref`) to access
//! components using their names. For example, if `v` is a 3D vector, one can write `v.z` instead
//! of `v[2]`.
use std::mem;
use std::ops::{Deref, DerefMut};
use core::{Scalar, Matrix};
use core::dimension::{U1, U2, U3, U4, U5, U6};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
/*
*
* Give coordinates to owned Vector{1 .. 6} and Matrix{1 .. 6}
*
*/
macro_rules! coords_impl(
($T: ident; $($comps: ident),*) => {
/// Data structure used to provide access to matrix and vector coordinates with the dot
/// notation, e.g., `v.x` is the same as `v[0]` for a vector.
#[repr(C)]
#[derive(Eq, PartialEq, Clone, Hash, Debug, Copy)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct $T<N: Scalar> {
$(pub $comps: N),*
}
}
);
macro_rules! deref_impl(
($R: ty, $C: ty; $Target: ident) => {
impl<N: Scalar, S> Deref for Matrix<N, $R, $C, S>
where S: OwnedStorage<N, $R, $C>,
S::Alloc: OwnedAllocator<N, $R, $C, S> {
type Target = $Target<N>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { mem::transmute(self) }
}
}
impl<N: Scalar, S> DerefMut for Matrix<N, $R, $C, S>
where S: OwnedStorage<N, $R, $C>,
S::Alloc: OwnedAllocator<N, $R, $C, S> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { mem::transmute(self) }
}
}
}
);
/*
*
* Vector coordinates.
*
*/
coords_impl!(X; x);
coords_impl!(XY; x, y);
coords_impl!(XYZ; x, y, z);
coords_impl!(XYZW; x, y, z, w);
coords_impl!(XYZWA; x, y, z, w, a);
coords_impl!(XYZWAB; x, y, z, w, a, b);
coords_impl!(IJKW; i, j, k, w);
/*
* Rectangular matrices with 2 rows.
*/
coords_impl!(M2x2; m11, m21,
m12, m22);
coords_impl!(M2x3; m11, m21,
m12, m22,
m13, m23);
coords_impl!(M2x4; m11, m21,
m12, m22,
m13, m23,
m14, m24);
coords_impl!(M2x5; m11, m21,
m12, m22,
m13, m23,
m14, m24,
m15, m25);
coords_impl!(M2x6; m11, m21,
m12, m22,
m13, m23,
m14, m24,
m15, m25,
m16, m26);
/*
* Rectangular matrices with 3 rows.
*/
coords_impl!(M3x2; m11, m21, m31,
m12, m22, m32);
coords_impl!(M3x3; m11, m21, m31,
m12, m22, m32,
m13, m23, m33);
coords_impl!(M3x4; m11, m21, m31,
m12, m22, m32,
m13, m23, m33,
m14, m24, m34);
coords_impl!(M3x5; m11, m21, m31,
m12, m22, m32,
m13, m23, m33,
m14, m24, m34,
m15, m25, m35);
coords_impl!(M3x6; m11, m21, m31,
m12, m22, m32,
m13, m23, m33,
m14, m24, m34,
m15, m25, m35,
m16, m26, m36);
/*
* Rectangular matrices with 4 rows.
*/
coords_impl!(M4x2; m11, m21, m31, m41,
m12, m22, m32, m42);
coords_impl!(M4x3; m11, m21, m31, m41,
m12, m22, m32, m42,
m13, m23, m33, m43);
coords_impl!(M4x4; m11, m21, m31, m41,
m12, m22, m32, m42,
m13, m23, m33, m43,
m14, m24, m34, m44);
coords_impl!(M4x5; m11, m21, m31, m41,
m12, m22, m32, m42,
m13, m23, m33, m43,
m14, m24, m34, m44,
m15, m25, m35, m45);
coords_impl!(M4x6; m11, m21, m31, m41,
m12, m22, m32, m42,
m13, m23, m33, m43,
m14, m24, m34, m44,
m15, m25, m35, m45,
m16, m26, m36, m46);
/*
* Rectangular matrices with 5 rows.
*/
coords_impl!(M5x2; m11, m21, m31, m41, m51,
m12, m22, m32, m42, m52);
coords_impl!(M5x3; m11, m21, m31, m41, m51,
m12, m22, m32, m42, m52,
m13, m23, m33, m43, m53);
coords_impl!(M5x4; m11, m21, m31, m41, m51,
m12, m22, m32, m42, m52,
m13, m23, m33, m43, m53,
m14, m24, m34, m44, m54);
coords_impl!(M5x5; m11, m21, m31, m41, m51,
m12, m22, m32, m42, m52,
m13, m23, m33, m43, m53,
m14, m24, m34, m44, m54,
m15, m25, m35, m45, m55);
coords_impl!(M5x6; m11, m21, m31, m41, m51,
m12, m22, m32, m42, m52,
m13, m23, m33, m43, m53,
m14, m24, m34, m44, m54,
m15, m25, m35, m45, m55,
m16, m26, m36, m46, m56);
/*
* Rectangular matrices with 6 rows.
*/
coords_impl!(M6x2; m11, m21, m31, m41, m51, m61,
m12, m22, m32, m42, m52, m62);
coords_impl!(M6x3; m11, m21, m31, m41, m51, m61,
m12, m22, m32, m42, m52, m62,
m13, m23, m33, m43, m53, m63);
coords_impl!(M6x4; m11, m21, m31, m41, m51, m61,
m12, m22, m32, m42, m52, m62,
m13, m23, m33, m43, m53, m63,
m14, m24, m34, m44, m54, m64);
coords_impl!(M6x5; m11, m21, m31, m41, m51, m61,
m12, m22, m32, m42, m52, m62,
m13, m23, m33, m43, m53, m63,
m14, m24, m34, m44, m54, m64,
m15, m25, m35, m45, m55, m65);
coords_impl!(M6x6; m11, m21, m31, m41, m51, m61,
m12, m22, m32, m42, m52, m62,
m13, m23, m33, m43, m53, m63,
m14, m24, m34, m44, m54, m64,
m15, m25, m35, m45, m55, m65,
m16, m26, m36, m46, m56, m66);
/*
*
* Attach coordinates to matrices.
*
*/
deref_impl!(U1, U1; X);
deref_impl!(U2, U1; XY);
deref_impl!(U3, U1; XYZ);
deref_impl!(U4, U1; XYZW);
deref_impl!(U5, U1; XYZWA);
deref_impl!(U6, U1; XYZWAB);
deref_impl!(U1, U2; XY);
deref_impl!(U1, U3; XYZ);
deref_impl!(U1, U4; XYZW);
deref_impl!(U1, U5; XYZWA);
deref_impl!(U1, U6; XYZWAB);
deref_impl!(U2, U2; M2x2);
deref_impl!(U2, U3; M2x3);
deref_impl!(U2, U4; M2x4);
deref_impl!(U2, U5; M2x5);
deref_impl!(U2, U6; M2x6);
deref_impl!(U3, U2; M3x2);
deref_impl!(U3, U3; M3x3);
deref_impl!(U3, U4; M3x4);
deref_impl!(U3, U5; M3x5);
deref_impl!(U3, U6; M3x6);
deref_impl!(U4, U2; M4x2);
deref_impl!(U4, U3; M4x3);
deref_impl!(U4, U4; M4x4);
deref_impl!(U4, U5; M4x5);
deref_impl!(U4, U6; M4x6);
deref_impl!(U5, U2; M5x2);
deref_impl!(U5, U3; M5x3);
deref_impl!(U5, U4; M5x4);
deref_impl!(U5, U5; M5x5);
deref_impl!(U5, U6; M5x6);
deref_impl!(U6, U2; M6x2);
deref_impl!(U6, U3; M6x3);
deref_impl!(U6, U4; M6x4);
deref_impl!(U6, U5; M6x5);
deref_impl!(U6, U6; M6x6);

373
src/core/decompositions.rs Normal file
View File

@ -0,0 +1,373 @@
use std::cmp;
use alga::general::Real;
use core::{SquareMatrix, OwnedSquareMatrix, ColumnVector, OwnedColumnVector};
use dimension::{Dim, Dynamic, U1};
use storage::{Storage, OwnedStorage};
use allocator::{Allocator, OwnedAllocator};
impl<N, D: Dim, S> SquareMatrix<N, D, S>
where N: Real,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
/// Get the householder matrix corresponding to a reflexion to the hyperplane
/// defined by `vector`. It can be a reflexion contained in a subspace.
///
/// # Arguments
/// * `dimension` - the dimension of the space the resulting matrix operates in
/// * `start` - the starting dimension of the subspace of the reflexion
/// * `vector` - the vector defining the reflection.
pub fn new_householder_generic<SB, D2>(dimension: D, start: usize, vector: &ColumnVector<N, D2, SB>)
-> OwnedSquareMatrix<N, D, S::Alloc>
where D2: Dim,
SB: Storage<N, D2, U1> {
let mut qk = Self::identity_generic(dimension, dimension);
let subdim = vector.shape().0;
let stop = subdim + start;
assert!(dimension.value() >= stop, "Householder matrix creation: subspace dimension index out of bounds.");
for j in start .. stop {
for i in start .. stop {
unsafe {
let vv = *vector.get_unchecked(i - start, 0) * *vector.get_unchecked(j - start, 0);
let qkij = *qk.get_unchecked(i, j);
*qk.get_unchecked_mut(i, j) = qkij - vv - vv;
}
}
}
qk
}
}
impl<N: Real, D: Dim, S: Storage<N, D, D>> SquareMatrix<N, D, S> {
/// QR decomposition using Householder reflections.
pub fn qr(self) -> (OwnedSquareMatrix<N, D, S::Alloc>, OwnedSquareMatrix<N, D, S::Alloc>)
where S::Alloc: Allocator<N, Dynamic, U1> +
Allocator<N, D, U1> {
let (nrows, ncols) = self.data.shape();
// XXX: too restrictive.
assert!(nrows.value() >= ncols.value(), "");
let mut q = OwnedSquareMatrix::<N, D, S::Alloc>::identity_generic(nrows, ncols);
let mut r = self.into_owned();
// Temporary buffer that contains a column.
let mut col = unsafe {
OwnedColumnVector::<N, D, S::Alloc>::new_uninitialized_generic(nrows, U1)
};
for ite in 0 .. cmp::min(nrows.value() - 1, ncols.value()) {
let subdim = Dynamic::new(nrows.value() - ite);
let mut v = col.rows_mut(0, subdim.value());
v.copy_from(&r.generic_slice((ite, ite), (subdim, U1)));
let alpha =
if unsafe { *v.get_unchecked(ite, 0) } >= ::zero() {
-v.norm()
}
else {
v.norm()
};
unsafe {
let x = *v.get_unchecked(0, 0);
*v.get_unchecked_mut(0, 0) = x - alpha;
}
if !v.normalize_mut().is_zero() {
let mut qk = OwnedSquareMatrix::<N, D, S::Alloc>::new_householder_generic(nrows, ite, &v);
r = &qk * r;
// FIXME: add a method `q.mul_tr(qk) := q * qk.transpose` ?
qk.transpose_mut();
q = q * qk;
}
}
(q, r)
}
/// Eigendecomposition of a square symmetric matrix.
pub fn eig(&self, eps: N, niter: usize)
-> (OwnedSquareMatrix<N, D, S::Alloc>, OwnedColumnVector<N, D, S::Alloc>)
where S::Alloc: Allocator<N, D, U1> +
Allocator<N, Dynamic, U1> {
assert!(self.is_square(),
"Unable to compute the eigenvectors and eigenvalues of a non-square matrix.");
let dim = self.data.shape().0;
let (mut eigenvectors, mut eigenvalues) = self.hessenberg();
if dim.value() == 1 {
return (eigenvectors, eigenvalues.diagonal());
}
// Allocate arrays for Givens rotation components
let mut c = unsafe { OwnedColumnVector::<N, D, S::Alloc>::new_uninitialized_generic(dim, U1) };
let mut s = unsafe { OwnedColumnVector::<N, D, S::Alloc>::new_uninitialized_generic(dim, U1) };
let mut iter = 0;
let mut curdim = dim.value() - 1;
for _ in 0 .. dim.value() {
let mut stop = false;
while !stop && iter < niter {
let lambda;
unsafe {
let a = *eigenvalues.get_unchecked(curdim - 1, curdim - 1);
let b = *eigenvalues.get_unchecked(curdim - 1, curdim);
let c = *eigenvalues.get_unchecked(curdim, curdim - 1);
let d = *eigenvalues.get_unchecked(curdim, curdim);
let trace = a + d;
let determinant = a * d - b * c;
let constquarter: N = ::convert(0.25f64);
let consthalf: N = ::convert(0.5f64);
let e = (constquarter * trace * trace - determinant).sqrt();
let lambda1 = consthalf * trace + e;
let lambda2 = consthalf * trace - e;
if (lambda1 - d).abs() < (lambda2 - d).abs() {
lambda = lambda1;
}
else {
lambda = lambda2;
}
}
// Shift matrix
for k in 0 .. curdim + 1 {
unsafe {
let a = *eigenvalues.get_unchecked(k, k);
*eigenvalues.get_unchecked_mut(k, k) = a - lambda;
}
}
// Givens rotation from left
for k in 0 .. curdim {
let x_i = unsafe { *eigenvalues.get_unchecked(k, k) };
let x_j = unsafe { *eigenvalues.get_unchecked(k + 1, k) };
let ctmp;
let stmp;
if x_j.abs() < eps {
ctmp = N::one();
stmp = N::zero();
}
else if x_i.abs() < eps {
ctmp = N::zero();
stmp = -N::one();
}
else {
let r = x_i.hypot(x_j);
ctmp = x_i / r;
stmp = -x_j / r;
}
c[k] = ctmp;
s[k] = stmp;
for j in k .. (curdim + 1) {
unsafe {
let a = *eigenvalues.get_unchecked(k, j);
let b = *eigenvalues.get_unchecked(k + 1, j);
*eigenvalues.get_unchecked_mut(k, j) = ctmp * a - stmp * b;
*eigenvalues.get_unchecked_mut(k + 1, j) = stmp * a + ctmp * b;
}
}
}
// Givens rotation from right applied to eigenvalues
for k in 0 .. curdim {
for i in 0 .. (k + 2) {
unsafe {
let a = *eigenvalues.get_unchecked(i, k);
let b = *eigenvalues.get_unchecked(i, k + 1);
*eigenvalues.get_unchecked_mut(i, k) = c[k] * a - s[k] * b;
*eigenvalues.get_unchecked_mut(i, k + 1) = s[k] * a + c[k] * b;
}
}
}
// Shift back
for k in 0 .. curdim + 1 {
unsafe {
let a = *eigenvalues.get_unchecked(k, k);
*eigenvalues.get_unchecked_mut(k, k) = a + lambda;
}
}
// Givens rotation from right applied to eigenvectors
for k in 0 .. curdim {
for i in 0 .. dim.value() {
unsafe {
let a = *eigenvectors.get_unchecked(i, k);
let b = *eigenvectors.get_unchecked(i, k + 1);
*eigenvectors.get_unchecked_mut(i, k) = c[k] * a - s[k] * b;
*eigenvectors.get_unchecked_mut(i, k + 1) = s[k] * a + c[k] * b;
}
}
}
iter = iter + 1;
stop = true;
for j in 0 .. curdim {
// Check last row.
if unsafe { *eigenvalues.get_unchecked(curdim, j) }.abs() >= eps {
stop = false;
break;
}
// Check last column.
if unsafe { *eigenvalues.get_unchecked(j, curdim) }.abs() >= eps {
stop = false;
break;
}
}
}
if stop {
if curdim > 1 {
curdim = curdim - 1;
}
else {
break;
}
}
}
(eigenvectors, eigenvalues.diagonal())
}
/// Cholesky decomposition G of a square symmetric positive definite matrix A, such that A = G * G^T
///
/// Matrix symmetricness is not checked. Returns `None` if `self` is not definite positive.
#[inline]
pub fn cholesky(&self) -> Result<OwnedSquareMatrix<N, D, S::Alloc>, &'static str> {
let out = self.transpose();
if !out.relative_eq(self, N::default_epsilon(), N::default_max_relative()) {
return Err("Cholesky: Input matrix is not symmetric");
}
self.do_cholesky(out)
}
/// Cholesky decomposition G of a square symmetric positive definite matrix A, such that A = G * G^T
#[inline]
pub fn cholesky_unchecked(&self) -> Result<OwnedSquareMatrix<N, D, S::Alloc>, &'static str> {
let out = self.transpose();
self.do_cholesky(out)
}
#[inline(always)]
fn do_cholesky(&self, mut out: OwnedSquareMatrix<N, D, S::Alloc>)
-> Result<OwnedSquareMatrix<N, D, S::Alloc>, &'static str> {
assert!(self.is_square(), "The input matrix must be square.");
for i in 0 .. out.nrows() {
for j in 0 .. (i + 1) {
let mut sum = out[(i, j)];
for k in 0 .. j {
sum = sum - out[(i, k)] * out[(j, k)];
}
if i > j {
out[(i, j)] = sum / out[(j, j)];
}
else if sum > N::zero() {
out[(i, i)] = sum.sqrt();
}
else {
return Err("Cholesky: Input matrix is not positive definite to machine precision.");
}
}
}
for i in 0 .. out.nrows() {
for j in i + 1 .. out.ncols() {
out[(i, j)] = N::zero();
}
}
Ok(out)
}
/// Hessenberg
/// Returns the matrix `self` in Hessenberg form and the corresponding similarity transformation
///
/// # Returns
/// The tuple (`q`, `h`) that `q * h * q^T = self`
pub fn hessenberg(&self) -> (OwnedSquareMatrix<N, D, S::Alloc>, OwnedSquareMatrix<N, D, S::Alloc>)
where S::Alloc: Allocator<N, D, U1> + Allocator<N, Dynamic, U1> {
let (nrows, ncols) = self.data.shape();
let mut h = self.clone_owned();
let mut q = OwnedSquareMatrix::<N, D, S::Alloc>::identity_generic(nrows, ncols);
if ncols.value() <= 2 {
return (q, h);
}
// Temporary buffer that contains a column.
let mut col = unsafe {
OwnedColumnVector::<N, D, S::Alloc>::new_uninitialized_generic(nrows, U1)
};
for ite in 0 .. (ncols.value() - 2) {
let subdim = Dynamic::new(nrows.value() - (ite + 1));
let mut v = col.rows_mut(0, subdim.value());
v.copy_from(&h.generic_slice((ite + 1, ite), (subdim, U1)));
let alpha = v.norm();
unsafe {
let x = *v.get_unchecked(0, 0);
*v.get_unchecked_mut(0, 0) = x - alpha;
}
if !v.normalize_mut().is_zero() {
// XXX: we output the householder matrix to a pre-allocated matrix instead of
// return a value to `p`. This would avoid allocation at each iteration.
let p = OwnedSquareMatrix::<N, D, S::Alloc>::new_householder_generic(nrows, ite + 1, &v);
q = q * &p;
h = &p * h * p;
}
}
(q, h)
}
}

View File

@ -0,0 +1,109 @@
//! The default matrix data storage allocator.
//!
//! This will use stack-allocated buffers for matrices with dimensions known at compile-time, and
//! heap-allocated buffers for matrices with at least one dimension unknown at compile-time.
use std::mem;
use std::ops::Mul;
use typenum::Prod;
use generic_array::ArrayLength;
use core::Scalar;
use core::dimension::{Dim, DimName, Dynamic};
use core::allocator::Allocator;
use core::matrix_array::MatrixArray;
use core::matrix_vec::MatrixVec;
/*
*
* Allocator.
*
*/
/// An allocator based on `GenericArray` and `MatrixVec` for statically-sized and dynamically-sized
/// matrices respectively.
pub struct DefaultAllocator;
// Static - Static
impl<N, R, C> Allocator<N, R, C> for DefaultAllocator
where N: Scalar,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
type Buffer = MatrixArray<N, R, C>;
#[inline]
unsafe fn allocate_uninitialized(_: R, _: C) -> Self::Buffer {
mem::uninitialized()
}
#[inline]
fn allocate_from_iterator<I: IntoIterator<Item = N>>(nrows: R, ncols: C, iter: I) -> Self::Buffer {
let mut res = unsafe { Self::allocate_uninitialized(nrows, ncols) };
let mut count = 0;
for (res, e) in res.iter_mut().zip(iter.into_iter()) {
*res = e;
count += 1;
}
assert!(count == nrows.value() * ncols.value(),
"Matrix init. from iterator: iterator not long enough.");
res
}
}
// Dynamic - Static
// Dynamic - Dynamic
impl<N: Scalar, C: Dim> Allocator<N, Dynamic, C> for DefaultAllocator {
type Buffer = MatrixVec<N, Dynamic, C>;
#[inline]
unsafe fn allocate_uninitialized(nrows: Dynamic, ncols: C) -> Self::Buffer {
let mut res = Vec::new();
let length = nrows.value() * ncols.value();
res.reserve_exact(length);
res.set_len(length);
MatrixVec::new(nrows, ncols, res)
}
#[inline]
fn allocate_from_iterator<I: IntoIterator<Item = N>>(nrows: Dynamic, ncols: C, iter: I) -> Self::Buffer {
let it = iter.into_iter();
let res: Vec<N> = it.collect();
assert!(res.len() == nrows.value() * ncols.value(),
"Allocation from iterator error: the iterator did not yield the correct number of elements.");
MatrixVec::new(nrows, ncols, res)
}
}
// Static - Dynamic
impl<N: Scalar, R: DimName> Allocator<N, R, Dynamic> for DefaultAllocator {
type Buffer = MatrixVec<N, R, Dynamic>;
#[inline]
unsafe fn allocate_uninitialized(nrows: R, ncols: Dynamic) -> Self::Buffer {
let mut res = Vec::new();
let length = nrows.value() * ncols.value();
res.reserve_exact(length);
res.set_len(length);
MatrixVec::new(nrows, ncols, res)
}
#[inline]
fn allocate_from_iterator<I: IntoIterator<Item = N>>(nrows: R, ncols: Dynamic, iter: I) -> Self::Buffer {
let it = iter.into_iter();
let res: Vec<N> = it.collect();
assert!(res.len() == nrows.value() * ncols.value(),
"Allocation from iterator error: the iterator did not yield the correct number of elements.");
MatrixVec::new(nrows, ncols, res)
}
}

56
src/core/determinant.rs Normal file
View File

@ -0,0 +1,56 @@
use num::One;
use alga::general::{ClosedMul, ClosedSub, ClosedAdd};
use core::{Scalar, SquareMatrix};
use core::dimension::Dim;
use core::storage::Storage;
impl<N, D: Dim, S> SquareMatrix<N, D, S>
where N: Scalar + One + ClosedMul + ClosedAdd + ClosedSub,
S: Storage<N, D, D> {
/// This matrix determinant.
#[inline]
pub fn determinant(&self) -> N {
assert!(self.is_square(), "Unable to invert a non-square matrix.");
let dim = self.shape().0;
unsafe {
match dim {
0 => N::one(),
1 => {
*self.get_unchecked(0, 0)
},
2 => {
let m11 = *self.get_unchecked(0, 0); let m12 = *self.get_unchecked(0, 1);
let m21 = *self.get_unchecked(1, 0); let m22 = *self.get_unchecked(1, 1);
m11 * m22 - m21 * m12
},
3 => {
let m11 = *self.get_unchecked(0, 0);
let m12 = *self.get_unchecked(0, 1);
let m13 = *self.get_unchecked(0, 2);
let m21 = *self.get_unchecked(1, 0);
let m22 = *self.get_unchecked(1, 1);
let m23 = *self.get_unchecked(1, 2);
let m31 = *self.get_unchecked(2, 0);
let m32 = *self.get_unchecked(2, 1);
let m33 = *self.get_unchecked(2, 2);
let minor_m12_m23 = m22 * m33 - m32 * m23;
let minor_m11_m23 = m21 * m33 - m31 * m23;
let minor_m11_m22 = m21 * m32 - m31 * m22;
m11 * minor_m12_m23 - m12 * minor_m11_m23 + m13 * minor_m11_m22
},
_ => {
unimplemented!()
}
}
}
}
}

360
src/core/dimension.rs Normal file
View File

@ -0,0 +1,360 @@
#![allow(missing_docs)]
//! Traits and tags for identifying the dimension of all algebraic entities.
use std::fmt::Debug;
use std::any::Any;
use std::ops::{Add, Sub, Mul, Div};
use typenum::{self, Unsigned, UInt, B1, Bit, UTerm, Sum, Prod, Diff, Quot};
/// Dim of dynamically-sized algebraic entities.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct Dynamic {
value: usize
}
impl Dynamic {
/// A dynamic size equal to `value`.
#[inline]
pub fn new(value: usize) -> Dynamic {
Dynamic {
value: value
}
}
}
/// Trait implemented by `Dynamic`.
pub trait IsDynamic { }
/// Trait implemented by `Dynamic` and type-level integers different from `U1`.
pub trait IsNotStaticOne { }
impl IsDynamic for Dynamic { }
impl IsNotStaticOne for Dynamic { }
/// Trait implemented by any type that can be used as a dimension. This includes type-level
/// integers and `Dynamic` (for dimensions not known at compile-time).
pub trait Dim: Any + Debug + Copy + PartialEq + Send {
/// Gets the compile-time value of `Self`. Returns `None` if it is not known, i.e., if `Self =
/// Dynamic`.
fn try_to_usize() -> Option<usize>;
/// Gets the run-time value of `self`. For type-level integers, this is the same as
/// `Self::try_to_usize().unwrap()`.
fn value(&self) -> usize;
/// Builds an instance of `Self` from a run-time value. Panics if `Self` is a type-level
/// integer and `dim != Self::try_to_usize().unwrap()`.
fn from_usize(dim: usize) -> Self;
}
impl Dim for Dynamic {
#[inline]
fn try_to_usize() -> Option<usize> {
None
}
#[inline]
fn from_usize(dim: usize) -> Self {
Dynamic::new(dim)
}
#[inline]
fn value(&self) -> usize {
self.value
}
}
/*
*
* Operations.
*
*/
macro_rules! dim_ops(
($($DimOp: ident, $DimNameOp: ident,
$Op: ident, $op: ident,
$DimResOp: ident, $DimNameResOp: ident,
$ResOp: ident);* $(;)*) => {$(
pub type $DimResOp<D1, D2> = <D1 as $DimOp<D2>>::Output;
pub trait $DimOp<D: Dim>: Dim {
type Output: Dim;
fn $op(self, other: D) -> Self::Output;
}
impl<D1: DimName, D2: DimName> $DimOp<D2> for D1
where D1::Value: $Op<D2::Value>,
$ResOp<D1::Value, D2::Value>: NamedDim {
type Output = <$ResOp<D1::Value, D2::Value> as NamedDim>::Name;
#[inline]
fn $op(self, _: D2) -> Self::Output {
Self::Output::name()
}
}
impl<D: Dim> $DimOp<D> for Dynamic {
type Output = Dynamic;
#[inline]
fn $op(self, other: D) -> Dynamic {
Dynamic::new(self.value.$op(other.value()))
}
}
impl<D: DimName> $DimOp<Dynamic> for D {
type Output = Dynamic;
#[inline]
fn $op(self, other: Dynamic) -> Dynamic {
Dynamic::new(self.value().$op(other.value))
}
}
pub type $DimNameResOp<D1, D2> = <D1 as $DimNameOp<D2>>::Output;
pub trait $DimNameOp<D: DimName>: DimName {
type Output: DimName;
fn $op(self, other: D) -> Self::Output;
}
impl<D1: DimName, D2: DimName> $DimNameOp<D2> for D1
where D1::Value: $Op<D2::Value>,
$ResOp<D1::Value, D2::Value>: NamedDim {
type Output = <$ResOp<D1::Value, D2::Value> as NamedDim>::Name;
#[inline]
fn $op(self, _: D2) -> Self::Output {
Self::Output::name()
}
}
)*}
);
dim_ops!(
DimAdd, DimNameAdd, Add, add, DimSum, DimNameSum, Sum;
DimMul, DimNameMul, Mul, mul, DimProd, DimNameProd, Prod;
DimSub, DimNameSub, Sub, sub, DimDiff, DimNameDiff, Diff;
DimDiv, DimNameDiv, Div, div, DimQuot, DimNameQuot, Quot;
);
/// Trait implemented exclusively by type-level integers.
pub trait DimName: Dim {
type Value: NamedDim<Name = Self>;
/// The name of this dimension, i.e., the singleton `Self`.
#[inline]
fn name() -> Self;
// FIXME: this is not a very idiomatic name.
/// The value of this dimension.
#[inline]
fn dim() -> usize {
Self::Value::to_usize()
}
}
pub trait NamedDim: Sized + Any + Unsigned {
type Name: DimName<Value = Self>;
}
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct U1;
impl Dim for U1 {
#[inline]
fn try_to_usize() -> Option<usize> {
Some(1)
}
#[inline]
fn from_usize(dim: usize) -> Self {
assert!(dim == 1, "Mismatched dimension.");
U1
}
#[inline]
fn value(&self) -> usize {
1
}
}
impl DimName for U1 {
type Value = typenum::U1;
#[inline]
fn name() -> Self {
U1
}
}
impl NamedDim for typenum::U1{
type Name = U1;
}
macro_rules! named_dimension(
($($D: ident),* $(,)*) => {$(
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct $D;
impl Dim for $D {
#[inline]
fn try_to_usize() -> Option<usize> {
Some(typenum::$D::to_usize())
}
#[inline]
fn from_usize(dim: usize) -> Self {
assert!(dim == typenum::$D::to_usize(), "Mismatched dimension.");
$D
}
#[inline]
fn value(&self) -> usize {
typenum::$D::to_usize()
}
}
impl DimName for $D {
type Value = typenum::$D;
#[inline]
fn name() -> Self {
$D
}
}
impl NamedDim for typenum::$D {
type Name = $D;
}
impl IsNotStaticOne for $D { }
)*}
);
// We give explicit names to all Unsigned in [0, 128[
named_dimension!(
U0, /*U1,*/ U2, U3, U4, U5, U6, U7, U8, U9,
U10, U11, U12, U13, U14, U15, U16, U17, U18, U19,
U20, U21, U22, U23, U24, U25, U26, U27, U28, U29,
U30, U31, U32, U33, U34, U35, U36, U37, U38, U39,
U40, U41, U42, U43, U44, U45, U46, U47, U48, U49,
U50, U51, U52, U53, U54, U55, U56, U57, U58, U59,
U60, U61, U62, U63, U64, U65, U66, U67, U68, U69,
U70, U71, U72, U73, U74, U75, U76, U77, U78, U79,
U80, U81, U82, U83, U84, U85, U86, U87, U88, U89,
U90, U91, U92, U93, U94, U95, U96, U97, U98, U99,
U100, U101, U102, U103, U104, U105, U106, U107, U108, U109,
U110, U111, U112, U113, U114, U115, U116, U117, U118, U119,
U120, U121, U122, U123, U124, U125, U126, U127
);
// For values greater than U1023, just use the typenum binary representation directly.
impl<A: Bit + Any + Debug + Copy + PartialEq + Send,
B: Bit + Any + Debug + Copy + PartialEq + Send,
C: Bit + Any + Debug + Copy + PartialEq + Send,
D: Bit + Any + Debug + Copy + PartialEq + Send,
E: Bit + Any + Debug + Copy + PartialEq + Send,
F: Bit + Any + Debug + Copy + PartialEq + Send,
G: Bit + Any + Debug + Copy + PartialEq + Send>
NamedDim
for UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, A>, B>, C>, D>, E>, F>, G> {
type Name = Self;
}
impl<A: Bit + Any + Debug + Copy + PartialEq + Send,
B: Bit + Any + Debug + Copy + PartialEq + Send,
C: Bit + Any + Debug + Copy + PartialEq + Send,
D: Bit + Any + Debug + Copy + PartialEq + Send,
E: Bit + Any + Debug + Copy + PartialEq + Send,
F: Bit + Any + Debug + Copy + PartialEq + Send,
G: Bit + Any + Debug + Copy + PartialEq + Send>
Dim
for UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, A>, B>, C>, D>, E>, F>, G> {
#[inline]
fn try_to_usize() -> Option<usize> {
Some(Self::to_usize())
}
#[inline]
fn from_usize(dim: usize) -> Self {
assert!(dim == Self::to_usize(), "Mismatched dimension.");
Self::new()
}
#[inline]
fn value(&self) -> usize {
Self::to_usize()
}
}
impl<A: Bit + Any + Debug + Copy + PartialEq + Send,
B: Bit + Any + Debug + Copy + PartialEq + Send,
C: Bit + Any + Debug + Copy + PartialEq + Send,
D: Bit + Any + Debug + Copy + PartialEq + Send,
E: Bit + Any + Debug + Copy + PartialEq + Send,
F: Bit + Any + Debug + Copy + PartialEq + Send,
G: Bit + Any + Debug + Copy + PartialEq + Send>
DimName
for UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, A>, B>, C>, D>, E>, F>, G> {
type Value = Self;
#[inline]
fn name() -> Self {
Self::new()
}
}
impl<A: Bit + Any + Debug + Copy + PartialEq + Send,
B: Bit + Any + Debug + Copy + PartialEq + Send,
C: Bit + Any + Debug + Copy + PartialEq + Send,
D: Bit + Any + Debug + Copy + PartialEq + Send,
E: Bit + Any + Debug + Copy + PartialEq + Send,
F: Bit + Any + Debug + Copy + PartialEq + Send,
G: Bit + Any + Debug + Copy + PartialEq + Send>
IsNotStaticOne
for UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, A>, B>, C>, D>, E>, F>, G> {
}
impl<U: Unsigned + DimName, B: Bit + Any + Debug + Copy + PartialEq + Send> NamedDim for UInt<U, B> {
type Name = UInt<U, B>;
}
impl<U: Unsigned + DimName, B: Bit + Any + Debug + Copy + PartialEq + Send> Dim for UInt<U, B> {
#[inline]
fn try_to_usize() -> Option<usize> {
Some(Self::to_usize())
}
#[inline]
fn from_usize(dim: usize) -> Self {
assert!(dim == Self::to_usize(), "Mismatched dimension.");
Self::new()
}
#[inline]
fn value(&self) -> usize {
Self::to_usize()
}
}
impl<U: Unsigned + DimName, B: Bit + Any + Debug + Copy + PartialEq + Send> DimName for UInt<U, B> {
type Value = UInt<U, B>;
#[inline]
fn name() -> Self {
Self::new()
}
}
impl<U: Unsigned + DimName, B: Bit + Any + Debug + Copy + PartialEq + Send> IsNotStaticOne for UInt<U, B> {
}

19
src/core/helper.rs Normal file
View File

@ -0,0 +1,19 @@
#[cfg(feature="arbitrary")]
use quickcheck::{Arbitrary, Gen};
use rand::{Rand, Rng};
/// Simple helper function for rejection sampling
#[cfg(feature="arbitrary")]
#[doc(hidden)]
#[inline]
pub fn reject<G: Gen, F: FnMut(&T) -> bool, T: Arbitrary>(g: &mut G, f: F) -> T {
use std::iter;
iter::repeat(()).map(|_| Arbitrary::arbitrary(g)).find(f).unwrap()
}
#[doc(hidden)]
#[inline]
pub fn reject_rand<G: Rng, F: FnMut(&T) -> bool, T: Rand>(g: &mut G, f: F) -> T {
use std::iter;
iter::repeat(()).map(|_| Rand::rand(g)).find(f).unwrap()
}

202
src/core/inverse.rs Normal file
View File

@ -0,0 +1,202 @@
use approx::ApproxEq;
use alga::general::Field;
use core::{Scalar, Matrix, SquareMatrix, OwnedSquareMatrix};
use core::dimension::Dim;
use core::storage::{Storage, StorageMut};
impl<N, D: Dim, S> SquareMatrix<N, D, S>
where N: Scalar + Field + ApproxEq,
S: Storage<N, D, D> {
/// Attempts to invert this matrix.
#[inline]
pub fn try_inverse(self) -> Option<OwnedSquareMatrix<N, D, S::Alloc>> {
let mut res = self.into_owned();
if res.shape().0 <= 3 {
if res.try_inverse_mut() {
Some(res)
}
else {
None
}
}
else {
gauss_jordan_inverse(res)
}
}
}
impl<N, D: Dim, S> SquareMatrix<N, D, S>
where N: Scalar + Field + ApproxEq,
S: StorageMut<N, D, D> {
/// Attempts to invert this matrix in-place. Returns `false` and leaves `self` untouched if
/// inversion fails.
#[inline]
pub fn try_inverse_mut(&mut self) -> bool {
assert!(self.is_square(), "Unable to invert a non-square matrix.");
let dim = self.shape().0;
unsafe {
match dim {
0 => true,
1 => {
if relative_eq!(self.get_unchecked(0, 0), &N::zero()) {
false
}
else {
*self.get_unchecked_mut(0, 0) = N::one() / self.determinant();
true
}
},
2 => {
let determinant = self.determinant();
if relative_eq!(&determinant, &N::zero()) {
false
}
else {
let m11 = *self.get_unchecked(0, 0); let m12 = *self.get_unchecked(0, 1);
let m21 = *self.get_unchecked(1, 0); let m22 = *self.get_unchecked(1, 1);
*self.get_unchecked_mut(0, 0) = m22 / determinant;
*self.get_unchecked_mut(0, 1) = -m12 / determinant;
*self.get_unchecked_mut(1, 0) = -m21 / determinant;
*self.get_unchecked_mut(1, 1) = m11 / determinant;
true
}
},
3 => {
let m11 = *self.get_unchecked(0, 0);
let m12 = *self.get_unchecked(0, 1);
let m13 = *self.get_unchecked(0, 2);
let m21 = *self.get_unchecked(1, 0);
let m22 = *self.get_unchecked(1, 1);
let m23 = *self.get_unchecked(1, 2);
let m31 = *self.get_unchecked(2, 0);
let m32 = *self.get_unchecked(2, 1);
let m33 = *self.get_unchecked(2, 2);
let minor_m12_m23 = m22 * m33 - m32 * m23;
let minor_m11_m23 = m21 * m33 - m31 * m23;
let minor_m11_m22 = m21 * m32 - m31 * m22;
let determinant = m11 * minor_m12_m23 -
m12 * minor_m11_m23 +
m13 * minor_m11_m22;
if relative_eq!(&determinant, &N::zero()) {
false
}
else {
*self.get_unchecked_mut(0, 0) = minor_m12_m23 / determinant;
*self.get_unchecked_mut(0, 1) = (m13 * m32 - m33 * m12) / determinant;
*self.get_unchecked_mut(0, 2) = (m12 * m23 - m22 * m13) / determinant;
*self.get_unchecked_mut(1, 0) = -minor_m11_m23 / determinant;
*self.get_unchecked_mut(1, 1) = (m11 * m33 - m31 * m13) / determinant;
*self.get_unchecked_mut(1, 2) = (m13 * m21 - m23 * m11) / determinant;
*self.get_unchecked_mut(2, 0) = minor_m11_m22 / determinant;
*self.get_unchecked_mut(2, 1) = (m12 * m31 - m32 * m11) / determinant;
*self.get_unchecked_mut(2, 2) = (m11 * m22 - m21 * m12) / determinant;
true
}
},
_ => {
let oself = self.clone_owned();
if let Some(res) = gauss_jordan_inverse(oself) {
self.copy_from(&res);
true
}
else {
false
}
}
}
}
}
}
/// Inverts the given matrix using Gauss-Jordan Ellimitation.
fn gauss_jordan_inverse<N, D, S>(mut matrix: SquareMatrix<N, D, S>) -> Option<OwnedSquareMatrix<N, D, S::Alloc>>
where D: Dim,
N: Scalar + Field + ApproxEq,
S: StorageMut<N, D, D> {
assert!(matrix.is_square(), "Unable to invert a non-square matrix.");
let dim = matrix.data.shape().0;
let mut res: OwnedSquareMatrix<N, D, S::Alloc> = Matrix::identity_generic(dim, dim);
let dim = dim.value();
unsafe {
for k in 0 .. dim {
// Search a non-zero value on the k-th column.
// FIXME: would it be worth it to spend some more time searching for the
// max instead?
let mut n0 = k; // index of a non-zero entry.
while n0 != dim {
if !matrix.get_unchecked(n0, k).is_zero() {
break;
}
n0 += 1;
}
if n0 == dim {
return None
}
// Swap pivot line.
if n0 != k {
for j in 0 .. dim {
matrix.swap_unchecked((n0, j), (k, j));
res.swap_unchecked((n0, j), (k, j));
}
}
let pivot = *matrix.get_unchecked(k, k);
for j in k .. dim {
let selfval = *matrix.get_unchecked(k, j) / pivot;
*matrix.get_unchecked_mut(k, j) = selfval;
}
for j in 0 .. dim {
let resval = *res.get_unchecked(k, j) / pivot;
*res.get_unchecked_mut(k, j) = resval;
}
for l in 0 .. dim {
if l != k {
let normalizer = *matrix.get_unchecked(l, k);
for j in k .. dim {
let selfval = *matrix.get_unchecked(l, j) - *matrix.get_unchecked(k, j) * normalizer;
*matrix.get_unchecked_mut(l, j) = selfval;
}
for j in 0 .. dim {
let resval = *res.get_unchecked(l, j) - *res.get_unchecked(k, j) * normalizer;
*res.get_unchecked_mut(l, j) = resval;
}
}
}
}
Some(res)
}
}

88
src/core/iter.rs Normal file
View File

@ -0,0 +1,88 @@
//! Matrix iterators.
use std::marker::PhantomData;
use std::mem;
use core::Scalar;
use core::dimension::Dim;
use core::storage::{Storage, StorageMut};
macro_rules! iterator {
(struct $Name:ident for $Storage:ident.$ptr: ident -> $Ptr:ty, $Ref:ty, $SRef: ty) => {
/// An iterator through a dense matrix with arbitrary strides matrix.
pub struct $Name<'a, N: Scalar, R: Dim, C: Dim, S: 'a + $Storage<N, R, C>> {
ptr: $Ptr,
inner_ptr: $Ptr,
inner_end: $Ptr,
size: usize, // We can't use an end pointer here because a stride might be zero.
strides: (S::RStride, S::CStride),
_phantoms: PhantomData<($Ref, R, C, S)>
}
// FIXME: we need to specialize for the case where the matrix storage is owned (in which
// case the iterator is trivial because it does not have any stride).
impl<'a, N: Scalar, R: Dim, C: Dim, S: 'a + $Storage<N, R, C>> $Name<'a, N, R, C, S> {
/// Creates a new iterator for the given matrix storage.
pub fn new(storage: $SRef) -> $Name<'a, N, R, C, S> {
let shape = storage.shape();
let strides = storage.strides();
let inner_offset = shape.0.value() * strides.0.value();
let ptr = storage.$ptr();
$Name {
ptr: ptr,
inner_ptr: ptr,
inner_end: unsafe { ptr.offset(inner_offset as isize) },
size: shape.0.value() * shape.1.value(),
strides: strides,
_phantoms: PhantomData
}
}
}
impl<'a, N: Scalar, R: Dim, C: Dim, S: 'a + $Storage<N, R, C>> Iterator for $Name<'a, N, R, C, S> {
type Item = $Ref;
#[inline]
fn next(&mut self) -> Option<$Ref> {
unsafe {
if self.size == 0 {
None
} else {
self.size -= 1;
// Jump to the next outer dimension if needed.
if self.ptr == self.inner_end {
let stride = self.strides.1.value() as isize;
self.inner_end = self.ptr.offset(stride);
self.ptr = self.inner_ptr.offset(stride);
self.inner_ptr = self.ptr;
}
// Go to the next element.
let old = self.ptr;
let stride = self.strides.0.value() as isize;
self.ptr = self.ptr.offset(stride);
Some(mem::transmute(old))
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.size, Some(self.size))
}
#[inline]
fn count(self) -> usize {
self.size_hint().0
}
}
}
}
iterator!(struct MatrixIter for Storage.ptr -> *const N, &'a N, &'a S);
iterator!(struct MatrixIterMut for StorageMut.ptr_mut -> *mut N, &'a mut N, &'a mut S);

1087
src/core/matrix.rs Normal file

File diff suppressed because it is too large Load Diff

788
src/core/matrix_alga.rs Normal file
View File

@ -0,0 +1,788 @@
use num::{Zero, One};
use alga::general::{AbstractMagma, AbstractGroupAbelian, AbstractGroup, AbstractLoop,
AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, AbstractModule,
Module, Field, RingCommutative, Real, Inverse, Additive, Multiplicative,
MeetSemilattice, JoinSemilattice, Lattice, Identity,
ClosedAdd, ClosedNeg, ClosedMul};
use alga::linear::{VectorSpace, NormedSpace, InnerSpace, FiniteDimVectorSpace, FiniteDimInnerSpace};
use core::{Scalar, Matrix, SquareMatrix};
use core::dimension::{Dim, DimName};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
/*
*
* Additive structures.
*
*/
impl<N, R: DimName, C: DimName, S> Identity<Additive> for Matrix<N, R, C, S>
where N: Scalar + Zero,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn identity() -> Self {
Self::from_element(N::zero())
}
}
impl<N, R: DimName, C: DimName, S> AbstractMagma<Additive> for Matrix<N, R, C, S>
where N: Scalar + ClosedAdd,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn operate(&self, other: &Self) -> Self {
self + other
}
}
impl<N, R: DimName, C: DimName, S> Inverse<Additive> for Matrix<N, R, C, S>
where N: Scalar + ClosedNeg,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn inverse(&self) -> Matrix<N, R, C, S> {
-self
}
#[inline]
fn inverse_mut(&mut self) {
*self = -self.clone()
}
}
macro_rules! inherit_additive_structure(
($($marker: ident<$operator: ident> $(+ $bounds: ident)*),* $(,)*) => {$(
impl<N, R: DimName, C: DimName, S> $marker<$operator> for Matrix<N, R, C, S>
where N: Scalar + $marker<$operator> $(+ $bounds)*,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> { }
)*}
);
inherit_additive_structure!(
AbstractSemigroup<Additive> + ClosedAdd,
AbstractMonoid<Additive> + Zero + ClosedAdd,
AbstractQuasigroup<Additive> + ClosedAdd + ClosedNeg,
AbstractLoop<Additive> + Zero + ClosedAdd + ClosedNeg,
AbstractGroup<Additive> + Zero + ClosedAdd + ClosedNeg,
AbstractGroupAbelian<Additive> + Zero + ClosedAdd + ClosedNeg
);
impl<N, R: DimName, C: DimName, S> AbstractModule for Matrix<N, R, C, S>
where N: Scalar + RingCommutative,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
type AbstractRing = N;
#[inline]
fn multiply_by(&self, n: N) -> Self {
self * n
}
}
impl<N, R: DimName, C: DimName, S> Module for Matrix<N, R, C, S>
where N: Scalar + RingCommutative,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
type Ring = N;
}
impl<N, R: DimName, C: DimName, S> VectorSpace for Matrix<N, R, C, S>
where N: Scalar + Field,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
type Field = N;
}
impl<N, R: DimName, C: DimName, S> FiniteDimVectorSpace for Matrix<N, R, C, S>
where N: Scalar + Field,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn dimension() -> usize {
R::dim() * C::dim()
}
#[inline]
fn canonical_basis_element(i: usize) -> Self {
assert!(i < Self::dimension(), "Index out of bound.");
let mut res = Self::zero();
unsafe { *res.data.get_unchecked_linear_mut(i) = N::one(); }
res
}
#[inline]
fn dot(&self, other: &Self) -> N {
self.dot(other)
}
#[inline]
unsafe fn component_unchecked(&self, i: usize) -> &N {
self.data.get_unchecked_linear(i)
}
#[inline]
unsafe fn component_unchecked_mut(&mut self, i: usize) -> &mut N {
self.data.get_unchecked_linear_mut(i)
}
}
impl<N, R: DimName, C: DimName, S> NormedSpace for Matrix<N, R, C, S>
where N: Real,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn norm_squared(&self) -> N {
self.norm_squared()
}
#[inline]
fn norm(&self) -> N {
self.norm()
}
#[inline]
fn normalize(&self) -> Self {
self.normalize()
}
#[inline]
fn normalize_mut(&mut self) -> N {
self.normalize_mut()
}
#[inline]
fn try_normalize(&self, min_norm: N) -> Option<Self> {
self.try_normalize(min_norm)
}
#[inline]
fn try_normalize_mut(&mut self, min_norm: N) -> Option<N> {
self.try_normalize_mut(min_norm)
}
}
impl<N, R: DimName, C: DimName, S> InnerSpace for Matrix<N, R, C, S>
where N: Real,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
type Real = N;
#[inline]
fn angle(&self, other: &Self) -> N {
self.angle(other)
}
#[inline]
fn inner_product(&self, other: &Self) -> N {
self.dot(other)
}
}
// FIXME: specialization will greatly simplify this implementation in the future.
// In particular:
// use `x()` instead of `::canonical_basis_element`
// use `::new(x, y, z)` instead of `::from_slice`
impl<N, R: DimName, C: DimName, S> FiniteDimInnerSpace for Matrix<N, R, C, S>
where N: Real,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn orthonormalize(vs: &mut [Matrix<N, R, C, S>]) -> usize {
let mut nbasis_elements = 0;
for i in 0 .. vs.len() {
{
let (elt, basis) = vs[.. i + 1].split_last_mut().unwrap();
for basis_element in &basis[.. nbasis_elements] {
*elt -= &*basis_element * elt.dot(basis_element)
}
}
if vs[i].try_normalize_mut(N::zero()).is_some() {
// FIXME: this will be efficient on dynamically-allocated vectors but for
// statically-allocated ones, `.clone_from` would be better.
vs.swap(nbasis_elements, i);
nbasis_elements += 1;
// All the other vectors will be dependent.
if nbasis_elements == Self::dimension() {
break;
}
}
}
nbasis_elements
}
#[inline]
fn orthonormal_subspace_basis<F>(vs: &[Self], mut f: F)
where F: FnMut(&Self) -> bool {
// FIXME: is this necessary?
assert!(vs.len() <= Self::dimension(), "The given set of vectors has no chance of being a free family.");
match Self::dimension() {
1 => {
if vs.len() == 0 {
f(&Self::canonical_basis_element(0));
}
},
2 => {
if vs.len() == 0 {
let _ = f(&Self::canonical_basis_element(0)) &&
f(&Self::canonical_basis_element(1));
}
else if vs.len() == 1 {
let v = &vs[0];
let res = Self::from_column_slice(&[-v[1], v[0]]);
f(&res.normalize());
}
// Otherwise, nothing.
},
3 => {
if vs.len() == 0 {
let _ = f(&Self::canonical_basis_element(0)) &&
f(&Self::canonical_basis_element(1)) &&
f(&Self::canonical_basis_element(2));
}
else if vs.len() == 1 {
let v = &vs[0];
let mut a;
if v[0].abs() > v[1].abs() {
a = Self::from_column_slice(&[v[2], N::zero(), -v[0]]);
}
else {
a = Self::from_column_slice(&[N::zero(), -v[2], v[1]]);
};
let _ = a.normalize_mut();
if f(&a.cross(v)) {
f(&a);
}
}
else if vs.len() == 2 {
f(&vs[0].cross(&vs[1]).normalize());
}
},
_ => {
// XXX: use a GenericArray instead.
let mut known_basis = Vec::new();
for v in vs.iter() {
known_basis.push(v.normalize())
}
for i in 0 .. Self::dimension() - vs.len() {
let mut elt = Self::canonical_basis_element(i);
for v in &known_basis {
elt -= v * elt.dot(v)
};
if let Some(subsp_elt) = elt.try_normalize(N::zero()) {
if !f(&subsp_elt) { return };
known_basis.push(subsp_elt);
}
}
}
}
}
}
/*
*
*
* Multiplicative structures.
*
*
*/
impl<N, D: DimName, S> Identity<Multiplicative> for SquareMatrix<N, D, S>
where N: Scalar + Zero + One,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S> AbstractMagma<Multiplicative> for SquareMatrix<N, D, S>
where N: Scalar + Zero + ClosedAdd + ClosedMul,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
#[inline]
fn operate(&self, other: &Self) -> Self {
self * other
}
}
macro_rules! impl_multiplicative_structure(
($($marker: ident<$operator: ident> $(+ $bounds: ident)*),* $(,)*) => {$(
impl<N, D: DimName, S> $marker<$operator> for SquareMatrix<N, D, S>
where N: Scalar + Zero + ClosedAdd + ClosedMul + $marker<$operator> $(+ $bounds)*,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> { }
)*}
);
impl_multiplicative_structure!(
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative> + One
);
// // FIXME: Field too strong?
// impl<N, S> Matrix for Matrix<N, S>
// where N: Scalar + Field,
// S: Storage<N> {
// type Field = N;
// type Row = OwnedMatrix<N, Static<U1>, S::C, S::Alloc>;
// type Column = OwnedMatrix<N, S::R, Static<U1>, S::Alloc>;
// type Transpose = OwnedMatrix<N, S::C, S::R, S::Alloc>;
// #[inline]
// fn nrows(&self) -> usize {
// self.shape().0
// }
// #[inline]
// fn ncolumns(&self) -> usize {
// self.shape().1
// }
// #[inline]
// fn row(&self, row: usize) -> Self::Row {
// let mut res: Self::Row = ::zero();
// for (column, e) in res.iter_mut().enumerate() {
// *e = self[(row, column)];
// }
// res
// }
// #[inline]
// fn column(&self, column: usize) -> Self::Column {
// let mut res: Self::Column = ::zero();
// for (row, e) in res.iter_mut().enumerate() {
// *e = self[(row, column)];
// }
// res
// }
// #[inline]
// unsafe fn get_unchecked(&self, i: usize, j: usize) -> Self::Field {
// self.get_unchecked(i, j)
// }
// #[inline]
// fn transpose(&self) -> Self::Transpose {
// self.transpose()
// }
// }
// impl<N, S> MatrixMut for Matrix<N, S>
// where N: Scalar + Field,
// S: StorageMut<N> {
// #[inline]
// fn set_row_mut(&mut self, irow: usize, row: &Self::Row) {
// assert!(irow < self.shape().0, "Row index out of bounds.");
// for (icol, e) in row.iter().enumerate() {
// unsafe { self.set_unchecked(irow, icol, *e) }
// }
// }
// #[inline]
// fn set_column_mut(&mut self, icol: usize, col: &Self::Column) {
// assert!(icol < self.shape().1, "Column index out of bounds.");
// for (irow, e) in col.iter().enumerate() {
// unsafe { self.set_unchecked(irow, icol, *e) }
// }
// }
// #[inline]
// unsafe fn set_unchecked(&mut self, i: usize, j: usize, val: Self::Field) {
// *self.get_unchecked_mut(i, j) = val
// }
// }
// // FIXME: Real is needed here only for invertibility...
// impl<N: Real> SquareMatrixMut for $t<N> {
// #[inline]
// fn from_diagonal(diag: &Self::Coordinates) -> Self {
// let mut res: $t<N> = ::zero();
// res.set_diagonal_mut(diag);
// res
// }
// #[inline]
// fn set_diagonal_mut(&mut self, diag: &Self::Coordinates) {
// for (i, e) in diag.iter().enumerate() {
// unsafe { self.set_unchecked(i, i, *e) }
// }
// }
// }
// Specializations depending on the dimension.
// matrix_group_approx_impl!(common: $t, 1, $vector, $($compN),+);
// // FIXME: Real is needed here only for invertibility...
// impl<N: Real> SquareMatrix for $t<N> {
// type Vector = $vector<N>;
// #[inline]
// fn diagonal(&self) -> Self::Coordinates {
// $vector::new(self.m11)
// }
// #[inline]
// fn determinant(&self) -> Self::Field {
// self.m11
// }
// #[inline]
// fn try_inverse(&self) -> Option<Self> {
// let mut res = *self;
// if res.try_inverse_mut() {
// Some(res)
// }
// else {
// None
// }
// }
// #[inline]
// fn try_inverse_mut(&mut self) -> bool {
// if relative_eq!(&self.m11, &::zero()) {
// false
// }
// else {
// self.m11 = ::one::<N>() / ::determinant(self);
// true
// }
// }
// #[inline]
// fn transpose_mut(&mut self) {
// // no-op
// }
// }
// ident, 2, $vector: ident, $($compN: ident),+) => {
// matrix_group_approx_impl!(common: $t, 2, $vector, $($compN),+);
// // FIXME: Real is needed only for inversion here.
// impl<N: Real> SquareMatrix for $t<N> {
// type Vector = $vector<N>;
// #[inline]
// fn diagonal(&self) -> Self::Coordinates {
// $vector::new(self.m11, self.m22)
// }
// #[inline]
// fn determinant(&self) -> Self::Field {
// self.m11 * self.m22 - self.m21 * self.m12
// }
// #[inline]
// fn try_inverse(&self) -> Option<Self> {
// let mut res = *self;
// if res.try_inverse_mut() {
// Some(res)
// }
// else {
// None
// }
// }
// #[inline]
// fn try_inverse_mut(&mut self) -> bool {
// let determinant = ::determinant(self);
// if relative_eq!(&determinant, &::zero()) {
// false
// }
// else {
// *self = Matrix2::new(
// self.m22 / determinant , -self.m12 / determinant,
// -self.m21 / determinant, self.m11 / determinant);
// true
// }
// }
// #[inline]
// fn transpose_mut(&mut self) {
// mem::swap(&mut self.m12, &mut self.m21)
// }
// }
// ident, 3, $vector: ident, $($compN: ident),+) => {
// matrix_group_approx_impl!(common: $t, 3, $vector, $($compN),+);
// // FIXME: Real is needed only for inversion here.
// impl<N: Real> SquareMatrix for $t<N> {
// type Vector = $vector<N>;
// #[inline]
// fn diagonal(&self) -> Self::Coordinates {
// $vector::new(self.m11, self.m22, self.m33)
// }
// #[inline]
// fn determinant(&self) -> Self::Field {
// let minor_m12_m23 = self.m22 * self.m33 - self.m32 * self.m23;
// let minor_m11_m23 = self.m21 * self.m33 - self.m31 * self.m23;
// let minor_m11_m22 = self.m21 * self.m32 - self.m31 * self.m22;
// self.m11 * minor_m12_m23 - self.m12 * minor_m11_m23 + self.m13 * minor_m11_m22
// }
// #[inline]
// fn try_inverse(&self) -> Option<Self> {
// let mut res = *self;
// if res.try_inverse_mut() {
// Some(res)
// }
// else {
// None
// }
// }
// #[inline]
// fn try_inverse_mut(&mut self) -> bool {
// let minor_m12_m23 = self.m22 * self.m33 - self.m32 * self.m23;
// let minor_m11_m23 = self.m21 * self.m33 - self.m31 * self.m23;
// let minor_m11_m22 = self.m21 * self.m32 - self.m31 * self.m22;
// let determinant = self.m11 * minor_m12_m23 -
// self.m12 * minor_m11_m23 +
// self.m13 * minor_m11_m22;
// if relative_eq!(&determinant, &::zero()) {
// false
// }
// else {
// *self = Matrix3::new(
// (minor_m12_m23 / determinant),
// ((self.m13 * self.m32 - self.m33 * self.m12) / determinant),
// ((self.m12 * self.m23 - self.m22 * self.m13) / determinant),
// (-minor_m11_m23 / determinant),
// ((self.m11 * self.m33 - self.m31 * self.m13) / determinant),
// ((self.m13 * self.m21 - self.m23 * self.m11) / determinant),
// (minor_m11_m22 / determinant),
// ((self.m12 * self.m31 - self.m32 * self.m11) / determinant),
// ((self.m11 * self.m22 - self.m21 * self.m12) / determinant)
// );
// true
// }
// }
// #[inline]
// fn transpose_mut(&mut self) {
// mem::swap(&mut self.m12, &mut self.m21);
// mem::swap(&mut self.m13, &mut self.m31);
// mem::swap(&mut self.m23, &mut self.m32);
// }
// }
// ident, $dimension: expr, $vector: ident, $($compN: ident),+) => {
// matrix_group_approx_impl!(common: $t, $dimension, $vector, $($compN),+);
// // FIXME: Real is needed only for inversion here.
// impl<N: Real> SquareMatrix for $t<N> {
// type Vector = $vector<N>;
// #[inline]
// fn diagonal(&self) -> Self::Coordinates {
// let mut diagonal: $vector<N> = ::zero();
// for i in 0 .. $dimension {
// unsafe { diagonal.unsafe_set(i, self.get_unchecked(i, i)) }
// }
// diagonal
// }
// #[inline]
// fn determinant(&self) -> Self::Field {
// // FIXME: extremely naive implementation.
// let mut det = ::zero();
// for icol in 0 .. $dimension {
// let e = unsafe { self.unsafe_at((0, icol)) };
// if e != ::zero() {
// let minor_mat = self.delete_row_column(0, icol);
// let minor = minor_mat.determinant();
// if icol % 2 == 0 {
// det += minor;
// }
// else {
// det -= minor;
// }
// }
// }
// det
// }
// #[inline]
// fn try_inverse(&self) -> Option<Self> {
// let mut res = *self;
// if res.try_inverse_mut() {
// Some(res)
// }
// else {
// None
// }
// }
// #[inline]
// fn try_inverse_mut(&mut self) -> bool {
// let mut res: $t<N> = ::one();
// // Inversion using Gauss-Jordan elimination
// for k in 0 .. $dimension {
// // search a non-zero value on the k-th column
// // FIXME: would it be worth it to spend some more time searching for the
// // max instead?
// let mut n0 = k; // index of a non-zero entry
// while n0 != $dimension {
// if self[(n0, k)] != ::zero() {
// break;
// }
// n0 = n0 + 1;
// }
// if n0 == $dimension {
// return false
// }
// // swap pivot line
// if n0 != k {
// for j in 0 .. $dimension {
// self.swap((n0, j), (k, j));
// res.swap((n0, j), (k, j));
// }
// }
// let pivot = self[(k, k)];
// for j in k .. $dimension {
// let selfval = self[(k, j)] / pivot;
// self[(k, j)] = selfval;
// }
// for j in 0 .. $dimension {
// let resval = res[(k, j)] / pivot;
// res[(k, j)] = resval;
// }
// for l in 0 .. $dimension {
// if l != k {
// let normalizer = self[(l, k)];
// for j in k .. $dimension {
// let selfval = self[(l, j)] - self[(k, j)] * normalizer;
// self[(l, j)] = selfval;
// }
// for j in 0 .. $dimension {
// let resval = res[(l, j)] - res[(k, j)] * normalizer;
// res[(l, j)] = resval;
// }
// }
// }
// }
// *self = res;
// true
// }
// #[inline]
// fn transpose_mut(&mut self) {
// for i in 1 .. $dimension {
// for j in 0 .. i {
// self.swap((i, j), (j, i))
// }
// }
// }
/*
*
* Ordering
*
*/
impl<N, R: Dim, C: Dim, S> MeetSemilattice for Matrix<N, R, C, S>
where N: Scalar + MeetSemilattice,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn meet(&self, other: &Self) -> Self {
self.zip_map(other, |a, b| a.meet(&b))
}
}
impl<N, R: Dim, C: Dim, S> JoinSemilattice for Matrix<N, R, C, S>
where N: Scalar + JoinSemilattice,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn join(&self, other: &Self) -> Self {
self.zip_map(other, |a, b| a.join(&b))
}
}
impl<N, R: Dim, C: Dim, S> Lattice for Matrix<N, R, C, S>
where N: Scalar + Lattice,
S: OwnedStorage<N, R, C>,
S::Alloc: OwnedAllocator<N, R, C, S> {
#[inline]
fn meet_join(&self, other: &Self) -> (Self, Self) {
let shape = self.data.shape();
assert!(shape == other.data.shape(), "Matrix meet/join error: mismatched dimensions.");
let mut mres = unsafe { Self::new_uninitialized_generic(shape.0, shape.1) };
let mut jres = unsafe { Self::new_uninitialized_generic(shape.0, shape.1) };
for i in 0 .. shape.0.value() * shape.1.value() {
unsafe {
let mj = self.data.get_unchecked_linear(i).meet_join(other.data.get_unchecked_linear(i));
*mres.data.get_unchecked_linear_mut(i) = mj.0;
*jres.data.get_unchecked_linear_mut(i) = mj.1;
}
}
(mres, jres)
}
}

298
src/core/matrix_array.rs Normal file
View File

@ -0,0 +1,298 @@
use std::ops::{Deref, DerefMut, Mul};
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
#[cfg(feature = "serde-serialize")]
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[cfg(feature = "serde-serialize")]
use serde::ser::SerializeSeq;
#[cfg(feature = "serde-serialize")]
use serde::de::{SeqVisitor, Visitor};
#[cfg(feature = "serde-serialize")]
use std::mem;
#[cfg(feature = "serde-serialize")]
use std::marker::PhantomData;
use typenum::Prod;
use generic_array::{ArrayLength, GenericArray};
use core::Scalar;
use core::dimension::{DimName, U1};
use core::storage::{Storage, StorageMut, Owned, OwnedStorage};
use core::allocator::Allocator;
use core::default_allocator::DefaultAllocator;
/*
*
* Static Storage.
*
*/
/// A array-based statically sized matrix data storage.
#[repr(C)]
pub struct MatrixArray<N, R, C>
where R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
data: GenericArray<N, Prod<R::Value, C::Value>>
}
impl<N, R, C> Hash for MatrixArray<N, R, C>
where N: Hash,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.data[..].hash(state)
}
}
impl<N, R, C> Deref for MatrixArray<N, R, C>
where R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
type Target = GenericArray<N, Prod<R::Value, C::Value>>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<N, R, C> DerefMut for MatrixArray<N, R, C>
where R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.data
}
}
impl<N, R, C> Debug for MatrixArray<N, R, C>
where N: Debug,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
#[inline]
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
self.data.fmt(fmt)
}
}
impl<N, R, C> Copy for MatrixArray<N, R, C>
where N: Copy,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N>,
GenericArray<N, Prod<R::Value, C::Value>> : Copy
{ }
impl<N, R, C> Clone for MatrixArray<N, R, C>
where N: Clone,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
#[inline]
fn clone(&self) -> Self {
MatrixArray {
data: self.data.clone()
}
}
}
impl<N, R, C> Eq for MatrixArray<N, R, C>
where N: Eq,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
}
impl<N, R, C> PartialEq for MatrixArray<N, R, C>
where N: PartialEq,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
#[inline]
fn eq(&self, right: &Self) -> bool {
self.data == right.data
}
}
unsafe impl<N, R, C> Storage<N, R, C> for MatrixArray<N, R, C>
where N: Scalar,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
type RStride = U1;
type CStride = R;
type Alloc = DefaultAllocator;
#[inline]
fn into_owned(self) -> Owned<N, R, C, Self::Alloc> {
self
}
#[inline]
fn clone_owned(&self) -> Owned<N, R, C, Self::Alloc> {
let it = self.iter().cloned();
Self::Alloc::allocate_from_iterator(self.shape().0, self.shape().1, it)
}
#[inline]
fn ptr(&self) -> *const N {
self[..].as_ptr()
}
#[inline]
fn shape(&self) -> (R, C) {
(R::name(), C::name())
}
#[inline]
fn strides(&self) -> (Self::RStride, Self::CStride) {
(Self::RStride::name(), Self::CStride::name())
}
}
unsafe impl<N, R, C> StorageMut<N, R, C> for MatrixArray<N, R, C>
where N: Scalar,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
#[inline]
fn ptr_mut(&mut self) -> *mut N {
self[..].as_mut_ptr()
}
}
unsafe impl<N, R, C> OwnedStorage<N, R, C> for MatrixArray<N, R, C>
where N: Scalar,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
#[inline]
fn as_slice(&self) -> &[N] {
&self[..]
}
#[inline]
fn as_mut_slice(&mut self) -> &mut [N] {
&mut self[..]
}
}
/*
*
* Allocation-less serde impls.
*
*/
// XXX: open an issue for GenericArray so that it implements serde traits?
#[cfg(feature = "serde-serialize")]
impl<N, R, C> Serialize for MatrixArray<N, R, C>
where N: Scalar + Serialize,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
let mut serializer = serializer.serialize_seq_fixed_size(R::dim() * C::dim())?;
for e in self.iter() {
serializer.serialize_element(e)?;
}
serializer.end()
}
}
#[cfg(feature = "serde-serialize")]
impl<N, R, C> Deserialize for MatrixArray<N, R, C>
where N: Scalar + Deserialize,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer {
let len = R::dim() * C::dim();
deserializer.deserialize_seq_fixed_size(len, MatrixArrayVisitor::new())
}
}
#[cfg(feature = "serde-serialize")]
/// A visitor that produces a matrix array.
struct MatrixArrayVisitor<N, R, C> {
marker: PhantomData<(N, R, C)>
}
#[cfg(feature = "serde-serialize")]
impl<N, R, C> MatrixArrayVisitor<N, R, C>
where N: Scalar,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
/// Construct a new sequence visitor.
pub fn new() -> Self {
MatrixArrayVisitor {
marker: PhantomData,
}
}
}
#[cfg(feature = "serde-serialize")]
impl<N, R, C> Visitor for MatrixArrayVisitor<N, R, C>
where N: Scalar + Deserialize,
R: DimName,
C: DimName,
R::Value: Mul<C::Value>,
Prod<R::Value, C::Value>: ArrayLength<N> {
type Value = MatrixArray<N, R, C>;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("a matrix array")
}
#[inline]
fn visit_seq<V>(self, mut visitor: V) -> Result<MatrixArray<N, R, C>, V::Error>
where V: SeqVisitor {
let mut out: Self::Value = unsafe { mem::uninitialized() };
let mut curr = 0;
while let Some(value) = try!(visitor.visit()) {
out[curr] = value;
curr += 1;
}
Ok(out)
}
}

482
src/core/matrix_slice.rs Normal file
View File

@ -0,0 +1,482 @@
use std::marker::PhantomData;
use core::{Scalar, Matrix};
use core::dimension::{Dim, DimName, Dynamic, DimMul, DimProd, U1};
use core::iter::MatrixIter;
use core::storage::{Storage, StorageMut, Owned};
use core::allocator::Allocator;
macro_rules! slice_storage_impl(
($doc: expr; $Storage: ident as $SRef: ty; $T: ident.$get_addr: ident ($Ptr: ty as $Ref: ty)) => {
#[doc = $doc]
pub struct $T<'a, N: Scalar, R: Dim, C: Dim, RStride: Dim, CStride: Dim, Alloc> {
ptr: $Ptr,
shape: (R, C),
strides: (RStride, CStride),
_phantoms: PhantomData<($Ref, Alloc)>,
}
// Dynamic and () are arbitrary. It's just to be able to call the constructors with
// `Slice::`
impl<'a, N: Scalar, R: Dim, C: Dim> $T<'a, N, R, C, Dynamic, Dynamic, ()> {
/// Create a new matrix slice without bound checking.
#[inline]
pub unsafe fn new_unchecked<RStor, CStor, S>(storage: $SRef, start: (usize, usize), shape: (R, C))
-> $T<'a, N, R, C, S::RStride, S::CStride, S::Alloc>
where RStor: Dim,
CStor: Dim,
S: $Storage<N, RStor, CStor> {
let strides = storage.strides();
$T::new_with_strides_unchecked(storage, start, shape, strides)
}
/// Create a new matrix slice without bound checking.
#[inline]
pub unsafe fn new_with_strides_unchecked<S, RStor, CStor, RStride, CStride>(storage: $SRef,
start: (usize, usize),
shape: (R, C),
strides: (RStride, CStride))
-> $T<'a, N, R, C, RStride, CStride, S::Alloc>
where RStor: Dim,
CStor: Dim,
S: $Storage<N, RStor, CStor>,
RStride: Dim,
CStride: Dim {
$T {
ptr: storage.$get_addr(start.0, start.1),
shape: shape,
strides: (strides.0, strides.1),
_phantoms: PhantomData
}
}
}
}
);
slice_storage_impl!("A matrix data storage for a matrix slice. Only contains an internal reference \
to another matrix data storage.";
Storage as &'a S; SliceStorage.get_address_unchecked(*const N as &'a N));
slice_storage_impl!("A mutable matrix data storage for mutable matrix slice. Only contains an \
internal mutable reference to another matrix data storage.";
StorageMut as &'a mut S; SliceStorageMut.get_address_unchecked_mut(*mut N as &'a mut N)
);
impl<'a, N: Scalar, R: Dim, C: Dim, RStride: Dim, CStride: Dim, Alloc> Copy
for SliceStorage<'a, N, R, C, RStride, CStride, Alloc> { }
impl<'a, N: Scalar, R: Dim, C: Dim, RStride: Dim, CStride: Dim, Alloc> Clone
for SliceStorage<'a, N, R, C, RStride, CStride, Alloc> {
#[inline]
fn clone(&self) -> Self {
SliceStorage {
ptr: self.ptr,
shape: self.shape,
strides: self.strides,
_phantoms: PhantomData,
}
}
}
macro_rules! storage_impl(
($($T: ident),* $(,)*) => {$(
unsafe impl<'a, N, R: Dim, C: Dim, RStride: Dim, CStride: Dim, Alloc> Storage<N, R, C>
for $T<'a, N, R, C, RStride, CStride, Alloc>
where N: Scalar,
Alloc: Allocator<N, R, C> {
type RStride = RStride;
type CStride = CStride;
type Alloc = Alloc;
#[inline]
fn into_owned(self) -> Owned<N, R, C, Self::Alloc> {
self.clone_owned()
}
#[inline]
fn clone_owned(&self) -> Owned<N, R, C, Self::Alloc> {
let (nrows, ncols) = self.shape();
let it = MatrixIter::new(self).cloned();
Alloc::allocate_from_iterator(nrows, ncols, it)
}
#[inline]
fn ptr(&self) -> *const N {
self.ptr
}
#[inline]
fn shape(&self) -> (R, C) {
self.shape
}
#[inline]
fn strides(&self) -> (Self::RStride, Self::CStride) {
self.strides
}
}
)*}
);
storage_impl!(SliceStorage, SliceStorageMut);
unsafe impl<'a, N, R: Dim, C: Dim, RStride: Dim, CStride: Dim, Alloc> StorageMut<N, R, C>
for SliceStorageMut<'a, N, R, C, RStride, CStride, Alloc>
where N: Scalar,
Alloc: Allocator<N, R, C> {
#[inline]
fn ptr_mut(&mut self) -> *mut N {
self.ptr
}
}
impl<N: Scalar, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S> {
#[inline]
fn assert_slice_index(&self, start: (usize, usize), shape: (usize, usize), steps: (usize, usize)) {
let my_shape = self.shape();
assert!(start.0 + (shape.0 - 1) * steps.0 <= my_shape.0, "Matrix slicing out of bounds.");
assert!(start.1 + (shape.1 - 1) * steps.1 <= my_shape.1, "Matrix slicing out of bounds.");
}
}
macro_rules! matrix_slice_impl(
($me: ident: $Me: ty, $MatrixSlice: ident, $SliceStorage: ident, $Storage: ident, $data: expr;
$row: ident,
$rows: ident,
$rows_with_step: ident,
$fixed_rows: ident,
$fixed_rows_with_step: ident,
$rows_generic: ident,
$column: ident,
$columns: ident,
$columns_with_step: ident,
$fixed_columns: ident,
$fixed_columns_with_step: ident,
$columns_generic: ident,
$slice: ident,
$slice_with_steps: ident,
$fixed_slice: ident,
$fixed_slice_with_steps: ident,
$generic_slice: ident,
$generic_slice_with_steps: ident) => {
/// A matrix slice.
pub type $MatrixSlice<'a, N, R, C, RStride, CStride, Alloc>
= Matrix<N, R, C, $SliceStorage<'a, N, R, C, RStride, CStride, Alloc>>;
impl<N: Scalar, R: Dim, C: Dim, S: $Storage<N, R, C>> Matrix<N, R, C, S> {
/*
*
* Row slicing.
*
*/
/// Returns a slice containing the i-th column of this matrix.
#[inline]
pub fn $row($me: $Me, i: usize) -> $MatrixSlice<N, U1, C, S::RStride, S::CStride, S::Alloc> {
$me.$fixed_rows::<U1>(i)
}
/// Extracts from this matrix a set of consecutive rows.
#[inline]
pub fn $rows($me: $Me, first_row: usize, nrows: usize)
-> $MatrixSlice<N, Dynamic, C, S::RStride, S::CStride, S::Alloc> {
let my_shape = $me.data.shape();
$me.assert_slice_index((first_row, 0), (nrows, my_shape.1.value()), (1, 1));
let shape = (Dynamic::new(nrows), my_shape.1);
unsafe {
let data = $SliceStorage::new_unchecked($data, (first_row, 0), shape);
Matrix::from_data_statically_unchecked(data)
}
}
/// Extracts from this matrix a set of consecutive rows regularly spaced by `step` rows.
#[inline]
pub fn $rows_with_step($me: $Me, first_row: usize, nrows: usize, step: usize)
-> $MatrixSlice<N, Dynamic, C, Dynamic, S::CStride, S::Alloc> {
$me.$rows_generic(first_row, Dynamic::new(nrows), Dynamic::new(step))
}
/// Extracts a compile-time number of consecutive rows from this matrix.
#[inline]
pub fn $fixed_rows<RSlice>($me: $Me, first_row: usize)
-> $MatrixSlice<N, RSlice, C, S::RStride, S::CStride, S::Alloc>
where RSlice: DimName {
let my_shape = $me.data.shape();
$me.assert_slice_index((first_row, 0), (RSlice::dim(), my_shape.1.value()), (1, 1));
let shape = (RSlice::name(), my_shape.1);
unsafe {
let data = $SliceStorage::new_unchecked($data, (first_row, 0), shape);
Matrix::from_data_statically_unchecked(data)
}
}
/// Extracts from this matrix a compile-time number of rows regularly spaced by `step` rows.
#[inline]
pub fn $fixed_rows_with_step<RSlice>($me: $Me, first_row: usize, step: usize)
-> $MatrixSlice<N, RSlice, C, Dynamic, S::CStride, S::Alloc>
where RSlice: DimName {
$me.$rows_generic(first_row, RSlice::name(), Dynamic::new(step))
}
/// Extracts from this matrix `nrows` rows regularly spaced by `step` rows. Both argument may
/// or may not be values known at compile-time.
#[inline]
pub fn $rows_generic<RSlice, RStep>($me: $Me, row_start: usize, nrows: RSlice, step: RStep)
-> $MatrixSlice<N, RSlice, C, DimProd<RStep, S::RStride>, S::CStride, S::Alloc>
where RSlice: Dim,
RStep: DimMul<S::RStride> {
let my_shape = $me.data.shape();
let my_strides = $me.data.strides();
$me.assert_slice_index((row_start, 0), (nrows.value(), my_shape.1.value()), (step.value(), 1));
let strides = (step.mul(my_strides.0), my_strides.1);
let shape = (nrows, my_shape.1);
unsafe {
let data = $SliceStorage::new_with_strides_unchecked($data, (row_start, 0), shape, strides);
Matrix::from_data_statically_unchecked(data)
}
}
/*
*
* Column slicing.
*
*/
/// Returns a slice containing the i-th column of this matrix.
#[inline]
pub fn $column($me: $Me, i: usize) -> $MatrixSlice<N, R, U1, S::RStride, S::CStride, S::Alloc> {
$me.$fixed_columns::<U1>(i)
}
/// Extracts from this matrix a set of consecutive columns.
#[inline]
pub fn $columns($me: $Me, first_col: usize, ncols: usize)
-> $MatrixSlice<N, R, Dynamic, S::RStride, S::CStride, S::Alloc> {
let my_shape = $me.data.shape();
$me.assert_slice_index((0, first_col), (my_shape.0.value(), ncols), (1, 1));
let shape = (my_shape.0, Dynamic::new(ncols));
unsafe {
let data = $SliceStorage::new_unchecked($data, (0, first_col), shape);
Matrix::from_data_statically_unchecked(data)
}
}
/// Extracts from this matrix a set of consecutive columns regularly spaced by `step` columns.
#[inline]
pub fn $columns_with_step($me: $Me, first_col: usize, ncols: usize, step: usize)
-> $MatrixSlice<N, R, Dynamic, S::RStride, Dynamic, S::Alloc> {
$me.$columns_generic(first_col, Dynamic::new(ncols), Dynamic::new(step))
}
/// Extracts a compile-time number of consecutive columns from this matrix.
#[inline]
pub fn $fixed_columns<CSlice>($me: $Me, first_col: usize)
-> $MatrixSlice<N, R, CSlice, S::RStride, S::CStride, S::Alloc>
where CSlice: DimName {
let my_shape = $me.data.shape();
$me.assert_slice_index((0, first_col), (my_shape.0.value(), CSlice::dim()), (1, 1));
let shape = (my_shape.0, CSlice::name());
unsafe {
let data = $SliceStorage::new_unchecked($data, (0, first_col), shape);
Matrix::from_data_statically_unchecked(data)
}
}
/// Extracts from this matrix a compile-time number of columns regularly spaced by `step`
/// columns.
#[inline]
pub fn $fixed_columns_with_step<CSlice>($me: $Me, first_col: usize, step: usize)
-> $MatrixSlice<N, R, CSlice, S::RStride, Dynamic, S::Alloc>
where CSlice: DimName {
$me.$columns_generic(first_col, CSlice::name(), Dynamic::new(step))
}
/// Extracts from this matrix `ncols` columns regularly spaced by `step` columns. Both argument may
/// or may not be values known at compile-time.
#[inline]
pub fn $columns_generic<CSlice, CStep>($me: $Me, first_col: usize, ncols: CSlice, step: CStep)
-> $MatrixSlice<N, R, CSlice, S::RStride, DimProd<CStep, S::CStride>, S::Alloc>
where CSlice: Dim,
CStep: DimMul<S::CStride> {
let my_shape = $me.data.shape();
let my_strides = $me.data.strides();
$me.assert_slice_index((0, first_col), (my_shape.0.value(), ncols.value()), (1, step.value()));
let strides = (my_strides.0, step.mul(my_strides.1));
let shape = (my_shape.0, ncols);
unsafe {
let data = $SliceStorage::new_with_strides_unchecked($data, (0, first_col), shape, strides);
Matrix::from_data_statically_unchecked(data)
}
}
/*
*
* General slicing.
*
*/
/// Slices this matrix starting at its component `(irow, icol)` and with `(nrows, ncols)`
/// consecutive elements.
#[inline]
pub fn $slice($me: $Me, start: (usize, usize), shape: (usize, usize))
-> $MatrixSlice<N, Dynamic, Dynamic, S::RStride, S::CStride, S::Alloc> {
$me.assert_slice_index(start, shape, (1, 1));
let shape = (Dynamic::new(shape.0), Dynamic::new(shape.1));
unsafe {
let data = $SliceStorage::new_unchecked($data, start, shape);
Matrix::from_data_statically_unchecked(data)
}
}
/// Slices this matrix starting at its component `(start.0, start.1)` and with
/// `(shape.0, shape.1)` components. Each row (resp. column) of the sliced matrix is
/// separated by `steps.0` (resp. `steps.1`) ignored rows (resp. columns) of the
/// original matrix.
#[inline]
pub fn $slice_with_steps($me: $Me, start: (usize, usize), shape: (usize, usize), steps: (usize, usize))
-> $MatrixSlice<N, Dynamic, Dynamic, Dynamic, Dynamic, S::Alloc> {
let shape = (Dynamic::new(shape.0), Dynamic::new(shape.1));
let steps = (Dynamic::new(steps.0), Dynamic::new(steps.1));
$me.$generic_slice_with_steps(start, shape, steps)
}
/// Slices this matrix starting at its component `(irow, icol)` and with `(R::dim(),
/// CSlice::dim())` consecutive components.
#[inline]
pub fn $fixed_slice<RSlice, CSlice>($me: $Me, irow: usize, icol: usize)
-> $MatrixSlice<N, RSlice, CSlice, S::RStride, S::CStride, S::Alloc>
where RSlice: DimName,
CSlice: DimName {
$me.assert_slice_index((irow, icol), (RSlice::dim(), CSlice::dim()), (1, 1));
let shape = (RSlice::name(), CSlice::name());
unsafe {
let data = $SliceStorage::new_unchecked($data, (irow, icol), shape);
Matrix::from_data_statically_unchecked(data)
}
}
/// Slices this matrix starting at its component `(start.0, start.1)` and with
/// `(R::dim(), CSlice::dim())` components. Each row (resp. column) of the sliced
/// matrix is separated by `steps.0` (resp. `steps.1`) ignored rows (resp. columns) of
/// the original matrix.
#[inline]
pub fn $fixed_slice_with_steps<RSlice, CSlice>($me: $Me, start: (usize, usize), steps: (usize, usize))
-> $MatrixSlice<N, RSlice, CSlice, Dynamic, Dynamic, S::Alloc>
where RSlice: DimName,
CSlice: DimName {
let shape = (RSlice::name(), CSlice::name());
let steps = (Dynamic::new(steps.0), Dynamic::new(steps.1));
$me.$generic_slice_with_steps(start, shape, steps)
}
/// Creates a slice that may or may not have a fixed size and stride.
#[inline]
pub fn $generic_slice<RSlice, CSlice>($me: $Me, start: (usize, usize), shape: (RSlice, CSlice))
-> $MatrixSlice<N, RSlice, CSlice, S::RStride, S::CStride, S::Alloc>
where RSlice: Dim,
CSlice: Dim {
$me.assert_slice_index(start, (shape.0.value(), shape.1.value()), (1, 1));
unsafe {
let data = $SliceStorage::new_unchecked($data, start, shape);
Matrix::from_data_statically_unchecked(data)
}
}
/// Creates a slice that may or may not have a fixed size and stride.
#[inline]
pub fn $generic_slice_with_steps<RSlice, CSlice, RStep, CStep>($me: $Me,
start: (usize, usize),
shape: (RSlice, CSlice),
steps: (RStep, CStep))
-> $MatrixSlice<N, RSlice, CSlice, DimProd<RStep, S::RStride>, DimProd<CStep, S::CStride>, S::Alloc>
where RSlice: Dim,
CSlice: Dim,
RStep: DimMul<S::RStride>,
CStep: DimMul<S::CStride> {
$me.assert_slice_index(start, (shape.0.value(), shape.1.value()), (steps.0.value(), steps.1.value()));
let my_strides = $me.data.strides();
let strides = (steps.0.mul(my_strides.0), steps.1.mul(my_strides.1));
unsafe {
let data = $SliceStorage::new_with_strides_unchecked($data, start, shape, strides);
Matrix::from_data_statically_unchecked(data)
}
}
}
}
);
matrix_slice_impl!(
self: &Self, MatrixSlice, SliceStorage, Storage, &self.data;
row,
rows,
rows_with_step,
fixed_rows,
fixed_rows_with_step,
rows_generic,
column,
columns,
columns_with_step,
fixed_columns,
fixed_columns_with_step,
columns_generic,
slice,
slice_with_steps,
fixed_slice,
fixed_slice_with_steps,
generic_slice,
generic_slice_with_steps);
matrix_slice_impl!(
self: &mut Self, MatrixSliceMut, SliceStorageMut, StorageMut, &mut self.data;
row_mut,
rows_mut,
rows_with_step_mut,
fixed_rows_mut,
fixed_rows_with_step_mut,
rows_generic_mut,
column_mut,
columns_mut,
columns_with_step_mut,
fixed_columns_mut,
fixed_columns_with_step_mut,
columns_generic_mut,
slice_mut,
slice_with_steps_mut,
fixed_slice_mut,
fixed_slice_with_steps_mut,
generic_slice_mut,
generic_slice_with_steps_mut);

173
src/core/matrix_vec.rs Normal file
View File

@ -0,0 +1,173 @@
use std::ops::Deref;
use core::Scalar;
use core::dimension::{Dim, DimName, Dynamic, U1};
use core::storage::{Storage, StorageMut, Owned, OwnedStorage};
use core::default_allocator::DefaultAllocator;
/*
*
* Storage.
*
*/
/// A Vec-based matrix data storage. It may be dynamically-sized.
#[repr(C)]
#[derive(Eq, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct MatrixVec<N, R: Dim, C: Dim> {
data: Vec<N>,
nrows: R,
ncols: C
}
impl<N, R: Dim, C: Dim> MatrixVec<N, R, C> {
/// Creates a new dynamic matrix data storage from the given vector and shape.
#[inline]
pub fn new(nrows: R, ncols: C, data: Vec<N>) -> MatrixVec<N, R, C> {
assert!(nrows.value() * ncols.value() == data.len(), "Data storage buffer dimension mismatch.");
MatrixVec {
data: data,
nrows: nrows,
ncols: ncols
}
}
/// The underlying data storage.
#[inline]
pub fn data(&self) -> &Vec<N> {
&self.data
}
/// The underlying mutable data storage.
///
/// This is unsafe because this may cause UB if the vector is modified by the user.
#[inline]
pub unsafe fn data_mut(&mut self) -> &mut Vec<N> {
&mut self.data
}
}
impl<N, R: Dim, C: Dim> Deref for MatrixVec<N, R, C> {
type Target = Vec<N>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.data
}
}
/*
*
* Dynamic Static
* Dynamic Dynamic
*
*/
unsafe impl<N: Scalar, C: Dim> Storage<N, Dynamic, C> for MatrixVec<N, Dynamic, C> {
type RStride = U1;
type CStride = Dynamic;
type Alloc = DefaultAllocator;
#[inline]
fn into_owned(self) -> Owned<N, Dynamic, C, Self::Alloc> {
self
}
#[inline]
fn clone_owned(&self) -> Owned<N, Dynamic, C, Self::Alloc> {
self.clone()
}
#[inline]
fn ptr(&self) -> *const N {
self[..].as_ptr()
}
#[inline]
fn shape(&self) -> (Dynamic, C) {
(self.nrows, self.ncols)
}
#[inline]
fn strides(&self) -> (Self::RStride, Self::CStride) {
(Self::RStride::name(), self.nrows)
}
}
unsafe impl<N: Scalar, R: DimName> Storage<N, R, Dynamic> for MatrixVec<N, R, Dynamic> {
type RStride = U1;
type CStride = R;
type Alloc = DefaultAllocator;
#[inline]
fn into_owned(self) -> Owned<N, R, Dynamic, Self::Alloc> {
self
}
#[inline]
fn clone_owned(&self) -> Owned<N, R, Dynamic, Self::Alloc> {
self.clone()
}
#[inline]
fn ptr(&self) -> *const N {
self[..].as_ptr()
}
#[inline]
fn shape(&self) -> (R, Dynamic) {
(self.nrows, self.ncols)
}
#[inline]
fn strides(&self) -> (Self::RStride, Self::CStride) {
(Self::RStride::name(), self.nrows)
}
}
/*
*
* StorageMut, OwnedStorage.
*
*/
unsafe impl<N: Scalar, C: Dim> StorageMut<N, Dynamic, C> for MatrixVec<N, Dynamic, C> {
#[inline]
fn ptr_mut(&mut self) -> *mut N {
self.as_mut_slice().as_mut_ptr()
}
}
unsafe impl<N: Scalar, C: Dim> OwnedStorage<N, Dynamic, C> for MatrixVec<N, Dynamic, C> {
#[inline]
fn as_slice(&self) -> &[N] {
&self[..]
}
#[inline]
fn as_mut_slice(&mut self) -> &mut [N] {
&mut self.data[..]
}
}
unsafe impl<N: Scalar, R: DimName> StorageMut<N, R, Dynamic> for MatrixVec<N, R, Dynamic> {
#[inline]
fn ptr_mut(&mut self) -> *mut N {
self.as_mut_slice().as_mut_ptr()
}
}
unsafe impl<N: Scalar, R: DimName> OwnedStorage<N, R, Dynamic> for MatrixVec<N, R, Dynamic> {
#[inline]
fn as_slice(&self) -> &[N] {
&self[..]
}
#[inline]
fn as_mut_slice(&mut self) -> &mut [N] {
&mut self.data[..]
}
}

43
src/core/mod.rs Normal file
View File

@ -0,0 +1,43 @@
//! [Reexported at the root of this crate.] Data structures for vector and matrix computations.
pub mod dimension;
pub mod constraint;
pub mod allocator;
pub mod storage;
pub mod coordinates;
mod ops;
pub mod iter;
pub mod default_allocator;
mod scalar;
mod matrix;
mod construction;
mod properties;
mod alias;
mod matrix_alga;
mod determinant;
mod inverse;
mod conversion;
mod matrix_slice;
mod matrix_array;
mod matrix_vec;
mod cg;
mod unit;
mod componentwise;
mod decompositions;
#[doc(hidden)]
pub mod helper;
pub use self::scalar::*;
pub use self::matrix::*;
pub use self::unit::*;
pub use self::dimension::*;
pub use self::default_allocator::*;
pub use self::alias::*;
pub use self::matrix_slice::*;
pub use self::matrix_array::*;
pub use self::matrix_vec::*;

490
src/core/ops.rs Normal file
View File

@ -0,0 +1,490 @@
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg,
Index, IndexMut};
use num::Zero;
use alga::general::{ClosedMul, ClosedDiv, ClosedAdd, ClosedSub, ClosedNeg};
use core::{Scalar, Matrix, OwnedMatrix, MatrixSum, MatrixMul, MatrixTrMul};
use core::dimension::Dim;
use core::constraint::{ShapeConstraint, SameNumberOfRows, SameNumberOfColumns, AreMultipliable};
use core::storage::{Storage, StorageMut, OwnedStorage};
use core::allocator::{SameShapeAllocator, Allocator, OwnedAllocator};
/*
*
* Indexing.
*
*/
impl<N: Scalar, R: Dim, C: Dim, S: Storage<N, R, C>> Index<usize> for Matrix<N, R, C, S> {
type Output = N;
#[inline]
fn index(&self, i: usize) -> &N {
let ij = self.vector_to_matrix_index(i);
&self[ij]
}
}
impl<N, R: Dim, C: Dim, S> Index<(usize, usize)> for Matrix<N, R, C, S>
where N: Scalar,
S: Storage<N, R, C> {
type Output = N;
#[inline]
fn index(&self, ij: (usize, usize)) -> &N {
let shape = self.shape();
assert!(ij.0 < shape.0 && ij.1 < shape.1, "Matrix index out of bounds.");
unsafe { self.get_unchecked(ij.0, ij.1) }
}
}
// Mutable versions.
impl<N: Scalar, R: Dim, C: Dim, S: StorageMut<N, R, C>> IndexMut<usize> for Matrix<N, R, C, S> {
#[inline]
fn index_mut(&mut self, i: usize) -> &mut N {
let ij = self.vector_to_matrix_index(i);
&mut self[ij]
}
}
impl<N, R: Dim, C: Dim, S> IndexMut<(usize, usize)> for Matrix<N, R, C, S>
where N: Scalar,
S: StorageMut<N, R, C> {
#[inline]
fn index_mut(&mut self, ij: (usize, usize)) -> &mut N {
let shape = self.shape();
assert!(ij.0 < shape.0 && ij.1 < shape.1, "Matrix index out of bounds.");
unsafe { self.get_unchecked_mut(ij.0, ij.1) }
}
}
/*
*
* Neg
*
*/
impl<N, R: Dim, C: Dim, S> Neg for Matrix<N, R, C, S>
where N: Scalar + ClosedNeg,
S: Storage<N, R, C> {
type Output = OwnedMatrix<N, R, C, S::Alloc>;
#[inline]
fn neg(self) -> Self::Output {
let mut res = self.into_owned();
res.neg_mut();
res
}
}
impl<'a, N, R: Dim, C: Dim, S> Neg for &'a Matrix<N, R, C, S>
where N: Scalar + ClosedNeg,
S: Storage<N, R, C> {
type Output = OwnedMatrix<N, R, C, S::Alloc>;
#[inline]
fn neg(self) -> Self::Output {
-self.clone_owned()
}
}
impl<N, R: Dim, C: Dim, S> Matrix<N, R, C, S>
where N: Scalar + ClosedNeg,
S: StorageMut<N, R, C> {
/// Negates `self` in-place.
#[inline]
pub fn neg_mut(&mut self) {
for e in self.iter_mut() {
*e = -*e
}
}
}
/*
*
* Addition & Substraction
*
*/
macro_rules! componentwise_binop_impl(
($Trait: ident, $method: ident, $bound: ident;
$TraitAssign: ident, $method_assign: ident) => {
impl<'b, N, R1, C1, R2, C2, SA, SB> $Trait<&'b Matrix<N, R2, C2, SB>> for Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim, C2: Dim,
N: Scalar + $bound,
SA: Storage<N, R1, C1>,
SB: Storage<N, R2, C2>,
SA::Alloc: SameShapeAllocator<N, R1, C1, R2, C2, SA>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
type Output = MatrixSum<N, R1, C1, R2, C2, SA>;
#[inline]
fn $method(self, right: &'b Matrix<N, R2, C2, SB>) -> Self::Output {
assert!(self.shape() == right.shape(), "Matrix addition/subtraction dimensions mismatch.");
let mut res = self.into_owned_sum::<R2, C2>();
// XXX: optimize our iterator!
//
// Using our own iterator prevents loop unrolling, wich breaks some optimization
// (like SIMD). On the other hand, using the slice iterator is 4x faster.
// for (left, right) in res.iter_mut().zip(right.iter()) {
for (left, right) in res.as_mut_slice().iter_mut().zip(right.iter()) {
*left = left.$method(*right)
}
res
}
}
impl<'a, N, R1, C1, R2, C2, SA, SB> $Trait<Matrix<N, R2, C2, SB>> for &'a Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim, C2: Dim,
N: Scalar + $bound,
SA: Storage<N, R1, C1>,
SB: Storage<N, R2, C2>,
SB::Alloc: SameShapeAllocator<N, R2, C2, R1, C1, SB>,
ShapeConstraint: SameNumberOfRows<R2, R1> + SameNumberOfColumns<C2, C1> {
type Output = MatrixSum<N, R2, C2, R1, C1, SB>;
#[inline]
fn $method(self, right: Matrix<N, R2, C2, SB>) -> Self::Output {
assert!(self.shape() == right.shape(), "Matrix addition/subtraction dimensions mismatch.");
let mut res = right.into_owned_sum::<R1, C1>();
// XXX: optimize our iterator!
//
// Using our own iterator prevents loop unrolling, wich breaks some optimization
// (like SIMD). On the other hand, using the slice iterator is 4x faster.
// for (left, right) in self.iter().zip(res.iter_mut()) {
for (left, right) in self.iter().zip(res.as_mut_slice().iter_mut()) {
*right = left.$method(*right)
}
res
}
}
impl<N, R1, C1, R2, C2, SA, SB> $Trait<Matrix<N, R2, C2, SB>> for Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim, C2: Dim,
N: Scalar + $bound,
SA: Storage<N, R1, C1>,
SB: Storage<N, R2, C2>,
SA::Alloc: SameShapeAllocator<N, R1, C1, R2, C2, SA>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
type Output = MatrixSum<N, R1, C1, R2, C2, SA>;
#[inline]
fn $method(self, right: Matrix<N, R2, C2, SB>) -> Self::Output {
self.$method(&right)
}
}
impl<'a, 'b, N, R1, C1, R2, C2, SA, SB> $Trait<&'b Matrix<N, R2, C2, SB>> for &'a Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim, C2: Dim,
N: Scalar + $bound,
SA: Storage<N, R1, C1>,
SB: Storage<N, R2, C2>,
SA::Alloc: SameShapeAllocator<N, R1, C1, R2, C2, SA>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
type Output = MatrixSum<N, R1, C1, R2, C2, SA>;
#[inline]
fn $method(self, right: &'b Matrix<N, R2, C2, SB>) -> Self::Output {
self.clone_owned().$method(right)
}
}
impl<'b, N, R1, C1, R2, C2, SA, SB> $TraitAssign<&'b Matrix<N, R2, C2, SB>> for Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim, C2: Dim,
N: Scalar + $bound,
SA: StorageMut<N, R1, C1>,
SB: Storage<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
#[inline]
fn $method_assign(&mut self, right: &'b Matrix<N, R2, C2, SB>) {
assert!(self.shape() == right.shape(), "Matrix addition/subtraction dimensions mismatch.");
for (left, right) in self.iter_mut().zip(right.iter()) {
left.$method_assign(*right)
}
}
}
impl<N, R1, C1, R2, C2, SA, SB> $TraitAssign<Matrix<N, R2, C2, SB>> for Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim, C2: Dim,
N: Scalar + $bound,
SA: StorageMut<N, R1, C1>,
SB: Storage<N, R2, C2>,
ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2> {
#[inline]
fn $method_assign(&mut self, right: Matrix<N, R2, C2, SB>) {
self.$method_assign(&right)
}
}
}
);
componentwise_binop_impl!(Add, add, ClosedAdd; AddAssign, add_assign);
componentwise_binop_impl!(Sub, sub, ClosedSub; SubAssign, sub_assign);
/*
*
* Multiplication
*
*/
// Matrix × Scalar
// Matrix / Scalar
macro_rules! componentwise_scalarop_impl(
($Trait: ident, $method: ident, $bound: ident;
$TraitAssign: ident, $method_assign: ident) => {
impl<N, R: Dim, C: Dim, S> $Trait<N> for Matrix<N, R, C, S>
where N: Scalar + $bound,
S: Storage<N, R, C> {
type Output = OwnedMatrix<N, R, C, S::Alloc>;
#[inline]
fn $method(self, rhs: N) -> Self::Output {
let mut res = self.into_owned();
// XXX: optimize our iterator!
//
// Using our own iterator prevents loop unrolling, wich breaks some optimization
// (like SIMD). On the other hand, using the slice iterator is 4x faster.
// for left in res.iter_mut() {
for left in res.as_mut_slice().iter_mut() {
*left = left.$method(rhs)
}
res
}
}
impl<'a, N, R: Dim, C: Dim, S> $Trait<N> for &'a Matrix<N, R, C, S>
where N: Scalar + $bound,
S: Storage<N, R, C> {
type Output = OwnedMatrix<N, R, C, S::Alloc>;
#[inline]
fn $method(self, rhs: N) -> Self::Output {
self.clone_owned().$method(rhs)
}
}
impl<N, R: Dim, C: Dim, S> $TraitAssign<N> for Matrix<N, R, C, S>
where N: Scalar + $bound,
S: StorageMut<N, R, C> {
#[inline]
fn $method_assign(&mut self, right: N) {
for left in self.iter_mut() {
left.$method_assign(right)
}
}
}
}
);
componentwise_scalarop_impl!(Mul, mul, ClosedMul; MulAssign, mul_assign);
componentwise_scalarop_impl!(Div, div, ClosedDiv; DivAssign, div_assign);
macro_rules! left_scalar_mul_impl(
($($T: ty),* $(,)*) => {$(
impl<R: Dim, C: Dim, S> Mul<Matrix<$T, R, C, S>> for $T
where S: Storage<$T, R, C> {
type Output = OwnedMatrix<$T, R, C, S::Alloc>;
#[inline]
fn mul(self, right: Matrix<$T, R, C, S>) -> Self::Output {
let mut res = right.into_owned();
// XXX: optimize our iterator!
//
// Using our own iterator prevents loop unrolling, wich breaks some optimization
// (like SIMD). On the other hand, using the slice iterator is 4x faster.
// for right in res.iter_mut() {
for right in res.as_mut_slice().iter_mut() {
*right = self * *right
}
res
}
}
impl<'b, R: Dim, C: Dim, S> Mul<&'b Matrix<$T, R, C, S>> for $T
where S: Storage<$T, R, C> {
type Output = OwnedMatrix<$T, R, C, S::Alloc>;
#[inline]
fn mul(self, right: &'b Matrix<$T, R, C, S>) -> Self::Output {
self * right.clone_owned()
}
}
)*}
);
left_scalar_mul_impl!(
u8, u16, u32, u64, usize,
i8, i16, i32, i64, isize,
f32, f64
);
// Matrix × Matrix
impl<'a, 'b, N, R1: Dim, C1: Dim, R2: Dim, C2: Dim, SA, SB> Mul<&'b Matrix<N, R2, C2, SB>>
for &'a Matrix<N, R1, C1, SA>
where N: Scalar + Zero + ClosedAdd + ClosedMul,
SB: Storage<N, R2, C2>,
SA: Storage<N, R1, C1>,
SA::Alloc: Allocator<N, R1, C2>,
ShapeConstraint: AreMultipliable<R1, C1, R2, C2> {
type Output = MatrixMul<N, R1, C1, C2, SA>;
#[inline]
fn mul(self, right: &'b Matrix<N, R2, C2, SB>) -> Self::Output {
let (nrows1, ncols1) = self.shape();
let (nrows2, ncols2) = right.shape();
assert!(ncols1 == nrows2, "Matrix multiplication dimensions mismatch.");
let mut res: MatrixMul<N, R1, C1, C2, SA> = unsafe {
Matrix::new_uninitialized_generic(self.data.shape().0, right.data.shape().1)
};
for i in 0 .. nrows1 {
for j in 0 .. ncols2 {
let mut acc = N::zero();
unsafe {
for k in 0 .. ncols1 {
acc = acc + *self.get_unchecked(i, k) * *right.get_unchecked(k, j);
}
*res.get_unchecked_mut(i, j) = acc;
}
}
}
res
}
}
impl<'a, N, R1: Dim, C1: Dim, R2: Dim, C2: Dim, SA, SB> Mul<Matrix<N, R2, C2, SB>>
for &'a Matrix<N, R1, C1, SA>
where N: Scalar + Zero + ClosedAdd + ClosedMul,
SB: Storage<N, R2, C2>,
SA: Storage<N, R1, C1>,
SA::Alloc: Allocator<N, R1, C2>,
ShapeConstraint: AreMultipliable<R1, C1, R2, C2> {
type Output = MatrixMul<N, R1, C1, C2, SA>;
#[inline]
fn mul(self, right: Matrix<N, R2, C2, SB>) -> Self::Output {
self * &right
}
}
impl<'b, N, R1: Dim, C1: Dim, R2: Dim, C2: Dim, SA, SB> Mul<&'b Matrix<N, R2, C2, SB>>
for Matrix<N, R1, C1, SA>
where N: Scalar + Zero + ClosedAdd + ClosedMul,
SB: Storage<N, R2, C2>,
SA: Storage<N, R1, C1>,
SA::Alloc: Allocator<N, R1, C2>,
ShapeConstraint: AreMultipliable<R1, C1, R2, C2> {
type Output = MatrixMul<N, R1, C1, C2, SA>;
#[inline]
fn mul(self, right: &'b Matrix<N, R2, C2, SB>) -> Self::Output {
&self * right
}
}
impl<N, R1: Dim, C1: Dim, R2: Dim, C2: Dim, SA, SB> Mul<Matrix<N, R2, C2, SB>>
for Matrix<N, R1, C1, SA>
where N: Scalar + Zero + ClosedAdd + ClosedMul,
SB: Storage<N, R2, C2>,
SA: Storage<N, R1, C1>,
SA::Alloc: Allocator<N, R1, C2>,
ShapeConstraint: AreMultipliable<R1, C1, R2, C2> {
type Output = MatrixMul<N, R1, C1, C2, SA>;
#[inline]
fn mul(self, right: Matrix<N, R2, C2, SB>) -> Self::Output {
&self * &right
}
}
// FIXME: this is too restrictive:
// we can't use `a *= b` when `a` is a mutable slice.
// we can't use `a *= b` when C2 is not equal to C1.
impl<N, R1, C1, R2, SA, SB> MulAssign<Matrix<N, R2, C1, SB>> for Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim,
N: Scalar + Zero + ClosedAdd + ClosedMul,
SB: Storage<N, R2, C1>,
SA: OwnedStorage<N, R1, C1>,
ShapeConstraint: AreMultipliable<R1, C1, R2, C1>,
SA::Alloc: OwnedAllocator<N, R1, C1, SA> {
#[inline]
fn mul_assign(&mut self, right: Matrix<N, R2, C1, SB>) {
*self = &*self * right
}
}
impl<'b, N, R1, C1, R2, SA, SB> MulAssign<&'b Matrix<N, R2, C1, SB>> for Matrix<N, R1, C1, SA>
where R1: Dim, C1: Dim, R2: Dim,
N: Scalar + Zero + ClosedAdd + ClosedMul,
SB: Storage<N, R2, C1>,
SA: OwnedStorage<N, R1, C1>,
ShapeConstraint: AreMultipliable<R1, C1, R2, C1>,
// FIXME: this is too restrictive. See comments for the non-ref version.
SA::Alloc: OwnedAllocator<N, R1, C1, SA> {
#[inline]
fn mul_assign(&mut self, right: &'b Matrix<N, R2, C1, SB>) {
*self = &*self * right
}
}
impl<N, R1: Dim, C1: Dim, SA> Matrix<N, R1, C1, SA>
where N: Scalar + Zero + ClosedAdd + ClosedMul,
SA: Storage<N, R1, C1> {
/// Equivalent to `self.transpose() * right`.
#[inline]
pub fn tr_mul<R2: Dim, C2: Dim, SB>(&self, right: &Matrix<N, R2, C2, SB>) -> MatrixTrMul<N, R1, C1, C2, SA>
where SB: Storage<N, R2, C2>,
SA::Alloc: Allocator<N, C1, C2>,
ShapeConstraint: AreMultipliable<C1, R1, R2, C2> {
let (nrows1, ncols1) = self.shape();
let (nrows2, ncols2) = right.shape();
assert!(nrows1 == nrows2, "Matrix multiplication dimensions mismatch.");
let mut res: MatrixTrMul<N, R1, C1, C2, SA> = unsafe {
Matrix::new_uninitialized_generic(self.data.shape().1, right.data.shape().1)
};
for i in 0 .. ncols1 {
for j in 0 .. ncols2 {
let mut acc = N::zero();
unsafe {
for k in 0 .. nrows1 {
acc = acc + *self.get_unchecked(k, i) * *right.get_unchecked(k, j);
}
*res.get_unchecked_mut(i, j) = acc;
}
}
}
res
}
}

107
src/core/properties.rs Normal file
View File

@ -0,0 +1,107 @@
// Matrix properties checks.
use num::{Zero, One};
use approx::ApproxEq;
use alga::general::{ClosedAdd, ClosedMul, ClosedSub, Field};
use core::{Scalar, Matrix, SquareMatrix};
use core::dimension::Dim;
use core::storage::Storage;
impl<N: Scalar, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S> {
/// Indicates if this is a square matrix.
#[inline]
pub fn is_square(&self) -> bool {
let shape = self.shape();
shape.0 == shape.1
}
}
impl<N: Scalar, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S>
// FIXME: ApproxEq prevents us from using those methods on integer matrices…
where N: ApproxEq,
N::Epsilon: Copy {
/// Indicated if this is the identity matrix within a relative error of `eps`.
///
/// If the matrix is diagonal, this checks that diagonal elements (i.e. at coordinates `(i, i)`
/// for i from `0` to `min(R, C)`) are equal one; and that all other elements are zero.
#[inline]
pub fn is_identity(&self, eps: N::Epsilon) -> bool
where N: Zero + One {
let (nrows, ncols) = self.shape();
let d;
if nrows > ncols {
d = ncols;
for i in d .. nrows {
for j in 0 .. ncols {
if !relative_eq!(self[(i, j)], N::zero(), epsilon = eps) {
return false;
}
}
}
}
else { // nrows <= ncols
d = nrows;
for i in 0 .. nrows {
for j in d .. ncols {
if !relative_eq!(self[(i, j)], N::zero(), epsilon = eps) {
return false;
}
}
}
}
// Off-diagonal elements of the sub-square matrix.
for i in 1 .. d {
for j in 0 .. i {
// FIXME: use unsafe indexing.
if !relative_eq!(self[(i, j)], N::zero(), epsilon = eps) ||
!relative_eq!(self[(j, i)], N::zero(), epsilon = eps) {
return false;
}
}
}
// Diagonal elements of the sub-square matrix.
for i in 0 .. d {
if !relative_eq!(self[(i, i)], N::one(), epsilon = eps) {
return false;
}
}
true
}
}
impl<N: Scalar + ApproxEq, D: Dim, S: Storage<N, D, D>> SquareMatrix<N, D, S>
where N: Zero + One + ClosedAdd + ClosedMul,
N::Epsilon: Copy {
/// Checks that this matrix is orthogonal, i.e., that it is square and `M × Mᵀ = Id`.
///
/// In this definition `Id` is approximately equal to the identity matrix with a relative error
/// equal to `eps`.
#[inline]
pub fn is_orthogonal(&self, eps: N::Epsilon) -> bool {
self.is_square() && (self.tr_mul(self)).is_identity(eps)
}
/// Checks that this matrix is orthogonal and has a determinant equal to 1.
#[inline]
pub fn is_special_orthogonal(&self, eps: N::Epsilon) -> bool
where N: ClosedSub + PartialOrd {
self.is_orthogonal(eps) && self.determinant() > N::zero()
}
/// Returns `true` if this matrix is invertible.
#[inline]
pub fn is_invertible(&self) -> bool
where N: Field {
// FIXME: improve this?
self.clone_owned().try_inverse().is_some()
}
}

9
src/core/scalar.rs Normal file
View File

@ -0,0 +1,9 @@
use std::fmt::Debug;
use std::any::Any;
/// The basic scarar type for all structures of `nalgebra`.
///
/// This does not make any assumption on the algebraic properties of `Self`.
pub trait Scalar: Copy + PartialEq + Debug + Any {
}
impl<T: Copy + PartialEq + Debug + Any> Scalar for T { }

184
src/core/storage.rs Normal file
View File

@ -0,0 +1,184 @@
//! Abstract definition of a matrix data storage.
use std::mem;
use std::any::Any;
use core::Scalar;
use dimension::Dim;
use allocator::{Allocator, SameShapeR, SameShapeC};
/*
* Aliases for sum storage.
*/
/// The data storage for the sum of two matrices with dimensions `(R1, C1)` and `(R2, C2)`.
pub type SumStorage<N, R1, C1, R2, C2, SA> =
<<SA as Storage<N, R1, C1>>::Alloc as Allocator<N, SameShapeR<R1, R2>, SameShapeC<C1, C2>>>::Buffer;
/*
* Aliases for multiplication storage.
*/
/// The data storage for the multiplication of two matrices with dimensions `(R1, C1)` on the left
/// hand side, and with `C2` columns on the right hand side.
pub type MulStorage<N, R1, C1, C2, SA> =
<<SA as Storage<N, R1, C1>>::Alloc as Allocator<N, R1, C2>>::Buffer;
/// The data storage for the multiplication of two matrices with dimensions `(R1, C1)` on the left
/// hand side, and with `C2` columns on the right hand side. The first matrix is implicitly
/// transposed.
pub type TrMulStorage<N, R1, C1, C2, SA> =
<<SA as Storage<N, R1, C1>>::Alloc as Allocator<N, C1, C2>>::Buffer;
/*
* Alias for allocation result.
*/
/// The owned data storage that can be allocated from `S`.
pub type Owned<N, R, C, A> =
<A as Allocator<N, R, C>>::Buffer;
/// The trait shared by all matrix data storage.
///
/// FIXME: doc
///
/// Note that `Self` must always have a number of elements compatible with the matrix length (given
/// by `R` and `C` if they are known at compile-time). For example, implementors of this trait
/// should **not** allow the user to modify the size of the underlying buffer with safe methods
/// (for example the `MatrixVec::data_mut` method is unsafe because the user could change the
/// vector's size so that it no longer contains enough elements: this will lead to UB.
pub unsafe trait Storage<N: Scalar, R: Dim, C: Dim>: Sized {
/// The static stride of this storage's rows.
type RStride: Dim;
/// The static stride of this storage's columns.
type CStride: Dim;
/// The allocator for this family of storage.
type Alloc: Allocator<N, R, C>;
/// Builds a matrix data storage that does not contain any reference.
fn into_owned(self) -> Owned<N, R, C, Self::Alloc>;
/// Clones this data storage into one that does not contain any reference.
fn clone_owned(&self) -> Owned<N, R, C, Self::Alloc>;
/// The matrix data pointer.
fn ptr(&self) -> *const N;
/// The dimension of the matrix at run-time. Arr length of zero indicates the additive identity
/// element of any dimension. Must be equal to `Self::dimension()` if it is not `None`.
fn shape(&self) -> (R, C);
/// The spacing between concecutive row elements and consecutive column elements.
///
/// For example this returns `(1, 5)` for a row-major matrix with 5 columns.
fn strides(&self) -> (Self::RStride, Self::CStride);
/// Compute the index corresponding to the irow-th row and icol-th column of this matrix. The
/// index must be such that the following holds:
///
/// ```.ignore
/// let lindex = self.linear_index(irow, icol);
/// assert!(*self.get_unchecked(irow, icol) == *self.get_unchecked_linear(lindex)
/// ```
#[inline]
fn linear_index(&self, irow: usize, icol: usize) -> usize {
let (rstride, cstride) = self.strides();
irow * rstride.value() + icol * cstride.value()
}
/// Gets the address of the i-th matrix component without performing bound-checking.
#[inline]
unsafe fn get_address_unchecked_linear(&self, i: usize) -> *const N {
self.ptr().offset(i as isize)
}
/// Gets the address of the i-th matrix component without performing bound-checking.
#[inline]
unsafe fn get_address_unchecked(&self, irow: usize, icol: usize) -> *const N {
self.get_address_unchecked_linear(self.linear_index(irow, icol))
}
/// Retrieves a reference to the i-th element without bound-checking.
#[inline]
unsafe fn get_unchecked_linear(&self, i: usize) -> &N {
&*self.get_address_unchecked_linear(i)
}
/// Retrieves a reference to the i-th element without bound-checking.
#[inline]
unsafe fn get_unchecked(&self, irow: usize, icol: usize) -> &N {
self.get_unchecked_linear(self.linear_index(irow, icol))
}
}
/// Trait implemented by matrix data storage that can provide a mutable access to its elements.
///
/// Note that a mutable access does not mean that the matrix owns its data. For example, a mutable
/// matrix slice can provide mutable access to its elements even if it does not own its data (it
/// contains only an internal reference to them).
pub unsafe trait StorageMut<N: Scalar, R: Dim, C: Dim>: Storage<N, R, C> {
/// The matrix mutable data pointer.
fn ptr_mut(&mut self) -> *mut N;
/// Gets the mutable address of the i-th matrix component without performing bound-checking.
#[inline]
unsafe fn get_address_unchecked_linear_mut(&mut self, i: usize) -> *mut N {
self.ptr_mut().offset(i as isize)
}
/// Gets the mutable address of the i-th matrix component without performing bound-checking.
#[inline]
unsafe fn get_address_unchecked_mut(&mut self, irow: usize, icol: usize) -> *mut N {
let lid = self.linear_index(irow, icol);
self.get_address_unchecked_linear_mut(lid)
}
/// Retrieves a mutable reference to the i-th element without bound-checking.
unsafe fn get_unchecked_linear_mut(&mut self, i: usize) -> &mut N {
&mut *self.get_address_unchecked_linear_mut(i)
}
/// Retrieves a mutable reference to the element at `(irow, icol)` without bound-checking.
#[inline]
unsafe fn get_unchecked_mut(&mut self, irow: usize, icol: usize) -> &mut N {
&mut *self.get_address_unchecked_mut(irow, icol)
}
/// Swaps two elements using their linear index without bound-checking.
#[inline]
unsafe fn swap_unchecked_linear(&mut self, i1: usize, i2: usize) {
let a = self.get_address_unchecked_linear_mut(i1);
let b = self.get_address_unchecked_linear_mut(i2);
mem::swap(&mut *a, &mut *b);
}
/// Swaps two elements without bound-checking.
#[inline]
unsafe fn swap_unchecked(&mut self, row_col1: (usize, usize), row_col2: (usize, usize)) {
let lid1 = self.linear_index(row_col1.0, row_col1.1);
let lid2 = self.linear_index(row_col2.0, row_col2.1);
self.swap_unchecked_linear(lid1, lid2)
}
}
/// A matrix storage that does not contain any reference and that is stored contiguously in memory.
///
/// The storage requirement means that for any value of `i` in `[0, nrows * ncols[`, the value
/// `.get_unchecked_linear` succeeds. This trait is unsafe because failing to comply to this may
/// cause Undefined Behaviors.
pub unsafe trait OwnedStorage<N: Scalar, R: Dim, C: Dim>: StorageMut<N, R, C> + Clone + Any
where Self::Alloc: Allocator<N, R, C, Buffer = Self> {
// NOTE: We could auto-impl those two methods but we don't to make sure the user is aware that
// data must be contiguous.
/// Converts this data storage to a slice.
#[inline]
fn as_slice(&self) -> &[N];
/// Converts this data storage to a mutable slice.
#[inline]
fn as_mut_slice(&mut self) -> &mut [N];
}

176
src/core/unit.rs Normal file
View File

@ -0,0 +1,176 @@
use std::mem;
use std::ops::{Neg, Deref};
use approx::ApproxEq;
use alga::general::SubsetOf;
use alga::linear::NormedSpace;
/// A wrapper that ensures the undelying algebraic entity has a unit norm.
///
/// Use `.as_ref()` or `.unwrap()` to obtain the undelying value by-reference or by-move.
#[repr(C)]
#[derive(Eq, PartialEq, Clone, Hash, Debug, Copy)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct Unit<T> {
value: T
}
impl<T: NormedSpace> Unit<T> {
/// Normalize the given value and return it wrapped on a `Unit` structure.
#[inline]
pub fn new_normalize(value: T) -> Self {
Self::new_and_get(value).0
}
/// Attempts to normalize the given value and return it wrapped on a `Unit` structure.
///
/// Returns `None` if the norm was smaller or equal to `min_norm`.
#[inline]
pub fn try_new(value: T, min_norm: T::Field) -> Option<Self> {
Self::try_new_and_get(value, min_norm).map(|res| res.0)
}
/// Normalize the given value and return it wrapped on a `Unit` structure and its norm.
#[inline]
pub fn new_and_get(mut value: T) -> (Self, T::Field) {
let n = value.normalize_mut();
(Unit { value: value }, n)
}
/// Normalize the given value and return it wrapped on a `Unit` structure and its norm.
///
/// Returns `None` if the norm was smaller or equal to `min_norm`.
#[inline]
pub fn try_new_and_get(mut value: T, min_norm: T::Field) -> Option<(Self, T::Field)> {
if let Some(n) = value.try_normalize_mut(min_norm) {
Some((Unit { value: value }, n))
}
else {
None
}
}
/// Normalizes this value again. This is useful when repeated computations
/// might cause a drift in the norm because of float inaccuracies.
///
/// Returns the norm before re-normalization (should be close to `1.0`).
#[inline]
pub fn renormalize(&mut self) -> T::Field {
self.value.normalize_mut()
}
}
impl<T> Unit<T> {
/// Wraps the given value, assuming it is already normalized.
///
/// This function is not safe because `value` is not verified to be actually normalized.
#[inline]
pub fn new_unchecked(value: T) -> Self {
Unit { value: value }
}
/// Retrieves the underlying value.
#[inline]
pub fn unwrap(self) -> T {
self.value
}
/// Returns a mutable reference to the underlying value. This is `_unchecked` because modifying
/// the underlying value in such a way that it no longer has unit length may lead to unexpected
/// results.
#[inline]
pub fn as_mut_unchecked(&mut self) -> &mut T {
&mut self.value
}
}
impl<T> AsRef<T> for Unit<T> {
#[inline]
fn as_ref(&self) -> &T {
&self.value
}
}
/*
*
* Conversions.
*
*/
impl<T: NormedSpace> SubsetOf<T> for Unit<T>
where T::Field: ApproxEq {
#[inline]
fn to_superset(&self) -> T {
self.clone().unwrap()
}
#[inline]
fn is_in_subset(value: &T) -> bool {
relative_eq!(value.norm_squared(), ::one())
}
#[inline]
unsafe fn from_superset_unchecked(value: &T) -> Self {
Unit::new_normalize(value.clone()) // We still need to re-normalize because the condition is inexact.
}
}
// impl<T: ApproxEq> ApproxEq for Unit<T> {
// type Epsilon = T::Epsilon;
//
// #[inline]
// fn default_epsilon() -> Self::Epsilon {
// T::default_epsilon()
// }
//
// #[inline]
// fn default_max_relative() -> Self::Epsilon {
// T::default_max_relative()
// }
//
// #[inline]
// fn default_max_ulps() -> u32 {
// T::default_max_ulps()
// }
//
// #[inline]
// fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
// self.value.relative_eq(&other.value, epsilon, max_relative)
// }
//
// #[inline]
// fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
// self.value.ulps_eq(&other.value, epsilon, max_ulps)
// }
// }
// FIXME:re-enable this impl when spacialization is possible.
// Currently, it is disabled so that we can have a nice output for the `UnitQuaternion` display.
/*
impl<T: fmt::Display> fmt::Display for Unit<T> {
// XXX: will not always work correctly due to rounding errors.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.value.fmt(f)
}
}
*/
impl<T: Neg> Neg for Unit<T> {
type Output = Unit<T::Output>;
#[inline]
fn neg(self) -> Self::Output {
Unit::new_unchecked(-self.value)
}
}
impl<T> Deref for Unit<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
unsafe { mem::transmute(self) }
}
}

206
src/geometry/isometry.rs Normal file
View File

@ -0,0 +1,206 @@
use std::fmt;
use std::marker::PhantomData;
use approx::ApproxEq;
use alga::general::{Real, SubsetOf};
use alga::linear::Rotation;
use core::{Scalar, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::{Storage, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{TranslationBase, PointBase};
/// An isometry that uses a data storage deduced from the allocator `A`.
pub type OwnedIsometryBase<N, D, A, R> =
IsometryBase<N, D, <A as Allocator<N, D, U1>>::Buffer, R>;
/// A direct isometry, i.e., a rotation followed by a translation.
#[repr(C)]
#[derive(Hash, Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct IsometryBase<N: Scalar, D: DimName, S, R> {
/// The pure rotational part of this isometry.
pub rotation: R,
/// The pure translational part of this isometry.
pub translation: TranslationBase<N, D, S>,
// One dummy private field just to prevent explicit construction.
#[cfg_attr(feature = "serde-serialize", serde(skip_serializing, skip_deserializing))]
_noconstruct: PhantomData<N>
}
impl<N, D: DimName, S, R> IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new isometry from its rotational and translational parts.
#[inline]
pub fn from_parts(translation: TranslationBase<N, D, S>, rotation: R) -> IsometryBase<N, D, S, R> {
IsometryBase {
rotation: rotation,
translation: translation,
_noconstruct: PhantomData
}
}
/// Inverts `self`.
#[inline]
pub fn inverse(&self) -> IsometryBase<N, D, S, R> {
let mut res = self.clone();
res.inverse_mut();
res
}
/// Inverts `self`.
#[inline]
pub fn inverse_mut(&mut self) {
self.rotation.inverse_mut();
self.translation.inverse_mut();
self.translation.vector = self.rotation.transform_vector(&self.translation.vector);
}
/// Appends to `self` the given translation in-place.
#[inline]
pub fn append_translation_mut(&mut self, t: &TranslationBase<N, D, S>) {
self.translation.vector += &t.vector
}
/// Appends to `self` the given rotation in-place.
#[inline]
pub fn append_rotation_mut(&mut self, r: &R) {
self.rotation = self.rotation.append_rotation(&r);
self.translation.vector = r.transform_vector(&self.translation.vector);
}
/// Appends in-place to `self` a rotation centered at the point `p`, i.e., the rotation that
/// lets `p` invariant.
#[inline]
pub fn append_rotation_wrt_point_mut(&mut self, r: &R, p: &PointBase<N, D, S>) {
self.translation.vector -= &p.coords;
self.append_rotation_mut(r);
self.translation.vector += &p.coords;
}
/// Appends in-place to `self` a rotation centered at the point with coordinates
/// `self.translation`.
#[inline]
pub fn append_rotation_wrt_center_mut(&mut self, r: &R) {
let center = PointBase::from_coordinates(self.translation.vector.clone());
self.append_rotation_wrt_point_mut(r, &center)
}
}
// NOTE: we don't require `R: Rotation<...>` here because this is not useful for the implementation
// and makes it hard to use it, e.g., for Transform × Isometry implementation.
// This is OK since all constructors of the isometry enforce the Rotation bound already (and
// explicit struct construction is prevented by the dummy ZST field).
impl<N, D: DimName, S, R> IsometryBase<N, D, S, R>
where N: Scalar,
S: Storage<N, D, U1> {
/// Converts this isometry into its equivalent homogeneous transformation matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>
where D: DimNameAdd<U1>,
R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>>,
S::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
let mut res: OwnedSquareMatrix<N, _, S::Alloc> = ::convert_ref(&self.rotation);
res.fixed_slice_mut::<D, U1>(0, D::dim()).copy_from(&self.translation.vector);
res
}
}
impl<N, D: DimName, S, R> Eq for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + Eq,
S::Alloc: OwnedAllocator<N, D, U1, S> {
}
impl<N, D: DimName, S, R> PartialEq for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + PartialEq,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn eq(&self, right: &IsometryBase<N, D, S, R>) -> bool {
self.translation == right.translation &&
self.rotation == right.rotation
}
}
impl<N, D: DimName, S, R> ApproxEq for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + ApproxEq<Epsilon = N::Epsilon>,
S::Alloc: OwnedAllocator<N, D, U1, S>,
N::Epsilon: Copy {
type Epsilon = N::Epsilon;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.translation.relative_eq(&other.translation, epsilon, max_relative) &&
self.rotation.relative_eq(&other.rotation, epsilon, max_relative)
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.translation.ulps_eq(&other.translation, epsilon, max_ulps) &&
self.rotation.ulps_eq(&other.rotation, epsilon, max_ulps)
}
}
/*
*
* Display
*
*/
impl<N, D: DimName, S, R> fmt::Display for IsometryBase<N, D, S, R>
where N: Real + fmt::Display,
S: OwnedStorage<N, D, U1>,
R: fmt::Display,
S::Alloc: OwnedAllocator<N, D, U1, S> + Allocator<usize, D, U1> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let precision = f.precision().unwrap_or(3);
try!(writeln!(f, "IsometryBase {{"));
try!(write!(f, "{:.*}", precision, self.translation));
try!(write!(f, "{:.*}", precision, self.rotation));
writeln!(f, "}}")
}
}
// /*
// *
// * Absolute
// *
// */
// impl<N: Absolute> Absolute for $t<N> {
// type AbsoluteValue = $submatrix<N::AbsoluteValue>;
//
// #[inline]
// fn abs(m: &$t<N>) -> $submatrix<N::AbsoluteValue> {
// Absolute::abs(&m.submatrix)
// }
// }

View File

@ -0,0 +1,198 @@
use alga::general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
AbstractSemigroup, Real, Inverse, Multiplicative, Identity, Id};
use alga::linear::{Transformation, Similarity, AffineTransformation, DirectIsometry, Isometry,
Rotation, ProjectiveTransformation};
use core::ColumnVector;
use core::dimension::{DimName, U1};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{IsometryBase, TranslationBase, PointBase};
/*
*
* Algebraic structures.
*
*/
impl<N, D: DimName, S, R> Identity<Multiplicative> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S, R> Inverse<Multiplicative> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn inverse(&self) -> Self {
self.inverse()
}
#[inline]
fn inverse_mut(&mut self) {
self.inverse_mut()
}
}
impl<N, D: DimName, S, R> AbstractMagma<Multiplicative> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
macro_rules! impl_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimName, S, R> $marker<$operator> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> { }
)*}
);
impl_multiplicative_structures!(
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
AbstractQuasigroup<Multiplicative>,
AbstractLoop<Multiplicative>,
AbstractGroup<Multiplicative>
);
/*
*
* Transformation groups.
*
*/
impl<N, D: DimName, S, R> Transformation<PointBase<N, D, S>> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn transform_point(&self, pt: &PointBase<N, D, S>) -> PointBase<N, D, S> {
self * pt
}
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, D, S>) -> ColumnVector<N, D, S> {
self * v
}
}
impl<N, D: DimName, S, R> ProjectiveTransformation<PointBase<N, D, S>> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn inverse_transform_point(&self, pt: &PointBase<N, D, S>) -> PointBase<N, D, S> {
self.rotation.inverse_transform_point(&(pt - &self.translation.vector))
}
#[inline]
fn inverse_transform_vector(&self, v: &ColumnVector<N, D, S>) -> ColumnVector<N, D, S> {
self.rotation.inverse_transform_vector(v)
}
}
impl<N, D: DimName, S, R> AffineTransformation<PointBase<N, D, S>> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Rotation = R;
type NonUniformScaling = Id;
type Translation = TranslationBase<N, D, S>;
#[inline]
fn decompose(&self) -> (TranslationBase<N, D, S>, R, Id, R) {
(self.translation.clone(), self.rotation.clone(), Id::new(), R::identity())
}
#[inline]
fn append_translation(&self, t: &Self::Translation) -> Self {
t * self
}
#[inline]
fn prepend_translation(&self, t: &Self::Translation) -> Self {
self * t
}
#[inline]
fn append_rotation(&self, r: &Self::Rotation) -> Self {
let shift = r.transform_vector(&self.translation.vector);
IsometryBase::from_parts(TranslationBase::from_vector(shift), r.clone() * self.rotation.clone())
}
#[inline]
fn prepend_rotation(&self, r: &Self::Rotation) -> Self {
self * r
}
#[inline]
fn append_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
#[inline]
fn prepend_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
#[inline]
fn append_rotation_wrt_point(&self, r: &Self::Rotation, p: &PointBase<N, D, S>) -> Option<Self> {
let mut res = self.clone();
res.append_rotation_wrt_point_mut(r, p);
Some(res)
}
}
impl<N, D: DimName, S, R> Similarity<PointBase<N, D, S>> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Scaling = Id;
#[inline]
fn translation(&self) -> TranslationBase<N, D, S> {
self.translation.clone()
}
#[inline]
fn rotation(&self) -> R {
self.rotation.clone()
}
#[inline]
fn scaling(&self) -> Id {
Id::new()
}
}
macro_rules! marker_impl(
($($Trait: ident),*) => {$(
impl<N, D: DimName, S, R> $Trait<PointBase<N, D, S>> for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> { }
)*}
);
marker_impl!(Isometry, DirectIsometry);

View File

@ -0,0 +1,19 @@
use core::MatrixArray;
use core::dimension::{U1, U2, U3};
use geometry::{Rotation, IsometryBase, UnitQuaternion, UnitComplex};
/// A D-dimensional isometry.
pub type Isometry<N, D> = IsometryBase<N, D, MatrixArray<N, D, U1>, Rotation<N, D>>;
/// A 2-dimensional isometry using a unit complex number for its rotational part.
pub type Isometry2<N> = IsometryBase<N, U2, MatrixArray<N, U2, U1>, UnitComplex<N>>;
/// A 3-dimensional isometry using a unit quaternion for its rotational part.
pub type Isometry3<N> = IsometryBase<N, U3, MatrixArray<N, U3, U1>, UnitQuaternion<N>>;
/// A 2-dimensional isometry using a rotation matrix for its rotation part.
pub type IsometryMatrix2<N> = Isometry<N, U2>;
/// A 3-dimensional isometry using a rotation matrix for its rotation part.
pub type IsometryMatrix3<N> = Isometry<N, U3>;

View File

@ -0,0 +1,195 @@
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use num::One;
use rand::{Rng, Rand};
use alga::general::Real;
use alga::linear::Rotation as AlgaRotation;
use core::ColumnVector;
use core::dimension::{DimName, U1, U2, U3, U4};
use core::allocator::{OwnedAllocator, Allocator};
use core::storage::OwnedStorage;
use geometry::{PointBase, TranslationBase, RotationBase, IsometryBase, UnitQuaternionBase, UnitComplex};
impl<N, D: DimName, S, R> IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new identity isometry.
#[inline]
pub fn identity() -> Self {
Self::from_parts(TranslationBase::identity(), R::identity())
}
}
impl<N, D: DimName, S, R> One for IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new identity isometry.
#[inline]
fn one() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S, R> Rand for IsometryBase<N, D, S, R>
where N: Real + Rand,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>> + Rand,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn rand<G: Rng>(rng: &mut G) -> Self {
Self::from_parts(rng.gen(), rng.gen())
}
}
impl<N, D: DimName, S, R> IsometryBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// The isometry that applies the rotation `r` with its axis passing through the point `p`.
/// This effectively lets `p` invariant.
#[inline]
pub fn rotation_wrt_point(r: R, p: PointBase<N, D, S>) -> Self {
let shift = r.transform_vector(&-&p.coords);
Self::from_parts(TranslationBase::from_vector(shift + p.coords), r)
}
}
#[cfg(feature = "arbitrary")]
impl<N, D: DimName, S, R> Arbitrary for IsometryBase<N, D, S, R>
where N: Real + Arbitrary + Send,
S: OwnedStorage<N, D, U1> + Send,
R: AlgaRotation<PointBase<N, D, S>> + Arbitrary + Send,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn arbitrary<G: Gen>(rng: &mut G) -> Self {
Self::from_parts(Arbitrary::arbitrary(rng), Arbitrary::arbitrary(rng))
}
}
/*
*
* Constructors for various static dimensions.
*
*/
// 2D rotation.
impl<N, S, SR> IsometryBase<N, U2, S, RotationBase<N, U2, SR>>
where N: Real,
S: OwnedStorage<N, U2, U1, Alloc = SR::Alloc>,
SR: OwnedStorage<N, U2, U2>,
S::Alloc: OwnedAllocator<N, U2, U1, S>,
SR::Alloc: OwnedAllocator<N, U2, U2, SR> {
/// Creates a new isometry from a translation and a rotation angle.
#[inline]
pub fn new(translation: ColumnVector<N, U2, S>, angle: N) -> Self {
Self::from_parts(TranslationBase::from_vector(translation), RotationBase::<N, U2, SR>::new(angle))
}
}
impl<N, S> IsometryBase<N, U2, S, UnitComplex<N>>
where N: Real,
S: OwnedStorage<N, U2, U1>,
S::Alloc: OwnedAllocator<N, U2, U1, S> {
/// Creates a new isometry from a translation and a rotation angle.
#[inline]
pub fn new(translation: ColumnVector<N, U2, S>, angle: N) -> Self {
Self::from_parts(TranslationBase::from_vector(translation), UnitComplex::from_angle(angle))
}
}
// 3D rotation.
macro_rules! isometry_construction_impl(
($RotId: ident < $($RotParams: ident),*>, $RRDim: ty, $RCDim: ty) => {
impl<N, S, SR> IsometryBase<N, U3, S, $RotId<$($RotParams),*>>
where N: Real,
S: OwnedStorage<N, U3, U1, Alloc = SR::Alloc>,
SR: OwnedStorage<N, $RRDim, $RCDim>,
S::Alloc: OwnedAllocator<N, U3, U1, S>,
SR::Alloc: OwnedAllocator<N, $RRDim, $RCDim, SR> +
Allocator<N, U3, U3> {
/// Creates a new isometry from a translation and a rotation axis-angle.
#[inline]
pub fn new(translation: ColumnVector<N, U3, S>, axisangle: ColumnVector<N, U3, S>) -> Self {
Self::from_parts(
TranslationBase::from_vector(translation),
$RotId::<$($RotParams),*>::from_scaled_axis(axisangle))
}
/// Creates an isometry that corresponds to the local frame of an observer standing at the
/// point `eye` and looking toward `target`.
///
/// It maps the view direction `target - eye` to the positive `z` axis and the origin to the
/// `eye`.
///
/// # Arguments
/// * eye - The observer position.
/// * target - The target position.
/// * up - Vertical direction. The only requirement of this parameter is to not be collinear
/// to `eye - at`. Non-collinearity is not checked.
#[inline]
pub fn new_observer_frame(eye: &PointBase<N, U3, S>,
target: &PointBase<N, U3, S>,
up: &ColumnVector<N, U3, S>)
-> Self {
Self::from_parts(
TranslationBase::from_vector(eye.coords.clone()),
$RotId::new_observer_frame(&(target - eye), up))
}
/// Builds a right-handed look-at view matrix.
///
/// This conforms to the common notion of right handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_rh(eye: &PointBase<N, U3, S>,
target: &PointBase<N, U3, S>,
up: &ColumnVector<N, U3, S>)
-> Self {
let rotation = $RotId::look_at_rh(&(target - eye), up);
let trans = &rotation * (-eye);
Self::from_parts(TranslationBase::from_vector(trans.coords), rotation)
}
/// Builds a left-handed look-at view matrix.
///
/// This conforms to the common notion of left handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_lh(eye: &PointBase<N, U3, S>,
target: &PointBase<N, U3, S>,
up: &ColumnVector<N, U3, S>)
-> Self {
let rotation = $RotId::look_at_lh(&(target - eye), up);
let trans = &rotation * (-eye);
Self::from_parts(TranslationBase::from_vector(trans.coords), rotation)
}
}
}
);
isometry_construction_impl!(RotationBase<N, U3, SR>, U3, U3);
isometry_construction_impl!(UnitQuaternionBase<N, SR>, U4, U1);

View File

@ -0,0 +1,163 @@
use alga::general::{Real, SubsetOf, SupersetOf};
use alga::linear::Rotation;
use core::{SquareMatrix, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameAdd, DimNameSum, U1};
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, TranslationBase, IsometryBase, SimilarityBase, TransformBase, SuperTCategoryOf, TAffine};
/*
* This file provides the following conversions:
* =============================================
*
* IsometryBase -> IsometryBase
* IsometryBase -> SimilarityBase
* IsometryBase -> TransformBase
* IsometryBase -> Matrix (homogeneous)
*/
impl<N1, N2, D: DimName, SA, SB, R1, R2> SubsetOf<IsometryBase<N2, D, SB, R2>> for IsometryBase<N1, D, SA, R1>
where N1: Real,
N2: Real + SupersetOf<N1>,
R1: Rotation<PointBase<N1, D, SA>> + SubsetOf<R2>,
R2: Rotation<PointBase<N2, D, SB>>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, D, U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> IsometryBase<N2, D, SB, R2> {
IsometryBase::from_parts(
self.translation.to_superset(),
self.rotation.to_superset()
)
}
#[inline]
fn is_in_subset(iso: &IsometryBase<N2, D, SB, R2>) -> bool {
::is_convertible::<_, TranslationBase<N1, D, SA>>(&iso.translation) &&
::is_convertible::<_, R1>(&iso.rotation)
}
#[inline]
unsafe fn from_superset_unchecked(iso: &IsometryBase<N2, D, SB, R2>) -> Self {
IsometryBase::from_parts(
iso.translation.to_subset_unchecked(),
iso.rotation.to_subset_unchecked()
)
}
}
impl<N1, N2, D: DimName, SA, SB, R1, R2> SubsetOf<SimilarityBase<N2, D, SB, R2>> for IsometryBase<N1, D, SA, R1>
where N1: Real,
N2: Real + SupersetOf<N1>,
R1: Rotation<PointBase<N1, D, SA>> + SubsetOf<R2>,
R2: Rotation<PointBase<N2, D, SB>>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, D, U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> SimilarityBase<N2, D, SB, R2> {
SimilarityBase::from_isometry(
self.to_superset(),
N2::one()
)
}
#[inline]
fn is_in_subset(sim: &SimilarityBase<N2, D, SB, R2>) -> bool {
::is_convertible::<_, IsometryBase<N1, D, SA, R1>>(&sim.isometry) &&
sim.scaling() == N2::one()
}
#[inline]
unsafe fn from_superset_unchecked(sim: &SimilarityBase<N2, D, SB, R2>) -> Self {
::convert_ref_unchecked(&sim.isometry)
}
}
impl<N1, N2, D, SA, SB, R, C> SubsetOf<TransformBase<N2, D, SB, C>> for IsometryBase<N1, D, SA, R>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SuperTCategoryOf<TAffine>,
R: Rotation<PointBase<N1, D, SA>> +
SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous()
SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm)
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> +
Allocator<N1, D, D> + // needed by R
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous()
Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut
Allocator<N2, D, U1> + // needed by: m.fixed_slice
Allocator<N2, U1, D> { // needed by: m.fixed_slice
#[inline]
fn to_superset(&self) -> TransformBase<N2, D, SB, C> {
TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset())
}
#[inline]
fn is_in_subset(t: &TransformBase<N2, D, SB, C>) -> bool {
<Self as SubsetOf<_>>::is_in_subset(t.matrix())
}
#[inline]
unsafe fn from_superset_unchecked(t: &TransformBase<N2, D, SB, C>) -> Self {
Self::from_superset_unchecked(t.matrix())
}
}
impl<N1, N2, D, SA, SB, R> SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>> for IsometryBase<N1, D, SA, R>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
R: Rotation<PointBase<N1, D, SA>> +
SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous()
SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm)
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> +
Allocator<N1, D, D> + // needed by R
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous()
Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut
Allocator<N2, D, U1> + // needed by: m.fixed_slice
Allocator<N2, U1, D> { // needed by: m.fixed_slice
#[inline]
fn to_superset(&self) -> SquareMatrix<N2, DimNameSum<D, U1>, SB> {
self.to_homogeneous().to_superset()
}
#[inline]
fn is_in_subset(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> bool {
let rot = m.fixed_slice::<D, D>(0, 0);
let bottom = m.fixed_slice::<U1, D>(D::dim(), 0);
// Scalar types agree.
m.iter().all(|e| SupersetOf::<N1>::is_in_subset(e)) &&
// The block part is a rotation.
rot.is_special_orthogonal(N2::default_epsilon() * ::convert(100.0)) &&
// The bottom row is (0, 0, ..., 1)
bottom.iter().all(|e| e.is_zero()) &&
m[(D::dim(), D::dim())] == N2::one()
}
#[inline]
unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> Self {
let t = m.fixed_slice::<D, U1>(0, D::dim()).into_owned();
let t = TranslationBase::from_vector(::convert_unchecked(t));
Self::from_parts(t, ::convert_unchecked(m.clone_owned()))
}
}

View File

@ -0,0 +1,435 @@
use std::ops::{Mul, MulAssign, Div, DivAssign};
use alga::general::Real;
use alga::linear::Rotation;
use core::ColumnVector;
use core::dimension::{DimName, U1, U3, U4};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{PointBase, RotationBase, IsometryBase, TranslationBase, UnitQuaternionBase};
// FIXME: there are several cloning of rotations that we could probably get rid of (but we didn't
// yet because that would require to add a bound like `where for<'a, 'b> &'a R: Mul<&'b R, Output = R>`
// which is quite ugly.
/*
*
* In this file, we provide:
* =========================
*
*
* (Operators)
*
* IsometryBase × IsometryBase
* IsometryBase × R
*
*
* IsometryBase ÷ IsometryBase
* IsometryBase ÷ R
*
* IsometryBase × PointBase
* IsometryBase × ColumnVector
*
*
* IsometryBase × TranslationBase
* TranslationBase × IsometryBase
* TranslationBase × R -> IsometryBase<R>
*
* NOTE: The following are provided explicitly because we can't have R × IsometryBase.
* RotationBase × IsometryBase<RotationBase>
* UnitQuaternion × IsometryBase<UnitQuaternion>
*
* RotationBase ÷ IsometryBase<RotationBase>
* UnitQuaternion ÷ IsometryBase<UnitQuaternion>
*
* RotationBase × TranslationBase -> IsometryBase<RotationBase>
* UnitQuaternion × TranslationBase -> IsometryBase<UnitQuaternion>
*
*
* (Assignment Operators)
*
* IsometryBase ×= TranslationBase
*
* IsometryBase ×= IsometryBase
* IsometryBase ×= R
*
* IsometryBase ÷= IsometryBase
* IsometryBase ÷= R
*
*/
macro_rules! isometry_binop_impl(
($Op: ident, $op: ident;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N, D: DimName, S, R> $Op<$Rhs> for $Lhs
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Output = $Output;
#[inline]
fn $op($lhs, $rhs: $Rhs) -> Self::Output {
$action
}
}
}
);
macro_rules! isometry_binop_impl_all(
($Op: ident, $op: ident;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
[val val] => $action_val_val: expr;
[ref val] => $action_ref_val: expr;
[val ref] => $action_val_ref: expr;
[ref ref] => $action_ref_ref: expr;) => {
isometry_binop_impl!(
$Op, $op;
$lhs: $Lhs, $rhs: $Rhs, Output = $Output;
$action_val_val; );
isometry_binop_impl!(
$Op, $op;
$lhs: &'a $Lhs, $rhs: $Rhs, Output = $Output;
$action_ref_val; 'a);
isometry_binop_impl!(
$Op, $op;
$lhs: $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_val_ref; 'b);
isometry_binop_impl!(
$Op, $op;
$lhs: &'a $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_ref_ref; 'a, 'b);
}
);
macro_rules! isometry_binop_assign_impl_all(
($OpAssign: ident, $op_assign: ident;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty;
[val] => $action_val: expr;
[ref] => $action_ref: expr;) => {
impl<N, D: DimName, S, R> $OpAssign<$Rhs> for $Lhs
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn $op_assign(&mut $lhs, $rhs: $Rhs) {
$action_val
}
}
impl<'b, N, D: DimName, S, R> $OpAssign<&'b $Rhs> for $Lhs
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn $op_assign(&mut $lhs, $rhs: &'b $Rhs) {
$action_ref
}
}
}
);
// IsometryBase × IsometryBase
// IsometryBase ÷ IsometryBase
isometry_binop_impl_all!(
Mul, mul;
self: IsometryBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>, Output = IsometryBase<N, D, S, R>;
[val val] => &self * &rhs;
[ref val] => self * &rhs;
[val ref] => &self * rhs;
[ref ref] => {
let shift = self.rotation.transform_vector(&rhs.translation.vector);
IsometryBase::from_parts(TranslationBase::from_vector(&self.translation.vector + shift),
self.rotation.clone() * rhs.rotation.clone()) // FIXME: too bad we have to clone.
};
);
isometry_binop_impl_all!(
Div, div;
self: IsometryBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>, Output = IsometryBase<N, D, S, R>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.inverse();
[ref ref] => self * rhs.inverse();
);
// IsometryBase ×= TranslationBase
isometry_binop_assign_impl_all!(
MulAssign, mul_assign;
self: IsometryBase<N, D, S, R>, rhs: TranslationBase<N, D, S>;
[val] => *self *= &rhs;
[ref] => {
let shift = self.rotation.transform_vector(&rhs.vector);
self.translation.vector += shift;
};
);
// IsometryBase ×= IsometryBase
// IsometryBase ÷= IsometryBase
isometry_binop_assign_impl_all!(
MulAssign, mul_assign;
self: IsometryBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>;
[val] => *self *= &rhs;
[ref] => {
let shift = self.rotation.transform_vector(&rhs.translation.vector);
self.translation.vector += shift;
self.rotation *= rhs.rotation.clone();
};
);
isometry_binop_assign_impl_all!(
DivAssign, div_assign;
self: IsometryBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>;
[val] => *self /= &rhs;
[ref] => *self *= rhs.inverse();
);
// IsometryBase ×= R
// IsometryBase ÷= R
isometry_binop_assign_impl_all!(
MulAssign, mul_assign;
self: IsometryBase<N, D, S, R>, rhs: R;
[val] => self.rotation *= rhs;
[ref] => self.rotation *= rhs.clone();
);
isometry_binop_assign_impl_all!(
DivAssign, div_assign;
self: IsometryBase<N, D, S, R>, rhs: R;
// FIXME: don't invert explicitly?
[val] => *self *= rhs.inverse();
[ref] => *self *= rhs.inverse();
);
// IsometryBase × R
// IsometryBase ÷ R
isometry_binop_impl_all!(
Mul, mul;
self: IsometryBase<N, D, S, R>, rhs: R, Output = IsometryBase<N, D, S, R>;
[val val] => IsometryBase::from_parts(self.translation, self.rotation * rhs);
[ref val] => IsometryBase::from_parts(self.translation.clone(), self.rotation.clone() * rhs); // FIXME: do not clone.
[val ref] => IsometryBase::from_parts(self.translation, self.rotation * rhs.clone());
[ref ref] => IsometryBase::from_parts(self.translation.clone(), self.rotation.clone() * rhs.clone());
);
isometry_binop_impl_all!(
Div, div;
self: IsometryBase<N, D, S, R>, rhs: R, Output = IsometryBase<N, D, S, R>;
[val val] => IsometryBase::from_parts(self.translation, self.rotation / rhs);
[ref val] => IsometryBase::from_parts(self.translation.clone(), self.rotation.clone() / rhs);
[val ref] => IsometryBase::from_parts(self.translation, self.rotation / rhs.clone());
[ref ref] => IsometryBase::from_parts(self.translation.clone(), self.rotation.clone() / rhs.clone());
);
// IsometryBase × PointBase
isometry_binop_impl_all!(
Mul, mul;
self: IsometryBase<N, D, S, R>, right: PointBase<N, D, S>, Output = PointBase<N, D, S>;
[val val] => self.translation * self.rotation.transform_point(&right);
[ref val] => &self.translation * self.rotation.transform_point(&right);
[val ref] => self.translation * self.rotation.transform_point(right);
[ref ref] => &self.translation * self.rotation.transform_point(right);
);
// IsometryBase × Vector
isometry_binop_impl_all!(
Mul, mul;
self: IsometryBase<N, D, S, R>, right: ColumnVector<N, D, S>, Output = ColumnVector<N, D, S>;
[val val] => self.rotation.transform_vector(&right);
[ref val] => self.rotation.transform_vector(&right);
[val ref] => self.rotation.transform_vector(right);
[ref ref] => self.rotation.transform_vector(right);
);
// IsometryBase × TranslationBase
isometry_binop_impl_all!(
Mul, mul;
self: IsometryBase<N, D, S, R>, right: TranslationBase<N, D, S>, Output = IsometryBase<N, D, S, R>;
[val val] => &self * &right;
[ref val] => self * &right;
[val ref] => &self * right;
[ref ref] => {
let new_tr = &self.translation.vector + self.rotation.transform_vector(&right.vector);
IsometryBase::from_parts(TranslationBase::from_vector(new_tr), self.rotation.clone())
};
);
// TranslationBase × IsometryBase
isometry_binop_impl_all!(
Mul, mul;
self: TranslationBase<N, D, S>, right: IsometryBase<N, D, S, R>, Output = IsometryBase<N, D, S, R>;
[val val] => IsometryBase::from_parts(self * right.translation, right.rotation);
[ref val] => IsometryBase::from_parts(self * &right.translation, right.rotation);
[val ref] => IsometryBase::from_parts(self * &right.translation, right.rotation.clone());
[ref ref] => IsometryBase::from_parts(self * &right.translation, right.rotation.clone());
);
// TranslationBase × R
isometry_binop_impl_all!(
Mul, mul;
self: TranslationBase<N, D, S>, right: R, Output = IsometryBase<N, D, S, R>;
[val val] => IsometryBase::from_parts(self, right);
[ref val] => IsometryBase::from_parts(self.clone(), right);
[val ref] => IsometryBase::from_parts(self, right.clone());
[ref ref] => IsometryBase::from_parts(self.clone(), right.clone());
);
macro_rules! isometry_from_composition_impl(
($Op: ident, $op: ident;
($R1: ty, $C1: ty),($R2: ty, $C2: ty) $(for $Dims: ident: $DimsBound: ident),*;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N $(, $Dims: $DimsBound)*, SA, SB> $Op<$Rhs> for $Lhs
where N: Real,
SA: OwnedStorage<N, $R1, $C1>,
SB: OwnedStorage<N, $R2, $C2, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, $R1, $C1, SA>,
SB::Alloc: OwnedAllocator<N, $R2, $C2, SB> {
type Output = $Output;
#[inline]
fn $op($lhs, $rhs: $Rhs) -> Self::Output {
$action
}
}
}
);
macro_rules! isometry_from_composition_impl_all(
($Op: ident, $op: ident;
($R1: ty, $C1: ty),($R2: ty, $C2: ty) $(for $Dims: ident: $DimsBound: ident),*;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
[val val] => $action_val_val: expr;
[ref val] => $action_ref_val: expr;
[val ref] => $action_val_ref: expr;
[ref ref] => $action_ref_ref: expr;) => {
isometry_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: $Lhs, $rhs: $Rhs, Output = $Output;
$action_val_val; );
isometry_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: &'a $Lhs, $rhs: $Rhs, Output = $Output;
$action_ref_val; 'a);
isometry_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_val_ref; 'b);
isometry_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: &'a $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_ref_ref; 'a, 'b);
}
);
// RotationBase × TranslationBase
isometry_from_composition_impl_all!(
Mul, mul;
(D, D), (D, U1) for D: DimName;
self: RotationBase<N, D, SA>, right: TranslationBase<N, D, SB>, Output = IsometryBase<N, D, SB, RotationBase<N, D, SA>>;
[val val] => IsometryBase::from_parts(TranslationBase::from_vector(&self * right.vector), self);
[ref val] => IsometryBase::from_parts(TranslationBase::from_vector(self * right.vector), self.clone());
[val ref] => IsometryBase::from_parts(TranslationBase::from_vector(&self * &right.vector), self);
[ref ref] => IsometryBase::from_parts(TranslationBase::from_vector(self * &right.vector), self.clone());
);
// UnitQuaternionBase × TranslationBase
isometry_from_composition_impl_all!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, right: TranslationBase<N, U3, SB>,
Output = IsometryBase<N, U3, SB, UnitQuaternionBase<N, SA>>;
[val val] => IsometryBase::from_parts(TranslationBase::from_vector(&self * right.vector), self);
[ref val] => IsometryBase::from_parts(TranslationBase::from_vector( self * right.vector), self.clone());
[val ref] => IsometryBase::from_parts(TranslationBase::from_vector(&self * &right.vector), self);
[ref ref] => IsometryBase::from_parts(TranslationBase::from_vector( self * &right.vector), self.clone());
);
// RotationBase × IsometryBase
isometry_from_composition_impl_all!(
Mul, mul;
(D, D), (D, U1) for D: DimName;
self: RotationBase<N, D, SA>, right: IsometryBase<N, D, SB, RotationBase<N, D, SA>>,
Output = IsometryBase<N, D, SB, RotationBase<N, D, SA>>;
[val val] => &self * &right;
[ref val] => self * &right;
[val ref] => &self * right;
[ref ref] => {
let shift = self * &right.translation.vector;
IsometryBase::from_parts(TranslationBase::from_vector(shift), self * &right.rotation)
};
);
// RotationBase ÷ IsometryBase
isometry_from_composition_impl_all!(
Div, div;
(D, D), (D, U1) for D: DimName;
self: RotationBase<N, D, SA>, right: IsometryBase<N, D, SB, RotationBase<N, D, SA>>,
Output = IsometryBase<N, D, SB, RotationBase<N, D, SA>>;
// FIXME: don't call iverse explicitly?
[val val] => self * right.inverse();
[ref val] => self * right.inverse();
[val ref] => self * right.inverse();
[ref ref] => self * right.inverse();
);
// UnitQuaternion × IsometryBase
isometry_from_composition_impl_all!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, right: IsometryBase<N, U3, SB, UnitQuaternionBase<N, SA>>,
Output = IsometryBase<N, U3, SB, UnitQuaternionBase<N, SA>>;
[val val] => &self * &right;
[ref val] => self * &right;
[val ref] => &self * right;
[ref ref] => {
let shift = self * &right.translation.vector;
IsometryBase::from_parts(TranslationBase::from_vector(shift), self * &right.rotation)
};
);
// UnitQuaternion ÷ IsometryBase
isometry_from_composition_impl_all!(
Div, div;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, right: IsometryBase<N, U3, SB, UnitQuaternionBase<N, SA>>,
Output = IsometryBase<N, U3, SB, UnitQuaternionBase<N, SA>>;
// FIXME: don't call inverse explicitly?
[val val] => self * right.inverse();
[ref val] => self * right.inverse();
[val ref] => self * right.inverse();
[ref ref] => self * right.inverse();
);

91
src/geometry/mod.rs Normal file
View File

@ -0,0 +1,91 @@
//! [Reexported at the root of this crate.] Data structures for points and usual transformations
//! (rotations, isometries, etc.)
mod op_macros;
mod point;
mod point_construction;
mod point_alias;
mod point_ops;
mod point_alga;
mod point_conversion;
mod point_coordinates;
mod rotation;
mod rotation_construction;
mod rotation_ops;
mod rotation_alga; // FIXME: implement RotationBase methods.
mod rotation_conversion;
mod rotation_alias;
mod rotation_specialization;
mod quaternion;
mod quaternion_construction;
mod quaternion_ops;
mod quaternion_alga;
mod quaternion_alias;
mod quaternion_coordinates;
mod quaternion_conversion;
mod unit_complex;
mod unit_complex_construction;
mod unit_complex_ops;
mod unit_complex_alga;
mod unit_complex_conversion;
mod translation;
mod translation_construction;
mod translation_ops;
mod translation_alga;
mod translation_conversion;
mod translation_alias;
mod isometry;
mod isometry_construction;
mod isometry_ops;
mod isometry_alga;
mod isometry_conversion;
mod isometry_alias;
mod similarity;
mod similarity_construction;
mod similarity_ops;
mod similarity_alga;
mod similarity_conversion;
mod similarity_alias;
mod transform;
mod transform_construction;
mod transform_ops;
mod transform_alga;
mod transform_conversion;
mod transform_alias;
mod orthographic;
mod perspective;
pub use self::point::*;
pub use self::point_alias::*;
pub use self::rotation::*;
pub use self::rotation_alias::*;
pub use self::quaternion::*;
pub use self::quaternion_alias::*;
pub use self::unit_complex::*;
pub use self::translation::*;
pub use self::translation_alias::*;
pub use self::isometry::*;
pub use self::isometry_alias::*;
pub use self::similarity::*;
pub use self::similarity_alias::*;
pub use self::transform::*;
pub use self::transform_alias::*;
pub use self::orthographic::{OrthographicBase, Orthographic3};
pub use self::perspective::{PerspectiveBase, Perspective3};

188
src/geometry/op_macros.rs Normal file
View File

@ -0,0 +1,188 @@
#![macro_use]
// FIXME: merge with `md_impl`.
/// Macro for the implementation of multiplication and division.
macro_rules! md_impl(
(
// Operator, operator method, and calar bounds.
$Op: ident, $op: ident $(where N: $($ScalarBounds: ident),*)*;
// Storage dimensions, and dimension bounds.
($R1: ty, $C1: ty),($R2: ty, $C2: ty) for $($Dims: ident: $DimsBound: ident $(<$BoundParam: ty>)*),+
// [Optional] Extra allocator bounds.
$(where $ConstraintType: ty: $ConstraintBound: ident<$($ConstraintBoundParams: ty $( = $EqBound: ty )*),*> )*;
// Argument identifiers and types + output.
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty;
// Operator actual mplementation.
$action: expr;
// Lifetime.
$($lives: tt),*) => {
impl<$($lives ,)* N $(, $Dims: $DimsBound $(<$BoundParam>)*)*, SA, SB> $Op<$Rhs> for $Lhs
where N: Scalar + Zero + ClosedAdd + ClosedMul $($(+ $ScalarBounds)*)*,
SA: Storage<N, $R1, $C1>,
SB: Storage<N, $R2, $C2>,
$( $ConstraintType: $ConstraintBound<$( $ConstraintBoundParams $( = $EqBound )*),*> ),*
{
type Output = $Result;
#[inline]
fn $op($lhs, $rhs: $Rhs) -> Self::Output {
$action
}
}
}
);
/// Macro for the implementation of multiplication and division.
/// Implements all the argument reference combinations.
macro_rules! md_impl_all(
(
// Operator, operator method, and calar bounds.
$Op: ident, $op: ident $(where N: $($ScalarBounds: ident),*)*;
// Storage dimensions, and dimension bounds.
($R1: ty, $C1: ty),($R2: ty, $C2: ty) for $($Dims: ident: $DimsBound: ident $(<$BoundParam: ty>)*),+
// [Optional] Extra allocator bounds.
$(where $ConstraintType: ty: $ConstraintBound: ident<$($ConstraintBoundParams: ty $( = $EqBound: ty )*),*> )*;
// Argument identifiers and types + output.
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty;
// Operators actual implementations.
[val val] => $action_val_val: expr;
[ref val] => $action_ref_val: expr;
[val ref] => $action_val_ref: expr;
[ref ref] => $action_ref_ref: expr;) => {
md_impl!(
$Op, $op $(where N: $($ScalarBounds),*)*;
($R1, $C1),($R2, $C2) for $($Dims: $DimsBound $(<$BoundParam>)*),+
$(where $ConstraintType: $ConstraintBound<$($ConstraintBoundParams $( = $EqBound )*),*>)*;
$lhs: $Lhs, $rhs: $Rhs, Output = $Result;
$action_val_val; );
md_impl!(
$Op, $op $(where N: $($ScalarBounds),*)*;
($R1, $C1),($R2, $C2) for $($Dims: $DimsBound $(<$BoundParam>)*),+
$(where $ConstraintType: $ConstraintBound<$($ConstraintBoundParams $( = $EqBound )*),*>)*;
$lhs: &'a $Lhs, $rhs: $Rhs, Output = $Result;
$action_ref_val; 'a);
md_impl!(
$Op, $op $(where N: $($ScalarBounds),*)*;
($R1, $C1),($R2, $C2) for $($Dims: $DimsBound $(<$BoundParam>)*),+
$(where $ConstraintType: $ConstraintBound<$($ConstraintBoundParams $( = $EqBound )*),*>)*;
$lhs: $Lhs, $rhs: &'b $Rhs, Output = $Result;
$action_val_ref; 'b);
md_impl!(
$Op, $op $(where N: $($ScalarBounds),*)*;
($R1, $C1),($R2, $C2) for $($Dims: $DimsBound $(<$BoundParam>)*),+
$(where $ConstraintType: $ConstraintBound<$($ConstraintBoundParams $( = $EqBound )*),*>)*;
$lhs: &'a $Lhs, $rhs: &'b $Rhs, Output = $Result;
$action_ref_ref; 'a, 'b);
}
);
/// Macro for the implementation of assignement-multiplication and assignement-division.
macro_rules! md_assign_impl(
(
// Operator, operator method, and scalar bounds.
$Op: ident, $op: ident $(where N: $($ScalarBounds: ident),*)*;
// Storage dimensions, and dimension bounds.
($R1: ty, $C1: ty),($R2: ty, $C2: ty) for $($Dims: ident: $DimsBound: ident $(<$BoundParam: ty>)*),+
// [Optional] Extra allocator bounds.
$(where $ConstraintType: ty: $ConstraintBound: ident<$($ConstraintBoundParams: ty $( = $EqBound: ty )*),*> )*;
// Argument identifiers and types.
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty;
// Actual implementation and lifetimes.
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N $(, $Dims: $DimsBound $(<$BoundParam>)*)*, SA, SB> $Op<$Rhs> for $Lhs
where N: Scalar + Zero + ClosedAdd + ClosedMul $($(+ $ScalarBounds)*)*,
SA: OwnedStorage<N, $R1, $C1>, // FIXME: this is too restrictive.
SB: Storage<N, $R2, $C2>,
SA::Alloc: OwnedAllocator<N, $R1, $C1, SA>,
$( $ConstraintType: $ConstraintBound<$( $ConstraintBoundParams $( = $EqBound )*),*> ),*
{
#[inline]
fn $op(&mut $lhs, $rhs: $Rhs) {
$action
}
}
}
);
/// Macro for the implementation of assignement-multiplication and assignement-division with and
/// without reference to the right-hand-side.
macro_rules! md_assign_impl_all(
(
// Operator, operator method, and scalar bounds.
$Op: ident, $op: ident $(where N: $($ScalarBounds: ident),*)*;
// Storage dimensions, and dimension bounds.
($R1: ty, $C1: ty),($R2: ty, $C2: ty) for $($Dims: ident: $DimsBound: ident $(<$BoundParam: ty>)*),+
// [Optional] Extra allocator bounds.
$(where $ConstraintType: ty: $ConstraintBound: ident<$($ConstraintBoundParams: ty $( = $EqBound: ty )*),*> )*;
// Argument identifiers and types.
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty;
// Actual implementation and lifetimes.
[val] => $action_val: expr;
[ref] => $action_ref: expr;) => {
md_assign_impl!(
$Op, $op $(where N: $($ScalarBounds),*)*;
($R1, $C1),($R2, $C2) for $($Dims: $DimsBound $(<$BoundParam>)*),+
$(where $ConstraintType: $ConstraintBound<$($ConstraintBoundParams $( = $EqBound )*),*>)*;
$lhs: $Lhs, $rhs: $Rhs;
$action_val; );
md_assign_impl!(
$Op, $op $(where N: $($ScalarBounds),*)*;
($R1, $C1),($R2, $C2) for $($Dims: $DimsBound $(<$BoundParam>)*),+
$(where $ConstraintType: $ConstraintBound<$($ConstraintBoundParams $( = $EqBound )*),*>)*;
$lhs: $Lhs, $rhs: &'b $Rhs;
$action_ref; 'b);
}
);
// FIXME: merge with `as_impl`.
/// Macro for the implementation of addition and subtraction.
macro_rules! add_sub_impl(
($Op: ident, $op: ident, $bound: ident;
($R1: ty, $C1: ty),($R2: ty, $C2: ty) $(-> ($RRes: ty))* for $($Dims: ident: $DimsBound: ident),+;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N $(, $Dims: $DimsBound)*, SA, SB> $Op<$Rhs> for $Lhs
where N: Scalar + $bound,
SA: Storage<N, $R1, $C1>,
SB: Storage<N, $R2, $C2>,
SA::Alloc: SameShapeAllocator<N, $R1, $C1, $R2, $C2, SA>,
ShapeConstraint: SameNumberOfRows<$R1, $R2 $(, Representative = $RRes)*> +
SameNumberOfColumns<$C1, $C2> {
type Output = $Result;
#[inline]
fn $op($lhs, $rhs: $Rhs) -> Self::Output {
$action
}
}
}
);
// FIXME: merge with `md_assign_impl`.
/// Macro for the implementation of assignement-addition and assignement-subtraction.
macro_rules! add_sub_assign_impl(
($Op: ident, $op: ident, $bound: ident;
($R1: ty, $C1: ty),($R2: ty, $C2: ty) for $($Dims: ident: $DimsBound: ident),+;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N $(, $Dims: $DimsBound)*, SA, SB> $Op<$Rhs> for $Lhs
where N: Scalar + $bound,
SA: OwnedStorage<N, $R1, $C1>, // FIXME: this is too restrictive.
SB: Storage<N, $R2, $C2>,
SA::Alloc: OwnedAllocator<N, $R1, $C1, SA>,
ShapeConstraint: SameNumberOfRows<$R1, $R2> + SameNumberOfColumns<$C1, $C2> {
#[inline]
fn $op(&mut $lhs, $rhs: $Rhs) {
$action
}
}
}
);

View File

@ -0,0 +1,295 @@
#[cfg(feature="arbitrary")]
use quickcheck::{Arbitrary, Gen};
use rand::{Rand, Rng};
use alga::general::Real;
use core::{Scalar, SquareMatrix, OwnedSquareMatrix, ColumnVector, OwnedColumnVector, MatrixArray};
use core::dimension::{U1, U3, U4};
use core::storage::{OwnedStorage, Storage, StorageMut};
use core::allocator::OwnedAllocator;
use core::helper;
use geometry::{PointBase, OwnedPoint};
/// A 3D orthographic projection stored as an homogeneous 4x4 matrix.
#[derive(Debug, Clone, Copy)] // FIXME: Hash
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct OrthographicBase<N: Scalar, S: Storage<N, U4, U4>> {
matrix: SquareMatrix<N, U4, S>
}
/// A 3D orthographic projection stored as a static homogeneous 4x4 matrix.
pub type Orthographic3<N> = OrthographicBase<N, MatrixArray<N, U4, U4>>;
impl<N, S> Eq for OrthographicBase<N, S>
where N: Scalar + Eq,
S: Storage<N, U4, U4> { }
impl<N: Scalar, S: Storage<N, U4, U4>> PartialEq for OrthographicBase<N, S> {
#[inline]
fn eq(&self, right: &Self) -> bool {
self.matrix == right.matrix
}
}
impl<N, S> OrthographicBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U4>,
S::Alloc: OwnedAllocator<N, U4, U4, S> {
/// Creates a new orthographic projection matrix.
#[inline]
pub fn new(left: N, right: N, bottom: N, top: N, znear: N, zfar: N) -> Self {
assert!(left < right, "The left corner must be farther than the right corner.");
assert!(bottom < top, "The top corner must be higher than the bottom corner.");
assert!(znear < zfar, "The far plane must be farther than the near plane.");
let matrix = SquareMatrix::<N, U4, S>::identity();
let mut res = Self::from_matrix_unchecked(matrix);
res.set_left_and_right(left, right);
res.set_bottom_and_top(bottom, top);
res.set_znear_and_zfar(znear, zfar);
res
}
/// Wraps the given matrix to interpret it as a 3D orthographic matrix.
///
/// It is not checked whether or not the given matrix actually represents an orthographic
/// projection.
#[inline]
pub fn from_matrix_unchecked(matrix: SquareMatrix<N, U4, S>) -> Self {
OrthographicBase {
matrix: matrix
}
}
/// Creates a new orthographic projection matrix from an aspect ratio and the vertical field of view.
#[inline]
pub fn from_fov(aspect: N, vfov: N, znear: N, zfar: N) -> Self {
assert!(znear < zfar, "The far plane must be farther than the near plane.");
assert!(!relative_eq!(aspect, N::zero()), "The apsect ratio must not be zero.");
let half: N = ::convert(0.5);
let width = zfar * (vfov * half).tan();
let height = width / aspect;
Self::new(-width * half, width * half, -height * half, height * half, znear, zfar)
}
}
impl<N: Real, S: Storage<N, U4, U4>> OrthographicBase<N, S> {
/// A reference to the underlying homogeneous transformation matrix.
#[inline]
pub fn as_matrix(&self) -> &SquareMatrix<N, U4, S> {
&self.matrix
}
/// Retrieves the underlying homogeneous matrix.
#[inline]
pub fn unwrap(self) -> SquareMatrix<N, U4, S> {
self.matrix
}
/// Retrieves the inverse of the underlying homogeneous matrix.
#[inline]
pub fn inverse(&self) -> OwnedSquareMatrix<N, U4, S::Alloc> {
let mut res = self.to_homogeneous();
let inv_m11 = N::one() / self.matrix[(0, 0)];
let inv_m22 = N::one() / self.matrix[(1, 1)];
let inv_m33 = N::one() / self.matrix[(2, 2)];
res[(0, 0)] = inv_m11;
res[(1, 1)] = inv_m22;
res[(2, 2)] = inv_m33;
res[(0, 3)] = -self.matrix[(0, 3)] * inv_m11;
res[(1, 3)] = -self.matrix[(1, 3)] * inv_m22;
res[(2, 3)] = -self.matrix[(2, 3)] * inv_m33;
res
}
/// Computes the corresponding homogeneous matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, U4, S::Alloc> {
self.matrix.clone_owned()
}
/// The smallest x-coordinate of the view cuboid.
#[inline]
pub fn left(&self) -> N {
(-N::one() - self.matrix[(0, 3)]) / self.matrix[(0, 0)]
}
/// The largest x-coordinate of the view cuboid.
#[inline]
pub fn right(&self) -> N {
(N::one() - self.matrix[(0, 3)]) / self.matrix[(0, 0)]
}
/// The smallest y-coordinate of the view cuboid.
#[inline]
pub fn bottom(&self) -> N {
(-N::one() - self.matrix[(1, 3)]) / self.matrix[(1, 1)]
}
/// The largest y-coordinate of the view cuboid.
#[inline]
pub fn top(&self) -> N {
(N::one() - self.matrix[(1, 3)]) / self.matrix[(1, 1)]
}
/// The near plane offset of the view cuboid.
#[inline]
pub fn znear(&self) -> N {
(N::one() + self.matrix[(2, 3)]) / self.matrix[(2, 2)]
}
/// The far plane offset of the view cuboid.
#[inline]
pub fn zfar(&self) -> N {
(-N::one() + self.matrix[(2, 3)]) / self.matrix[(2, 2)]
}
// FIXME: when we get specialization, specialize the Mul impl instead.
/// Projects a point. Faster than matrix multiplication.
#[inline]
pub fn project_point<SB>(&self, p: &PointBase<N, U3, SB>) -> OwnedPoint<N, U3, SB::Alloc>
where SB: Storage<N, U3, U1> {
OwnedPoint::<N, U3, SB::Alloc>::new(
self.matrix[(0, 0)] * p[0] + self.matrix[(0, 3)],
self.matrix[(1, 1)] * p[1] + self.matrix[(1, 3)],
self.matrix[(2, 2)] * p[2] + self.matrix[(2, 3)]
)
}
/// Un-projects a point. Faster than multiplication by the underlying matrix inverse.
#[inline]
pub fn unproject_point<SB>(&self, p: &PointBase<N, U3, SB>) -> OwnedPoint<N, U3, SB::Alloc>
where SB: Storage<N, U3, U1> {
OwnedPoint::<N, U3, SB::Alloc>::new(
(p[0] - self.matrix[(0, 3)]) / self.matrix[(0, 0)],
(p[1] - self.matrix[(1, 3)]) / self.matrix[(1, 1)],
(p[2] - self.matrix[(2, 3)]) / self.matrix[(2, 2)]
)
}
// FIXME: when we get specialization, specialize the Mul impl instead.
/// Projects a vector. Faster than matrix multiplication.
#[inline]
pub fn project_vector<SB>(&self, p: &ColumnVector<N, U3, SB>) -> OwnedColumnVector<N, U3, SB::Alloc>
where SB: Storage<N, U3, U1> {
OwnedColumnVector::<N, U3, SB::Alloc>::new(
self.matrix[(0, 0)] * p[0],
self.matrix[(1, 1)] * p[1],
self.matrix[(2, 2)] * p[2]
)
}
}
impl<N: Real, S: StorageMut<N, U4, U4>> OrthographicBase<N, S> {
/// Sets the smallest x-coordinate of the view cuboid.
#[inline]
pub fn set_left(&mut self, left: N) {
let right = self.right();
self.set_left_and_right(left, right);
}
/// Sets the largest x-coordinate of the view cuboid.
#[inline]
pub fn set_right(&mut self, right: N) {
let left = self.left();
self.set_left_and_right(left, right);
}
/// Sets the smallest y-coordinate of the view cuboid.
#[inline]
pub fn set_bottom(&mut self, bottom: N) {
let top = self.top();
self.set_bottom_and_top(bottom, top);
}
/// Sets the largest y-coordinate of the view cuboid.
#[inline]
pub fn set_top(&mut self, top: N) {
let bottom = self.bottom();
self.set_bottom_and_top(bottom, top);
}
/// Sets the near plane offset of the view cuboid.
#[inline]
pub fn set_znear(&mut self, znear: N) {
let zfar = self.zfar();
self.set_znear_and_zfar(znear, zfar);
}
/// Sets the far plane offset of the view cuboid.
#[inline]
pub fn set_zfar(&mut self, zfar: N) {
let znear = self.znear();
self.set_znear_and_zfar(znear, zfar);
}
/// Sets the view cuboid coordinates along the `x` axis.
#[inline]
pub fn set_left_and_right(&mut self, left: N, right: N) {
assert!(left < right, "The left corner must be farther than the right corner.");
self.matrix[(0, 0)] = ::convert::<_, N>(2.0) / (right - left);
self.matrix[(0, 3)] = -(right + left) / (right - left);
}
/// Sets the view cuboid coordinates along the `y` axis.
#[inline]
pub fn set_bottom_and_top(&mut self, bottom: N, top: N) {
assert!(bottom < top, "The top corner must be higher than the bottom corner.");
self.matrix[(1, 1)] = ::convert::<_, N>(2.0) / (top - bottom);
self.matrix[(1, 3)] = -(top + bottom) / (top - bottom);
}
/// Sets the near and far plane offsets of the view cuboid.
#[inline]
pub fn set_znear_and_zfar(&mut self, znear: N, zfar: N) {
assert!(!relative_eq!(zfar - znear, N::zero()), "The near-plane and far-plane must not be superimposed.");
self.matrix[(2, 2)] = -::convert::<_, N>(2.0) / (zfar - znear);
self.matrix[(2, 3)] = -(zfar + znear) / (zfar - znear);
}
}
impl<N, S> Rand for OrthographicBase<N, S>
where N: Real + Rand,
S: OwnedStorage<N, U4, U4>,
S::Alloc: OwnedAllocator<N, U4, U4, S> {
fn rand<R: Rng>(r: &mut R) -> Self {
let left = Rand::rand(r);
let right = helper::reject_rand(r, |x: &N| *x > left);
let bottom = Rand::rand(r);
let top = helper::reject_rand(r, |x: &N| *x > bottom);
let znear = Rand::rand(r);
let zfar = helper::reject_rand(r, |x: &N| *x > znear);
Self::new(left, right, bottom, top, znear, zfar)
}
}
#[cfg(feature="arbitrary")]
impl<N, S> Arbitrary for OrthographicBase<N, S>
where N: Real + Arbitrary,
S: OwnedStorage<N, U4, U4> + Send,
S::Alloc: OwnedAllocator<N, U4, U4, S> {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let left = Arbitrary::arbitrary(g);
let right = helper::reject(g, |x: &N| *x > left);
let bottom = Arbitrary::arbitrary(g);
let top = helper::reject(g, |x: &N| *x > bottom);
let znear = Arbitrary::arbitrary(g);
let zfar = helper::reject(g, |x: &N| *x > znear);
Self::new(left, right, bottom, top, znear, zfar)
}
}

256
src/geometry/perspective.rs Normal file
View File

@ -0,0 +1,256 @@
#[cfg(feature="arbitrary")]
use quickcheck::{Arbitrary, Gen};
use rand::{Rand, Rng};
use alga::general::Real;
use core::{Scalar, SquareMatrix, OwnedSquareMatrix, ColumnVector, OwnedColumnVector, MatrixArray};
use core::dimension::{U1, U3, U4};
use core::storage::{OwnedStorage, Storage, StorageMut};
use core::allocator::OwnedAllocator;
use core::helper;
use geometry::{PointBase, OwnedPoint};
/// A 3D perspective projection stored as an homogeneous 4x4 matrix.
#[derive(Debug, Clone, Copy)] // FIXME: Hash
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct PerspectiveBase<N: Scalar, S: Storage<N, U4, U4>> {
matrix: SquareMatrix<N, U4, S>
}
/// A 3D perspective projection stored as a static homogeneous 4x4 matrix.
pub type Perspective3<N> = PerspectiveBase<N, MatrixArray<N, U4, U4>>;
impl<N, S> Eq for PerspectiveBase<N, S>
where N: Scalar + Eq,
S: Storage<N, U4, U4> { }
impl<N, S> PartialEq for PerspectiveBase<N, S>
where N: Scalar,
S: Storage<N, U4, U4> {
#[inline]
fn eq(&self, right: &Self) -> bool {
self.matrix == right.matrix
}
}
impl<N, S> PerspectiveBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U4>,
S::Alloc: OwnedAllocator<N, U4, U4, S> {
/// Creates a new perspective matrix from the aspect ratio, y field of view, and near/far planes.
pub fn new(aspect: N, fovy: N, znear: N, zfar: N) -> Self {
assert!(!relative_eq!(zfar - znear, N::zero()), "The near-plane and far-plane must not be superimposed.");
assert!(!relative_eq!(aspect, N::zero()), "The apsect ratio must not be zero.");
let matrix = SquareMatrix::<N, U4, S>::identity();
let mut res = PerspectiveBase::from_matrix_unchecked(matrix);
res.set_fovy(fovy);
res.set_aspect(aspect);
res.set_znear_and_zfar(znear, zfar);
res.matrix[(3, 3)] = N::zero();
res.matrix[(3, 2)] = -N::one();
res
}
/// Wraps the given matrix to interpret it as a 3D perspective matrix.
///
/// It is not checked whether or not the given matrix actually represents an orthographic
/// projection.
#[inline]
pub fn from_matrix_unchecked(matrix: SquareMatrix<N, U4, S>) -> Self {
PerspectiveBase {
matrix: matrix
}
}
}
impl<N, S> PerspectiveBase<N, S>
where N: Real,
S: Storage<N, U4, U4> {
/// A reference to the underlying homogeneous transformation matrix.
#[inline]
pub fn as_matrix(&self) -> &SquareMatrix<N, U4, S> {
&self.matrix
}
/// Retrieves the underlying homogeneous matrix.
#[inline]
pub fn unwrap(self) -> SquareMatrix<N, U4, S> {
self.matrix
}
/// Retrieves the inverse of the underlying homogeneous matrix.
#[inline]
pub fn inverse(&self) -> OwnedSquareMatrix<N, U4, S::Alloc> {
let mut res = self.to_homogeneous();
res[(0, 0)] = N::one() / self.matrix[(0, 0)];
res[(1, 1)] = N::one() / self.matrix[(1, 1)];
res[(2, 2)] = N::zero();
let m23 = self.matrix[(2, 3)];
let m32 = self.matrix[(3, 2)];
res[(2, 3)] = N::one() / m32;
res[(3, 2)] = N::one() / m23;
res[(3, 3)] = -self.matrix[(2, 2)] / (m23 * m32);
res
}
/// Computes the corresponding homogeneous matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, U4, S::Alloc> {
self.matrix.clone_owned()
}
/// Gets the `width / height` aspect ratio of the view frustrum.
#[inline]
pub fn aspect(&self) -> N {
self.matrix[(1, 1)] / self.matrix[(0, 0)]
}
/// Gets the y field of view of the view frustrum.
#[inline]
pub fn fovy(&self) -> N {
(N::one() / self.matrix[(1, 1)]).atan() * ::convert(2.0)
}
/// Gets the near plane offset of the view frustrum.
#[inline]
pub fn znear(&self) -> N {
let ratio = (-self.matrix[(2, 2)] + N::one()) / (-self.matrix[(2, 2)] - N::one());
self.matrix[(2, 3)] / (ratio * ::convert(2.0)) - self.matrix[(2, 3)] / ::convert(2.0)
}
/// Gets the far plane offset of the view frustrum.
#[inline]
pub fn zfar(&self) -> N {
let ratio = (-self.matrix[(2, 2)] + N::one()) / (-self.matrix[(2, 2)] - N::one());
(self.matrix[(2, 3)] - ratio * self.matrix[(2, 3)]) / ::convert(2.0)
}
// FIXME: add a method to retrieve znear and zfar simultaneously?
// FIXME: when we get specialization, specialize the Mul impl instead.
/// Projects a point. Faster than matrix multiplication.
#[inline]
pub fn project_point<SB>(&self, p: &PointBase<N, U3, SB>) -> OwnedPoint<N, U3, SB::Alloc>
where SB: Storage<N, U3, U1> {
let inverse_denom = -N::one() / p[2];
OwnedPoint::<N, U3, SB::Alloc>::new(
self.matrix[(0, 0)] * p[0] * inverse_denom,
self.matrix[(1, 1)] * p[1] * inverse_denom,
(self.matrix[(2, 2)] * p[2] + self.matrix[(2, 3)]) * inverse_denom
)
}
/// Un-projects a point. Faster than multiplication by the matrix inverse.
#[inline]
pub fn unproject_point<SB>(&self, p: &PointBase<N, U3, SB>) -> OwnedPoint<N, U3, SB::Alloc>
where SB: Storage<N, U3, U1> {
let inverse_denom = self.matrix[(2, 3)] / (p[2] + self.matrix[(2, 2)]);
OwnedPoint::<N, U3, SB::Alloc>::new(
p[0] * inverse_denom / self.matrix[(0, 0)],
p[1] * inverse_denom / self.matrix[(1, 1)],
-inverse_denom
)
}
// FIXME: when we get specialization, specialize the Mul impl instead.
/// Projects a vector. Faster than matrix multiplication.
#[inline]
pub fn project_vector<SB>(&self, p: &ColumnVector<N, U3, SB>) -> OwnedColumnVector<N, U3, SB::Alloc>
where SB: Storage<N, U3, U1> {
let inverse_denom = -N::one() / p[2];
OwnedColumnVector::<N, U3, SB::Alloc>::new(
self.matrix[(0, 0)] * p[0] * inverse_denom,
self.matrix[(1, 1)] * p[1] * inverse_denom,
self.matrix[(2, 2)]
)
}
}
impl<N, S> PerspectiveBase<N, S>
where N: Real,
S: StorageMut<N, U4, U4> {
/// Updates this perspective matrix with a new `width / height` aspect ratio of the view
/// frustrum.
#[inline]
pub fn set_aspect(&mut self, aspect: N) {
assert!(!relative_eq!(aspect, N::zero()), "The aspect ratio must not be zero.");
self.matrix[(0, 0)] = self.matrix[(1, 1)] / aspect;
}
/// Updates this perspective with a new y field of view of the view frustrum.
#[inline]
pub fn set_fovy(&mut self, fovy: N) {
let old_m22 = self.matrix[(1, 1)];
self.matrix[(1, 1)] = N::one() / (fovy / ::convert(2.0)).tan();
self.matrix[(0, 0)] = self.matrix[(0, 0)] * (self.matrix[(1, 1)] / old_m22);
}
/// Updates this perspective matrix with a new near plane offset of the view frustrum.
#[inline]
pub fn set_znear(&mut self, znear: N) {
let zfar = self.zfar();
self.set_znear_and_zfar(znear, zfar);
}
/// Updates this perspective matrix with a new far plane offset of the view frustrum.
#[inline]
pub fn set_zfar(&mut self, zfar: N) {
let znear = self.znear();
self.set_znear_and_zfar(znear, zfar);
}
/// Updates this perspective matrix with new near and far plane offsets of the view frustrum.
#[inline]
pub fn set_znear_and_zfar(&mut self, znear: N, zfar: N) {
self.matrix[(2, 2)] = (zfar + znear) / (znear - zfar);
self.matrix[(2, 3)] = zfar * znear * ::convert(2.0) / (znear - zfar);
}
}
impl<N, S> Rand for PerspectiveBase<N, S>
where N: Real + Rand,
S: OwnedStorage<N, U4, U4>,
S::Alloc: OwnedAllocator<N, U4, U4, S> {
fn rand<R: Rng>(r: &mut R) -> Self {
let znear = Rand::rand(r);
let zfar = helper::reject_rand(r, |&x: &N| !(x - znear).is_zero());
let aspect = helper::reject_rand(r, |&x: &N| !x.is_zero());
Self::new(aspect, Rand::rand(r), znear, zfar)
}
}
#[cfg(feature="arbitrary")]
impl<N, S> Arbitrary for PerspectiveBase<N, S>
where N: Real + Arbitrary,
S: OwnedStorage<N, U4, U4> + Send,
S::Alloc: OwnedAllocator<N, U4, U4, S> {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let znear = Arbitrary::arbitrary(g);
let zfar = helper::reject(g, |&x: &N| !(x - znear).is_zero());
let aspect = helper::reject(g, |&x: &N| !x.is_zero());
Self::new(aspect, Arbitrary::arbitrary(g), znear, zfar)
}
}

228
src/geometry/point.rs Normal file
View File

@ -0,0 +1,228 @@
use num::One;
use std::fmt;
use std::cmp::Ordering;
use approx::ApproxEq;
use core::{Scalar, ColumnVector, OwnedColumnVector};
use core::iter::{MatrixIter, MatrixIterMut};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::{Storage, StorageMut, MulStorage};
use core::allocator::{Allocator, SameShapeR};
// XXX Bad name: we can't even add points…
/// The type of the result of the sum of a point with a vector.
pub type PointSum<N, D1, D2, SA> =
PointBase<N, SameShapeR<D1, D2>,
<<SA as Storage<N, D1, U1>>::Alloc as Allocator<N, SameShapeR<D1, D2>, U1>>::Buffer>;
/// The type of the result of the multiplication of a point by a matrix.
pub type PointMul<N, R1, C1, SA> = PointBase<N, R1, MulStorage<N, R1, C1, U1, SA>>;
/// A point with an owned storage.
pub type OwnedPoint<N, D, A> = PointBase<N, D, <A as Allocator<N, D, U1>>::Buffer>;
/// A point in a n-dimensional euclidean space.
#[repr(C)]
#[derive(Hash, Debug)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct PointBase<N: Scalar, D: DimName, S: Storage<N, D, U1>> {
/// The coordinates of this point, i.e., the shift from the origin.
pub coords: ColumnVector<N, D, S>
}
impl<N, D, S> Copy for PointBase<N, D, S>
where N: Scalar,
D: DimName,
S: Storage<N, D, U1> + Copy { }
impl<N, D, S> Clone for PointBase<N, D, S>
where N: Scalar,
D: DimName,
S: Storage<N, D, U1> + Clone {
#[inline]
fn clone(&self) -> Self {
PointBase::from_coordinates(self.coords.clone())
}
}
impl<N: Scalar, D: DimName, S: Storage<N, D, U1>> PointBase<N, D, S> {
/// Creates a new point with the given coordinates.
#[inline]
pub fn from_coordinates(coords: ColumnVector<N, D, S>) -> PointBase<N, D, S> {
PointBase {
coords: coords
}
}
}
impl<N: Scalar, D: DimName, S: Storage<N, D, U1>> PointBase<N, D, S> {
/// Moves this point into one that owns its data.
#[inline]
pub fn into_owned(self) -> OwnedPoint<N, D, S::Alloc> {
PointBase::from_coordinates(self.coords.into_owned())
}
/// Clones this point into one that owns its data.
#[inline]
pub fn clone_owned(&self) -> OwnedPoint<N, D, S::Alloc> {
PointBase::from_coordinates(self.coords.clone_owned())
}
/// The dimension of this point.
#[inline]
pub fn len(&self) -> usize {
self.coords.len()
}
/// The stride of this point. This is the number of buffer element separating each component of
/// this point.
#[inline]
pub fn stride(&self) -> usize {
self.coords.strides().0
}
/// Iterates through this point coordinates.
#[inline]
pub fn iter(&self) -> MatrixIter<N, D, U1, S> {
self.coords.iter()
}
/// Gets a reference to i-th element of this point without bound-checking.
#[inline]
pub unsafe fn get_unchecked(&self, i: usize) -> &N {
self.coords.get_unchecked(i, 0)
}
/// Converts this point into a vector in homogeneous coordinates, i.e., appends a `1` at the
/// end of it.
#[inline]
pub fn to_homogeneous(&self) -> OwnedColumnVector<N, DimNameSum<D, U1>, S::Alloc>
where N: One,
D: DimNameAdd<U1>,
S::Alloc: Allocator<N, DimNameSum<D, U1>, U1> {
let mut res = unsafe { OwnedColumnVector::<N, _, S::Alloc>::new_uninitialized() };
res.fixed_slice_mut::<D, U1>(0, 0).copy_from(&self.coords);
res[(D::dim(), 0)] = N::one();
res
}
}
impl<N: Scalar, D: DimName, S: StorageMut<N, D, U1>> PointBase<N, D, S> {
/// Mutably iterates through this point coordinates.
#[inline]
pub fn iter_mut(&mut self) -> MatrixIterMut<N, D, U1, S> {
self.coords.iter_mut()
}
/// Gets a mutable reference to i-th element of this point without bound-checking.
#[inline]
pub unsafe fn get_unchecked_mut(&mut self, i: usize) -> &mut N {
self.coords.get_unchecked_mut(i, 0)
}
/// Swaps two entries without bound-checking.
#[inline]
pub unsafe fn swap_unchecked(&mut self, i1: usize, i2: usize) {
self.coords.swap_unchecked((i1, 0), (i2, 0))
}
}
impl<N, D: DimName, S> ApproxEq for PointBase<N, D, S>
where N: Scalar + ApproxEq,
S: Storage<N, D, U1>,
N::Epsilon: Copy {
type Epsilon = N::Epsilon;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.coords.relative_eq(&other.coords, epsilon, max_relative)
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.coords.ulps_eq(&other.coords, epsilon, max_ulps)
}
}
impl<N, D: DimName, S> Eq for PointBase<N, D, S>
where N: Scalar + Eq,
S: Storage<N, D, U1> { }
impl<N, D: DimName, S> PartialEq for PointBase<N, D, S>
where N: Scalar,
S: Storage<N, D, U1> {
#[inline]
fn eq(&self, right: &Self) -> bool {
self.coords == right.coords
}
}
impl<N, D: DimName, S> PartialOrd for PointBase<N, D, S>
where N: Scalar + PartialOrd,
S: Storage<N, D, U1> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.coords.partial_cmp(&other.coords)
}
#[inline]
fn lt(&self, right: &Self) -> bool {
self.coords.lt(&right.coords)
}
#[inline]
fn le(&self, right: &Self) -> bool {
self.coords.le(&right.coords)
}
#[inline]
fn gt(&self, right: &Self) -> bool {
self.coords.gt(&right.coords)
}
#[inline]
fn ge(&self, right: &Self) -> bool {
self.coords.ge(&right.coords)
}
}
/*
*
* Display
*
*/
impl<N, D: DimName, S> fmt::Display for PointBase<N, D, S>
where N: Scalar + fmt::Display,
S: Storage<N, D, U1> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{{"));
let mut it = self.coords.iter();
try!(write!(f, "{}", *it.next().unwrap()));
for comp in it {
try!(write!(f, ", {}", *comp));
}
write!(f, "}}")
}
}

View File

@ -0,0 +1,83 @@
use alga::general::{Field, Real, MeetSemilattice, JoinSemilattice, Lattice};
use alga::linear::{AffineSpace, EuclideanSpace};
use core::{ColumnVector, Scalar};
use core::dimension::{DimName, U1};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::PointBase;
impl<N, D: DimName, S> AffineSpace for PointBase<N, D, S>
where N: Scalar + Field,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Translation = ColumnVector<N, D, S>;
}
impl<N, D: DimName, S> EuclideanSpace for PointBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Coordinates = ColumnVector<N, D, S>;
type Real = N;
#[inline]
fn origin() -> Self {
Self::origin()
}
#[inline]
fn coordinates(&self) -> Self::Coordinates {
self.coords.clone()
}
#[inline]
fn from_coordinates(coords: Self::Coordinates) -> Self {
Self::from_coordinates(coords)
}
#[inline]
fn scale_by(&self, n: N) -> Self {
self * n
}
}
/*
*
* Ordering
*
*/
impl<N, D: DimName, S> MeetSemilattice for PointBase<N, D, S>
where N: Scalar + MeetSemilattice,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn meet(&self, other: &Self) -> Self {
PointBase::from_coordinates(self.coords.meet(&other.coords))
}
}
impl<N, D: DimName, S> JoinSemilattice for PointBase<N, D, S>
where N: Scalar + JoinSemilattice,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn join(&self, other: &Self) -> Self {
PointBase::from_coordinates(self.coords.join(&other.coords))
}
}
impl<N, D: DimName, S> Lattice for PointBase<N, D, S>
where N: Scalar + Lattice,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn meet_join(&self, other: &Self) -> (Self, Self) {
let (meet, join) = self.coords.meet_join(&other.coords);
(PointBase::from_coordinates(meet), PointBase::from_coordinates(join))
}
}

View File

@ -0,0 +1,20 @@
use core::MatrixArray;
use core::dimension::{U1, U2, U3, U4, U5, U6};
use geometry::PointBase;
/// A statically sized D-dimensional column point.
pub type Point<N, D> = PointBase<N, D, MatrixArray<N, D, U1>>;
/// A statically sized 1-dimensional column point.
pub type Point1<N> = Point<N, U1>;
/// A statically sized 2-dimensional column point.
pub type Point2<N> = Point<N, U2>;
/// A statically sized 3-dimensional column point.
pub type Point3<N> = Point<N, U3>;
/// A statically sized 4-dimensional column point.
pub type Point4<N> = Point<N, U4>;
/// A statically sized 5-dimensional column point.
pub type Point5<N> = Point<N, U5>;
/// A statically sized 6-dimensional column point.
pub type Point6<N> = Point<N, U6>;

View File

@ -0,0 +1,127 @@
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use rand::{Rand, Rng};
use num::{Zero, One, Bounded};
use alga::general::ClosedDiv;
use core::{Scalar, ColumnVector};
use core::storage::{Storage, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use core::dimension::{DimName, DimNameAdd, DimNameSum, U1, U2, U3, U4, U5, U6};
use geometry::PointBase;
impl<N, D: DimName, S> PointBase<N, D, S>
where N: Scalar,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new point with uninitialized coordinates.
#[inline]
pub unsafe fn new_uninitialized() -> Self {
Self::from_coordinates(ColumnVector::<_, D, _>::new_uninitialized())
}
/// Creates a new point with all coordinates equal to zero.
#[inline]
pub fn origin() -> Self
where N: Zero {
Self::from_coordinates(ColumnVector::<_, D, _>::from_element(N::zero()))
}
/// Creates a new point from its homogeneous vector representation.
///
/// In practice, this builds a D-dimensional points with the same first D component as `v`
/// divided by the last component of `v`. Returns `None` if this divisor is zero.
#[inline]
pub fn from_homogeneous<SB>(v: ColumnVector<N, DimNameSum<D, U1>, SB>) -> Option<Self>
where N: Scalar + Zero + One + ClosedDiv,
D: DimNameAdd<U1>,
SB: Storage<N, DimNameSum<D, U1>, U1, Alloc = S::Alloc>,
S::Alloc: Allocator<N, DimNameSum<D, U1>, U1> {
if !v[D::dim()].is_zero() {
let coords = v.fixed_slice::<D, U1>(0, 0) / v[D::dim()];
Some(Self::from_coordinates(coords))
}
else {
None
}
}
}
/*
*
* Traits that buid points.
*
*/
impl<N, D: DimName, S> Bounded for PointBase<N, D, S>
where N: Scalar + Bounded,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn max_value() -> Self {
Self::from_coordinates(ColumnVector::max_value())
}
#[inline]
fn min_value() -> Self {
Self::from_coordinates(ColumnVector::min_value())
}
}
impl<N, D: DimName, S> Rand for PointBase<N, D, S>
where N: Scalar + Rand,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn rand<G: Rng>(rng: &mut G) -> Self {
PointBase::from_coordinates(rng.gen())
}
}
#[cfg(feature="arbitrary")]
impl<N, D: DimName, S> Arbitrary for PointBase<N, D, S>
where N: Scalar + Arbitrary + Send,
S: OwnedStorage<N, D, U1> + Send,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn arbitrary<G: Gen>(g: &mut G) -> Self {
PointBase::from_coordinates(ColumnVector::arbitrary(g))
}
}
/*
*
* Small points construction from components.
*
*/
macro_rules! componentwise_constructors_impl(
($($D: ty, $($args: ident:$irow: expr),*);* $(;)*) => {$(
impl<N, S> PointBase<N, $D, S>
where N: Scalar,
S: OwnedStorage<N, $D, U1>,
S::Alloc: OwnedAllocator<N, $D, U1, S> {
/// Initializes this matrix from its components.
#[inline]
pub fn new($($args: N),*) -> PointBase<N, $D, S> {
unsafe {
let mut res = Self::new_uninitialized();
$( *res.get_unchecked_mut($irow) = $args; )*
res
}
}
}
)*}
);
componentwise_constructors_impl!(
U1, x:0;
U2, x:0, y:1;
U3, x:0, y:1, z:2;
U4, x:0, y:1, z:2, w:3;
U5, x:0, y:1, z:2, w:3, a:4;
U6, x:0, y:1, z:2, w:3, a:4, b:5;
);

View File

@ -0,0 +1,73 @@
use num::{One, Zero};
use alga::general::{SubsetOf, SupersetOf, ClosedDiv};
use core::{Scalar, Matrix, ColumnVector, OwnedColumnVector};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, OwnedPoint};
/*
* This file provides the following conversions:
* =============================================
*
* PointBase -> PointBase
* PointBase -> ColumnVector (homogeneous)
*/
impl<N1, N2, D, SA, SB> SubsetOf<PointBase<N2, D, SB>> for PointBase<N1, D, SA>
where D: DimName,
N1: Scalar,
N2: Scalar + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, D, U1>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> {
#[inline]
fn to_superset(&self) -> PointBase<N2, D, SB> {
PointBase::from_coordinates(self.coords.to_superset())
}
#[inline]
fn is_in_subset(m: &PointBase<N2, D, SB>) -> bool {
// FIXME: is there a way to reuse the `.is_in_subset` from the matrix implementation of
// SubsetOf?
m.iter().all(|e| e.is_in_subset())
}
#[inline]
unsafe fn from_superset_unchecked(m: &PointBase<N2, D, SB>) -> Self {
PointBase::from_coordinates(Matrix::from_superset_unchecked(&m.coords))
}
}
impl<N1, N2, D, SA, SB> SubsetOf<ColumnVector<N2, DimNameSum<D, U1>, SB>> for PointBase<N1, D, SA>
where D: DimNameAdd<U1>,
N1: Scalar,
N2: Scalar + Zero + One + ClosedDiv + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> +
Allocator<N1, DimNameSum<D, U1>, U1>,
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, U1, SB> +
Allocator<N2, D, U1> {
#[inline]
fn to_superset(&self) -> ColumnVector<N2, DimNameSum<D, U1>, SB> {
let p: OwnedPoint<N2, D, SB::Alloc> = self.to_superset();
p.to_homogeneous()
}
#[inline]
fn is_in_subset(v: &ColumnVector<N2, DimNameSum<D, U1>, SB>) -> bool {
::is_convertible::<_, OwnedColumnVector<N1, DimNameSum<D, U1>, SA::Alloc>>(v) &&
!v[D::dim()].is_zero()
}
#[inline]
unsafe fn from_superset_unchecked(v: &ColumnVector<N2, DimNameSum<D, U1>, SB>) -> Self {
let coords = v.fixed_slice::<D, U1>(0, 0) / v[D::dim()];
Self::from_coordinates(::convert_unchecked(coords))
}
}

View File

@ -0,0 +1,47 @@
use std::mem;
use std::ops::{Deref, DerefMut};
use core::Scalar;
use core::dimension::{U1, U2, U3, U4, U5, U6};
use core::coordinates::{X, XY, XYZ, XYZW, XYZWA, XYZWAB};
use core::allocator::OwnedAllocator;
use core::storage::OwnedStorage;
use geometry::PointBase;
/*
*
* Give coordinates to PointBase{1 .. 6}
*
*/
macro_rules! deref_impl(
($D: ty, $Target: ident $(, $comps: ident)*) => {
impl<N: Scalar, S> Deref for PointBase<N, $D, S>
where S: OwnedStorage<N, $D, U1>,
S::Alloc: OwnedAllocator<N, $D, U1, S> {
type Target = $Target<N>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { mem::transmute(self) }
}
}
impl<N: Scalar, S> DerefMut for PointBase<N, $D, S>
where S: OwnedStorage<N, $D, U1>,
S::Alloc: OwnedAllocator<N, $D, U1, S> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { mem::transmute(self) }
}
}
}
);
deref_impl!(U1, X, x);
deref_impl!(U2, XY, x, y);
deref_impl!(U3, XYZ, x, y, z);
deref_impl!(U4, XYZW, x, y, z, w);
deref_impl!(U5, XYZWA, x, y, z, w, a);
deref_impl!(U6, XYZWAB, x, y, z, w, a, b);

263
src/geometry/point_ops.rs Normal file
View File

@ -0,0 +1,263 @@
use std::ops::{Neg, Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Index, IndexMut};
use num::Zero;
use alga::general::{ClosedNeg, ClosedAdd, ClosedSub, ClosedMul, ClosedDiv};
use core::{Scalar, ColumnVector, Matrix, ColumnVectorSum};
use core::dimension::{Dim, DimName, U1};
use core::constraint::{ShapeConstraint, SameNumberOfRows, SameNumberOfColumns, AreMultipliable};
use core::storage::{Storage, StorageMut};
use core::allocator::{SameShapeAllocator, Allocator};
use geometry::{PointBase, OwnedPoint, PointMul};
/*
*
* Indexing.
*
*/
impl<N, D: DimName, S> Index<usize> for PointBase<N, D, S>
where N: Scalar,
S: Storage<N, D, U1> {
type Output = N;
#[inline]
fn index(&self, i: usize) -> &Self::Output {
&self.coords[i]
}
}
impl<N, D: DimName, S> IndexMut<usize> for PointBase<N, D, S>
where N: Scalar,
S: StorageMut<N, D, U1> {
#[inline]
fn index_mut(&mut self, i: usize) -> &mut Self::Output {
&mut self.coords[i]
}
}
/*
* Neg.
*
*/
impl<N, D: DimName, S> Neg for PointBase<N, D, S>
where N: Scalar + ClosedNeg,
S: Storage<N, D, U1> {
type Output = OwnedPoint<N, D, S::Alloc>;
#[inline]
fn neg(self) -> Self::Output {
PointBase::from_coordinates(-self.coords)
}
}
impl<'a, N, D: DimName, S> Neg for &'a PointBase<N, D, S>
where N: Scalar + ClosedNeg,
S: Storage<N, D, U1> {
type Output = OwnedPoint<N, D, S::Alloc>;
#[inline]
fn neg(self) -> Self::Output {
PointBase::from_coordinates(-&self.coords)
}
}
/*
*
* Subtraction & Addition.
*
*/
// PointBase - PointBase
add_sub_impl!(Sub, sub, ClosedSub;
(D, U1), (D, U1) for D: DimName;
self: &'a PointBase<N, D, SA>, right: &'b PointBase<N, D, SB>, Output = ColumnVectorSum<N, D, D, SA>;
&self.coords - &right.coords; 'a, 'b);
add_sub_impl!(Sub, sub, ClosedSub;
(D, U1), (D, U1) for D: DimName;
self: &'a PointBase<N, D, SB>, right: PointBase<N, D, SA>, Output = ColumnVectorSum<N, D, D, SA>;
&self.coords - right.coords; 'a);
add_sub_impl!(Sub, sub, ClosedSub;
(D, U1), (D, U1) for D: DimName;
self: PointBase<N, D, SA>, right: &'b PointBase<N, D, SB>, Output = ColumnVectorSum<N, D, D, SA>;
self.coords - &right.coords; 'b);
add_sub_impl!(Sub, sub, ClosedSub;
(D, U1), (D, U1) for D: DimName;
self: PointBase<N, D, SA>, right: PointBase<N, D, SB>, Output = ColumnVectorSum<N, D, D, SA>;
self.coords - right.coords; );
// PointBase - Vector
add_sub_impl!(Sub, sub, ClosedSub;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: &'a PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(&self.coords - right); 'a, 'b);
add_sub_impl!(Sub, sub, ClosedSub;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: &'a PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(&self.coords - &right); 'a); // FIXME: should not be a ref to `right`.
add_sub_impl!(Sub, sub, ClosedSub;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(self.coords - right); 'b);
add_sub_impl!(Sub, sub, ClosedSub;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(self.coords - right); );
// PointBase + Vector
add_sub_impl!(Add, add, ClosedAdd;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: &'a PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(&self.coords + right); 'a, 'b);
add_sub_impl!(Add, add, ClosedAdd;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: &'a PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(&self.coords + &right); 'a); // FIXME: should not be a ref to `right`.
add_sub_impl!(Add, add, ClosedAdd;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(self.coords + right); 'b);
add_sub_impl!(Add, add, ClosedAdd;
(D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim;
self: PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>;
Self::Output::from_coordinates(self.coords + right); );
// XXX: replace by the shared macro: add_sub_assign_impl
macro_rules! op_assign_impl(
($($TraitAssign: ident, $method_assign: ident, $bound: ident);* $(;)*) => {$(
impl<'b, N, D1: DimName, D2: Dim, SA, SB> $TraitAssign<&'b ColumnVector<N, D2, SB>> for PointBase<N, D1, SA>
where N: Scalar + $bound,
SA: StorageMut<N, D1, U1>,
SB: Storage<N, D2, U1>,
ShapeConstraint: SameNumberOfRows<D1, D2> {
#[inline]
fn $method_assign(&mut self, right: &'b ColumnVector<N, D2, SB>) {
self.coords.$method_assign(right)
}
}
impl<N, D1: DimName, D2: Dim, SA, SB> $TraitAssign<ColumnVector<N, D2, SB>> for PointBase<N, D1, SA>
where N: Scalar + $bound,
SA: StorageMut<N, D1, U1>,
SB: Storage<N, D2, U1>,
ShapeConstraint: SameNumberOfRows<D1, D2> {
#[inline]
fn $method_assign(&mut self, right: ColumnVector<N, D2, SB>) {
self.coords.$method_assign(right)
}
}
)*}
);
op_assign_impl!(
AddAssign, add_assign, ClosedAdd;
SubAssign, sub_assign, ClosedSub;
);
/*
*
* Matrix × PointBase
*
*/
md_impl_all!(
Mul, mul;
(R1, C1), (D2, U1) for R1: DimName, C1: Dim, D2: DimName
where SA::Alloc: Allocator<N, R1, U1>
where ShapeConstraint: AreMultipliable<R1, C1, D2, U1>;
self: Matrix<N, R1, C1, SA>, right: PointBase<N, D2, SB>, Output = PointMul<N, R1, C1, SA>;
[val val] => PointBase::from_coordinates(self * right.coords);
[ref val] => PointBase::from_coordinates(self * right.coords);
[val ref] => PointBase::from_coordinates(self * &right.coords);
[ref ref] => PointBase::from_coordinates(self * &right.coords);
);
/*
*
* PointBase ×/÷ Scalar
*
*/
macro_rules! componentwise_scalarop_impl(
($Trait: ident, $method: ident, $bound: ident;
$TraitAssign: ident, $method_assign: ident) => {
impl<N, D: DimName, S> $Trait<N> for PointBase<N, D, S>
where N: Scalar + $bound,
S: Storage<N, D, U1> {
type Output = OwnedPoint<N, D, S::Alloc>;
#[inline]
fn $method(self, right: N) -> Self::Output {
PointBase::from_coordinates(self.coords.$method(right))
}
}
impl<'a, N, D: DimName, S> $Trait<N> for &'a PointBase<N, D, S>
where N: Scalar + $bound,
S: Storage<N, D, U1> {
type Output = OwnedPoint<N, D, S::Alloc>;
#[inline]
fn $method(self, right: N) -> Self::Output {
PointBase::from_coordinates((&self.coords).$method(right))
}
}
impl<N, D: DimName, S> $TraitAssign<N> for PointBase<N, D, S>
where N: Scalar + $bound,
S: StorageMut<N, D, U1> {
#[inline]
fn $method_assign(&mut self, right: N) {
self.coords.$method_assign(right)
}
}
}
);
componentwise_scalarop_impl!(Mul, mul, ClosedMul; MulAssign, mul_assign);
componentwise_scalarop_impl!(Div, div, ClosedDiv; DivAssign, div_assign);
macro_rules! left_scalar_mul_impl(
($($T: ty),* $(,)*) => {$(
impl<D: DimName, S> Mul<PointBase<$T, D, S>> for $T
where S: Storage<$T, D, U1> {
type Output = OwnedPoint<$T, D, S::Alloc>;
#[inline]
fn mul(self, right: PointBase<$T, D, S>) -> Self::Output {
PointBase::from_coordinates(self * right.coords)
}
}
impl<'b, D: DimName, S> Mul<&'b PointBase<$T, D, S>> for $T
where S: Storage<$T, D, U1> {
type Output = OwnedPoint<$T, D, S::Alloc>;
#[inline]
fn mul(self, right: &'b PointBase<$T, D, S>) -> Self::Output {
PointBase::from_coordinates(self * &right.coords)
}
}
)*}
);
left_scalar_mul_impl!(
u8, u16, u32, u64, usize,
i8, i16, i32, i64, isize,
f32, f64
);

703
src/geometry/quaternion.rs Normal file
View File

@ -0,0 +1,703 @@
use std::fmt;
use num::Zero;
use approx::ApproxEq;
use alga::general::Real;
use core::{Unit, ColumnVector, OwnedColumnVector, MatrixSlice, MatrixSliceMut, SquareMatrix,
OwnedSquareMatrix};
use core::storage::{Storage, StorageMut};
use core::allocator::Allocator;
use core::dimension::{U1, U3, U4};
use geometry::{RotationBase, OwnedRotation};
/// A quaternion with an owned storage allocated by `A`.
pub type OwnedQuaternionBase<N, A> = QuaternionBase<N, <A as Allocator<N, U4, U1>>::Buffer>;
/// A unit quaternion with an owned storage allocated by `A`.
pub type OwnedUnitQuaternionBase<N, A> = UnitQuaternionBase<N, <A as Allocator<N, U4, U1>>::Buffer>;
/// A quaternion. See the type alias `UnitQuaternionBase = Unit<QuaternionBase>` for a quaternion
/// that may be used as a rotation.
#[repr(C)]
#[derive(Hash, Debug, Copy, Clone)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct QuaternionBase<N: Real, S: Storage<N, U4, U1>> {
/// This quaternion as a 4D vector of coordinates in the `[ x, y, z, w ]` storage order.
pub coords: ColumnVector<N, U4, S>
}
impl<N, S> Eq for QuaternionBase<N, S>
where N: Real + Eq,
S: Storage<N, U4, U1> {
}
impl<N, S> PartialEq for QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
fn eq(&self, rhs: &Self) -> bool {
self.coords == rhs.coords ||
// Account for the double-covering of S², i.e. q = -q
self.as_vector().iter().zip(rhs.as_vector().iter()).all(|(a, b)| *a == -*b)
}
}
impl<N, S> QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
/// Moves this quaternion into one that owns its data.
#[inline]
pub fn into_owned(self) -> OwnedQuaternionBase<N, S::Alloc> {
QuaternionBase::from_vector(self.coords.into_owned())
}
/// Clones this quaternion into one that owns its data.
#[inline]
pub fn clone_owned(&self) -> OwnedQuaternionBase<N, S::Alloc> {
QuaternionBase::from_vector(self.coords.clone_owned())
}
/// The vector part `(i, j, k)` of this quaternion.
#[inline]
pub fn vector(&self) -> MatrixSlice<N, U3, U1, S::RStride, S::CStride, S::Alloc> {
self.coords.fixed_rows::<U3>(0)
}
/// The scalar part `w` of this quaternion.
#[inline]
pub fn scalar(&self) -> N {
self.coords[3]
}
/// Reinterprets this quaternion as a 4D vector.
#[inline]
pub fn as_vector(&self) -> &ColumnVector<N, U4, S> {
&self.coords
}
/// The norm of this quaternion.
#[inline]
pub fn norm(&self) -> N {
self.coords.norm()
}
/// The squared norm of this quaternion.
#[inline]
pub fn norm_squared(&self) -> N {
self.coords.norm_squared()
}
/// Normalizes this quaternion.
#[inline]
pub fn normalize(&self) -> OwnedQuaternionBase<N, S::Alloc> {
QuaternionBase::from_vector(self.coords.normalize())
}
/// Compute the conjugate of this quaternion.
#[inline]
pub fn conjugate(&self) -> OwnedQuaternionBase<N, S::Alloc> {
let v = OwnedColumnVector::<N, U4, S::Alloc>::new(-self.coords[0],
-self.coords[1],
-self.coords[2],
self.coords[3]);
QuaternionBase::from_vector(v)
}
/// Inverts this quaternion if it is not zero.
#[inline]
pub fn try_inverse(&self) -> Option<OwnedQuaternionBase<N, S::Alloc>> {
let mut res = QuaternionBase::from_vector(self.coords.clone_owned());
if res.try_inverse_mut() {
Some(res)
}
else {
None
}
}
/// Linear interpolation between two quaternion.
#[inline]
pub fn lerp<S2>(&self, other: &QuaternionBase<N, S2>, t: N) -> OwnedQuaternionBase<N, S::Alloc>
where S2: Storage<N, U4, U1> {
self * (N::one() - t) + other * t
}
}
impl<N, S> QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1>,
S::Alloc: Allocator<N, U3, U1> {
/// The polar decomposition of this quaternion.
///
/// Returns, from left to right: the quaternion norm, the half rotation angle, the rotation
/// axis. If the rotation angle is zero, the rotation axis is set to `None`.
pub fn polar_decomposition(&self) -> (N, N, Option<Unit<OwnedColumnVector<N, U3, S::Alloc>>>) {
if let Some((q, n)) = Unit::try_new_and_get(self.clone_owned(), N::zero()) {
if let Some(axis) = Unit::try_new(self.vector().clone_owned(), N::zero()) {
let angle = q.angle() / ::convert(2.0f64);
(n, angle, Some(axis))
}
else {
(n, N::zero(), None)
}
}
else {
(N::zero(), N::zero(), None)
}
}
/// Compute the exponential of a quaternion.
#[inline]
pub fn exp(&self) -> OwnedQuaternionBase<N, S::Alloc> {
let v = self.vector();
let nn = v.norm_squared();
if relative_eq!(nn, N::zero()) {
QuaternionBase::identity()
}
else {
let w_exp = self.scalar().exp();
let n = nn.sqrt();
let nv = v * (w_exp * n.sin() / n);
QuaternionBase::from_parts(n.cos(), nv)
}
}
/// Compute the natural logarithm of a quaternion.
#[inline]
pub fn ln(&self) -> OwnedQuaternionBase<N, S::Alloc> {
let n = self.norm();
let v = self.vector();
let s = self.scalar();
QuaternionBase::from_parts(n.ln(), v.normalize() * (s / n).acos())
}
/// Raise the quaternion to a given floating power.
#[inline]
pub fn powf(&self, n: N) -> OwnedQuaternionBase<N, S::Alloc> {
(self.ln() * n).exp()
}
}
impl<N, S> QuaternionBase<N, S>
where N: Real,
S: StorageMut<N, U4, U1> {
/// Transforms this quaternion into its 4D vector form (Vector part, Scalar part).
#[inline]
pub fn as_vector_mut(&mut self) -> &mut ColumnVector<N, U4, S> {
&mut self.coords
}
/// The mutable vector part `(i, j, k)` of this quaternion.
#[inline]
pub fn vector_mut(&mut self) -> MatrixSliceMut<N, U3, U1, S::RStride, S::CStride, S::Alloc> {
self.coords.fixed_rows_mut::<U3>(0)
}
/// Replaces this quaternion by its conjugate.
#[inline]
pub fn conjugate_mut(&mut self) {
self.coords[0] = -self.coords[0];
self.coords[1] = -self.coords[1];
self.coords[2] = -self.coords[2];
}
/// Inverts this quaternion in-place if it is not zero.
#[inline]
pub fn try_inverse_mut(&mut self) -> bool {
let norm_squared = self.norm_squared();
if relative_eq!(&norm_squared, &N::zero()) {
false
}
else {
self.conjugate_mut();
self.coords /= norm_squared;
true
}
}
/// Normalizes this quaternion.
#[inline]
pub fn normalize_mut(&mut self) -> N {
self.coords.normalize_mut()
}
}
impl<N, S> ApproxEq for QuaternionBase<N, S>
where N: Real + ApproxEq<Epsilon = N>,
S: Storage<N, U4, U1> {
type Epsilon = N;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.as_vector().relative_eq(other.as_vector(), epsilon, max_relative) ||
// Account for the double-covering of S², i.e. q = -q
self.as_vector().iter().zip(other.as_vector().iter()).all(|(a, b)| a.relative_eq(&-*b, epsilon, max_relative))
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.as_vector().ulps_eq(other.as_vector(), epsilon, max_ulps) ||
// Account for the double-covering of S², i.e. q = -q.
self.as_vector().iter().zip(other.as_vector().iter()).all(|(a, b)| a.ulps_eq(&-*b, epsilon, max_ulps))
}
}
impl<N, S> fmt::Display for QuaternionBase<N, S>
where N: Real + fmt::Display,
S: Storage<N, U4, U1> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Quaternion {} ({}, {}, {})", self[3], self[0], self[1], self[2])
}
}
/// A unit quaternions. May be used to represent a rotation.
///
///
/// <center>
/// <big><b>
/// Due to a [bug](https://github.com/rust-lang/rust/issues/32077) in rustdoc, the documentation
/// below has been written manually lists only method signatures.<br>
/// Trait implementations are not listed either.
/// </b></big>
/// </center>
///
/// Please refer directly to the documentation written above each function definition on the source
/// code for more details.
///
/// <h2 id="methods">Methods</h2>
///
///
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">angle</a>(&self) -> N</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">angle_to</a>(&self, other: &UnitQuaternionBase) -> N</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">axis</a>(&self) -> Option&lt;Unit&lt;OwnedColumnVector&gt;&gt;</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">clone_owned</a>(&self) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">conjugate_mut</a>(&mut self)</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">conjugate</a>(&self) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">exp</a>(&self) -> OwnedQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">from_axis_angle</a>(axis: &Unit&lt;ColumnVector&gt;, angle: N) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">from_euler_angles</a>(roll: N, pitch: N, yaw: N) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">from_quaternion</a>(q: QuaternionBase) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">from_rotation_matrix</a>(rotmat: &RotationBase) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">from_scaled_axis</a>(axisangle: ColumnVector) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">identity</a>() -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">into_owned</a>(self) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">inverse_mut</a>(&mut self)</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">inverse</a>(&self) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">lerp</a>(&self, other: &UnitQuaternionBase, t: N) -> OwnedQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">ln</a>(&self) -> OwnedQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">look_at_lh</a>(dir: &ColumnVector, up: &ColumnVector) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">look_at_rh</a>(dir: &ColumnVector, up: &ColumnVector) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">new</a>(axisangle: ColumnVector) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">new_observer_frame</a>(dir: &ColumnVector, up: &ColumnVector) -> Self</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">nlerp</a>(&self, other: &UnitQuaternionBase, t: N) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">powf</a>(&self, n: N) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">quaternion</a>(&self) -> &QuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">rotation_between</a>(a: &ColumnVector, b: &ColumnVector) -> Option&lt;Self&gt;</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">rotation_to</a>(&self, other: &UnitQuaternionBase) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">scaled_axis</a>(&self) -> OwnedColumnVector</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">scaled_rotation_between</a>(a: &ColumnVector, b: &ColumnVector, s: N) -> Option&lt;Self&gt;</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">slerp</a>(&self, other: &UnitQuaternionBase, t: N) -> OwnedUnitQuaternionBase</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">to_homogeneous</a>(&self) -> OwnedSquareMatrix</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">to_rotation_matrix</a>(&self) -> OwnedRotation</code>
/// </h4>
/// <h4 class="method"><span class="invisible">
/// <code>fn <a class="fnname">try_slerp</a>(&self, other: &UnitQuaternionBase, t: N, epsilon: N) -> Option&lt;OwnedUnitQuaternionBase&gt;</code>
/// </h4>
pub type UnitQuaternionBase<N, S> = Unit<QuaternionBase<N, S>>;
impl<N, S> UnitQuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
/// Moves this unit quaternion into one that owns its data.
#[inline]
pub fn into_owned(self) -> OwnedUnitQuaternionBase<N, S::Alloc> {
UnitQuaternionBase::new_unchecked(self.unwrap().into_owned())
}
/// Clones this unit quaternion into one that owns its data.
#[inline]
pub fn clone_owned(&self) -> OwnedUnitQuaternionBase<N, S::Alloc> {
UnitQuaternionBase::new_unchecked(self.as_ref().clone_owned())
}
/// The rotation angle in [0; pi] of this unit quaternion.
#[inline]
pub fn angle(&self) -> N {
let w = self.quaternion().scalar().abs();
// Handle innacuracies that make break `.acos`.
if w >= N::one() {
N::zero()
}
else {
w.acos() * ::convert(2.0f64)
}
}
/// The underlying quaternion.
///
/// Same as `self.as_ref()`.
#[inline]
pub fn quaternion(&self) -> &QuaternionBase<N, S> {
self.as_ref()
}
/// Compute the conjugate of this unit quaternion.
#[inline]
pub fn conjugate(&self) -> OwnedUnitQuaternionBase<N, S::Alloc> {
UnitQuaternionBase::new_unchecked(self.as_ref().conjugate())
}
/// Inverts this quaternion if it is not zero.
#[inline]
pub fn inverse(&self) -> OwnedUnitQuaternionBase<N, S::Alloc> {
self.conjugate()
}
/// The rotation angle needed to make `self` and `other` coincide.
#[inline]
pub fn angle_to<S2>(&self, other: &UnitQuaternionBase<N, S2>) -> N
where S2: Storage<N, U4, U1> {
let delta = self.rotation_to(other);
delta.angle()
}
/// The unit quaternion needed to make `self` and `other` coincide.
///
/// The result is such that: `self.rotation_to(other) * self == other`.
#[inline]
pub fn rotation_to<S2>(&self, other: &UnitQuaternionBase<N, S2>) -> OwnedUnitQuaternionBase<N, S2::Alloc>
where S2: Storage<N, U4, U1> {
other / self
}
/// Linear interpolation between two unit quaternions.
///
/// The result is not normalized.
#[inline]
pub fn lerp<S2>(&self, other: &UnitQuaternionBase<N, S2>, t: N) -> OwnedQuaternionBase<N, S::Alloc>
where S2: Storage<N, U4, U1> {
self.as_ref().lerp(other.as_ref(), t)
}
/// Normalized linear interpolation between two unit quaternions.
#[inline]
pub fn nlerp<S2>(&self, other: &UnitQuaternionBase<N, S2>, t: N) -> OwnedUnitQuaternionBase<N, S::Alloc>
where S2: Storage<N, U4, U1> {
let mut res = self.lerp(other, t);
let _ = res.normalize_mut();
UnitQuaternionBase::new_unchecked(res)
}
/// Spherical linear interpolation between two unit quaternions.
///
/// Panics if the angle between both quaternion is 180 degrees (in which case the interpolation
/// is not well-defined).
#[inline]
pub fn slerp<S2>(&self, other: &UnitQuaternionBase<N, S2>, t: N) -> OwnedUnitQuaternionBase<N, S::Alloc>
where S2: Storage<N, U4, U1, Alloc = S::Alloc> {
self.try_slerp(other, t, N::zero()).expect(
"Unable to perform a spherical quaternion interpolation when they \
are 180 degree apart (the result is not unique).")
}
/// Computes the spherical linear interpolation between two unit quaternions or returns `None`
/// if both quaternions are approximately 180 degrees apart (in which case the interpolation is
/// not well-defined).
///
/// # Arguments
/// * `self`: the first quaternion to interpolate from.
/// * `other`: the second quaternion to interpolate toward.
/// * `t`: the interpolation parameter. Should be between 0 and 1.
/// * `epsilon`: the value bellow which the sinus of the angle separating both quaternion
/// must be to return `None`.
#[inline]
pub fn try_slerp<S2>(&self, other: &UnitQuaternionBase<N, S2>, t: N, epsilon: N)
-> Option<OwnedUnitQuaternionBase<N, S::Alloc>>
where S2: Storage<N, U4, U1, Alloc = S::Alloc> {
let c_hang = self.coords.dot(&other.coords);
// self == other
if c_hang.abs() >= N::one() {
return Some(self.clone_owned())
}
let hang = c_hang.acos();
let s_hang = (N::one() - c_hang * c_hang).sqrt();
// FIXME: what if s_hang is 0.0 ? The result is not well-defined.
if relative_eq!(s_hang, N::zero(), epsilon = epsilon) {
None
}
else {
let ta = ((N::one() - t) * hang).sin() / s_hang;
let tb = (t * hang).sin() / s_hang;
let res = self.as_ref() * ta + other.as_ref() * tb;
Some(UnitQuaternionBase::new_unchecked(res))
}
}
}
impl<N, S> UnitQuaternionBase<N, S>
where N: Real,
S: StorageMut<N, U4, U1> {
/// Compute the conjugate of this unit quaternion in-place.
#[inline]
pub fn conjugate_mut(&mut self) {
self.as_mut_unchecked().conjugate_mut()
}
/// Inverts this quaternion if it is not zero.
#[inline]
pub fn inverse_mut(&mut self) {
self.as_mut_unchecked().conjugate_mut()
}
}
impl<N, S> UnitQuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1>,
S::Alloc: Allocator<N, U3, U1> {
/// The rotation axis of this unit quaternion or `None` if the rotation is zero.
#[inline]
pub fn axis(&self) -> Option<Unit<OwnedColumnVector<N, U3, S::Alloc>>> {
let v =
if self.quaternion().scalar() >= N::zero() {
self.as_ref().vector().clone_owned()
}
else {
-self.as_ref().vector()
};
Unit::try_new(v, N::zero())
}
/// The rotation axis of this unit quaternion multiplied by the rotation agle.
#[inline]
pub fn scaled_axis(&self) -> OwnedColumnVector<N, U3, S::Alloc> {
if let Some(axis) = self.axis() {
axis.unwrap() * self.angle()
}
else {
ColumnVector::zero()
}
}
/// Compute the exponential of a quaternion.
///
/// Note that this function yields a `QuaternionBase<N>` because it looses the unit property.
#[inline]
pub fn exp(&self) -> OwnedQuaternionBase<N, S::Alloc> {
self.as_ref().exp()
}
/// Compute the natural logarithm of a quaternion.
///
/// Note that this function yields a `QuaternionBase<N>` because it looses the unit property.
/// The vector part of the return value corresponds to the axis-angle representation (divided
/// by 2.0) of this unit quaternion.
#[inline]
pub fn ln(&self) -> OwnedQuaternionBase<N, S::Alloc> {
if let Some(v) = self.axis() {
QuaternionBase::from_parts(N::zero(), v.unwrap() * self.angle())
}
else {
QuaternionBase::zero()
}
}
/// Raise the quaternion to a given floating power.
///
/// This returns the unit quaternion that identifies a rotation with axis `self.axis()` and
/// angle `self.angle() × n`.
#[inline]
pub fn powf(&self, n: N) -> OwnedUnitQuaternionBase<N, S::Alloc> {
if let Some(v) = self.axis() {
UnitQuaternionBase::from_axis_angle(&v, self.angle() * n)
}
else {
UnitQuaternionBase::identity()
}
}
}
impl<N, S> UnitQuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1>,
S::Alloc: Allocator<N, U3, U3> {
/// Builds a rotation matrix from this unit quaternion.
#[inline]
pub fn to_rotation_matrix(&self) -> OwnedRotation<N, U3, S::Alloc> {
let i = self.as_ref()[0];
let j = self.as_ref()[1];
let k = self.as_ref()[2];
let w = self.as_ref()[3];
let ww = w * w;
let ii = i * i;
let jj = j * j;
let kk = k * k;
let ij = i * j * ::convert(2.0f64);
let wk = w * k * ::convert(2.0f64);
let wj = w * j * ::convert(2.0f64);
let ik = i * k * ::convert(2.0f64);
let jk = j * k * ::convert(2.0f64);
let wi = w * i * ::convert(2.0f64);
RotationBase::from_matrix_unchecked(
SquareMatrix::<_, U3, _>::new(
ww + ii - jj - kk, ij - wk, wj + ik,
wk + ij, ww - ii + jj - kk, jk - wi,
ik - wj, wi + jk, ww - ii - jj + kk
)
)
}
/// Converts this unit quaternion into its equivalent homogeneous transformation matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, U4, S::Alloc>
where S::Alloc: Allocator<N, U4, U4> {
self.to_rotation_matrix().to_homogeneous()
}
}
impl<N, S> fmt::Display for UnitQuaternionBase<N, S>
where N: Real + fmt::Display,
S: Storage<N, U4, U1>,
S::Alloc: Allocator<N, U3, U1> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(axis) = self.axis() {
let axis = axis.unwrap();
write!(f, "UnitQuaternion angle: {} axis: ({}, {}, {})", self.angle(), axis[0], axis[1], axis[2])
}
else {
write!(f, "UnitQuaternion angle: {} axis: (undefined)", self.angle())
}
}
}
impl<N, S> ApproxEq for UnitQuaternionBase<N, S>
where N: Real + ApproxEq<Epsilon = N>,
S: Storage<N, U4, U1> {
type Epsilon = N;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.as_ref().relative_eq(other.as_ref(), epsilon, max_relative)
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.as_ref().ulps_eq(other.as_ref(), epsilon, max_ulps)
}
}

View File

@ -0,0 +1,382 @@
use num::Zero;
use alga::general::{AbstractMagma, AbstractGroup, AbstractGroupAbelian, AbstractLoop,
AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, AbstractModule,
Module, Real, Inverse, Multiplicative, Additive, Identity, Id};
use alga::linear::{Transformation, AffineTransformation, Similarity, Isometry, DirectIsometry,
OrthogonalTransformation, VectorSpace, FiniteDimVectorSpace, NormedSpace,
Rotation, ProjectiveTransformation};
use core::ColumnVector;
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use core::dimension::{U1, U3, U4};
use geometry::{PointBase, QuaternionBase, UnitQuaternionBase};
impl<N, S> Identity<Multiplicative> for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, S> Identity<Additive> for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn identity() -> Self {
Self::zero()
}
}
impl<N, S> AbstractMagma<Multiplicative> for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
impl<N, S> AbstractMagma<Additive> for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self + rhs
}
}
impl<N, S> Inverse<Additive> for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn inverse(&self) -> Self {
-self
}
}
macro_rules! impl_structures(
($Quaternion: ident; $($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, S> $marker<$operator> for $Quaternion<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> { }
)*}
);
impl_structures!(
QuaternionBase;
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
AbstractSemigroup<Additive>,
AbstractQuasigroup<Additive>,
AbstractMonoid<Additive>,
AbstractLoop<Additive>,
AbstractGroup<Additive>,
AbstractGroupAbelian<Additive>
);
/*
*
* Vector space.
*
*/
impl<N, S> AbstractModule for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
type AbstractRing = N;
#[inline]
fn multiply_by(&self, n: N) -> Self {
self * n
}
}
impl<N, S> Module for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
type Ring = N;
}
impl<N, S> VectorSpace for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
type Field = N;
}
impl<N, S> FiniteDimVectorSpace for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn dimension() -> usize {
4
}
#[inline]
fn canonical_basis_element(i: usize) -> Self {
Self::from_vector(ColumnVector::canonical_basis_element(i))
}
#[inline]
fn dot(&self, other: &Self) -> N {
self.coords.dot(&other.coords)
}
#[inline]
unsafe fn component_unchecked(&self, i: usize) -> &N {
self.coords.component_unchecked(i)
}
#[inline]
unsafe fn component_unchecked_mut(&mut self, i: usize) -> &mut N {
self.coords.component_unchecked_mut(i)
}
}
impl<N, S> NormedSpace for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn norm_squared(&self) -> N {
self.coords.norm_squared()
}
#[inline]
fn norm(&self) -> N {
self.as_vector().norm()
}
#[inline]
fn normalize(&self) -> Self {
let v = self.coords.normalize();
Self::from_vector(v)
}
#[inline]
fn normalize_mut(&mut self) -> N {
self.coords.normalize_mut()
}
#[inline]
fn try_normalize(&self, min_norm: N) -> Option<Self> {
if let Some(v) = self.coords.try_normalize(min_norm) {
Some(Self::from_vector(v))
}
else {
None
}
}
#[inline]
fn try_normalize_mut(&mut self, min_norm: N) -> Option<N> {
self.coords.try_normalize_mut(min_norm)
}
}
/*
*
* Implementations for UnitQuaternionBase.
*
*/
impl<N, S> Identity<Multiplicative> for UnitQuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, S> AbstractMagma<Multiplicative> for UnitQuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
impl<N, S> Inverse<Multiplicative> for UnitQuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn inverse(&self) -> Self {
self.inverse()
}
#[inline]
fn inverse_mut(&mut self) {
self.inverse_mut()
}
}
impl_structures!(
UnitQuaternionBase;
AbstractSemigroup<Multiplicative>,
AbstractQuasigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
AbstractLoop<Multiplicative>,
AbstractGroup<Multiplicative>
);
impl<N, SA, SB> Transformation<PointBase<N, U3, SB>> for UnitQuaternionBase<N, SA>
where N: Real,
SA: OwnedStorage<N, U4, U1>,
SB: OwnedStorage<N, U3, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> {
#[inline]
fn transform_point(&self, pt: &PointBase<N, U3, SB>) -> PointBase<N, U3, SB> {
self * pt
}
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, U3, SB>) -> ColumnVector<N, U3, SB> {
self * v
}
}
impl<N, SA, SB> ProjectiveTransformation<PointBase<N, U3, SB>> for UnitQuaternionBase<N, SA>
where N: Real,
SA: OwnedStorage<N, U4, U1>,
SB: OwnedStorage<N, U3, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> {
#[inline]
fn inverse_transform_point(&self, pt: &PointBase<N, U3, SB>) -> PointBase<N, U3, SB> {
// FIXME: would it be useful performancewise not to call inverse explicitly (i-e. implement
// the inverse transformation explicitly here) ?
self.inverse() * pt
}
#[inline]
fn inverse_transform_vector(&self, v: &ColumnVector<N, U3, SB>) -> ColumnVector<N, U3, SB> {
self.inverse() * v
}
}
impl<N, SA, SB> AffineTransformation<PointBase<N, U3, SB>> for UnitQuaternionBase<N, SA>
where N: Real,
SA: OwnedStorage<N, U4, U1>,
SB: OwnedStorage<N, U3, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> {
type Rotation = Self;
type NonUniformScaling = Id;
type Translation = Id;
#[inline]
fn decompose(&self) -> (Id, Self, Id, Self) {
(Id::new(), self.clone(), Id::new(), Self::identity())
}
#[inline]
fn append_translation(&self, _: &Self::Translation) -> Self {
self.clone()
}
#[inline]
fn prepend_translation(&self, _: &Self::Translation) -> Self {
self.clone()
}
#[inline]
fn append_rotation(&self, r: &Self::Rotation) -> Self {
r * self
}
#[inline]
fn prepend_rotation(&self, r: &Self::Rotation) -> Self {
self * r
}
#[inline]
fn append_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
#[inline]
fn prepend_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
}
impl<N, SA, SB> Similarity<PointBase<N, U3, SB>> for UnitQuaternionBase<N, SA>
where N: Real,
SA: OwnedStorage<N, U4, U1>,
SB: OwnedStorage<N, U3, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> {
type Scaling = Id;
#[inline]
fn translation(&self) -> Id {
Id::new()
}
#[inline]
fn rotation(&self) -> Self {
self.clone()
}
#[inline]
fn scaling(&self) -> Id {
Id::new()
}
}
macro_rules! marker_impl(
($($Trait: ident),*) => {$(
impl<N, SA, SB> $Trait<PointBase<N, U3, SB>> for UnitQuaternionBase<N, SA>
where N: Real,
SA: OwnedStorage<N, U4, U1>,
SB: OwnedStorage<N, U3, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> { }
)*}
);
marker_impl!(Isometry, DirectIsometry, OrthogonalTransformation);
impl<N, SA, SB> Rotation<PointBase<N, U3, SB>> for UnitQuaternionBase<N, SA>
where N: Real,
SA: OwnedStorage<N, U4, U1>,
SB: OwnedStorage<N, U3, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, U4, U1, SA> + Allocator<N, U3, U1>,
SB::Alloc: OwnedAllocator<N, U3, U1, SB> {
#[inline]
fn powf(&self, n: N) -> Option<Self> {
Some(self.powf(n))
}
#[inline]
fn rotation_between(a: &ColumnVector<N, U3, SB>, b: &ColumnVector<N, U3, SB>) -> Option<Self> {
Self::rotation_between(a, b)
}
#[inline]
fn scaled_rotation_between(a: &ColumnVector<N, U3, SB>, b: &ColumnVector<N, U3, SB>, s: N) -> Option<Self> {
Self::scaled_rotation_between(a, b, s)
}
}

View File

@ -0,0 +1,10 @@
use core::MatrixArray;
use core::dimension::{U1, U4};
use geometry::{QuaternionBase, UnitQuaternionBase};
/// A statically-allocated quaternion.
pub type Quaternion<N> = QuaternionBase<N, MatrixArray<N, U4, U1>>;
/// A statically-allocated unit quaternion.
pub type UnitQuaternion<N> = UnitQuaternionBase<N, MatrixArray<N, U4, U1>>;

View File

@ -0,0 +1,369 @@
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use rand::{Rand, Rng};
use num::{Zero, One};
use alga::general::Real;
use core::{Unit, ColumnVector, Vector3};
use core::storage::{Storage, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use core::dimension::{U1, U3, U4};
use geometry::{QuaternionBase, UnitQuaternionBase, RotationBase, OwnedRotation};
impl<N, S> QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
/// Creates a quaternion from a 4D vector. The quaternion scalar part corresponds to the `w`
/// vector component.
#[inline]
pub fn from_vector(vector: ColumnVector<N, U4, S>) -> Self {
QuaternionBase {
coords: vector
}
}
}
impl<N, S> QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
/// Creates a new quaternion from its individual components. Note that the arguments order does
/// **not** follow the storage order.
///
/// The storage order is `[ x, y, z, w ]`.
#[inline]
pub fn new(w: N, x: N, y: N, z: N) -> Self {
let v = ColumnVector::<N, U4, S>::new(x, y, z, w);
Self::from_vector(v)
}
/// Creates a new quaternion from its scalar and vector parts. Note that the arguments order does
/// **not** follow the storage order.
///
/// The storage order is [ vector, scalar ].
#[inline]
// FIXME: take a reference to `vector`?
pub fn from_parts<SB>(scalar: N, vector: ColumnVector<N, U3, SB>) -> Self
where SB: Storage<N, U3, U1> {
Self::new(scalar, vector[0], vector[1], vector[2])
}
/// Creates a new quaternion from its polar decomposition.
///
/// Note that `axis` is assumed to be a unit vector.
// FIXME: take a reference to `axis`?
pub fn from_polar_decomposition<SB>(scale: N, theta: N, axis: Unit<ColumnVector<N, U3, SB>>) -> Self
where SB: Storage<N, U3, U1> {
let rot = UnitQuaternionBase::<N, S>::from_axis_angle(&axis, theta * ::convert(2.0f64));
rot.unwrap() * scale
}
/// The quaternion multiplicative identity.
#[inline]
pub fn identity() -> Self {
Self::new(N::one(), N::zero(), N::zero(), N::zero())
}
}
impl<N, S> One for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn one() -> Self {
Self::identity()
}
}
impl<N, S> Zero for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn zero() -> Self {
Self::new(N::zero(), N::zero(), N::zero(), N::zero())
}
#[inline]
fn is_zero(&self) -> bool {
self.coords.is_zero()
}
}
impl<N, S> Rand for QuaternionBase<N, S>
where N: Real + Rand,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn rand<R: Rng>(rng: &mut R) -> Self {
QuaternionBase::new(rng.gen(), rng.gen(), rng.gen(), rng.gen())
}
}
#[cfg(feature="arbitrary")]
impl<N, S> Arbitrary for QuaternionBase<N, S>
where N: Real + Arbitrary,
S: OwnedStorage<N, U4, U1> + Send,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn arbitrary<G: Gen>(g: &mut G) -> Self {
QuaternionBase::new(N::arbitrary(g), N::arbitrary(g),
N::arbitrary(g), N::arbitrary(g))
}
}
impl<N, S> UnitQuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
/// The quaternion multiplicative identity.
#[inline]
pub fn identity() -> Self {
Self::new_unchecked(QuaternionBase::identity())
}
/// Creates a new quaternion from a unit vector (the rotation axis) and an angle
/// (the rotation angle).
#[inline]
pub fn from_axis_angle<SB>(axis: &Unit<ColumnVector<N, U3, SB>>, angle: N) -> Self
where SB: Storage<N, U3, U1> {
let (sang, cang) = (angle / ::convert(2.0f64)).sin_cos();
let q = QuaternionBase::from_parts(cang, axis.as_ref() * sang);
Self::new_unchecked(q)
}
/// Creates a new unit quaternion from a quaternion.
///
/// The input quaternion will be normalized.
#[inline]
pub fn from_quaternion(q: QuaternionBase<N, S>) -> Self {
Self::new_normalize(q)
}
/// Creates a new unit quaternion from Euler angles.
///
/// The primitive rotations are applied in order: 1 roll 2 pitch 3 yaw.
#[inline]
pub fn from_euler_angles(roll: N, pitch: N, yaw: N) -> Self {
let (sr, cr) = (roll * ::convert(0.5f64)).sin_cos();
let (sp, cp) = (pitch * ::convert(0.5f64)).sin_cos();
let (sy, cy) = (yaw * ::convert(0.5f64)).sin_cos();
let q = QuaternionBase::new(
cr * cp * cy + sr * sp * sy,
sr * cp * cy - cr * sp * sy,
cr * sp * cy + sr * cp * sy,
cr * cp * sy - sr * sp * cy);
Self::new_unchecked(q)
}
/// Builds an unit quaternion from a rotation matrix.
#[inline]
pub fn from_rotation_matrix<SB>(rotmat: &RotationBase<N, U3, SB>) -> Self
where SB: Storage<N, U3, U3>,
SB::Alloc: Allocator<N, U3, U1> {
// Robust matrix to quaternion transformation.
// See http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion
let tr = rotmat[(0, 0)] + rotmat[(1, 1)] + rotmat[(2, 2)];
let res;
let _0_25: N = ::convert(0.25);
if tr > N::zero() {
let denom = (tr + N::one()).sqrt() * ::convert(2.0);
res = QuaternionBase::new(_0_25 * denom,
(rotmat[(2, 1)] - rotmat[(1, 2)]) / denom,
(rotmat[(0, 2)] - rotmat[(2, 0)]) / denom,
(rotmat[(1, 0)] - rotmat[(0, 1)]) / denom);
}
else if rotmat[(0, 0)] > rotmat[(1, 1)] && rotmat[(0, 0)] > rotmat[(2, 2)] {
let denom = (N::one() + rotmat[(0, 0)] - rotmat[(1, 1)] - rotmat[(2, 2)]).sqrt() * ::convert(2.0);
res = QuaternionBase::new((rotmat[(2, 1)] - rotmat[(1, 2)]) / denom,
_0_25 * denom,
(rotmat[(0, 1)] + rotmat[(1, 0)]) / denom,
(rotmat[(0, 2)] + rotmat[(2, 0)]) / denom);
}
else if rotmat[(1, 1)] > rotmat[(2, 2)] {
let denom = (N::one() + rotmat[(1, 1)] - rotmat[(0, 0)] - rotmat[(2, 2)]).sqrt() * ::convert(2.0);
res = QuaternionBase::new((rotmat[(0, 2)] - rotmat[(2, 0)]) / denom,
(rotmat[(0, 1)] + rotmat[(1, 0)]) / denom,
_0_25 * denom,
(rotmat[(1, 2)] + rotmat[(2, 1)]) / denom);
}
else {
let denom = (N::one() + rotmat[(2, 2)] - rotmat[(0, 0)] - rotmat[(1, 1)]).sqrt() * ::convert(2.0);
res = QuaternionBase::new((rotmat[(1, 0)] - rotmat[(0, 1)]) / denom,
(rotmat[(0, 2)] + rotmat[(2, 0)]) / denom,
(rotmat[(1, 2)] + rotmat[(2, 1)]) / denom,
_0_25 * denom);
}
Self::new_unchecked(res)
}
/// The unit quaternion needed to make `a` and `b` be collinear and point toward the same
/// direction.
#[inline]
pub fn rotation_between<SB, SC>(a: &ColumnVector<N, U3, SB>, b: &ColumnVector<N, U3, SC>) -> Option<Self>
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1> {
Self::scaled_rotation_between(a, b, N::one())
}
/// The smallest rotation needed to make `a` and `b` collinear and point toward the same
/// direction, raised to the power `s`.
#[inline]
pub fn scaled_rotation_between<SB, SC>(a: &ColumnVector<N, U3, SB>, b: &ColumnVector<N, U3, SC>, s: N) -> Option<Self>
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1> {
// FIXME: code duplication with RotationBase.
if let (Some(na), Some(nb)) = (a.try_normalize(N::zero()), b.try_normalize(N::zero())) {
let c = na.cross(&nb);
if let Some(axis) = Unit::try_new(c, N::default_epsilon()) {
return Some(Self::from_axis_angle(&axis, na.dot(&nb).acos() * s))
}
// Zero or PI.
if na.dot(&nb) < N::zero() {
// PI
//
// The rotation axis is undefined but the angle not zero. This is not a
// simple rotation.
return None;
}
}
Some(Self::identity())
}
/// Creates an unit quaternion that corresponds to the local frame of an observer standing at the
/// origin and looking toward `dir`.
///
/// It maps the view direction `dir` to the positive `z` axis.
///
/// # Arguments
/// * dir - The look direction, that is, direction the matrix `z` axis will be aligned with.
/// * up - The vertical direction. The only requirement of this parameter is to not be
/// collinear
/// to `dir`. Non-collinearity is not checked.
#[inline]
pub fn new_observer_frame<SB, SC>(dir: &ColumnVector<N, U3, SB>, up: &ColumnVector<N, U3, SC>) -> Self
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1>,
S::Alloc: Allocator<N, U3, U3> +
Allocator<N, U3, U1> {
Self::from_rotation_matrix(&OwnedRotation::<N, U3, S::Alloc>::new_observer_frame(dir, up))
}
/// Builds a right-handed look-at view matrix without translation.
///
/// This conforms to the common notion of right handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_rh<SB, SC>(dir: &ColumnVector<N, U3, SB>, up: &ColumnVector<N, U3, SC>) -> Self
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1>,
S::Alloc: Allocator<N, U3, U3> +
Allocator<N, U3, U1> {
Self::new_observer_frame(&-dir, up).inverse()
}
/// Builds a left-handed look-at view matrix without translation.
///
/// This conforms to the common notion of left handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_lh<SB, SC>(dir: &ColumnVector<N, U3, SB>, up: &ColumnVector<N, U3, SC>) -> Self
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1>,
S::Alloc: Allocator<N, U3, U3> +
Allocator<N, U3, U1> {
Self::new_observer_frame(dir, up).inverse()
}
}
impl<N, S> UnitQuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> +
Allocator<N, U3, U1> {
/// Creates a new unit quaternion rotation from a rotation axis scaled by the rotation angle.
///
/// If `axisangle` is zero, this returns the indentity rotation.
#[inline]
pub fn new<SB>(axisangle: ColumnVector<N, U3, SB>) -> Self
where SB: Storage<N, U3, U1> {
let two: N = ::convert(2.0f64);
let q = QuaternionBase::<N, S>::from_parts(N::zero(), axisangle / two).exp();
Self::new_unchecked(q)
}
/// Creates a new unit quaternion rotation from a rotation axis scaled by the rotation angle.
///
/// If `axisangle` is zero, this returns the indentity rotation.
/// Same as `Self::new(axisangle)`.
#[inline]
pub fn from_scaled_axis<SB>(axisangle: ColumnVector<N, U3, SB>) -> Self
where SB: Storage<N, U3, U1> {
Self::new(axisangle)
}
}
impl<N, S> One for UnitQuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn one() -> Self {
Self::identity()
}
}
impl<N, S> Rand for UnitQuaternionBase<N, S>
where N: Real + Rand,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> +
Allocator<N, U3, U1> {
#[inline]
fn rand<R: Rng>(rng: &mut R) -> Self {
let axisangle = Vector3::rand(rng);
UnitQuaternionBase::from_scaled_axis(axisangle)
}
}
#[cfg(feature="arbitrary")]
impl<N, S> Arbitrary for UnitQuaternionBase<N, S>
where N: Real + Arbitrary,
S: OwnedStorage<N, U4, U1> + Send,
S::Alloc: OwnedAllocator<N, U4, U1, S> +
Allocator<N, U3, U1> {
#[inline]
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let axisangle = Vector3::arbitrary(g);
UnitQuaternionBase::from_scaled_axis(axisangle)
}
}

View File

@ -0,0 +1,212 @@
use num::Zero;
use alga::general::{SubsetOf, SupersetOf, Real};
use alga::linear::Rotation as AlgaRotation;
use core::{ColumnVector, SquareMatrix};
use core::dimension::{U1, U3, U4};
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, QuaternionBase, UnitQuaternionBase, OwnedUnitQuaternionBase, RotationBase,
OwnedRotation, IsometryBase, SimilarityBase, TransformBase, SuperTCategoryOf, TAffine, TranslationBase};
/*
* This file provides the following conversions:
* =============================================
*
* Quaternion -> Quaternion
* UnitQuaternion -> UnitQuaternion
* UnitQuaternion -> RotationBase<U3>
* UnitQuaternion -> IsometryBase<U3>
* UnitQuaternion -> SimilarityBase<U3>
* UnitQuaternion -> TransformBase<U3>
* UnitQuaternion -> Matrix<U4> (homogeneous)
*
* NOTE:
* UnitQuaternion -> Quaternion is already provided by: Unit<T> -> T
*/
impl<N1, N2, SA, SB> SubsetOf<QuaternionBase<N2, SB>> for QuaternionBase<N1, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U4, U1>,
SB: OwnedStorage<N2, U4, U1>,
SA::Alloc: OwnedAllocator<N1, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N2, U4, U1, SB> {
#[inline]
fn to_superset(&self) -> QuaternionBase<N2, SB> {
QuaternionBase::from_vector(self.coords.to_superset())
}
#[inline]
fn is_in_subset(q: &QuaternionBase<N2, SB>) -> bool {
::is_convertible::<_, ColumnVector<N1, U4, SA>>(&q.coords)
}
#[inline]
unsafe fn from_superset_unchecked(q: &QuaternionBase<N2, SB>) -> Self {
Self::from_vector(q.coords.to_subset_unchecked())
}
}
impl<N1, N2, SA, SB> SubsetOf<UnitQuaternionBase<N2, SB>> for UnitQuaternionBase<N1, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U4, U1>,
SB: OwnedStorage<N2, U4, U1>,
SA::Alloc: OwnedAllocator<N1, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N2, U4, U1, SB> {
#[inline]
fn to_superset(&self) -> UnitQuaternionBase<N2, SB> {
UnitQuaternionBase::new_unchecked(self.as_ref().to_superset())
}
#[inline]
fn is_in_subset(uq: &UnitQuaternionBase<N2, SB>) -> bool {
::is_convertible::<_, QuaternionBase<N1, SA>>(uq.as_ref())
}
#[inline]
unsafe fn from_superset_unchecked(uq: &UnitQuaternionBase<N2, SB>) -> Self {
Self::new_unchecked(::convert_ref_unchecked(uq.as_ref()))
}
}
impl<N1, N2, SA, SB> SubsetOf<RotationBase<N2, U3, SB>> for UnitQuaternionBase<N1, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U4, U1>,
SB: OwnedStorage<N2, U3, U3>,
SA::Alloc: OwnedAllocator<N1, U4, U1, SA> +
Allocator<N1, U3, U3>,
SB::Alloc: OwnedAllocator<N2, U3, U3, SB> +
Allocator<N2, U4, U1> +
Allocator<N2, U3, U1> {
#[inline]
fn to_superset(&self) -> RotationBase<N2, U3, SB> {
let q: OwnedUnitQuaternionBase<N2, SB::Alloc> = self.to_superset();
q.to_rotation_matrix()
}
#[inline]
fn is_in_subset(rot: &RotationBase<N2, U3, SB>) -> bool {
::is_convertible::<_, OwnedRotation<N1, U3, SA::Alloc>>(rot)
}
#[inline]
unsafe fn from_superset_unchecked(rot: &RotationBase<N2, U3, SB>) -> Self {
let q = OwnedUnitQuaternionBase::<N2, SB::Alloc>::from_rotation_matrix(rot);
::convert_unchecked(q)
}
}
impl<N1, N2, SA, SB, R> SubsetOf<IsometryBase<N2, U3, SB, R>> for UnitQuaternionBase<N1, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U4, U1>,
SB: OwnedStorage<N2, U3, U1>,
R: AlgaRotation<PointBase<N2, U3, SB>> + SupersetOf<UnitQuaternionBase<N1, SA>>,
SA::Alloc: OwnedAllocator<N1, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N2, U3, U1, SB> {
#[inline]
fn to_superset(&self) -> IsometryBase<N2, U3, SB, R> {
IsometryBase::from_parts(TranslationBase::identity(), ::convert_ref(self))
}
#[inline]
fn is_in_subset(iso: &IsometryBase<N2, U3, SB, R>) -> bool {
iso.translation.vector.is_zero()
}
#[inline]
unsafe fn from_superset_unchecked(iso: &IsometryBase<N2, U3, SB, R>) -> Self {
::convert_ref_unchecked(&iso.rotation)
}
}
impl<N1, N2, SA, SB, R> SubsetOf<SimilarityBase<N2, U3, SB, R>> for UnitQuaternionBase<N1, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U4, U1>,
SB: OwnedStorage<N2, U3, U1>,
R: AlgaRotation<PointBase<N2, U3, SB>> + SupersetOf<UnitQuaternionBase<N1, SA>>,
SA::Alloc: OwnedAllocator<N1, U4, U1, SA>,
SB::Alloc: OwnedAllocator<N2, U3, U1, SB> {
#[inline]
fn to_superset(&self) -> SimilarityBase<N2, U3, SB, R> {
SimilarityBase::from_isometry(::convert_ref(self), N2::one())
}
#[inline]
fn is_in_subset(sim: &SimilarityBase<N2, U3, SB, R>) -> bool {
sim.isometry.translation.vector.is_zero() &&
sim.scaling() == N2::one()
}
#[inline]
unsafe fn from_superset_unchecked(sim: &SimilarityBase<N2, U3, SB, R>) -> Self {
::convert_ref_unchecked(&sim.isometry)
}
}
impl<N1, N2, SA, SB, C> SubsetOf<TransformBase<N2, U3, SB, C>> for UnitQuaternionBase<N1, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U4, U1>,
SB: OwnedStorage<N2, U4, U4>,
C: SuperTCategoryOf<TAffine>,
SA::Alloc: OwnedAllocator<N1, U4, U1, SA> +
Allocator<N1, U3, U3> +
Allocator<N1, U3, U1> +
Allocator<N1, U4, U4>,
SB::Alloc: OwnedAllocator<N2, U4, U4, SB> +
Allocator<N2, U3, U3> +
Allocator<N2, U1, U3> {
#[inline]
fn to_superset(&self) -> TransformBase<N2, U3, SB, C> {
TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset())
}
#[inline]
fn is_in_subset(t: &TransformBase<N2, U3, SB, C>) -> bool {
<Self as SubsetOf<_>>::is_in_subset(t.matrix())
}
#[inline]
unsafe fn from_superset_unchecked(t: &TransformBase<N2, U3, SB, C>) -> Self {
Self::from_superset_unchecked(t.matrix())
}
}
impl<N1, N2, SA, SB> SubsetOf<SquareMatrix<N2, U4, SB>> for UnitQuaternionBase<N1, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U4, U1>,
SB: OwnedStorage<N2, U4, U4>,
SA::Alloc: OwnedAllocator<N1, U4, U1, SA> +
Allocator<N1, U3, U3> +
Allocator<N1, U3, U1> +
Allocator<N1, U4, U4>,
SB::Alloc: OwnedAllocator<N2, U4, U4, SB> +
Allocator<N2, U3, U3> +
Allocator<N2, U1, U3> {
#[inline]
fn to_superset(&self) -> SquareMatrix<N2, U4, SB> {
self.to_homogeneous().to_superset()
}
#[inline]
fn is_in_subset(m: &SquareMatrix<N2, U4, SB>) -> bool {
::is_convertible::<_, OwnedRotation<N1, U3, SA::Alloc>>(m)
}
#[inline]
unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, U4, SB>) -> Self {
let rot: OwnedRotation<N1, U3, SA::Alloc> = ::convert_ref_unchecked(m);
Self::from_rotation_matrix(&rot)
}
}

View File

@ -0,0 +1,34 @@
use std::mem;
use std::ops::{Deref, DerefMut};
use alga::general::Real;
use core::coordinates::IJKW;
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use core::dimension::{U1, U4};
use geometry::QuaternionBase;
impl<N, S> Deref for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
type Target = IJKW<N>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { mem::transmute(self) }
}
}
impl<N, S> DerefMut for QuaternionBase<N, S>
where N: Real,
S: OwnedStorage<N, U4, U1>,
S::Alloc: OwnedAllocator<N, U4, U1, S> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { mem::transmute(self) }
}
}

View File

@ -0,0 +1,729 @@
/*
* This file provides:
* ===================
*
*
* (Quaternion)
*
* Index<usize>
* IndexMut<usize>
* Quaternion × Quaternion
* Quaternion + Quaternion
* Quaternion - Quaternion
* -Quaternion
* Quaternion × Scalar
* Quaternion ÷ Scalar
* Scalar × Quaternion
*
* (Unit Quaternion)
* UnitQuaternion × UnitQuaternion
* UnitQuaternion × RotationBase -> UnitQuaternion
* RotationBase × UnitQuaternion -> UnitQuaternion
*
* UnitQuaternion ÷ UnitQuaternion
* UnitQuaternion ÷ RotationBase -> UnitQuaternion
* RotationBase ÷ UnitQuaternion -> UnitQuaternion
*
*
* UnitQuaternion × PointBase
* UnitQuaternion × ColumnVector
* UnitQuaternion × Unit<ColumnVector>
*
* NOTE: -UnitQuaternion is already provided by `Unit<T>`.
*
*
* (Assignment Operators)
*
* Quaternion ×= Scalar
* Quaternion ×= Quaternion
* Quaternion += Quaternion
* Quaternion -= Quaternion
*
* UnitQuaternion ×= UnitQuaternion
* UnitQuaternion ×= RotationBase
*
* UnitQuaternion ÷= UnitQuaternion
* UnitQuaternion ÷= RotationBase
*
* FIXME: RotationBase ×= UnitQuaternion
* FIXME: RotationBase ÷= UnitQuaternion
*
*/
use std::ops::{Index, IndexMut, Neg, Add, AddAssign, Mul, MulAssign, Div, DivAssign, Sub, SubAssign};
use alga::general::Real;
use core::{ColumnVector, OwnedColumnVector, Unit};
use core::storage::{Storage, StorageMut};
use core::allocator::Allocator;
use core::dimension::{U1, U3, U4};
use geometry::{QuaternionBase, OwnedQuaternionBase, UnitQuaternionBase, OwnedUnitQuaternionBase,
PointBase, OwnedPoint, RotationBase};
impl<N, S> Index<usize> for QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
type Output = N;
#[inline]
fn index(&self, i: usize) -> &N {
&self.coords[i]
}
}
impl<N, S> IndexMut<usize> for QuaternionBase<N, S>
where N: Real,
S: StorageMut<N, U4, U1> {
#[inline]
fn index_mut(&mut self, i: usize) -> &mut N {
&mut self.coords[i]
}
}
macro_rules! quaternion_op_impl(
($Op: ident, $op: ident;
($LhsRDim: ident, $LhsCDim: ident), ($RhsRDim: ident, $RhsCDim: ident);
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty $(=> $VDimA: ty, $VDimB: ty)*;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N, SA, SB> $Op<$Rhs> for $Lhs
where N: Real,
SA: Storage<N, $LhsRDim, $LhsCDim>,
SB: Storage<N, $RhsRDim, $RhsCDim>,
$(SA::Alloc: Allocator<N, $VDimA, U1>,
SB::Alloc: Allocator<N, $VDimB, U1>)* {
type Output = $Result;
#[inline]
fn $op($lhs, $rhs: $Rhs) -> Self::Output {
$action
}
}
}
);
// Quaternion + Quaternion
quaternion_op_impl!(
Add, add;
(U4, U1), (U4, U1);
self: &'a QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
QuaternionBase::from_vector(&self.coords + &rhs.coords);
'a, 'b);
quaternion_op_impl!(
Add, add;
(U4, U1), (U4, U1);
self: &'a QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SB::Alloc>;
QuaternionBase::from_vector(&self.coords + rhs.coords);
'a);
quaternion_op_impl!(
Add, add;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
QuaternionBase::from_vector(self.coords + &rhs.coords);
'b);
quaternion_op_impl!(
Add, add;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
QuaternionBase::from_vector(self.coords + rhs.coords);
);
// Quaternion - Quaternion
quaternion_op_impl!(
Sub, sub;
(U4, U1), (U4, U1);
self: &'a QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
QuaternionBase::from_vector(&self.coords - &rhs.coords);
'a, 'b);
quaternion_op_impl!(
Sub, sub;
(U4, U1), (U4, U1);
self: &'a QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SB::Alloc>;
QuaternionBase::from_vector(&self.coords - rhs.coords);
'a);
quaternion_op_impl!(
Sub, sub;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
QuaternionBase::from_vector(self.coords - &rhs.coords);
'b);
quaternion_op_impl!(
Sub, sub;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
QuaternionBase::from_vector(self.coords - rhs.coords);
);
// Quaternion × Quaternion
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: &'a QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
QuaternionBase::new(
self[3] * rhs[3] - self[0] * rhs[0] - self[1] * rhs[1] - self[2] * rhs[2],
self[3] * rhs[0] + self[0] * rhs[3] + self[1] * rhs[2] - self[2] * rhs[1],
self[3] * rhs[1] - self[0] * rhs[2] + self[1] * rhs[3] + self[2] * rhs[0],
self[3] * rhs[2] + self[0] * rhs[1] - self[1] * rhs[0] + self[2] * rhs[3]);
'a, 'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: &'a QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
self * &rhs;
'a);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
&self * rhs;
'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>, Output = OwnedQuaternionBase<N, SA::Alloc>;
&self * &rhs;
);
// UnitQuaternion × UnitQuaternion
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: &'b UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
UnitQuaternionBase::new_unchecked(self.quaternion() * rhs.quaternion());
'a, 'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
self * &rhs;
'a);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: &'b UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
&self * rhs;
'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
&self * &rhs;
);
// UnitQuaternion ÷ UnitQuaternion
quaternion_op_impl!(
Div, div;
(U4, U1), (U4, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: &'b UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
self * rhs.inverse();
'a, 'b);
quaternion_op_impl!(
Div, div;
(U4, U1), (U4, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
self / &rhs;
'a);
quaternion_op_impl!(
Div, div;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: &'b UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
&self / rhs;
'b);
quaternion_op_impl!(
Div, div;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: UnitQuaternionBase<N, SB>, Output = OwnedUnitQuaternionBase<N, SA::Alloc>;
&self / &rhs;
);
// UnitQuaternion × RotationBase
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U3);
self: &'a UnitQuaternionBase<N, SA>, rhs: &'b RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
// FIXME: can we avoid the conversion from a rotation matrix?
self * OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(rhs);
'a, 'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U3);
self: &'a UnitQuaternionBase<N, SA>, rhs: RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
self * OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(&rhs);
'a);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: &'b RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
self * OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(rhs);
'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
self * OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(&rhs);
);
// UnitQuaternion ÷ RotationBase
quaternion_op_impl!(
Div, div;
(U4, U1), (U3, U3);
self: &'a UnitQuaternionBase<N, SA>, rhs: &'b RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
// FIXME: can we avoid the conversion to a rotation matrix?
self / OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(rhs);
'a, 'b);
quaternion_op_impl!(
Div, div;
(U4, U1), (U3, U3);
self: &'a UnitQuaternionBase<N, SA>, rhs: RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
self / OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(&rhs);
'a);
quaternion_op_impl!(
Div, div;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: &'b RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
self / OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(rhs);
'b);
quaternion_op_impl!(
Div, div;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: RotationBase<N, U3, SB>,
Output = OwnedUnitQuaternionBase<N, SA::Alloc> => U3, U3;
self / OwnedUnitQuaternionBase::<N, SA::Alloc>::from_rotation_matrix(&rhs);
);
// RotationBase × UnitQuaternion
quaternion_op_impl!(
Mul, mul;
(U3, U3), (U4, U1);
self: &'a RotationBase<N, U3, SA>, rhs: &'b UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
// FIXME: can we avoid the conversion from a rotation matrix?
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(self) * rhs;
'a, 'b);
quaternion_op_impl!(
Mul, mul;
(U3, U3), (U4, U1);
self: &'a RotationBase<N, U3, SA>, rhs: UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(self) * rhs;
'a);
quaternion_op_impl!(
Mul, mul;
(U3, U3), (U4, U1);
self: RotationBase<N, U3, SA>, rhs: &'b UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(&self) * rhs;
'b);
quaternion_op_impl!(
Mul, mul;
(U3, U3), (U4, U1);
self: RotationBase<N, U3, SA>, rhs: UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(&self) * rhs;
);
// RotationBase ÷ UnitQuaternion
quaternion_op_impl!(
Div, div;
(U3, U3), (U4, U1);
self: &'a RotationBase<N, U3, SA>, rhs: &'b UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
// FIXME: can we avoid the conversion from a rotation matrix?
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(self) / rhs;
'a, 'b);
quaternion_op_impl!(
Div, div;
(U3, U3), (U4, U1);
self: &'a RotationBase<N, U3, SA>, rhs: UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(self) / rhs;
'a);
quaternion_op_impl!(
Div, div;
(U3, U3), (U4, U1);
self: RotationBase<N, U3, SA>, rhs: &'b UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(&self) / rhs;
'b);
quaternion_op_impl!(
Div, div;
(U3, U3), (U4, U1);
self: RotationBase<N, U3, SA>, rhs: UnitQuaternionBase<N, SB>,
Output = OwnedUnitQuaternionBase<N, SB::Alloc> => U3, U3;
OwnedUnitQuaternionBase::<N, SB::Alloc>::from_rotation_matrix(&self) / rhs;
);
// UnitQuaternion × Vector
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: &'b ColumnVector<N, U3, SB>,
Output = OwnedColumnVector<N, U3, SA::Alloc> => U3, U4;
{
let two: N = ::convert(2.0f64);
let t = self.as_ref().vector().cross(rhs) * two;
let cross = self.as_ref().vector().cross(&t);
t * self.as_ref().scalar() + cross + rhs
};
'a, 'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: ColumnVector<N, U3, SB>,
Output = OwnedColumnVector<N, U3, SA::Alloc> => U3, U4;
self * &rhs;
'a);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, rhs: &'b ColumnVector<N, U3, SB>,
Output = OwnedColumnVector<N, U3, SA::Alloc> => U3, U4;
&self * rhs;
'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, rhs: ColumnVector<N, U3, SB>,
Output = OwnedColumnVector<N, U3, SA::Alloc> => U3, U4;
&self * &rhs;
);
// UnitQuaternion × PointBase
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: &'b PointBase<N, U3, SB>,
Output = OwnedPoint<N, U3, SA::Alloc> => U3, U4;
PointBase::from_coordinates(self * &rhs.coords);
'a, 'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: PointBase<N, U3, SB>,
Output = OwnedPoint<N, U3, SA::Alloc> => U3, U4;
PointBase::from_coordinates(self * rhs.coords);
'a);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, rhs: &'b PointBase<N, U3, SB>,
Output = OwnedPoint<N, U3, SA::Alloc> => U3, U4;
PointBase::from_coordinates(self * &rhs.coords);
'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, rhs: PointBase<N, U3, SB>,
Output = OwnedPoint<N, U3, SA::Alloc> => U3, U4;
PointBase::from_coordinates(self * rhs.coords);
);
// UnitQuaternion × Unit<Vector>
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: &'b Unit<ColumnVector<N, U3, SB>>,
Output = Unit<OwnedColumnVector<N, U3, SA::Alloc>> => U3, U4;
Unit::new_unchecked(self * rhs.as_ref());
'a, 'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: &'a UnitQuaternionBase<N, SA>, rhs: Unit<ColumnVector<N, U3, SB>>,
Output = Unit<OwnedColumnVector<N, U3, SA::Alloc>> => U3, U4;
Unit::new_unchecked(self * rhs.unwrap());
'a);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, rhs: &'b Unit<ColumnVector<N, U3, SB>>,
Output = Unit<OwnedColumnVector<N, U3, SA::Alloc>> => U3, U4;
Unit::new_unchecked(self * rhs.as_ref());
'b);
quaternion_op_impl!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, rhs: Unit<ColumnVector<N, U3, SB>>,
Output = Unit<OwnedColumnVector<N, U3, SA::Alloc>> => U3, U4;
Unit::new_unchecked(self * rhs.unwrap());
);
macro_rules! scalar_op_impl(
($($Op: ident, $op: ident, $OpAssign: ident, $op_assign: ident);* $(;)*) => {$(
impl<N, S> $Op<N> for QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
type Output = OwnedQuaternionBase<N, S::Alloc>;
#[inline]
fn $op(self, n: N) -> Self::Output {
QuaternionBase::from_vector(self.coords.$op(n))
}
}
impl<'a, N, S> $Op<N> for &'a QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
type Output = OwnedQuaternionBase<N, S::Alloc>;
#[inline]
fn $op(self, n: N) -> Self::Output {
QuaternionBase::from_vector((&self.coords).$op(n))
}
}
impl<N, S> $OpAssign<N> for QuaternionBase<N, S>
where N: Real,
S: StorageMut<N, U4, U1> {
#[inline]
fn $op_assign(&mut self, n: N) {
self.coords.$op_assign(n)
}
}
)*}
);
scalar_op_impl!(
Mul, mul, MulAssign, mul_assign;
Div, div, DivAssign, div_assign;
);
macro_rules! left_scalar_mul_impl(
($($T: ty),* $(,)*) => {$(
impl<S> Mul<QuaternionBase<$T, S>> for $T
where S: Storage<$T, U4, U1> {
type Output = OwnedQuaternionBase<$T, S::Alloc>;
#[inline]
fn mul(self, right: QuaternionBase<$T, S>) -> Self::Output {
QuaternionBase::from_vector(self * right.coords)
}
}
impl<'b, S> Mul<&'b QuaternionBase<$T, S>> for $T
where S: Storage<$T, U4, U1> {
type Output = OwnedQuaternionBase<$T, S::Alloc>;
#[inline]
fn mul(self, right: &'b QuaternionBase<$T, S>) -> Self::Output {
QuaternionBase::from_vector(self * &right.coords)
}
}
)*}
);
left_scalar_mul_impl!(f32, f64);
impl<N, S> Neg for QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
type Output = OwnedQuaternionBase<N, S::Alloc>;
#[inline]
fn neg(self) -> Self::Output {
QuaternionBase::from_vector(-self.coords)
}
}
impl<'a, N, S> Neg for &'a QuaternionBase<N, S>
where N: Real,
S: Storage<N, U4, U1> {
type Output = OwnedQuaternionBase<N, S::Alloc>;
#[inline]
fn neg(self) -> Self::Output {
QuaternionBase::from_vector(-&self.coords)
}
}
macro_rules! quaternion_op_impl(
($OpAssign: ident, $op_assign: ident;
($LhsRDim: ident, $LhsCDim: ident), ($RhsRDim: ident, $RhsCDim: ident);
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty $(=> $VDimA: ty, $VDimB: ty)*;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N, SA, SB> $OpAssign<$Rhs> for $Lhs
where N: Real,
SA: StorageMut<N, $LhsRDim, $LhsCDim>,
SB: Storage<N, $RhsRDim, $RhsCDim>,
$(SA::Alloc: Allocator<N, $VDimA, U1> + Allocator<N, U4, U1>,
// ^^^^^^^^^^^^^^^^^^^^
// XXX: For some reasons, the compiler needs
// this bound to compile UnitQuat *= RotationBase.
// Though in theory this bound is already
// inherited from `SA: StorageMut`…
SB::Alloc: Allocator<N, $VDimB, U1>)* {
#[inline]
fn $op_assign(&mut $lhs, $rhs: $Rhs) {
$action
}
}
}
);
// Quaternion += Quaternion
quaternion_op_impl!(
AddAssign, add_assign;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>;
self.coords += &rhs.coords;
'b);
quaternion_op_impl!(
AddAssign, add_assign;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>;
self.coords += rhs.coords; );
// Quaternion -= Quaternion
quaternion_op_impl!(
SubAssign, sub_assign;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>;
self.coords -= &rhs.coords;
'b);
quaternion_op_impl!(
SubAssign, sub_assign;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>;
self.coords -= rhs.coords; );
// Quaternion ×= Quaternion
quaternion_op_impl!(
MulAssign, mul_assign;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: &'b QuaternionBase<N, SB>;
{
let res = &*self * rhs;
// FIXME: will this be optimized away?
self.coords.copy_from(&res.coords);
};
'b);
quaternion_op_impl!(
MulAssign, mul_assign;
(U4, U1), (U4, U1);
self: QuaternionBase<N, SA>, rhs: QuaternionBase<N, SB>;
*self *= &rhs; );
// UnitQuaternion ×= UnitQuaternion
quaternion_op_impl!(
MulAssign, mul_assign;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: &'b UnitQuaternionBase<N, SB>;
{
let res = &*self * rhs;
self.as_mut_unchecked().coords.copy_from(&res.as_ref().coords);
};
'b);
quaternion_op_impl!(
MulAssign, mul_assign;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: UnitQuaternionBase<N, SB>;
*self *= &rhs; );
// UnitQuaternion ÷= UnitQuaternion
quaternion_op_impl!(
DivAssign, div_assign;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: &'b UnitQuaternionBase<N, SB>;
{
let res = &*self / rhs;
self.as_mut_unchecked().coords.copy_from(&res.as_ref().coords);
};
'b);
quaternion_op_impl!(
DivAssign, div_assign;
(U4, U1), (U4, U1);
self: UnitQuaternionBase<N, SA>, rhs: UnitQuaternionBase<N, SB>;
*self /= &rhs; );
// UnitQuaternion ×= RotationBase
quaternion_op_impl!(
MulAssign, mul_assign;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: &'b RotationBase<N, U3, SB> => U3, U3;
{
let res = &*self * rhs;
self.as_mut_unchecked().coords.copy_from(&res.as_ref().coords);
};
'b);
quaternion_op_impl!(
MulAssign, mul_assign;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: RotationBase<N, U3, SB> => U3, U3;
*self *= &rhs; );
// UnitQuaternion ÷= RotationBase
quaternion_op_impl!(
DivAssign, div_assign;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: &'b RotationBase<N, U3, SB> => U3, U3;
{
let res = &*self / rhs;
self.as_mut_unchecked().coords.copy_from(&res.as_ref().coords);
};
'b);
quaternion_op_impl!(
DivAssign, div_assign;
(U4, U1), (U3, U3);
self: UnitQuaternionBase<N, SA>, rhs: RotationBase<N, U3, SB> => U3, U3;
*self /= &rhs; );

174
src/geometry/rotation.rs Normal file
View File

@ -0,0 +1,174 @@
use num::{Zero, One};
use std::fmt;
use approx::ApproxEq;
use alga::general::Real;
use core::{SquareMatrix, Scalar, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::{Storage, StorageMut};
use core::allocator::Allocator;
/// A rotation matrix with an owned storage.
pub type OwnedRotation<N, D, A> = RotationBase<N, D, <A as Allocator<N, D, D>>::Buffer>;
/// A rotation matrix.
#[repr(C)]
#[derive(Hash, Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct RotationBase<N: Scalar, D: DimName, S> {
matrix: SquareMatrix<N, D, S>
}
impl<N: Scalar, D: DimName, S: Storage<N, D, D>> RotationBase<N, D, S>
where N: Scalar,
S: Storage<N, D, D> {
/// A reference to the underlying matrix representation of this rotation.
#[inline]
pub fn matrix(&self) -> &SquareMatrix<N, D, S> {
&self.matrix
}
/// A mutable reference to the underlying matrix representation of this rotation.
///
/// This is unsafe because this allows the user to replace the matrix by another one that is
/// non-square, non-inversible, or non-orthonormal. If one of those properties is broken,
/// subsequent method calls may be UB.
#[inline]
pub unsafe fn matrix_mut(&mut self) -> &mut SquareMatrix<N, D, S> {
&mut self.matrix
}
/// Unwraps the underlying matrix.
#[inline]
pub fn unwrap(self) -> SquareMatrix<N, D, S> {
self.matrix
}
/// Converts this rotation into its equivalent homogeneous transformation matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>
where N: Zero + One,
D: DimNameAdd<U1>,
S::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
let mut res = OwnedSquareMatrix::<N, _, S::Alloc>::identity();
res.fixed_slice_mut::<D, D>(0, 0).copy_from(&self.matrix);
res
}
}
impl<N: Scalar, D: DimName, S: Storage<N, D, D>> RotationBase<N, D, S> {
/// Creates a new rotation from the given square matrix.
///
/// The matrix squareness is checked but not its orthonormality.
#[inline]
pub fn from_matrix_unchecked(matrix: SquareMatrix<N, D, S>) -> RotationBase<N, D, S> {
assert!(matrix.is_square(), "Unable to create a rotation from a non-square matrix.");
RotationBase {
matrix: matrix
}
}
/// Transposes `self`.
#[inline]
pub fn transpose(&self) -> OwnedRotation<N, D, S::Alloc> {
RotationBase::from_matrix_unchecked(self.matrix.transpose())
}
/// Inverts `self`.
#[inline]
pub fn inverse(&self) -> OwnedRotation<N, D, S::Alloc> {
self.transpose()
}
}
impl<N: Scalar, D: DimName, S: StorageMut<N, D, D>> RotationBase<N, D, S> {
/// Transposes `self` in-place.
#[inline]
pub fn transpose_mut(&mut self) {
self.matrix.transpose_mut()
}
/// Inverts `self` in-place.
#[inline]
pub fn inverse_mut(&mut self) {
self.transpose_mut()
}
}
impl<N: Scalar + Eq, D: DimName, S: Storage<N, D, D>> Eq for RotationBase<N, D, S> { }
impl<N: Scalar + PartialEq, D: DimName, S: Storage<N, D, D>> PartialEq for RotationBase<N, D, S> {
#[inline]
fn eq(&self, right: &RotationBase<N, D, S>) -> bool {
self.matrix == right.matrix
}
}
impl<N, D: DimName, S> ApproxEq for RotationBase<N, D, S>
where N: Scalar + ApproxEq,
S: Storage<N, D, D>,
N::Epsilon: Copy {
type Epsilon = N::Epsilon;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.matrix.relative_eq(&other.matrix, epsilon, max_relative)
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.matrix.ulps_eq(&other.matrix, epsilon, max_ulps)
}
}
/*
*
* Display
*
*/
impl<N, D: DimName, S> fmt::Display for RotationBase<N, D, S>
where N: Real + fmt::Display,
S: Storage<N, D, D>,
S::Alloc: Allocator<usize, D, D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let precision = f.precision().unwrap_or(3);
try!(writeln!(f, "RotationBase matrix {{"));
try!(write!(f, "{:.*}", precision, self.matrix));
writeln!(f, "}}")
}
}
// // /*
// // *
// // * Absolute
// // *
// // */
// // impl<N: Absolute> Absolute for $t<N> {
// // type AbsoluteValue = $submatrix<N::AbsoluteValue>;
// //
// // #[inline]
// // fn abs(m: &$t<N>) -> $submatrix<N::AbsoluteValue> {
// // Absolute::abs(&m.submatrix)
// // }
// // }

View File

@ -0,0 +1,301 @@
use alga::general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
AbstractSemigroup, Real, Inverse, Multiplicative, Identity, Id};
use alga::linear::{Transformation, Similarity, AffineTransformation, Isometry, DirectIsometry,
OrthogonalTransformation, ProjectiveTransformation, Rotation};
use core::ColumnVector;
use core::dimension::{DimName, U1};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{RotationBase, PointBase};
/*
*
* Algebraic structures.
*
*/
impl<N, D: DimName, S> Identity<Multiplicative> for RotationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S> Inverse<Multiplicative> for RotationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
#[inline]
fn inverse(&self) -> Self {
self.transpose()
}
#[inline]
fn inverse_mut(&mut self) {
self.transpose_mut()
}
}
impl<N, D: DimName, S> AbstractMagma<Multiplicative> for RotationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
macro_rules! impl_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimName, S> $marker<$operator> for RotationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> { }
)*}
);
impl_multiplicative_structures!(
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
AbstractQuasigroup<Multiplicative>,
AbstractLoop<Multiplicative>,
AbstractGroup<Multiplicative>
);
/*
*
* Transformation groups.
*
*/
impl<N, D: DimName, SA, SB> Transformation<PointBase<N, D, SB>> for RotationBase<N, D, SA>
where N: Real,
SA: OwnedStorage<N, D, D>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, D, D, SA>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
#[inline]
fn transform_point(&self, pt: &PointBase<N, D, SB>) -> PointBase<N, D, SB> {
self * pt
}
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, D, SB>) -> ColumnVector<N, D, SB> {
self * v
}
}
impl<N, D: DimName, SA, SB> ProjectiveTransformation<PointBase<N, D, SB>> for RotationBase<N, D, SA>
where N: Real,
SA: OwnedStorage<N, D, D>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, D, D, SA>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
#[inline]
fn inverse_transform_point(&self, pt: &PointBase<N, D, SB>) -> PointBase<N, D, SB> {
PointBase::from_coordinates(self.inverse_transform_vector(&pt.coords))
}
#[inline]
fn inverse_transform_vector(&self, v: &ColumnVector<N, D, SB>) -> ColumnVector<N, D, SB> {
self.matrix().tr_mul(v)
}
}
impl<N, D: DimName, SA, SB> AffineTransformation<PointBase<N, D, SB>> for RotationBase<N, D, SA>
where N: Real,
SA: OwnedStorage<N, D, D>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, D, D, SA>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
type Rotation = Self;
type NonUniformScaling = Id;
type Translation = Id;
#[inline]
fn decompose(&self) -> (Id, Self, Id, Self) {
(Id::new(), self.clone(), Id::new(), Self::identity())
}
#[inline]
fn append_translation(&self, _: &Self::Translation) -> Self {
self.clone()
}
#[inline]
fn prepend_translation(&self, _: &Self::Translation) -> Self {
self.clone()
}
#[inline]
fn append_rotation(&self, r: &Self::Rotation) -> Self {
r * self
}
#[inline]
fn prepend_rotation(&self, r: &Self::Rotation) -> Self {
self * r
}
#[inline]
fn append_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
#[inline]
fn prepend_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
}
impl<N, D: DimName, SA, SB> Similarity<PointBase<N, D, SB>> for RotationBase<N, D, SA>
where N: Real,
SA: OwnedStorage<N, D, D>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, D, D, SA>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
type Scaling = Id;
#[inline]
fn translation(&self) -> Id {
Id::new()
}
#[inline]
fn rotation(&self) -> Self {
self.clone()
}
#[inline]
fn scaling(&self) -> Id {
Id::new()
}
}
macro_rules! marker_impl(
($($Trait: ident),*) => {$(
impl<N, D: DimName, SA, SB> $Trait<PointBase<N, D, SB>> for RotationBase<N, D, SA>
where N: Real,
SA: OwnedStorage<N, D, D>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, D, D, SA>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> { }
)*}
);
marker_impl!(Isometry, DirectIsometry, OrthogonalTransformation);
/// Subgroups of the n-dimensional rotation group `SO(n)`.
impl<N, D: DimName, SA, SB> Rotation<PointBase<N, D, SB>> for RotationBase<N, D, SA>
where N: Real,
SA: OwnedStorage<N, D, D>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, D, D, SA>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
#[inline]
fn powf(&self, _: N) -> Option<Self> {
// XXX: Add the general case.
// XXX: Use specialization for 2D and 3D.
unimplemented!()
}
#[inline]
fn rotation_between(_: &ColumnVector<N, D, SB>, _: &ColumnVector<N, D, SB>) -> Option<Self> {
// XXX: Add the general case.
// XXX: Use specialization for 2D and 3D.
unimplemented!()
}
#[inline]
fn scaled_rotation_between(_: &ColumnVector<N, D, SB>, _: &ColumnVector<N, D, SB>, _: N) -> Option<Self> {
// XXX: Add the general case.
// XXX: Use specialization for 2D and 3D.
unimplemented!()
}
}
/*
impl<N: Real> Matrix for RotationBase<N> {
type Field = N;
type Row = Matrix<N>;
type Column = Matrix<N>;
type Transpose = Self;
#[inline]
fn nrows(&self) -> usize {
self.submatrix.nrows()
}
#[inline]
fn ncolumns(&self) -> usize {
self.submatrix.ncolumns()
}
#[inline]
fn row(&self, i: usize) -> Self::Row {
self.submatrix.row(i)
}
#[inline]
fn column(&self, i: usize) -> Self::Column {
self.submatrix.column(i)
}
#[inline]
fn get(&self, i: usize, j: usize) -> Self::Field {
self.submatrix[(i, j)]
}
#[inline]
unsafe fn get_unchecked(&self, i: usize, j: usize) -> Self::Field {
self.submatrix.at_fast(i, j)
}
#[inline]
fn transpose(&self) -> Self::Transpose {
RotationBase::from_matrix_unchecked(self.submatrix.transpose())
}
}
impl<N: Real> SquareMatrix for RotationBase<N> {
type Vector = Matrix<N>;
#[inline]
fn diagonal(&self) -> Self::Coordinates {
self.submatrix.diagonal()
}
#[inline]
fn determinant(&self) -> Self::Field {
::one()
}
#[inline]
fn try_inverse(&self) -> Option<Self> {
Some(::transpose(self))
}
#[inline]
fn try_inverse_mut(&mut self) -> bool {
self.transpose_mut();
true
}
#[inline]
fn transpose_mut(&mut self) {
self.submatrix.transpose_mut()
}
}
impl<N: Real> InversibleSquareMatrix for RotationBase<N> { }
*/

View File

@ -0,0 +1,13 @@
use core::MatrixArray;
use core::dimension::{U2, U3};
use geometry::RotationBase;
/// A D-dimensional rotation matrix.
pub type Rotation<N, D> = RotationBase<N, D, MatrixArray<N, D, D>>;
/// A 2-dimensional rotation matrix.
pub type Rotation2<N> = Rotation<N, U2>;
/// A 3-dimensional rotation matrix.
pub type Rotation3<N> = Rotation<N, U3>;

View File

@ -0,0 +1,31 @@
use num::{Zero, One};
use alga::general::{ClosedAdd, ClosedMul};
use core::{SquareMatrix, Scalar};
use core::dimension::DimName;
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::RotationBase;
impl<N, D: DimName, S> RotationBase<N, D, S>
where N: Scalar + Zero + One,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
/// Creates a new square identity rotation of the given `dimension`.
#[inline]
pub fn identity() -> RotationBase<N, D, S> {
Self::from_matrix_unchecked(SquareMatrix::<N, D, S>::identity())
}
}
impl<N, D: DimName, S> One for RotationBase<N, D, S>
where N: Scalar + Zero + One + ClosedAdd + ClosedMul,
S: OwnedStorage<N, D, D>,
S::Alloc: OwnedAllocator<N, D, D, S> {
#[inline]
fn one() -> Self {
Self::identity()
}
}

View File

@ -0,0 +1,195 @@
use num::Zero;
use alga::general::{Real, SubsetOf, SupersetOf};
use alga::linear::Rotation as AlgaRotation;
use core::{Matrix, SquareMatrix};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1, U3, U4};
use core::storage::OwnedStorage;
use core::allocator::{OwnedAllocator, Allocator};
use geometry::{PointBase, TranslationBase, RotationBase, UnitQuaternionBase, OwnedUnitQuaternionBase, IsometryBase,
SimilarityBase, TransformBase, SuperTCategoryOf, TAffine};
/*
* This file provides the following conversions:
* =============================================
*
* RotationBase -> RotationBase
* Rotation3 -> UnitQuaternion
* RotationBase -> IsometryBase
* RotationBase -> SimilarityBase
* RotationBase -> TransformBase
* RotationBase -> Matrix (homogeneous)
*/
impl<N1, N2, D: DimName, SA, SB> SubsetOf<RotationBase<N2, D, SB>> for RotationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, D>,
SB: OwnedStorage<N2, D, D>,
SA::Alloc: OwnedAllocator<N1, D, D, SA>,
SB::Alloc: OwnedAllocator<N2, D, D, SB> {
#[inline]
fn to_superset(&self) -> RotationBase<N2, D, SB> {
RotationBase::from_matrix_unchecked(self.matrix().to_superset())
}
#[inline]
fn is_in_subset(rot: &RotationBase<N2, D, SB>) -> bool {
::is_convertible::<_, Matrix<N1, D, D, SA>>(rot.matrix())
}
#[inline]
unsafe fn from_superset_unchecked(rot: &RotationBase<N2, D, SB>) -> Self {
RotationBase::from_matrix_unchecked(rot.matrix().to_subset_unchecked())
}
}
impl<N1, N2, SA, SB> SubsetOf<UnitQuaternionBase<N2, SB>> for RotationBase<N1, U3, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, U3, U3>,
SB: OwnedStorage<N2, U4, U1>,
SA::Alloc: OwnedAllocator<N1, U3, U3, SA> +
Allocator<N1, U4, U1> +
Allocator<N1, U3, U1>,
SB::Alloc: OwnedAllocator<N2, U4, U1, SB> +
Allocator<N2, U3, U3> {
#[inline]
fn to_superset(&self) -> UnitQuaternionBase<N2, SB> {
let q = OwnedUnitQuaternionBase::<N1, SA::Alloc>::from_rotation_matrix(self);
q.to_superset()
}
#[inline]
fn is_in_subset(q: &UnitQuaternionBase<N2, SB>) -> bool {
::is_convertible::<_, OwnedUnitQuaternionBase<N1, SA::Alloc>>(q)
}
#[inline]
unsafe fn from_superset_unchecked(q: &UnitQuaternionBase<N2, SB>) -> Self {
let q: OwnedUnitQuaternionBase<N1, SA::Alloc> = ::convert_ref_unchecked(q);
q.to_rotation_matrix()
}
}
impl<N1, N2, D: DimName, SA, SB, R> SubsetOf<IsometryBase<N2, D, SB, R>> for RotationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, D>,
SB: OwnedStorage<N2, D, U1>,
R: AlgaRotation<PointBase<N2, D, SB>> + SupersetOf<RotationBase<N1, D, SA>>,
SA::Alloc: OwnedAllocator<N1, D, D, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> IsometryBase<N2, D, SB, R> {
IsometryBase::from_parts(TranslationBase::identity(), ::convert_ref(self))
}
#[inline]
fn is_in_subset(iso: &IsometryBase<N2, D, SB, R>) -> bool {
iso.translation.vector.is_zero()
}
#[inline]
unsafe fn from_superset_unchecked(iso: &IsometryBase<N2, D, SB, R>) -> Self {
::convert_ref_unchecked(&iso.rotation)
}
}
impl<N1, N2, D: DimName, SA, SB, R> SubsetOf<SimilarityBase<N2, D, SB, R>> for RotationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, D>,
SB: OwnedStorage<N2, D, U1>,
R: AlgaRotation<PointBase<N2, D, SB>> + SupersetOf<RotationBase<N1, D, SA>>,
SA::Alloc: OwnedAllocator<N1, D, D, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> SimilarityBase<N2, D, SB, R> {
SimilarityBase::from_parts(TranslationBase::identity(), ::convert_ref(self), N2::one())
}
#[inline]
fn is_in_subset(sim: &SimilarityBase<N2, D, SB, R>) -> bool {
sim.isometry.translation.vector.is_zero() &&
sim.scaling() == N2::one()
}
#[inline]
unsafe fn from_superset_unchecked(sim: &SimilarityBase<N2, D, SB, R>) -> Self {
::convert_ref_unchecked(&sim.isometry.rotation)
}
}
impl<N1, N2, D, SA, SB, C> SubsetOf<TransformBase<N2, D, SB, C>> for RotationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, D>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SuperTCategoryOf<TAffine>,
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, D, SA> +
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, D> +
Allocator<N2, U1, D> {
#[inline]
fn to_superset(&self) -> TransformBase<N2, D, SB, C> {
TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset())
}
#[inline]
fn is_in_subset(t: &TransformBase<N2, D, SB, C>) -> bool {
<Self as SubsetOf<_>>::is_in_subset(t.matrix())
}
#[inline]
unsafe fn from_superset_unchecked(t: &TransformBase<N2, D, SB, C>) -> Self {
Self::from_superset_unchecked(t.matrix())
}
}
impl<N1, N2, D, SA, SB> SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>> for RotationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, D>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, D, SA> +
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, D> +
Allocator<N2, U1, D> {
#[inline]
fn to_superset(&self) -> SquareMatrix<N2, DimNameSum<D, U1>, SB> {
self.to_homogeneous().to_superset()
}
#[inline]
fn is_in_subset(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> bool {
let rot = m.fixed_slice::<D, D>(0, 0);
let bottom = m.fixed_slice::<U1, D>(D::dim(), 0);
// Scalar types agree.
m.iter().all(|e| SupersetOf::<N1>::is_in_subset(e)) &&
// The block part is a rotation.
rot.is_special_orthogonal(N2::default_epsilon() * ::convert(100.0)) &&
// The bottom row is (0, 0, ..., 1)
bottom.iter().all(|e| e.is_zero()) &&
m[(D::dim(), D::dim())] == N2::one()
}
#[inline]
unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> Self {
let r = m.fixed_slice::<D, D>(0, 0);
Self::from_matrix_unchecked(::convert_unchecked(r.into_owned()))
}
}

View File

@ -0,0 +1,162 @@
/*
*
* This provides the following operator overladings:
*
* Index<(usize, usize)>
*
* RotationBase × RotationBase
* RotationBase ÷ RotationBase
* RotationBase × Matrix
* Matrix × RotationBase
* Matrix ÷ RotationBase
* RotationBase × PointBase
*
*
* RotationBase ×= RotationBase
* Matrix ×= RotationBase
*/
use std::ops::{Mul, MulAssign, Div, DivAssign, Index};
use num::Zero;
use alga::general::{ClosedMul, ClosedAdd};
use core::{Scalar, Matrix, MatrixMul};
use core::dimension::{Dim, DimName, U1};
use core::constraint::{ShapeConstraint, AreMultipliable};
use core::storage::{OwnedStorage, Storage};
use core::allocator::{OwnedAllocator, Allocator};
use geometry::{PointBase, PointMul, RotationBase, OwnedRotation};
impl<N: Scalar, D: DimName, S: Storage<N, D, D>> Index<(usize, usize)> for RotationBase<N, D, S> {
type Output = N;
#[inline]
fn index(&self, row_col: (usize, usize)) -> &N {
self.matrix().index(row_col)
}
}
// RotationBase × RotationBase
md_impl_all!(
Mul, mul;
(D, D), (D, D) for D: DimName;
self: RotationBase<N, D, SA>, right: RotationBase<N, D, SB>, Output = OwnedRotation<N, D, SA::Alloc>;
[val val] => RotationBase::from_matrix_unchecked(self.unwrap() * right.unwrap());
[ref val] => RotationBase::from_matrix_unchecked(self.matrix() * right.unwrap());
[val ref] => RotationBase::from_matrix_unchecked(self.unwrap() * right.matrix());
[ref ref] => RotationBase::from_matrix_unchecked(self.matrix() * right.matrix());
);
// RotationBase ÷ RotationBase
// FIXME: instead of calling inverse explicitely, could we just add a `mul_tr` or `mul_inv` method?
md_impl_all!(
Div, div;
(D, D), (D, D) for D: DimName;
self: RotationBase<N, D, SA>, right: RotationBase<N, D, SB>, Output = OwnedRotation<N, D, SA::Alloc>;
[val val] => self * right.inverse();
[ref val] => self * right.inverse();
[val ref] => self * right.inverse();
[ref ref] => self * right.inverse();
);
// RotationBase × Matrix
md_impl_all!(
Mul, mul;
(D1, D1), (R2, C2) for D1: DimName, R2: Dim, C2: Dim
where SA::Alloc: Allocator<N, D1, C2>
where ShapeConstraint: AreMultipliable<D1, D1, R2, C2>;
self: RotationBase<N, D1, SA>, right: Matrix<N, R2, C2, SB>, Output = MatrixMul<N, D1, D1, C2 , SA>;
[val val] => self.unwrap() * right;
[ref val] => self.matrix() * right;
[val ref] => self.unwrap() * right;
[ref ref] => self.matrix() * right;
);
// Matrix × RotationBase
md_impl_all!(
Mul, mul;
(R1, C1), (D2, D2) for R1: Dim, C1: Dim, D2: DimName
where SA::Alloc: Allocator<N, R1, D2>
where ShapeConstraint: AreMultipliable<R1, C1, D2, D2>;
self: Matrix<N, R1, C1, SA>, right: RotationBase<N, D2, SB>, Output = MatrixMul<N, R1, C1, D2, SA>;
[val val] => self * right.unwrap();
[ref val] => self * right.unwrap();
[val ref] => self * right.matrix();
[ref ref] => self * right.matrix();
);
// Matrix ÷ RotationBase
md_impl_all!(
Div, div;
(R1, C1), (D2, D2) for R1: Dim, C1: Dim, D2: DimName
where SA::Alloc: Allocator<N, R1, D2>
where ShapeConstraint: AreMultipliable<R1, C1, D2, D2>;
self: Matrix<N, R1, C1, SA>, right: RotationBase<N, D2, SB>, Output = MatrixMul<N, R1, C1, D2, SA>;
[val val] => self * right.inverse();
[ref val] => self * right.inverse();
[val ref] => self * right.inverse();
[ref ref] => self * right.inverse();
);
// RotationBase × PointBase
// FIXME: we don't handle properly non-zero origins here. Do we want this to be the intended
// behavior?
md_impl_all!(
Mul, mul;
(D, D), (D, U1) for D: DimName
where SA::Alloc: Allocator<N, D, U1>
where ShapeConstraint: AreMultipliable<D, D, D, U1>;
self: RotationBase<N, D, SA>, right: PointBase<N, D, SB>, Output = PointMul<N, D, D, SA>;
[val val] => self.unwrap() * right;
[ref val] => self.matrix() * right;
[val ref] => self.unwrap() * right;
[ref ref] => self.matrix() * right;
);
// RotationBase ×= RotationBase
// FIXME: try not to call `inverse()` explicitly.
md_assign_impl_all!(
MulAssign, mul_assign;
(D, D), (D, D) for D: DimName;
self: RotationBase<N, D, SA>, right: RotationBase<N, D, SB>;
[val] => unsafe { self.matrix_mut().mul_assign(right.unwrap()) };
[ref] => unsafe { self.matrix_mut().mul_assign(right.matrix()) };
);
md_assign_impl_all!(
DivAssign, div_assign;
(D, D), (D, D) for D: DimName;
self: RotationBase<N, D, SA>, right: RotationBase<N, D, SB>;
[val] => unsafe { self.matrix_mut().mul_assign(right.inverse().unwrap()) };
[ref] => unsafe { self.matrix_mut().mul_assign(right.inverse().matrix()) };
);
// Matrix *= RotationBase
// FIXME: try not to call `inverse()` explicitly.
// FIXME: this shares the same limitations as for the current impl. of MulAssign for matrices.
// (In particular the number of matrix column must be equal to the number of rotation columns,
// i.e., equal to the rotation dimension.
md_assign_impl_all!(
MulAssign, mul_assign;
(R1, C1), (C1, C1) for R1: DimName, C1: DimName;
self: Matrix<N, R1, C1, SA>, right: RotationBase<N, C1, SB>;
[val] => self.mul_assign(right.unwrap());
[ref] => self.mul_assign(right.matrix());
);
md_assign_impl_all!(
DivAssign, div_assign;
(R1, C1), (C1, C1) for R1: DimName, C1: DimName;
self: Matrix<N, R1, C1, SA>, right: RotationBase<N, C1, SB>;
[val] => self.mul_assign(right.inverse().unwrap());
[ref] => self.mul_assign(right.inverse().matrix());
);

View File

@ -0,0 +1,381 @@
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use std::ops::Neg;
use num::Zero;
use rand::{Rand, Rng};
use alga::general::Real;
use core::{Unit, ColumnVector, SquareMatrix, OwnedSquareMatrix, OwnedColumnVector, Vector3};
use core::dimension::{U1, U2, U3};
use core::storage::{Storage, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{RotationBase, OwnedRotation, UnitComplex};
/*
*
* 2D RotationBase matrix.
*
*/
impl<N, S> RotationBase<N, U2, S>
where N: Real,
S: OwnedStorage<N, U2, U2>,
S::Alloc: OwnedAllocator<N, U2, U2, S> {
/// Builds a 2 dimensional rotation matrix from an angle in radian.
pub fn new(angle: N) -> Self {
let (sia, coa) = angle.sin_cos();
Self::from_matrix_unchecked(SquareMatrix::<N, U2, S>::new(coa, -sia, sia, coa))
}
/// Builds a 2 dimensional rotation matrix from an angle in radian wrapped in a 1-dimensional vector.
///
/// Equivalent to `Self::new(axisangle[0])`.
#[inline]
pub fn from_scaled_axis<SB: Storage<N, U1, U1>>(axisangle: ColumnVector<N, U1, SB>) -> Self {
Self::new(axisangle[0])
}
/// The rotation matrix required to align `a` and `b` but with its angl.
///
/// This is the rotation `R` such that `(R * a).angle(b) == 0 && (R * a).dot(b).is_positive()`.
#[inline]
pub fn rotation_between<SB, SC>(a: &ColumnVector<N, U2, SB>, b: &ColumnVector<N, U2, SC>) -> Self
where SB: Storage<N, U2, U1>,
SC: Storage<N, U2, U1> {
::convert(UnitComplex::rotation_between(a, b).to_rotation_matrix())
}
/// The smallest rotation needed to make `a` and `b` collinear and point toward the same
/// direction, raised to the power `s`.
#[inline]
pub fn scaled_rotation_between<SB, SC>(a: &ColumnVector<N, U2, SB>, b: &ColumnVector<N, U2, SC>, s: N) -> Self
where SB: Storage<N, U2, U1>,
SC: Storage<N, U2, U1> {
::convert(UnitComplex::scaled_rotation_between(a, b, s).to_rotation_matrix())
}
}
impl<N, S> RotationBase<N, U2, S>
where N: Real,
S: Storage<N, U2, U2> {
/// The rotation angle.
#[inline]
pub fn angle(&self) -> N {
self.matrix()[(1, 0)].atan2(self.matrix()[(0, 0)])
}
/// The rotation angle needed to make `self` and `other` coincide.
#[inline]
pub fn angle_to<SB: Storage<N, U2, U2>>(&self, other: &RotationBase<N, U2, SB>) -> N {
self.rotation_to(other).angle()
}
/// The rotation matrix needed to make `self` and `other` coincide.
///
/// The result is such that: `self.rotation_to(other) * self == other`.
#[inline]
pub fn rotation_to<SB>(&self, other: &RotationBase<N, U2, SB>) -> OwnedRotation<N, U2, SB::Alloc>
where SB: Storage<N, U2, U2> {
other * self.inverse()
}
/// Raise the quaternion to a given floating power, i.e., returns the rotation with the angle
/// of `self` multiplied by `n`.
#[inline]
pub fn powf(&self, n: N) -> OwnedRotation<N, U2, S::Alloc> {
OwnedRotation::<_, _, S::Alloc>::new(self.angle() * n)
}
/// The rotation angle returned as a 1-dimensional vector.
#[inline]
pub fn scaled_axis(&self) -> OwnedColumnVector<N, U1, S::Alloc>
where S::Alloc: Allocator<N, U1, U1> {
ColumnVector::<_, U1, _>::new(self.angle())
}
}
impl<N, S> Rand for RotationBase<N, U2, S>
where N: Real + Rand,
S: OwnedStorage<N, U2, U2>,
S::Alloc: OwnedAllocator<N, U2, U2, S> {
#[inline]
fn rand<R: Rng>(rng: &mut R) -> Self {
Self::new(rng.gen())
}
}
#[cfg(feature="arbitrary")]
impl<N, S> Arbitrary for RotationBase<N, U2, S>
where N: Real + Arbitrary,
S: OwnedStorage<N, U2, U2> + Send,
S::Alloc: OwnedAllocator<N, U2, U2, S> {
#[inline]
fn arbitrary<G: Gen>(g: &mut G) -> Self {
Self::new(N::arbitrary(g))
}
}
/*
*
* 3D RotationBase matrix.
*
*/
impl<N, S> RotationBase<N, U3, S>
where N: Real,
S: OwnedStorage<N, U3, U3>,
S::Alloc: OwnedAllocator<N, U3, U3, S> {
/// Builds a 3 dimensional rotation matrix from an axis and an angle.
///
/// # Arguments
/// * `axisangle` - A vector representing the rotation. Its magnitude is the amount of rotation
/// in radian. Its direction is the axis of rotation.
pub fn new<SB: Storage<N, U3, U1>>(axisangle: ColumnVector<N, U3, SB>) -> Self {
let (axis, angle) = Unit::new_and_get(axisangle.into_owned());
Self::from_axis_angle(&axis, angle)
}
/// Builds a 3D rotation matrix from an axis scaled by the rotation angle.
pub fn from_scaled_axis<SB: Storage<N, U3, U1>>(axisangle: ColumnVector<N, U3, SB>) -> Self {
Self::new(axisangle)
}
/// Builds a 3D rotation matrix from an axis and a rotation angle.
pub fn from_axis_angle<SB>(axis: &Unit<ColumnVector<N, U3, SB>>, angle: N) -> Self
where SB: Storage<N, U3, U1> {
if angle.is_zero() {
Self::identity()
}
else {
let ux = axis.as_ref()[0];
let uy = axis.as_ref()[1];
let uz = axis.as_ref()[2];
let sqx = ux * ux;
let sqy = uy * uy;
let sqz = uz * uz;
let (sin, cos) = angle.sin_cos();
let one_m_cos = N::one() - cos;
Self::from_matrix_unchecked(
SquareMatrix::<N, U3, S>::new(
(sqx + (N::one() - sqx) * cos),
(ux * uy * one_m_cos - uz * sin),
(ux * uz * one_m_cos + uy * sin),
(ux * uy * one_m_cos + uz * sin),
(sqy + (N::one() - sqy) * cos),
(uy * uz * one_m_cos - ux * sin),
(ux * uz * one_m_cos - uy * sin),
(uy * uz * one_m_cos + ux * sin),
(sqz + (N::one() - sqz) * cos)))
}
}
/// Creates a new rotation from Euler angles.
///
/// The primitive rotations are applied in order: 1 roll 2 pitch 3 yaw.
pub fn from_euler_angles(roll: N, pitch: N, yaw: N) -> Self {
let (sr, cr) = roll.sin_cos();
let (sp, cp) = pitch.sin_cos();
let (sy, cy) = yaw.sin_cos();
Self::from_matrix_unchecked(
SquareMatrix::<N, U3, S>::new(
cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr,
sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr,
-sp, cp * sr, cp * cr)
)
}
/// Creates a rotation that corresponds to the local frame of an observer standing at the
/// origin and looking toward `dir`.
///
/// It maps the view direction `dir` to the positive `z` axis.
///
/// # Arguments
/// * dir - The look direction, that is, direction the matrix `z` axis will be aligned with.
/// * up - The vertical direction. The only requirement of this parameter is to not be
/// collinear
/// to `dir`. Non-collinearity is not checked.
#[inline]
pub fn new_observer_frame<SB, SC>(dir: &ColumnVector<N, U3, SB>, up: &ColumnVector<N, U3, SC>) -> Self
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1> {
let zaxis = dir.normalize();
let xaxis = up.cross(&zaxis).normalize();
let yaxis = zaxis.cross(&xaxis).normalize();
Self::from_matrix_unchecked(SquareMatrix::<N, U3, S>::new(
xaxis.x, yaxis.x, zaxis.x,
xaxis.y, yaxis.y, zaxis.y,
xaxis.z, yaxis.z, zaxis.z))
}
/// Builds a right-handed look-at view matrix without translation.
///
/// This conforms to the common notion of right handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_rh<SB, SC>(dir: &ColumnVector<N, U3, SB>, up: &ColumnVector<N, U3, SC>) -> Self
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1> {
Self::new_observer_frame(&dir.neg(), up).inverse()
}
/// Builds a left-handed look-at view matrix without translation.
///
/// This conforms to the common notion of left handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_lh<SB, SC>(dir: &ColumnVector<N, U3, SB>, up: &ColumnVector<N, U3, SC>) -> Self
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1> {
Self::new_observer_frame(dir, up).inverse()
}
/// The rotation matrix required to align `a` and `b` but with its angl.
///
/// This is the rotation `R` such that `(R * a).angle(b) == 0 && (R * a).dot(b).is_positive()`.
#[inline]
pub fn rotation_between<SB, SC>(a: &ColumnVector<N, U3, SB>, b: &ColumnVector<N, U3, SC>) -> Option<Self>
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1> {
Self::scaled_rotation_between(a, b, N::one())
}
/// The smallest rotation needed to make `a` and `b` collinear and point toward the same
/// direction, raised to the power `s`.
#[inline]
pub fn scaled_rotation_between<SB, SC>(a: &ColumnVector<N, U3, SB>, b: &ColumnVector<N, U3, SC>, n: N)
-> Option<Self>
where SB: Storage<N, U3, U1>,
SC: Storage<N, U3, U1> {
// FIXME: code duplication with RotationBase.
if let (Some(na), Some(nb)) = (a.try_normalize(N::zero()), b.try_normalize(N::zero())) {
let c = na.cross(&nb);
if let Some(axis) = Unit::try_new(c, N::default_epsilon()) {
return Some(Self::from_axis_angle(&axis, na.dot(&nb).acos() * n))
}
// Zero or PI.
if na.dot(&nb) < N::zero() {
// PI
//
// The rotation axis is undefined but the angle not zero. This is not a
// simple rotation.
return None;
}
}
Some(Self::identity())
}
}
impl<N, S> RotationBase<N, U3, S>
where N: Real,
S: Storage<N, U3, U3> {
/// The rotation angle.
#[inline]
pub fn angle(&self) -> N {
((self.matrix()[(0, 0)] + self.matrix()[(1, 1)] + self.matrix()[(2, 2)] - N::one()) / ::convert(2.0)).acos()
}
}
impl<N, S> RotationBase<N, U3, S>
where N: Real,
S: Storage<N, U3, U3>,
S::Alloc: Allocator<N, U3, U1> {
/// The rotation axis. Returns `None` if the rotation angle is zero or PI.
#[inline]
pub fn axis(&self) -> Option<Unit<OwnedColumnVector<N, U3, S::Alloc>>> {
let axis = OwnedColumnVector::<N, U3, S::Alloc>::new(
self.matrix()[(2, 1)] - self.matrix()[(1, 2)],
self.matrix()[(0, 2)] - self.matrix()[(2, 0)],
self.matrix()[(1, 0)] - self.matrix()[(0, 1)]);
Unit::try_new(axis, N::default_epsilon())
}
/// The rotation axis multiplied by the rotation angle.
#[inline]
pub fn scaled_axis(&self) -> OwnedColumnVector<N, U3, S::Alloc> {
if let Some(axis) = self.axis() {
axis.unwrap() * self.angle()
}
else {
ColumnVector::zero()
}
}
/// The rotation angle needed to make `self` and `other` coincide.
#[inline]
pub fn angle_to<SB: Storage<N, U3, U3>>(&self, other: &RotationBase<N, U3, SB>) -> N {
self.rotation_to(other).angle()
}
/// The rotation matrix needed to make `self` and `other` coincide.
///
/// The result is such that: `self.rotation_to(other) * self == other`.
#[inline]
pub fn rotation_to<SB>(&self, other: &RotationBase<N, U3, SB>) -> OwnedRotation<N, U3, SB::Alloc>
where SB: Storage<N, U3, U3> {
other * self.inverse()
}
/// Raise the quaternion to a given floating power, i.e., returns the rotation with the same
/// axis as `self` and an angle equal to `self.angle()` multiplied by `n`.
#[inline]
pub fn powf(&self, n: N) -> OwnedRotation<N, U3, S::Alloc> {
if let Some(axis) = self.axis() {
OwnedRotation::<_, _, S::Alloc>::from_axis_angle(&axis, self.angle() * n)
}
else if self.matrix()[(0, 0)] < N::zero() {
let minus_id = OwnedSquareMatrix::<N, U3, S::Alloc>::from_diagonal_element(-N::one());
OwnedRotation::<_, _, S::Alloc>::from_matrix_unchecked(minus_id)
}
else {
OwnedRotation::<_, _, S::Alloc>::identity()
}
}
}
impl<N, S> Rand for RotationBase<N, U3, S>
where N: Real + Rand,
S: OwnedStorage<N, U3, U3>,
S::Alloc: OwnedAllocator<N, U3, U3, S> +
Allocator<N, U3, U1> {
#[inline]
fn rand<R: Rng>(rng: &mut R) -> Self {
Self::new(Vector3::rand(rng))
}
}
#[cfg(feature="arbitrary")]
impl<N, S> Arbitrary for RotationBase<N, U3, S>
where N: Real + Arbitrary,
S: OwnedStorage<N, U3, U3> + Send,
S::Alloc: OwnedAllocator<N, U3, U3, S> +
Allocator<N, U3, U1> {
#[inline]
fn arbitrary<G: Gen>(g: &mut G) -> Self {
Self::new(Vector3::arbitrary(g))
}
}

276
src/geometry/similarity.rs Normal file
View File

@ -0,0 +1,276 @@
use std::fmt;
use approx::ApproxEq;
use alga::general::{ClosedMul, Real, SubsetOf};
use alga::linear::Rotation;
use core::{Scalar, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::{Storage, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, TranslationBase, IsometryBase};
/// A similarity that uses a data storage deduced from the allocator `A`.
pub type OwnedSimilarityBase<N, D, A, R> =
SimilarityBase<N, D, <A as Allocator<N, D, U1>>::Buffer, R>;
/// A similarity, i.e., an uniform scaling, followed by a rotation, followed by a translation.
#[repr(C)]
#[derive(Hash, Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct SimilarityBase<N: Scalar, D: DimName, S, R> {
/// The part of this similarity that does not include the scaling factor.
pub isometry: IsometryBase<N, D, S, R>,
scaling: N
}
impl<N, D: DimName, S, R> SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new similarity from its rotational and translational parts.
#[inline]
pub fn from_parts(translation: TranslationBase<N, D, S>, rotation: R, scaling: N) -> SimilarityBase<N, D, S, R> {
SimilarityBase::from_isometry(IsometryBase::from_parts(translation, rotation), scaling)
}
/// Creates a new similarity from its rotational and translational parts.
#[inline]
pub fn from_isometry(isometry: IsometryBase<N, D, S, R>, scaling: N) -> SimilarityBase<N, D, S, R> {
assert!(!relative_eq!(scaling, N::zero()), "The scaling factor must not be zero.");
SimilarityBase {
isometry: isometry,
scaling: scaling
}
}
/// Creates a new similarity that applies only a scaling factor.
#[inline]
pub fn from_scaling(scaling: N) -> SimilarityBase<N, D, S, R> {
Self::from_isometry(IsometryBase::identity(), scaling)
}
/// Inverts `self`.
#[inline]
pub fn inverse(&self) -> SimilarityBase<N, D, S, R> {
let mut res = self.clone();
res.inverse_mut();
res
}
/// Inverts `self` in-place.
#[inline]
pub fn inverse_mut(&mut self) {
self.scaling = N::one() / self.scaling;
self.isometry.inverse_mut();
self.isometry.translation.vector *= self.scaling;
}
/// The scaling factor of this similarity transformation.
#[inline]
pub fn set_scaling(&mut self, scaling: N) {
assert!(!relative_eq!(scaling, N::zero()), "The similarity scaling factor must not be zero.");
self.scaling = scaling;
}
/// The similarity transformation that applies a scaling factor `scaling` before `self`.
#[inline]
pub fn prepend_scaling(&self, scaling: N) -> Self {
assert!(!relative_eq!(scaling, N::zero()), "The similarity scaling factor must not be zero.");
Self::from_isometry(self.isometry.clone(), self.scaling * scaling)
}
/// The similarity transformation that applies a scaling factor `scaling` after `self`.
#[inline]
pub fn append_scaling(&self, scaling: N) -> Self {
assert!(!relative_eq!(scaling, N::zero()), "The similarity scaling factor must not be zero.");
Self::from_parts(
TranslationBase::from_vector(&self.isometry.translation.vector * scaling),
self.isometry.rotation.clone(),
self.scaling * scaling)
}
/// Sets `self` to the similarity transformation that applies a scaling factor `scaling` before `self`.
#[inline]
pub fn prepend_scaling_mut(&mut self, scaling: N) {
assert!(!relative_eq!(scaling, N::zero()), "The similarity scaling factor must not be zero.");
self.scaling *= scaling
}
/// Sets `self` to the similarity transformation that applies a scaling factor `scaling` after `self`.
#[inline]
pub fn append_scaling_mut(&mut self, scaling: N) {
assert!(!relative_eq!(scaling, N::zero()), "The similarity scaling factor must not be zero.");
self.isometry.translation.vector *= scaling;
self.scaling *= scaling;
}
/// Appends to `self` the given translation in-place.
#[inline]
pub fn append_translation_mut(&mut self, t: &TranslationBase<N, D, S>) {
self.isometry.append_translation_mut(t)
}
/// Appends to `self` the given rotation in-place.
#[inline]
pub fn append_rotation_mut(&mut self, r: &R) {
self.isometry.append_rotation_mut(r)
}
/// Appends in-place to `self` a rotation centered at the point `p`, i.e., the rotation that
/// lets `p` invariant.
#[inline]
pub fn append_rotation_wrt_point_mut(&mut self, r: &R, p: &PointBase<N, D, S>) {
self.isometry.append_rotation_wrt_point_mut(r, p)
}
/// Appends in-place to `self` a rotation centered at the point with coordinates
/// `self.translation`.
#[inline]
pub fn append_rotation_wrt_center_mut(&mut self, r: &R) {
self.isometry.append_rotation_wrt_center_mut(r)
}
}
// NOTE: we don't require `R: Rotation<...>` here becaus this is not useful for the implementation
// and makes it harde to use it, e.g., for Transform × Isometry implementation.
// This is OK since all constructors of the isometry enforce the Rotation bound already (and
// explicit struct construction is prevented by the private scaling factor).
impl<N, D: DimName, S, R> SimilarityBase<N, D, S, R>
where N: Scalar + ClosedMul,
S: Storage<N, D, U1> {
/// Converts this similarity into its equivalent homogeneous transformation matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>
where D: DimNameAdd<U1>,
R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>>,
S::Alloc: Allocator<N, D, D> +
Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
let mut res = self.isometry.to_homogeneous();
for e in res.fixed_slice_mut::<D, D>(0, 0).iter_mut() {
*e *= self.scaling
}
res
}
/// The scaling factor of this similarity transformation.
#[inline]
pub fn scaling(&self) -> N {
self.scaling
}
}
impl<N, D: DimName, S, R> Eq for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + Eq,
S::Alloc: OwnedAllocator<N, D, U1, S> {
}
impl<N, D: DimName, S, R> PartialEq for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + PartialEq,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn eq(&self, right: &SimilarityBase<N, D, S, R>) -> bool {
self.isometry == right.isometry && self.scaling == right.scaling
}
}
impl<N, D: DimName, S, R> ApproxEq for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + ApproxEq<Epsilon = N::Epsilon>,
S::Alloc: OwnedAllocator<N, D, U1, S>,
N::Epsilon: Copy {
type Epsilon = N::Epsilon;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.isometry.relative_eq(&other.isometry, epsilon, max_relative) &&
self.scaling.relative_eq(&other.scaling, epsilon, max_relative)
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.isometry.ulps_eq(&other.isometry, epsilon, max_ulps) &&
self.scaling.ulps_eq(&other.scaling, epsilon, max_ulps)
}
}
/*
*
* Display
*
*/
impl<N, D: DimName, S, R> fmt::Display for SimilarityBase<N, D, S, R>
where N: Real + fmt::Display,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>> + fmt::Display,
S::Alloc: OwnedAllocator<N, D, U1, S> + Allocator<usize, D, U1> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let precision = f.precision().unwrap_or(3);
try!(writeln!(f, "SimilarityBase {{"));
try!(write!(f, "{:.*}", precision, self.isometry));
try!(write!(f, "Scaling: {:.*}", precision, self.scaling));
writeln!(f, "}}")
}
}
/*
// /*
// *
// * ToHomogeneous
// *
// */
// impl<N: Real> ToHomogeneous<$homogeneous<N>> for $t<N> {
// #[inline]
// fn to_homogeneous(&self) -> $homogeneous<N> {
// self.vector.to_homogeneous()
// }
// }
// /*
// *
// * Absolute
// *
// */
// impl<N: Absolute> Absolute for $t<N> {
// type AbsoluteValue = $submatrix<N::AbsoluteValue>;
//
// #[inline]
// fn abs(m: &$t<N>) -> $submatrix<N::AbsoluteValue> {
// Absolute::abs(&m.submatrix)
// }
// }
*/

View File

@ -0,0 +1,184 @@
use alga::general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
AbstractSemigroup, Real, Inverse, Multiplicative, Identity};
use alga::linear::{Transformation, AffineTransformation, Rotation, Similarity, ProjectiveTransformation};
use core::ColumnVector;
use core::dimension::{DimName, U1};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{SimilarityBase, TranslationBase, PointBase};
/*
*
* Algebraic structures.
*
*/
impl<N, D: DimName, S, R> Identity<Multiplicative> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S, R> Inverse<Multiplicative> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn inverse(&self) -> Self {
self.inverse()
}
#[inline]
fn inverse_mut(&mut self) {
self.inverse_mut()
}
}
impl<N, D: DimName, S, R> AbstractMagma<Multiplicative> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
macro_rules! impl_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimName, S, R> $marker<$operator> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> { }
)*}
);
impl_multiplicative_structures!(
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
AbstractQuasigroup<Multiplicative>,
AbstractLoop<Multiplicative>,
AbstractGroup<Multiplicative>
);
/*
*
* Transformation groups.
*
*/
impl<N, D: DimName, S, R> Transformation<PointBase<N, D, S>> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn transform_point(&self, pt: &PointBase<N, D, S>) -> PointBase<N, D, S> {
self * pt
}
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, D, S>) -> ColumnVector<N, D, S> {
self * v
}
}
impl<N, D: DimName, S, R> ProjectiveTransformation<PointBase<N, D, S>> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn inverse_transform_point(&self, pt: &PointBase<N, D, S>) -> PointBase<N, D, S> {
self.isometry.inverse_transform_point(pt) / self.scaling()
}
#[inline]
fn inverse_transform_vector(&self, v: &ColumnVector<N, D, S>) -> ColumnVector<N, D, S> {
self.isometry.inverse_transform_vector(v) / self.scaling()
}
}
impl<N, D: DimName, S, R> AffineTransformation<PointBase<N, D, S>> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type NonUniformScaling = N;
type Rotation = R;
type Translation = TranslationBase<N, D, S>;
#[inline]
fn decompose(&self) -> (TranslationBase<N, D, S>, R, N, R) {
(self.isometry.translation.clone(), self.isometry.rotation.clone(), self.scaling(), R::identity())
}
#[inline]
fn append_translation(&self, t: &Self::Translation) -> Self {
t * self
}
#[inline]
fn prepend_translation(&self, t: &Self::Translation) -> Self {
self * t
}
#[inline]
fn append_rotation(&self, r: &Self::Rotation) -> Self {
SimilarityBase::from_isometry(self.isometry.append_rotation(r), self.scaling())
}
#[inline]
fn prepend_rotation(&self, r: &Self::Rotation) -> Self {
self * r
}
#[inline]
fn append_scaling(&self, s: &Self::NonUniformScaling) -> Self {
self.append_scaling(*s)
}
#[inline]
fn prepend_scaling(&self, s: &Self::NonUniformScaling) -> Self {
self.prepend_scaling(*s)
}
#[inline]
fn append_rotation_wrt_point(&self, r: &Self::Rotation, p: &PointBase<N, D, S>) -> Option<Self> {
let mut res = self.clone();
res.append_rotation_wrt_point_mut(r, p);
Some(res)
}
}
impl<N, D: DimName, S, R> Similarity<PointBase<N, D, S>> for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Scaling = N;
#[inline]
fn translation(&self) -> TranslationBase<N, D, S> {
self.isometry.translation()
}
#[inline]
fn rotation(&self) -> R {
self.isometry.rotation()
}
#[inline]
fn scaling(&self) -> N {
self.scaling()
}
}

View File

@ -0,0 +1,19 @@
use core::MatrixArray;
use core::dimension::{U1, U2, U3};
use geometry::{Rotation, SimilarityBase, UnitQuaternion, UnitComplex};
/// A D-dimensional similarity.
pub type Similarity<N, D> = SimilarityBase<N, D, MatrixArray<N, D, U1>, Rotation<N, D>>;
/// A 2-dimensional similarity.
pub type Similarity2<N> = SimilarityBase<N, U2, MatrixArray<N, U2, U1>, UnitComplex<N>>;
/// A 3-dimensional similarity.
pub type Similarity3<N> = SimilarityBase<N, U3, MatrixArray<N, U3, U1>, UnitQuaternion<N>>;
/// A 2-dimensional similarity using a rotation matrix for its rotation part.
pub type SimilarityMatrix2<N> = Similarity<N, U2>;
/// A 3-dimensional similarity using a rotation matrix for its rotation part.
pub type SimilarityMatrix3<N> = Similarity<N, U3>;

View File

@ -0,0 +1,200 @@
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use num::One;
use rand::{Rng, Rand};
use alga::general::Real;
use alga::linear::Rotation as AlgaRotation;
use core::ColumnVector;
use core::dimension::{DimName, U1, U2, U3, U4};
use core::allocator::{OwnedAllocator, Allocator};
use core::storage::OwnedStorage;
use geometry::{PointBase, TranslationBase, RotationBase, SimilarityBase,
UnitComplex, UnitQuaternionBase, IsometryBase};
impl<N, D: DimName, S, R> SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new identity similarity.
#[inline]
pub fn identity() -> Self {
Self::from_isometry(IsometryBase::identity(), N::one())
}
}
impl<N, D: DimName, S, R> One for SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new identity similarity.
#[inline]
fn one() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S, R> Rand for SimilarityBase<N, D, S, R>
where N: Real + Rand,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>> + Rand,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn rand<G: Rng>(rng: &mut G) -> Self {
let mut s = rng.gen();
while relative_eq!(s, N::zero()) {
s = rng.gen()
}
Self::from_isometry(rng.gen(), s)
}
}
impl<N, D: DimName, S, R> SimilarityBase<N, D, S, R>
where N: Real,
S: OwnedStorage<N, D, U1>,
R: AlgaRotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// The similarity that applies tha scaling factor `scaling`, followed by the rotation `r` with
/// its axis passing through the point `p`.
#[inline]
pub fn rotation_wrt_point(r: R, p: PointBase<N, D, S>, scaling: N) -> Self {
let shift = r.transform_vector(&-&p.coords);
Self::from_parts(TranslationBase::from_vector(shift + p.coords), r, scaling)
}
}
#[cfg(feature = "arbitrary")]
impl<N, D: DimName, S, R> Arbitrary for SimilarityBase<N, D, S, R>
where N: Real + Arbitrary + Send,
S: OwnedStorage<N, D, U1> + Send,
R: AlgaRotation<PointBase<N, D, S>> + Arbitrary + Send,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn arbitrary<G: Gen>(rng: &mut G) -> Self {
let mut s = Arbitrary::arbitrary(rng);
while relative_eq!(s, N::zero()) {
s = Arbitrary::arbitrary(rng)
}
Self::from_isometry(Arbitrary::arbitrary(rng), s)
}
}
/*
*
* Constructors for various static dimensions.
*
*/
// 2D rotation.
impl<N, S, SR> SimilarityBase<N, U2, S, RotationBase<N, U2, SR>>
where N: Real,
S: OwnedStorage<N, U2, U1, Alloc = SR::Alloc>,
SR: OwnedStorage<N, U2, U2>,
S::Alloc: OwnedAllocator<N, U2, U1, S>,
SR::Alloc: OwnedAllocator<N, U2, U2, SR> {
/// Creates a new similarity from a translation and a rotation angle.
#[inline]
pub fn new(translation: ColumnVector<N, U2, S>, angle: N, scaling: N) -> Self {
Self::from_parts(TranslationBase::from_vector(translation), RotationBase::<N, U2, SR>::new(angle), scaling)
}
}
impl<N, S> SimilarityBase<N, U2, S, UnitComplex<N>>
where N: Real,
S: OwnedStorage<N, U2, U1>,
S::Alloc: OwnedAllocator<N, U2, U1, S> {
/// Creates a new similarity from a translation and a rotation angle.
#[inline]
pub fn new(translation: ColumnVector<N, U2, S>, angle: N, scaling: N) -> Self {
Self::from_parts(TranslationBase::from_vector(translation), UnitComplex::new(angle), scaling)
}
}
// 3D rotation.
macro_rules! similarity_construction_impl(
($Rot: ty, $RotId: ident, $RRDim: ty, $RCDim: ty) => {
impl<N, S, SR> SimilarityBase<N, U3, S, $Rot>
where N: Real,
S: OwnedStorage<N, U3, U1, Alloc = SR::Alloc>,
SR: OwnedStorage<N, $RRDim, $RCDim>,
S::Alloc: OwnedAllocator<N, U3, U1, S>,
SR::Alloc: OwnedAllocator<N, $RRDim, $RCDim, SR> +
Allocator<N, U3, U3> {
/// Creates a new similarity from a translation, rotation axis-angle, and scaling
/// factor.
#[inline]
pub fn new(translation: ColumnVector<N, U3, S>, axisangle: ColumnVector<N, U3, S>, scaling: N) -> Self {
Self::from_isometry(IsometryBase::<_, _, _, $Rot>::new(translation, axisangle), scaling)
}
/// Creates an similarity that corresponds to the a scaling factor and a local frame of
/// an observer standing at the point `eye` and looking toward `target`.
///
/// It maps the view direction `target - eye` to the positive `z` axis and the origin to the
/// `eye`.
///
/// # Arguments
/// * eye - The observer position.
/// * target - The target position.
/// * up - Vertical direction. The only requirement of this parameter is to not be collinear
/// to `eye - at`. Non-collinearity is not checked.
#[inline]
pub fn new_observer_frame(eye: &PointBase<N, U3, S>,
target: &PointBase<N, U3, S>,
up: &ColumnVector<N, U3, S>,
scaling: N)
-> Self {
Self::from_isometry(IsometryBase::<_, _, _, $Rot>::new_observer_frame(eye, target, up), scaling)
}
/// Builds a right-handed look-at view matrix including scaling factor.
///
/// This conforms to the common notion of right handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_rh(eye: &PointBase<N, U3, S>,
target: &PointBase<N, U3, S>,
up: &ColumnVector<N, U3, S>,
scaling: N)
-> Self {
Self::from_isometry(IsometryBase::<_, _, _, $Rot>::look_at_rh(eye, target, up), scaling)
}
/// Builds a left-handed look-at view matrix including a scaling factor.
///
/// This conforms to the common notion of left handed look-at matrix from the computer
/// graphics community.
///
/// # Arguments
/// * eye - The eye position.
/// * target - The target position.
/// * up - A vector approximately aligned with required the vertical axis. The only
/// requirement of this parameter is to not be collinear to `target - eye`.
#[inline]
pub fn look_at_lh(eye: &PointBase<N, U3, S>,
target: &PointBase<N, U3, S>,
up: &ColumnVector<N, U3, S>,
scaling: N)
-> Self {
Self::from_isometry(IsometryBase::<_, _, _, $Rot>::look_at_lh(eye, target, up), scaling)
}
}
}
);
similarity_construction_impl!(RotationBase<N, U3, SR>, RotationBase, U3, U3);
similarity_construction_impl!(UnitQuaternionBase<N, SR>, UnitQuaternionBase, U4, U1);

View File

@ -0,0 +1,163 @@
use alga::general::{Real, SubsetOf, SupersetOf};
use alga::linear::Rotation;
use core::{SquareMatrix, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameAdd, DimNameSum, U1};
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, TranslationBase, IsometryBase, SimilarityBase, TransformBase, SuperTCategoryOf, TAffine};
/*
* This file provides the following conversions:
* =============================================
*
* SimilarityBase -> SimilarityBase
* SimilarityBase -> TransformBase
* SimilarityBase -> Matrix (homogeneous)
*/
impl<N1, N2, D: DimName, SA, SB, R1, R2> SubsetOf<SimilarityBase<N2, D, SB, R2>> for SimilarityBase<N1, D, SA, R1>
where N1: Real + SubsetOf<N2>,
N2: Real + SupersetOf<N1>,
R1: Rotation<PointBase<N1, D, SA>> + SubsetOf<R2>,
R2: Rotation<PointBase<N2, D, SB>>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, D, U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> SimilarityBase<N2, D, SB, R2> {
SimilarityBase::from_isometry(
self.isometry.to_superset(),
self.scaling().to_superset()
)
}
#[inline]
fn is_in_subset(sim: &SimilarityBase<N2, D, SB, R2>) -> bool {
::is_convertible::<_, IsometryBase<N1, D, SA, R1>>(&sim.isometry) &&
::is_convertible::<_, N1>(&sim.scaling())
}
#[inline]
unsafe fn from_superset_unchecked(sim: &SimilarityBase<N2, D, SB, R2>) -> Self {
SimilarityBase::from_isometry(
sim.isometry.to_subset_unchecked(),
sim.scaling().to_subset_unchecked()
)
}
}
impl<N1, N2, D, SA, SB, R, C> SubsetOf<TransformBase<N2, D, SB, C>> for SimilarityBase<N1, D, SA, R>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SuperTCategoryOf<TAffine>,
R: Rotation<PointBase<N1, D, SA>> +
SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous()
SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm)
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> +
Allocator<N1, D, D> + // needed by R
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous()
Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut
Allocator<N2, D, U1> + // needed by: m.fixed_slice
Allocator<N2, U1, D> { // needed by: m.fixed_slice
#[inline]
fn to_superset(&self) -> TransformBase<N2, D, SB, C> {
TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset())
}
#[inline]
fn is_in_subset(t: &TransformBase<N2, D, SB, C>) -> bool {
<Self as SubsetOf<_>>::is_in_subset(t.matrix())
}
#[inline]
unsafe fn from_superset_unchecked(t: &TransformBase<N2, D, SB, C>) -> Self {
Self::from_superset_unchecked(t.matrix())
}
}
impl<N1, N2, D, SA, SB, R> SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>> for SimilarityBase<N1, D, SA, R>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
R: Rotation<PointBase<N1, D, SA>> +
SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous()
SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm)
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> +
Allocator<N1, D, D> + // needed by R
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous()
Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut
Allocator<N2, D, U1> + // needed by: m.fixed_slice
Allocator<N2, U1, D> { // needed by: m.fixed_slice
#[inline]
fn to_superset(&self) -> SquareMatrix<N2, DimNameSum<D, U1>, SB> {
self.to_homogeneous().to_superset()
}
#[inline]
fn is_in_subset(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> bool {
let mut rot = m.fixed_slice::<D, D>(0, 0).clone_owned();
if rot.fixed_columns_mut::<U1>(0).try_normalize_mut(N2::zero()).is_some() &&
rot.fixed_columns_mut::<U1>(1).try_normalize_mut(N2::zero()).is_some() &&
rot.fixed_columns_mut::<U1>(2).try_normalize_mut(N2::zero()).is_some() {
// FIXME: could we avoid explicit the computation of the determinant?
// (its sign is needed to see if the scaling factor is negative).
if rot.determinant() < N2::zero() {
rot.fixed_columns_mut::<U1>(0).neg_mut();
rot.fixed_columns_mut::<U1>(1).neg_mut();
rot.fixed_columns_mut::<U1>(2).neg_mut();
}
let bottom = m.fixed_slice::<U1, D>(D::dim(), 0);
// Scalar types agree.
m.iter().all(|e| SupersetOf::<N1>::is_in_subset(e)) &&
// The normalized block part is a rotation.
// rot.is_special_orthogonal(N2::default_epsilon().sqrt()) &&
// The bottom row is (0, 0, ..., 1)
bottom.iter().all(|e| e.is_zero()) &&
m[(D::dim(), D::dim())] == N2::one()
}
else {
false
}
}
#[inline]
unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> Self {
let mut mm = m.clone_owned();
let na = mm.fixed_slice_mut::<D, U1>(0, 0).normalize_mut();
let nb = mm.fixed_slice_mut::<D, U1>(0, 1).normalize_mut();
let nc = mm.fixed_slice_mut::<D, U1>(0, 2).normalize_mut();
let mut scale = (na + nb + nc) / ::convert(3.0); // We take the mean, for robustness.
// FIXME: could we avoid the explicit computation of the determinant?
// (its sign is needed to see if the scaling factor is negative).
if mm.fixed_slice::<D, D>(0, 0).determinant() < N2::zero() {
mm.fixed_slice_mut::<D, U1>(0, 0).neg_mut();
mm.fixed_slice_mut::<D, U1>(0, 1).neg_mut();
mm.fixed_slice_mut::<D, U1>(0, 2).neg_mut();
scale = -scale;
}
let t = m.fixed_slice::<D, U1>(0, D::dim()).into_owned();
let t = TranslationBase::from_vector(::convert_unchecked(t));
Self::from_parts(t, ::convert_unchecked(mm), ::convert_unchecked(scale))
}
}

View File

@ -0,0 +1,512 @@
use std::ops::{Mul, MulAssign, Div, DivAssign};
use alga::general::Real;
use alga::linear::Rotation;
use core::ColumnVector;
use core::dimension::{DimName, U1, U3, U4};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{PointBase, RotationBase, SimilarityBase, TranslationBase, UnitQuaternionBase, IsometryBase};
// FIXME: there are several cloning of rotations that we could probably get rid of (but we didn't
// yet because that would require to add a bound like `where for<'a, 'b> &'a R: Mul<&'b R, Output = R>`
// which is quite ugly.
/*
*
* In this file, we provide:
* =========================
*
*
* (Operators)
*
* SimilarityBase × SimilarityBase
* SimilarityBase × R
* SimilarityBase × IsometryBase
*
* IsometryBase × SimilarityBase
* IsometryBase ÷ SimilarityBase
*
*
* SimilarityBase ÷ SimilarityBase
* SimilarityBase ÷ R
* SimilarityBase ÷ IsometryBase
*
* SimilarityBase × PointBase
* SimilarityBase × ColumnVector
*
*
* SimilarityBase × TranslationBase
* TranslationBase × SimilarityBase
*
* NOTE: The following are provided explicitly because we can't have R × SimilarityBase.
* RotationBase × SimilarityBase<RotationBase>
* UnitQuaternion × SimilarityBase<UnitQuaternion>
*
* RotationBase ÷ SimilarityBase<RotationBase>
* UnitQuaternion ÷ SimilarityBase<UnitQuaternion>
*
* (Assignment Operators)
*
* SimilarityBase ×= TranslationBase
*
* SimilarityBase ×= SimilarityBase
* SimilarityBase ×= IsometryBase
* SimilarityBase ×= R
*
* SimilarityBase ÷= SimilarityBase
* SimilarityBase ÷= IsometryBase
* SimilarityBase ÷= R
*
*/
// XXX: code duplication: those macros are the same as for the isometry.
macro_rules! similarity_binop_impl(
($Op: ident, $op: ident;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N, D: DimName, S, R> $Op<$Rhs> for $Lhs
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Output = $Output;
#[inline]
fn $op($lhs, $rhs: $Rhs) -> Self::Output {
$action
}
}
}
);
macro_rules! similarity_binop_impl_all(
($Op: ident, $op: ident;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
[val val] => $action_val_val: expr;
[ref val] => $action_ref_val: expr;
[val ref] => $action_val_ref: expr;
[ref ref] => $action_ref_ref: expr;) => {
similarity_binop_impl!(
$Op, $op;
$lhs: $Lhs, $rhs: $Rhs, Output = $Output;
$action_val_val; );
similarity_binop_impl!(
$Op, $op;
$lhs: &'a $Lhs, $rhs: $Rhs, Output = $Output;
$action_ref_val; 'a);
similarity_binop_impl!(
$Op, $op;
$lhs: $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_val_ref; 'b);
similarity_binop_impl!(
$Op, $op;
$lhs: &'a $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_ref_ref; 'a, 'b);
}
);
macro_rules! similarity_binop_assign_impl_all(
($OpAssign: ident, $op_assign: ident;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty;
[val] => $action_val: expr;
[ref] => $action_ref: expr;) => {
impl<N, D: DimName, S, R> $OpAssign<$Rhs> for $Lhs
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn $op_assign(&mut $lhs, $rhs: $Rhs) {
$action_val
}
}
impl<'b, N, D: DimName, S, R> $OpAssign<&'b $Rhs> for $Lhs
where N: Real,
S: OwnedStorage<N, D, U1>,
R: Rotation<PointBase<N, D, S>>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn $op_assign(&mut $lhs, $rhs: &'b $Rhs) {
$action_ref
}
}
}
);
// SimilarityBase × SimilarityBase
// SimilarityBase ÷ SimilarityBase
similarity_binop_impl_all!(
Mul, mul;
self: SimilarityBase<N, D, S, R>, rhs: SimilarityBase<N, D, S, R>, Output = SimilarityBase<N, D, S, R>;
[val val] => &self * &rhs;
[ref val] => self * &rhs;
[val ref] => &self * rhs;
[ref ref] => {
let mut res = self * &rhs.isometry;
res.prepend_scaling_mut(rhs.scaling());
res
};
);
similarity_binop_impl_all!(
Div, div;
self: SimilarityBase<N, D, S, R>, rhs: SimilarityBase<N, D, S, R>, Output = SimilarityBase<N, D, S, R>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.inverse();
[ref ref] => self * rhs.inverse();
);
// SimilarityBase ×= TranslationBase
similarity_binop_assign_impl_all!(
MulAssign, mul_assign;
self: SimilarityBase<N, D, S, R>, rhs: TranslationBase<N, D, S>;
[val] => *self *= &rhs;
[ref] => {
let shift = self.isometry.rotation.transform_vector(&rhs.vector) * self.scaling();
self.isometry.translation.vector += shift;
};
);
// SimilarityBase ×= SimilarityBase
// SimilarityBase ÷= SimilarityBase
similarity_binop_assign_impl_all!(
MulAssign, mul_assign;
self: SimilarityBase<N, D, S, R>, rhs: SimilarityBase<N, D, S, R>;
[val] => *self *= &rhs;
[ref] => {
*self *= &rhs.isometry;
self.prepend_scaling_mut(rhs.scaling());
};
);
similarity_binop_assign_impl_all!(
DivAssign, div_assign;
self: SimilarityBase<N, D, S, R>, rhs: SimilarityBase<N, D, S, R>;
[val] => *self /= &rhs;
// FIXME: don't invert explicitly.
[ref] => *self *= rhs.inverse();
);
// SimilarityBase ×= IsometryBase
// SimilarityBase ÷= IsometryBase
similarity_binop_assign_impl_all!(
MulAssign, mul_assign;
self: SimilarityBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>;
[val] => *self *= &rhs;
[ref] => {
let shift = self.isometry.rotation.transform_vector(&rhs.translation.vector) * self.scaling();
self.isometry.translation.vector += shift;
self.isometry.rotation *= rhs.rotation.clone();
};
);
similarity_binop_assign_impl_all!(
DivAssign, div_assign;
self: SimilarityBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>;
[val] => *self /= &rhs;
// FIXME: don't invert explicitly.
[ref] => *self *= rhs.inverse();
);
// SimilarityBase ×= R
// SimilarityBase ÷= R
similarity_binop_assign_impl_all!(
MulAssign, mul_assign;
self: SimilarityBase<N, D, S, R>, rhs: R;
[val] => self.isometry.rotation *= rhs;
[ref] => self.isometry.rotation *= rhs.clone();
);
similarity_binop_assign_impl_all!(
DivAssign, div_assign;
self: SimilarityBase<N, D, S, R>, rhs: R;
// FIXME: don't invert explicitly?
[val] => *self *= rhs.inverse();
[ref] => *self *= rhs.inverse();
);
// SimilarityBase × R
// SimilarityBase ÷ R
similarity_binop_impl_all!(
Mul, mul;
self: SimilarityBase<N, D, S, R>, rhs: R, Output = SimilarityBase<N, D, S, R>;
[val val] => {
let scaling = self.scaling();
SimilarityBase::from_isometry(self.isometry * rhs, scaling)
};
[ref val] => SimilarityBase::from_isometry(&self.isometry * rhs, self.scaling());
[val ref] => {
let scaling = self.scaling();
SimilarityBase::from_isometry(self.isometry * rhs, scaling)
};
[ref ref] => SimilarityBase::from_isometry(&self.isometry * rhs, self.scaling());
);
similarity_binop_impl_all!(
Div, div;
self: SimilarityBase<N, D, S, R>, rhs: R, Output = SimilarityBase<N, D, S, R>;
[val val] => {
let scaling = self.scaling();
SimilarityBase::from_isometry(self.isometry / rhs, scaling)
};
[ref val] => SimilarityBase::from_isometry(&self.isometry / rhs, self.scaling());
[val ref] => {
let scaling = self.scaling();
SimilarityBase::from_isometry(self.isometry / rhs, scaling)
};
[ref ref] => SimilarityBase::from_isometry(&self.isometry / rhs, self.scaling());
);
// SimilarityBase × IsometryBase
// SimilarityBase ÷ IsometryBase
similarity_binop_impl_all!(
Mul, mul;
self: SimilarityBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>, Output = SimilarityBase<N, D, S, R>;
[val val] => &self * &rhs;
[ref val] => self * &rhs;
[val ref] => &self * rhs;
[ref ref] => {
let shift = self.isometry.rotation.transform_vector(&rhs.translation.vector) * self.scaling();
SimilarityBase::from_parts(
TranslationBase::from_vector(&self.isometry.translation.vector + shift),
self.isometry.rotation.clone() * rhs.rotation.clone(),
self.scaling())
};
);
similarity_binop_impl_all!(
Div, div;
self: SimilarityBase<N, D, S, R>, rhs: IsometryBase<N, D, S, R>, Output = SimilarityBase<N, D, S, R>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.inverse();
[ref ref] => self * rhs.inverse();
);
// IsometryBase × SimilarityBase
// IsometryBase ÷ SimilarityBase
similarity_binop_impl_all!(
Mul, mul;
self: IsometryBase<N, D, S, R>, rhs: SimilarityBase<N, D, S, R>, Output = SimilarityBase<N, D, S, R>;
[val val] => {
let scaling = rhs.scaling();
SimilarityBase::from_isometry(self * rhs.isometry, scaling)
};
[ref val] => {
let scaling = rhs.scaling();
SimilarityBase::from_isometry(self * rhs.isometry, scaling)
};
[val ref] => {
let scaling = rhs.scaling();
SimilarityBase::from_isometry(self * &rhs.isometry, scaling)
};
[ref ref] => {
let scaling = rhs.scaling();
SimilarityBase::from_isometry(self * &rhs.isometry, scaling)
};
);
similarity_binop_impl_all!(
Div, div;
self: IsometryBase<N, D, S, R>, rhs: SimilarityBase<N, D, S, R>, Output = SimilarityBase<N, D, S, R>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.inverse();
[ref ref] => self * rhs.inverse();
);
// SimilarityBase × PointBase
similarity_binop_impl_all!(
Mul, mul;
self: SimilarityBase<N, D, S, R>, right: PointBase<N, D, S>, Output = PointBase<N, D, S>;
[val val] => {
let scaling = self.scaling();
self.isometry.translation * (self.isometry.rotation.transform_point(&right) * scaling)
};
[ref val] => &self.isometry.translation * (self.isometry.rotation.transform_point(&right) * self.scaling());
[val ref] => {
let scaling = self.scaling();
self.isometry.translation * (self.isometry.rotation.transform_point(right) * scaling)
};
[ref ref] => &self.isometry.translation * (self.isometry.rotation.transform_point(right) * self.scaling());
);
// SimilarityBase × Vector
similarity_binop_impl_all!(
Mul, mul;
self: SimilarityBase<N, D, S, R>, right: ColumnVector<N, D, S>, Output = ColumnVector<N, D, S>;
[val val] => self.isometry.rotation.transform_vector(&right) * self.scaling();
[ref val] => self.isometry.rotation.transform_vector(&right) * self.scaling();
[val ref] => self.isometry.rotation.transform_vector(right) * self.scaling();
[ref ref] => self.isometry.rotation.transform_vector(right) * self.scaling();
);
// SimilarityBase × TranslationBase
similarity_binop_impl_all!(
Mul, mul;
self: SimilarityBase<N, D, S, R>, right: TranslationBase<N, D, S>, Output = SimilarityBase<N, D, S, R>;
[val val] => &self * &right;
[ref val] => self * &right;
[val ref] => &self * right;
[ref ref] => {
let shift = self.isometry.rotation.transform_vector(&right.vector) * self.scaling();
SimilarityBase::from_parts(
TranslationBase::from_vector(&self.isometry.translation.vector + shift),
self.isometry.rotation.clone(),
self.scaling())
};
);
// TranslationBase × SimilarityBase
similarity_binop_impl_all!(
Mul, mul;
self: TranslationBase<N, D, S>, right: SimilarityBase<N, D, S, R>, Output = SimilarityBase<N, D, S, R>;
[val val] => {
let scaling = right.scaling();
SimilarityBase::from_isometry(self * right.isometry, scaling)
};
[ref val] => {
let scaling = right.scaling();
SimilarityBase::from_isometry(self * right.isometry, scaling)
};
[val ref] => SimilarityBase::from_isometry(self * &right.isometry, right.scaling());
[ref ref] => SimilarityBase::from_isometry(self * &right.isometry, right.scaling());
);
macro_rules! similarity_from_composition_impl(
($Op: ident, $op: ident;
($R1: ty, $C1: ty),($R2: ty, $C2: ty) $(for $Dims: ident: $DimsBound: ident),*;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
$action: expr; $($lives: tt),*) => {
impl<$($lives ,)* N $(, $Dims: $DimsBound)*, SA, SB> $Op<$Rhs> for $Lhs
where N: Real,
SA: OwnedStorage<N, $R1, $C1>,
SB: OwnedStorage<N, $R2, $C2, Alloc = SA::Alloc>,
SA::Alloc: OwnedAllocator<N, $R1, $C1, SA>,
SB::Alloc: OwnedAllocator<N, $R2, $C2, SB> {
type Output = $Output;
#[inline]
fn $op($lhs, $rhs: $Rhs) -> Self::Output {
$action
}
}
}
);
macro_rules! similarity_from_composition_impl_all(
($Op: ident, $op: ident;
($R1: ty, $C1: ty),($R2: ty, $C2: ty) $(for $Dims: ident: $DimsBound: ident),*;
$lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty;
[val val] => $action_val_val: expr;
[ref val] => $action_ref_val: expr;
[val ref] => $action_val_ref: expr;
[ref ref] => $action_ref_ref: expr;) => {
similarity_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: $Lhs, $rhs: $Rhs, Output = $Output;
$action_val_val; );
similarity_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: &'a $Lhs, $rhs: $Rhs, Output = $Output;
$action_ref_val; 'a);
similarity_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_val_ref; 'b);
similarity_from_composition_impl!(
$Op, $op;
($R1, $C1),($R2, $C2) $(for $Dims: $DimsBound),*;
$lhs: &'a $Lhs, $rhs: &'b $Rhs, Output = $Output;
$action_ref_ref; 'a, 'b);
}
);
// RotationBase × SimilarityBase
similarity_from_composition_impl_all!(
Mul, mul;
(D, D), (D, U1) for D: DimName;
self: RotationBase<N, D, SA>, right: SimilarityBase<N, D, SB, RotationBase<N, D, SA>>,
Output = SimilarityBase<N, D, SB, RotationBase<N, D, SA>>;
[val val] => &self * &right;
[ref val] => self * &right;
[val ref] => &self * right;
[ref ref] => SimilarityBase::from_isometry(self * &right.isometry, right.scaling());
);
// RotationBase ÷ SimilarityBase
similarity_from_composition_impl_all!(
Div, div;
(D, D), (D, U1) for D: DimName;
self: RotationBase<N, D, SA>, right: SimilarityBase<N, D, SB, RotationBase<N, D, SA>>,
Output = SimilarityBase<N, D, SB, RotationBase<N, D, SA>>;
// FIXME: don't call iverse explicitly?
[val val] => self * right.inverse();
[ref val] => self * right.inverse();
[val ref] => self * right.inverse();
[ref ref] => self * right.inverse();
);
// UnitQuaternion × SimilarityBase
similarity_from_composition_impl_all!(
Mul, mul;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, right: SimilarityBase<N, U3, SB, UnitQuaternionBase<N, SA>>,
Output = SimilarityBase<N, U3, SB, UnitQuaternionBase<N, SA>>;
[val val] => &self * &right;
[ref val] => self * &right;
[val ref] => &self * right;
[ref ref] => SimilarityBase::from_isometry(self * &right.isometry, right.scaling());
);
// UnitQuaternion ÷ SimilarityBase
similarity_from_composition_impl_all!(
Div, div;
(U4, U1), (U3, U1);
self: UnitQuaternionBase<N, SA>, right: SimilarityBase<N, U3, SB, UnitQuaternionBase<N, SA>>,
Output = SimilarityBase<N, U3, SB, UnitQuaternionBase<N, SA>>;
// FIXME: don't call inverse explicitly?
[val val] => self * right.inverse();
[ref val] => self * right.inverse();
[val ref] => self * right.inverse();
[ref ref] => self * right.inverse();
);

310
src/geometry/transform.rs Normal file
View File

@ -0,0 +1,310 @@
use std::any::Any;
use std::fmt::Debug;
use std::marker::PhantomData;
use approx::ApproxEq;
use alga::general::Field;
use core::{Scalar, SquareMatrix, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameAdd, DimNameSum, U1};
use core::storage::{Storage, StorageMut};
use core::allocator::Allocator;
/// Trait implemented by phantom types identifying the projective transformation type.
///
/// NOTE: this trait is not intended to be implementable outside of the `nalgebra` crate.
pub trait TCategory: Any + Debug + Copy + PartialEq + Send {
/// Indicates whether a `Transform` with the category `Self` has a bottom-row different from
/// `0 0 .. 1`.
#[inline]
fn has_normalizer() -> bool {
true
}
/// Checks that the given matrix is a valid homogeneous representation of an element of the
/// category `Self`.
fn check_homogeneous_invariants<N, D, S>(mat: &SquareMatrix<N, D, S>) -> bool
where N: Scalar + Field + ApproxEq,
D: DimName,
S: Storage<N, D, D>,
N::Epsilon: Copy;
}
/// Traits that gives the `Transform` category that is compatible with the result of the
/// multiplication of transformations with categories `Self` and `Other`.
pub trait TCategoryMul<Other: TCategory>: TCategory {
/// The transform category that results from the multiplication of a `Transform<Self>` to a
/// `Transform<Other>`. This is usually equal to `Self` or `Other`, whichever is the most
/// general category.
type Representative: TCategory;
}
/// Indicates that `Self` is a more general `Transform` category than `Other`.
pub trait SuperTCategoryOf<Other: TCategory>: TCategory { }
/// Indicates that `Self` is a more specific `Transform` category than `Other`.
///
/// Automatically implemented based on `SuperTCategoryOf`.
pub trait SubTCategoryOf<Other: TCategory>: TCategory { }
impl<T1, T2> SubTCategoryOf<T2> for T1
where T1: TCategory,
T2: SuperTCategoryOf<T1> {
}
/// Tag representing the most general (not necessarily inversible) `Transform` type.
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub enum TGeneral { }
/// Tag representing the most general inversible `Transform` type.
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub enum TProjective { }
/// Tag representing an affine `Transform`. Its bottom-row is equal to `(0, 0 ... 0, 1)`.
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub enum TAffine { }
impl TCategory for TGeneral {
#[inline]
fn check_homogeneous_invariants<N, D, S>(_: &SquareMatrix<N, D, S>) -> bool
where N: Scalar + Field + ApproxEq,
D: DimName,
S: Storage<N, D, D>,
N::Epsilon: Copy {
true
}
}
impl TCategory for TProjective {
#[inline]
fn check_homogeneous_invariants<N, D, S>(mat: &SquareMatrix<N, D, S>) -> bool
where N: Scalar + Field + ApproxEq,
D: DimName,
S: Storage<N, D, D>,
N::Epsilon: Copy {
mat.is_invertible()
}
}
impl TCategory for TAffine {
#[inline]
fn has_normalizer() -> bool {
false
}
#[inline]
fn check_homogeneous_invariants<N, D, S>(mat: &SquareMatrix<N, D, S>) -> bool
where N: Scalar + Field + ApproxEq,
D: DimName,
S: Storage<N, D, D>,
N::Epsilon: Copy {
mat.is_invertible() &&
mat[(D::dim(), D::dim())] == N::one() &&
(0 .. D::dim()).all(|i| mat[(D::dim(), i)].is_zero())
}
}
macro_rules! category_mul_impl(
($($a: ident * $b: ident => $c: ty);* $(;)*) => {$(
impl TCategoryMul<$a> for $b {
type Representative = $c;
}
)*}
);
// We require stability uppon multiplication.
impl<T: TCategory> TCategoryMul<T> for T {
type Representative = T;
}
category_mul_impl!(
// TGeneral * TGeneral => TGeneral;
TGeneral * TProjective => TGeneral;
TGeneral * TAffine => TGeneral;
TProjective * TGeneral => TGeneral;
// TProjective * TProjective => TProjective;
TProjective * TAffine => TProjective;
TAffine * TGeneral => TGeneral;
TAffine * TProjective => TProjective;
// TAffine * TAffine => TAffine;
);
macro_rules! super_tcategory_impl(
($($a: ident >= $b: ident);* $(;)*) => {$(
impl SuperTCategoryOf<$b> for $a { }
)*}
);
impl<T: TCategory> SuperTCategoryOf<T> for T { }
super_tcategory_impl!(
TGeneral >= TProjective;
TGeneral >= TAffine;
TProjective >= TAffine;
);
/// A transformation matrix that owns its data.
pub type OwnedTransform<N, D, A, C>
= TransformBase<N, D, <A as Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>>>::Buffer, C>;
/// A transformation matrix in homogeneous coordinates.
///
/// It is stored as a matrix with dimensions `(D + 1, D + 1)`, e.g., it stores a 4x4 matrix for a
/// 3D transformation.
#[repr(C)]
#[derive(Debug, Clone, Copy)] // FIXME: Hash
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct TransformBase<N: Scalar, D: DimNameAdd<U1>, S, C: TCategory> {
matrix: SquareMatrix<N, DimNameSum<D, U1>, S>,
#[cfg_attr(feature = "serde-serialize", serde(skip_serializing, skip_deserializing))]
_phantom: PhantomData<C>
}
// XXX: for some reasons, implementing Clone and Copy manually causes an ICE…
impl<N, D, S, C: TCategory> Eq for TransformBase<N, D, S, C>
where N: Scalar + Eq,
D: DimNameAdd<U1>,
S: Storage<N, DimNameSum<D, U1>, DimNameSum<D, U1>> { }
impl<N, D, S, C: TCategory> PartialEq for TransformBase<N, D, S, C>
where N: Scalar,
D: DimNameAdd<U1>,
S: Storage<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
#[inline]
fn eq(&self, right: &Self) -> bool {
self.matrix == right.matrix
}
}
impl<N, D, S, C: TCategory> TransformBase<N, D, S, C>
where N: Scalar,
D: DimNameAdd<U1>,
S: Storage<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
/// Creates a new transformation from the given homogeneous matrix. The transformation category
/// of `Self` is not checked to be verified by the given matrix.
#[inline]
pub fn from_matrix_unchecked(matrix: SquareMatrix<N, DimNameSum<D, U1>, S>) -> Self {
TransformBase {
matrix: matrix,
_phantom: PhantomData
}
}
/// Moves this transform into one that owns its data.
#[inline]
pub fn into_owned(self) -> OwnedTransform<N, D, S::Alloc, C> {
TransformBase::from_matrix_unchecked(self.matrix.into_owned())
}
/// Clones this transform into one that owns its data.
#[inline]
pub fn clone_owned(&self) -> OwnedTransform<N, D, S::Alloc, C> {
TransformBase::from_matrix_unchecked(self.matrix.clone_owned())
}
/// The underlying matrix.
#[inline]
pub fn unwrap(self) -> SquareMatrix<N, DimNameSum<D, U1>, S> {
self.matrix
}
/// A reference to the underlynig matrix.
#[inline]
pub fn matrix(&self) -> &SquareMatrix<N, DimNameSum<D, U1>, S> {
&self.matrix
}
/// A mutable reference to the underlying matrix.
///
/// It is `_unchecked` because direct modifications of this matrix may break invariants
/// identified by this transformation category.
#[inline]
pub fn matrix_mut_unchecked(&mut self) -> &mut SquareMatrix<N, DimNameSum<D, U1>, S> {
&mut self.matrix
}
/// Sets the category of this transform.
///
/// This can be done only if the new category is more general than the current one, e.g., a
/// transform with category `TProjective` cannot be converted to a transform with category
/// `TAffine` because not all projective transformations are affine (the other way-round is
/// valid though).
#[inline]
pub fn set_category<CNew: SuperTCategoryOf<C>>(self) -> TransformBase<N, D, S, CNew> {
TransformBase::from_matrix_unchecked(self.matrix)
}
/// Converts this transform into its equivalent homogeneous transformation matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc> {
self.matrix().clone_owned()
}
}
impl<N, D, S, C> TransformBase<N, D, S, C>
where N: Scalar + Field + ApproxEq,
D: DimNameAdd<U1>,
C: TCategory,
S: Storage<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
/// Attempts to invert this transformation. You may use `.inverse` instead of this
/// transformation has a subcategory of `TProjective`.
#[inline]
pub fn try_inverse(self) -> Option<OwnedTransform<N, D, S::Alloc, C>> {
if let Some(m) = self.matrix.try_inverse() {
Some(TransformBase::from_matrix_unchecked(m))
}
else {
None
}
}
/// Inverts this transformation. Use `.try_inverse` if this transform has the `TGeneral`
/// category (it may not be invertible).
#[inline]
pub fn inverse(self) -> OwnedTransform<N, D, S::Alloc, C>
where C: SubTCategoryOf<TProjective> {
// FIXME: specialize for TAffine?
TransformBase::from_matrix_unchecked(self.matrix.try_inverse().unwrap())
}
}
impl<N, D, S, C> TransformBase<N, D, S, C>
where N: Scalar + Field + ApproxEq,
D: DimNameAdd<U1>,
C: TCategory,
S: StorageMut<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
/// Attempts to invert this transformation in-place. You may use `.inverse_mut` instead of this
/// transformation has a subcategory of `TProjective`.
#[inline]
pub fn try_inverse_mut(&mut self) -> bool {
self.matrix.try_inverse_mut()
}
/// Inverts this transformation in-place. Use `.try_inverse_mut` if this transform has the
/// `TGeneral` category (it may not be invertible).
#[inline]
pub fn inverse_mut(&mut self)
where C: SubTCategoryOf<TProjective> {
let _ = self.matrix.try_inverse_mut();
}
}
impl<N, D, S> TransformBase<N, D, S, TGeneral>
where N: Scalar,
D: DimNameAdd<U1>,
S: Storage<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
/// A mutable reference to underlying matrix. Use `.matrix_mut_unchecked` instead if this
/// transformation category is not `TGeneral`.
#[inline]
pub fn matrix_mut(&mut self) -> &mut SquareMatrix<N, DimNameSum<D, U1>, S> {
self.matrix_mut_unchecked()
}
}

View File

@ -0,0 +1,157 @@
use approx::ApproxEq;
use alga::general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
AbstractSemigroup, Field, Real, Inverse, Multiplicative, Identity};
use alga::linear::{Transformation, ProjectiveTransformation};
use core::{Scalar, ColumnVector};
use core::dimension::{DimNameSum, DimNameAdd, U1};
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, TransformBase, TCategory, SubTCategoryOf, TProjective};
/*
*
* Algebraic structures.
*
*/
impl<N, D: DimNameAdd<U1>, S, C> Identity<Multiplicative> for TransformBase<N, D, S, C>
where N: Scalar + Field,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: TCategory,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, D: DimNameAdd<U1>, S, C> Inverse<Multiplicative> for TransformBase<N, D, S, C>
where N: Scalar + Field + ApproxEq,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SubTCategoryOf<TProjective>,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
#[inline]
fn inverse(&self) -> Self {
self.clone().inverse()
}
#[inline]
fn inverse_mut(&mut self) {
self.inverse_mut()
}
}
impl<N, D: DimNameAdd<U1>, S, C> AbstractMagma<Multiplicative> for TransformBase<N, D, S, C>
where N: Scalar + Field,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: TCategory,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
macro_rules! impl_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimNameAdd<U1>, S, C> $marker<$operator> for TransformBase<N, D, S, C>
where N: Scalar + Field,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: TCategory,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> { }
)*}
);
macro_rules! impl_inversible_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimNameAdd<U1>, S, C> $marker<$operator> for TransformBase<N, D, S, C>
where N: Scalar + Field + ApproxEq,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SubTCategoryOf<TProjective>,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> { }
)*}
);
impl_multiplicative_structures!(
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
);
impl_inversible_multiplicative_structures!(
AbstractQuasigroup<Multiplicative>,
AbstractLoop<Multiplicative>,
AbstractGroup<Multiplicative>
);
/*
*
* Transformation groups.
*
*/
impl<N, D: DimNameAdd<U1>, SA, SB, C> Transformation<PointBase<N, D, SB>> for TransformBase<N, D, SA, C>
where N: Real,
SA: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
C: TCategory,
SA::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, SA> +
Allocator<N, D, D> +
Allocator<N, D, U1> +
Allocator<N, U1, D>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
#[inline]
fn transform_point(&self, pt: &PointBase<N, D, SB>) -> PointBase<N, D, SB> {
self * pt
}
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, D, SB>) -> ColumnVector<N, D, SB> {
self * v
}
}
impl<N, D: DimNameAdd<U1>, SA, SB, C> ProjectiveTransformation<PointBase<N, D, SB>> for TransformBase<N, D, SA, C>
where N: Real,
SA: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
C: SubTCategoryOf<TProjective>,
SA::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, SA> +
Allocator<N, D, D> +
Allocator<N, D, U1> +
Allocator<N, U1, D>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
#[inline]
fn inverse_transform_point(&self, pt: &PointBase<N, D, SB>) -> PointBase<N, D, SB> {
self.inverse() * pt
}
#[inline]
fn inverse_transform_vector(&self, v: &ColumnVector<N, D, SB>) -> ColumnVector<N, D, SB> {
self.inverse() * v
}
}
// FIXME: we need to implement an SVD for this.
//
// impl<N, D: DimNameAdd<U1>, SA, SB, C> AffineTransformation<PointBase<N, D, SB>> for TransformBase<N, D, SA, C>
// where N: Real,
// SA: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
// SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
// C: SubTCategoryOf<TAffine>,
// SA::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, SA> +
// Allocator<N, D, D> +
// Allocator<N, D, U1> +
// Allocator<N, U1, D>,
// SB::Alloc: OwnedAllocator<N, D, U1, SB> {
// type PreRotation = OwnedRotation<N, D, SA::Alloc>;
// type NonUniformScaling = OwnedColumnVector<N, D, SA::Alloc>;
// type PostRotation = OwnedRotation<N, D, SA::Alloc>;
// type Translation = OwnedTranslation<N, D, SA::Alloc>;
//
// #[inline]
// fn decompose(&self) -> (Self::Translation, Self::PostRotation, Self::NonUniformScaling, Self::PreRotation) {
// unimplemented!()
// }
// }

View File

@ -0,0 +1,29 @@
use core::MatrixArray;
use core::dimension::{U1, U2, U3, DimNameSum};
use geometry::{TransformBase, TGeneral, TProjective, TAffine};
/// A `D`-dimensional general transformation that may not be inversible. Stored as an homogeneous
/// `(D + 1) × (D + 1)` matrix.
pub type Transform<N, D> = TransformBase<N, D, MatrixArray<N, DimNameSum<D, U1>, DimNameSum<D, U1>>, TGeneral>;
/// An inversible `D`-dimensional general transformation. Stored as an homogeneous
/// `(D + 1) × (D + 1)` matrix.
pub type Projective<N, D> = TransformBase<N, D, MatrixArray<N, DimNameSum<D, U1>, DimNameSum<D, U1>>, TProjective>;
/// A `D`-dimensional affine transformation. Stored as an homogeneous `(D + 1) × (D + 1)` matrix.
pub type Affine<N, D> = TransformBase<N, D, MatrixArray<N, DimNameSum<D, U1>, DimNameSum<D, U1>>, TAffine>;
/// A 2D general transformation that may not be inversible. Stored as an homogeneous 3x3 matrix.
pub type Transform2<N> = Transform<N, U2>;
/// An inversible 2D general transformation. Stored as an homogeneous 3x3 matrix.
pub type Projective2<N> = Projective<N, U2>;
/// A 2D affine transformation. Stored as an homogeneous 3x3 matrix.
pub type Affine2<N> = Affine<N, U2>;
/// A 3D general transformation that may not be inversible. Stored as an homogeneous 4x4 matrix.
pub type Transform3<N> = Transform<N, U3>;
/// An inversible 3D general transformation. Stored as an homogeneous 4x4 matrix.
pub type Projective3<N> = Projective<N, U3>;
/// A 3D affine transformation. Stored as an homogeneous 4x4 matrix.
pub type Affine3<N> = Affine<N, U3>;

View File

@ -0,0 +1,36 @@
use num::{Zero, One};
use alga::general::Field;
use core::{Scalar, OwnedSquareMatrix};
use core::dimension::{DimNameAdd, DimNameSum, U1};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{TransformBase, TCategory};
impl<N, D, S, C: TCategory> TransformBase<N, D, S, C>
where N: Scalar + Zero + One,
D: DimNameAdd<U1>,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
/// Creates a new identity transform.
#[inline]
pub fn identity() -> Self {
Self::from_matrix_unchecked(OwnedSquareMatrix::<N, _, S::Alloc>::identity())
}
}
impl<N, D, S, C: TCategory> One for TransformBase<N, D, S, C>
where N: Scalar + Field,
D: DimNameAdd<U1>,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
/// Creates a new identity transform.
#[inline]
fn one() -> Self {
Self::identity()
}
}

View File

@ -0,0 +1,67 @@
use approx::ApproxEq;
use alga::general::{SubsetOf, Field};
use core::{Scalar, SquareMatrix};
use core::dimension::{DimName, DimNameAdd, DimNameSum, U1};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{TransformBase, TCategory, SuperTCategoryOf};
impl<N1, N2, D: DimName, SA, SB, C1, C2> SubsetOf<TransformBase<N2, D, SB, C2>> for TransformBase<N1, D, SA, C1>
where N1: Scalar + Field + ApproxEq + SubsetOf<N2>,
N2: Scalar + Field + ApproxEq,
C1: TCategory,
C2: SuperTCategoryOf<C1>,
D: DimNameAdd<U1>,
SA: OwnedStorage<N1, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SA::Alloc: OwnedAllocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>, SA>,
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB>,
N1::Epsilon: Copy,
N2::Epsilon: Copy {
#[inline]
fn to_superset(&self) -> TransformBase<N2, D, SB, C2> {
TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset())
}
#[inline]
fn is_in_subset(t: &TransformBase<N2, D, SB, C2>) -> bool {
<Self as SubsetOf<_>>::is_in_subset(t.matrix())
}
#[inline]
unsafe fn from_superset_unchecked(t: &TransformBase<N2, D, SB, C2>) -> Self {
Self::from_superset_unchecked(t.matrix())
}
}
impl<N1, N2, D: DimName, SA, SB, C> SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>> for TransformBase<N1, D, SA, C>
where N1: Scalar + Field + ApproxEq + SubsetOf<N2>,
N2: Scalar + Field + ApproxEq,
C: TCategory,
D: DimNameAdd<U1>,
SA: OwnedStorage<N1, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SA::Alloc: OwnedAllocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>, SA>,
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB>,
N1::Epsilon: Copy,
N2::Epsilon: Copy {
#[inline]
fn to_superset(&self) -> SquareMatrix<N2, DimNameSum<D, U1>, SB> {
self.matrix().to_superset()
}
#[inline]
fn is_in_subset(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> bool {
C::check_homogeneous_invariants(m)
}
#[inline]
unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> Self {
TransformBase::from_matrix_unchecked(::convert_ref_unchecked(m))
}
}

View File

@ -0,0 +1,615 @@
use num::{Zero, One};
use std::ops::{Index, IndexMut, Mul, MulAssign, Div, DivAssign};
use approx::ApproxEq;
use alga::general::{Field, Real, ClosedAdd, ClosedMul, ClosedNeg, SubsetOf};
use core::{Scalar, ColumnVector, OwnedColumnVector, OwnedSquareMatrix};
use core::storage::{Storage, StorageMut, OwnedStorage};
use core::allocator::{Allocator, OwnedAllocator};
use core::dimension::{DimName, DimNameAdd, DimNameSum, U1, U3, U4};
use geometry::{PointBase, OwnedPoint, TransformBase, OwnedTransform, TCategory, TCategoryMul,
SubTCategoryOf, SuperTCategoryOf, TGeneral, TProjective, TAffine, RotationBase,
UnitQuaternionBase, IsometryBase, SimilarityBase, TranslationBase};
/*
*
* In the following, we provide:
* =========================
*
* Index<(usize, usize)>
* IndexMut<(usize, usize)> (where TCategory == TGeneral)
*
* (Operators)
*
* TransformBase × IsometryBase
* TransformBase × RotationBase
* TransformBase × SimilarityBase
* TransformBase × TransformBase
* TransformBase × UnitQuaternion
* FIXME: TransformBase × UnitComplex
* TransformBase × TranslationBase
* TransformBase × ColumnVector
* TransformBase × PointBase
*
* IsometryBase × TransformBase
* RotationBase × TransformBase
* SimilarityBase × TransformBase
* TranslationBase × TransformBase
* UnitQuaternionBase × TransformBase
* FIXME: UnitComplex × TransformBase
*
* FIXME: TransformBase ÷ IsometryBase
* TransformBase ÷ RotationBase
* FIXME: TransformBase ÷ SimilarityBase
* TransformBase ÷ TransformBase
* TransformBase ÷ UnitQuaternion
* TransformBase ÷ TranslationBase
*
* FIXME: IsometryBase ÷ TransformBase
* RotationBase ÷ TransformBase
* FIXME: SimilarityBase ÷ TransformBase
* TranslationBase ÷ TransformBase
* UnitQuaternionBase ÷ TransformBase
* FIXME: UnitComplex ÷ TransformBase
*
*
* (Assignment Operators)
*
*
* TransformBase ×= TransformBase
* TransformBase ×= SimilarityBase
* TransformBase ×= IsometryBase
* TransformBase ×= RotationBase
* TransformBase ×= UnitQuaternionBase
* FIXME: TransformBase ×= UnitComplex
* TransformBase ×= TranslationBase
*
* TransformBase ÷= TransformBase
* FIXME: TransformBase ÷= SimilarityBase
* FIXME: TransformBase ÷= IsometryBase
* TransformBase ÷= RotationBase
* TransformBase ÷= UnitQuaternionBase
* FIXME: TransformBase ÷= UnitComplex
*
*/
/*
*
* Indexing.
*
*/
impl<N, D, S, C: TCategory> Index<(usize, usize)> for TransformBase<N, D, S, C>
where N: Scalar,
D: DimName + DimNameAdd<U1>,
S: Storage<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
type Output = N;
#[inline]
fn index(&self, ij: (usize, usize)) -> &N {
self.matrix().index(ij)
}
}
// Only general transformations are mutably indexable.
impl<N, D, S> IndexMut<(usize, usize)> for TransformBase<N, D, S, TGeneral>
where N: Scalar,
D: DimName + DimNameAdd<U1>,
S: StorageMut<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
#[inline]
fn index_mut(&mut self, ij: (usize, usize)) -> &mut N {
self.matrix_mut().index_mut(ij)
}
}
// TransformBase × ColumnVector
md_impl_all!(
Mul, mul where N: Field;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1) for D: DimNameAdd<U1>, C: TCategory
where SA::Alloc: Allocator<N, D, D>
where SA::Alloc: Allocator<N, D, U1>
where SA::Alloc: Allocator<N, U1, D>;
self: TransformBase<N, D, SA, C>, rhs: ColumnVector<N, D, SB>, Output = OwnedColumnVector<N, D, SA::Alloc>;
[val val] => &self * &rhs;
[ref val] => self * &rhs;
[val ref] => &self * rhs;
[ref ref] => {
let transform = self.matrix().fixed_slice::<D, D>(0, 0);
if C::has_normalizer() {
let normalizer = self.matrix().fixed_slice::<U1, D>(D::dim(), 0);
let n = normalizer.tr_dot(&rhs);
if !n.is_zero() {
return transform * (rhs / n);
}
}
transform * rhs
};
);
// TransformBase × PointBase
md_impl_all!(
Mul, mul where N: Field;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1) for D: DimNameAdd<U1>, C: TCategory
where SA::Alloc: Allocator<N, D, D>
where SA::Alloc: Allocator<N, D, U1>
where SA::Alloc: Allocator<N, U1, D>;
self: TransformBase<N, D, SA, C>, rhs: PointBase<N, D, SB>, Output = OwnedPoint<N, D, SA::Alloc>;
[val val] => &self * &rhs;
[ref val] => self * &rhs;
[val ref] => &self * rhs;
[ref ref] => {
let transform = self.matrix().fixed_slice::<D, D>(0, 0);
let translation = self.matrix().fixed_slice::<D, U1>(0, D::dim());
if C::has_normalizer() {
let normalizer = self.matrix().fixed_slice::<U1, D>(D::dim(), 0);
let n = normalizer.tr_dot(&rhs.coords) + unsafe { *self.matrix().get_unchecked(D::dim(), D::dim()) };
if !n.is_zero() {
return transform * (rhs / n) + translation;
}
}
transform * rhs + translation
};
);
// TransformBase × TransformBase
md_impl_all!(
Mul, mul;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (DimNameSum<D, U1>, DimNameSum<D, U1>) for D: DimNameAdd<U1>, CA: TCategoryMul<CB>, CB: TCategory;
self: TransformBase<N, D, SA, CA>, rhs: TransformBase<N, D, SB, CB>, Output = OwnedTransform<N, D, SA::Alloc, CA::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.unwrap());
[ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.unwrap());
[val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.matrix());
[ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.matrix());
);
// TransformBase × RotationBase
md_impl_all!(
Mul, mul where N: One;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, D) for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: RotationBase<N, D, SB>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
[val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
);
// RotationBase × TransformBase
md_impl_all!(
Mul, mul where N: One;
(D, D), (DimNameSum<D, U1>, DimNameSum<D, U1>) for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: RotationBase<N, D, SA>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[ref val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[val ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
[ref ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
);
// TransformBase × UnitQuaternionBase
md_impl_all!(
Mul, mul where N: Real;
(U4, U4), (U4, U1) for C: TCategoryMul<TAffine>
where SB::Alloc: Allocator<N, U3, U3>
where SB::Alloc: Allocator<N, U4, U4>;
self: TransformBase<N, U3, SA, C>, rhs: UnitQuaternionBase<N, SB>, Output = OwnedTransform<N, U3, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
[val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
);
// UnitQuaternionBase × TransformBase
md_impl_all!(
Mul, mul where N: Real;
(U4, U1), (U4, U4) for C: TCategoryMul<TAffine>
where SA::Alloc: Allocator<N, U3, U3>
where SA::Alloc: Allocator<N, U4, U4>;
self: UnitQuaternionBase<N, SA>, rhs: TransformBase<N, U3, SB, C>, Output = OwnedTransform<N, U3, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[ref val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[val ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
[ref ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
);
// TransformBase × IsometryBase
md_impl_all!(
Mul, mul where N: Real;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: IsometryBase<N, D, SB, R>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
[val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
);
// IsometryBase × TransformBase
md_impl_all!(
Mul, mul where N: Real;
(D, U1), (DimNameSum<D, U1>, DimNameSum<D, U1>)
for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SA::Alloc> >
where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: IsometryBase<N, D, SA, R>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[ref val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[val ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
[ref ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
);
// TransformBase × SimilarityBase
md_impl_all!(
Mul, mul where N: Real;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
where SB::Alloc: Allocator<N, D, D >
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: SimilarityBase<N, D, SB, R>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
[val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
);
// SimilarityBase × TransformBase
md_impl_all!(
Mul, mul where N: Real;
(D, U1), (DimNameSum<D, U1>, DimNameSum<D, U1>)
for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SA::Alloc> >
where SA::Alloc: Allocator<N, D, D >
where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: SimilarityBase<N, D, SA, R>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[ref val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[val ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
[ref ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
);
/*
*
* FIXME: don't explicitly build the homogeneous translation matrix.
* Directly apply the translation, just as in `Matrix::{append,prepend}_translation`. This has not
* been done yet because of the `DimNameDiff` requirement (which is not automatically deduced from
* `DimNameAdd` requirement).
*
*/
// TransformBase × TranslationBase
md_impl_all!(
Mul, mul where N: Real;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1) for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: TranslationBase<N, D, SB>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
[val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
[ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
);
// TranslationBase × TransformBase
md_impl_all!(
Mul, mul where N: Real;
(D, U1), (DimNameSum<D, U1>, DimNameSum<D, U1>)
for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TranslationBase<N, D, SA>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[ref val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
[val ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
[ref ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
);
// TransformBase ÷ TransformBase
md_impl_all!(
Div, div where N: ApproxEq, Field;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (DimNameSum<D, U1>, DimNameSum<D, U1>) for D: DimNameAdd<U1>, CA: TCategoryMul<CB>, CB: SubTCategoryOf<TProjective>;
self: TransformBase<N, D, SA, CA>, rhs: TransformBase<N, D, SB, CB>, Output = OwnedTransform<N, D, SA::Alloc, CA::Representative>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.clone_owned().inverse();
[ref ref] => self * rhs.clone_owned().inverse();
);
// TransformBase ÷ RotationBase
md_impl_all!(
Div, div where N: One;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, D) for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: RotationBase<N, D, SB>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.inverse();
[ref ref] => self * rhs.inverse();
);
// RotationBase ÷ TransformBase
md_impl_all!(
Div, div where N: One;
(D, D), (DimNameSum<D, U1>, DimNameSum<D, U1>) for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: RotationBase<N, D, SA>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => self.inverse() * rhs;
[ref val] => self.inverse() * rhs;
[val ref] => self.inverse() * rhs;
[ref ref] => self.inverse() * rhs;
);
// TransformBase ÷ UnitQuaternionBase
md_impl_all!(
Div, div where N: Real;
(U4, U4), (U4, U1) for C: TCategoryMul<TAffine>
where SB::Alloc: Allocator<N, U3, U3>
where SB::Alloc: Allocator<N, U4, U4>;
self: TransformBase<N, U3, SA, C>, rhs: UnitQuaternionBase<N, SB>, Output = OwnedTransform<N, U3, SA::Alloc, C::Representative>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.inverse();
[ref ref] => self * rhs.inverse();
);
// UnitQuaternionBase ÷ TransformBase
md_impl_all!(
Div, div where N: Real;
(U4, U1), (U4, U4) for C: TCategoryMul<TAffine>
where SA::Alloc: Allocator<N, U3, U3>
where SA::Alloc: Allocator<N, U4, U4>;
self: UnitQuaternionBase<N, SA>, rhs: TransformBase<N, U3, SB, C>, Output = OwnedTransform<N, U3, SA::Alloc, C::Representative>;
[val val] => self.inverse() * rhs;
[ref val] => self.inverse() * rhs;
[val ref] => self.inverse() * rhs;
[ref ref] => self.inverse() * rhs;
);
// // TransformBase ÷ IsometryBase
// md_impl_all!(
// Div, div where N: Real;
// (DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
// for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
// where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
// self: TransformBase<N, D, SA, C>, rhs: IsometryBase<N, D, SB, R>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
// [val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.inverse().to_homogeneous());
// [ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.inverse().to_homogeneous());
// [val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.inverse().to_homogeneous());
// [ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.inverse().to_homogeneous());
// );
// // IsometryBase ÷ TransformBase
// md_impl_all!(
// Div, div where N: Real;
// (D, U1), (DimNameSum<D, U1>, DimNameSum<D, U1>)
// for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SA::Alloc> >
// where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
// self: IsometryBase<N, D, SA, R>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
// [val val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
// [ref val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
// [val ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
// [ref ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
// );
// // TransformBase ÷ SimilarityBase
// md_impl_all!(
// Div, div where N: Real;
// (DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
// for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
// where SB::Alloc: Allocator<N, D, D >
// where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
// self: TransformBase<N, D, SA, C>, rhs: SimilarityBase<N, D, SB, R>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
// [val val] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
// [ref val] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
// [val ref] => Self::Output::from_matrix_unchecked(self.unwrap() * rhs.to_homogeneous());
// [ref ref] => Self::Output::from_matrix_unchecked(self.matrix() * rhs.to_homogeneous());
// );
// // SimilarityBase ÷ TransformBase
// md_impl_all!(
// Div, div where N: Real;
// (D, U1), (DimNameSum<D, U1>, DimNameSum<D, U1>)
// for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SA::Alloc> >
// where SA::Alloc: Allocator<N, D, D >
// where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
// self: SimilarityBase<N, D, SA, R>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
// [val val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
// [ref val] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.unwrap());
// [val ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
// [ref ref] => Self::Output::from_matrix_unchecked(self.to_homogeneous() * rhs.matrix());
// );
// TransformBase ÷ TranslationBase
md_impl_all!(
Div, div where N: Real;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1) for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: TranslationBase<N, D, SB>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => self * rhs.inverse();
[ref val] => self * rhs.inverse();
[val ref] => self * rhs.inverse();
[ref ref] => self * rhs.inverse();
);
// TranslationBase ÷ TransformBase
md_impl_all!(
Div, div where N: Real;
(D, U1), (DimNameSum<D, U1>, DimNameSum<D, U1>)
for D: DimNameAdd<U1>, C: TCategoryMul<TAffine>
where SA::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TranslationBase<N, D, SA>, rhs: TransformBase<N, D, SB, C>, Output = OwnedTransform<N, D, SA::Alloc, C::Representative>;
[val val] => self.inverse() * rhs;
[ref val] => self.inverse() * rhs;
[val ref] => self.inverse() * rhs;
[ref ref] => self.inverse() * rhs;
);
// TransformBase ×= TransformBase
md_assign_impl_all!(
MulAssign, mul_assign;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (DimNameSum<D, U1>, DimNameSum<D, U1>) for D: DimNameAdd<U1>, CA: TCategory, CB: SubTCategoryOf<CA>;
self: TransformBase<N, D, SA, CA>, rhs: TransformBase<N, D, SB, CB>;
[val] => *self.matrix_mut_unchecked() *= rhs.unwrap();
[ref] => *self.matrix_mut_unchecked() *= rhs.matrix();
);
// TransformBase ×= SimilarityBase
md_assign_impl_all!(
MulAssign, mul_assign;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
for D: DimNameAdd<U1>, C: TCategory, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >
where SB::Alloc: Allocator<N, D, D>;
self: TransformBase<N, D, SA, C>, rhs: SimilarityBase<N, D, SB, R>;
[val] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
[ref] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
);
// TransformBase ×= IsometryBase
md_assign_impl_all!(
MulAssign, mul_assign;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
for D: DimNameAdd<U1>, C: TCategory, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: IsometryBase<N, D, SB, R>;
[val] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
[ref] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
);
/*
*
* FIXME: don't explicitly build the homogeneous translation matrix.
* Directly apply the translation, just as in `Matrix::{append,prepend}_translation`. This has not
* been done yet because of the `DimNameDiff` requirement (which is not automatically deduced from
* `DimNameAdd` requirement).
*
*/
// TransformBase ×= TranslationBase
md_assign_impl_all!(
MulAssign, mul_assign where N: One;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1) for D: DimNameAdd<U1>, C: TCategory
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: TranslationBase<N, D, SB>;
[val] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
[ref] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
);
// TransformBase ×= RotationBase
md_assign_impl_all!(
MulAssign, mul_assign where N: One;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, D) for D: DimNameAdd<U1>, C: TCategory
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: RotationBase<N, D, SB>;
[val] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
[ref] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
);
// TransformBase ×= UnitQuaternionBase
md_assign_impl_all!(
MulAssign, mul_assign where N: Real;
(U4, U4), (U4, U1) for C: TCategory
where SB::Alloc: Allocator<N, U3, U3>
where SB::Alloc: Allocator<N, U4, U4>;
self: TransformBase<N, U3, SA, C>, rhs: UnitQuaternionBase<N, SB>;
[val] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
[ref] => *self.matrix_mut_unchecked() *= rhs.to_homogeneous();
);
// TransformBase ÷= TransformBase
md_assign_impl_all!(
DivAssign, div_assign where N: Field, ApproxEq;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (DimNameSum<D, U1>, DimNameSum<D, U1>)
for D: DimNameAdd<U1>, CA: SuperTCategoryOf<CB>, CB: SubTCategoryOf<TProjective>;
self: TransformBase<N, D, SA, CA>, rhs: TransformBase<N, D, SB, CB>;
[val] => *self *= rhs.clone_owned().inverse();
[ref] => *self *= rhs.clone_owned().inverse();
);
// // TransformBase ÷= SimilarityBase
// md_assign_impl_all!(
// DivAssign, div_assign;
// (DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
// for D: DimNameAdd<U1>, C: TCategory, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
// where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >
// where SB::Alloc: Allocator<N, D, D>;
// self: TransformBase<N, D, SA, C>, rhs: SimilarityBase<N, D, SB, R>;
// [val] => *self *= rhs.inverse();
// [ref] => *self *= rhs.inverse();
// );
//
//
// // TransformBase ÷= IsometryBase
// md_assign_impl_all!(
// DivAssign, div_assign;
// (DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1)
// for D: DimNameAdd<U1>, C: TCategory, R: SubsetOf<OwnedSquareMatrix<N, DimNameSum<D, U1>, SB::Alloc> >
// where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
// self: TransformBase<N, D, SA, C>, rhs: IsometryBase<N, D, SB, R>;
// [val] => *self *= rhs.inverse();
// [ref] => *self *= rhs.inverse();
// );
// TransformBase ÷= TranslationBase
md_assign_impl_all!(
DivAssign, div_assign where N: One, ClosedNeg;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, U1) for D: DimNameAdd<U1>, C: TCategory
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: TranslationBase<N, D, SB>;
[val] => *self *= rhs.inverse();
[ref] => *self *= rhs.inverse();
);
// TransformBase ÷= RotationBase
md_assign_impl_all!(
DivAssign, div_assign where N: One;
(DimNameSum<D, U1>, DimNameSum<D, U1>), (D, D) for D: DimNameAdd<U1>, C: TCategory
where SB::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1> >;
self: TransformBase<N, D, SA, C>, rhs: RotationBase<N, D, SB>;
[val] => *self *= rhs.inverse();
[ref] => *self *= rhs.inverse();
);
// TransformBase ÷= UnitQuaternionBase
md_assign_impl_all!(
DivAssign, div_assign where N: Real;
(U4, U4), (U4, U1) for C: TCategory
where SB::Alloc: Allocator<N, U3, U3>
where SB::Alloc: Allocator<N, U4, U4>;
self: TransformBase<N, U3, SA, C>, rhs: UnitQuaternionBase<N, SB>;
[val] => *self *= rhs.inverse();
[ref] => *self *= rhs.inverse();
);

145
src/geometry/translation.rs Normal file
View File

@ -0,0 +1,145 @@
use num::{Zero, One};
use std::fmt;
use approx::ApproxEq;
use alga::general::{Real, ClosedNeg};
use core::{Scalar, ColumnVector, OwnedSquareMatrix};
use core::dimension::{DimName, DimNameSum, DimNameAdd, U1};
use core::storage::{Storage, StorageMut, Owned};
use core::allocator::Allocator;
/// A translation with an owned vector storage.
pub type OwnedTranslation<N, D, S> = TranslationBase<N, D, Owned<N, D, U1, <S as Storage<N, D, U1>>::Alloc>>;
/// A translation.
#[repr(C)]
#[derive(Hash, Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct TranslationBase<N: Scalar, D: DimName, S/*: Storage<N, D, U1>*/> {
/// The translation coordinates, i.e., how much is added to a point's coordinates when it is
/// translated.
pub vector: ColumnVector<N, D, S>
}
impl<N, D: DimName, S> TranslationBase<N, D, S>
where N: Scalar,
S: Storage<N, D, U1> {
/// Creates a new translation from the given vector.
#[inline]
pub fn from_vector(vector: ColumnVector<N, D, S>) -> TranslationBase<N, D, S> {
TranslationBase {
vector: vector
}
}
/// Inverts `self`.
#[inline]
pub fn inverse(&self) -> OwnedTranslation<N, D, S>
where N: ClosedNeg {
TranslationBase::from_vector(-&self.vector)
}
/// Converts this translation into its equivalent homogeneous transformation matrix.
#[inline]
pub fn to_homogeneous(&self) -> OwnedSquareMatrix<N, DimNameSum<D, U1>, S::Alloc>
where N: Zero + One,
D: DimNameAdd<U1>,
S::Alloc: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>> {
let mut res = OwnedSquareMatrix::<N, _, S::Alloc>::identity();
res.fixed_slice_mut::<D, U1>(0, D::dim()).copy_from(&self.vector);
res
}
}
impl<N, D: DimName, S> TranslationBase<N, D, S>
where N: Scalar + ClosedNeg,
S: StorageMut<N, D, U1> {
/// Inverts `self` in-place.
#[inline]
pub fn inverse_mut(&mut self) {
self.vector.neg_mut()
}
}
impl<N, D: DimName, S> Eq for TranslationBase<N, D, S>
where N: Scalar + Eq,
S: Storage<N, D, U1> {
}
impl<N, D: DimName, S> PartialEq for TranslationBase<N, D, S>
where N: Scalar + PartialEq,
S: Storage<N, D, U1> {
#[inline]
fn eq(&self, right: &TranslationBase<N, D, S>) -> bool {
self.vector == right.vector
}
}
impl<N, D: DimName, S> ApproxEq for TranslationBase<N, D, S>
where N: Scalar + ApproxEq,
S: Storage<N, D, U1>,
N::Epsilon: Copy {
type Epsilon = N::Epsilon;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool {
self.vector.relative_eq(&other.vector, epsilon, max_relative)
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.vector.ulps_eq(&other.vector, epsilon, max_ulps)
}
}
/*
*
* Display
*
*/
impl<N, D: DimName, S> fmt::Display for TranslationBase<N, D, S>
where N: Real + fmt::Display,
S: Storage<N, D, U1>,
S::Alloc: Allocator<usize, D, U1> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let precision = f.precision().unwrap_or(3);
try!(writeln!(f, "TranslationBase {{"));
try!(write!(f, "{:.*}", precision, self.vector));
writeln!(f, "}}")
}
}
// // /*
// // *
// // * Absolute
// // *
// // */
// // impl<N: Absolute> Absolute for $t<N> {
// // type AbsoluteValue = $submatrix<N::AbsoluteValue>;
// //
// // #[inline]
// // fn abs(m: &$t<N>) -> $submatrix<N::AbsoluteValue> {
// // Absolute::abs(&m.submatrix)
// // }
// // }
// */

View File

@ -0,0 +1,209 @@
use alga::general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
AbstractSemigroup, Real, Inverse, Multiplicative, Identity, Id};
use alga::linear::{Transformation, ProjectiveTransformation, Similarity, AffineTransformation,
Isometry, DirectIsometry, Translation};
use core::ColumnVector;
use core::dimension::{DimName, U1};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::{TranslationBase, PointBase};
/*
*
* Algebraic structures.
*
*/
impl<N, D: DimName, S> Identity<Multiplicative> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S> Inverse<Multiplicative> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn inverse(&self) -> Self {
self.inverse()
}
#[inline]
fn inverse_mut(&mut self) {
self.inverse_mut()
}
}
impl<N, D: DimName, S> AbstractMagma<Multiplicative> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
macro_rules! impl_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimName, S> $marker<$operator> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> { }
)*}
);
impl_multiplicative_structures!(
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
AbstractQuasigroup<Multiplicative>,
AbstractLoop<Multiplicative>,
AbstractGroup<Multiplicative>
);
/*
*
* Transformation groups.
*
*/
impl<N, D: DimName, S> Transformation<PointBase<N, D, S>> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn transform_point(&self, pt: &PointBase<N, D, S>) -> PointBase<N, D, S> {
pt + &self.vector
}
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, D, S>) -> ColumnVector<N, D, S> {
v.clone()
}
}
impl<N, D: DimName, S> ProjectiveTransformation<PointBase<N, D, S>> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn inverse_transform_point(&self, pt: &PointBase<N, D, S>) -> PointBase<N, D, S> {
pt - &self.vector
}
#[inline]
fn inverse_transform_vector(&self, v: &ColumnVector<N, D, S>) -> ColumnVector<N, D, S> {
v.clone()
}
}
impl<N, D: DimName, S> AffineTransformation<PointBase<N, D, S>> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Rotation = Id;
type NonUniformScaling = Id;
type Translation = Self;
#[inline]
fn decompose(&self) -> (Self, Id, Id, Id) {
(self.clone(), Id::new(), Id::new(), Id::new())
}
#[inline]
fn append_translation(&self, t: &Self::Translation) -> Self {
t * self
}
#[inline]
fn prepend_translation(&self, t: &Self::Translation) -> Self {
self * t
}
#[inline]
fn append_rotation(&self, _: &Self::Rotation) -> Self {
self.clone()
}
#[inline]
fn prepend_rotation(&self, _: &Self::Rotation) -> Self {
self.clone()
}
#[inline]
fn append_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
#[inline]
fn prepend_scaling(&self, _: &Self::NonUniformScaling) -> Self {
self.clone()
}
}
impl<N, D: DimName, S> Similarity<PointBase<N, D, S>> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
type Scaling = Id;
#[inline]
fn translation(&self) -> Self {
self.clone()
}
#[inline]
fn rotation(&self) -> Id {
Id::new()
}
#[inline]
fn scaling(&self) -> Id {
Id::new()
}
}
macro_rules! marker_impl(
($($Trait: ident),*) => {$(
impl<N, D: DimName, S> $Trait<PointBase<N, D, S>> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> { }
)*}
);
marker_impl!(Isometry, DirectIsometry);
/// Subgroups of the n-dimensional translation group `T(n)`.
impl<N, D: DimName, S> Translation<PointBase<N, D, S>> for TranslationBase<N, D, S>
where N: Real,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn to_vector(&self) -> ColumnVector<N, D, S> {
self.vector.clone()
}
#[inline]
fn from_vector(v: ColumnVector<N, D, S>) -> Option<Self> {
Some(Self::from_vector(v))
}
#[inline]
fn powf(&self, n: N) -> Option<Self> {
Some(Self::from_vector(&self.vector * n))
}
#[inline]
fn translation_between(a: &PointBase<N, D, S>, b: &PointBase<N, D, S>) -> Option<Self> {
Some(Self::from_vector(b - a))
}
}

View File

@ -0,0 +1,13 @@
use core::MatrixArray;
use core::dimension::{U1, U2, U3};
use geometry::TranslationBase;
/// A D-dimensional translation.
pub type Translation<N, D> = TranslationBase<N, D, MatrixArray<N, D, U1>>;
/// A 2-dimensional translation.
pub type Translation2<N> = Translation<N, U2>;
/// A 3-dimensional translation.
pub type Translation3<N> = Translation<N, U3>;

View File

@ -0,0 +1,86 @@
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use num::{Zero, One};
use rand::{Rng, Rand};
use alga::general::ClosedAdd;
use core::{ColumnVector, Scalar};
use core::dimension::{DimName, U1, U2, U3, U4, U5, U6};
use core::storage::OwnedStorage;
use core::allocator::OwnedAllocator;
use geometry::TranslationBase;
impl<N, D: DimName, S> TranslationBase<N, D, S>
where N: Scalar + Zero,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
/// Creates a new square identity rotation of the given `dimension`.
#[inline]
pub fn identity() -> TranslationBase<N, D, S> {
Self::from_vector(ColumnVector::<N, D, S>::from_element(N::zero()))
}
}
impl<N, D: DimName, S> One for TranslationBase<N, D, S>
where N: Scalar + Zero + ClosedAdd,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn one() -> Self {
Self::identity()
}
}
impl<N, D: DimName, S> Rand for TranslationBase<N, D, S>
where N: Scalar + Rand,
S: OwnedStorage<N, D, U1>,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn rand<G: Rng>(rng: &mut G) -> Self {
Self::from_vector(rng.gen())
}
}
#[cfg(feature = "arbitrary")]
impl<N, D: DimName, S> Arbitrary for TranslationBase<N, D, S>
where N: Scalar + Arbitrary + Send,
S: OwnedStorage<N, D, U1> + Send,
S::Alloc: OwnedAllocator<N, D, U1, S> {
#[inline]
fn arbitrary<G: Gen>(rng: &mut G) -> Self {
Self::from_vector(Arbitrary::arbitrary(rng))
}
}
/*
*
* Small translation construction from components.
*
*/
macro_rules! componentwise_constructors_impl(
($($D: ty, $($args: ident:$irow: expr),*);* $(;)*) => {$(
impl<N, S> TranslationBase<N, $D, S>
where N: Scalar,
S: OwnedStorage<N, $D, U1>,
S::Alloc: OwnedAllocator<N, $D, U1, S> {
/// Initializes this matrix from its components.
#[inline]
pub fn new($($args: N),*) -> Self {
Self::from_vector(ColumnVector::<N, $D, S>::new($($args),*))
}
}
)*}
);
componentwise_constructors_impl!(
U1, x:0;
U2, x:0, y:1;
U3, x:0, y:1, z:2;
U4, x:0, y:1, z:2, w:3;
U5, x:0, y:1, z:2, w:3, a:4;
U6, x:0, y:1, z:2, w:3, a:4, b:5;
);

View File

@ -0,0 +1,159 @@
use alga::general::{SubsetOf, SupersetOf, Real};
use alga::linear::Rotation;
use core::{Scalar, ColumnVector, SquareMatrix};
use core::dimension::{DimName, DimNameAdd, DimNameSum, U1};
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, TranslationBase, IsometryBase, SimilarityBase, TransformBase, SuperTCategoryOf, TAffine};
/*
* This file provides the following conversions:
* =============================================
*
* TranslationBase -> TranslationBase
* TranslationBase -> IsometryBase
* TranslationBase -> SimilarityBase
* TranslationBase -> TransformBase
* TranslationBase -> Matrix (homogeneous)
*/
impl<N1, N2, D: DimName, SA, SB> SubsetOf<TranslationBase<N2, D, SB>> for TranslationBase<N1, D, SA>
where N1: Scalar,
N2: Scalar + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, D, U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> TranslationBase<N2, D, SB> {
TranslationBase::from_vector(self.vector.to_superset())
}
#[inline]
fn is_in_subset(rot: &TranslationBase<N2, D, SB>) -> bool {
::is_convertible::<_, ColumnVector<N1, D, SA>>(&rot.vector)
}
#[inline]
unsafe fn from_superset_unchecked(rot: &TranslationBase<N2, D, SB>) -> Self {
TranslationBase::from_vector(rot.vector.to_subset_unchecked())
}
}
impl<N1, N2, D: DimName, SA, SB, R> SubsetOf<IsometryBase<N2, D, SB, R>> for TranslationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, D, U1>,
R: Rotation<PointBase<N2, D, SB>>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> IsometryBase<N2, D, SB, R> {
IsometryBase::from_parts(self.to_superset(), R::identity())
}
#[inline]
fn is_in_subset(iso: &IsometryBase<N2, D, SB, R>) -> bool {
iso.rotation == R::identity()
}
#[inline]
unsafe fn from_superset_unchecked(iso: &IsometryBase<N2, D, SB, R>) -> Self {
Self::from_superset_unchecked(&iso.translation)
}
}
impl<N1, N2, D: DimName, SA, SB, R> SubsetOf<SimilarityBase<N2, D, SB, R>> for TranslationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, D, U1>,
R: Rotation<PointBase<N2, D, SB>>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA>,
SB::Alloc: OwnedAllocator<N2, D, U1, SB> {
#[inline]
fn to_superset(&self) -> SimilarityBase<N2, D, SB, R> {
SimilarityBase::from_parts(self.to_superset(), R::identity(), N2::one())
}
#[inline]
fn is_in_subset(sim: &SimilarityBase<N2, D, SB, R>) -> bool {
sim.isometry.rotation == R::identity() &&
sim.scaling() == N2::one()
}
#[inline]
unsafe fn from_superset_unchecked(sim: &SimilarityBase<N2, D, SB, R>) -> Self {
Self::from_superset_unchecked(&sim.isometry.translation)
}
}
impl<N1, N2, D, SA, SB, C> SubsetOf<TransformBase<N2, D, SB, C>> for TranslationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SuperTCategoryOf<TAffine>,
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> +
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, U1> +
Allocator<N2, DimNameSum<D, U1>, D> {
#[inline]
fn to_superset(&self) -> TransformBase<N2, D, SB, C> {
TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset())
}
#[inline]
fn is_in_subset(t: &TransformBase<N2, D, SB, C>) -> bool {
<Self as SubsetOf<_>>::is_in_subset(t.matrix())
}
#[inline]
unsafe fn from_superset_unchecked(t: &TransformBase<N2, D, SB, C>) -> Self {
Self::from_superset_unchecked(t.matrix())
}
}
impl<N1, N2, D, SA, SB> SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>> for TranslationBase<N1, D, SA>
where N1: Real,
N2: Real + SupersetOf<N1>,
SA: OwnedStorage<N1, D, U1>,
SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>,
D: DimNameAdd<U1>,
SA::Alloc: OwnedAllocator<N1, D, U1, SA> +
Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> +
Allocator<N2, D, U1> +
Allocator<N2, DimNameSum<D, U1>, D> {
#[inline]
fn to_superset(&self) -> SquareMatrix<N2, DimNameSum<D, U1>, SB> {
self.to_homogeneous().to_superset()
}
#[inline]
fn is_in_subset(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> bool {
let id = m.fixed_slice::<DimNameSum<D, U1>, D>(0, 0);
// Scalar types agree.
m.iter().all(|e| SupersetOf::<N1>::is_in_subset(e)) &&
// The block part does nothing.
id.is_identity(N2::zero()) &&
// The normalization factor is one.
m[(D::dim(), D::dim())] == N2::one()
}
#[inline]
unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> Self {
let t = m.fixed_slice::<D, U1>(0, D::dim());
Self::from_vector(::convert_unchecked(t.into_owned()))
}
}

Some files were not shown because too many files have changed in this diff Show More