#include "CityBlocks.h"
#include "CodingUtils.h"

const float CityBlocks::FLOOR_HEIGHT = 0.001f;

CityBlocks::CityBlocks(scene::ISceneNode* parent, scene::ISceneManager* mgr, s32 id)
	: scene::ISceneNode(parent, mgr, id)
{
	//Define material properties
	m_material.Wireframe = false;
	m_material.Lighting = false;
	m_material.setTexture(0, SceneManager->getVideoDriver()->getTexture("./assets/streetpatch.png"));
	m_material.setFlag(video::EMF_ANISOTROPIC_FILTER, true);

	//Geometry
	const float positions[] = {
		0, 0,
		64*CodingUtils::BLOCKS_COUNT, 0,
		64*CodingUtils::BLOCKS_COUNT, 64*CodingUtils::BLOCKS_COUNT,
		0, 64*CodingUtils::BLOCKS_COUNT,
	};
	const float uvs[] = {
		0, 0,
		CodingUtils::BLOCKS_COUNT, 0,
		CodingUtils::BLOCKS_COUNT, CodingUtils::BLOCKS_COUNT,
		0, CodingUtils::BLOCKS_COUNT,
	};
	const video::SColor colorWhite(255,255,255,255);
	unsigned int vertexIndex = 0;

	//Vertices
	for (unsigned int j = 0; j<4; j++) 
	{
		unsigned int posIndex = j*2;
		m_vertices[vertexIndex++] = video::S3DVertex(
			positions[posIndex], FLOOR_HEIGHT, positions[posIndex+1],
			0,1,0,
			colorWhite,	
			uvs[posIndex],uvs[posIndex+1]);
	}
	//Indices
	u32 indexIndex = 0;
	m_indices[indexIndex++] = 2; //Triangle 1
	m_indices[indexIndex++] = 1;
	m_indices[indexIndex++] = 0;
	m_indices[indexIndex++] = 2; //Triangle 2
	m_indices[indexIndex++] = 0;
	m_indices[indexIndex++] = 3;

	//Initialize bounding box
	m_box.reset(m_vertices[0].Pos);
	for (s32 i=1; i<4; ++i) {
		m_box.addInternalPoint(m_vertices[i].Pos);
	}
}

CityBlocks::~CityBlocks()
{
}

void CityBlocks::OnRegisterSceneNode()
{
	if (IsVisible)
		SceneManager->registerNodeForRendering(this);

	ISceneNode::OnRegisterSceneNode();
}

void CityBlocks::render()
{
	video::IVideoDriver* driver = SceneManager->getVideoDriver();

	driver->setMaterial(m_material);
	driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
	driver->drawVertexPrimitiveList(&m_vertices[0], VERTEX_COUNT, &m_indices[0], PRIMITIVE_COUNT,
		video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT);
}