QuadTree.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/FixedSizeFreeList.h>
  5. #include <Jolt/Core/Atomics.h>
  6. #include <Jolt/Core/NonCopyable.h>
  7. #include <Jolt/Physics/Body/BodyManager.h>
  8. #include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>
  9. //#define JPH_DUMP_BROADPHASE_TREE
  10. JPH_NAMESPACE_BEGIN
  11. /// Internal tree structure in broadphase, is essentially a quad AABB tree.
  12. /// Tree is lockless (except for UpdatePrepare/Finalize() function), modifying objects in the tree will widen the aabbs of parent nodes to make the node fit.
  13. /// During the UpdatePrepare/Finalize() call the tree is rebuilt to achieve a tight fit again.
  14. class QuadTree : public NonCopyable
  15. {
  16. public:
  17. JPH_OVERRIDE_NEW_DELETE
  18. private:
  19. // Forward declare
  20. class AtomicNodeID;
  21. /// Class that points to either a body or a node in the tree
  22. class NodeID
  23. {
  24. public:
  25. JPH_OVERRIDE_NEW_DELETE
  26. /// Default constructor does not initialize
  27. inline NodeID() = default;
  28. /// Construct a node ID
  29. static inline NodeID sInvalid() { return NodeID(cInvalidNodeIndex); }
  30. static inline NodeID sFromBodyID(BodyID inID) { NodeID node_id(inID.GetIndexAndSequenceNumber()); JPH_ASSERT(node_id.IsBody()); return node_id; }
  31. static inline NodeID sFromNodeIndex(uint32 inIdx) { NodeID node_id(inIdx | cIsNode); JPH_ASSERT(node_id.IsNode()); return node_id; }
  32. /// Check what type of ID it is
  33. inline bool IsValid() const { return mID != cInvalidNodeIndex; }
  34. inline bool IsBody() const { return (mID & cIsNode) == 0; }
  35. inline bool IsNode() const { return (mID & cIsNode) != 0; }
  36. /// Get body or node index
  37. inline BodyID GetBodyID() const { JPH_ASSERT(IsBody()); return BodyID(mID); }
  38. inline uint32 GetNodeIndex() const { JPH_ASSERT(IsNode()); return mID & ~cIsNode; }
  39. /// Comparison
  40. inline bool operator == (const BodyID &inRHS) const { return mID == inRHS.GetIndexAndSequenceNumber(); }
  41. inline bool operator == (const NodeID &inRHS) const { return mID == inRHS.mID; }
  42. private:
  43. friend class AtomicNodeID;
  44. inline explicit NodeID(uint32 inID) : mID(inID) { }
  45. static const uint32 cIsNode = BodyID::cBroadPhaseBit; ///< If this bit is set it means that the ID refers to a node, otherwise it refers to a body
  46. uint32 mID;
  47. };
  48. static_assert(sizeof(NodeID) == sizeof(BodyID), "Body id's should have the same size as NodeIDs");
  49. /// A NodeID that uses atomics to store the value
  50. class AtomicNodeID
  51. {
  52. public:
  53. /// Constructor
  54. AtomicNodeID() = default;
  55. explicit AtomicNodeID(const NodeID &inRHS) : mID(inRHS.mID) { }
  56. /// Assignment
  57. inline void operator = (const NodeID &inRHS) { mID = inRHS.mID; }
  58. /// Getting the value
  59. inline operator NodeID () const { return NodeID(mID); }
  60. /// Check if the ID is valid
  61. inline bool IsValid() const { return mID != cInvalidNodeIndex; }
  62. /// Comparison
  63. inline bool operator == (const BodyID &inRHS) const { return mID == inRHS.GetIndexAndSequenceNumber(); }
  64. inline bool operator == (const NodeID &inRHS) const { return mID == inRHS.mID; }
  65. /// Atomically compare and swap value. Expects inOld value, replaces with inNew value or returns false
  66. inline bool CompareExchange(NodeID inOld, NodeID inNew) { return mID.compare_exchange_strong(inOld.mID, inNew.mID); }
  67. private:
  68. atomic<uint32> mID;
  69. };
  70. /// Class that represents a node in the tree
  71. class Node
  72. {
  73. public:
  74. /// Construct node
  75. explicit Node(bool inIsChanged);
  76. /// Get bounding box encapsulating all children
  77. void GetNodeBounds(AABox &outBounds) const;
  78. /// Get bounding box in a consistent way with the functions below (check outBounds.IsValid() before using the box)
  79. void GetChildBounds(int inChildIndex, AABox &outBounds) const;
  80. /// Set the bounds in such a way that other threads will either see a fully correct bounding box or a bounding box with no volume
  81. void SetChildBounds(int inChildIndex, const AABox &inBounds);
  82. /// Invalidate bounding box in such a way that other threads will not temporarily see a very large bounding box
  83. void InvalidateChildBounds(int inChildIndex);
  84. /// Encapsulate inBounds in node bounds, returns true if there were changes
  85. bool EncapsulateChildBounds(int inChildIndex, const AABox &inBounds);
  86. /// Bounding box for child nodes or bodies (all initially set to invalid so no collision test will ever traverse to the leaf)
  87. atomic<float> mBoundsMinX[4];
  88. atomic<float> mBoundsMinY[4];
  89. atomic<float> mBoundsMinZ[4];
  90. atomic<float> mBoundsMaxX[4];
  91. atomic<float> mBoundsMaxY[4];
  92. atomic<float> mBoundsMaxZ[4];
  93. /// Index of child node or body ID.
  94. AtomicNodeID mChildNodeID[4];
  95. /// Index of the parent node.
  96. /// Note: This value is unreliable during the UpdatePrepare/Finalize() function as a node may be relinked to the newly built tree.
  97. atomic<uint32> mParentNodeIndex = cInvalidNodeIndex;
  98. /// If this part of the tree has changed, if not, we will treat this sub tree as a single body during the UpdatePrepare/Finalize().
  99. /// If any changes are made to an object inside this sub tree then the direct path from the body to the top of the tree will become changed.
  100. atomic<uint32> mIsChanged;
  101. // Padding to align to 124 bytes
  102. uint32 mPadding = 0;
  103. };
  104. // Maximum size of the stack during tree walk
  105. static constexpr int cStackSize = 128;
  106. static_assert(sizeof(atomic<float>) == 4, "Assuming that an atomic doesn't add any additional storage");
  107. static_assert(sizeof(atomic<uint32>) == 4, "Assuming that an atomic doesn't add any additional storage");
  108. static_assert(is_trivially_destructible<Node>(), "Assuming that we don't have a destructor");
  109. public:
  110. /// Class that allocates tree nodes, can be shared between multiple trees
  111. using Allocator = FixedSizeFreeList<Node>;
  112. static_assert(Allocator::ObjectStorageSize == 128, "Node should be 128 bytes");
  113. /// Data to track location of a Body in the tree
  114. struct Tracking
  115. {
  116. /// Constructor to satisfy the vector class
  117. Tracking() = default;
  118. Tracking(const Tracking &inRHS) : mBroadPhaseLayer(inRHS.mBroadPhaseLayer.load()), mObjectLayer(inRHS.mObjectLayer.load()), mBodyLocation(inRHS.mBodyLocation.load()) { }
  119. /// Invalid body location identifier
  120. static const uint32 cInvalidBodyLocation = 0xffffffff;
  121. atomic<BroadPhaseLayer::Type> mBroadPhaseLayer = (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid;
  122. atomic<ObjectLayer> mObjectLayer = cObjectLayerInvalid;
  123. atomic<uint32> mBodyLocation { cInvalidBodyLocation };
  124. };
  125. using TrackingVector = Array<Tracking>;
  126. /// Destructor
  127. ~QuadTree();
  128. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  129. /// Name of the tree for debugging purposes
  130. void SetName(const char *inName) { mName = inName; }
  131. inline const char * GetName() const { return mName; }
  132. #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
  133. /// Check if there is anything in the tree
  134. inline bool HasBodies() const { return mNumBodies != 0; }
  135. /// Check if the tree needs an UpdatePrepare/Finalize()
  136. inline bool IsDirty() const { return mIsDirty; }
  137. /// Check if this tree can get an UpdatePrepare/Finalize() or if it needs a DiscardOldTree() first
  138. inline bool CanBeUpdated() const { return mFreeNodeBatch.mNumObjects == 0; }
  139. /// Initialization
  140. void Init(Allocator &inAllocator);
  141. struct UpdateState
  142. {
  143. NodeID mRootNodeID; ///< This will be the new root node id
  144. };
  145. /// Will throw away the previous frame's nodes so that we can start building a new tree in the background
  146. void DiscardOldTree();
  147. /// Update the broadphase, needs to be called regularly to achieve a tight fit of the tree when bodies have been modified.
  148. /// UpdatePrepare() will build the tree, UpdateFinalize() will lock the root of the tree shortly and swap the trees and afterwards clean up temporary data structures.
  149. void UpdatePrepare(const BodyVector &inBodies, TrackingVector &ioTracking, UpdateState &outUpdateState, bool inFullRebuild);
  150. void UpdateFinalize(const BodyVector &inBodies, const TrackingVector &inTracking, const UpdateState &inUpdateState);
  151. /// Temporary data structure to pass information between AddBodiesPrepare and AddBodiesFinalize/Abort
  152. struct AddState
  153. {
  154. NodeID mLeafID = NodeID::sInvalid();
  155. AABox mLeafBounds;
  156. };
  157. /// Prepare adding inNumber bodies at ioBodyIDs to the quad tree, returns the state in outState that should be used in AddBodiesFinalize.
  158. /// This can be done on a background thread without influencing the broadphase.
  159. /// ioBodyIDs may be shuffled around by this function.
  160. void AddBodiesPrepare(const BodyVector &inBodies, TrackingVector &ioTracking, BodyID *ioBodyIDs, int inNumber, AddState &outState);
  161. /// Finalize adding bodies to the quadtree, supply the same number of bodies as in AddBodiesPrepare.
  162. void AddBodiesFinalize(TrackingVector &ioTracking, int inNumberBodies, const AddState &inState);
  163. /// Abort adding bodies to the quadtree, supply the same bodies and state as in AddBodiesPrepare.
  164. /// This can be done on a background thread without influencing the broadphase.
  165. void AddBodiesAbort(TrackingVector &ioTracking, const AddState &inState);
  166. /// Remove inNumber bodies in ioBodyIDs from the quadtree.
  167. void RemoveBodies(const BodyVector &inBodies, TrackingVector &ioTracking, const BodyID *ioBodyIDs, int inNumber);
  168. /// Call whenever the aabb of a body changes.
  169. void NotifyBodiesAABBChanged(const BodyVector &inBodies, const TrackingVector &inTracking, const BodyID *ioBodyIDs, int inNumber);
  170. /// Cast a ray and get the intersecting bodies in ioCollector.
  171. void CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  172. /// Get bodies intersecting with inBox in ioCollector
  173. void CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  174. /// Get bodies intersecting with a sphere in ioCollector
  175. void CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  176. /// Get bodies intersecting with a point and any hits to ioCollector
  177. void CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  178. /// Get bodies intersecting with an oriented box and any hits to ioCollector
  179. void CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  180. /// Cast a box and get intersecting bodies in ioCollector
  181. void CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
  182. /// Find all colliding pairs between dynamic bodies, calls ioPairCollector for every pair found
  183. void FindCollidingPairs(const BodyVector &inBodies, const BodyID *inActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, BodyPairCollector &ioPairCollector, ObjectLayerPairFilter inObjectLayerPairFilter) const;
  184. #ifdef JPH_TRACK_BROADPHASE_STATS
  185. /// Trace the stats of this tree to the TTY
  186. void ReportStats() const;
  187. #endif // JPH_TRACK_BROADPHASE_STATS
  188. private:
  189. /// Constants
  190. static const uint32 cInvalidNodeIndex = 0xffffffff; ///< Value used to indicate node index is invalid
  191. static const float cLargeFloat; ///< A large floating point number that is small enough to not cause any overflows
  192. static const AABox cInvalidBounds; ///< Invalid bounding box using cLargeFloat
  193. /// We alternate between two trees in order to let collision queries complete in parallel to adding/removing objects to the tree
  194. struct RootNode
  195. {
  196. /// Get the ID of the root node
  197. inline NodeID GetNodeID() const { return NodeID::sFromNodeIndex(mIndex); }
  198. /// Index of the root node of the tree (this is always a node, never a body id)
  199. atomic<uint32> mIndex { cInvalidNodeIndex };
  200. };
  201. /// Caches location of body inBodyID in the tracker, body can be found in mNodes[inNodeIdx].mChildNodeID[inChildIdx]
  202. void GetBodyLocation(const TrackingVector &inTracking, BodyID inBodyID, uint32 &outNodeIdx, uint32 &outChildIdx) const;
  203. void SetBodyLocation(TrackingVector &ioTracking, BodyID inBodyID, uint32 inNodeIdx, uint32 inChildIdx) const;
  204. static void sInvalidateBodyLocation(TrackingVector &ioTracking, BodyID inBodyID);
  205. /// Get the current root of the tree
  206. JPH_INLINE const RootNode & GetCurrentRoot() const { return mRootNode[mRootNodeIndex]; }
  207. JPH_INLINE RootNode & GetCurrentRoot() { return mRootNode[mRootNodeIndex]; }
  208. /// Depending on if inNodeID is a body or tree node return the bounding box
  209. inline AABox GetNodeOrBodyBounds(const BodyVector &inBodies, NodeID inNodeID) const;
  210. /// Mark node and all of its parents as changed
  211. inline void MarkNodeAndParentsChanged(uint32 inNodeIndex);
  212. /// Widen parent bounds of node inNodeIndex to encapsulate inNewBounds, also mark node and all of its parents as changed
  213. inline void WidenAndMarkNodeAndParentsChanged(uint32 inNodeIndex, const AABox &inNewBounds);
  214. /// Allocate a new node
  215. inline uint32 AllocateNode(bool inIsChanged);
  216. /// Try to insert a new leaf to the tree at inNodeIndex
  217. inline bool TryInsertLeaf(TrackingVector &ioTracking, int inNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies);
  218. /// Try to replace the existing root with a new root that contains both the existing root and the new leaf
  219. inline bool TryCreateNewRoot(TrackingVector &ioTracking, atomic<uint32> &ioRootNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies);
  220. /// Build a tree for ioBodyIDs, returns the NodeID of the root (which will be the ID of a single body if inNumber = 1). All tree levels up to inMaxDepthMarkChanged will be marked as 'changed'.
  221. NodeID BuildTree(const BodyVector &inBodies, TrackingVector &ioTracking, NodeID *ioNodeIDs, int inNumber, uint inMaxDepthMarkChanged, AABox &outBounds);
  222. /// Sorts ioNodeIDs spatially into 2 groups. Second groups starts at ioNodeIDs + outMidPoint.
  223. /// After the function returns ioNodeIDs and ioNodeCenters will be shuffled
  224. static void sPartition(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inNumber, int &outMidPoint);
  225. /// Sorts ioNodeIDs from inBegin to (but excluding) inEnd spatially into 4 groups.
  226. /// outSplit needs to be 5 ints long, when the function returns each group runs from outSplit[i] to (but excluding) outSplit[i + 1]
  227. /// After the function returns ioNodeIDs and ioNodeCenters will be shuffled
  228. static void sPartition4(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inBegin, int inEnd, int *outSplit);
  229. #ifdef _DEBUG
  230. /// Validate that the tree is consistent.
  231. /// Note: This function only works if the tree is not modified while we're traversing it.
  232. void ValidateTree(const BodyVector &inBodies, const TrackingVector &inTracking, uint32 inNodeIndex, uint32 inNumExpectedBodies) const;
  233. #endif
  234. #ifdef JPH_DUMP_BROADPHASE_TREE
  235. /// Dump the tree in DOT format (see: https://graphviz.org/)
  236. void DumpTree(const NodeID &inRoot, const char *inFileNamePrefix) const;
  237. #endif
  238. #ifdef JPH_TRACK_BROADPHASE_STATS
  239. /// Mutex protecting the various LayerToStats members
  240. mutable Mutex mStatsMutex;
  241. struct Stat
  242. {
  243. uint64 mNumQueries = 0;
  244. uint64 mNodesVisited = 0;
  245. uint64 mBodiesVisited = 0;
  246. uint64 mHitsReported = 0;
  247. uint64 mTotalTicks = 0;
  248. uint64 mCollectorTicks = 0;
  249. };
  250. using LayerToStats = UnorderedMap<String, Stat>;
  251. /// Trace the stats of a single query type to the TTY
  252. void ReportStats(const char *inName, const LayerToStats &inLayer) const;
  253. mutable LayerToStats mCastRayStats;
  254. mutable LayerToStats mCollideAABoxStats;
  255. mutable LayerToStats mCollideSphereStats;
  256. mutable LayerToStats mCollidePointStats;
  257. mutable LayerToStats mCollideOrientedBoxStats;
  258. mutable LayerToStats mCastAABoxStats;
  259. #endif // JPH_TRACK_BROADPHASE_STATS
  260. /// Debug function to get the depth of the tree from node inNodeID
  261. uint GetMaxTreeDepth(const NodeID &inNodeID) const;
  262. /// Walk the node tree calling the Visitor::VisitNodes for each node encountered and Visitor::VisitBody for each body encountered
  263. template <class Visitor>
  264. JPH_INLINE void WalkTree(const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking, Visitor &ioVisitor JPH_IF_TRACK_BROADPHASE_STATS(, LayerToStats &ioStats)) const;
  265. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  266. /// Name of this tree for debugging purposes
  267. const char * mName = "Layer";
  268. #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
  269. /// Number of bodies currently in the tree
  270. atomic<uint32> mNumBodies { 0 };
  271. /// We alternate between two tree root nodes. When updating, we activate the new tree and we keep the old tree alive.
  272. /// for queries that are in progress until the next time DiscardOldTree() is called.
  273. RootNode mRootNode[2];
  274. atomic<uint32> mRootNodeIndex { 0 };
  275. /// Allocator that controls adding / freeing nodes
  276. Allocator * mAllocator = nullptr;
  277. /// This is a list of nodes that must be deleted after the trees are swapped and the old tree is no longer in use
  278. Allocator::Batch mFreeNodeBatch;
  279. /// Flag to keep track of changes to the broadphase, if false, we don't need to UpdatePrepare/Finalize()
  280. atomic<bool> mIsDirty = false;
  281. };
  282. JPH_NAMESPACE_END