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
use super::*;

/// A 3-dimensional vector.
///
/// This is three `f32` values, `x`, `y`, and `z`.
///
/// Internally, this data type is actually just a [`Vec4`]. The `w` coordinate
/// value is simply ignored during calculations. Doing it like this is a slight
/// waste of space, but gives much faster operation.
#[derive(Clone, Copy, Default)]
#[repr(align(16), C)]
pub struct Vec3 {
  pub(crate) v4: Vec4,
}
unsafe impl Zeroable for Vec3 {}
unsafe impl Pod for Vec3 {}
impl core::cmp::PartialEq for Vec3 {
  #[inline]
  fn eq(&self, rhs: &Self) -> bool {
    if_sse! {{
      let a: m128 = cast(self.v4);
      let b: m128 = cast(rhs.v4);
      // Note(Lokathor): Lanes 0/1/2 must be identical, lane 3 we don't care.
      (a.cmp_eq(b).move_mask() & 0b0111) == 0b0111
    } else {
      let a: [f32;4] = cast(self.v4);
      let b: [f32;4] = cast(rhs.v4);
      let eq0 = a[0] == b[0];
      let eq1 = a[1] == b[1];
      let eq2 = a[2] == b[2];
      eq0 & eq1 & eq2
    }}
  }
}

impl core::fmt::Debug for Vec3 {
  /// Passes the formatter along to the fields, so you can use any normal `f32`
  /// Debug format arguments that you like.
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    let [x, y, z, _]: [f32; 4] = cast(self.v4);
    f.write_str("Vec3 { x: ")?;
    core::fmt::Debug::fmt(&x, f)?;
    f.write_str(", y: ")?;
    core::fmt::Debug::fmt(&y, f)?;
    f.write_str(", z: ")?;
    core::fmt::Debug::fmt(&z, f)?;
    f.write_str(" }")
  }
}

impl core::fmt::Display for Vec3 {
  /// Display formats without labels like a 3-tuple.
  ///
  /// Passes the formatter along to the fields, so you can use any normal `f32`
  /// Display format arguments that you like.
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    let [x, y, z, _]: [f32; 4] = cast(*self);
    f.write_str("(")?;
    core::fmt::Display::fmt(&x, f)?;
    f.write_str(", ")?;
    core::fmt::Display::fmt(&y, f)?;
    f.write_str(", ")?;
    core::fmt::Display::fmt(&z, f)?;
    f.write_str(")")
  }
}

impl core::fmt::LowerExp for Vec3 {
  /// LowerExp formats like Display, but with the lower exponent.
  ///
  /// Passes the formatter along to the fields, so you can use any normal `f32`
  /// LowerExp format arguments that you like.
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    let [x, y, z, _]: [f32; 4] = cast(*self);
    f.write_str("(")?;
    core::fmt::LowerExp::fmt(&x, f)?;
    f.write_str(", ")?;
    core::fmt::LowerExp::fmt(&y, f)?;
    f.write_str(", ")?;
    core::fmt::LowerExp::fmt(&z, f)?;
    f.write_str(")")
  }
}

impl core::fmt::UpperExp for Vec3 {
  /// UpperExp formats like Display, but with the upper exponent.
  ///
  /// Passes the formatter along to the fields, so you can use any normal `f32`
  /// UpperExp format arguments that you like.
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    let [x, y, z, _]: [f32; 4] = cast(*self);
    f.write_str("(")?;
    core::fmt::UpperExp::fmt(&x, f)?;
    f.write_str(", ")?;
    core::fmt::UpperExp::fmt(&y, f)?;
    f.write_str(", ")?;
    core::fmt::UpperExp::fmt(&z, f)?;
    f.write_str(")")
  }
}

impl Index<usize> for Vec3 {
  type Output = f32;
  #[inline(always)]
  fn index(&self, index: usize) -> &f32 {
    let arr_ref: &[f32; 4] = cast_ref(self);
    // Note(Lokathor): This style seems weird but it makes all vec/mat type give
    // a similar error message when the input is out of bounds.
    match index {
      0 => &arr_ref[0],
      1 => &arr_ref[1],
      2 => &arr_ref[2],
      otherwise => panic!("Vec3 index out of bounds: {}", otherwise),
    }
  }
}
impl IndexMut<usize> for Vec3 {
  #[inline(always)]
  fn index_mut(&mut self, index: usize) -> &mut f32 {
    let arr_mut: &mut [f32; 4] = cast_mut(self);
    // Note(Lokathor): This style seems weird but it makes all vec/mat type give
    // a similar error message when the input is out of bounds.
    match index {
      0 => &mut arr_mut[0],
      1 => &mut arr_mut[1],
      2 => &mut arr_mut[2],
      otherwise => panic!("Vec3 index out of bounds: {}", otherwise),
    }
  }
}

