Skip to main content

three_rs/math/
vector3.rs

1//! Port of `three.js/src/math/Vector3.js`.
2//!
3//! All arithmetic is `f64`, matching JavaScript number semantics: three.js
4//! computes every transform in doubles and only narrows to `f32` when the
5//! value reaches a buffer or a uniform.
6
7use super::math_utils::{clamp, js_max, js_min};
8use super::{Color, Euler, Matrix3, Matrix4, Quaternion};
9
10/// Port of three.js' `Vector3`: an ordered triplet `(x, y, z)`, used for
11/// points, directions and anything else three.js models as three numbers.
12#[derive(Clone, Copy, Debug, Default, PartialEq)]
13pub struct Vector3 {
14    /// The x component.
15    pub x: f64,
16    /// The y component.
17    pub y: f64,
18    /// The z component.
19    pub z: f64,
20}
21
22impl Vector3 {
23    /// `new Vector3( x, y, z )`.
24    pub const fn new(x: f64, y: f64, z: f64) -> Self {
25        Self { x, y, z }
26    }
27
28    /// `(0, 0, 0)`.
29    pub const ZERO: Self = Self::new(0.0, 0.0, 0.0);
30
31    /// `Vector3.set()`.
32    pub fn set(&mut self, x: f64, y: f64, z: f64) -> &mut Self {
33        self.x = x;
34        self.y = y;
35        self.z = z;
36        self
37    }
38
39    /// `Vector3.setScalar()`.
40    pub fn set_scalar(&mut self, scalar: f64) -> &mut Self {
41        self.set(scalar, scalar, scalar)
42    }
43
44    /// `Vector3.setX()`.
45    pub fn set_x(&mut self, x: f64) -> &mut Self {
46        self.x = x;
47        self
48    }
49
50    /// `Vector3.setY()`.
51    pub fn set_y(&mut self, y: f64) -> &mut Self {
52        self.y = y;
53        self
54    }
55
56    /// `Vector3.setZ()`.
57    pub fn set_z(&mut self, z: f64) -> &mut Self {
58        self.z = z;
59        self
60    }
61
62    /// `Vector3.setComponent()`; panics where three.js throws.
63    pub fn set_component(&mut self, index: usize, value: f64) -> &mut Self {
64        match index {
65            0 => self.x = value,
66            1 => self.y = value,
67            2 => self.z = value,
68            _ => panic!("THREE.Vector3: index is out of range: {index}"),
69        }
70        self
71    }
72
73    /// `Vector3.getComponent()`.
74    pub fn get_component(&self, index: usize) -> f64 {
75        match index {
76            0 => self.x,
77            1 => self.y,
78            2 => self.z,
79            _ => panic!("THREE.Vector3: index is out of range: {index}"),
80        }
81    }
82
83    /// `Vector3.copy()`.
84    pub fn copy(&mut self, v: &Self) -> &mut Self {
85        self.x = v.x;
86        self.y = v.y;
87        self.z = v.z;
88        self
89    }
90
91    /// `Vector3.add()`.
92    pub fn add(&mut self, v: &Self) -> &mut Self {
93        self.x += v.x;
94        self.y += v.y;
95        self.z += v.z;
96        self
97    }
98
99    /// `Vector3.addScalar()`.
100    pub fn add_scalar(&mut self, s: f64) -> &mut Self {
101        self.x += s;
102        self.y += s;
103        self.z += s;
104        self
105    }
106
107    /// `Vector3.addVectors()`.
108    pub fn add_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
109        self.x = a.x + b.x;
110        self.y = a.y + b.y;
111        self.z = a.z + b.z;
112        self
113    }
114
115    /// `Vector3.addScaledVector()`.
116    pub fn add_scaled_vector(&mut self, v: &Self, s: f64) -> &mut Self {
117        self.x += v.x * s;
118        self.y += v.y * s;
119        self.z += v.z * s;
120        self
121    }
122
123    /// `Vector3.sub()`.
124    pub fn sub(&mut self, v: &Self) -> &mut Self {
125        self.x -= v.x;
126        self.y -= v.y;
127        self.z -= v.z;
128        self
129    }
130
131    /// `Vector3.subScalar()`.
132    pub fn sub_scalar(&mut self, s: f64) -> &mut Self {
133        self.x -= s;
134        self.y -= s;
135        self.z -= s;
136        self
137    }
138
139    /// `Vector3.subVectors()`.
140    pub fn sub_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
141        self.x = a.x - b.x;
142        self.y = a.y - b.y;
143        self.z = a.z - b.z;
144        self
145    }
146
147    /// `Vector3.multiply()`.
148    pub fn multiply(&mut self, v: &Self) -> &mut Self {
149        self.x *= v.x;
150        self.y *= v.y;
151        self.z *= v.z;
152        self
153    }
154
155    /// `Vector3.multiplyScalar()`.
156    pub fn multiply_scalar(&mut self, s: f64) -> &mut Self {
157        self.x *= s;
158        self.y *= s;
159        self.z *= s;
160        self
161    }
162
163    /// `Vector3.multiplyVectors()`.
164    pub fn multiply_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
165        self.x = a.x * b.x;
166        self.y = a.y * b.y;
167        self.z = a.z * b.z;
168        self
169    }
170
171    /// `Vector3.applyEuler()`.
172    pub fn apply_euler(&mut self, euler: &Euler) -> &mut Self {
173        let mut q = Quaternion::default();
174        q.set_from_euler(euler);
175        self.apply_quaternion(&q)
176    }
177
178    /// `Vector3.applyAxisAngle()`.
179    pub fn apply_axis_angle(&mut self, axis: &Self, angle: f64) -> &mut Self {
180        let mut q = Quaternion::default();
181        q.set_from_axis_angle(axis, angle);
182        self.apply_quaternion(&q)
183    }
184
185    /// `Vector3.applyMatrix3()`.
186    pub fn apply_matrix3(&mut self, m: &Matrix3) -> &mut Self {
187        let (x, y, z) = (self.x, self.y, self.z);
188        let e = &m.elements;
189
190        self.x = e[0] * x + e[3] * y + e[6] * z;
191        self.y = e[1] * x + e[4] * y + e[7] * z;
192        self.z = e[2] * x + e[5] * y + e[8] * z;
193
194        self
195    }
196
197    /// `Vector3.applyNormalMatrix()`.
198    pub fn apply_normal_matrix(&mut self, m: &Matrix3) -> &mut Self {
199        self.apply_matrix3(m).normalize()
200    }
201
202    /// `Vector3.applyMatrix4()`.
203    pub fn apply_matrix4(&mut self, m: &Matrix4) -> &mut Self {
204        let (x, y, z) = (self.x, self.y, self.z);
205        let e = &m.elements;
206
207        let w = 1.0 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
208
209        self.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
210        self.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
211        self.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
212
213        self
214    }
215
216    /// `Vector3.applyQuaternion()`.
217    pub fn apply_quaternion(&mut self, q: &Quaternion) -> &mut Self {
218        let (vx, vy, vz) = (self.x, self.y, self.z);
219        let (qx, qy, qz, qw) = (q.x, q.y, q.z, q.w);
220
221        // t = 2 * cross( q.xyz, v )
222        let tx = 2.0 * (qy * vz - qz * vy);
223        let ty = 2.0 * (qz * vx - qx * vz);
224        let tz = 2.0 * (qx * vy - qy * vx);
225
226        // v + q.w * t + cross( q.xyz, t )
227        self.x = vx + qw * tx + qy * tz - qz * ty;
228        self.y = vy + qw * ty + qz * tx - qx * tz;
229        self.z = vz + qw * tz + qx * ty - qy * tx;
230
231        self
232    }
233
234    /// `Vector3.project()`: world space to normalised device coordinates.
235    pub fn project(&mut self, camera: &impl crate::cameras::RenderCamera) -> &mut Self {
236        self.apply_matrix4(&camera.matrix_world_inverse())
237            .apply_matrix4(&camera.projection_matrix())
238    }
239
240    /// `Vector3.unproject()`: normalised device coordinates back to world space.
241    pub fn unproject(&mut self, camera: &impl crate::cameras::RenderCamera) -> &mut Self {
242        self.apply_matrix4(&camera.projection_matrix_inverse())
243            .apply_matrix4(&camera.matrix_world())
244    }
245
246    /// `Vector3.transformDirection()`.
247    pub fn transform_direction(&mut self, m: &Matrix4) -> &mut Self {
248        let (x, y, z) = (self.x, self.y, self.z);
249        let e = &m.elements;
250
251        self.x = e[0] * x + e[4] * y + e[8] * z;
252        self.y = e[1] * x + e[5] * y + e[9] * z;
253        self.z = e[2] * x + e[6] * y + e[10] * z;
254
255        self.normalize()
256    }
257
258    /// `Vector3.divide()`.
259    pub fn divide(&mut self, v: &Self) -> &mut Self {
260        self.x /= v.x;
261        self.y /= v.y;
262        self.z /= v.z;
263        self
264    }
265
266    /// `Vector3.divideScalar()`.
267    pub fn divide_scalar(&mut self, s: f64) -> &mut Self {
268        self.multiply_scalar(1.0 / s)
269    }
270
271    /// `Vector3.min()`.
272    pub fn min(&mut self, v: &Self) -> &mut Self {
273        self.x = js_min(self.x, v.x);
274        self.y = js_min(self.y, v.y);
275        self.z = js_min(self.z, v.z);
276        self
277    }
278
279    /// `Vector3.max()`.
280    pub fn max(&mut self, v: &Self) -> &mut Self {
281        self.x = js_max(self.x, v.x);
282        self.y = js_max(self.y, v.y);
283        self.z = js_max(self.z, v.z);
284        self
285    }
286
287    /// `Vector3.clamp()`.
288    pub fn clamp(&mut self, min: &Self, max: &Self) -> &mut Self {
289        self.x = clamp(self.x, min.x, max.x);
290        self.y = clamp(self.y, min.y, max.y);
291        self.z = clamp(self.z, min.z, max.z);
292        self
293    }
294
295    /// `Vector3.clampScalar()`.
296    pub fn clamp_scalar(&mut self, min_val: f64, max_val: f64) -> &mut Self {
297        self.x = clamp(self.x, min_val, max_val);
298        self.y = clamp(self.y, min_val, max_val);
299        self.z = clamp(self.z, min_val, max_val);
300        self
301    }
302
303    /// `Vector3.clampLength()`.
304    pub fn clamp_length(&mut self, min: f64, max: f64) -> &mut Self {
305        let length = self.length();
306        self.divide_scalar(if length == 0.0 { 1.0 } else { length })
307            .multiply_scalar(clamp(length, min, max))
308    }
309
310    /// `Vector3.floor()`.
311    pub fn floor(&mut self) -> &mut Self {
312        self.x = self.x.floor();
313        self.y = self.y.floor();
314        self.z = self.z.floor();
315        self
316    }
317
318    /// `Vector3.ceil()`.
319    pub fn ceil(&mut self) -> &mut Self {
320        self.x = self.x.ceil();
321        self.y = self.y.ceil();
322        self.z = self.z.ceil();
323        self
324    }
325
326    /// `Vector3.round()` — `Math.round`, which rounds half *up* (toward
327    /// +Infinity), not half away from zero the way Rust's `f64::round` does.
328    pub fn round(&mut self) -> &mut Self {
329        self.x = js_round(self.x);
330        self.y = js_round(self.y);
331        self.z = js_round(self.z);
332        self
333    }
334
335    /// `Vector3.roundToZero()` — `Math.trunc`.
336    pub fn round_to_zero(&mut self) -> &mut Self {
337        self.x = self.x.trunc();
338        self.y = self.y.trunc();
339        self.z = self.z.trunc();
340        self
341    }
342
343    /// `Vector3.negate()`.
344    pub fn negate(&mut self) -> &mut Self {
345        self.x = -self.x;
346        self.y = -self.y;
347        self.z = -self.z;
348        self
349    }
350
351    /// `Vector3.dot()`.
352    pub fn dot(&self, v: &Self) -> f64 {
353        self.x * v.x + self.y * v.y + self.z * v.z
354    }
355
356    /// `Vector3.lengthSq()`.
357    pub fn length_sq(&self) -> f64 {
358        self.x * self.x + self.y * self.y + self.z * self.z
359    }
360
361    /// `Vector3.length()`: the Euclidean length of this vector.
362    pub fn length(&self) -> f64 {
363        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
364    }
365
366    /// `Vector3.manhattanLength()`.
367    pub fn manhattan_length(&self) -> f64 {
368        self.x.abs() + self.y.abs() + self.z.abs()
369    }
370
371    /// `Vector3.normalize()`: divides by the length, or by 1 when the length is
372    /// 0. See [`Vector3::normalized`] for the form that returns the result
373    /// instead.
374    pub fn normalize(&mut self) -> &mut Self {
375        let l = self.length();
376        self.divide_scalar(if l == 0.0 { 1.0 } else { l })
377    }
378
379    /// `self` scaled to unit length, as a value, for expressions.
380    /// [`Vector3::normalize`] is the same scaling written in place.
381    pub fn normalized(mut self) -> Self {
382        self.normalize();
383        self
384    }
385
386    /// `Vector3.setLength()`.
387    pub fn set_length(&mut self, length: f64) -> &mut Self {
388        self.normalize().multiply_scalar(length)
389    }
390
391    /// `Vector3.lerp()`.
392    pub fn lerp(&mut self, v: &Self, alpha: f64) -> &mut Self {
393        self.x += (v.x - self.x) * alpha;
394        self.y += (v.y - self.y) * alpha;
395        self.z += (v.z - self.z) * alpha;
396        self
397    }
398
399    /// `Vector3.lerpVectors()`.
400    pub fn lerp_vectors(&mut self, v1: &Self, v2: &Self, alpha: f64) -> &mut Self {
401        self.x = v1.x + (v2.x - v1.x) * alpha;
402        self.y = v1.y + (v2.y - v1.y) * alpha;
403        self.z = v1.z + (v2.z - v1.z) * alpha;
404        self
405    }
406
407    /// `Vector3.cross()`, in place. See [`Vector3::crossed`] for the form that
408    /// returns the result instead.
409    pub fn cross(&mut self, v: &Self) -> &mut Self {
410        let a = *self;
411        self.cross_vectors(&a, v)
412    }
413
414    /// `self × v` as a value, for expressions. [`Vector3::cross`] is the same
415    /// product written in place.
416    pub fn crossed(&self, v: &Self) -> Self {
417        let mut out = *self;
418        out.cross(v);
419        out
420    }
421
422    /// `Vector3.crossVectors()`.
423    pub fn cross_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
424        let (ax, ay, az) = (a.x, a.y, a.z);
425        let (bx, by, bz) = (b.x, b.y, b.z);
426        self.x = ay * bz - az * by;
427        self.y = az * bx - ax * bz;
428        self.z = ax * by - ay * bx;
429        self
430    }
431
432    /// `Vector3.projectOnVector()`.
433    pub fn project_on_vector(&mut self, v: &Self) -> &mut Self {
434        let denominator = v.length_sq();
435
436        if denominator == 0.0 {
437            return self.set(0.0, 0.0, 0.0);
438        }
439
440        let scalar = v.dot(self) / denominator;
441        self.copy(v).multiply_scalar(scalar)
442    }
443
444    /// `Vector3.projectOnPlane()`.
445    pub fn project_on_plane(&mut self, plane_normal: &Self) -> &mut Self {
446        let mut v = *self;
447        v.project_on_vector(plane_normal);
448        self.sub(&v)
449    }
450
451    /// `Vector3.reflect()`.
452    pub fn reflect(&mut self, normal: &Self) -> &mut Self {
453        let mut v = *normal;
454        v.multiply_scalar(2.0 * self.dot(normal));
455        self.sub(&v)
456    }
457
458    /// `Vector3.angleTo()`.
459    pub fn angle_to(&self, v: &Self) -> f64 {
460        let denominator = (self.length_sq() * v.length_sq()).sqrt();
461
462        if denominator == 0.0 {
463            return std::f64::consts::PI / 2.0;
464        }
465
466        let theta = self.dot(v) / denominator;
467
468        clamp(theta, -1.0, 1.0).acos()
469    }
470
471    /// `Vector3.distanceTo()`.
472    pub fn distance_to(&self, v: &Self) -> f64 {
473        self.distance_to_squared(v).sqrt()
474    }
475
476    /// `Vector3.distanceToSquared()`.
477    pub fn distance_to_squared(&self, v: &Self) -> f64 {
478        let (dx, dy, dz) = (self.x - v.x, self.y - v.y, self.z - v.z);
479        dx * dx + dy * dy + dz * dz
480    }
481
482    /// `Vector3.manhattanDistanceTo()`.
483    pub fn manhattan_distance_to(&self, v: &Self) -> f64 {
484        (self.x - v.x).abs() + (self.y - v.y).abs() + (self.z - v.z).abs()
485    }
486
487    /// `Vector3.setFromSphericalCoords()`.
488    pub fn set_from_spherical_coords(&mut self, radius: f64, phi: f64, theta: f64) -> &mut Self {
489        let sin_phi_radius = phi.sin() * radius;
490
491        self.x = sin_phi_radius * theta.sin();
492        self.y = phi.cos() * radius;
493        self.z = sin_phi_radius * theta.cos();
494
495        self
496    }
497
498    /// `Vector3.setFromCylindricalCoords()`.
499    pub fn set_from_cylindrical_coords(&mut self, radius: f64, theta: f64, y: f64) -> &mut Self {
500        self.x = radius * theta.sin();
501        self.y = y;
502        self.z = radius * theta.cos();
503        self
504    }
505
506    /// `Vector3.setFromMatrixPosition()`.
507    pub fn set_from_matrix_position(&mut self, m: &Matrix4) -> &mut Self {
508        let e = &m.elements;
509        self.x = e[12];
510        self.y = e[13];
511        self.z = e[14];
512        self
513    }
514
515    /// `Vector3.setFromMatrixScale()`.
516    pub fn set_from_matrix_scale(&mut self, m: &Matrix4) -> &mut Self {
517        let sx = self.set_from_matrix_column(m, 0).length();
518        let sy = self.set_from_matrix_column(m, 1).length();
519        let sz = self.set_from_matrix_column(m, 2).length();
520
521        self.x = sx;
522        self.y = sy;
523        self.z = sz;
524
525        self
526    }
527
528    /// `Vector3.setFromMatrixColumn()`.
529    pub fn set_from_matrix_column(&mut self, m: &Matrix4, index: usize) -> &mut Self {
530        self.from_array(&m.elements, index * 4)
531    }
532
533    /// `Vector3.setFromMatrix3Column()`.
534    pub fn set_from_matrix3_column(&mut self, m: &Matrix3, index: usize) -> &mut Self {
535        self.from_array(&m.elements, index * 3)
536    }
537
538    /// `Vector3.setFromEuler()`.
539    pub fn set_from_euler(&mut self, e: &Euler) -> &mut Self {
540        self.x = e.x;
541        self.y = e.y;
542        self.z = e.z;
543        self
544    }
545
546    /// `Vector3.setFromColor()`.
547    pub fn set_from_color(&mut self, c: &Color) -> &mut Self {
548        self.x = c.r;
549        self.y = c.g;
550        self.z = c.b;
551        self
552    }
553
554    /// `Vector3.equals()`.
555    pub fn equals(&self, v: &Self) -> bool {
556        v.x == self.x && v.y == self.y && v.z == self.z
557    }
558
559    /// `Vector3.fromArray()`.
560    pub fn from_array(&mut self, array: &[f64], offset: usize) -> &mut Self {
561        self.x = array[offset];
562        self.y = array[offset + 1];
563        self.z = array[offset + 2];
564        self
565    }
566
567    /// `Vector3.toArray()`.
568    pub fn to_array(&self) -> [f64; 3] {
569        [self.x, self.y, self.z]
570    }
571}
572
573/// `Math.round`: ties go toward +Infinity, so `-0.5` rounds to `-0`, not `-1`.
574pub(crate) fn js_round(x: f64) -> f64 {
575    (x + 0.5).floor()
576}