CmSphere.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "CmSphere.h"
  2. #include "CmRay.h"
  3. #include "CmPlane.h"
  4. #include "CmAABox.h"
  5. namespace BansheeEngine
  6. {
  7. std::pair<bool, float> Sphere::intersects(const Ray& ray, bool discardInside) const
  8. {
  9. const Vector3& raydir = ray.getDirection();
  10. const Vector3& rayorig = ray.getOrigin() - getCenter();
  11. float radius = getRadius();
  12. // Check origin inside first
  13. if (rayorig.squaredLength() <= radius*radius && discardInside)
  14. {
  15. return std::pair<bool, float>(true, 0.0f);
  16. }
  17. // t = (-b +/- sqrt(b*b + 4ac)) / 2a
  18. float a = raydir.dot(raydir);
  19. float b = 2 * rayorig.dot(raydir);
  20. float c = rayorig.dot(rayorig) - radius*radius;
  21. // Determinant
  22. float d = (b*b) - (4 * a * c);
  23. if (d < 0)
  24. {
  25. // No intersection
  26. return std::pair<bool, float>(false, 0.0f);
  27. }
  28. else
  29. {
  30. // If d == 0 there is one intersection, if d > 0 there are 2.
  31. // We only return the first one.
  32. float t = ( -b - Math::sqrt(d) ) / (2 * a);
  33. if (t < 0)
  34. t = ( -b + Math::sqrt(d) ) / (2 * a);
  35. return std::pair<bool, float>(true, t);
  36. }
  37. }
  38. bool Sphere::intersects(const Plane& plane) const
  39. {
  40. return (Math::abs(plane.getDistance(getCenter())) <= getRadius());
  41. }
  42. bool Sphere::intersects(const AABox& box) const
  43. {
  44. return box.intersects(*this);
  45. }
  46. }