Merge pull request #40 from alexbool/update-nalgebra-0.20

Update nalgebra 0.20 (take 2)
This commit is contained in:
Dimitri Sabadie 2020-03-19 01:21:59 +01:00 committed by GitHub
commit 1bcf1de99e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 816 additions and 711 deletions

View File

@ -3,7 +3,10 @@ extern crate splines;
use splines::{Interpolation, Key, Spline}; use splines::{Interpolation, Key, Spline};
fn main() { fn main() {
let keys = vec![Key::new(0., 0., Interpolation::default()), Key::new(5., 1., Interpolation::default())]; let keys = vec![
Key::new(0., 0., Interpolation::default()),
Key::new(5., 1., Interpolation::default()),
];
let spline = Spline::from_vec(keys); let spline = Spline::from_vec(keys);
println!("value at 0: {:?}", spline.clamped_sample(0.)); println!("value at 0: {:?}", spline.clamped_sample(0.));

View File

@ -1,11 +1,12 @@
#[macro_use] extern crate serde_json; #[macro_use]
extern crate serde_json;
extern crate splines; extern crate splines;
use serde_json::from_value; use serde_json::from_value;
use splines::Spline; use splines::Spline;
fn main() { fn main() {
let value = json!{ let value = json! {
[ [
{ {
"t": 0, "t": 0,

View File

@ -1,9 +1,9 @@
use cgmath::{ use cgmath::{
BaseFloat, BaseNum, InnerSpace, Quaternion, Vector1, Vector2, Vector3, Vector4, VectorSpace BaseFloat, BaseNum, InnerSpace, Quaternion, Vector1, Vector2, Vector3, Vector4, VectorSpace,
}; };
use crate::interpolate::{ use crate::interpolate::{
Additive, Interpolate, Linear, One, cubic_bezier_def, cubic_hermite_def, quadratic_bezier_def cubic_bezier_def, cubic_hermite_def, quadratic_bezier_def, Additive, Interpolate, Linear, One,
}; };
macro_rules! impl_interpolate_vec { macro_rules! impl_interpolate_vec {
@ -50,7 +50,10 @@ impl_interpolate_vec!(Vector2);
impl_interpolate_vec!(Vector3); impl_interpolate_vec!(Vector3);
impl_interpolate_vec!(Vector4); impl_interpolate_vec!(Vector4);
impl<T> Linear<T> for Quaternion<T> where T: BaseFloat { impl<T> Linear<T> for Quaternion<T>
where
T: BaseFloat,
{
#[inline(always)] #[inline(always)]
fn outer_mul(self, t: T) -> Self { fn outer_mul(self, t: T) -> Self {
self * t self * t
@ -63,7 +66,10 @@ impl<T> Linear<T> for Quaternion<T> where T: BaseFloat {
} }
impl<T> Interpolate<T> for Quaternion<T> impl<T> Interpolate<T> for Quaternion<T>
where Self: InnerSpace<Scalar = T>, T: Additive + BaseFloat + One { where
Self: InnerSpace<Scalar = T>,
T: Additive + BaseFloat + One,
{
#[inline(always)] #[inline(always)]
fn lerp(a: Self, b: Self, t: T) -> Self { fn lerp(a: Self, b: Self, t: T) -> Self {
a.nlerp(b, t) a.nlerp(b, t)

View File

@ -28,14 +28,22 @@
//! [`Trigo`]: crate::interpolate::Trigo //! [`Trigo`]: crate::interpolate::Trigo
//! [num-traits]: https://crates.io/crates/num-traits //! [num-traits]: https://crates.io/crates/num-traits
#[cfg(feature = "std")] use std::f32; #[cfg(not(feature = "std"))]
#[cfg(not(feature = "std"))] use core::f32; use core::f32;
#[cfg(not(feature = "std"))] use core::intrinsics::cosf32; #[cfg(not(feature = "std"))]
#[cfg(feature = "std")] use std::f64; use core::f64;
#[cfg(not(feature = "std"))] use core::f64; #[cfg(not(feature = "std"))]
#[cfg(not(feature = "std"))] use core::intrinsics::cosf64; use core::intrinsics::cosf32;
#[cfg(feature = "std")] use std::ops::{Add, Mul, Sub}; #[cfg(not(feature = "std"))]
#[cfg(not(feature = "std"))] use core::ops::{Add, Mul, Sub}; use core::intrinsics::cosf64;
#[cfg(not(feature = "std"))]
use core::ops::{Add, Mul, Sub};
#[cfg(feature = "std")]
use std::f32;
#[cfg(feature = "std")]
use std::f64;
#[cfg(feature = "std")]
use std::ops::{Add, Mul, Sub};
/// Keys that can be interpolated in between. Implementing this trait is required to perform /// Keys that can be interpolated in between. Implementing this trait is required to perform
/// sampling on splines. /// sampling on splines.
@ -68,17 +76,9 @@ pub trait Interpolate<T>: Sized + Copy + Linear<T> {
/// Set of types that support additions and subtraction. /// Set of types that support additions and subtraction.
/// ///
/// The [`Copy`] trait is also a supertrait as its likely to be used everywhere. /// The [`Copy`] trait is also a supertrait as its likely to be used everywhere.
pub trait Additive: pub trait Additive: Copy + Add<Self, Output = Self> + Sub<Self, Output = Self> {}
Copy +
Add<Self, Output = Self> +
Sub<Self, Output = Self> {
}
impl<T> Additive for T impl<T> Additive for T where T: Copy + Add<Self, Output = Self> + Sub<Self, Output = Self> {}
where T: Copy +
Add<Self, Output = Self> +
Sub<Self, Output = Self> {
}
/// Set of additive types that support outer multiplication and division, making them linear. /// Set of additive types that support outer multiplication and division, making them linear.
pub trait Linear<T>: Additive { pub trait Linear<T>: Additive {
@ -101,7 +101,7 @@ macro_rules! impl_linear_simple {
self / t self / t
} }
} }
} };
} }
impl_linear_simple!(f32); impl_linear_simple!(f32);
@ -119,7 +119,7 @@ macro_rules! impl_linear_cast {
self / t as $q self / t as $q
} }
} }
} };
} }
impl_linear_cast!(f32, f64); impl_linear_cast!(f32, f64);
@ -139,7 +139,7 @@ macro_rules! impl_one_float {
1. 1.
} }
} }
} };
} }
impl_one_float!(f32); impl_one_float!(f32);
@ -198,8 +198,10 @@ impl Trigo for f64 {
/// ///
/// `V` is the value being interpolated. `T` is the sampling value (also sometimes called time). /// `V` is the value being interpolated. `T` is the sampling value (also sometimes called time).
pub fn cubic_hermite_def<V, T>(x: (V, T), a: (V, T), b: (V, T), y: (V, T), t: T) -> V pub fn cubic_hermite_def<V, T>(x: (V, T), a: (V, T), b: (V, T), y: (V, T), t: T) -> V
where V: Linear<T>, where
T: Additive + Mul<T, Output = T> + One { V: Linear<T>,
T: Additive + Mul<T, Output = T> + One,
{
// some stupid generic constants, because Rust doesnt have polymorphic literals… // some stupid generic constants, because Rust doesnt have polymorphic literals…
let one_t = T::one(); let one_t = T::one();
let two_t = one_t + one_t; // lolololol let two_t = one_t + one_t; // lolololol
@ -215,15 +217,20 @@ where V: Linear<T>,
let m0 = (b.0 - x.0).outer_div(b.1 - x.1); let m0 = (b.0 - x.0).outer_div(b.1 - x.1);
let m1 = (y.0 - a.0).outer_div(y.1 - a.1); let m1 = (y.0 - a.0).outer_div(y.1 - a.1);
a.0.outer_mul(two_t3 - three_t2 + one_t) + m0.outer_mul(t3 - t2 * two_t + t) + b.0.outer_mul(three_t2 - two_t3) + m1.outer_mul(t3 - t2) a.0.outer_mul(two_t3 - three_t2 + one_t)
+ m0.outer_mul(t3 - t2 * two_t + t)
+ b.0.outer_mul(three_t2 - two_t3)
+ m1.outer_mul(t3 - t2)
} }
/// Default implementation of [`Interpolate::quadratic_bezier`]. /// Default implementation of [`Interpolate::quadratic_bezier`].
/// ///
/// `V` is the value being interpolated. `T` is the sampling value (also sometimes called time). /// `V` is the value being interpolated. `T` is the sampling value (also sometimes called time).
pub fn quadratic_bezier_def<V, T>(a: V, u: V, b: V, t: T) -> V pub fn quadratic_bezier_def<V, T>(a: V, u: V, b: V, t: T) -> V
where V: Linear<T>, where
T: Additive + Mul<T, Output = T> + One { V: Linear<T>,
T: Additive + Mul<T, Output = T> + One,
{
let one_t = T::one() - t; let one_t = T::one() - t;
let one_t_2 = one_t * one_t; let one_t_2 = one_t * one_t;
u + (a - u).outer_mul(one_t_2) + (b - u).outer_mul(t * t) u + (a - u).outer_mul(one_t_2) + (b - u).outer_mul(t * t)
@ -233,14 +240,19 @@ where V: Linear<T>,
/// ///
/// `V` is the value being interpolated. `T` is the sampling value (also sometimes called time). /// `V` is the value being interpolated. `T` is the sampling value (also sometimes called time).
pub fn cubic_bezier_def<V, T>(a: V, u: V, v: V, b: V, t: T) -> V pub fn cubic_bezier_def<V, T>(a: V, u: V, v: V, b: V, t: T) -> V
where V: Linear<T>, where
T: Additive + Mul<T, Output = T> + One { V: Linear<T>,
T: Additive + Mul<T, Output = T> + One,
{
let one_t = T::one() - t; let one_t = T::one() - t;
let one_t_2 = one_t * one_t; let one_t_2 = one_t * one_t;
let one_t_3 = one_t_2 * one_t; let one_t_3 = one_t_2 * one_t;
let three = T::one() + T::one() + T::one(); let three = T::one() + T::one() + T::one();
a.outer_mul(one_t_3) + u.outer_mul(three * one_t_2 * t) + v.outer_mul(three * one_t * t * t) + b.outer_mul(t * t * t) a.outer_mul(one_t_3)
+ u.outer_mul(three * one_t_2 * t)
+ v.outer_mul(three * one_t * t * t)
+ b.outer_mul(t * t * t)
} }
macro_rules! impl_interpolate_simple { macro_rules! impl_interpolate_simple {
@ -250,7 +262,13 @@ macro_rules! impl_interpolate_simple {
a * (1. - t) + b * t a * (1. - t) + b * t
} }
fn cubic_hermite(x: (Self, $t), a: (Self, $t), b: (Self, $t), y: (Self, $t), t: $t) -> Self { fn cubic_hermite(
x: (Self, $t),
a: (Self, $t),
b: (Self, $t),
y: (Self, $t),
t: $t,
) -> Self {
cubic_hermite_def(x, a, b, y, t) cubic_hermite_def(x, a, b, y, t)
} }
@ -262,7 +280,7 @@ macro_rules! impl_interpolate_simple {
cubic_bezier_def(a, u, v, b, t) cubic_bezier_def(a, u, v, b, t)
} }
} }
} };
} }
impl_interpolate_simple!(f32); impl_interpolate_simple!(f32);
@ -275,8 +293,20 @@ macro_rules! impl_interpolate_via {
a * (1. - t as $v) + b * t as $v a * (1. - t as $v) + b * t as $v
} }
fn cubic_hermite((x, xt): (Self, $t), (a, at): (Self, $t), (b, bt): (Self, $t), (y, yt): (Self, $t), t: $t) -> Self { fn cubic_hermite(
cubic_hermite_def((x, xt as $v), (a, at as $v), (b, bt as $v), (y, yt as $v), t as $v) (x, xt): (Self, $t),
(a, at): (Self, $t),
(b, bt): (Self, $t),
(y, yt): (Self, $t),
t: $t,
) -> Self {
cubic_hermite_def(
(x, xt as $v),
(a, at as $v),
(b, bt as $v),
(y, yt as $v),
t as $v,
)
} }
fn quadratic_bezier(a: Self, u: Self, b: Self, t: $t) -> Self { fn quadratic_bezier(a: Self, u: Self, b: Self, t: $t) -> Self {
@ -287,7 +317,7 @@ macro_rules! impl_interpolate_via {
cubic_bezier_def(a, u, v, b, t as $v) cubic_bezier_def(a, u, v, b, t as $v)
} }
} }
} };
} }
impl_interpolate_via!(f32, f64); impl_interpolate_via!(f32, f64);

