I’m trying to code my own raytracer for a particle system to draw particles that are a bit overlapped by others with a darker color. Particle is a circle. So I want to trace ray from each particle’s center to a light source. My HLSL:
Particle particle = sbParticles[index];
Particle lightSource = sbParticles[2];
float shadowFactor = 1.0f;
float3 rayDirection = normalize(lightSource.pos - particle.pos);
float3 origin = particle.pos;
float a = dot(rayDirection, rayDirection);
float b = 2.0 * dot(rayDirection, origin);
float c = dot(origin, origin) - particle.radius * particle.radius;
float discriminant = b * b - 4.0 * a * c;
if (discriminant < 0.0f)
{
shadowFactor = 0.0f;
}
else
{
float t0 = (-b - sqrt(discriminant)) / (2.0 * a);
float t1 = (-b + sqrt(discriminant)) / (2.0 * a);
float t = min(t0, t1);
if (t > 0.0f) shadowFactor = 1.0f;
}
Particles positions:
sbParticles[0].pos = XMFLOAT3(-100.0, 60.0, 20.0);
sbParticles[0].radius = 70.0f;
sbParticles[1].pos = XMFLOAT3(100.0, 60.0, 20.0);
sbParticles[1].radius = 70.0f;
sbParticles[2].pos = XMFLOAT3(400.0, 60.0, 20.0); // light source
sbParticles[2].radius = 70.0f;
But when I run this code it doesn’t work as I expect. As you can see, sbParticles[1]
is next to sbParticles[0]
, so I want to trace a ray from sbParticles[0]
and hit sbParticles[1]
. Discriminant is positive (it’s always positive, even when sbParticles[1]
does not overlap sbParticles[0]
at all !). And t
contains 70, which is the particle’s radius.
What math am I missing?