check if line intersects triangle

Solutions on MaxInterview for check if line intersects triangle by the best coders in the world

showing results for - "check if line intersects triangle"
Nicole
30 Jun 2017
1bool isTriangleIntersecting(vec3d p1,vec3d p2,vec3d p3,vec3d qq1,vec3d qq2) {
2			
3  //p1 , 2 , 3 are points of triangle
4  // q1 and q2 defines a line
5  
6			vec3d q1 = subtractvec(qq1, qq2);
7			q1 = normalize(q1);
8			q1 = multiplicatevec(q1, vec3d{1000,1000,1000});
9			q1 = addvec(q1, qq1);
10
11
12			vec3d q2 = subtractvec(qq2, qq1);
13			q2 = normalize(q2);
14			q2 = multiplicatevec(q2, vec3d{ 1000,1000,1000 });
15			q2 = addvec(q2, qq2);
16
17
18
19			if (GetNaturality(volumeOfTetrahedron(q1, p1, p2, p3)) != GetNaturality(volumeOfTetrahedron(q2, p1, p2, p3))) {
20				if (GetNaturality(volumeOfTetrahedron(q1, q2, p1, p2)) == GetNaturality(volumeOfTetrahedron(q1, q2, p2, p3)) && GetNaturality(volumeOfTetrahedron(q1, q2, p2, p3)) == GetNaturality(volumeOfTetrahedron(q1, q2, p3, p1))) {
21					return true;
22				}
23			}
24			return false;
25		}
26
27vec3d normalize(vec3d v) {
28			float lenght = sqrt(v.posx * v.posx + v.posy * v.posy + v.posz * v.posz);
29			v.posx /= lenght;
30			v.posy /= lenght;
31			v.posz /= lenght;
32			return v;
33		}
34
35float GetNaturality(float f) {
36			if (f == 0) {
37				return 0;
38			}
39			return f / abs(f);
40		}
41
42		vec3d multiplicatevec(vec3d origin, vec3d v) {
43			origin.posx *= v.posx;
44			origin.posy *= v.posy;
45			origin.posz *= v.posz;
46			return origin;
47		}
48
49		vec3d subtractvec(vec3d origin,vec3d v) {
50			origin.posx -= v.posx;
51			origin.posy -= v.posy;
52			origin.posz -= v.posz;
53			return origin;
54		
55		}
56
57		vec3d addvec(vec3d origin, vec3d v) {
58			origin.posx += v.posx;
59			origin.posy += v.posy;
60			origin.posz += v.posz;
61			return origin;
62
63		}
64