View File

@ -1,6 +1,7 @@
//! Available interpolation modes. //! Available interpolation modes.
#[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize}; #[cfg(feature = "serialization")]
use serde_derive::{Deserialize, Serialize};
/// Available kind of interpolations. /// Available kind of interpolations.
/// ///
@ -53,7 +54,7 @@ pub enum Interpolation<T, V> {
/// Stroke Bézier interpolation is always a cubic Bézier interpolation by default. /// Stroke Bézier interpolation is always a cubic Bézier interpolation by default.
StrokeBezier(V, V), StrokeBezier(V, V),
#[doc(hidden)] #[doc(hidden)]
__NonExhaustive __NonExhaustive,
} }
impl<T, V> Default for Interpolation<T, V> { impl<T, V> Default for Interpolation<T, V> {

View File

@ -11,9 +11,13 @@ use crate::{Key, Spline};
/// Iterator over spline keys. /// Iterator over spline keys.
/// ///
/// This iterator type is guaranteed to iterate over sorted keys. /// This iterator type is guaranteed to iterate over sorted keys.
pub struct Iter<'a, T, V> where T: 'a, V: 'a { pub struct Iter<'a, T, V>
where
T: 'a,
V: 'a,
{
spline: &'a Spline<T, V>, spline: &'a Spline<T, V>,
i: usize i: usize,
} }
impl<'a, T, V> Iterator for Iter<'a, T, V> { impl<'a, T, V> Iterator for Iter<'a, T, V> {
@ -35,10 +39,6 @@ impl<'a, T, V> IntoIterator for &'a Spline<T, V> {
type IntoIter = Iter<'a, T, V>; type IntoIter = Iter<'a, T, V>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
Iter { Iter { spline: self, i: 0 }
spline: self,
i: 0
}
} }
} }