impl AsRef<[f32; 3]> for Vec3 {
  #[inline(always)]
  fn as_ref(&self) -> &[f32; 3] {
    unsafe { &*(self as *const Vec3 as *const [f32; 3]) }
  }
}
impl AsMut<[f32; 3]> for Vec3 {
  #[inline(always)]
  fn as_mut(&mut self) -> &mut [f32; 3] {
    unsafe { &mut *(self as *mut Vec3 as *mut [f32; 3]) }
  }
}

impl From<[f32; 3]> for Vec3 {
  #[inline]
  fn from([x, y, z]: [f32; 3]) -> Self {
    Self {
      v4: Vec4::from([x, y, z, 0.0]),
    }
  }
}
impl From<Vec3> for [f32; 3] {
  #[inline]
  fn from(Vec3 { v4 }: Vec3) -> Self {
    let [x, y, z, _]: [f32; 4] = cast(v4);
    [x, y, z]
  }
}

#[cfg(feature = "mint")]
impl From<mint::Vector3<f32>> for Vec3 {
  #[inline]
  fn from(mint::Vector3 { x, y, z }: mint::Vector3<f32>) -> Self {
    Self::from([x, y, z])
  }
}
#[cfg(feature = "mint")]
impl From<Vec3> for mint::Vector3<f32> {
  #[inline]
  fn from(v: Vec3) -> Self {
    let [x, y, z]: [f32; 3] = <[f32; 3]>::from(v);
    Self { x, y, z }
  }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Vec3 {
  #[inline]
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: serde::Serializer,
  {
    <[f32; 3]>::from(*self).serialize(serializer)
  }
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Vec3 {
  #[inline]
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    Ok(Self::from(<[f32; 3]>::deserialize(deserializer)?))
  }
}

impl Add for Vec3 {
  type Output = Self;
  #[inline]
  fn add(self, rhs: Self) -> Self {
    Self {
      v4: self.v4 + rhs.v4,
    }
  }
}
impl Add<f32> for Vec3 {
  type Output = Self;
  #[inline]
  fn add(self, rhs: f32) -> Self {
    Self {
      v4: self.v4 + Vec4::splat(rhs),
    }
  }
}
impl Add<Vec3> for f32 {
  type Output = Vec3;
  #[inline]
  fn add(self, rhs: Vec3) -> Vec3 {
    Vec3::splat(self) + rhs
  }
}
impl AddAssign for Vec3 {
  #[inline]
  fn add_assign(&mut self, rhs: Self) {
    *self = *self + rhs
  }
}
impl AddAssign<f32> for Vec3 {
  #[inline]
  fn add_assign(&mut self, rhs: f32) {
    *self = *self + rhs
  }
}

impl Sub for Vec3 {
  type Output = Self;
  #[inline]
  fn sub(self, rhs: Self) -> Self {
    Self {
      v4: self.v4 - rhs.v4,
    }
  }
}
impl Sub<f32> for Vec3 {
  type Output = Self;
  #[inline]
  fn sub(self, rhs: f32) -> Self {
    Self {
      v4: self.v4 - Vec4::splat(rhs),
    }
  }
}
impl Sub<Vec3> for f32 {
  type Output = Vec3;
  #[inline]
  fn sub(self, rhs: Vec3) -> Vec3 {
    Vec3::splat(self) - rhs
  }
}
impl SubAssign for Vec3 {
  #[inline]
  fn sub_assign(&mut self, rhs: Self) {
    *self = *self - rhs
  }
}
impl SubAssign<f32> for Vec3 {
  #[inline]
  fn sub_assign(&mut self, rhs: f32) {
    *self = *self - rhs
  }
}

impl Neg for Vec3 {
  type Output = Self;
  #[inline]
  fn neg(self) -> Self {
    Self { v4: -self.v4 }
  }
}

impl Mul<f32> for Vec3 {
  type Output = Self;
  #[inline]
  fn mul(self, rhs: f32) -> Self {
    Self { v4: self.v4 * rhs }
  }
}
impl Mul<Vec3> for f32 {
  type Output = Vec3;
  #[inline]
  fn mul(self, rhs: Vec3) -> Vec3 {
    rhs * self
  }
}
impl MulAssign<f32> for Vec3 {
  #[inline]
  fn mul_assign(&mut self, rhs: f32) {
    *self = *self * rhs;
  }
}

impl Mul for Vec3 {
  type Output = Self;
  /// Non-mathematical component-wise multiplication (GLSL-style)
  #[inline]
  fn mul(self, rhs: Self) -> Self {
    Self {
      v4: self.v4 * rhs.v4,
    }
  }
}
impl MulAssign for Vec3 {
  #[inline]
  fn mul_assign(&mut self, rhs: Self) {
    *self = *self * rhs;
  }
}

/// ## Accessors
impl Vec3 {
  /// Gets the `x` component of this vector.
  #[inline(always)]
  pub fn x(self) -> f32 {
    let [x, _, _] = <[f32; 3]>::from(self);
    x
  }
  /// Gets the `y` component of this vector.
  #[inline(always)]
  pub fn y(self) -> f32 {
    let [_, y, _] = <[f32; 3]>::from(self);
    y
  }
  /// Gets the `z` component of this vector.
  #[inline(always)]
  pub fn z(self) -> f32 {
    let [_, _, z] = <[f32; 3]>::from(self);
    z
  }
  /// `&mut` to the `x` component of this vector.
  #[inline(always)]
  pub fn x_mut(&mut self) -> &mut f32 {
    let arr_mut: &mut [f32; 4] = cast_mut(self);
    &mut arr_mut[0]
  }
  /// `&mut` to the `y` component of this vector.
  #[inline(always)]
  pub fn y_mut(&mut self) -> &mut f32 {
    let arr_mut: &mut [f32; 4] = cast_mut(self);
    &mut arr_mut[1]
  }
  /// `&mut` to the `z` component of this vector.
  #[inline(always)]
  pub fn z_mut(&mut self) -> &mut f32 {
    let arr_mut: &mut [f32; 4] = cast_mut(self);
    &mut arr_mut[2]
  }
}

/// ## Constructors
impl Vec3 {
  /// Makes a new `Vec3`
  #[inline(always)]
  pub fn new(x: f32, y: f32, z: f32) -> Self {
    Self::from([x, y, z])
  }

