Expand description
Ndarray extensions for computer graphics mathematics.
§🎯 ndarray_cg
High-performance computer graphics mathematics built on ndarray
A comprehensive matrix and linear algebra library specifically designed for computer graphics applications. Built on top of the powerful ndarray
crate, ndarray_cg provides specialized functionality for 2D/3D transformations, graphics pipelines, and geometric operations with excellent performance characteristics.
§✨ Features
§🔄 Matrix Operations
- 2D/3D/4D Matrices - Specialized matrix types for graphics (Mat2, Mat3, Mat4)
- Row & Column Major - Support for both memory layouts
- Operator Overloading - Natural mathematical syntax (+, -, *, etc.)
- In-Place Operations - Memory-efficient computations
§🎮 Graphics Transformations
- Rotation Matrices - 2D/3D rotation operations
- Translation - Homogeneous coordinate translations
- Scaling - Uniform and non-uniform scaling
- Reflection - Mirror transformations
- Shearing - Skew transformations
§🚀 Performance Optimized
- SIMD Support - Vectorized operations via ndarray
- Zero-Copy Views - Efficient memory access patterns
- Stack Allocation - Small matrices on stack
- Generic Types - Works with f32, f64, and other numeric types
§🔧 Developer Experience
- Type Aliases - Convenient F32x2x2, F32x3x3, F32x4x4 types
- Indexed Iteration - Multiple iteration patterns
- Debug Support - Rich debugging and display traits
§📦 Installation
Add to your Cargo.toml
:
ndarray_cg = { workspace = true, features = ["enabled"] }
§🚀 Quick Start
§Basic Matrix Operations
use ndarray_cg::*;
fn main() {
// Create a 2x2 matrix using row-major layout
// [ 1.0, 2.0 ]
// [ 3.0, 4.0 ]
let matrix = Mat2::from_row_major([1.0, 2.0, 3.0, 4.0]);
// Create a rotation matrix (45 degrees)
let rotation = mat2x2::rot(45.0f32.to_radians());
// Apply rotation to the matrix
let rotated = rotation * matrix;
println!("Original: {:?}", matrix.raw_slice());
println!("Rotated: {:?}", rotated.raw_slice());
}
§Common Graphics Transformations
ⓘ
use ndarray_cg::*;
use std::f32::consts::PI;
fn graphics_example() {
// 2D Rotation (45 degrees)
let angle = PI / 4.0;
let rotation = mat2x2::rot(angle);
// 2D Scaling
let scale = mat2x2::scale([2.0, 3.0]);
// 2D Translation (using homogeneous coordinates)
let translation = mat2x2h::translate([5.0, 10.0]);
// Reflection across X-axis
let reflect = mat2x2::reflect_x();
// Shearing transformation
let shear = mat2x2::shear([1.0, 0.5]);
// Combine transformations
let transform = translation * scale * rotation;
println!("Combined transform: {:?}", transform.raw_slice());
}
§Matrix Arithmetic Operations
use ndarray_cg::*;
fn arithmetic_examples() {
// Matrix addition
let mat_a = F32x2x2::from_row_major([
1.0, 2.0,
3.0, 4.0,
]);
let mat_b = F32x2x2::from_row_major([
5.0, 6.0,
7.0, 8.0,
]);
// Using operator overloading (recommended)
let result = &mat_a + &mat_b;
// Or using explicit function calls
let mut result2 = F32x2x2::default();
d2::add(&mut result2, &mat_a, &mat_b);
println!("Addition result: {:?}", result.raw_slice());
}
§Matrix Multiplication
use ndarray_cg::*;
use mat::DescriptorOrderRowMajor;
fn multiplication_example() {
// 1x3 matrix
let mat_a = Mat::<1, 3, f32, DescriptorOrderRowMajor>::from_row_major([
1.0, 2.0, 3.0,
]);
// 3x2 matrix
let mat_b = Mat::<3, 2, f32, DescriptorOrderRowMajor>::from_row_major([
7.0, 8.0,
9.0, 10.0,
11.0, 12.0,
]);
// Matrix multiplication: 1x3 * 3x2 = 1x2
let result = &mat_a * &mat_b;
println!("Multiplication result: {:?}", result.raw_slice()); // [58.0, 64.0]
}
§📖 API Reference
§Matrix Types
Type | Description | Use Case |
---|---|---|
Mat2 / F32x2x2 | 2x2 matrix | 2D transformations |
Mat3 / F32x3x3 | 3x3 matrix | 2D homogeneous coords |
Mat4 / F32x4x4 | 4x4 matrix | 3D transformations |
§Transformation Functions
Function | Purpose | Example |
---|---|---|
mat2x2::rot(angle) | 2D rotation | mat2x2::rot(PI / 4.0) |
mat2x2::scale([sx, sy]) | 2D scaling | mat2x2::scale([2.0, 3.0]) |
mat2x2h::translate([tx, ty]) | 2D translation | mat2x2h::translate([5.0, 10.0]) |
mat2x2::reflect_x() | X-axis reflection | mat2x2::reflect_x() |
mat2x2::shear([shx, shy]) | Shearing | mat2x2::shear([1.0, 0.5]) |
§Advanced Features
use ndarray_cg::*;
use mat::DescriptorOrderRowMajor;
fn advanced_features() {
// Matrix iteration
let matrix = Mat::<1, 2, f32, DescriptorOrderRowMajor>::from_row_major([1.0, 2.0]);
// Iterate over matrix lanes (rows/columns)
for value in matrix.lane_iter(0, 0) {
println!("Value: {}", value);
}
// Indexed iteration
for (index, value) in matrix.iter_indexed_msfirst() {
println!("Index: {:?}, Value: {}", index, value);
}
}
§🎯 Use Cases
- 2D Game Development - Sprite transformations and camera systems
- 3D Graphics Programming - Model-view-projection matrices
- Computer Vision - Image transformations and homography
- Animation Systems - Skeletal animation and keyframe interpolation
- Physics Simulations - Coordinate system transformations
§🔧 Advanced Configuration
§Features
enabled
- Core functionality (default)full
- All features enabled
§Memory Layout Options
ⓘ
use ndarray_cg::*;
use mat::{DescriptorOrderRowMajor, DescriptorOrderColumnMajor};
// Row-major (default for graphics)
let row_major = Mat::<2, 2, f32, DescriptorOrderRowMajor>::from_row_major([1.0, 2.0, 3.0, 4.0]);
// Column-major (for compatibility with certain graphics APIs)
let col_major = Mat::<2, 2, f32, DescriptorOrderColMajor>::default();
§⚡ Performance Notes
- Built on ndarray’s highly optimized SIMD operations
- Zero-cost abstractions over raw array operations
- Efficient memory layouts for cache performance
- Generic over numeric types (f32, f64, etc.)
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.
- mat3x3
- 3D entities with 3 along both dimensions. Useful for 3D graphics
- mat3x3h
- 3D entities with 3+homogenous coordinate along both dimensions. Useful for 3D graphics.
- mat4x4
- General functions for 4x4 matrices
- md
- Multidimensional space. This module serves as a central interface for accessing and managing data within various structures. It organizes functionalities into distinct layers for clarity and modularity, separating data access from attribute management.
- 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::*
. - quaternion
- This module defines the core data structure for quaternions,
Quat<E>
, along with common type aliases. Quaternions are used to represent rotations in 3D space in a compact and efficient manner, avoiding issues like gimbal lock. - 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.
- array
- Create an
Array
with one, two, three, four, five, or six dimensions. - 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. - azip
- Array zip macro: lock step function application across several arrays and producers.
- 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.
- s
- Slice argument constructor.
- 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.
- Array
Base - An n-dimensional array.
- Axis
- An axis index.
- Dim
- Dimension description.
- Mat
- A matrix structure.
- NewAxis
- Token to represent a new axis in a slice description.
- Quat
- Represents a quaternion using a 4D vector for its components
[x, y, z, w]
. - 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.
- Vector
- A vector structure.
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
+=
. - Array
Mut - A trait for accessing a mutable reference to a fixed-size array from a collection.
- Array
Ref - A trait for accessing a reference to a fixed-size array from a collection.
- AsArray
- Argument conversion into an array view
- AsBytes
- Trait for borrowing data as byte slices.
This trait abstracts the conversion of types that implement Pod (or collections thereof)
into their raw byte representation as a slice (
&[u8]
). - 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.
- Dimension
- Array shape and index trait.
- 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
Array - The
IntoArray
trait is used to convert a collection into a fixed-size array. - Into
Bytes - Trait for consuming data into an owned byte vector.
This trait is for types that can be meaningfully converted into a
Vec< u8 >
by consuming the original value. - 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
. - Into
Vector - A trait for types that can be converted into a
Vector
. - Linalg
Scalar - Elements that support linear algebra operations.
- MatEl
- Trait for indicating that a type can be used as a matrix element.
- 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
. - RawSlice
- Provides immutable access to the underlying data of a collection as a flat slice.
- 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.
- Shape
Builder - A trait for
Shape
andD where D: Dimension
that allows customizing the memory layout (strides) of an array shape. - 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
Space - A marker trait that groups together the essential immutable behaviors of a fixed-size vector.
- Vector
Space Mut - A marker trait that extends
VectorSpace
with mutable iteration capabilities. - 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§
- Dim
- Create a new dimension value.
- 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
- IxDyn
- Create a dynamic-dimensional index
- arr0
- Create a zero-dimensional array with the element
x
. - arr1
- Create a one-dimensional array with elements from
xs
. - arr2
- Create a two-dimensional array with elements from
xs
. - aview0
- Create a zero-dimensional array view borrowing
x
. - aview1
- Create a one-dimensional array view with elements borrowing
xs
. - aview2
- Create a two-dimensional array view with elements borrowing
xs
. - aview_
mut1 - Create a one-dimensional read-write array view with elements borrowing
xs
. - 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§
- ArcArray
- An array where the data has shared ownership and is copy on write.
- Array
- An array that owns its data uniquely.
- Array0
- zero-dimensional array
- Array1
- one-dimensional array
- Array2
- two-dimensional array
- Array3
- three-dimensional array
- Array4
- four-dimensional array
- Array5
- five-dimensional array
- Array6
- six-dimensional array
- ArrayD
- dynamic-dimensional array
- Array
View - A read-only array view.
- Array
View0 - zero-dimensional array view
- Array
View1 - one-dimensional array view
- Array
View2 - two-dimensional array view
- Array
View3 - three-dimensional array view
- Array
View4 - four-dimensional array view
- Array
View5 - five-dimensional array view
- Array
View6 - six-dimensional array view
- Array
ViewD - dynamic-dimensional array view
- Array
View Mut - A read-write array view.
- Array
View Mut0 - zero-dimensional read-write array view
- Array
View Mut1 - one-dimensional read-write array view
- Array
View Mut2 - two-dimensional read-write array view
- Array
View Mut3 - three-dimensional read-write array view
- Array
View Mut4 - four-dimensional read-write array view
- Array
View Mut5 - five-dimensional read-write array view
- Array
View Mut6 - six-dimensional read-write array view
- Array
View MutD - dynamic-dimensional read-write array view
- CowArray
- An array with copy-on-write behavior.
- F32x1
- A 1-dimensional vector of
f32
s. - F32x2
- A 2-dimensional vector of
f32
s. - F32x3
- A 3-dimensional vector of
f32
s. - F32x4
- A 4-dimensional vector of
f32
s. - F32x2x2
- Type aliases for 2x2
f32
column major matrix. - F32x3x3
- Type aliases for 3x3
f32
column major matrix. - F32x4x4
- Type aliases for 4x4
f32
column major matrix. - F64x1
- A 1-dimensional vector of
f64
s. - F64x2
- A 2-dimensional vector of
f64
s. - F64x3
- A 3-dimensional vector of
f64
s. - F64x4
- A 4-dimensional vector of
f64
s. - F64x2x2
- Type aliases for 2x2
f64
column major matrix. - F64x3x3
- Type aliases for 3x3
f64
column major matrix. - F64x4x4
- Type aliases for 4x4
f64
column major matrix. - I32x1
- A 1-dimensional vector of
i32
s. - I32x2
- A 2-dimensional vector of
i32
s. - I32x3
- A 3-dimensional vector of
i32
s. - I32x4
- A 4-dimensional vector of
i32
s. - I64x1
- A 1-dimensional vector of
i64
s. - I64x2
- A 2-dimensional vector of
i64
s. - I64x3
- A 3-dimensional vector of
i64
s. - I64x4
- A 4-dimensional vector of
i64
s. - 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
- IxDyn
- dynamic-dimensional
- Mat2
- Type aliases for 2x2 matrix.
- Mat3
- Type aliases for 3x3 matrix.
- Mat4
- Type aliases for 4x4 matrix.
- QuatF32
- A type alias for a quaternion with
f32
components. - QuatF64
- A type alias for a quaternion with
f64
components. - RawArray
View - A read-only array view without a lifetime.
- RawArray
View Mut - A mutable array view without a lifetime.
- U32x1
- A 1-dimensional vector of
u32
s. - U32x2
- A 2-dimensional vector of
u32
s. - U32x3
- A 3-dimensional vector of
u32
s. - U32x4
- A 4-dimensional vector of
u32
s. - U64x1
- A 1-dimensional vector of
u64
s. - U64x2
- A 2-dimensional vector of
u64
s. - U64x3
- A 3-dimensional vector of
u64
s. - U64x4
- A 4-dimensional vector of
u64
s.
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.
- 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.