View File

@ -6,7 +6,8 @@
//! Splines constructed with this crate have the property that its possible to change the //! Splines constructed with this crate have the property that its possible to change the
//! interpolation mode on a key-based way, allowing you to implement and encode complex curves. //! interpolation mode on a key-based way, allowing you to implement and encode complex curves.
#[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize}; #[cfg(feature = "serialization")]
use serde_derive::{Deserialize, Serialize};
use crate::interpolation::Interpolation; use crate::interpolation::Interpolation;
@ -26,12 +27,16 @@ pub struct Key<T, V> {
/// Carried value. /// Carried value.
pub value: V, pub value: V,
/// Interpolation mode. /// Interpolation mode.
pub interpolation: Interpolation<T, V> pub interpolation: Interpolation<T, V>,
} }
impl<T, V> Key<T, V> { impl<T, V> Key<T, V> {
/// Create a new key. /// Create a new key.
pub fn new(t: T, value: V, interpolation: Interpolation<T, V>) -> Self { pub fn new(t: T, value: V, interpolation: Interpolation<T, V>) -> Self {
Key { t, value, interpolation } Key {
t,
value,
interpolation,
}
} }
} }

View File

@ -106,14 +106,17 @@
#![cfg_attr(not(feature = "std"), feature(alloc))] #![cfg_attr(not(feature = "std"), feature(alloc))]
#![cfg_attr(not(feature = "std"), feature(core_intrinsics))] #![cfg_attr(not(feature = "std"), feature(core_intrinsics))]
#[cfg(not(feature = "std"))] extern crate alloc; #[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(feature = "impl-cgmath")] mod cgmath; #[cfg(feature = "impl-cgmath")]
mod cgmath;
pub mod interpolate; pub mod interpolate;
pub mod interpolation; pub mod interpolation;
pub mod iter; pub mod iter;
pub mod key; pub mod key;
#[cfg(feature = "impl-nalgebra")] mod nalgebra; #[cfg(feature = "impl-nalgebra")]
mod nalgebra;
pub mod spline; pub mod spline;
pub use crate::interpolate::Interpolate; pub use crate::interpolate::Interpolate;