  /// Splats the given value across all components.
  #[inline]
  pub fn splat(v: f32) -> Self {
    Self { v4: Vec4::splat(v) }
  }

  /// Extends this 4d vec into a 4d vec with the `w` given.
  #[inline]
  pub fn to_vec4(self, w: f32) -> Vec4 {
    let [x, y, z]: [f32; 3] = <[f32; 3]>::from(self);
    Vec4::from([x, y, z, w])
  }

  /// Reduces this 3d vec to a 2d vec by simply forgetting the `z` value.
  #[inline]
  pub fn to_vec2(self) -> Vec2 {
    let [x, y, _]: [f32; 3] = <[f32; 3]>::from(self);
    Vec2::new(x, y)
  }
}

/// ## Operations
impl Vec3 {
  /// Dot product.
  ///
  /// This is the sum of the component-wise multiplication of the two values.
  /// Order doesn't matter. Positive dot product means the vectors are pointing
  /// in the same general direction, zero dot product means they're
  /// perpendicular, and negative dot product means they have opposite general
  /// direction.
  #[inline]
  pub fn dot(self, rhs: Self) -> f32 {
    if_sse! {{
      let square = self * rhs;
      let z_ = square.zxx();
      let xz_ = square + z_;
      let y_ = square.yxx();
      let xzy_ = xz_ + y_;
      xzy_.v4.sse.extract0_f32()
    } else {
      let t = self * rhs;
      t.x() + t.y() + t.z()
    }}
  }

  /// The length / magnitude of the vector.
  ///
  /// * `sqrt(x^2 + y^2 + z^2)`
  #[inline]
  pub fn length(self) -> f32 {
    lokacore::sqrt_f32(self.length2())
  }

  /// The squared length / magnitude of the vector.
  ///
  /// * `x^2 + y^2 + z^2`
  #[inline]
  pub fn length2(self) -> f32 {
    let sq = self * self;
    sq.x() + sq.y() + sq.z()
  }

  /// Generates a new vector where the length is 1.0
  ///
  /// Or, well, as close as it can get. Floating point, and all that.
  #[inline]
  pub fn normalize(self) -> Self {
    let len = self.length();
    Self::new(self.x() / len, self.y() / len, self.z() / len)
  }

  /// Determines a 3D vector that's at a right angle to the two input vectors.
  ///
  /// * The length of the output is equal to the area of the planar section
  ///   formed by the two inputs.
  /// * The direction of the output is right-handed perpendicular to the two
  ///   inputs.
  #[inline]
  pub fn cross(self, rhs: Self) -> Self {
    //let out_x = self.y() * rhs.z() - self.z() * rhs.y();
    //let out_y = self.z() * rhs.x() - self.x() * rhs.z();
    //let out_z = self.x() * rhs.y() - self.y() * rhs.x();
    (self.yzx() * rhs.zxy()) - (self.zxy() * rhs.yzx())
  }
}