2 Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans https://bulletphysics.org
4 This software is provided 'as-is', without any express or implied warranty.
5 In no event will the authors be held liable for any damages arising from the use of this software.
6 Permission is granted to anyone to use this software for any purpose,
7 including commercial applications, and to alter it and redistribute it freely,
8 subject to the following restrictions:
10 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
11 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
12 3. This notice may not be removed or altered from any source distribution.
15 #ifndef _BT_POOL_ALLOCATOR_H
16 #define _BT_POOL_ALLOCATOR_H
19 #include "btAlignedAllocator.h"
20 #include "btThreads.h"
22 ///The btPoolAllocator class allows to efficiently allocate a large pool of objects, instead of dynamically allocating them separately.
29 unsigned char* m_pool;
30 btSpinMutex m_mutex; // only used if BT_THREADSAFE
33 btPoolAllocator(int elemSize, int maxElements)
34 : m_elemSize(elemSize),
35 m_maxElements(maxElements)
37 m_pool = (unsigned char*)btAlignedAlloc(static_cast<unsigned int>(m_elemSize * m_maxElements), 16);
39 unsigned char* p = m_pool;
41 m_freeCount = m_maxElements;
42 int count = m_maxElements;
45 *(void**)p = (p + m_elemSize);
53 btAlignedFree(m_pool);
56 int getFreeCount() const
61 int getUsedCount() const
63 return m_maxElements - m_freeCount;
66 int getMaxCount() const
71 void* allocate(int size)
75 btMutexLock(&m_mutex);
76 btAssert(!size || size <= m_elemSize);
77 //btAssert(m_freeCount>0); // should return null if all full
78 void* result = m_firstFree;
79 if (NULL != m_firstFree)
81 m_firstFree = *(void**)m_firstFree;
84 btMutexUnlock(&m_mutex);
88 bool validPtr(void* ptr)
92 if (((unsigned char*)ptr >= m_pool && (unsigned char*)ptr < m_pool + m_maxElements * m_elemSize))
100 void freeMemory(void* ptr)
104 btAssert((unsigned char*)ptr >= m_pool && (unsigned char*)ptr < m_pool + m_maxElements * m_elemSize);
106 btMutexLock(&m_mutex);
107 *(void**)ptr = m_firstFree;
110 btMutexUnlock(&m_mutex);
114 int getElementSize() const
119 unsigned char* getPoolAddress()
124 const unsigned char* getPoolAddress() const
130 #endif //_BT_POOL_ALLOCATOR_H