+class InstanceArrayBase: public Renderable, public NonCopyable
+{
+private:
+ struct Block
+ {
+ char *begin = 0;
+ char *end = 0;
+ };
+
+ struct Slot
+ {
+ bool used = false;
+ union
+ {
+ std::uint16_t array_index;
+ std::uint16_t next_free;
+ };
+ std::uint16_t block_index;
+ std::uint16_t index_in_block;
+ };
+
+ const Object &object;
+ VertexArray instance_data;
+ Buffer *instance_buffer = 0;
+ VertexSetup vtx_setup;
+ int matrix_location = -1;
+ unsigned matrix_offset = 0;
+ std::size_t instance_size;
+ std::size_t default_count;
+ std::vector<Block> storage;
+ std::vector<Slot> slots;
+ std::vector<int> array_order;
+ int first_free = -1;
+ int last_free = -1;
+ std::size_t instance_count = 0;
+
+protected:
+ InstanceArrayBase(const Object &, std::size_t);
+ ~InstanceArrayBase();
+
+private:
+ void add_block(std::size_t);
+ std::size_t allocate();
+ char *get_address(std::size_t) const;
+ std::size_t find_index(char *) const;
+ void release(std::size_t);
+protected:
+ template<typename T, typename A>
+ T *create(A &);
+
+ template<typename T>
+ void destroy(T *);
+
+ template<typename T>
+ void destroy_all();
+
+ void update_instance_matrix(std::size_t, const Matrix &);
+
+public:
+ std::size_t size() const { return instance_count; }
+
+ virtual void render(Renderer &, Tag) const;
+};
+
+template<typename T, typename A>
+inline T *InstanceArrayBase::create(A &array)
+{
+ size_t index = allocate();
+ return new(get_address(index)) T(object, array, index);
+}
+
+template<typename T>
+inline void InstanceArrayBase::destroy(T *obj)
+{
+ char *addr = reinterpret_cast<char *>(obj);
+ obj->~T();
+ release(find_index(addr));
+}
+
+template<typename T>
+inline void InstanceArrayBase::destroy_all()
+{
+ for(unsigned i=0; i<slots.size(); ++i)
+ if(slots[i].used)
+ reinterpret_cast<T *>(get_address(i))->~T();
+}
+
+