Example #1
0
bool Sphere::intersect(const Ray& ray, Hit& hit) const
{
  float a = (ray.direction.normalized()).dot(ray.direction.normalized());
  float b = 2.0f * (ray.direction.normalized()).dot(ray.origin - mCenter);
  float c = (ray.origin - mCenter).dot(ray.origin - mCenter) - (mRadius * mRadius);

  float discriminant = b * b - 4 * a * c;

  if (discriminant > 0) {

    float s1 = (- b + sqrtf(discriminant)) / 2 * a;
    float s2 = (- b - sqrtf(discriminant)) / 2 * a;

    // Tester le chemin le plus court ?
    if (s1 > 0) {
      if (s1 < s2 && hit.t() > s1) {
        hit.setT(s1);
	hit.setIntersection(ray.direction * s1);
      }
    }

    if (s2 > 0) {
      if (s2 < s1 && hit.t() > s2) {
        hit.setT(s2);
	hit.setIntersection(ray.direction * s2);
      }
    }
  }
  else if (discriminant = 0) {
    float s = - b / 2 * a;

    if (hit.t() > s) {
      hit.setT(s);
      hit.setIntersection(ray.direction * s);
    }
  }
  else {
    return false;
  }

  return true;
}