raySphereIntersectionInterval.glsl 926 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Compute the intersection interval of a ray with a sphere.
  3. *
  4. * @name czm_raySphereIntersectionInterval
  5. * @glslFunction
  6. *
  7. * @param {czm_ray} ray The ray.
  8. * @param {vec3} center The center of the sphere.
  9. * @param {float} radius The radius of the sphere.
  10. * @return {czm_raySegment} The intersection interval of the ray with the sphere.
  11. */
  12. czm_raySegment czm_raySphereIntersectionInterval(czm_ray ray, vec3 center, float radius)
  13. {
  14. vec3 o = ray.origin;
  15. vec3 d = ray.direction;
  16. vec3 oc = o - center;
  17. float a = dot(d, d);
  18. float b = 2.0 * dot(d, oc);
  19. float c = dot(oc, oc) - (radius * radius);
  20. float det = (b * b) - (4.0 * a * c);
  21. if (det < 0.0) {
  22. return czm_emptyRaySegment;
  23. }
  24. float sqrtDet = sqrt(det);
  25. float t0 = (-b - sqrtDet) / (2.0 * a);
  26. float t1 = (-b + sqrtDet) / (2.0 * a);
  27. czm_raySegment result = czm_raySegment(t0, t1);
  28. return result;
  29. }