AGX Dynamics  2.35.0.1
CellTable.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2022. 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_HIERARCHICAL_GRID_CELLTABLE_H
18 #define AGX_HIERARCHICAL_GRID_CELLTABLE_H
19 
20 #include <agx/Vec3.h>
22 #include <agxData/Array.h>
23 #include <agxData/Buffer.h>
24 
25 namespace agx
26 {
27  template <typename CellIdT, typename HashT = HashFn<CellIdT> >
28  class CellTable
29  {
30  public:
31  class Bucket
32  {
33  public:
34  enum State
35  {
38  VALID
39  };
40 
42 
44  {
45  }
46 
48  {
49  cellIndex = b.cellIndex;
50  state = b.state;
51 
52  return *this;
53  }
54 
56  { return state >= ACTIVE; }
57 
59  {
60  // prefetch( &state, agx::NTA );
61  return state == VALID;
62  }
63 
64  private:
65  friend class CellTable<CellIdT, HashT>;
66  agx::UInt8 state;
67  };
68 
69 
70  template<typename T>
72  {
73  public:
75  AGX_FORCE_INLINE template_iterator() : m_cellTable(0), m_currentIndex(0) {}
76 
77  AGX_FORCE_INLINE template_iterator(T* hashSet, size_t startIndex = 0) : m_cellTable(hashSet), m_currentIndex(startIndex-1)
78  { this->gotoNextElement(); }
79 
81  #ifndef __clang__ // TODO Make sure clang does not produce warnings for this
83  {
85  constIt.m_cellTable = m_cellTable;
86  constIt.m_currentIndex = m_currentIndex;
87  return constIt;
88  }
89  #endif
90 
92  {
93  this->gotoNextElement();
94  return *this;
95  }
96 
98  {
99  size_t oldIndex = m_currentIndex;
100  this->gotoNextElement();
101 
102  return template_iterator<T>(m_cellTable, oldIndex);
103  }
104 
105 
107  {
108  this->gotoPreviousElement();
109  return *this;
110  }
111 
113  {
114  size_t oldIndex = m_currentIndex;
115  this->gotoPreviousElement();
116 
117  return template_iterator<T>(m_cellTable, oldIndex);
118  }
119 
121  { return this->m_currentIndex == rhs.m_currentIndex && this->m_cellTable == rhs.m_cellTable; }
122 
124  { return this->m_currentIndex != rhs.m_currentIndex || this->m_cellTable != rhs.m_cellTable; }
125 
126 
128  {
129  agxAssert1(m_cellTable && m_currentIndex != m_cellTable->m_capacity, "Can not dereference an invalid bucket!");
130  return m_cellTable->m_buckets[m_currentIndex].cellIndex;
131  }
132 
134  { return &(operator*()); }
135 
136 
138  {
139  m_cellTable = copy.m_cellTable;
140  m_currentIndex = copy.m_currentIndex;
141  return *this;
142  }
143 
144  private:
145  AGX_FORCE_INLINE void gotoNextElement()
146  {
147  m_currentIndex++;
148  while (m_currentIndex < m_cellTable->m_capacity && !m_cellTable->m_buckets[m_currentIndex].isValid())
149  m_currentIndex++;
150  }
151 
152  AGX_FORCE_INLINE void gotoPreviousElement()
153  {
154  if (m_currentIndex > 0) {
155  m_currentIndex--;
156  while (m_currentIndex > 0 && !m_cellTable->buckets()[m_currentIndex].isValid())
157  m_currentIndex--;
158  }
159  }
160  private:
161  friend class CellTable;
162  T* m_cellTable;
163  size_t m_currentIndex;
164  };
165 
169 
170 
171  public:
172  CellTable(agxData::Buffer *cellIdBuffer) :
173  m_size(0), m_capacity(0), m_buckets(nullptr),
174  m_smoothingAverage(0), m_maxProbeLength(0),
175  m_cellIds(cellIdBuffer->ptr<CellIdT>()), m_cellIdBuffer(cellIdBuffer), m_cellIdReallocationCallback(&CellTable::cellIdReallocationCallback, this)
176  {
177  m_cellIdBuffer->reallocationEvent.addCallback(&m_cellIdReallocationCallback);
178  this->rebuild(0);
179  }
180 
182  {
183  m_cellIdBuffer->reallocationEvent.removeCallback(&m_cellIdReallocationCallback);
184  m_allocator.deallocateBytes(m_buckets, m_capacity * sizeof(Bucket));
185  }
186 
187 
188  AGX_FORCE_INLINE UInt32 find(const CellIdT& cellId) const
189  {
190  UInt32 bucketIndex = findBucket(cellId);
191  // std::cout << "Found " << cellId << " at " << bucketIndex << std::endl;
192  return bucketIndex != InvalidIndex ? m_buckets[bucketIndex].cellIndex : InvalidIndex;
193  }
194 
195  AGX_FORCE_INLINE bool contains(const CellIdT& cellId) const
196  {
197  return this->findBucket(cellId) != InvalidIndex;
198  }
199 
200  void updateWithReordering(const agxData::Array<UInt32>& sortedIndices)
201  {
202  // std::cout << "numBuckets: " << m_capacity << ", size: " << m_size << ", maxProbeLength: " << m_maxProbeLength << std::endl;
203  for (size_t i = 0; i < m_capacity; ++i)
204  {
205  if (m_buckets[i].isValid())
206  m_buckets[i].cellIndex = sortedIndices[m_buckets[i].cellIndex];
207  }
208  }
209 
210 
211  void insert(const CellIdT& cellId, UInt32 cellIndex)
212  {
213  UInt32 hashValue = m_hashFunctor(cellId);
214  Bucket *bucket;
215  Bucket *targetBucket = 0;
216  size_t offset = 0;
217  // std::cout << "Insert " << cellIndex << " with id " << cellId << std::endl;
218 
219  /* Check if we should grow and rebuild hash table */
220  if (m_size >= (size_t)((float)m_capacity * AGX_HASH_TABLE_GROW_THRESHOLD))
221  this->rebuild((size_t)((float)(m_capacity+1) * AGX_HASH_TABLE_GROW_FACTOR));
222 
223 #ifdef _MSC_VER
224 #pragma warning(push)
225 #pragma warning(disable: 4127) // warning C4127: conditional expression is constant
226 #endif
227 
228  {
229  /* Iterate until target bucket is found */
230  const bool trueVal = true;
231  do
232  {
233  bucket = &m_buckets[(hashValue + offset * offset) % m_capacity];
234 
235  /* Check if overwriting previous insertion with same key */
236  if (bucket->isValid() && m_cellIds[bucket->cellIndex] == cellId)
237  {
238  targetBucket = bucket;
239  break;
240  }
241 
242  /* Tag first free slot */
243  if (!bucket->isValid() && !targetBucket)
244  targetBucket = bucket;
245 
246  /* If we have found a free bucket we can stop iterating when we are sure that the key was not previously inserted */
247  if (targetBucket && offset >= m_maxProbeLength)
248  break;
249 
250  /* Go to next bucket */
251  offset++;
252 
253  /* Resize and rebuild table if it takes too long to find a free slot */
254  if (offset > AGX_HASH_TABLE_MAX_PROBE_LENGTH)
255  {
256  this->rebuild((size_t)((float)m_capacity * AGX_HASH_TABLE_GROW_FACTOR));
257  this->insert(cellId, cellIndex);
258  return;
259  }
260  } while (trueVal);
261  }
262 #ifdef _MSC_VER
263 #pragma warning(pop)
264 #endif
265 
266  agxAssert(targetBucket);
267 
268  if (offset > m_maxProbeLength)
269  m_maxProbeLength = (UInt16)offset;
270 
271  targetBucket->cellIndex = cellIndex;
272 
273  /* Check if inserting a new value rather than overwriting an old entry */
274  if (!targetBucket->isValid())
275  {
276  m_size++;
277  targetBucket->state = Bucket::VALID;
278  }
279 
280  }
281 
282  void erase(const CellIdT& cellId)
283  {
284  UInt32 bucketIndex = findBucket(cellId);
285  agxAssert(bucketIndex != InvalidIndex);
286 
287  Bucket *bucket = &m_buckets[bucketIndex];
288  agxAssert(bucket->isValid() && m_cellIds[bucket->cellIndex] == cellId);
289 
290  m_size--;
291 
292  // Bucket does not become inactive since it might be in the middle of a probing chain
293  bucket->state = Bucket::ACTIVE;
294  }
295 
300  { return iterator(this); }
301 
303  { return const_iterator(this); }
304 
305 
310  { return iterator(this, m_capacity); }
311 
313  { return const_iterator(this, m_capacity); }
314 
315  private:
316  AGX_FORCE_INLINE UInt32 findBucket(const CellIdT& cellId) const
317  {
318  agxAssert(m_buckets);
319 
320  UInt32 hashValue = m_hashFunctor(cellId);
321  size_t index = hashValue % m_capacity;
322  const Bucket *bucket = &m_buckets[index];
323 
324  /* First test is outside for-loop, hopefully getting better branch prediction */
325  if (bucket->isValid() && m_cellIds[bucket->cellIndex] == cellId)
326  return (UInt32)index;
327 
328 
329  for (size_t offset = 1; bucket->isActive() && offset <= m_maxProbeLength; offset++)
330  {
331  index = (hashValue + offset * offset) % m_capacity;
332  bucket = &m_buckets[index];
333 
334  if (bucket->isValid() && m_cellIds[bucket->cellIndex] == cellId)
335  return (UInt32)index;
336  }
337 
338  /* Not found */
339  return InvalidIndex;
340  }
341 
342  void rebuild(size_t size)
343  {
344  size = std::max( size, size_t(AGX_HASH_TABLE_MIN_SIZE) );
345  // std::cout << "HashTable: Rebuilding and resizing from " << m_capacity << " to " << agx::nextPrime((int)(size)) << " buckets." << std::endl;
346  agxAssert(size >= m_size);
347  size_t oldNumBuckets = m_capacity;
348  Bucket *oldBuckets = m_buckets;
349 
350  m_capacity = agx::nextPrime((int)size);
351  m_buckets = (Bucket *)m_allocator.allocateBytes(m_capacity * sizeof(Bucket));
352  for (size_t i = 0; i < m_capacity; ++i)
353  ::new (&m_buckets[i]) Bucket();
354 
355  m_size = 0;
356  m_maxProbeLength = 0;
357 
358  for (size_t i = 0; i < oldNumBuckets; i++)
359  {
360  Bucket& bucket = oldBuckets[i];
361 
362  if (bucket.isValid())
363  this->insert(m_cellIds[bucket.cellIndex], bucket.cellIndex);
364  }
365 
366  m_allocator.deallocateBytes((void *)oldBuckets, oldNumBuckets * sizeof(Bucket));
367  }
368 
369  void cellIdReallocationCallback(agxData::Buffer *)
370  {
371  // std::cout << "cellIdReallocationCallback" << std::endl;
372  m_cellIds = m_cellIdBuffer->ptr<CellIdT>();
373  }
374 
375  private:
376  size_t m_size;
377  size_t m_capacity;
378  Bucket *m_buckets;
379  // UInt32 *m_bucketValues;
380  // Bucket::State *m_bucketStates;
381 
382  Real32 m_smoothingAverage;
383  UInt16 m_maxProbeLength;
384  ByteAllocator m_allocator;
385  HashT m_hashFunctor;
386 
387 
388  const CellIdT *m_cellIds;
389  agxData::BufferRef m_cellIdBuffer;
390  agxData::Buffer::Event::CallbackType m_cellIdReallocationCallback;
391  };
392 }
393 
394 
395 #endif /* AGX_HIERARCHICAL_GRID_CELLTABLE_H */
#define AGX_HASH_TABLE_GROW_FACTOR
#define AGX_HASH_TABLE_GROW_THRESHOLD
#define AGX_HASH_TABLE_MAX_PROBE_LENGTH
#define AGX_HASH_TABLE_MIN_SIZE
#define m_size
Definition: agx/Vector.h:429
#define m_capacity
Definition: agx/Vector.h:430
Type-specific Array used for fast access into the data held by a Buffer.
Definition: Array.h:107
Abstract representation of a data buffer.
Definition: Buffer.h:56
void * allocateBytes(size_t numBytes, size_t alignment=16)
Allocate a memory section of specified alignment.
void deallocateBytes(void *buffer, size_t numBytes)
Deallocate a section previously allocated using allocateBytes method.
bool isValid() const
Definition: CellTable.h:58
bool isActive() const
Definition: CellTable.h:55
Bucket & operator=(const Bucket &b)
Definition: CellTable.h:47
template_iterator< T > & operator++()
Definition: CellTable.h:91
template_iterator(T *hashSet, size_t startIndex=0)
Definition: CellTable.h:77
template_iterator< T > operator++(int)
Definition: CellTable.h:97
template_iterator()
Constructors.
Definition: CellTable.h:75
bool operator!=(const template_iterator< T > &rhs)
Definition: CellTable.h:123
bool operator==(const template_iterator< T > &rhs)
Definition: CellTable.h:120
template_iterator< T > operator--()
Definition: CellTable.h:106
template_iterator< T > operator--(int)
Definition: CellTable.h:112
template_iterator< T > & operator=(const template_iterator< T > &copy)
Definition: CellTable.h:137
template_iterator< const CellTable > const_iterator
Definition: CellTable.h:168
iterator begin()
Iterator to first element in hash set.
Definition: CellTable.h:299
const_iterator end() const
Definition: CellTable.h:312
const_iterator begin() const
Definition: CellTable.h:302
void updateWithReordering(const agxData::Array< UInt32 > &sortedIndices)
Definition: CellTable.h:200
iterator end()
Iterator marking end of hash set.
Definition: CellTable.h:309
CellTable(agxData::Buffer *cellIdBuffer)
Definition: CellTable.h:172
void erase(const CellIdT &cellId)
Definition: CellTable.h:282
template_iterator< CellTable > iterator
Iterators.
Definition: CellTable.h:167
void insert(const CellIdT &cellId, UInt32 cellIndex)
Definition: CellTable.h:211
bool contains(const CellIdT &cellId) const
Definition: CellTable.h:195
UInt32 find(const CellIdT &cellId) const
Definition: CellTable.h:188
T CallbackType
Definition: Event.h:37
#define agxAssert1(expr, msg)
Definition: debug.h:144
#define agxAssert(expr)
Definition: debug.h:143
#define AGX_FORCE_INLINE
Definition: macros.h:58
std::pair< agx::Name, agx::Real > Bucket
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
uint16_t UInt16
Definition: Integer.h:39
uint32_t UInt32
Definition: Integer.h:40
AGXCORE_EXPORT int nextPrime(int n)
uint8_t UInt8
Definition: Integer.h:38
float Real32
Definition: Real.h:44
AGXCORE_EXPORT const InvalidIndexStruct InvalidIndex
Vec3T< T > max(const Vec3T< T > &lhs, const Vec3T< T > &rhs)
Definition: Vec3Template.h:874