Tanoda
pb_Geometry.cs
Go to the documentation of this file.
1using UnityEngine;
2
3namespace GILES
4{
8 public static class pb_Geometry
9 {
15 public static bool RayIntersectsTriangle(
16 Ray InRay,
17 Vector3 InTriangleA,
18 Vector3 InTriangleB,
19 Vector3 InTriangleC,
20 Culling cull,
21 out float OutDistance,
22 out Vector3 OutPoint)
23 {
24 OutDistance = 0f;
25 OutPoint = Vector3.zero;
26
27 Vector3 e1, e2; //Edge1, Edge2
28 Vector3 P, Q, T;
29 float det, inv_det, u, v;
30 float t;
31
32 //Find vectors for two edges sharing V1
33 e1 = InTriangleB - InTriangleA;
34 e2 = InTriangleC - InTriangleA;
35
36 //Begin calculating determinant - also used to calculate `u` parameter
37 P = Vector3.Cross(InRay.direction, e2);
38
39 //if determinant is near zero, ray lies in plane of triangle
40 det = Vector3.Dot(e1, P);
41
42 // NON-CULLING
43 if( (cull == Culling.Front && det < Mathf.Epsilon) || (det > -Mathf.Epsilon && det < Mathf.Epsilon) )
44 return false;
45
46 inv_det = 1f / det;
47
48 //calculate distance from V1 to ray origin
49 T = InRay.origin - InTriangleA;
50
51 // Calculate u parameter and test bound
52 u = Vector3.Dot(T, P) * inv_det;
53
54 //The intersection lies outside of the triangle
55 if(u < 0f || u > 1f)
56 return false;
57
58 //Prepare to test v parameter
59 Q = Vector3.Cross(T, e1);
60
61 //Calculate V parameter and test bound
62 v = Vector3.Dot(InRay.direction, Q) * inv_det;
63
64 //The intersection lies outside of the triangle
65 if(v < 0f || u + v > 1f)
66 return false;
67
68 t = Vector3.Dot(e2, Q) * inv_det;
69
70 if(t > Mathf.Epsilon)
71 {
72 //ray intersection
73 OutDistance = t;
74
75 OutPoint.x = (u * InTriangleB.x + v * InTriangleC.x + (1-(u+v)) * InTriangleA.x);
76 OutPoint.y = (u * InTriangleB.y + v * InTriangleC.y + (1-(u+v)) * InTriangleA.y);
77 OutPoint.z = (u * InTriangleB.z + v * InTriangleC.z + (1-(u+v)) * InTriangleA.z);
78
79 return true;
80 }
81
82 return false;
83 }
84 }
85}
Culling
Definition: pb_Enum.cs:62