glam/
lib.rs

1/*!
2# glam
3
4`glam` is a simple and fast linear algebra library for games and graphics.
5
6## Features
7
8* [`f32`](mod@f32) types
9  * vectors: [`Vec2`], [`Vec3`], [`Vec3A`] and [`Vec4`]
10  * square matrices: [`Mat2`], [`Mat3`], [`Mat3A`] and [`Mat4`]
11  * a quaternion type: [`Quat`]
12  * affine transformation types: [`Affine2`], [`Affine3`] and [`Affine3A`]
13* [`f64`](mod@f64) types
14  * vectors: [`DVec2`], [`DVec3`] and [`DVec4`]
15  * square matrices: [`DMat2`], [`DMat3`] and [`DMat4`]
16  * a quaternion type: [`DQuat`]
17  * affine transformation types: [`DAffine2`] and [`DAffine3`]
18* [`i8`](mod@i8) types
19  * vectors: [`I8Vec2`], [`I8Vec3`] and [`I8Vec4`]
20* [`u8`](mod@u8) types
21  * vectors: [`U8Vec2`], [`U8Vec3`] and [`U8Vec4`]
22* [`i16`](mod@i16) types
23  * vectors: [`I16Vec2`], [`I16Vec3`] and [`I16Vec4`]
24* [`u16`](mod@u16) types
25  * vectors: [`U16Vec2`], [`U16Vec3`] and [`U16Vec4`]
26* [`i32`](mod@i32) types
27  * vectors: [`IVec2`], [`IVec3`] and [`IVec4`]
28* [`u32`](mod@u32) types
29  * vectors: [`UVec2`], [`UVec3`] and [`UVec4`]
30* [`i64`](mod@i64) types
31  * vectors: [`I64Vec2`], [`I64Vec3`] and [`I64Vec4`]
32* [`u64`](mod@u64) types
33  * vectors: [`U64Vec2`], [`U64Vec3`] and [`U64Vec4`]
34* [`usize`](mod@usize) types
35  * vectors: [`USizeVec2`], [`USizeVec3`] and [`USizeVec4`]
36* [`bool`](mod@bool) types
37  * vectors: [`BVec2`], [`BVec3`] and [`BVec4`]
38
39## SIMD
40
41`glam` is built with SIMD in mind. Many `f32` types use 128-bit SIMD vector types for storage
42and/or implementation. The use of SIMD generally enables better performance than using primitive
43numeric types such as `f32`.
44
45Some `glam` types use SIMD for storage meaning they are 16 byte aligned, these types include
46`Mat2`, `Mat3A`, `Mat4`, `Quat`, `Vec3A`, `Vec4`, `Affine2` an `Affine3A`. Types
47with an `A` suffix are a SIMD alternative to a scalar type, e.g. `Vec3` uses `f32` storage and
48`Vec3A` uses SIMD storage.
49
50When SIMD is not available on the target the types will maintain 16 byte alignment and internal
51padding so that object sizes and layouts will not change between architectures. There are scalar
52math fallback implementations exist when SIMD is not available. It is intended to add support for
53other SIMD architectures once they appear in stable Rust.
54
55Currently only SSE2 on x86/x86_64, NEON on Aarch64, and simd128 on WASM are supported.
56
57## Vec3A and Mat3A
58
59`Vec3A` is a SIMD optimized version of the `Vec3` type, which due to 16 byte alignment results
60in `Vec3A` containing 4 bytes of padding making it 16 bytes in size in total. `Mat3A` is composed
61of three `Vec3A` columns.
62
63| Type       | `f32` bytes | Align bytes | Size bytes | Padding |
64|:-----------|------------:|------------:|-----------:|--------:|
65|[`Vec3`]    |           12|            4|          12|        0|
66|[`Vec3A`]   |           12|           16|          16|        4|
67|[`Mat3`]    |           36|            4|          36|        0|
68|[`Mat3A`]   |           36|           16|          48|       12|
69
70Despite this wasted space the SIMD implementations tend to outperform `f32` implementations in
71[**mathbench**](https://github.com/bitshifter/mathbench-rs) benchmarks.
72
73`glam` treats [`Vec3`] as the default 3D vector type and [`Vec3A`] a special case for optimization.
74When methods need to return a 3D vector they will generally return [`Vec3`].
75
76There are [`From`] trait implementations for converting from [`Vec4`] to a [`Vec3A`] and between
77[`Vec3`] and [`Vec3A`] (and vice versa).
78
79```
80use glam::{Vec3, Vec3A, Vec4};
81
82let v4 = Vec4::new(1.0, 2.0, 3.0, 4.0);
83
84// Convert from `Vec4` to `Vec3A`, this is a no-op if SIMD is supported.
85// We use an explicit method here instead of a From impl as data is lost in the conversion.
86let v3a = Vec3A::from_vec4(v4);
87assert_eq!(Vec3A::new(1.0, 2.0, 3.0), v3a);
88
89// Convert from `Vec3A` to `Vec3`.
90let v3 = Vec3::from(v3a);
91assert_eq!(Vec3::new(1.0, 2.0, 3.0), v3);
92
93// Convert from `Vec3` to `Vec3A`.
94let v3a = Vec3A::from(v3);
95assert_eq!(Vec3A::new(1.0, 2.0, 3.0), v3a);
96```
97
98## Affine2, Affine3 and Affine3A
99
100`Affine2`, `Affine3` and `Affine3A` are composed of a linear transform matrix and a vector
101translation. The represent 2D and 3D affine transformations which are commonly used in games.
102
103`Affine3` is composed from `Vec3` and `Mat3` whereas `Affine3A` is composed from `Mat3A` and
104`Vec3A`. `Affine3A` will generally be faster but is 16 byte aligned and 64 btyes verses `Affine3`
105which is 48 bytes.
106
107The table below shows the performance advantage of `Affine2` over `Mat3A` and `Mat3A` over `Mat3`.
108
109| operation          | `Mat3`      | `Mat3A`    | `Affine2`  |
110|--------------------|-------------|------------|------------|
111| inverse            | 11.4±0.09ns | 7.1±0.09ns | 5.4±0.06ns |
112| mul self           | 10.5±0.04ns | 5.2±0.05ns | 4.0±0.05ns |
113| transform point2   |  2.7±0.02ns | 2.7±0.03ns | 2.8±0.04ns |
114| transform vector2  |  2.6±0.01ns | 2.6±0.03ns | 2.3±0.02ns |
115
116Performance is much closer between `Mat4` and `Affine3A` with the affine type being faster to
117invert.
118
119| operation          | `Mat4`      | `Affine3A`  |
120|--------------------|-------------|-------------|
121| inverse            | 15.9±0.11ns | 10.8±0.06ns |
122| mul self           |  7.3±0.05ns |  7.0±0.06ns |
123| transform point3   |  3.6±0.02ns |  4.3±0.04ns |
124| transform point3a  |  3.0±0.02ns |  3.0±0.04ns |
125| transform vector3  |  4.1±0.02ns |  3.9±0.04ns |
126| transform vector3a |  2.8±0.02ns |  2.8±0.02ns |
127
128Benchmarks were taken on an Intel Core i7-4710HQ.
129
130## Linear algebra conventions
131
132`glam` interprets vectors as column matrices (also known as column vectors) meaning when
133transforming a vector with a matrix the matrix goes on the left.
134
135```
136use glam::{Mat3, Vec3};
137let m = Mat3::IDENTITY;
138let x = Vec3::X;
139let v = m * x;
140assert_eq!(v, x);
141```
142
143Matrices are stored in memory in column-major order.
144
145All angles are in radians. Rust provides the `f32::to_radians()` and `f64::to_radians()` methods to
146convert from degrees.
147
148## Direct element access
149
150Because some types may internally be implemented using SIMD types, direct access to vector elements
151is supported by implementing the [`Deref`] and [`DerefMut`] traits.
152
153```
154use glam::Vec3A;
155let mut v = Vec3A::new(1.0, 2.0, 3.0);
156assert_eq!(3.0, v.z);
157v.z += 1.0;
158assert_eq!(4.0, v.z);
159```
160
161[`Deref`]: https://doc.rust-lang.org/std/ops/trait.Deref.html
162[`DerefMut`]: https://doc.rust-lang.org/std/ops/trait.DerefMut.html
163
164## glam assertions
165
166`glam` does not enforce validity checks on method parameters at runtime. For example methods that
167require normalized vectors as input such as `Quat::from_axis_angle(axis, angle)` will not check
168that axis is a valid normalized vector. To help catch unintended misuse of `glam` the
169`debug-glam-assert` or `glam-assert` features can be enabled to add checks ensure that inputs to
170are valid.
171
172## Vector swizzles
173
174`glam` vector types have functions allowing elements of vectors to be reordered, this includes
175creating a vector of a different size from the vectors elements.
176
177The swizzle functions are implemented using traits to add them to each vector type. This is
178primarily because there are a lot of swizzle functions which can obfuscate the other vector
179functions in documentation and so on. The traits are [`Vec2Swizzles`], [`Vec3Swizzles`] and
180[`Vec4Swizzles`].
181
182Note that the [`Vec3Swizzles`] implementation for [`Vec3A`] will return a [`Vec3A`] for 3 element
183swizzles, all other implementations will return [`Vec3`].
184
185```
186use glam::{swizzles::*, Vec2, Vec3, Vec3A, Vec4};
187
188let v = Vec4::new(1.0, 2.0, 3.0, 4.0);
189
190// Reverse elements of `v`, if SIMD is supported this will use a vector shuffle.
191let wzyx = v.wzyx();
192assert_eq!(Vec4::new(4.0, 3.0, 2.0, 1.0), wzyx);
193
194// Swizzle the yzw elements of `v` into a `Vec3`
195let yzw = v.yzw();
196assert_eq!(Vec3::new(2.0, 3.0, 4.0), yzw);
197
198// To swizzle a `Vec4` into a `Vec3A` swizzle the `Vec4` first then convert to
199// `Vec3A`. If SIMD is supported this will use a vector shuffle. The last
200// element of the shuffled `Vec4` is ignored by the `Vec3A`.
201let yzw = Vec3A::from_vec4(v.yzwx());
202assert_eq!(Vec3A::new(2.0, 3.0, 4.0), yzw);
203
204// You can swizzle from a `Vec4` to a `Vec2`
205let xy = v.xy();
206assert_eq!(Vec2::new(1.0, 2.0), xy);
207
208// And back again
209let yyxx = xy.yyxx();
210assert_eq!(Vec4::new(2.0, 2.0, 1.0, 1.0), yyxx);
211```
212
213## SIMD and scalar consistency
214
215`glam` types implement `serde` `Serialize` and `Deserialize` traits to ensure
216that they will serialize and deserialize exactly the same whether or not
217SIMD support is being used.
218
219The SIMD versions implement the `core::fmt::Debug` and `core::fmt::Display`
220traits so they print the same as the scalar version.
221
222```
223use glam::Vec4;
224let a = Vec4::new(1.0, 2.0, 3.0, 4.0);
225assert_eq!(format!("{}", a), "[1, 2, 3, 4]");
226```
227
228## Optional features
229
230All `glam` dependencies are optional, however some are required for tests
231and benchmarks.
232
233* `approx` - traits and macros for approximate float comparisons
234* `arbitrary` - implementations of `Arbitrary` trait for all `glam` types.
235* `bytemuck` - for casting into slices of bytes
236* `encase` - `encase` trait implementations for `glam` types.
237* `libm` - uses `libm` math functions instead of `std`
238* `mint` - for interoperating with other 3D math libraries
239* `rand` - implementations of `Distribution` trait for all `glam` types.
240* `rkyv` - implementations of `Archive`, `Serialize` and `Deserialize` for all
241  `glam` types. Note that serialization is not interoperable with and without the
242  `scalar-math` feature. It should work between all other builds of `glam`.
243  Endian conversion is currently not supported
244* `bytecheck` - to perform archive validation when using the `rkyv` feature
245* `serde` - implementations of `Serialize` and `Deserialize` for all `glam`
246  types. Note that serialization should work between builds of `glam` with and without SIMD enabled
247* `speedy` - implementations of `speedy`'s `Readable` and `Writable` for all `glam` types.
248* `zerocopy` - implementations of zerocopy traits for safe transmutes.
249
250## Feature gates
251
252* `std` - the default feature, has no dependencies.
253* `nostd-libm` - uses `libm` math functions if `std` is not available
254* `scalar-math` - disables SIMD support and uses native alignment for all types.
255* `debug-glam-assert` - adds assertions in debug builds which check the validity of parameters
256  passed to `glam` to help catch runtime errors.
257* `glam-assert` - adds assertions to all builds which check the validity of parameters passed to
258  `glam` to help catch runtime errors.
259* `cuda` - forces `glam` types to match expected cuda alignment
260* `fast-math` - By default, glam attempts to provide bit-for-bit identical results on all platforms.
261  Using this feature will enable platform specific optimizations that may not be identical to other
262  platforms. **Intermediate libraries should not use this feature and defer the decision to the
263  final binary build**.
264* `core-simd` - enables SIMD support via the portable simd module. This is an unstable feature which
265  requires a nightly Rust toolchain and `std` support.
266
267## Minimum Supported Rust Version (MSRV)
268
269The minimum supported Rust version is `1.68.2`.
270
271*/
272#![doc(html_root_url = "https://docs.rs/glam/0.31.0")]
273#![cfg_attr(not(feature = "std"), no_std)]
274#![cfg_attr(target_arch = "spirv", feature(repr_simd))]
275#![deny(
276    rust_2018_compatibility,
277    rust_2018_idioms,
278    future_incompatible,
279    nonstandard_style
280)]
281// clippy doesn't like `to_array(&self)`
282#![allow(clippy::wrong_self_convention)]
283#![cfg_attr(
284    all(feature = "core-simd", not(feature = "scalar-math")),
285    feature(portable_simd)
286)]
287
288#[cfg(all(
289    not(feature = "std"),
290    not(feature = "libm"),
291    not(feature = "nostd-libm")
292))]
293compile_error!(
294    "You must specify a math backend. Consider enabling either `std`, `libm`, or `nostd-libm`."
295);
296
297#[macro_use]
298mod macros;
299
300mod align16;
301mod deref;
302mod euler;
303mod features;
304
305#[cfg(all(
306    target_arch = "aarch64",
307    not(any(feature = "core-simd", feature = "scalar-math"))
308))]
309mod neon;
310
311#[cfg(target_arch = "spirv")]
312mod spirv;
313
314#[cfg(all(
315    target_feature = "sse2",
316    not(any(feature = "core-simd", feature = "scalar-math"))
317))]
318mod sse2;
319
320#[cfg(all(
321    target_feature = "simd128",
322    not(any(feature = "core-simd", feature = "scalar-math"))
323))]
324mod wasm32;
325
326#[cfg(all(feature = "core-simd", not(feature = "scalar-math")))]
327mod coresimd;
328
329#[cfg(all(
330    target_feature = "sse2",
331    not(any(feature = "core-simd", feature = "scalar-math"))
332))]
333use align16::Align16;
334
335/** `bool` vector mask types. */
336pub mod bool;
337pub use self::bool::*;
338
339/** `f32` vector, quaternion and matrix types. */
340pub mod f32;
341pub use self::f32::*;
342
343/** `f64` vector, quaternion and matrix types. */
344pub mod f64;
345pub use self::f64::*;
346
347/** `i8` vector types. */
348pub mod i8;
349pub use self::i8::*;
350
351/** `u8` vector types. */
352pub mod u8;
353pub use self::u8::*;
354
355/** `i16` vector types. */
356pub mod i16;
357pub use self::i16::*;
358
359/** `u16` vector types. */
360pub mod u16;
361pub use self::u16::*;
362
363/** `i32` vector types. */
364pub mod i32;
365pub use self::i32::*;
366
367/** `u32` vector types. */
368pub mod u32;
369pub use self::u32::*;
370
371/** `i64` vector types. */
372pub mod i64;
373pub use self::i64::*;
374
375/** `u64` vector types. */
376pub mod u64;
377pub use self::u64::*;
378
379/** `usize` vector types. */
380pub mod usize;
381pub use self::usize::*;
382
383/** Traits adding swizzle methods to all vector types. */
384pub mod swizzles;
385pub use self::swizzles::{Vec2Swizzles, Vec3Swizzles, Vec4Swizzles};
386
387/** Rotation Helper */
388pub use euler::EulerRot;
389
390/** A trait for extending [`prim@f32`] and [`prim@f64`] with extra methods. */
391mod float;
392pub use float::FloatExt;