www.pudn.com > Ray_Tracing_Materials.rar > Sphere.cpp, change:2005-03-02,size:2761b
/*
File Name:
Sphere.cpp
Created by:
Allen Sherrod (Programming Ace of www.UltimateGameProgramming.com).
Description:
This file has the source for the Sphere functions.
*/
#include"Sphere.h"
TraceResult Sphere::Intersect(Ray &ray)
{
// result will hold the result of the test if the ray hits this sphere.
// RayToSphereDir will hold the direction of the ray's origin to the sphere origin.
TraceResult result;
CVector4 RayToSphereDir;
// RayToSphereLength will hold the length of the ray's origin to the spheres origin.
// IntersectPoint will be greater than or equal to 0 if the ray hits the sphere.
// SquaredPoint will be used after the IntersectPoint test has turned up a hit.
float RayToSphereLength = 0.0f;
float IntersectPoint = 0.0f;
float SquaredPoint = 0.0f;
// Get the direction of the ray to the current object we are testing against.
RayToSphereDir = center - ray.origin;
// Dot product the direction of the ray to current sphere to get the length.
RayToSphereLength = RayToSphereDir.DotProduct3(RayToSphereDir);
// Get the dot product of the direction of the ray to the sphere with the direction the
// ray is moving to find the intersect point.
IntersectPoint = RayToSphereDir.DotProduct3(ray.direction);
// If this is less than zero then the ray does not hit the sphere else it might.
if(IntersectPoint < 0 )
{
result.hit = false;
return result;
}
// Get the squared sphere radius - the length of the ray direction to the sphere
// plus the IntersectPoint squared.
SquaredPoint = (radius * radius) - RayToSphereLength +
(IntersectPoint * IntersectPoint);
// If this is less than zero then the ray does not hit the sphere at all for sure.
if(SquaredPoint < 0)
{
result.hit = false;
return result;
}
// Else it does hit the sphere and we record the results.
result.hit = true;
result.distance = IntersectPoint - (float)sqrt(SquaredPoint);
return result;
}
CVector4 Sphere::GetNormal(CVector4 &RayShapeIntersect)
{
CVector4 normal;
// Calculate the sphere normal at the point of intersection.
float oneOverRadius = 1 / radius;
normal.x = (RayShapeIntersect.x - center.x) * oneOverRadius;
normal.y = (RayShapeIntersect.y - center.y) * oneOverRadius;
normal.z = (RayShapeIntersect.z - center.z) * oneOverRadius;
normal.Normal();
return normal;
}
// Copyright February 2005
// All Rights Reserved!
// Allen Sherrod
// ProgrammingAce@UltimateGameProgramming.com
// www.UltimateGameProgramming.com