#include <irrlicht.h>
#include <iphysics.h>

#pragma comment(lib, "Irrlicht.lib")
#pragma comment(lib, "IPhysics.lib")

int main()
{
	/// Create Irrlicht device
	IrrlichtDevice* device = createDevice(EDT_DIRECT3D9);

	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();

	/// Create physics object;
	CPhysics physics;
	physics.init(device);

	/// Create terrain node from heightmap
	ITerrainSceneNode* terrainNode = smgr->addTerrainSceneNode("../../Media/heightmap.bmp");
	terrainNode->setMaterialTexture(0, driver->getTexture("../../Media/terrain_texture.jpg"));
	terrainNode->setMaterialTexture(1, driver->getTexture("../../Media/terrain_detail.jpg"));
	terrainNode->setMaterialType(EMT_DETAIL_MAP);
	terrainNode->scaleTexture(1.0f, 10.0f);
	terrainNode->setMaterialFlag(EMF_LIGHTING, false);
	
	/// Create SPhysicsSerializedEntity struct
	SPhysicsSerializedEntity terrain;
	terrain.path = "../../Media/serializedTerrain.data8";
	terrain.bodyType = EBT_STATIC;
	terrain.node = terrainNode;
	terrain.scale = vector3df(20.0f, 2.0f, 20.0f);
	
	/// Create terrain from serialized data
	IPhysicsEntity* terrainEntity = physics.addEntity(&terrain);

	/// If there is no serialized terrain file then create a
	//! new serialized terrain.
	if (terrainEntity == NULL)
	{
		cout << "Serializing terrain" << endl;

		/// Remove the scene node created while making the 
		//! serialized terrain scene node.
		terrainNode->remove();

		/// Create terrain from heightmap
		terrainNode = smgr->addTerrainSceneNode("../../Media/heightmap.bmp");
		terrainNode->setMaterialTexture(0, driver->getTexture("../../Media/terrain_texture.jpg"));
		terrainNode->setMaterialTexture(1, driver->getTexture("../../Media/terrain_detail.jpg"));
		terrainNode->setMaterialType(EMT_DETAIL_MAP);
		terrainNode->scaleTexture(1.0f, 10.0f);
		terrainNode->setMaterialFlag(EMF_LIGHTING, false);

		/// Create SPhysicsTerrain
		SPhysicsTerrain terrain;
		terrain.node = terrainNode;
		terrain.scale = vector3df(20.0f, 2.0f, 20.0f);

		/// Create terrain entity
		IPhysicsEntity* terrainEntity = physics.addEntity(&terrain);

		/// Serialize terrain entity
		terrainEntity->serialize("../../Media/serializedTerrain.data");
	}
	else
		cout << "Serialized terrain loaded" << endl;
	
	/// Add irrlicht FPS Camera
	smgr->addCameraSceneNodeFPS();

	while (device->run())
	{
		driver->beginScene(true, true, SColor(255,0,0,0));

		smgr->drawAll();

		physics.update();

		driver->endScene();
	}

	physics.close();

	return 0;
}