cvmath 0.0.8

Computer Graphics Vector Math Library
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
use super::*;

//----------------------------------------------------------------

/// Bounds3 shape.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(C)]
pub struct Bounds3<T> {
	pub mins: Vec3<T>,
	pub maxs: Vec3<T>,
}

/// Bounds3 constructor.
#[allow(non_snake_case)]
#[inline]
pub const fn Bounds3<T>(mins: Vec3<T>, maxs: Vec3<T>) -> Bounds3<T> {
	Bounds3 { mins, maxs }
}

/// Bounds3 constructor.
///
/// ```
/// use cvmath::{Bounds3, Point3};
///
/// let explicit = cvmath::Bounds3!(1, 2, 3, 4, 5, 6);
/// let splat = cvmath::Bounds3!(7, 8);
/// let zero: Bounds3<i32> = cvmath::Bounds3!();
///
/// assert_eq!(explicit, Bounds3(Point3(1, 2, 3), Point3(4, 5, 6)));
/// assert_eq!(splat, Bounds3(Point3(7, 7, 7), Point3(8, 8, 8)));
/// assert_eq!(zero, Bounds3::ZERO);
/// ```
#[macro_export]
macro_rules! Bounds3 {
	($x_min:expr, $y_min:expr, $z_min:expr, $x_max:expr, $y_max:expr, $z_max:expr $(,)?) => {
		$crate::Bounds3 {
			mins: $crate::Vec3 { x: $x_min, y: $y_min, z: $z_min },
			maxs: $crate::Vec3 { x: $x_max, y: $y_max, z: $z_max },
		}
	};
	($mins:expr, $maxs:expr $(,)?) => {
		$crate::Bounds3 {
			mins: $crate::Vec3 { x: $mins, y: $mins, z: $mins },
			maxs: $crate::Vec3 { x: $maxs, y: $maxs, z: $maxs },
		}
	};
	() => {
		$crate::Bounds3::ZERO
	};
}

specialized_type!(Bounds3, Bounds3f, f32, mins: Point3f, maxs: Point3f);
specialized_type!(Bounds3, Bounds3d, f64, mins: Point3d, maxs: Point3d);
specialized_type!(Bounds3, Bounds3i, i32, mins: Point3i, maxs: Point3i);

#[cfg(feature = "dataview")]
unsafe impl<T: dataview::Pod> dataview::Pod for Bounds3<T> {}

impl<T: Zero> Bounds3<T> {
	/// Zero bounds.
	pub const ZERO: Bounds3<T> = Bounds3 { mins: Point3::ZERO, maxs: Point3::ZERO };
}
impl<T: Zero + One> Bounds3<T> {
	/// Unit bounds.
	pub const UNIT: Bounds3<T> = Bounds3 { mins: Point3::ZERO, maxs: Point3::ONE };
}

impl<T> Bounds3<T> {
	/// Constructs a new bounds.
	#[inline]
	pub const fn new(mins: Point3<T>, maxs: Point3<T>) -> Bounds3<T> {
		Bounds3 { mins, maxs }
	}
	/// Bounds from the origin to the vector.
	#[inline]
	pub fn vec(maxs: Vec3<T>) -> Bounds3<T> where T: Default {
		let mins = Point3::default();
		Bounds3 { mins, maxs }
	}
	/// Creates a bounds at the given point with size.
	#[inline]
	pub fn point(point: Point3<T>, size: Vec3<T>) -> Bounds3<T> where T: Copy + ops::Add<Output = T> + ops::Sub<Output = T> {
		Bounds3 { mins: point - size, maxs: point + size }
	}
	/// Normalizes the min and max values ensuring that `self.mins <= self.maxs`.
	///
	/// Because the constructors don't implicitly do this for you,
	/// it is typical to have this call follow the construction of the bounds.
	#[inline]
	pub fn norm(self) -> Bounds3<T> where T: Extrema {
		let (mins, maxs) = self.mins.min_max(self.maxs);
		Bounds3 { mins, maxs }
	}
	/// Returns the size of the bounds.
	///
	/// ```
	/// use cvmath::{Bounds3, Point3, Vec3};
	///
	/// let bounds = Bounds3(Point3(1, 1, 3), Point3(3, 2, 3));
	/// assert_eq!(Vec3(2, 1, 0), bounds.size());
	/// ```
	#[inline]
	pub fn size(self) -> Vec3<T> where T: ops::Sub<Output = T> {
		self.maxs - self.mins
	}
}

