HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
karma_procedurals/sphere_intersect.vfl
/*%vcc -l intersect.otl -O vop % */
#include "math.h"
cvex
main(
// Inputs
vector ray_org = 0; // ray origin given by procedural
vector ray_dir = 0; // ray direction given by procedural
// Parameters
float radius = 1;
vector color = {1, 1, 1};
// Outputs
export float distance = 0; // distance to hit
export vector Ng = 0; // normal at hit
export vector uvw = 0; // uvw
export int hit = 0; // boolean determining whether there was a hit
)
{
// intersect with sphere
hit = 0;
float b = 2*dot(ray_org, ray_dir);
float c = length2(ray_org) - radius*radius;
float d = b*b - 4.0f*c;
// check discriminant for hit
if (d > 0)
{
d = sqrt(d);
float dist0 = 0.5f * (-b - d);
float dist1 = 0.5f * (-b + d);
if (dist0 > 0 && dist0 < dist1)
{
hit = 1;
distance = dist0;
}
else if (dist1 > 0)
{
hit = 1;
distance = dist1;
}
Ng = ray_org + distance * ray_dir;
Ng = normalize(Ng);
uvw.x = fit(atan2(Ng.x, Ng.z), -PI, PI, 0, 1);
uvw.y = fit(asin(Ng.y), -PI_2, PI_2, 0, 1);
uvw.z = 0;
}
}