AGX Dynamics  2.37.2.0
SphereBoxOverlapTest.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2024. Algoryx Simulation AB.
3 
4 All AGX source code, intellectual property, documentation, sample code,
5 tutorials, scene files and technical white papers, are copyrighted, proprietary
6 and confidential material of Algoryx Simulation AB. You may not download, read,
7 store, distribute, publish, copy or otherwise disseminate, use or expose this
8 material unless having a written signed agreement with Algoryx Simulation AB, or having been
9 advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10 valid commercial license from Algoryx Simulation AB.
11 
12 Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13 from using this software, unless otherwise stated in written agreements with
14 Algoryx Simulation AB.
15 */
16 
17 #ifndef AGX_HIERARCHICALGRIDSPHEREBOXOVERLAPTEST_H
18 #define AGX_HIERARCHICALGRIDSPHEREBOXOVERLAPTEST_H
19 
20 #include <agx/Vec3.h>
21 #include <agx/AffineMatrix4x4.h>
22 
23 namespace agx
24 {
25 
26  #define AXIS_TEST(axis) \
27  { \
28  Real diff = std::abs( localSpherePosition[axis] ) - boxHalfExtents[axis]; \
29  if (diff > 0) { \
30  if (diff > sphereRadius) \
31  return false; /* Early out */ \
32  isOutside = true; \
33  pointOnBox[axis] = (localSpherePosition[axis] > 0) ? boxHalfExtents[axis] : -boxHalfExtents[axis]; \
34  } \
35  }
36 
37 
38  inline bool sphereBoxOverlapTest
39  (
40  Real sphereRadius, const Vec3& spherePosition,
41  const Vec3& boxHalfExtents, const AffineMatrix4x4 &boxInvTransform
42  )
43  {
44 
45  // This is easy. get the sphere center `p' relative to the box, and then clip
46  // that to the boundary of the box (call that point `q'). if q is on the
47  // boundary of the box and |p-q| is <= sphere radius, they touch.
48  // if q is inside the box, the sphere is inside the box, so set a contact
49  // normal to push the sphere to the closest box face.
50 
51  // all collision detection takes place in box's frame
52  Vec3 localSpherePosition = spherePosition * boxInvTransform;
53  Vec3 pointOnBox = localSpherePosition;
54 
55  bool isOutside = false;
56  // Unrolled loop
57  AXIS_TEST(0)
58  AXIS_TEST(1)
59  AXIS_TEST(2)
60 
61  if (isOutside) {
62  Vec3 normal = localSpherePosition - pointOnBox;
63  Real distance2 = normal.length2();
64  if (distance2 > sphereRadius * sphereRadius)
65  return false; //sphere completely outside of box
66  }
67 
68  return true;
69  }
70 
71 }
72 
73 
74 #endif /* AGX_HIERARCHICALGRIDSPHEREBOXOVERLAPTEST_H */
Real length2() const
Length squared of the vector = vec .
Definition: Vec3Template.h:689
bool sphereBoxOverlapTest(Real sphereRadius, const Vec3 &spherePosition, const Vec3 &boxHalfExtents, const AffineMatrix4x4 &boxInvTransform)
#define AXIS_TEST(axis)
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
double Real
Definition: Real.h:42