raytri.cpp
Go to the documentation of this file.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <math.h>
6 
63 #include "raytri.h"
64 
65 namespace ConvexDecomposition
66 {
67 
68 
69 /* a = b - c */
70 #define vector(a,b,c) \
71  (a)[0] = (b)[0] - (c)[0]; \
72  (a)[1] = (b)[1] - (c)[1]; \
73  (a)[2] = (b)[2] - (c)[2];
74 
75 
76 
77 #define innerProduct(v,q) \
78  ((v)[0] * (q)[0] + \
79  (v)[1] * (q)[1] + \
80  (v)[2] * (q)[2])
81 
82 #define crossProduct(a,b,c) \
83  (a)[0] = (b)[1] * (c)[2] - (c)[1] * (b)[2]; \
84  (a)[1] = (b)[2] * (c)[0] - (c)[2] * (b)[0]; \
85  (a)[2] = (b)[0] * (c)[1] - (c)[0] * (b)[1];
86 
87 bool rayIntersectsTriangle(const double *p,const double *d,const double *v0,const double *v1,const double *v2,double &t)
88 {
89 
90  double e1[3],e2[3],h[3],s[3],q[3];
91  double a,f,u,v;
92 
93  vector(e1,v1,v0);
94  vector(e2,v2,v0);
95  crossProduct(h,d,e2);
96  a = innerProduct(e1,h);
97 
98  if (a > -0.00001 && a < 0.00001)
99  return(false);
100 
101  f = 1/a;
102  vector(s,p,v0);
103  u = f * (innerProduct(s,h));
104 
105  if (u < 0.0 || u > 1.0)
106  return(false);
107 
108  crossProduct(q,s,e1);
109  v = f * innerProduct(d,q);
110  if (v < 0.0 || u + v > 1.0)
111  return(false);
112  // at this stage we can compute t to find out where
113  // the intersection point is on the line
114  t = f * innerProduct(e2,q);
115  if (t > 0) // ray intersection
116  return(true);
117  else // this means that there is a line intersection
118  // but not a ray intersection
119  return (false);
120 }
121 
122 
123 bool lineIntersectsTriangle(const double *rayStart,const double *rayEnd,const double *p1,const double *p2,const double *p3,double *sect)
124 {
125  double dir[3];
126 
127  dir[0] = rayEnd[0] - rayStart[0];
128  dir[1] = rayEnd[1] - rayStart[1];
129  dir[2] = rayEnd[2] - rayStart[2];
130 
131  double d = sqrt(dir[0]*dir[0] + dir[1]*dir[1] + dir[2]*dir[2]);
132  double r = 1.0f / d;
133 
134  dir[0]*=r;
135  dir[1]*=r;
136  dir[2]*=r;
137 
138 
139  double t;
140 
141  bool ret = rayIntersectsTriangle(rayStart, dir, p1, p2, p3, t );
142 
143  if ( ret )
144  {
145  if ( t > d )
146  {
147  sect[0] = rayStart[0] + dir[0]*t;
148  sect[1] = rayStart[1] + dir[1]*t;
149  sect[2] = rayStart[2] + dir[2]*t;
150  }
151  else
152  {
153  ret = false;
154  }
155  }
156 
157  return ret;
158 }
159 
160 }; // end of namespace
#define crossProduct(a, b, c)
Definition: raytri.cpp:82
#define vector(a, b, c)
Definition: raytri.cpp:70
bool rayIntersectsTriangle(const double *p, const double *d, const double *v0, const double *v1, const double *v2, double &t)
Definition: raytri.cpp:87
bool lineIntersectsTriangle(const double *rayStart, const double *rayEnd, const double *p1, const double *p2, const double *p3, double *sect)
Definition: raytri.cpp:123
#define innerProduct(v, q)
Definition: raytri.cpp:77


convex_decomposition
Author(s): John W. Ratcliff
autogenerated on Mon Feb 28 2022 22:06:34