cgmath Documentation
repository·master·Indexed 22 days ago
https://github.com/rustgd/cgmathA linear algebra and mathematics library for computer graphics (v0.18.0) providing fixed-dimension vectors, matrices, quaternions, and transformation types. It features a trait-based API (VectorSpace, MetricSpace, InnerSpace, EuclideanSpace), type-safe angle wrappers (Rad, Deg), and support for perspective projections and spatial transformations. The library treats vectors as column matrices and offers an optional swizzle feature for vector component manipulation.
What's inside cgmath
- cgmath-rs is a linear algebra and mathematics library specifically designed for computer graphics. It provides common mathematical structures used in graphics programming, including vectors, matrices, quaternions, and projection types.
Understand cgmath vector-matrix multiplication conventions
mastercgmath treats vectors as column matrices (column vectors). When performing transformations, the matrix must be placed on the left of the vector.
Consequently, the library implements the multiplication operator for
Matrix * Vector, but it does not implementVector * Matrix.Enable swizzling via Cargo features
masterTo use swizzle operators (familiar to GPU programmers), you must enable the
swizzlefeature in yourCargo.tomlor via the command line.Enabling this feature increases the library size by approximately 0.6MB, but unused operators will be optimized away by the compiler in release mode when linked statically.
The Quaternion type
masterA
Quaternion<S>represents a rotation in 3D space using a scalar partsand a vector partv(Vector3<S>). It is marked as#[repr(C)]for compatibility. Quaternions can be constructed from individual components, from a scalar and a vector, or converted from Euler angles.pub struct Quaternion<S> { pub v: Vector3<S>, pub s: S, }Understand Point types in cgmath
masterIn
cgmath, Points represent fixed positions in affine space. They are distinct from Vectors because points have no length or direction; they only represent a specific location.Supported types:
Point1<S>: A point in 1-dimensional space.Point2<S>: A point in 2-dimensional space.Point3<S>: A point in 3-dimensional space.
All point types are marked as
#[repr(C)]and support common traits likeCopy,Clone,PartialEq, andHash.What are Euler angles in cgmath and how to use them
masterEuler<A>represents a rotation in three-dimensional space using a set of Tait–Bryan angles with an XYZ axis rotation sequence (intrinsic rotations). The rotation is applied first around the X axis (pitch), then the Y axis (yaw), and lastly the Z axis (roll).Important Considerations
- Gimbal Lock: Euler angles are prone to gimbal lock and are difficult to interpolate. It is highly recommended to convert them to a more robust representation like a
Quaternion,Basis3,Matrix3, orMatrix4for actual rotation logic. - Ranges:
x(pitch):[-pi, pi]y(yaw):[-pi/2, pi/2]z(roll):[-pi, pi]
Conversion
You can convert
Eulerangles into other rotation types using theFromtrait. For example, to create aQuaternionfrom Euler angles:use cgmath::{Deg, Euler, Quaternion}; let rotation = Quaternion::from(Euler { x: Deg(90.0), y: Deg(45.0), z: Deg(15.0), });- Gimbal Lock: Euler angles are prone to gimbal lock and are difficult to interpolate. It is highly recommended to convert them to a more robust representation like a
Use the Rotation trait for generic transformations
masterThe
Rotationtrait defines a generic interface for transformations that create circular motion and preserve at least one point in space. It is implemented by types likeBasis2andBasis3.Key capabilities include:
- Creating rotations via
look_at(direction and up vector) orbetween_vectors(shortest rotation between two unit vectors). - Transforming vectors via
rotate_vectorand points viarotate_point. - Reversing a rotation using
invert().
- Creating rotations via
Understand the cgmath trait hierarchy
mastercgmath uses a trait-based API to organize mathematical operations by their properties. The primary traits are:
VectorSpace: Main operators for vectors, quaternions, and matrices.MetricSpace: Types with a distance function.InnerSpace: Types with a dot (inner) product (e.g., vectors or quaternions), used for magnitude and normalization.EuclideanSpace: Represents points in euclidean space with an associated space of displacement vectors.Matrix: Common operations for matrices of arbitrary dimensions.SquareMatrix: Operations specific to matrices where rows equal columns.Array: Contiguous, indexable arrays (specifically for vectors).ElementWise: Element-wise arithmetic operations (addition, subtraction, multiplication, division, and remainder).
Use the cgmath prelude to import main traits
masterTo avoid importing mathematical traits individually, use the
preludemodule. This provides access to the core traits required for vector, matrix, and quaternion operations, such asVectorSpace,MetricSpace,InnerSpace, andEuclideanSpace.use cgmath::prelude::*;Convert cgmath types to arrays using the `conv` module
masterWhen type inference is difficult—such as when declaring uniforms for graphics libraries like
glium—you can use thecgmath::convmodule to convert cgmath types into fixed-length arrays. This is a cleaner alternative to usingInto::<[T; N]>::into(value)directly.use cgmath::{Matrix4, Point2}; use cgmath::prelude::*; use cgmath::conv::*; let point = Point2::new(1, 2); let matrix = Matrix4::from_scale(2.0); // Using conv functions for cleaner syntax in macros or assignments let point_array = array2(point); let matrix_array = array4x4(matrix);Use swizzling to manipulate vector components
masterWhen theswizzlefeature is enabled, you can create new vectors by selecting and reordering components from an existing vector using swizzle methods.Serialize and Deserialize Decomposed transforms with Serde
masterIf the
serdefeature is enabled,Decomposed<V, R>implementsSerializeandDeserialize. The data is represented as a struct with three fields:scalerotdisp