gemath 0.1.0

Type-safe game math with type-level units/spaces, typed angles, and explicit fallible ops (plus optional geometry/collision).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// Re-export shared marker types for backwards-compatible paths like `gemath::vec3::Meters`.
pub use crate::markers::{Local, Meters, Pixels, Screen, World};

use core::marker::PhantomData;
use crate::angle::{Degrees, Radians};
use crate::math;
#[cfg(feature = "unit_vec")]
use crate::unit_vec::UnitVec3;

/// 3D vector with type-level unit and coordinate space
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Default)]
pub struct Vec3<Unit: Copy = (), Space: Copy = ()> {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    #[cfg_attr(feature = "serde", serde(skip))]
    _unit: PhantomData<Unit>,
    #[cfg_attr(feature = "serde", serde(skip))]
    _space: PhantomData<Space>,
}

/// Type aliases for common units and spaces
pub type Vec3f32 = Vec3<(),()>;
pub type Vec3Meters = Vec3<Meters,()>;
pub type Vec3Pixels = Vec3<Pixels,()>;
pub type Vec3World = Vec3<(),World>;
pub type Vec3Local = Vec3<(),Local>;
pub type Vec3Screen = Vec3<(),Screen>;
pub type Vec3MetersWorld = Vec3<Meters,World>;
pub type Vec3PixelsScreen = Vec3<Pixels,Screen>;

impl<Unit: Copy, Space: Copy> Vec3<Unit, Space> {
    pub const ZERO: Self = Self { x: 0.0, y: 0.0, z: 0.0, _unit: PhantomData, _space: PhantomData };

    #[inline]
    pub const fn new(x: f32, y: f32, z: f32) -> Self {
        Self { x, y, z, _unit: PhantomData, _space: PhantomData }
    }

    /// Calculates the dot product of two vectors.
    #[inline]
    pub const fn dot(self, other: Self) -> f32 {
        self.x * other.x + self.y * other.y + self.z * other.z
    }

    #[inline]
    pub const fn yxz(self) -> Self {
        Self { x: self.y, y: self.x, z: self.z, _unit: PhantomData, _space: PhantomData }
    }

