Expand description
§ndarray_cg
This crate provides math functionality for computer graphics based on ndarray
. The approach used in ndarray for computer graphics math is highly flexible and performant, even though there are many specialized crates focused on game development and computer graphics.
To use it within workspace, simply add it to the Cargo.toml
ndarray_cg = { workspace = true, features = { "enabled" } }
§Example: Trivial
use ndarray_cg::d2;
// Will create the following matrix
// [ 1.0, 2.0,
// 3.0, 4.0,
// 5.0, 6.0 ]
let matrix = mat::Mat< 2, 2, f32, DescriptorOrderRowMajor >::from_row_major( [ 1.0, 2.0, 3.0, 4.0 ] );
// For computer graphics related matrices, you can use a shortcut:
// Will create the following matrix
// [ 1.0, 2.0,
// 3.0, 4.0 ]
let matrix = mat::Mat2::from_row_major( [ 1.0, 2.0, 3.0, 4.0 ] );
// You can multiply two matrices
let rotated_matrix = mat::mat2x2::rot( 45.0f32.to_radians() ) * matrix;
// You can iterate over your matrix in different ways
let matrix = mat::Mat< 2, 3, f32, DescriptorOrderRowMajor >::from_row_major( [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 ] );
for ( id, v ) in rotated_matrix.iter_indexed_msfirst()
{
println!( " Index: {:?} , value: {:?}", id, v );
}
for ( id, v ) in rotated_matrix.lane_indexed_iter( 1, 0 )
{
println!( " Index: {:?} , value: {:?}", id, v );
}
§Example: Adding
use ndarray_cg::
{
Mat,
d2,
};
let mat_a = Mat::< 2, 2, f32 >::zero().raw_set
([
1.0, 2.0,
3.0, 4.0,
]);
let mat_b = Mat::< 2, 2, f32 >::zero().raw_set
([
5.0, 6.0,
7.0, 8.0,
]);
let mut mat_r = Mat::< 2, 2, f32 >::zero();
// Perform addition
d2::add( &mut mat_r, &mat_a, &mat_b );
let exp = Mat::< 2, 2, f32 >::zero().raw_set
([
6.0, 8.0,
10.0, 12.0,
]);
assert_eq!( mat_r.raw_slice(), exp.raw_slice(), "Expected {:?}, got {:?}", exp.raw_slice(), mat_r.raw_slice() );
// Operator overloading
let mat_r = &mat_a + &mat_b;
assert_eq!( mat_r.raw_slice(), exp.raw_slice(), "Expected {:?}, got {:?}", exp.raw_slice(), mat_r.raw_slice() );
§Example: Multiplication
use ndarray_cg::
{
Mat,
d2,
};
let mat_a = Mat::< 1, 3, f32 >::zero().raw_set
([
1.0, 2.0, 3.0,
]);
let mat_b = Mat::< 3, 2, f32 >::zero().raw_set
([
7.0, 8.0,
9.0, 10.0,
11.0, 12.0,
]);
let mut mat_r = Mat::< 1, 2, f32 >::zero();
// Perform multiplication
d2::mul( &mut mat_r, &mat_a, &mat_b );
let exp = Mat::< 1, 2, f32 >::zero().raw_set
([
58.0, 64.0,
]);
assert_eq!( mat_r.raw_slice(), exp.raw_slice(), "Expected {:?}, got {:?}", exp.raw_slice(), mat_r.raw_slice() );
// Operator overloading
let mat_r = &mat_a * &mat_b;
assert_eq!( mat_r.raw_slice(), exp.raw_slice(), "Expected {:?}, got {:?}", exp.raw_slice(), mat_r.raw_slice() );
§Example: Angle rotation
use ndarray_cg::RawSlice;
let angle_radians = PI / 4.0;
let cos_theta = angle_radians.cos();
let sin_theta = angle_radians.sin();
let exp : [ f32; 4 ] =
[
cos_theta, -sin_theta,
sin_theta, cos_theta,
];
let got = ndarray_cg::mat2x2::rot( angle_radians );
assert_eq!( got.raw_slice(), exp );
§Example: Translation
use ndarray_cg::RawSliceMut;
let tx = 2.0;
let ty = 3.0;
let exp = ndarray_cg::Mat::< 3, 3, _ >::zero().raw_set
([
1.0, 0.0, tx,
0.0, 1.0, ty,
0.0, 0.0, 1.0,
]);
let got = ndarray_cg::mat2x2h::translate( [ tx, ty ] );
assert_eq!( got, exp );
§Example: Basic scaling
use ndarray_cg::RawSlice;
let sx = 2.0;
let sy = 3.0;
let exp = ndarray_cg::Mat::< 2, 2, _ >::zero().raw_set
([
sx, 0.0,
0.0, sy,
]);
let got = ndarray_cg::mat2x2::scale( [ sx, sy ] );
assert_eq!( got, exp );
§Example: Reflecting
use ndarray_cg::RawSliceMut;
let exp = ndarray_cg::Mat::< 2, 2, _ >::zero().raw_set
([
1.0, 0.0,
0.0, -1.0,
]);
let got = ndarray_cg::mat2x2::reflect_x();
assert_eq!( got, exp );
§Example: Shearing
use ndarray_cg::RawSlice;
let shx = 1.0;
let shy = 0.5;
let exp = ndarray_cg::Mat::< 2, 2, _ >::zero().raw_set
([
1.0, shx,
shy, 1.0,
]);
let got = ndarray_cg::mat2x2::shear( [ shx, shy ] );
assert_eq!( got, exp );
§Example: Line iteration
use ndarray_cg::
{
IndexingRef,
RawSliceMut,
};
let mat = ndarray_cg::Mat::< 1, 2, f32 >::zero().raw_set( [ 1.0, 2.0 ] );
let row_iter : Vec< _ > = mat.lane_iter( 0, 0 ).collect();
let exp = vec![ &1.0, &2.0 ];
assert_eq!( row_iter, exp, "Expected {:?}, got {:?}", exp, row_iter );
Modules§
- _private_
phf_ reexport_ for_ macro_ if_ phf_ feature - Rust-PHF is a library to generate efficient lookup tables at compile time using perfect hash functions.
- additional_
attributes - Documentation for Additional Attributes
- approx
- Approximate equality for floating-point types can be determined using either relative difference or comparisons based on units in the last place (ULPs). Approximate equality for floating-point types can be determined using either relative difference or comparisons based on units in the last place (ULPs).
- clone_
dyn - d2
- 2D entities, like matrix and vector. Not the same as 2D in CG
- derive
- Derives.
- exposed
- Exposed namespace of the module.
- general
- General math traits. General math traits.
- index
- Multidimensional indices. Indices.
- mat
- Matrix and all related.
- mat2x2
- 2D entities with 2 along both dimensions. Useful for 2D graphics.
- mat2x2h
- 2D entities with 2+homogenous coordinate along both dimensions. Useful for 2D graphics.
- mat3x3h
- 3D entities with 3+homogenous coordinate along both dimensions. Useful for 3D graphics.
- md
- Multidimensional space.
- mem
- Memort-related things.
- nd
- Ndarray things.
- orphan
- Orphan namespace of the module.
- own
- Own namespace of the module.
- prelude
- Prelude to use essentials:
use my_module::prelude::*
. - vector
- Vector things. Indices.
Macros§
- abs_
diff_ eq - Approximate equality of using the absolute difference.
- abs_
diff_ ne - Approximate inequality of using the absolute difference.
- assert_
abs_ diff_ eq - An assertion that delegates to
abs_diff_eq!
, and panics with a helpful error on failure. - assert_
abs_ diff_ ne - An assertion that delegates to
abs_diff_ne!
, and panics with a helpful error on failure. - assert_
relative_ eq - An assertion that delegates to
relative_eq!
, and panics with a helpful error on failure. - assert_
relative_ ne - An assertion that delegates to
relative_ne!
, and panics with a helpful error on failure. - assert_
ulps_ eq - An assertion that delegates to
ulps_eq!
, and panics with a helpful error on failure. - assert_
ulps_ ne - An assertion that delegates to
ulps_ne!
, and panics with a helpful error on failure. - from
- Variadic constructor.
- relative_
eq - Approximate equality using both the absolute difference and relative based comparisons.
- relative_
ne - Approximate inequality using both the absolute difference and relative based comparisons.
- ulps_eq
- Approximate equality using both the absolute difference and ULPs (Units in Last Place).
- ulps_ne
- Approximate inequality using both the absolute difference and ULPs (Units in Last Place).
Structs§
- AbsDiff
- The requisite parameters for testing for approximate equality using a absolute difference based comparison.
- Mat
- A matrix structure.
- Relative
- The requisite parameters for testing for approximate equality using a relative based comparison.
- Ulps
- The requisite parameters for testing for approximate equality using an ULPs based comparison.
Enums§
- Parse
Error - The
ParseError
enum is a collection of all the possible reasons an enum can fail to parse from a string.
Traits§
- AbsDiff
Eq - Equality that is defined using the absolute difference of two numbers.
- Add
- The addition operator
+
. - AddAssign
- The addition assignment operator
+=
. - AsBytes
- Trait for converting data to byte slices.
- AsIx2
- Trait for converting a type into a 2-dimensional index (
Ix2
). - AsIx3
- Trait for converting a type into a 3-dimensional index (
Ix3
). - AsStatic
Ref Deprecated - A cheap reference-to-reference conversion. Used to convert a value to a
reference value with
'static
lifetime within generic code. - Clone
Dyn - A trait to upcast a clonable entity and clone it. It’s implemented for all entities which can be cloned.
- Collection
- A trait for collections of scalars.
- Const
Layout - Trait for setting values in a matrix.
- Const
Length - A trait implemented for entities with known length at compile-time.
- Div
- The division operator
/
. - DivAssign
- The division assignment operator
/=
. - Enum
Count - A trait for capturing the number of variants in Enum. This trait can be autoderived by
strum_macros
. - Enum
Message - Associates additional pieces of information with an Enum. This can be
autoimplemented by deriving
EnumMessage
and annotating your variants with#[strum(message="...")]
. - Enum
Property EnumProperty
is a trait that makes it possible to store additional information with enum variants. This trait is designed to be used with the macro of the same name in thestrum_macros
crate. Currently, the only string literals are supported in attributes, the other methods will be implemented as additional attribute types become stabilized.- Error
Error
is a trait representing the basic expectations for error values, i.e., values of typeE
inResult<T, E>
.- From1
- Constructor with single argument.
- From2
- Constructor with two arguments.
- From3
- Constructor with three arguments.
- Indexable
- Trait for objects that have an indexable dimension.
- Indexing
Mut - Trait for indexing and iterating over matrix elements with mutable access.
- Indexing
Ref - Trait for indexing and iterating over matrix elements.
- Into
- A value-to-value conversion that consumes the input value. The
opposite of
From
. - Into1
- value-to-value conversion that consumes the input value. Change left and rught, but keep semantic of `From1``.
- Into
Enum Iterator - This trait designates that an
Enum
can be iterated over. It can be auto generated usingstrum_macros
on your behalf. - Into
Iterator - Conversion into an
Iterator
. - Linalg
Scalar - Elements that support linear algebra operations.
- MatEl
- MatWith
Shape - A trait indicate that matrix in case of referencing it can be interpreted as such having specified shape
ROWS x COLS
. - MatWith
Shape Mut - A trait indicate that matrix in case of mutable referencing it can be interpreted as such having specified shape
ROWS x COLS
. - Mul
- The multiplication operator
*
. - MulAssign
- The multiplication assignment operator
*=
. - NdFloat
- Floating-point element types
f32
andf64
. - Pod
- Marker trait for “plain old data”.
- RawSlice
- RawSlice
Mut - Trait for accessing and modifying the underlying data of a collection as a mutable slice.
- Relative
Eq - Equality comparisons between two numbers using both the absolute difference and relative based comparisons.
- Rotation
- Trait for representing and manipulating rotations.
- Scalar
Mut - Trait for setting values in a matrix.
- Scalar
Ref - Trait for setting values in a matrix.
- Stride
Trait - Trait for objects that have a stride.
- Sub
- The subtraction operator
-
. - SubAssign
- The subtraction assignment operator
-=
. - Sum
- Trait to represent types that can be created by summing up an iterator.
- TryInto
- An attempted conversion that consumes
self
, which may or may not be expensive. - UlpsEq
- Equality comparisons between two numbers using both the absolute difference and ULPs (Units in Last Place) based comparisons.
- Variant
Iterator - Variant
Metadata - Variant
Names - A trait for retrieving the names of each variant in Enum. This trait can
be autoderived by
strum_macros
. - Vector
Iter - Trait to get iterator over elements of a vector. Should be implemented even for scalars.
- Vector
Iter Mut - Trait to get iterator over elements of a vector.
- Vector
Iterator - Trait that encapsulates an vector elements iterator with specific characteristics and implemetning
CloneDyn
. - Vector
Iterator Ref - Trait that encapsulates an vector elements iterator with specific characteristics and implemetning
CloneDyn
. - Vector
Mut - A trait for accessing a mutable reference to a fixed-size array from a collection.
- Vector
Ref - A trait for accessing a reference to a fixed-size array from a collection.
- Vector
Space - Vector
Space Mut - Vector
With Length - A trait indicate that entity in case of referencing it can be interpreted as such having specified length
LEN
. - Vector
With Length Mut - A trait indicate that entity in case of mutable referencing it can be interpreted as such having specified length
LEN
. - Zero
- Defines an additive identity element for
Self
.
Functions§
- Ix0
- Create a zero-dimensional index
- Ix1
- Create a one-dimensional index
- Ix2
- Create a two-dimensional index
- Ix3
- Create a three-dimensional index
- Ix4
- Create a four-dimensional index
- Ix5
- Create a five-dimensional index
- Ix6
- Create a six-dimensional index
- clone
- True clone which is applicable not only to clonable entities, but to trait objects implementing CloneDyn.
- clone_
into_ box - Clone boxed dyn.
Type Aliases§
- Ix
- Array index type
- Ix0
- zero-dimensionial
- Ix1
- one-dimensional
- Ix2
- two-dimensional
- Ix3
- three-dimensional
- Ix4
- four-dimensional
- Ix5
- five-dimensional
- Ix6
- six-dimensional
- Mat2
- Mat3
- Mat4
Attribute Macros§
- clone_
dyn - Derive macro to generate former for a structure. Former is variation of Builder Pattern.
- phantom
- Provides an automatic
PhantomData
field for a struct based on its generic types.
Derive Macros§
- Add
- What
#[derive(Add)]
generates - AddAssign
- What
#[derive(AddAssign)]
generates - AsMut
- Derive macro to implement AsMut when-ever it’s possible to do automatically.
- AsRef
- Derive macro to implement AsRef when-ever it’s possible to do automatically.
- AsRef
Str - Converts enum variants to
&'static str
. - AsStatic
Str - Constructor
- What
#[derive(Constructor)]
generates - Deref
- Derive macro to implement Deref when-ever it’s possible to do automatically.
- Deref
Mut - Derive macro to implement Deref when-ever it’s possible to do automatically.
- Display
- Div
- What
#[derive(Mul)]
generates - DivAssign
- What
#[derive(MulAssign)]
generates - Enum
Count - Add a constant
usize
equal to the number of variants. - Enum
Discriminants - Generate a new type with only the discriminant names.
- EnumIs
- Generated
is_*()
methods for each variant. E.g.Color.is_red()
. - Enum
Iter - Creates a new type that iterates of the variants of an enum.
- Enum
Message - Add a verbose message to an enum variant.
- Enum
Property - Add custom properties to enum variants.
- Enum
String - Converts strings to enum variants based on their name.
- Enum
TryAs - Generated
try_as_*()
methods for all tuple-style variants. E.g.Message.try_as_write()
. - Enum
Variant Names - Implements
Strum::VariantNames
which adds an associated constantVARIANTS
which is an array of discriminant names. - Error
- Using
#[derive(Error)]
- From
- Provides an automatic
From
implementation for struct wrapping a single value. - From
Repr - Add a function to enum that allows accessing variants by its discriminant
- FromStr
- Index
- Provides an automatic Index trait implementation when-ever it’s possible.
- Index
Mut - Provides an automatic IndexMut trait implementation when-ever it’s possible.
- Inner
From - Derive macro to implement From converting outer type into inner when-ever it’s possible to do automatically.
- Into
- What
#[derive(Into)]
generates - Into
Iterator - Using
#[derive(IntoIterator)]
- Into
Static Str - Implements
From<MyEnum> for &'static str
on an enum. - IsVariant
- What
#[derive(IsVariant)]
generates - Mul
- What
#[derive(Mul)]
generates - MulAssign
- What
#[derive(MulAssign)]
generates - New
- Provides an automatic
new
implementation for struct wrapping a single value. - Not
- Provides an automatic Not trait implementation for struct.
- Pod
- Derive the
Pod
trait for a struct - Sub
- What
#[derive(Add)]
generates - SubAssign
- What
#[derive(AddAssign)]
generates - Sum
- Using
#[derive(Sum)]
- ToString
- implements
std::string::ToString
on an enum - TryInto
- What
#[derive(TryInto)]
generates - Unwrap
- What
#[derive(Unwrap)]
generates - Variadic
From - The
derive_variadic_from
macro is designed to provide a way to implement theFrom
-like traits for structs with a variable number of fields, allowing them to be constructed from tuples of different lengths or from individual arguments. This functionality is particularly useful for creating flexible constructors that enable different methods of instantiation for a struct. By automating the implementation of traits, this macro reduces boilerplate code and enhances code readability and maintainability.