www.pudn.com > Ray_Tracing_Materials.rar > Triangle.cpp, change:2005-03-02,size:2147b
/*
File Name:
Triangle.cpp
Created by:
Allen Sherrod (Programming Ace of www.UltimateGameProgramming.com).
Description:
This file has the source for the Triangle class functions.
*/
#include"Triangle.h"
TraceResult Triangle::Intersect(Ray &ray)
{
// result will hold the result of the test if the ray hits this triangle.
TraceResult result;
result.hit = false;
// Store these vectors between the points for future use.
CVector4 vecAB = p2 - p1;
CVector4 vecAC = p3 - p1;
// Get the corss product bewteen the p3 - p1 vector and the ray direction.
CVector4 cross;
cross.CrossProduct(ray.direction, vecAC);
// Calculate the determinate.
float det = vecAB.DotProduct3(cross);
// If the dot product between the cross product result and the vector
// between point 2 and 1 is 0 or less than 0, the ray does not hit.
if(det < 0.0001f)
{
result.hit = false;
return result;
}
CVector4 rayPointVec = ray.origin - p1;
float test1 = rayPointVec.DotProduct3(cross);
// Ray must be behind the plane of the triangle if these are true.
if(test1 < 0.0f || test1 > det)
{
result.hit = false;
return result;
}
CVector4 cross2;
cross2.CrossProduct(rayPointVec , vecAB);
float test2 = ray.direction.DotProduct3(cross2);
// If the second test is less than 0 or if test1 + test2 is > det
// then we don't have a hit.
if(test2 < 0.0f || test1 + test2 > det)
{
result.hit = false;
return result;
}
// Else we have a hit and can calculate the distance of intersection.
float inverseDet = 1.0f / det;
result.distance = vecAC.DotProduct3(cross2);
result.distance *= inverseDet;
result.hit = true;
return result;
}
CVector4 Triangle::GetNormal()
{
CVector4 normal;
normal.CrossProduct(p2 - p1, p3 - p1);
normal.Normal();
return normal;
}
// Copyright February 2005
// All Rights Reserved!
// Allen Sherrod
// ProgrammingAce@UltimateGameProgramming.com
// www.UltimateGameProgramming.com