ContSphere3.h 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // David Eberly, Geometric Tools, Redmond WA 98052
  2. // Copyright (c) 1998-2020
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // https://www.boost.org/LICENSE_1_0.txt
  5. // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
  6. // Version: 4.0.2019.08.13
  7. #pragma once
  8. #include <Mathematics/Hypersphere.h>
  9. #include <Mathematics/Vector3.h>
  10. #include <vector>
  11. namespace WwiseGTE
  12. {
  13. // Compute the smallest bounding sphere whose center is the average of
  14. // the input points.
  15. template <typename Real>
  16. bool GetContainer(int numPoints, Vector3<Real> const* points, Sphere3<Real>& sphere)
  17. {
  18. sphere.center = points[0];
  19. for (int i = 1; i < numPoints; ++i)
  20. {
  21. sphere.center += points[i];
  22. }
  23. sphere.center /= (Real)numPoints;
  24. sphere.radius = (Real)0;
  25. for (int i = 0; i < numPoints; ++i)
  26. {
  27. Vector3<Real> diff = points[i] - sphere.center;
  28. Real radiusSqr = Dot(diff, diff);
  29. if (radiusSqr > sphere.radius)
  30. {
  31. sphere.radius = radiusSqr;
  32. }
  33. }
  34. sphere.radius = std::sqrt(sphere.radius);
  35. return true;
  36. }
  37. template <typename Real>
  38. bool GetContainer(std::vector<Vector3<Real>> const& points, Sphere3<Real>& sphere)
  39. {
  40. return GetContainer(static_cast<int>(points.size()), points.data(), sphere);
  41. }
  42. // Test for containment of a point inside a sphere.
  43. template <typename Real>
  44. bool InContainer(Vector3<Real> const& point, Sphere3<Real> const& sphere)
  45. {
  46. Vector3<Real> diff = point - sphere.center;
  47. return Length(diff) <= sphere.radius;
  48. }
  49. // Compute the smallest bounding sphere that contains the input spheres.
  50. template <typename Real>
  51. bool MergeContainers(Sphere3<Real> const& sphere0, Sphere3<Real> const& sphere1, Sphere3<Real>& merge)
  52. {
  53. Vector3<Real> cenDiff = sphere1.center - sphere0.center;
  54. Real lenSqr = Dot(cenDiff, cenDiff);
  55. Real rDiff = sphere1.radius - sphere0.radius;
  56. Real rDiffSqr = rDiff * rDiff;
  57. if (rDiffSqr >= lenSqr)
  58. {
  59. merge = (rDiff >= (Real)0 ? sphere1 : sphere0);
  60. }
  61. else
  62. {
  63. Real length = std::sqrt(lenSqr);
  64. if (length > (Real)0)
  65. {
  66. Real coeff = (length + rDiff) / (((Real)2)*length);
  67. merge.center = sphere0.center + coeff * cenDiff;
  68. }
  69. else
  70. {
  71. merge.center = sphere0.center;
  72. }
  73. merge.radius = (Real)0.5 * (length + sphere0.radius + sphere1.radius);
  74. }
  75. return true;
  76. }
  77. }