Sphere.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Geometry/AABox.h>
  5. JPH_NAMESPACE_BEGIN
  6. class [[nodiscard]] Sphere
  7. {
  8. public:
  9. /// Constructor
  10. inline Sphere() = default;
  11. inline Sphere(const Float3 &inCenter, float inRadius) : mCenter(inCenter), mRadius(inRadius) { }
  12. inline Sphere(Vec3Arg inCenter, float inRadius) : mRadius(inRadius) { inCenter.StoreFloat3(&mCenter); }
  13. /// Calculate the support vector for this convex shape.
  14. inline Vec3 GetSupport(Vec3Arg inDirection) const
  15. {
  16. float length = inDirection.Length();
  17. return length > 0.0f ? Vec3::sLoadFloat3Unsafe(mCenter) + (mRadius/ length) * inDirection : Vec3::sLoadFloat3Unsafe(mCenter);
  18. }
  19. // Properties
  20. inline Vec3 GetCenter() const { return Vec3::sLoadFloat3Unsafe(mCenter); }
  21. inline float GetRadius() const { return mRadius; }
  22. /// Test if two spheres overlap
  23. inline bool Overlaps(const Sphere &inB) const
  24. {
  25. return (Vec3::sLoadFloat3Unsafe(mCenter) - Vec3::sLoadFloat3Unsafe(inB.mCenter)).LengthSq() <= Square(mRadius + inB.mRadius);
  26. }
  27. /// Check if this sphere overlaps with a box
  28. inline bool Overlaps(const AABox &inOther) const
  29. {
  30. return inOther.GetSqDistanceTo(GetCenter()) <= Square(mRadius);
  31. }
  32. /// Create the minimal sphere that encapsulates this sphere and inPoint
  33. inline void EncapsulatePoint(Vec3Arg inPoint)
  34. {
  35. // Calculate distance between point and center
  36. Vec3 center = GetCenter();
  37. Vec3 d_vec = inPoint - center;
  38. float d_sq = d_vec.LengthSq();
  39. if (d_sq > Square(mRadius))
  40. {
  41. // It is further away than radius, we need to widen the sphere
  42. // The diameter of the new sphere is radius + d, so the new radius is half of that
  43. float d = sqrt(d_sq);
  44. float radius = 0.5f * (mRadius + d);
  45. // The center needs to shift by new radius - old radius in the direction of d
  46. center += (radius - mRadius) / d * d_vec;
  47. // Store new sphere
  48. center.StoreFloat3(&mCenter);
  49. mRadius = radius;
  50. }
  51. }
  52. private:
  53. Float3 mCenter;
  54. float mRadius;
  55. };
  56. JPH_NAMESPACE_END