public Intersection intersect(Ray ray)
{
Intersection result = new Intersection();
// compute s1 = d x e2
Point p1 = mesh.p[v1];
Point p2 = mesh.p[v2];
Point p3 = mesh.p[v3];
Vector e1 = p1.to(p2);
Vector e2 = p1.to(p3);
Vector s1 = ray.d.cross(e2);
double divisor = s1.dot(e1);
if (divisor == 0)
return result;
double invDivisor = 1.0 / divisor;
// compute first barycentric coordinate b1
Vector d = p1.to(ray.o);
double b1 = d.dot(s1) * invDivisor;
if (b1 < 0 || b1 > 1)
return result;
// compute second barycentric coordinate b2
Vector s2 = d.cross(e1);
double b2 = ray.d.dot(s2) * invDivisor;
if (b2 < 0 || b2 > 1)
return result;
// compute t to intersection point
double t = e2.dot(s2) * invDivisor;
if (t < ray.mint || t > ray.maxt)
return result;
// compute triangle partial derivatives
Vector dpdu, dpdv;
double[][] uvs = getUVs();
// compute deltas for triangle partial derivatives
double du1 = uvs[0][0] - uvs[2][0];
double du2 = uvs[1][0] - uvs[2][0];
double dv1 = uvs[0][1] - uvs[2][1];
double dv2 = uvs[1][1] - uvs[2][1];
Vector dp1 = p3.to(p1);
Vector dp2 = p3.to(p2);
double determinant = du1 * dv2 - dv1 * du2;
if (determinant == 0)
{
dpdu = new Vector();