////////////////////////////////////////////////////////////////////////////////
// SPTree.h
// Implementation of a space partition tree designed to speed up spacial queries
// Developed by Bjoern Ganster since 2020
////////////////////////////////////////////////////////////////////////////////

#pragma once

#include "RenderableObject.h"

class SPTreeCell: public VirtualClass {
public:
	SPTreeCell* negCell;
	SPTreeCell* posCell;
	std::vector<RenderableObject*> negObjects, posObjects, undecidedObjects;
	Plane plane;

	// Constructor
	SPTreeCell();

	// Destructor
	~SPTreeCell();
};

class SPTree: public VirtualClass {
public:
	// Constructor
	SPTree(size_t maxObjectsPerCell);

	// Destructor
	~SPTree() OVERRIDE;

	// Add object
	void add(RenderableObject* obj);

	// Update object
	void update(RenderableObject* obj);

	// Remove object
	void remove(RenderableObject* obj);

	// Check which other objects collide with obj
	size_t getColliders(RenderableObject* obj, std::vector<RenderableObject*>& colliders);

	// Import scene from obj
	void importScene(RenderableObject* obj);
private:
	SPTreeCell mMainCell;
	size_t mMaxObjectsPerCell;

	void recursivelyDeleteCells(SPTreeCell* cell);

	void addRecursive(SPTreeCell* cell, RenderableObject* obj);
	void removeRecursive(SPTreeCell* cell, RenderableObject* obj);
	void moveRecursive(SPTreeCell* cell, std::vector<RenderableObject*>& target);
	void split(SPTreeCell* cell);
	void getCollidersRecursive(RenderableObject* obj, std::vector<RenderableObject*>& colliders, SPTreeCell* cell);
};