View File

@ -4,13 +4,19 @@ use num_traits as nt;
use std::ops::Mul; use std::ops::Mul;
use crate::interpolate::{ use crate::interpolate::{
Interpolate, Linear, Additive, One, cubic_bezier_def, cubic_hermite_def, quadratic_bezier_def cubic_bezier_def, cubic_hermite_def, quadratic_bezier_def, Additive, Interpolate, Linear, One,
}; };
macro_rules! impl_interpolate_vector { macro_rules! impl_interpolate_vector {
($($t:tt)*) => { ($($t:tt)*) => {
// implement Linear // implement Linear
impl<T> Linear<T> for $($t)*<T> where T: Scalar + ClosedAdd + ClosedSub + ClosedMul + ClosedDiv { impl<T> Linear<T> for $($t)*<T>
where T: Scalar +
Copy +
ClosedAdd +
ClosedSub +
ClosedMul +
ClosedDiv {
#[inline(always)] #[inline(always)]
fn outer_mul(self, t: T) -> Self { fn outer_mul(self, t: T) -> Self {
self * t self * t

View File

@ -1,11 +1,17 @@
//! Spline curves and operations. //! Spline curves and operations.
#[cfg(feature = "serialization")] use serde_derive::{Deserialize, Serialize}; #[cfg(not(feature = "std"))]
#[cfg(not(feature = "std"))] use alloc::vec::Vec; use alloc::vec::Vec;
#[cfg(feature = "std")] use std::cmp::Ordering; #[cfg(not(feature = "std"))]
#[cfg(feature = "std")] use std::ops::{Div, Mul}; use core::cmp::Ordering;
#[cfg(not(feature = "std"))] use core::ops::{Div, Mul}; #[cfg(not(feature = "std"))]
#[cfg(not(feature = "std"))] use core::cmp::Ordering; use core::ops::{Div, Mul};
#[cfg(feature = "serialization")]
use serde_derive::{Deserialize, Serialize};
#[cfg(feature = "std")]
use std::cmp::Ordering;
#[cfg(feature = "std")]
use std::ops::{Div, Mul};
use crate::interpolate::{Additive, Interpolate, One, Trigo}; use crate::interpolate::{Additive, Interpolate, One, Trigo};
use crate::interpolation::Interpolation; use crate::interpolation::Interpolation;
@ -29,13 +35,20 @@ pub struct Spline<T, V>(pub(crate) Vec<Key<T, V>>);
impl<T, V> Spline<T, V> { impl<T, V> Spline<T, V> {
/// Internal sort to ensure invariant of sorting keys is valid. /// Internal sort to ensure invariant of sorting keys is valid.
fn internal_sort(&mut self) where T: PartialOrd { fn internal_sort(&mut self)
self.0.sort_by(|k0, k1| k0.t.partial_cmp(&k1.t).unwrap_or(Ordering::Less)); where
T: PartialOrd,
{
self.0
.sort_by(|k0, k1| k0.t.partial_cmp(&k1.t).unwrap_or(Ordering::Less));
} }
/// Create a new spline out of keys. The keys dont have to be sorted even though its recommended /// Create a new spline out of keys. The keys dont have to be sorted even though its recommended
/// to provide ascending sorted ones (for performance purposes). /// to provide ascending sorted ones (for performance purposes).
pub fn from_vec(keys: Vec<Key<T, V>>) -> Self where T: PartialOrd { pub fn from_vec(keys: Vec<Key<T, V>>) -> Self
where
T: PartialOrd,
{
let mut spline = Spline(keys); let mut spline = Spline(keys);
spline.internal_sort(); spline.internal_sort();
spline spline
@ -48,7 +61,11 @@ impl<T, V> Spline<T, V> {
/// ///
/// Its valid to use any iterator that implements `Iterator<Item = Key<T>>`. However, you should /// Its valid to use any iterator that implements `Iterator<Item = Key<T>>`. However, you should
/// use [`Spline::from_vec`] if you are passing a [`Vec`]. /// use [`Spline::from_vec`] if you are passing a [`Vec`].
pub fn from_iter<I>(iter: I) -> Self where I: Iterator<Item = Key<T, V>>, T: PartialOrd { pub fn from_iter<I>(iter: I) -> Self
where
I: Iterator<Item = Key<T, V>>,
T: PartialOrd,
{
Self::from_vec(iter.collect()) Self::from_vec(iter.collect())
} }
@ -85,8 +102,10 @@ impl<T, V> Spline<T, V> {
/// youre near the beginning of the spline or its end, ensure you have enough keys around to make /// youre near the beginning of the spline or its end, ensure you have enough keys around to make
/// the sampling. /// the sampling.
pub fn sample_with_key(&self, t: T) -> Option<(V, &Key<T, V>, Option<&Key<T, V>>)> pub fn sample_with_key(&self, t: T) -> Option<(V, &Key<T, V>, Option<&Key<T, V>>)>
where T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd, where
V: Additive + Interpolate<T> { T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd,
V: Additive + Interpolate<T>,
{
let keys = &self.0; let keys = &self.0;
let i = search_lower_cp(keys, t)?; let i = search_lower_cp(keys, t)?;
let cp0 = &keys[i]; let cp0 = &keys[i];
@ -128,7 +147,13 @@ impl<T, V> Spline<T, V> {
let cpm0 = &keys[i - 1]; let cpm0 = &keys[i - 1];
let cpm1 = &keys[i + 2]; let cpm1 = &keys[i + 2];
let nt = normalize_time(t, cp0, cp1); let nt = normalize_time(t, cp0, cp1);
let value = Interpolate::cubic_hermite((cpm0.value, cpm0.t), (cp0.value, cp0.t), (cp1.value, cp1.t), (cpm1.value, cpm1.t), nt); let value = Interpolate::cubic_hermite(
(cpm0.value, cpm0.t),
(cp0.value, cp0.t),
(cp1.value, cp1.t),
(cpm1.value, cpm1.t),
nt,
);
Some((value, cp0, Some(cp1))) Some((value, cp0, Some(cp1)))
} }
@ -139,17 +164,20 @@ impl<T, V> Spline<T, V> {
let cp1 = &keys[i + 1]; let cp1 = &keys[i + 1];
let nt = normalize_time(t, cp0, cp1); let nt = normalize_time(t, cp0, cp1);
let value = let value = match cp1.interpolation {
match cp1.interpolation { Interpolation::Bezier(v) => Interpolate::cubic_bezier(
Interpolation::Bezier(v) => { cp0.value,
Interpolate::cubic_bezier(cp0.value, u, cp1.value + cp1.value - v, cp1.value, nt) u,
} cp1.value + cp1.value - v,
cp1.value,
nt,
),
Interpolation::StrokeBezier(v, _) => { Interpolation::StrokeBezier(v, _) => {
Interpolate::cubic_bezier(cp0.value, u, v, cp1.value, nt) Interpolate::cubic_bezier(cp0.value, u, v, cp1.value, nt)
} }
_ => Interpolate::quadratic_bezier(cp0.value, u, cp1.value, nt) _ => Interpolate::quadratic_bezier(cp0.value, u, cp1.value, nt),
}; };
Some((value, cp0, Some(cp1))) Some((value, cp0, Some(cp1)))
@ -162,8 +190,10 @@ impl<T, V> Spline<T, V> {
/// Sample a spline at a given time. /// Sample a spline at a given time.
/// ///
pub fn sample(&self, t: T) -> Option<V> pub fn sample(&self, t: T) -> Option<V>
where T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd, where
V: Additive + Interpolate<T> { T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd,
V: Additive + Interpolate<T>,
{
self.sample_with_key(t).map(|(v, _, _)| v) self.sample_with_key(t).map(|(v, _, _)| v)
} }
@ -179,8 +209,10 @@ impl<T, V> Spline<T, V> {
/// ///
/// This function returns [`None`] if you have no key. /// This function returns [`None`] if you have no key.
pub fn clamped_sample_with_key(&self, t: T) -> Option<(V, &Key<T, V>, Option<&Key<T, V>>)> pub fn clamped_sample_with_key(&self, t: T) -> Option<(V, &Key<T, V>, Option<&Key<T, V>>)>
where T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd, where
V: Additive + Interpolate<T> { T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd,
V: Additive + Interpolate<T>,
{
if self.0.is_empty() { if self.0.is_empty() {
return None; return None;
} }
@ -188,7 +220,11 @@ impl<T, V> Spline<T, V> {
self.sample_with_key(t).or_else(move || { self.sample_with_key(t).or_else(move || {
let first = self.0.first().unwrap(); let first = self.0.first().unwrap();
if t <= first.t { if t <= first.t {
let second = if self.0.len() >= 2 { Some(&self.0[1]) } else { None }; let second = if self.0.len() >= 2 {
Some(&self.0[1])
} else {
None
};
Some((first.value, &first, second)) Some((first.value, &first, second))
} else { } else {
let last = self.0.last().unwrap(); let last = self.0.last().unwrap();
@ -204,13 +240,18 @@ impl<T, V> Spline<T, V> {
/// Sample a spline at a given time with clamping. /// Sample a spline at a given time with clamping.
pub fn clamped_sample(&self, t: T) -> Option<V> pub fn clamped_sample(&self, t: T) -> Option<V>
where T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd, where
V: Additive + Interpolate<T> { T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd,
V: Additive + Interpolate<T>,
{
self.clamped_sample_with_key(t).map(|(v, _, _)| v) self.clamped_sample_with_key(t).map(|(v, _, _)| v)
} }
/// Add a key into the spline. /// Add a key into the spline.
pub fn add(&mut self, key: Key<T, V>) where T: PartialOrd { pub fn add(&mut self, key: Key<T, V>)
where
T: PartialOrd,
{
self.0.push(key); self.0.push(key);
self.internal_sort(); self.internal_sort();
} }
@ -233,14 +274,10 @@ impl<T, V> Spline<T, V> {
/// That function makes sense only if you want to change the interpolator (i.e. [`Key::t`]) of /// That function makes sense only if you want to change the interpolator (i.e. [`Key::t`]) of
/// your key. If you just want to change the interpolation mode or the carried value, consider /// your key. If you just want to change the interpolation mode or the carried value, consider
/// using the [`Spline::get_mut`] method instead as it will be way faster. /// using the [`Spline::get_mut`] method instead as it will be way faster.
pub fn replace<F>( pub fn replace<F>(&mut self, index: usize, f: F) -> Option<Key<T, V>>
&mut self,
index: usize,
f: F
) -> Option<Key<T, V>>
where where
F: FnOnce(&Key<T, V>) -> Key<T, V>, F: FnOnce(&Key<T, V>) -> Key<T, V>,
T: PartialOrd T: PartialOrd,
{ {
let key = self.remove(index)?; let key = self.remove(index)?;
self.add(f(&key)); self.add(f(&key));
@ -256,7 +293,7 @@ impl<T, V> Spline<T, V> {
pub fn get_mut(&mut self, index: usize) -> Option<KeyMut<T, V>> { pub fn get_mut(&mut self, index: usize) -> Option<KeyMut<T, V>> {
self.0.get_mut(index).map(|key| KeyMut { self.0.get_mut(index).map(|key| KeyMut {
value: &mut key.value, value: &mut key.value,
interpolation: &mut key.interpolation interpolation: &mut key.interpolation,
}) })
} }
} }
@ -275,17 +312,19 @@ pub struct KeyMut<'a, T, V> {
// Normalize a time ([0;1]) given two control points. // Normalize a time ([0;1]) given two control points.
#[inline(always)] #[inline(always)]
pub(crate) fn normalize_time<T, V>( pub(crate) fn normalize_time<T, V>(t: T, cp: &Key<T, V>, cp1: &Key<T, V>) -> T
t: T, where
cp: &Key<T, V>, T: Additive + Div<T, Output = T> + PartialEq,
cp1: &Key<T, V> {
) -> T where T: Additive + Div<T, Output = T> + PartialEq {
assert!(cp1.t != cp.t, "overlapping keys"); assert!(cp1.t != cp.t, "overlapping keys");
(t - cp.t) / (cp1.t - cp.t) (t - cp.t) / (cp1.t - cp.t)
} }
// Find the lower control point corresponding to a given time. // Find the lower control point corresponding to a given time.
fn search_lower_cp<T, V>(cps: &[Key<T, V>], t: T) -> Option<usize> where T: PartialOrd { fn search_lower_cp<T, V>(cps: &[Key<T, V>], t: T) -> Option<usize>
where
T: PartialOrd,
{
let mut i = 0; let mut i = 0;
let len = cps.len(); let len = cps.len();
@ -295,7 +334,7 @@ fn search_lower_cp<T, V>(cps: &[Key<T, V>], t: T) -> Option<usize> where T: Part
loop { loop {
let cp = &cps[i]; let cp = &cps[i];
let cp1 = &cps[i+1]; let cp1 = &cps[i + 1];
if t >= cp1.t { if t >= cp1.t {
if i >= len - 2 { if i >= len - 2 {

View File

@ -1,8 +1,9 @@
use float_cmp::approx_eq;
use splines::{Interpolation, Key, Spline}; use splines::{Interpolation, Key, Spline};
#[cfg(feature = "cgmath")] use cgmath as cg; #[cfg(feature = "cgmath")]
#[cfg(feature = "nalgebra")] use nalgebra as na; use cgmath as cg;
#[cfg(feature = "nalgebra")]
use nalgebra as na;
#[test] #[test]
fn step_interpolation_f32() { fn step_interpolation_f32() {
@ -153,9 +154,19 @@ fn several_interpolations_several_keys() {
#[cfg(feature = "cgmath")] #[cfg(feature = "cgmath")]
#[test] #[test]
fn stroke_bezier_straight() { fn stroke_bezier_straight() {
use float_cmp::approx_eq;
let keys = vec![ let keys = vec![
Key::new(0.0, cg::Vector2::new(0., 1.), Interpolation::StrokeBezier(cg::Vector2::new(0., 1.), cg::Vector2::new(0., 1.))), Key::new(
Key::new(5.0, cg::Vector2::new(5., 1.), Interpolation::StrokeBezier(cg::Vector2::new(5., 1.), cg::Vector2::new(5., 1.))) 0.0,
cg::Vector2::new(0., 1.),
Interpolation::StrokeBezier(cg::Vector2::new(0., 1.), cg::Vector2::new(0., 1.)),
),
Key::new(
5.0,
cg::Vector2::new(5., 1.),
Interpolation::StrokeBezier(cg::Vector2::new(5., 1.), cg::Vector2::new(5., 1.)),
),
]; ];
let spline = Spline::from_vec(keys); let spline = Spline::from_vec(keys);