embedded_vector/lib.rs
1// Copyright (C) 2026 Jorge Andre Castro
2//
3// This program is free software: you can redistribute it and/or modify it
4// under the terms of the GNU General Public License as published by the
5// Free Software Foundation, either version 2 of the License, or (at your option)
6// any later version.
7
8//! # embedded-vector
9//!
10//! 2D, 3D, and 4D `f32` vectors for `no_std` embedded systems.
11//!
12//! No standard-library dependency, no `unsafe`, no allocation, and no panics.
13//! Uses [`embedded_f32_sqrt`] for square-root calculations.
14//!
15//! ## Quick start
16//!
17//! ```rust
18//! use embedded_vector::{Vec3, Vec4};
19//!
20//! let a = Vec3::new(1.0, 2.0, 3.0);
21//! let b = Vec3::new(4.0, 5.0, 6.0);
22//!
23//! assert_eq!(a + b, Vec3::new(5.0, 7.0, 9.0));
24//! assert_eq!(a.dot(&b), 32.0);
25//! assert_eq!(a.cross(&b), Vec3::new(-3.0, 6.0, -3.0));
26//!
27//! let n = a.norm().unwrap(); // √14 ≈ 3.742
28//! let u = a.normalize().unwrap(); // Unit vector
29//! assert!((u.norm().unwrap() - 1.0).abs() < 1e-5);
30//!
31//! // Homogeneous coordinates
32//! let p = Vec4::from_vec3(a, 2.0);
33//! assert_eq!(p.perspective_divide().unwrap(), Vec3::new(0.5, 1.0, 1.5));
34//! # let _ = n;
35//! ```
36//!
37//! ## Numerical robustness
38//!
39//! `norm`, `normalize`, and `distance` handle vectors with very large (`1e30`)
40//! or very small (`1e-30`) components: the calculation scales the values when
41//! `x² + y² + …` would overflow or underflow to zero.
42
43#![no_std]
44#![forbid(unsafe_code)]
45#![warn(missing_docs)]
46
47use embedded_f32_sqrt::sqrt;
48
49// ─────────────────────────────────────────────────────────────
50// Erreurs
51// ─────────────────────────────────────────────────────────────
52
53/// Errors returned by vector operations.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum VecError {
57 /// Zero vector: normalization, projection, or reflection is undefined.
58 ZeroNorm,
59 /// A `NaN` or infinite value was found in the input or result.
60 NonFiniteValue,
61 /// Division by zero (scalar divisor or zero `w` component).
62 DivisionByZero,
63}
64
65// ─────────────────────────────────────────────────────────────
66// Robust norm (internal)
67// ─────────────────────────────────────────────────────────────
68
69/// Euclidean norm without intermediate overflow or underflow.
70fn robust_norm<const N: usize>(c: [f32; N]) -> Result<f32, VecError> {
71 let mut max = 0.0_f32;
72 for v in c {
73 if !v.is_finite() {
74 return Err(VecError::NonFiniteValue);
75 }
76 let a = v.abs();
77 if a > max {
78 max = a;
79 }
80 }
81 if max == 0.0 {
82 return Ok(0.0);
83 }
84
85 // Fast path: the sum of squares is representable and normal.
86 let mut sq = 0.0_f32;
87 for v in c {
88 sq += v * v;
89 }
90 if sq.is_finite() && sq >= f32::MIN_POSITIVE {
91 return sqrt(sq).map_err(|_| VecError::NonFiniteValue);
92 }
93
94 // Slow path: scale by the largest component.
95 let mut s = 0.0_f32;
96 for v in c {
97 let r = v / max;
98 s += r * r;
99 }
100 let n = sqrt(s).map_err(|_| VecError::NonFiniteValue)? * max;
101 if n.is_finite() {
102 Ok(n)
103 } else {
104 Err(VecError::NonFiniteValue)
105 }
106}
107
108// ─────────────────────────────────────────────────────────────
109// Implementation shared by Vec2 / Vec3 / Vec4
110// ─────────────────────────────────────────────────────────────
111
112macro_rules! impl_vec {
113 ($T:ident, $N:literal, $($f:ident : $i:literal),+) => {
114 impl $T {
115 /// Creates a new vector.
116 #[inline]
117 pub const fn new($($f: f32),+) -> Self {
118 Self { $($f),+ }
119 }
120
121 /// Zero vector.
122 pub const ZERO: Self = Self { $($f: 0.0),+ };
123
124 /// Vector whose components are all `1.0`.
125 pub const ONE: Self = Self { $($f: 1.0),+ };
126
127 /// Returns the components as an array.
128 #[inline]
129 pub const fn as_array(&self) -> [f32; $N] {
130 [$(self.$f),+]
131 }
132
133 /// Creates a vector from an array.
134 #[inline]
135 pub const fn from_array(v: [f32; $N]) -> Self {
136 Self { $($f: v[$i]),+ }
137 }
138
139 /// Dot product.
140 #[inline]
141 pub fn dot(&self, rhs: &Self) -> f32 {
142 0.0 $(+ self.$f * rhs.$f)+
143 }
144
145 /// Squared norm. Infallible, but may be `inf` or `0` for extreme
146 /// components; use [`Self::norm`] in those cases.
147 #[inline]
148 pub fn norm_sq(&self) -> f32 {
149 self.dot(self)
150 }
151
152 /// Euclidean norm (robust for very large or very small values).
153 ///
154 /// Returns [`VecError::NonFiniteValue`] if a component is `NaN` or
155 /// infinite, or if the norm exceeds `f32::MAX`.
156 /// The norm of the zero vector is `Ok(0.0)`.
157 pub fn norm(&self) -> Result<f32, VecError> {
158 robust_norm(self.as_array())
159 }
160
161 /// Unit vector in the same direction.
162 ///
163 /// Returns [`VecError::ZeroNorm`] for an exact zero vector and
164 /// [`VecError::NonFiniteValue`] if a component is invalid.
165 pub fn normalize(&self) -> Result<Self, VecError> {
166 let n = self.norm()?;
167 if n == 0.0 {
168 return Err(VecError::ZeroNorm);
169 }
170 Ok(Self { $($f: self.$f / n),+ })
171 }
172
173 /// Like [`Self::normalize`], but returns [`Self::ZERO`] on failure.
174 #[inline]
175 pub fn normalize_or_zero(&self) -> Self {
176 self.normalize().unwrap_or(Self::ZERO)
177 }
178
179 /// Squared distance (avoids the square root).
180 #[inline]
181 pub fn distance_sq(&self, rhs: &Self) -> f32 {
182 (*self - *rhs).norm_sq()
183 }
184
185 /// Distance euclidienne entre deux vecteurs.
186 pub fn distance(&self, rhs: &Self) -> Result<f32, VecError> {
187 (*self - *rhs).norm()
188 }
189
190 /// Linear interpolation: `self + t * (rhs - self)`.
191 #[inline]
192 pub fn lerp(&self, rhs: &Self, t: f32) -> Self {
193 Self { $($f: self.$f + t * (rhs.$f - self.$f)),+ }
194 }
195
196 /// Component-wise multiplication (Hadamard product).
197 #[inline]
198 pub fn hadamard(&self, rhs: &Self) -> Self {
199 Self { $($f: self.$f * rhs.$f),+ }
200 }
201
202 /// Component-wise minimum.
203 #[inline]
204 pub fn min(&self, rhs: &Self) -> Self {
205 Self { $($f: self.$f.min(rhs.$f)),+ }
206 }
207
208 /// Component-wise maximum.
209 #[inline]
210 pub fn max(&self, rhs: &Self) -> Self {
211 Self { $($f: self.$f.max(rhs.$f)),+ }
212 }
213
214 /// Component-wise absolute value.
215 #[inline]
216 pub fn abs(&self) -> Self {
217 Self { $($f: self.$f.abs()),+ }
218 }
219
220 /// Divides by a scalar without silently producing `inf` or `NaN`.
221 ///
222 /// Returns [`VecError::DivisionByZero`] if `s == 0.0` and
223 /// [`VecError::NonFiniteValue`] if the result is not finite.
224 pub fn checked_div(&self, s: f32) -> Result<Self, VecError> {
225 if s == 0.0 {
226 return Err(VecError::DivisionByZero);
227 }
228 let r = *self / s;
229 if r.is_finite() { Ok(r) } else { Err(VecError::NonFiniteValue) }
230 }
231
232 /// Projection de `self` sur `rhs` : `(self·rhs / |rhs|²) * rhs`.
233 ///
234 /// Scale-independent for both inputs, avoiding overflow in intermediate
235 /// dot products and squared norms. Returns [`VecError::ZeroNorm`] if
236 /// `rhs` is zero, or [`VecError::NonFiniteValue`] for non-finite inputs
237 /// or an unrepresentable result.
238 pub fn project_onto(&self, rhs: &Self) -> Result<Self, VecError> {
239 let mut rhs_scale = 0.0_f32;
240 for v in rhs.as_array() {
241 if !v.is_finite() {
242 return Err(VecError::NonFiniteValue);
243 }
244 let a = v.abs();
245 if a > rhs_scale {
246 rhs_scale = a;
247 }
248 }
249 if rhs_scale == 0.0 {
250 return Err(VecError::ZeroNorm);
251 }
252
253 let mut self_scale = 0.0_f32;
254 for v in self.as_array() {
255 if !v.is_finite() {
256 return Err(VecError::NonFiniteValue);
257 }
258 let a = v.abs();
259 if a > self_scale {
260 self_scale = a;
261 }
262 }
263 if self_scale == 0.0 {
264 return Ok(Self::ZERO);
265 }
266
267 let direction = *rhs / rhs_scale;
268 let scaled_self = *self / self_scale;
269 let factor = scaled_self.dot(&direction) / direction.norm_sq();
270 let out = (direction * factor) * self_scale;
271 if out.is_finite() { Ok(out) } else { Err(VecError::NonFiniteValue) }
272 }
273
274 /// Component of `self` perpendicular to `rhs`: `self - proj(self, rhs)`.
275 pub fn reject_from(&self, rhs: &Self) -> Result<Self, VecError> {
276 let out = *self - self.project_onto(rhs)?;
277 if out.is_finite() { Ok(out) } else { Err(VecError::NonFiniteValue) }
278 }
279
280 /// Reflects `self` across the plane or line with normal `normal`.
281 ///
282 /// `normal` does not need to be a unit vector, but must be nonzero.
283 pub fn reflect(&self, normal: &Self) -> Result<Self, VecError> {
284 let out = *self - self.project_onto(normal)? * 2.0;
285 if out.is_finite() { Ok(out) } else { Err(VecError::NonFiniteValue) }
286 }
287
288 /// Returns `true` if all components are finite.
289 #[inline]
290 pub fn is_finite(&self) -> bool {
291 true $(&& self.$f.is_finite())+
292 }
293
294 /// Approximate equality: each component differs by at most `eps`.
295 #[inline]
296 pub fn is_approx_eq(&self, rhs: &Self, eps: f32) -> bool {
297 true $(&& (self.$f - rhs.$f).abs() <= eps)+
298 }
299 }
300
301 impl Default for $T {
302 #[inline]
303 fn default() -> Self { Self::ZERO }
304 }
305 impl From<[f32; $N]> for $T {
306 #[inline]
307 fn from(v: [f32; $N]) -> Self { Self::from_array(v) }
308 }
309 impl From<$T> for [f32; $N] {
310 #[inline]
311 fn from(v: $T) -> Self { v.as_array() }
312 }
313 impl core::ops::Add for $T {
314 type Output = Self;
315 #[inline]
316 fn add(self, rhs: Self) -> Self { Self { $($f: self.$f + rhs.$f),+ } }
317 }
318 impl core::ops::Sub for $T {
319 type Output = Self;
320 #[inline]
321 fn sub(self, rhs: Self) -> Self { Self { $($f: self.$f - rhs.$f),+ } }
322 }
323 impl core::ops::Mul<f32> for $T {
324 type Output = Self;
325 #[inline]
326 fn mul(self, s: f32) -> Self { Self { $($f: self.$f * s),+ } }
327 }
328 impl core::ops::Mul<$T> for f32 {
329 type Output = $T;
330 #[inline]
331 fn mul(self, v: $T) -> $T { v * self }
332 }
333 impl core::ops::Div<f32> for $T {
334 type Output = Self;
335 #[inline]
336 fn div(self, s: f32) -> Self { Self { $($f: self.$f / s),+ } }
337 }
338 impl core::ops::Neg for $T {
339 type Output = Self;
340 #[inline]
341 fn neg(self) -> Self { Self { $($f: -self.$f),+ } }
342 }
343 impl core::ops::AddAssign for $T {
344 #[inline]
345 fn add_assign(&mut self, rhs: Self) { $(self.$f += rhs.$f;)+ }
346 }
347 impl core::ops::SubAssign for $T {
348 #[inline]
349 fn sub_assign(&mut self, rhs: Self) { $(self.$f -= rhs.$f;)+ }
350 }
351 impl core::ops::MulAssign<f32> for $T {
352 #[inline]
353 fn mul_assign(&mut self, s: f32) { $(self.$f *= s;)+ }
354 }
355 impl core::ops::DivAssign<f32> for $T {
356 #[inline]
357 fn div_assign(&mut self, s: f32) { $(self.$f /= s;)+ }
358 }
359 impl core::iter::Sum for $T {
360 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
361 iter.fold(Self::ZERO, |a, b| a + b)
362 }
363 }
364 };
365}
366
367// ─────────────────────────────────────────────────────────────
368// Vec2
369// ─────────────────────────────────────────────────────────────
370
371/// A 2D vector of `f32` components.
372#[derive(Debug, Clone, Copy, PartialEq)]
373pub struct Vec2 {
374 /// X component.
375 pub x: f32,
376 /// Y component.
377 pub y: f32,
378}
379
380impl_vec!(Vec2, 2, x: 0, y: 1);
381
382impl Vec2 {
383 /// Unit vector along X: `[1, 0]`.
384 pub const X: Self = Self::new(1.0, 0.0);
385 /// Unit vector along Y: `[0, 1]`.
386 pub const Y: Self = Self::new(0.0, 1.0);
387
388 /// 2D cross product (the Z component of `self × rhs`): `x₁y₂ - y₁x₂`.
389 ///
390 /// Positive when `rhs` is to the left of `self` (counterclockwise).
391 #[inline]
392 pub fn cross(&self, rhs: &Self) -> f32 {
393 self.x * rhs.y - self.y * rhs.x
394 }
395
396 /// Perpendicular vector (90° counterclockwise rotation): `[-y, x]`.
397 #[inline]
398 pub const fn perp(&self) -> Self {
399 Self::new(-self.y, self.x)
400 }
401
402 /// Extends to `Vec3` with the `z` component.
403 #[inline]
404 pub const fn extend(&self, z: f32) -> Vec3 {
405 Vec3::new(self.x, self.y, z)
406 }
407}
408
409// ─────────────────────────────────────────────────────────────
410// Vec3
411// ─────────────────────────────────────────────────────────────
412
413/// A 3D vector of `f32` components.
414#[derive(Debug, Clone, Copy, PartialEq)]
415pub struct Vec3 {
416 /// X component.
417 pub x: f32,
418 /// Y component.
419 pub y: f32,
420 /// Z component.
421 pub z: f32,
422}
423
424impl_vec!(Vec3, 3, x: 0, y: 1, z: 2);
425
426impl Vec3 {
427 /// Unit vector along X: `[1, 0, 0]`.
428 pub const X: Self = Self::new(1.0, 0.0, 0.0);
429 /// Unit vector along Y: `[0, 1, 0]`.
430 pub const Y: Self = Self::new(0.0, 1.0, 0.0);
431 /// Unit vector along Z: `[0, 0, 1]`.
432 pub const Z: Self = Self::new(0.0, 0.0, 1.0);
433
434 /// Cross product: `self × rhs` (right-hand rule).
435 ///
436 /// Property: `a × b = -(b × a)`.
437 #[inline]
438 pub fn cross(&self, rhs: &Self) -> Self {
439 Self::new(
440 self.y * rhs.z - self.z * rhs.y,
441 self.z * rhs.x - self.x * rhs.z,
442 self.x * rhs.y - self.y * rhs.x,
443 )
444 }
445
446 /// Scalar triple product: `self · (b × c)` (signed parallelepiped volume).
447 #[inline]
448 pub fn triple(&self, b: &Self, c: &Self) -> f32 {
449 self.dot(&b.cross(c))
450 }
451
452 /// Removes the `z` component.
453 #[inline]
454 pub const fn truncate(&self) -> Vec2 {
455 Vec2::new(self.x, self.y)
456 }
457
458 /// Extends to `Vec4` with the `w` component.
459 #[inline]
460 pub const fn extend(&self, w: f32) -> Vec4 {
461 Vec4::new(self.x, self.y, self.z, w)
462 }
463}
464
465// ─────────────────────────────────────────────────────────────
466// Vec4
467// ─────────────────────────────────────────────────────────────
468
469/// A 4D vector of `f32` components.
470///
471/// Useful for homogeneous coordinates (`w=1` for a point, `w=0` for a
472/// direction), RGBA colors, and quaternions `(x, y, z, w)`.
473#[derive(Debug, Clone, Copy, PartialEq)]
474pub struct Vec4 {
475 /// X component.
476 pub x: f32,
477 /// Y component.
478 pub y: f32,
479 /// Z component.
480 pub z: f32,
481 /// W component.
482 pub w: f32,
483}
484
485impl_vec!(Vec4, 4, x: 0, y: 1, z: 2, w: 3);
486
487impl Vec4 {
488 /// Unit vector along X: `[1, 0, 0, 0]`.
489 pub const X: Self = Self::new(1.0, 0.0, 0.0, 0.0);
490 /// Unit vector along Y: `[0, 1, 0, 0]`.
491 pub const Y: Self = Self::new(0.0, 1.0, 0.0, 0.0);
492 /// Unit vector along Z: `[0, 0, 1, 0]`.
493 pub const Z: Self = Self::new(0.0, 0.0, 1.0, 0.0);
494 /// Unit vector along W: `[0, 0, 0, 1]`.
495 pub const W: Self = Self::new(0.0, 0.0, 0.0, 1.0);
496
497 /// Creates a `Vec4` from a `Vec3` by adding `w`.
498 ///
499 /// Convention: `w=1.0` for a point and `w=0.0` for a direction.
500 #[inline]
501 pub const fn from_vec3(v: Vec3, w: f32) -> Self {
502 Self::new(v.x, v.y, v.z, w)
503 }
504
505 /// Extracts the XYZ components as a `Vec3`, ignoring `w`.
506 #[inline]
507 pub const fn xyz(&self) -> Vec3 {
508 Vec3::new(self.x, self.y, self.z)
509 }
510
511 /// Perspective divide: `(x/w, y/w, z/w)`.
512 ///
513 /// Returns [`VecError::DivisionByZero`] if `w == 0` (a direction or point
514 /// at infinity), and [`VecError::NonFiniteValue`] if the result is not finite.
515 pub fn perspective_divide(&self) -> Result<Vec3, VecError> {
516 self.xyz().checked_div(self.w)
517 }
518}