AGX Dynamics 2.38.0.2
Loading...
Searching...
No Matches
CollisionGroupManager.h
Go to the documentation of this file.
1/*
2Copyright 2007-2024. Algoryx Simulation AB.
3
4All AGX source code, intellectual property, documentation, sample code,
5tutorials, scene files and technical white papers, are copyrighted, proprietary
6and confidential material of Algoryx Simulation AB. You may not download, read,
7store, distribute, publish, copy or otherwise disseminate, use or expose this
8material unless having a written signed agreement with Algoryx Simulation AB, or having been
9advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10valid commercial license from Algoryx Simulation AB.
11
12Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13from using this software, unless otherwise stated in written agreements with
14Algoryx 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>
26
27namespace agxCollide
28{
31 {
32 public:
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
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
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
95
96
101 bool canGroupsCollide(agx::UInt32 group1, agx::UInt32 group2) const;
102
107
109 static bool hasGroup(agx::Physics::CollisionGroupSetPtr set, const agx::Name& groupName);
111
112 const CollisionHash& getDisabledGroupCollisions() const;
113 const CollisionHash& getDisabledSetCollisions() const;
114
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
125
127
130
133
135
137
138 protected:
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:
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
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 */
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
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
486 typedef agx::HashVector<agx::Name, agx::UInt32> CollisionGroupNameTable;
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 */
#define AGX_DECLARE_POINTER_TYPES(type)
Definition Referenced.h:254
#define AGXSTREAM_DECLARE_SERIALIZABLE(T)
Use this in a Serializable class to add the required methods Important: Use full namespace in the dec...
#define AGXPHYSICS_EXPORT
#define AGX_HASH_SET_MIN_SIZE
Definition agx/HashSet.h:63
#define AGX_HASH_SET_MAX_PROBE_LENGTH
Definition agx/HashSet.h:70
#define AGX_HASH_SET_GROW_FACTOR
Definition agx/HashSet.h:67
#define AGX_HASH_SET_GROW_THRESHOLD
Definition agx/HashSet.h:65
#define m_size
Definition agx/Vector.h:429
#define m_capacity
Definition agx/Vector.h:430
agx::Physics::CollisionGroupSetPtr getExtendedSet(agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId, bool unreferenceOldSet=true)
Extend an existing group set by adding an additional group (can be nullptr pointer)
const agxData::EntityStorage * getCollisionGroupSetStorage() const
const CollisionHash & getDisabledGroupCollisions() const
agx::Physics::CollisionGroupPtr getGroup(const agx::Name &groupName)
void internal_restore(agxStream::InputArchive &in)
const agxData::EntityStorage * getCollisionGroupStorage() const
static void printSet(const agx::Physics::CollisionGroupSetPtr &set)
static bool hasGroup(agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId)
void unreferenceSet(agx::Physics::CollisionGroupSetPtr set)
Unreference a set when it is no longer used.
bool canSetsCollide(agx::UInt32 set1, agx::UInt32 set2) const
static bool hasGroup(agx::Physics::CollisionGroupSetPtr set, const agx::Name &groupName)
agx::HashSet< agx::Physics::CollisionGroupPtr > GroupHash
bool canGroupsCollide(agx::UInt32 group1, agx::UInt32 group2) const
void setEnableCollisions(agx::UInt32 groupId1, agx::UInt32 groupId2, bool flag)
Enable/disable collisions between two groups.
agx::Vector< agx::Physics::CollisionGroupPtr > GroupVector
static bool verify(agx::Physics::CollisionGroupSetPtr set)
agx::HashSet< agx::UInt32 > GroupIdHash
agx::Vector< agx::Physics::CollisionGroupSetPtr > GroupSetVector
agx::Physics::CollisionGroupSetPtr getExtendedSetFromAddedSet(agx::Physics::CollisionGroupSetPtr set, agx::Physics::CollisionGroupSetPtr set2, bool unreferenceOldSet=true)
Extend an existing group set by adding an additional group set.
const CollisionHash & getDisabledSetCollisions() const
static CollisionGroupManager * defaultManager()
agx::Physics::CollisionGroupPtr getGroup(agx::UInt32 groupId)
agx::Physics::CollisionGroupSetPtr getMatchingSet(agx::Physics::CollisionGroupSetPtr set)
Get the matching set stored in another CollisionGroupManager NOTE: The old set must be manually unref...
agx::HashSet< agx::Physics::CollisionGroupSetPtr > GroupSetHash
bool hasGroup(agx::UInt32 groupId) const
SymmetricCollisionGroupVector getDisabledCollisionGroupPairs() const
bool hasGroup(const agx::Name &groupName) const
agx::HashSet< agx::UInt64 > CollisionHash
agx::Physics::CollisionGroupSetPtr getReducedSet(agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId, bool unreferenceOldSet=true)
Reduce an existing group set by removing a group.
agx::Vector< agx::SymmetricPair< agx::Physics::CollisionGroupPtr > > SymmetricCollisionGroupVector
agx::UInt32 getGroupId(const agx::Name &groupName)
This class contains all Geometries and performs Broad Phase and Narrow Phase collision detection to c...
Definition Space.h:82
agx::Index getId() const
Definition EntityPtr.h:273
agxData::EntityStorage * getStorage() const
Definition EntityPtr.h:272
bool isValid() const
Definition EntityPtr.h:287
Data storage for a collection of entity instances of a specified EntityModel.
Class for reading a binary stream of serialized data.
This class is an abstract base class for all classes that can be stored and retrieved from an Archive...
Byte allocator.
Definition Allocator.h:57
A component is an object containing other objects, enabling hierarchical structuring.
Definition Component.h:39
bool contains(const KeyT &key) const
Boolean query to test existence of an element.
This class is a combined container which has the find complexity of a HashTable, deterministic iterat...
Definition HashVector.h:41
Inheritance with partial specialization due to bug with ref_ptr containers.
Representation of a name string.
Definition Name.h:33
Pointer to a entity instance of type Physics.CollisionGroup.
AGXPHYSICS_EXPORT agx::UInt32 & id()
Pointer to a entity instance of type Physics.CollisionGroupSet.
AGXPHYSICS_EXPORT agx::Vector< agx::Physics::CollisionGroupPtr > & groups()
Templated vector class.
Definition agx/Vector.h:53
#define agxAssert(expr)
Definition debug.h:143
#define AGX_FORCE_INLINE
Definition macros.h:58
This namespace consists of a set of classes for handling geometric intersection tests including boole...
std::ostream & operator<<(std::ostream &output, const BoundingAABB &bound)
std::pair< agx::Name, agx::Real > Bucket
uint16_t UInt16
Definition Integer.h:31
std::mutex Mutex
Definition Referenced.h:99
uint32_t UInt32
Definition Integer.h:32
AGXCORE_EXPORT UInt32 hash(const T &key)
AGXCORE_EXPORT int nextPrime(int n)
AGXCORE_EXPORT agx::UInt64 buildHashKey(agx::UInt32 id1, agx::UInt32 id2)
uint8_t UInt8
Definition Integer.h:30
AGXCORE_EXPORT const InvalidIndexStruct InvalidIndex