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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
use core::{
fmt::{Debug, Formatter},
iter::zip,
};
use retrofire_core::{assert_approx_eq, mat};
use retrofire_core::{
geom::{Edge, Line2, Mesh, Plane3, Pos, Ray, Ray2, Ray3, Tri},
math::{ApproxEq, Mat2, Mat3, Point2, Point3, vec2, vec3},
render::{Model, Obj, World, scene::BBox},
};
#[cfg(feature = "std")]
use retrofire_core::geom::Sphere;
/// Trait for finding intersection points of geometric objects.
pub trait Intersect<T> {
/// The result of an intersection test.
type Result;
/// Finds the point(s) where `self` and another object intersect, if any.
///
/// It is implementation defined whether this method returns all the
/// intersection points or, for instance, only the closest one.
fn intersect(&self, other: &T) -> Self::Result;
}
pub type RayIntersect3<B> = Option<(f32, Point3<B>)>;
pub type RayIntersect2<B> = Option<(f32, Point2<B>)>;
#[derive(Copy, Clone, PartialEq)]
pub enum LineIntersect<B> {
/// Unique intersection point.
Point(Point2<B>),
/// Line is coincident with the intersecting object.
Coincident,
}
//
// Inherent impls
//
impl<B> LineIntersect<B> {
/// Returns the intersection point if `self` is a `LineIntersect::Point`,
/// `None` otherwise.
pub fn point(&self) -> Option<Point2<B>> {
match self {
LineIntersect::Point(p) => Some(*p),
LineIntersect::Coincident => None,
}
}
}
//
// 3D Intersect impls
//
impl<B> Intersect<Plane3<B>> for Ray3<B> {
type Result = RayIntersect3<B>;
/// Returns the unique intersection point of `self` and a plane,
/// or `None` if they do not intersect.
///
/// If an intersection point exists, returns `Some((t, point))`, where
/// `point` is the intersection point and `t` is the ray parameter value
/// such that `self.orig + t * self.dir == point`.
fn intersect(&self, p: &Plane3<B>) -> Self::Result {
let &Self(orig, dir) = self;
// Plane equation:
// ax + by + cz = d
// let n = (a, b, c), P = (x, y, z)
// n·P = d
//
// Ray equation:
// P = O + t·v
//
// Substitute ray eqn to plane eqn
// n·(O + t·v) = d
// n·O + t·n·v = d
// t·n·v = d - n·O // divide by n·v (a scalar)
// t = (d - n·O) / n·v
// = (-n·O + d) / n·v
// = - (n·O - d) / n·v
//
// Or in homogeneous coordinates:
// let n = (a, b, c, -d), O = (o_x, o_y, o_z, 1)
// t = - n·O / n·v
//
// Length of n does not matter, normalization would cancel out anyway.
// n·O is positive if the point is outside the plane, negative if inside.
// n·v is positive if pointing towards the same hemisphere as the plane
// normal, negative otherwise.
//
// Cases where an intersection exists:
// * if n·O = 0, the ray origin lies on the plane.
// * if n·O < 0 and n·v > 0, the ray is inside and points towards the plane.
// * if n·O > 0 and n·v < 0, the ray is outside and points towards the plane.
//
// Cases where it does not exist:
// * if n·O != 0 and n·v = 0, the ray is parallel but not coincident with the plane.
// * if n·O < 0 and n·v < 0, the ray is inside and points away from the plane.
// * if n·O > 0 and n·v > 0, the ray is outside and points away from the plane.
let [a, b, c, d] = p.coeffs();
let n = vec3(a, b, c);
let num = orig.to_vec().dot(&n) + d;
let denom = dir.dot(&n);
if num >= 0.0 && denom < 0.0 || num <= 0.0 && denom > 0.0 {
// Ray points towards the plane or origin lies on the plane
let t = -num / denom;
Some((t, orig + t * dir))
} else if num == 0.0 && denom == 0.0 {
// Ray coincident with the plane, unlikely
Some((0.0, orig))
} else {
None
}
}
}
impl<B, P: Pos<Type = Point3<B>>> Intersect<Tri<P>> for Ray3<B> {
type Result = RayIntersect3<B>;
/// Returns the intersection of `self` and a triangle, or `None` if they
/// do not intersect.
///
/// # Examples
/// ```
/// use retrofire_core::geom::{tri, Ray, Ray3};
/// use retrofire_core::math::{pt3, vec3};
/// use retrofire_geom::Intersect;
///
/// let t = tri(pt3(0.0, 0.0, 0.0), pt3(2.0, 0.0, 0.0), pt3(0.0, 2.0, 0.0));
///
/// let ray: Ray3 = Ray(pt3(1.0, 0.5, 4.0), vec3(0.0, 0.0, -1.0));
/// assert_eq!(ray.intersect(&t), Some((4.0, pt3(1.0, 0.5, 0.0))));
///
/// let ray: Ray3 = Ray(pt3(0.0, 0.0, 4.0), vec3(0.0, -1.0, -1.0));
/// assert_eq!(ray.intersect(&t), None);
/// ```
fn intersect(&self, tri: &Tri<P>) -> Self::Result {
// tri ABC, ab = B-A, ac = C-A
// ray P = O + t * d
//
// triangle plane parametric:
// P = A + u * ab + v * ac
//
// solve linear equation for (t, u, v):
// O + t * d = a + u * ab + v * ac
//
// ( t )
// <=> O - A = ( -d ab ac ) ( u )
// ( v )
//
// inside triangle iff 0 <= t && 0 <= u && 0 <= v && u + v <= 1
struct Plane;
let &Ray(orig, dir) = self;
let &a = tri.0[0].pos();
let [ab, ac] = tri.tangents();
let m = Mat3::<Plane, B, 3>::from_linear(-dir, ab, ac);
let [t, u, v] = m.solve(orig - a)?.0;
// If inside the triangle
(t >= 0.0 && u >= 0.0 && v >= 0.0 && u + v <= 1.0)
.then(|| (t, orig + t * dir))
}
}
impl<B, P: Pos<Type = Point2<B>>> Intersect<Tri<P>> for Ray2<B> {
type Result = RayIntersect2<B>;
/// Returns the intersection of `self` and a triangle, or `None` if they
/// do not intersect.
///
/// # Examples
/// ```
/// use retrofire_core::geom::{tri, Ray, Ray2};
/// use retrofire_core::math::{pt2, vec2};
/// use retrofire_geom::Intersect;
///
/// let t = tri(pt2(0.0, 0.0), pt2(2.0, 0.0), pt2(0.0, 2.0));
///
/// let ray: Ray2 = Ray(pt2(-2.0, 1.0), vec2(1.0, 0.0));
/// assert_eq!(ray.intersect(&t), Some((2.0, pt2(0.0, 1.0))));
///
/// let ray: Ray2 = Ray(pt2(-2.0, 1.0), vec2(1.0, 11.0));
/// assert_eq!(ray.intersect(&t), None);
/// ```
fn intersect(&self, tri: &Tri<P>) -> Self::Result {
let tri = Tri(tri.0.each_ref().map(|p| p.pos().clone()));
tri.edges()
.iter()
.filter_map(|e| self.intersect(&Edge(*e.0, *e.1)))
.min_by(|(t, _), (u, _)| t.total_cmp(u))
}
}
impl<B> Intersect<BBox<B>> for Ray3<B> {
type Result = RayIntersect3<B>; // Only closest for now
/// Returns the nearest intersection point of `self` and a box,
/// or `None` if they do not intersect.
///
/// If an intersection point exists, returns `Some((t, point))`, where
/// `point` is the intersection point and `t` is the ray parameter value
/// such that `self.orig + t * self.dir == point`.
fn intersect(&self, bbox: &BBox<B>) -> Self::Result {
let &BBox(low, upp) = bbox;
let Ray(orig, dir) = *self;
// Ray equation:
// p(t) = O + d·t
// x(t) = Ox + dx·t
// y(t) = Oy + dy·t
// z(t) = Oz + dz·t
//
// Plane equations:
// x = lx, x = ux
// y = ly, x = uy
// z = lz, x = uz
//
// For each slab, ie. pair of parallel planes:
// Substitute eg.
// x_l = Ox + x_d·t0
// x_u = Ox + x_d·t1
//
// t0 = (x_l - x_O) / x_d | x_d=0 iff ray parallel with planes
// t1 = (x_u - x_O) / x_d
//
// Same for y and z slabs
if bbox.is_empty() {
return None;
}
let r_dir = dir.map(f32::recip);
let low = (low - orig) * r_dir;
let upp = (upp - orig) * r_dir;
let near = low.zip_map(upp, f32::min);
let far = low.zip_map(upp, f32::max);
let near_t = near[0].max(near[1]).max(near[2]);
let far_t = far[0].min(far[1]).min(far[2]);
if far_t.is_infinite() {
return None;
}
if near_t > far_t || far_t < 0.0 {
// ---max---min--- (misses the box) or
// ---min---max---0---> (box behind ray)
return None;
}
let t = if near_t >= 0.0 {
// ---0---min---max---> (hits box)
near_t
} else {
// ---min---0---max---> (inside the box, unlikely)
far_t
};
Some((t, orig + t * dir))
}
}
#[cfg(feature = "std")]
impl<B> Intersect<Sphere<B>> for Ray3<B> {
type Result = RayIntersect3<B>; // Only closest for now
/// Returns the intersection point of `self` and a sphere closest to the
/// origin of `self`, or `None` if they do not intersect.
///
/// # Examples
/// ```
/// ```
fn intersect(&self, &Sphere(center, r): &Sphere<B>) -> Self::Result {
let &Ray(orig, dir) = self;
// > r, no intersection
// If |C - C'| = r, one -"-
// < r, two -"-
// _______
// / \
// / \
// | C--r--|
// \ | /
// \___|___/
// _|
// O--------+-C'----> d
//
// Find point P = (x, y, z) given sphere (C, r) and ray (O, d)
//
// Sphere equation:
// (x - c_x)² + (y - c_y)² + (z - c_z)² = r²
// or in vector form
// (P - C) · (P - C) = r²
//
// Ray equation:
// P = O + t·d
//
// Intersection:
//
// Substitute ray equation to sphere equation:
// (o + t·d - c) · (o + t·d - c) = r²
//
// Multiply out
// o (o + td - c) + t·d (o + td - c) - c (o + td - c) = r²
//
// Distribute
// o·o + o·td - o·c + o·td + td·td - td·c - c·o - c·td + c·c = r²
//
// Reorder
// td·td + o·td + o·td - td·c + o·o - o·c - c·o + c·c - r² = 0
//
// Factor out t's
// (d·d) t² + (o·d + o·d - c·d) t + o·o - 2o·c + c·c - r² = 0
//
// Solve quadratic equation:
// (d·d) t² + 2(o - c)·d t + (o - c)² - r² = 0
//
// t = (-b ± √(b² - 4ac)) / 2a
let c_to_o = orig - center;
let a = dir.len_sqr(); // >= 0
let b = 2.0 * c_to_o.dot(&dir);
let c = c_to_o.len_sqr() - r * r;
let discriminant = b * b - 4.0 * a * c;
if discriminant < 0.0 {
// the line of the ray does not hit the sphere
return None;
}
use retrofire_core::math::float::f32;
let sqrt = f32::sqrt(discriminant);
// sqrt >= 0.0, thus t0 <= t1 always
let (t0, t1) = (-b - sqrt, -b + sqrt);
let t = if t0 >= 0.0 {
// ray hits both points
t0
} else if t1 >= 0.0 {
// ray origin is inside sphere
t1
} else {
// sphere is behind ray
return None;
};
let t = t / (2.0 * a);
Some((t, orig + t * dir))
}
}
pub type RayMeshIntersect3<B> = Option<(f32, Point3<B>, usize)>;
impl<A: Clone, B> Intersect<Mesh<A, B>> for Ray3<B> {
type Result = RayMeshIntersect3<B>;
/// Returns the closest intersection of `self` and a mesh, or `None` if
/// they do not intersect.
fn intersect(&self, mesh: &Mesh<A, B>) -> Self::Result {
zip(mesh.faces(), 0..)
.filter_map(|(face, i)| {
let (t, pt) = self.intersect(&face)?;
Some((t, pt, i))
})
.min_by(|(t, ..), (u, ..)| t.total_cmp(u))
}
}
impl<A: Clone> Intersect<Obj<A>> for Ray3<World> {
type Result = RayMeshIntersect3<World>;
/// Returns the closest intersection of `self` and an `Obj`, or `None` if
/// they do not intersect.
fn intersect(&self, obj: &Obj<A>) -> Self::Result {
let inv_tf = obj.tf.inverse();
let ray: Ray3<Model> =
Ray(inv_tf.apply(&self.0), inv_tf.apply(&self.1));
ray.intersect(&obj.bbox)?;
let (_, model_pt, face) = ray.intersect(&obj.geom)?;
let world_pt = obj.tf.apply(&model_pt);
let t = (world_pt - self.0).len() / self.1.len();
assert_approx_eq!(self.0 + t * self.1, world_pt, eps = 1e-4);
Some((t, world_pt, face))
}
}
//
// 2D intersection
//
impl<B> Intersect<Self> for Line2<B> {
type Result = Option<LineIntersect<B>>;
/// Computes the intersection point of `self` and another 2-line.
///
/// If the lines are parallel but not coincident, returns `None`. Otherwise,
/// if the lines are coincident, returns `Some(LineIntersect::Coincident)`.
/// Otherwise, returns `Some(LineIntersect::Point(p))`, where `p` is the
/// unique intersection point.
///
/// # Examples
/// ```
/// use core::assert_matches;
///
/// use retrofire_core::{
/// geom::{Ray, Line2}, math::{pt2, vec2, ApproxEq},
/// };
/// use retrofire_geom::{Intersect, isect::LineIntersect::*};
///
/// let horiz: Line2 = Ray(pt2(0.0, 2.0), vec2(1.0, 0.0)).into();
/// let vert: Line2 = Ray(pt2(3.0, 0.0), vec2(0.0, 1.0)).into();
///
/// let isect = horiz.intersect(&vert);
/// assert_matches!(isect, Some(Point(p)) if p.approx_eq(&pt2(3.0, 2.0)));
///
/// let horiz2 = <Line2>::from(Ray(pt2(0.0, 3.0), vec2(1.0, 0.0)));
/// assert_eq!(horiz.intersect(&horiz2), None);
///
/// assert_eq!(horiz.intersect(&horiz), Some(Coincident));
///
///
/// ```
fn intersect(&self, other: &Self) -> Self::Result {
let [a, b, c] = self.coeffs();
let [d, e, f] = other.coeffs();
// Solve the system of equations for x and y:
// ax + by + c = 0 // self
// dx + ey + f = 0 // other
let abde: Mat2<B> = mat![a, b; d, e];
match abde.solve(vec2(-c, -f)) {
Some(res) => Some(LineIntersect::Point(res.to_pt())),
None if [a, b, c].approx_eq(&[d, e, f]) => {
Some(LineIntersect::Coincident)
}
None => None,
}
}
}
impl<B> Intersect<Line2<B>> for Ray2<B> {
type Result = RayIntersect2<B>;
// Returns the intersection point of self and a line.
fn intersect(&self, line: &Line2<B>) -> Self::Result {
// TODO if degenerate ray, could return if ray origin on edge
// First find intersection of lines
let ray_line = Line2::from(*self);
let isect = ray_line.intersect(line)?;
let Self(orig, dir) = self;
match isect {
LineIntersect::Point(pt) => {
// Check if the point lies in the correct half-line
let t = (pt - *orig).dot(dir);
(t >= 0.0).then_some((t / dir.len_sqr(), pt))
}
LineIntersect::Coincident => {
// Ray lies on the line, the closest common point
// is simply the origin point
Some((0.0, *orig))
}
}
}
}
impl<B> Intersect<Edge<Point2<B>>> for Ray2<B> {
type Result = RayIntersect2<B>;
/// Returns the intersection of `self` and an edge, or `None` if there is
/// no intersection point.
///
/// # Examples
/// ```
/// use retrofire_core::{
/// assert_approx_eq, geom::{Edge, Ray}, math::{pt2, vec2, Point2},
/// };
/// use retrofire_geom::isect::Intersect;
///
/// // ^
/// // 3 O
/// // | \
/// // | v
/// // E==1=======X==E
/// // |
/// // <----+-------------->
/// let ray: Ray<Point2> = Ray(pt2(2.0, 3.0), vec2(1.0, -2.0));
/// let edge = Edge(pt2(-1.0, 1.0), pt2(4.0, 1.0));
///
/// let (t, point) = ray.intersect(&edge).unwrap();
/// assert_eq!(t, 1.0);
/// assert_approx_eq!(point, pt2(3.0, 1.0));
///
/// // O
/// // \
/// // E=====E v
/// //
/// let edge = Edge(pt2(-1.0, 1.0), pt2(2.0, 1.0));
/// assert_eq!(ray.intersect(&edge), None);
/// ```
// // TODO check that these are handled by actual unit tests
// // E=====E <---O
// let ray: Ray<Point2> = Ray(pt2(4.0, 1.0), vec2(-1.0, 0.0));
// assert_eq!(ray.intersect(&edge), Some((2.0, pt2(2.0, 1.0))));
//
// // E==O--E-->
// let ray: Ray<Point2> = Ray(pt2(1.0, 1.0), vec2(1.0, 0.0));
// assert_eq!(ray.intersect(&edge), Some((0.0, pt2(1.0, 1.0))));
//
// // E=====E O--->
// let ray: Ray<Point2> = Ray(pt2(4.0, 1.0), vec2(1.0, 0.0));
// assert_eq!(ray.intersect(&edge), None);
fn intersect(&self, edge: &Edge<Point2<B>>) -> Self::Result {
// Compute ray-line intersection
let (t, pt) = self.intersect(&Line2::from(*edge))?;
// Ray intersects the line of edge, but still have to check
// whether the point is between edge endpoints
let e01 = edge.1 - edge.0;
let u = (pt - edge.0).scalar_project(&e01);
if u.approx_in(0.0..1.0) {
return Some((t, pt));
}
// If ray is coincident with the edge, ray-line gives ray.0 as the
// intersection point. If ray.0 is outside the edge, there are two cases:
// e-----e r--->
// where there is no intersection, and
// e-----e <---r
// where the intersection point is the closest edge endpoint.
if !self.0.approx_eq(&pt) {
return None;
}
let t0 = (edge.0 - pt).dot(&self.1);
if t0.approx_le(&0.0) {
return None;
}
let t1 = (edge.1 - pt).dot(&self.1);
let (t, pt) = if t0 <= t1 { (t0, edge.0) } else { (t1, edge.1) };
Some((t / self.1.len_sqr(), pt))
}
}
impl<B> Intersect<Self> for Edge<Point2<B>> {
type Result = Option<Point2<B>>;
/// Returns the intersection point of `self` and another edge, or `None`
/// if the edges do not intersect.
///
/// # Examples
/// ```
/// use retrofire_core::{
/// assert_approx_eq,
/// geom::Edge,
/// math::{pt2, Point2}
/// };
/// use retrofire_geom::isect::Intersect;
///
/// //
/// // O1
/// // \
/// // \
/// // \
/// // E1---X----E2
/// // \
/// // O2
/// let edge: Edge<Point2> = Edge(pt2(0.0, 1.0), pt2(4.0, 1.0));
/// let other = Edge(pt2(0.0, 3.0), pt2(3.0, 0.0));
///
/// assert_approx_eq!(edge.intersect(&other), Some(pt2(2.0, 1.0)));
///
/// ```
fn intersect(&self, edge: &Self) -> Self::Result {
let ray = Ray(self.0, self.1 - self.0);
match ray.intersect(edge) {
Some((t, pt)) if t <= 1.0 => Some(pt),
_ => None,
}
}
}
//
// Foreign trait impls
//
impl<B: Debug + Default> Debug for LineIntersect<B> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Self::Point(p) => Debug::fmt(p, f),
Self::Coincident => f.write_str("Coincident"),
}
}
}
#[cfg(test)]
mod tests {
use retrofire_core::math::{Linear, Vec3, pt3};
use super::*;
mod ray_plane {
use super::*;
const PLANE: Plane3<()> = Plane3::new(0.0, 1.0, 0.0, 2.0);
#[test]
fn ray_towards_plane_has_intersection() {
// Outside
let r = Ray(pt3(0.0, 3.0, 0.0), vec3(1.0, -1.0, 1.0));
assert_eq!(r.intersect(&PLANE), Some((1.0, pt3(1.0, 2.0, 1.0))));
// Inside
let r = Ray(pt3(0.0, 1.0, 0.0), vec3(1.0, 1.0, 1.0));
assert_eq!(r.intersect(&PLANE), Some((1.0, pt3(1.0, 2.0, 1.0))));
}
#[test]
fn ray_origin_on_plane_has_intersection() {
let r = Ray(pt3(0.0, 2.0, 0.0), vec3(1.0, -1.0, 1.0));
assert_eq!(r.intersect(&PLANE), Some((0.0, pt3(0.0, 2.0, 0.0))));
}
#[test]
fn ray_coincident_with_plane_has_intersection() {
let r = Ray(pt3(0.0, 2.0, 0.0), vec3(1.0, 0.0, 1.0));
assert_eq!(r.intersect(&PLANE), Some((0.0, pt3(0.0, 2.0, 0.0))));
}
#[test]
fn ray_parallel_with_plane_no_intersection() {
let r = Ray(pt3(0.0, 3.0, 0.0), vec3(1.0, 0.0, 1.0));
assert_eq!(r.intersect(&PLANE), None);
}
#[test]
fn ray_points_away_from_plane_no_intersection() {
// Outside
let r = Ray(pt3(0.0, 3.0, 0.0), vec3(1.0, 1.0, 1.0));
assert_eq!(r.intersect(&PLANE), None);
// Inside
let r = Ray(pt3(0.0, 1.0, 0.0), vec3(1.0, -1.0, 1.0));
assert_eq!(r.intersect(&PLANE), None);
}
#[test]
fn degenerate_ray_only_intersects_if_coincident() {
let r = Ray(pt3(0.0, 3.0, 0.0), Vec3::zero());
assert_eq!(r.intersect(&PLANE), None);
let r = Ray(pt3(0.0, 1.0, 0.0), Vec3::zero());
assert_eq!(r.intersect(&PLANE), None);
let r = Ray(pt3(0.0, 2.0, 0.0), Vec3::zero());
assert_eq!(r.intersect(&PLANE), Some((0.0, pt3(0.0, 2.0, 0.0))));
}
}
mod ray_bbox {
use super::*;
const BBOX: BBox<()> = BBox(pt3(-1.0, -1.0, -1.0), pt3(1.0, 1.0, 1.0));
#[test]
fn parallel_simple() {
// +----+
// x--> | |
// +----+
let ray = Ray(pt3(0.0, 0.0, -2.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&BBOX), Some((1.0, pt3(0.0, 0.0, -1.0))));
}
#[test]
fn diagonal_simple() {
//
// +----+
// ^| |
// / +----+
// x
let ray = Ray(pt3(-1.5, 0.0, -2.0), vec3(1.0, 0.0, 1.0));
assert_eq!(ray.intersect(&BBOX), Some((1.0, pt3(-0.5, 0.0, -1.0))));
}
#[test]
#[ignore]
fn parallel_intersect_at_vertex() {
// x--> ,_____.
// / /|
// /_____/ |
// | | /
// |_____|/
let ray = Ray(pt3(1.0, 1.0, -2.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&BBOX), Some((1.0, pt3(1.0, 1.0, -1.0))));
}
#[test]
#[ignore]
fn parallel_intersect_at_edge() {
// ,_____.
// x--> / /|
// /_____/ |
// | | /
// |_____|/
//
let ray = Ray(pt3(0.0, 1.0, -2.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&BBOX), Some((1.0, pt3(0.0, 1.0, -1.0))));
}
#[test]
fn ray_starts_inside() {
// +--^----+
// | | |
// | x |
// +-------+
let ray = Ray(pt3(0.0, 0.0, -0.5), vec3(0.0, 1.0, 0.0));
assert_eq!(ray.intersect(&BBOX), Some((1.0, pt3(0.0, 1.0, -0.5))));
}
#[test]
fn ray_starts_on_side_plane() {
// Points away
// +-----+
// <--x |
// +-----+
let ray = Ray(pt3(0.0, 0.0, -1.0), vec3(0.0, 0.0, -1.0));
assert_eq!(ray.intersect(&BBOX), Some((0.0, pt3(0.0, 0.0, -1.0))));
// Points inside
// +-----+
// x--> |
// +-----+
let ray = Ray(pt3(0.0, 0.0, -1.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&BBOX), Some((0.0, pt3(0.0, 0.0, -1.0))));
}
#[test]
fn no_intersection() {
// Diagonal ray
// ^
// / +----+
// x | |
// +----+
let ray = Ray(pt3(0.0, 0.0, -2.5), vec3(0.0, 1.0, 1.0));
assert_eq!(ray.intersect(&BBOX), None);
// Parallel but offset ray
// x--->
// +----+
// | |
// +----+
let ray = Ray(pt3(0.0, 1.5, -2.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&BBOX), None);
}
#[test]
fn opposite_direction() {
// +----+
// | | x--->
// +----+
let ray = Ray(pt3(0.0, 0.0, 2.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&BBOX), None);
}
#[test]
fn zero_length_ray() {
let ray = Ray(pt3(0.0, 0.0, -2.0), vec3(0.0, 0.0, 0.0));
assert_eq!(ray.intersect(&BBOX), None);
}
#[test]
fn empty_box() {
let empty = BBox::<()>(pt3(-1.0, -1.0, 1.0), pt3(1.0, 1.0, -1.0));
let ray = Ray(pt3(0.0, 0.0, -2.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&empty), None);
}
}
// TODO until sqrt has a fallback
#[cfg(feature = "std")]
mod ray_sphere {
use super::*;
const SPHERE: Sphere = Sphere(pt3(0.0, 0.0, 1.0), 2.0);
#[test]
fn ray_passes_through_sphere() {
let ray: Ray3 = Ray(pt3(0.0, 0.0, -3.0), vec3(0.0, 0.0, 2.0));
assert_eq!(
ray.intersect(&SPHERE),
Some((1.0, pt3(0.0, 0.0, -1.0)))
);
}
#[test]
fn ray_tangent_to_sphere() {
let ray: Ray3 = Ray(pt3(0.0, 2.0, -3.0), vec3(0.0, 0.0, 2.0));
assert_eq!(ray.intersect(&SPHERE), Some((2.0, pt3(0.0, 2.0, 1.0))));
}
#[test]
fn ray_origin_inside_sphere() {
let ray: Ray3 = Ray(pt3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 2.0));
assert_eq!(ray.intersect(&SPHERE), Some((1.5, pt3(0.0, 0.0, 3.0))));
let ray: Ray3 = Ray(pt3(0.0, 0.0, 2.0), vec3(0.0, 0.0, 2.0));
assert_eq!(ray.intersect(&SPHERE), Some((0.5, pt3(0.0, 0.0, 3.0))));
}
#[test]
fn sphere_behind_ray() {
let ray: Ray3 = Ray(pt3(0.0, 0.0, -3.0), vec3(0.0, 0.0, -1.0));
assert_eq!(ray.intersect(&SPHERE), None);
}
#[test]
fn ray_misses_sphere() {
let ray: Ray3 = Ray(pt3(0.0, 0.0, -3.0), vec3(0.0, 1.0, 1.0));
assert_eq!(ray.intersect(&SPHERE), None);
}
}
mod ray_mesh {
use retrofire_core::geom::Normal3;
use super::*;
use crate::solids::{Build, Cube};
#[test]
fn ray_hits_cube_from_outside() {
let cube: Mesh<Normal3> = Cube { side_len: 1.0 }.build();
let along_z = Ray(pt3(0.2, -0.1, -3.0), vec3(0.0, 0.0, 1.0));
assert_eq!(
along_z.intersect(&cube),
Some((2.5, pt3(0.2, -0.1, -0.5), 8))
);
let along_y = Ray(pt3(0.0, 10.0, 0.0), vec3(0.0, -2.0, 0.0));
assert_eq!(
along_y.intersect(&cube),
Some((4.75, pt3(0.0, 0.5, 0.0), 6))
);
let diagonal = Ray(pt3(4.0, -4.0, 4.0), vec3(-1.0, 1.0, -1.0));
assert_eq!(
diagonal.intersect(&cube),
Some((3.5, pt3(0.5, -0.5, 0.5), 2))
);
}
#[test]
fn ray_hits_cube_from_inside() {
let cube: Mesh<Normal3> = Cube { side_len: 1.0 }.build();
let from_origin = Ray(pt3(0.0, 0.0, 0.0), vec3(-0.5, 0.25, -1.0));
assert_eq!(
from_origin.intersect(&cube),
Some((0.5, pt3(-0.25, 0.125, -0.5), 9))
);
let along_z = Ray(pt3(0.2, 0.3, 0.25), vec3(0.0, 0.0, 2.0));
assert_eq!(
along_z.intersect(&cube),
Some((0.125, pt3(0.2, 0.3, 0.5), 10))
);
}
#[test]
fn ray_misses_cube() {
let cube: Mesh<Normal3> = Cube { side_len: 1.0 }.build();
let passes_cube = Ray(pt3(1.0, 0.0, -3.0), vec3(0.0, 0.0, 1.0));
assert_eq!(passes_cube.intersect(&cube), None);
let opposite_dir = Ray(pt3(0.0, 0.0, 1.0), vec3(0.0, 0.0, 1.0));
assert_eq!(opposite_dir.intersect(&cube), None);
}
#[test]
#[ignore = "TODO"]
#[cfg(feature = "std")]
fn torus() {
let torus: Mesh<Normal3> = crate::solids::Torus {
major_radius: 1.0,
minor_radius: 0.3,
major_sectors: 16,
minor_sectors: 8,
}
.build();
let ray = Ray(pt3(0.0, 0.0, -3.0), vec3(0.0, 0.0, 1.0));
let ip = ray.intersect(&torus);
assert_eq!(ip, None);
}
}
mod ray_obj {
use retrofire_core::{geom::Normal3, math::translate};
use super::*;
use crate::solids::{Build, Cube};
#[test]
#[ignore = "TODO"]
fn obj() {
let cube = Obj::<Normal3>::with_transform(
Cube { side_len: 1.0 }.build(),
translate((1.0, 2.0, 3.0)).to(),
);
let ray = Ray(pt3(1.0, 2.0, 1.0), vec3(0.0, 0.0, 2.0));
assert_eq!(ray.intersect(&cube), None /* TODO */);
let ray = Ray(pt3(0.0, 0.0, -3.0), vec3(0.0, 0.0, 1.0));
assert_eq!(ray.intersect(&cube), None);
}
}
// TODO 2D tests from stash
}