ougge/src/Game/GameObjectPool.hpp
2024-09-14 21:28:18 +05:00

65 lines
2.1 KiB
C++

#include "GameObject.hpp"
/*
Fixed array stkring deleted elements indices as bits in array of u64.
Fast emplace, erase and lookup.
------------------------[construct]------------------------
operation 'GameObjectPool::GameObjectPool()' took 1.0549 ms
operation 'other_collections_construct' took 0.0133 ms
-------------------------[emplace]-------------------------
operation 'GameObjectPool::emplace' took 8.0557 ms
operation 'vector::emplace_back' took 11.3735 ms
operation 'set::emplace' took 80.5633 ms
operation 'list::emplace_front' took 18.1442 ms
operation 'forward_list::emplace_front' took 11.5467 ms
--------------------------[erase]--------------------------
operation 'GameObjectPool::erase' took 0.2745 ms
operation 'vector::erase' took 15790.6 ms
operation 'set::erase' took 1.2697 ms
operation 'list::erase_after' took 0.93 ms
operation 'forward_list::erase_after' took 1.1127 ms
-------------------------[iterate]-------------------------
operation 'GameObjectPool::iterate' took 1.1166 ms
operation 'vector::iterate' took 0.8883 ms
operation 'set::iterate' took 2.8011 ms
operation 'list::iterate' took 2.0766 ms
operation 'forward_list::iterate' took 2.0823 ms
*/
class GameObjectPool {
void* buffer;
u64* used_indices;
u32 size;
u32 first_unused_index;
bool isIndexUsed(u32 index);
u32 getNearestUnusedIndex(u32 startIndex);
u32 getNearestUsedIndex(u32 startIndex);
public:
///@param size must be a multiple of 64
GameObjectPool(u32 size);
~GameObjectPool();
GameObject& get(u32 index);
std::pair<u32, GameObject&> emplace(GameObject&& new_obj);
void erase(u32 index);
class iterator {
GameObjectPool* p;
u32 index = 0;
public:
iterator(GameObjectPool* p, u32 index);
std::pair<u32, GameObject&> operator*();
iterator& operator++();
inline bool operator!=(const iterator& o) const { return index != o.index; };
inline bool operator==(const iterator& o) const { return index == o.index; };
};
inline iterator begin() { return iterator(this, 0); }
inline iterator end() { return iterator(this, -1); }
friend class iterator;
};