代码部分

 1 // Determine whether a ray intersect with a triangle
2 // Parameters
3 // orig: origin of the ray
4 // dir: direction of the ray
5 // v0, v1, v2: vertices of triangle
6 // t(out): weight of the intersection for the ray
7 // u(out), v(out): barycentric coordinate of intersection
8
9 bool IntersectTriangle(const Vector3& orig, const Vector3& dir,
10     Vector3& v0, Vector3& v1, Vector3& v2,
11     float* t, float* u, float* v)
12 {
13     // E1
14     Vector3 E1 = v1 - v0;
15
16     // E2
17     Vector3 E2 = v2 - v0;
18
19     // P
20     Vector3 P = dir.Cross(E2);
21
22     // determinant
23     float det = E1.Dot(P);
24
25     // keep det > 0, modify T accordingly
26     Vector3 T;
27     if( det >0 )
28     {
29         T = orig - v0;
30     }
31     else
32     {
33         T = v0 - orig;
34         det = -det;
35     }
36
37     // If determinant is near zero, ray lies in plane of triangle
38     if( det < 0.0001f )
39         return false;
40
41     // Calculate u and make sure u <= 1
42     *u = T.Dot(P);
43     if( *u < 0.0f || *u > det )
44         return false;
45
46     // Q
47     Vector3 Q = T.Cross(E1);
48
49     // Calculate v and make sure u + v <= 1
50     *v = dir.Dot(Q);
51     if( *v < 0.0f || *u + *v > det )
52         return false;
53
54     // Calculate t, scale parameters, ray intersects triangle
55     *t = E2.Dot(Q);
56
57     float fInvDet = 1.0f / det;
58     *t *= fInvDet;
59     *u *= fInvDet;
60     *v *= fInvDet;
61
62     return true;
63 }

代码说明

27-35行用来确保det>0，如果det<0则令det = -det，并对T做相应的调整，这样做是为了方便后续计算，否则的话需要分别处理det>0和det<0两种情况。

交点坐标

O + Dt

(1 - u - v)V0 + uV1 + vV2

后记

Happy Coding

== The End ==

posted on 2010-08-09 13:41  翰墨小生  阅读(27962)  评论(30编辑  收藏  举报