impl<T> Bounds3<T> {
	/// Returns whether the point `rhs` is contained within `self`.
	#[inline]
	pub fn contains(&self, rhs: Point3<T>) -> bool where T: PartialOrd {
		rhs.spatial_ge(&self.mins) && rhs.spatial_le(&self.maxs)
	}
	/// Returns whether the bounds `rhs` is fully contained within `self`.
	#[inline]
	pub fn encloses(&self, rhs: Bounds3<T>) -> bool where T: PartialOrd {
		rhs.mins.spatial_ge(&self.mins) && rhs.maxs.spatial_le(&self.maxs)
	}
	/// Returns whether `rhs` is overlapped with `self`.
	#[inline]
	pub fn overlaps(&self, rhs: Bounds3<T>) -> bool where T: PartialOrd {
		rhs.maxs.spatial_ge(&self.mins) && rhs.mins.spatial_le(&self.maxs)
	}
	/// Includes the point in the bounds.
	pub fn include(self, pt: Point3<T>) -> Bounds3<T> where T: Copy + Extrema {
		let mins = self.mins.min(pt);
		let maxs = self.maxs.max(pt);
		Bounds3 { mins, maxs }
	}
	/// Returns the new bounds containing both `rhs` and `self`.
	#[inline]
	pub fn union(self, rhs: Bounds3<T>) -> Bounds3<T> where T: Extrema {
		let mins = self.mins.min(rhs.mins);
		let maxs = self.maxs.max(rhs.maxs);
		Bounds3 { mins, maxs }
	}
	/// Returns the overlapping area (if any) between `rhs` and `self`.
	#[inline]
	pub fn intersect(self, rhs: Bounds3<T>) -> Option<Bounds3<T>> where T: PartialOrd + Extrema {
		let mins = self.mins.max(rhs.mins);
		let maxs = self.maxs.min(rhs.maxs);
		if mins.spatial_le(&maxs) {
			Some(Bounds3 { mins, maxs })
		}
		else {
			None
		}
	}
}

impl<T: Float> Bounds3<T> {
	/// Empty bounds represented by inverted infinities.
	///
	/// Useful as the initial accumulator for [include](Bounds3::include) or [union](Bounds3::union).
	pub const EMPTY: Bounds3<T> = Bounds3 {
		mins: Point3 { x: T::INFINITY, y: T::INFINITY, z: T::INFINITY },
		maxs: Point3 { x: T::NEG_INFINITY, y: T::NEG_INFINITY, z: T::NEG_INFINITY },
	};

	/// Constructs bounds that enclose all bounds in the given iterator.
	///
	/// Returns [`EMPTY`](Bounds3::EMPTY) if the iterator is empty.
	#[inline]
	pub fn collection<I: IntoIterator<Item = Bounds3<T>>>(bounds: I) -> Bounds3<T> {
		<Bounds3<T> as FromIterator<Bounds3<T>>>::from_iter(bounds)
	}
}

impl<T: Float> FromIterator<Bounds3<T>> for Bounds3<T> {
	#[inline]
	fn from_iter<I: IntoIterator<Item = Bounds3<T>>>(iter: I) -> Bounds3<T> {
		iter.into_iter().fold(Self::EMPTY, Bounds3::union)
	}
}
impl<T: Float> FromIterator<Point3<T>> for Bounds3<T> {
	#[inline]
	fn from_iter<I: IntoIterator<Item = Point3<T>>>(iter: I) -> Bounds3<T> {
		iter.into_iter().fold(Bounds3::EMPTY, Bounds3::include)
	}
}

impl<T> Bounds3<T> {
	/// Returns whether `rhs` is strictly contained within `self`.
	#[inline]
	pub fn strictly_contains(&self, rhs: Point3<T>) -> bool where T: PartialOrd {
		rhs.spatial_gt(&self.mins) && rhs.spatial_lt(&self.maxs)
	}
	/// Returns whether `rhs` is strictly contained within `self`.
	#[inline]
	pub fn strictly_encloses(&self, rhs: Bounds3<T>) -> bool where T: PartialOrd {
		rhs.mins.spatial_gt(&self.mins) && rhs.maxs.spatial_lt(&self.maxs)
	}
	/// Returns whether `rhs` is strictly overlapped with `self`.
	#[inline]
	pub fn strictly_overlaps(&self, rhs: Bounds3<T>) -> bool where T: PartialOrd {
		rhs.maxs.spatial_gt(&self.mins) && rhs.mins.spatial_lt(&self.maxs)
	}
	/// Returns the overlapping area (not empty) between `rhs` and `self`.
	#[inline]
	pub fn strictly_intersect(self, rhs: Bounds3<T>) -> Option<Bounds3<T>> where T: PartialOrd + Extrema {
		let mins = self.mins.max(rhs.mins);
		let maxs = self.maxs.min(rhs.maxs);
		if mins.spatial_lt(&maxs) {
			Some(Bounds3 { mins, maxs })
		}
		else {
			None
		}
	}
}

