AGX Dynamics  2.37.2.0
CollisionGroupManager.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 AGXCOLLIDE_COLLISIONGROUPHANDLER_H
18 #define AGXCOLLIDE_COLLISIONGROUPHANDLER_H
19 
20 #include <agx/HashSet.h>
21 #include <agx/AtomicValue.h>
22 #include <agx/Component.h>
25 #include <agxStream/Serializable.h>
26 
27 namespace agxCollide
28 {
31  {
32  public:
33  static CollisionGroupManager *defaultManager();
34 
35  public:
36  // typedef agx::Vector< agx::UInt32 > GroupIdVector;
42 
44 
45  public:
47 
53  agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId, bool unreferenceOldSet = true);
54 
59  agx::Physics::CollisionGroupSetPtr getExtendedSetFromAddedSet(
60  agx::Physics::CollisionGroupSetPtr set, agx::Physics::CollisionGroupSetPtr set2, bool unreferenceOldSet = true);
61 
67  agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId, bool unreferenceOldSet = true);
68 
75 
76 
80  void unreferenceSet(agx::Physics::CollisionGroupSetPtr set);
81 
85  void setEnableCollisions(agx::UInt32 groupId1, agx::UInt32 groupId2, bool flag);
86 
91  bool canSetsCollide(agx::UInt32 set1, agx::UInt32 set2) const;
92 
93  // Wrapper
94  bool canSetsCollide(agx::Physics::CollisionGroupSetPtr set1, agx::Physics::CollisionGroupSetPtr set2) const;
95 
96 
101  bool canGroupsCollide(agx::UInt32 group1, agx::UInt32 group2) const;
102 
106  agx::UInt32 generateUniqueId();
107 
108  static bool hasGroup(agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId);
109  static bool hasGroup(agx::Physics::CollisionGroupSetPtr set, const agx::Name& groupName);
110  static bool verify(agx::Physics::CollisionGroupSetPtr set);
111 
112  const CollisionHash& getDisabledGroupCollisions() const;
113  const CollisionHash& getDisabledSetCollisions() const;
114 
115  static void printSet(const agx::Physics::CollisionGroupSetPtr& set);
116 
117  // Not thread safe
118  bool hasGroup(const agx::Name& groupName) const;
119  bool hasGroup(agx::UInt32 groupId) const;
120 
121  // Not thread safe
122  agx::UInt32 getGroupId(const agx::Name& groupName);
123  agx::Physics::CollisionGroupPtr getGroup(const agx::Name& groupName);
125 
127 
129  SymmetricCollisionGroupVector getDisabledCollisionGroupPairs() const;
130 
131  const agxData::EntityStorage* getCollisionGroupStorage() const;
132  const agxData::EntityStorage* getCollisionGroupSetStorage() const;
133 
134  void internal_restore(agxStream::InputArchive& in);
135 
137 
138  protected:
139  virtual ~CollisionGroupManager();
140 
141  private:
142  friend class Space;
143  agx::UInt32 generateNameId();
144  void setUniqueIdCounter(agx::UInt32 id);
145  void setNameIdCounter(agx::UInt32 id);
146  agx::Physics::CollisionGroupPtr restoreGroup(const agx::Name& groupName, agx::UInt32 id);
147 
148 
149  private:
150  agx::Physics::CollisionGroupSetPtr getUnarySet(agx::UInt32 groupId);
151  void internal_unreferenceSet(agx::Physics::CollisionGroupSetPtr set);
152  bool internal_canCollide(const GroupIdHash& groups1, const GroupIdHash& groups2);
153  void removeInactiveSets();
154  void registerNewSet(agx::Physics::CollisionGroupSetPtr set);
155  void reset();
156 
157  class GroupSetCache
158  {
159  public:
160  class Bucket
161  {
162  public:
163  enum State
164  {
167  VALID
168  };
169 
171 
172  AGX_FORCE_INLINE Bucket() : state(INACTIVE)
173  {
174  }
175 
177  {
178  groupSet = b.groupSet;
179  state = b.state;
180 
181  return *this;
182  }
183 
185  { return state >= ACTIVE; }
186 
188  {
189  // prefetch( &state, agx::NTA );
190  return state == VALID;
191  }
192 
193  private:
194  friend class GroupSetCache;
195  agx::UInt8 state;
196  };
197 
198 
199  public:
200  GroupSetCache() :
201  m_size(0), m_capacity(0), m_buckets(nullptr),
202  m_maxProbeLength(0)
203  {
204  this->rebuild(0);
205  }
206 
207  void clear()
208  {
209  deallocateBuckets();
210  m_size = 0;
211  m_capacity = 0;
212  m_buckets = nullptr;
213  m_maxProbeLength = 0;
214  rebuild(0);
215  }
216 
217  ~GroupSetCache()
218  {
219  deallocateBuckets();
220  }
221 
222 
224  {
225  agx::UInt32 bucketIndex = findBucket(&group, 1);
226  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
227  }
228 
230  {
231  agxAssert(set && set.groups().size() + 1 < 1024);
232  agx::Physics::CollisionGroupPtr localGroups[1024];
233  size_t numGroups = 0;
234 
235  // Build extended list, insert group in already sorted vector
236  const GroupVector& groups = set.groups();
237  size_t i = 0;
238  for (; i < groups.size() && groups[i].id() < group.id(); ++i)
239  localGroups[numGroups++] = groups[i];
240 
241  localGroups[numGroups++] = group;
242 
243  for (; i < groups.size(); ++i)
244  localGroups[numGroups++] = groups[i];
245 
246 
247  agx::UInt32 bucketIndex = findBucket(localGroups, numGroups);
248  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
249  }
250 
252  {
253  agxAssert(set && set.groups().size() - 1 < 1024);
254  agx::Physics::CollisionGroupPtr localGroups[1024];
255  size_t numGroups = 0;
256 
257  // Build reduced list
258  const GroupVector& groups = set.groups();
259  for (size_t i = 0; i < groups.size(); ++i)
260  {
261  if (groups[i].id() == group.id())
262  continue;
263 
264  localGroups[numGroups++] = groups[i];
265  }
266 
267  agx::UInt32 bucketIndex = findBucket(localGroups, numGroups);
268  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
269  }
270 
272  {
273  if (!set)
275 
276  const GroupVector& groups = set.groups();
277 
278  agx::UInt32 bucketIndex = findBucket(groups.begin(), groups.size());
279  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
280  }
281 
282  void insert(agx::Physics::CollisionGroupSetPtr set)
283  {
284  agxAssert(set);
285  const GroupVector& groups = set.groups();
286 
287  agx::UInt32 hashValue = calculateHash(groups.begin(), groups.size());
288 
289  Bucket *bucket;
290  Bucket *targetBucket = 0;
291  size_t offset = 0;
292  // std::cout << "Insert " << cellIndex << " with id " << cellId << std::endl;
293 
294  /* Check if we should grow and rebuild hash table */
295  if (m_size >= (size_t)((float)m_capacity * AGX_HASH_SET_GROW_THRESHOLD))
296  this->rebuild((size_t)((float)(m_capacity+1) * AGX_HASH_SET_GROW_FACTOR));
297 
298  /* Iterate until target bucket is found */
299  bool goon = true;
300  do
301  {
302  bucket = &m_buckets[(hashValue + offset * offset) % m_capacity];
303 
304  /* Check if overwriting previous insertion with same key */
305  if (bucket->isValid() && compareGroups(groups.begin(), groups.size(), bucket->groupSet))
306  {
307  targetBucket = bucket;
308  break;
309  }
310 
311  /* Tag first free slot */
312  if (!bucket->isValid() && !targetBucket)
313  targetBucket = bucket;
314 
315  /* If we have found a free bucket we can stop iterating when we are sure that the key was not previously inserted */
316  if (targetBucket && offset >= m_maxProbeLength)
317  break;
318 
319  /* Go to next bucket */
320  offset++;
321 
322  /* Resize and rebuild table if it takes too long to find a free slot */
323  if (offset > AGX_HASH_SET_MAX_PROBE_LENGTH)
324  {
325  this->rebuild((size_t)((float)m_capacity * AGX_HASH_SET_GROW_FACTOR));
326  return this->insert(set);
327  }
328  } while (goon);
329 
330  agxAssert(targetBucket);
331 
332  if (offset > m_maxProbeLength)
333  m_maxProbeLength = (agx::UInt16)offset;
334 
335  targetBucket->groupSet = set;
336 
337  /* Check if inserting a new value rather than overwriting an old entry */
338  if (!targetBucket->isValid())
339  {
340  m_size++;
341  targetBucket->state = Bucket::VALID;
342  }
343  }
344 
345  bool contains(agx::Physics::CollisionGroupSetPtr set) const
346  {
347  return find(set).isValid();
348  }
349 
350 
351  void erase(agx::Physics::CollisionGroupSetPtr set)
352  {
353  agxAssert(set);
354  const GroupVector& groups = set.groups();
355 
356  agx::UInt32 bucketIndex = findBucket(groups.begin(), groups.size());
357  agxAssert(bucketIndex != agx::InvalidIndex);
358 
359  Bucket *bucket = &m_buckets[bucketIndex];
360  agxAssert(bucket->isValid() && compareGroups(groups.begin(), groups.size(), bucket->groupSet));
361 
362  m_size--;
363 
364  // Bucket does not become inactive since it might be in the middle of a probing chain
365  bucket->state = Bucket::ACTIVE;
366  }
367 
368  private:
369 
370  AGX_FORCE_INLINE agx::UInt32 findBucket(const agx::Physics::CollisionGroupPtr *localGroups, size_t numGroups) const
371  {
372  agxAssert(m_buckets);
373  if (m_buckets) {
374 
375  agx::UInt32 hashValue = calculateHash(localGroups, numGroups);
376 
377  size_t index = hashValue % m_capacity;
378  const Bucket *bucket = &m_buckets[index];
379 
380  /* First test is outside for-loop, hopefully getting better branch prediction */
381  if (bucket->isValid() && compareGroups(localGroups, numGroups, bucket->groupSet))
382  return (agx::UInt32)index;
383 
384 
385  for (size_t offset = 1; bucket->isActive() && offset <= m_maxProbeLength; offset++)
386  {
387  index = (hashValue + offset * offset) % m_capacity;
388  bucket = &m_buckets[index];
389 
390  if (bucket->isValid() && compareGroups(localGroups, numGroups, bucket->groupSet))
391  return (agx::UInt32)index;
392  }
393  }
394 
395  /* Not found */
396  return agx::InvalidIndex;
397  }
398 
399  AGX_FORCE_INLINE agx::UInt32 calculateHash(const agx::Physics::CollisionGroupPtr *localGroups, size_t numGroups) const
400  {
401  // Calculate hash
402  agx::UInt32 hashValue = 0;
403  for (size_t i = 0; i < numGroups; ++i)
404  hashValue = agx::hash(hashValue, agx::hash(localGroups[i].id()));
405 
406  return hashValue;
407  }
408 
409 
410  AGX_FORCE_INLINE bool compareGroups(const agx::Physics::CollisionGroupPtr *localGroups, size_t numGroups, agx::Physics::CollisionGroupSetPtr set) const
411  {
412  agxAssert(set);
413  const GroupVector& groups = set.groups();
414 
415  if (groups.size() != numGroups)
416  return false;
417 
418  for (size_t i = 0; i < groups.size(); ++i)
419  {
420  if (groups[i].id() != localGroups[i].id())
421  return false;
422  }
423 
424  return true;
425  }
426 
427  void rebuild(size_t size)
428  {
429  size = std::max( size, size_t(AGX_HASH_SET_MIN_SIZE) );
430  //LOGGER_DEBUG() << "HashTable: Rebuilding and resizing from " << numBuckets() << " to " << agx::nextPrime((int)(numBuckets() * resizeFactor)) << " buckets.\n" << LOGGER_END();
431  agxAssert(size >= m_size);
432  size_t oldNumBuckets = m_capacity;
433  Bucket *oldBuckets = m_buckets;
434 
435  m_capacity = agx::nextPrime((int)size);
436  m_buckets = (Bucket *)m_allocator.allocateBytes(m_capacity * sizeof(Bucket));
437  for (size_t i = 0; i < m_capacity; ++i)
438  ::new (&m_buckets[i]) Bucket();
439 
440  m_size = 0;
441  m_maxProbeLength = 0;
442 
443  for (size_t i = 0; i < oldNumBuckets; i++)
444  {
445  Bucket& bucket = oldBuckets[i];
446 
447  if (bucket.isValid())
448  this->insert(bucket.groupSet);
449  }
450 
451  m_allocator.deallocateBytes((void *)oldBuckets, oldNumBuckets * sizeof(Bucket));
452  }
453 
454  void deallocateBuckets()
455  {
456  m_allocator.deallocateBytes(m_buckets, m_capacity * sizeof(Bucket));
457  }
458 
459  private:
460  size_t m_size;
461  size_t m_capacity;
462  Bucket *m_buckets;
463 
464  agx::UInt16 m_maxProbeLength;
465  agx::ByteAllocator m_allocator;
466  };
467 
468 
469  private:
470  agx::AtomicValue m_nameIdCounter;
471  agx::AtomicValue m_uniqueIdCounter;
472  agx::Mutex m_mutex;
473  GroupSetCache m_groupSetCache;
474  agxData::EntityStorageRef m_collisionGroupSetStorage;
475 
476  CollisionHash m_disabledSetCollisions;
477  CollisionHash m_disabledGroupCollisions;
478 
480 
481  agxData::EntityStorageRef m_collisionGroupStorage;
482 
484  CollisionGroupTable m_collisionGroupTable;
485 
487  CollisionGroupNameTable m_collisionGroupNameTable;
488  };
489 
490 
491  AGXPHYSICS_EXPORT std::ostream& operator << ( std::ostream& output, const agx::Physics::CollisionGroupSetPtr& set );
492  AGXPHYSICS_EXPORT std::ostream& operator << ( std::ostream& output, const agx::Physics::CollisionGroupPtr& group );
493 
494 
495 
496 
497  /* Implementation */
498 
500  {
501  // std::cout << "canSetsCollide " << set1 << " : " << set2 << " => " << !m_disabledSetCollisions.contains(agx::buildHashKey(set1, set2)) << std::endl;
502  return !m_disabledSetCollisions.contains(agx::buildHashKey(set1, set2));
503  }
504 
506  {
507  agxAssert(set1);
508  agxAssert(set2);
509  agxAssert(set1.getStorage() == m_collisionGroupSetStorage);
510  agxAssert(set2.getStorage() == m_collisionGroupSetStorage);
511  return this->canSetsCollide((agx::UInt32)set1.getId(), (agx::UInt32)set2.getId());
512  }
513 
515  {
516  return !m_disabledGroupCollisions.contains(agx::buildHashKey(group1, group2));
517  }
518 
521 
522 }
523 
524 
525 #endif /* AGXCOLLIDE_COLLISIONGROUPHANDLER_H */
bool canSetsCollide(agx::UInt32 set1, agx::UInt32 set2) const
agx::HashSet< agx::UInt32 > GroupIdHash
InputRef< T > in(const char *name, T &obj)
Create an object with a name and a reference to the object that should be restored (usually a pointer...
Definition: InputArchive.h:400
AGXCORE_EXPORT UInt32 hash(const T &key)
Definition: HashFunction.h:65
AGXTERRAIN_EXPORT void clear()
Vec3T< T > max(const Vec3T< T > &lhs, const Vec3T< T > &rhs)
Definition: Vec3Template.h:855
iterator begin()
Definition: Vector.h:1041
Data storage for a collection of entity instances of a specified EntityModel.
Definition: EntityStorage.h:72
A component is an object containing other objects, enabling hierarchical structuring.
Definition: Component.h:38
This namespace consists of a set of classes for handling geometric intersection tests including boole...
Pointer to a entity instance of type Physics.CollisionGroup.
#define m_size
Definition: Vector.h:429
uint8_t UInt8
Definition: Integer.h:38
const CollisionHash & getDisabledGroupCollisions() const
std::pair< agx::Name, agx::Real > Bucket
#define AGXPHYSICS_EXPORT
AGXCORE_EXPORT const InvalidIndexStruct InvalidIndex
agx::Index getId() const
Definition: EntityPtr.h:273
Representation of a name string.
Definition: Name.h:32
#define AGX_FORCE_INLINE
Definition: Object.h:59
Pointer to a entity instance of type Physics.CollisionGroupSet.
std::ostream & operator<<(std::ostream &output, const BoundingAABB &bound)
Definition: BoundingAABB.h:224
#define AGX_HASH_SET_GROW_THRESHOLD
Definition: HashSet.h:65
Templated vector class.
Definition: Vector.h:52
#define AGX_HASH_SET_GROW_FACTOR
Definition: HashSet.h:67
AGXCORE_EXPORT agx::UInt64 buildHashKey(agx::UInt32 id1, agx::UInt32 id2)
Definition: HashFunction.h:41
This class contains all Geometries and performs Broad Phase and Narrow Phase collision detection to c...
Definition: Space.h:81
agx::HashSet< agx::UInt64 > CollisionHash
agx::HashSet< agx::Physics::CollisionGroupPtr > GroupHash
agx::Vector< agx::Physics::CollisionGroupSetPtr > GroupSetVector
agx::Vector< agx::Physics::CollisionGroupPtr > GroupVector
#define AGX_HASH_SET_MAX_PROBE_LENGTH
Definition: HashSet.h:70
Byte allocator.
Definition: Allocator.h:56
bool canGroupsCollide(agx::UInt32 group1, agx::UInt32 group2) const
agx::Vector< agx::SymmetricPair< agx::Physics::CollisionGroupPtr > > SymmetricCollisionGroupVector
#define agxAssert(expr)
Definition: debug.h:143
AGXCORE_EXPORT int nextPrime(int n)
AGXPHYSICS_EXPORT bool setEnableCollisions(agx::RigidBody *rb1, agx::RigidBody *rb2, bool enable)
Enable or disable the collision between all geometries in RigidBody rb1 and RigidBody rb2...
Class for reading a binary stream of serialized data.
Definition: InputArchive.h:51
#define AGX_HASH_SET_MIN_SIZE
Definition: HashSet.h:63
#define AGXSTREAM_DECLARE_SERIALIZABLE(T)
Use this in a Serializable class to add the required methods Important: Use full namespace in the dec...
Definition: Serializable.h:207
This class is an abstract base class for all classes that can be stored and retrieved from an Archive...
Definition: Serializable.h:44
std::mutex Mutex
Definition: Referenced.h:99
size_t size() const
Definition: Container.h:134
#define m_capacity
Definition: Vector.h:430
uint16_t UInt16
Definition: Integer.h:39
const CollisionHash & getDisabledSetCollisions() const
agx::HashSet< agx::Physics::CollisionGroupSetPtr > GroupSetHash
Inheritance with partial specialization due to bug with ref_ptr containers.
agxData::EntityStorage * getStorage() const
Definition: EntityPtr.h:272
AGXPHYSICS_EXPORT agx::UInt32 & id()
uint32_t UInt32
Definition: Integer.h:40
AGX_DECLARE_POINTER_TYPES(SpaceListener)