#include "CPhysicsWater.h"

const NewtonBody* CPhysicsWater::m_waterBody;

void CPhysicsWater::init(NewtonWorld* world, IrrlichtDevice* device)
{
	m_world = world;
	m_device = device;

	int m_waterMaterial = NewtonMaterialCreateGroupID(m_world);

	// set water to metal material property
	NewtonMaterialSetCollisionCallback (m_world, m_waterMaterial, m_waterMaterial, NULL, WaterBeginContact, NULL, NULL);

	// create the water volume
	NewtonCollision* waterCollisionVolume;
	// I found the size and position by trial and error (about 20 try) 
	waterCollisionVolume = NewtonCreateBox(m_world, 400.0f  * IrrToNewton, 80.0f * IrrToNewton, 240.0f * IrrToNewton, NULL);
	m_waterBody = NewtonCreateBody(m_world, waterCollisionVolume);
	NewtonReleaseCollision (m_world, waterCollisionVolume);

	matrix4 mat;
	mat.setTranslation(vector3df (40.0f, -30.0f, 60.0f) * IrrToNewton);
	NewtonBodySetMatrix (m_waterBody, mat.pointer()); // Irrlicht 1.3

	// the box is metal
	NewtonBodySetMaterialGroupID (m_waterBody, m_waterMaterial);
}

int CPhysicsWater::WaterBeginContact (const NewtonMaterial* material, const NewtonBody* body0, const NewtonBody* body1)
{
	float mass; 
	float Ixx; 
	float Iyy; 
	float Izz; 
	const NewtonBody* body;
	const NewtonBody* volumeBody;

	body = body0;
	volumeBody = body1;

	// the body with zero mass is the water volume
	NewtonBodyGetMassMatrix (body1, &mass, &Ixx, &Iyy, &Izz); 
	if (mass > 0.0f) 
	{
		body = body1;
		volumeBody = body0;
	}

	CPhysicsEntity* entity = (CPhysicsEntity*)NewtonBodyGetUserData(volumeBody);

	// save this water volume with the body
	if (entity)
		entity->waterBody = volumeBody;

	// reject this collsion pair
	return 0;
}