impl<T: Copy + ops::Add<T, Output = T>> ops::Add<Vec3<T>> for Bounds3<T> {
	type Output = Bounds3<T>;
	#[inline]
	fn add(self, rhs: Vec3<T>) -> Bounds3<T> {
		Bounds3 {
			mins: self.mins + rhs,
			maxs: self.maxs + rhs,
		}
	}
}
impl<T: Copy + ops::Sub<T, Output = T>> ops::Sub<Vec3<T>> for Bounds3<T> {
	type Output = Bounds3<T>;
	#[inline]
	fn sub(self, rhs: Vec3<T>) -> Bounds3<T> {
		Bounds3 {
			mins: self.mins - rhs,
			maxs: self.maxs - rhs,
		}
	}
}
impl<T: Copy + ops::AddAssign<T>> ops::AddAssign<Vec3<T>> for Bounds3<T> {
	#[inline]
	fn add_assign(&mut self, rhs: Vec3<T>) {
		self.mins += rhs;
		self.maxs += rhs;
	}
}
impl<T: Copy + ops::SubAssign<T>> ops::SubAssign<Vec3<T>> for Bounds3<T> {
	#[inline]
	fn sub_assign(&mut self, rhs: Vec3<T>) {
		self.mins -= rhs;
		self.maxs -= rhs;
	}
}

impl<T: Scalar> Lerp for Bounds3<T> {
	type T = T;

	#[inline]
	fn lerp(self, rhs: Bounds3<T>, t: T) -> Bounds3<T> {
		Bounds3 {
			mins: lerp(self.mins, rhs.mins, t),
			maxs: lerp(self.maxs, rhs.maxs, t),
		}
	}
}

impl<T> AsRef<[Point3<T>; 2]> for Bounds3<T> {
	#[inline]
	fn as_ref(&self) -> &[Point3<T>; 2] {
		unsafe { core::mem::transmute(self) }
	}
}
impl<T> AsMut<[Point3<T>; 2]> for Bounds3<T> {
	#[inline]
	fn as_mut(&mut self) -> &mut [Point3<T>; 2] {
		unsafe { core::mem::transmute(self) }
	}
}
impl<T> From<[Point3<T>; 2]> for Bounds3<T> {
	#[inline]
	fn from([mins, maxs]: [Point3<T>; 2]) -> Bounds3<T> {
		Bounds3 { mins, maxs }
	}
}
impl<T> From<Bounds3<T>> for [Point3<T>; 2] {
	#[inline]
	fn from(bounds: Bounds3<T>) -> [Point3<T>; 2] {
		[bounds.mins, bounds.maxs]
	}
}

//----------------------------------------------------------------

impl<T> Bounds3<T> {
	/// Casts the bounds to a different unit type.
	#[inline]
	pub fn cast<U>(self) -> Bounds3<U> where T: CastTo<U> {
		Bounds3 {
			mins: self.mins.cast(),
			maxs: self.maxs.cast(),
		}
	}
}

impl<T: Scalar> Bounds3<T> {
	/// Width of the Bounds3.
	#[inline]
	pub fn width(&self) -> T {
		self.maxs.x - self.mins.x
	}
	/// Height of the Bounds3.
	#[inline]
	pub fn height(&self) -> T {
		self.maxs.y - self.mins.y
	}
	/// Depth of the Bounds3.
	#[inline]
	pub fn depth(&self) -> T {
		self.maxs.z - self.mins.z
	}
	/// Surface area of the Bounds3.
	#[inline]
	pub fn area(&self) -> T {
		let size = self.size();
		(T::ONE + T::ONE) * (size.x * size.y + size.y * size.z + size.z * size.x)
	}
	/// Volume of the Bounds3.
	#[inline]
	pub fn volume(&self) -> T {
		(self.maxs.x - self.mins.x) * (self.maxs.y - self.mins.y) * (self.maxs.z - self.mins.z)
	}
	/// Center of the Bounds3.
	#[inline]
	pub fn center(&self) -> Point3<T> {
		(self.mins + self.maxs) / (T::ONE + T::ONE)
	}
	/// Transform of the unit cube.
	#[inline]
	pub fn transform(self) -> Transform3<T> {
		Transform3::compose(
			Vec3(self.width(), T::ZERO, T::ZERO),
			Vec3(T::ZERO, self.height(), T::ZERO),
			Vec3(T::ZERO, T::ZERO, self.depth()),
			self.mins,
		)
	}
}