    /// Computes the cross product of two Vec3 vectors.
    #[inline]
    pub const fn cross(self, rhs: Self) -> Self {
        Self {
            x: self.y * rhs.z - self.z * rhs.y,
            y: self.z * rhs.x - self.x * rhs.z,
            z: self.x * rhs.y - self.y * rhs.x,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Calculates the squared length (magnitude squared) of the vector.
    /// This is equivalent to `self.dot(self)`.
    #[inline]
    pub const fn length_squared(self) -> f32 {
        self.dot(self)
    }

    /// Calculates the length (magnitude) of the vector.
    #[inline]
    pub fn length(self) -> f32 {
        math::sqrt(self.length_squared())
    }

    /// Normalizes the vector to unit length.
    /// Returns `Vec3::ZERO` if the vector has zero length.
    #[inline]
    pub fn normalize(self) -> Self {
        let len_sq = self.length_squared();
        if len_sq == 0.0 {
            // Or use a small epsilon comparison
            Self::ZERO
        } else {
            self / math::sqrt(len_sq)
        }
    }

    /// Tries to normalize the vector to unit length.
    /// Returns `None` if the vector has zero length.
    #[inline]
    pub fn try_normalize(self) -> Option<Self> {
        let len_sq = self.length_squared();
        if len_sq > 0.0 {
            Some(self * (1.0 / math::sqrt(len_sq)))
        } else {
            None
        }
    }

    /// Divides this vector by a scalar, returning `None` for invalid divisors.
    ///
    /// Returns `None` if `rhs` is zero (including `-0.0`) or non-finite (`NaN`, `±inf`).
    #[inline]
    pub fn checked_div_scalar(self, rhs: f32) -> Option<Self> {
        if rhs == 0.0 || !rhs.is_finite() {
            None
        } else {
            Some(self / rhs)
        }
    }

    /// Reflects the vector `self` off a surface with the given `normal`.
    /// `normal` is assumed to be of unit length.
    /// Formula: `self - normal * 2.0 * self.dot(normal)`
    #[inline]
    pub fn reflect(self, normal: Self) -> Self {
        self - normal * (2.0 * self.dot(normal))
    }

    /// Reflects this vector about a **unit** normal.
    #[inline]
    #[cfg(feature = "unit_vec")]
    pub fn reflect_unit(self, normal: UnitVec3<Unit, Space>) -> Self {
        self.reflect(normal.as_vec())
    }

    /// Computes the refraction of this vector (`i`) given a surface normal `n` and an index of refraction `eta` (n1/n2).
    /// Returns a zero vector if total internal reflection occurs.
    /// Matches the C++ gb_math implementation.
    pub fn refract(self, normal: Self, eta: f32) -> Self {
        let n_dot_i = normal.dot(self);
        let k = 1.0 - eta * eta * (1.0 - n_dot_i * n_dot_i);

        if k < 0.0 {
            Self::ZERO
        } else {
            self * eta - normal * (eta * n_dot_i * math::sqrt(k))
        }
    }

    /// Attempts to compute the refraction of this vector (`i`) given a surface normal `n` and an index of refraction `eta` (n1/n2).
    /// Returns `None` if total internal reflection occurs.
    /// Matches the C++ gb_math implementation logic.
    pub fn try_refract(self, normal: Self, eta: f32) -> Option<Self> {
        let n_dot_i = normal.dot(self);
        let k = 1.0 - eta * eta * (1.0 - n_dot_i * n_dot_i);

        if k < 0.0 {
            None
        } else {
            Some(self * eta - normal * (eta * n_dot_i * math::sqrt(k)))
        }
    }

    /// Computes refraction using a **unit** normal.
    #[inline]
    #[cfg(feature = "unit_vec")]
    pub fn refract_unit(self, normal: UnitVec3<Unit, Space>, eta: f32) -> Self {
        self.refract(normal.as_vec(), eta)
    }

    /// Attempts refraction using a **unit** normal.
    #[inline]
    #[cfg(feature = "unit_vec")]
    pub fn try_refract_unit(self, normal: UnitVec3<Unit, Space>, eta: f32) -> Option<Self> {
        self.try_refract(normal.as_vec(), eta)
    }

    /// Reflects the vector `i` about the normal `n` (static version).
    pub fn reflect_incident(i: Self, n: Self) -> Self {
        i - n * (2.0 * i.dot(n))
    }

    /// Refracts the incident vector `i` through a surface with normal `n` (static version).
    pub fn refract_gl(i: Self, n: Self, eta: f32) -> Self {
        let dot_ni = i.dot(n);
        let k = 1.0 - eta * eta * (1.0 - dot_ni * dot_ni);
        if k < 0.0 {
            Self::ZERO
        } else {
            i * eta - n * (eta * dot_ni + math::sqrt(k))
        }
    }

    /// Attempts to refract the incident vector `i` through a surface with normal `n` (static version).
    pub fn try_refract_gl(i: Self, n: Self, eta: f32) -> Option<Self> {
        let dot_ni = i.dot(n);
        let k = 1.0 - eta * eta * (1.0 - dot_ni * dot_ni);
        if k < 0.0 {
            None
        } else {
            Some(i * eta - n * (eta * dot_ni + math::sqrt(k)))
        }
    }

    /// Refracts the incident vector `i` through a surface with normal `n` (static version).
    ///
    /// This is the naming-consistent alias for `refract_gl`.
    #[inline]
    pub fn refract_incident(i: Self, n: Self, eta: f32) -> Self {
        Self::refract_gl(i, n, eta)
    }

    /// Attempts to refract the incident vector `i` through a surface with normal `n` (static version).
    ///
    /// This is the naming-consistent alias for `try_refract_gl`.
    #[inline]
    pub fn try_refract_incident(i: Self, n: Self, eta: f32) -> Option<Self> {
        Self::try_refract_gl(i, n, eta)
    }

    /// Linearly interpolates between two vectors.
    #[inline]
    pub fn lerp(self, b: Self, t: f32) -> Self {
        Self {
            x: self.x + (b.x - self.x) * t,
            y: self.y + (b.y - self.y) * t,
            z: self.z + (b.z - self.z) * t,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns the angle (in radians) between self and other.
    pub fn angle_between(self, other: Self) -> f32 {
        let dot = self.dot(other);
        let len_product = self.length() * other.length();
        if len_product == 0.0 {
            0.0
        } else {
            math::acos((dot / len_product).clamp(-1.0, 1.0))
        }
    }

    /// Projects self onto other.
    pub fn project_onto(self, other: Self) -> Self {
        let other_len_sq = other.length_squared();
        if other_len_sq == 0.0 {
            Self::ZERO
        } else {
            other * (self.dot(other) / other_len_sq)
        }
    }

    /// Returns a vector perpendicular to self (rotated 90 degrees counterclockwise).
    pub fn perp(self) -> Self {
        Self {
            x: -self.y,
            y: self.x,
            z: self.z,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Normalizes the vector or returns Vec3::ZERO if length is zero.
    pub fn normalize_or_zero(self) -> Self {
        let len = self.length();
        if len == 0.0 { Self::ZERO } else { self / len }
    }

    /// Returns the distance between self and other.
    pub fn distance(self, other: Self) -> f32 {
        (self - other).length()
    }

    /// Clamps each component of self between min and max.
    pub fn clamp(self, min: Self, max: Self) -> Self {
        Self {
            x: self.x.max(min.x).min(max.x),
            y: self.y.max(min.y).min(max.y),
            z: self.z.max(min.z).min(max.z),
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns the component-wise minimum of self and other.
    #[inline]
    pub const fn min(self, other: Self) -> Self {
        Self {
            x: if self.x < other.x { self.x } else { other.x },
            y: if self.y < other.y { self.y } else { other.y },
            z: if self.z < other.z { self.z } else { other.z },
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns the component-wise maximum of self and other.
    #[inline]
    pub const fn max(self, other: Self) -> Self {
        Self {
            x: if self.x > other.x { self.x } else { other.x },
            y: if self.y > other.y { self.y } else { other.y },
            z: if self.z > other.z { self.z } else { other.z },
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns true if any component is NaN.
    pub fn is_nan(self) -> bool {
        self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
    }

    /// Returns true if all components are finite.
    pub fn is_finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
    }

    /// Rotates the vector around an arbitrary axis (unit vector) by the given angle (in radians, CCW, right-hand rule).
    pub fn rotate_axis(self, axis: Vec3<Unit, Space>, angle: Radians) -> Self {
        // Rodrigues' rotation formula
        let cos = math::cos(angle.0);
        let sin = math::sin(angle.0);
        let one_minus_cos = 1.0 - cos;
        let k = axis;
        let v = Vec3::new(self.x, self.y, self.z);
        let dot = k.dot(v);
        let cross = k.cross(v);
        let rotated = v * cos + cross * sin + k * (dot * one_minus_cos);
        Self {
            x: rotated.x,
            y: rotated.y,
            z: rotated.z,
            _unit: core::marker::PhantomData,
            _space: core::marker::PhantomData,
        }
    }

    /// Rotates around a **unit** axis using Rodrigues' rotation formula.
    #[inline]
    #[cfg(feature = "unit_vec")]
    pub fn rotate_unit_axis(self, axis: UnitVec3<Unit, Space>, angle: Radians) -> Self {
        self.rotate_axis(axis.as_vec(), angle)
    }

    /// Rotates the vector around the Z axis by the given angle (in radians, CCW). (For compatibility)
    pub fn rotate(self, angle: Radians) -> Self {
        let z_axis = Vec3::new(0.0, 0.0, 1.0);
        self.rotate_axis(z_axis, angle)
    }

    /// Rotates the vector around the Z axis by the given angle (in degrees, CCW). (For compatibility)
    pub fn rotate_deg(self, angle: Degrees) -> Self {
        self.rotate(angle.to_radians())
    }
}

use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

impl<Unit: Copy, Space: Copy> Add for Vec3<Unit, Space> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
            z: self.z + rhs.z,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> AddAssign for Vec3<Unit, Space> {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        self.x += rhs.x;
        self.y += rhs.y;
        self.z += rhs.z;
    }
}

impl<Unit: Copy, Space: Copy> Sub for Vec3<Unit, Space> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> SubAssign for Vec3<Unit, Space> {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        self.x -= rhs.x;
        self.y -= rhs.y;
        self.z -= rhs.z;
    }
}

impl<Unit: Copy, Space: Copy> Mul<f32> for Vec3<Unit, Space> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: f32) -> Self::Output {
        Self {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> Mul<Vec3<Unit, Space>> for f32 {
    type Output = Vec3<Unit, Space>;
    #[inline]
    fn mul(self, rhs: Vec3<Unit, Space>) -> Self::Output {
        Vec3 {
            x: self * rhs.x,
            y: self * rhs.y,
            z: self * rhs.z,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> MulAssign<f32> for Vec3<Unit, Space> {
    #[inline]
    fn mul_assign(&mut self, rhs: f32) {
        self.x *= rhs;
        self.y *= rhs;
        self.z *= rhs;
    }
}

// Hadamard product Vec3 * Vec3
impl<Unit: Copy, Space: Copy> Mul<Vec3<Unit, Space>> for Vec3<Unit, Space> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x * rhs.x,
            y: self.y * rhs.y,
            z: self.z * rhs.z,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> MulAssign<Vec3<Unit, Space>> for Vec3<Unit, Space> {
    #[inline]
    fn mul_assign(&mut self, rhs: Self) {
        self.x *= rhs.x;
        self.y *= rhs.y;
        self.z *= rhs.z;
    }
}

impl<Unit: Copy, Space: Copy> Div<f32> for Vec3<Unit, Space> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: f32) -> Self::Output {
        Self {
            x: self.x / rhs,
            y: self.y / rhs,
            z: self.z / rhs,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> DivAssign<f32> for Vec3<Unit, Space> {
    #[inline]
    fn div_assign(&mut self, rhs: f32) {
        self.x /= rhs;
        self.y /= rhs;
        self.z /= rhs;
    }
}

// Hadamard division Vec3 / Vec3
impl<Unit: Copy, Space: Copy> Div<Vec3<Unit, Space>> for Vec3<Unit, Space> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x / rhs.x,
            y: self.y / rhs.y,
            z: self.z / rhs.z,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> DivAssign<Vec3<Unit, Space>> for Vec3<Unit, Space> {
    #[inline]
    fn div_assign(&mut self, rhs: Self) {
        self.x /= rhs.x;
        self.y /= rhs.y;
        self.z /= rhs.z;
    }
}

impl<Unit: Copy, Space: Copy> Neg for Vec3<Unit, Space> {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self::Output {
        Self {
            x: -self.x,
            y: -self.y,
            z: -self.z,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

// Example: conversion from Vec3<Meters, Space> to Vec3<Pixels, Space>
impl<Space: Copy> Vec3<Meters, Space> {
    pub fn to_pixels(self, scale: f32) -> Vec3<Pixels, Space> {
        Vec3 { x: self.x * scale, y: self.y * scale, z: self.z * scale, _unit: PhantomData, _space: PhantomData }
    }
}