//----------------------------------------------------------------

#[cfg(feature = "urandom")]
impl<T: Scalar> urandom::Distribution<Bounds3<T>> for urandom::distr::StandardUniform where
	urandom::distr::StandardUniform: urandom::Distribution<Point3<T>>,
{
	#[inline]
	fn sample<R: urandom::Rng + ?Sized>(&self, rand: &mut urandom::Random<R>) -> Bounds3<T> {
		let distr = urandom::distr::StandardUniform;
		let mins = distr.sample(rand);
		let maxs = distr.sample(rand);
		Bounds3 { mins, maxs }.norm()
	}
}

#[cfg(feature = "urandom")]
impl<T: urandom::distr::SampleUniform> urandom::distr::SampleUniform for Bounds3<T> {
	type Sampler = Bounds3<urandom::distr::Uniform<T>>;
}
#[cfg(feature = "urandom")]
impl<T: urandom::distr::SampleUniform> urandom::distr::UniformSampler<Bounds3<T>> for Bounds3<urandom::distr::Uniform<T>> where Point3<T>: urandom::distr::SampleUniform {
	#[inline]
	fn try_new(low: Bounds3<T>, high: Bounds3<T>) -> Result<Self, urandom::distr::UniformError> {
		let mins = Vec3::try_new(low.mins, high.mins)?;
		let maxs = Vec3::try_new(low.maxs, high.maxs)?;
		Ok(Bounds3 { mins, maxs })
	}
	#[inline]
	fn try_new_inclusive(low: Bounds3<T>, high: Bounds3<T>) -> Result<Self, urandom::distr::UniformError> where Self: Sized {
		let mins = Vec3::try_new_inclusive(low.mins, high.mins)?;
		let maxs = Vec3::try_new_inclusive(low.maxs, high.maxs)?;
		Ok(Bounds3 { mins, maxs })
	}
}
#[cfg(feature = "urandom")]
impl<T: urandom::distr::SampleUniform> urandom::Distribution<Bounds3<T>> for Bounds3<urandom::distr::Uniform<T>> {
	#[inline]
	fn sample<R: urandom::Rng + ?Sized>(&self, rand: &mut urandom::Random<R>) -> Bounds3<T> {
		let mins = self.mins.sample(rand);
		let maxs = self.maxs.sample(rand);
		Bounds3 { mins, maxs }
	}
}

//----------------------------------------------------------------

impl<T: Float> Trace3<T> for Bounds3<T> {
	#[inline]
	fn inside(&self, pt: Point3<T>) -> bool {
		self.contains(pt)
	}

	fn trace(&self, ray: &Ray3<T>) -> Option<Hit3<T>> {
		let inv_dir = ray.direction.map(|d| T::ONE / d);

		let tmin = (self.mins - ray.origin) * inv_dir;
		let tmax = (self.maxs - ray.origin) * inv_dir;
		let (tmin, tmax) = tmin.min_max(tmax);

		let t0 = tmin.vmax();
		let t1 = tmax.vmin();

		let distance = if !(t0 <= t1) { return None }
		else if t0 > ray.distance.min && t0 <= ray.distance.max { t0 }
		else if t1 > ray.distance.min && t1 <= ray.distance.max { t1 }
		else { return None };

		// Outward shape normal: use direction sign per axis
		let sign = ray.direction.map(T::signum);

		// Calculate the normal based on which axis was hit
		let normal = (
			Vec3::dup(distance).eq(tmin).select(-sign, Vec3::ZERO) +
			Vec3::dup(distance).eq(tmax).select( sign, Vec3::ZERO)
		).norm();

		let point = ray.at(distance);

		let (normal, side) = if normal.dot(ray.direction) < T::ZERO {
			(normal, HitSide::Entry)
		}
		else {
			(-normal, HitSide::Exit)
		};

		Some(Hit3 { point, distance, normal, index: 0, side })
	}
}