// This file is part of ThriceBall.
//
// Author: Kai Hillenbrand (AnTeevY)
// © Copyright, 2009 by Kai Hillenbrand, http://www.anteevy.de

// --------------------------------------------------

#include "drainer.h"

CDrainer::CDrainer(CRenderer *renderer, CLevel *level, NxOgre::Scene *scene, OGRE3DRenderSystem *rendersys)
	: m_pRenderer(renderer), m_pLevel(level), m_pScene(scene), m_pRenderSystem(rendersys), m_fAmount(0),
	m_fXPos(0), m_fYPos(0), m_fZPos(0)
{
	m_pSceneMgr = m_pRenderer->getSceneManager();
	m_pPlayer = m_pRenderer->getPlayer();
}

void CDrainer::create(float x, float y, float z, float amount, float sizeX, float sizeZ)
{
	// apply the variables
	m_fXPos = x;
	m_fYPos = y;
	m_fZPos = z;
	m_fAmount = amount;
	m_fSizeX = sizeX;
	m_fSizeZ = sizeZ;
	
	// avoid twice the same entity name
	String entName = "";
	bool entExists = true;

	while (entExists)
	{
		entName = "Drainer_" + StringConverter::toString(Ogre::Math::RangeRandom(0,10000));
		entExists = m_pSceneMgr->hasEntity(entName);
	}	

	// create the visible mesh
	Ogre::Entity* triangleEntity = m_pSceneMgr->createEntity(entName, "drainer.mesh");
	triangleEntity->setCastShadows(m_pRenderer->shadowsEnabled());
	triangleEntity->setMaterialName("lila");
	Ogre::SceneNode* triangleNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
	triangleNode->attachObject(triangleEntity);
	triangleNode->setPosition(Vector3(m_fXPos, m_fYPos, m_fZPos));
	triangleNode->scale(m_fSizeX / 4, 1, m_fSizeZ / 4);

	setupVolume();	// sets up volume and trigger
}

void CDrainer::setupVolume()
{
	m_pVolume = m_pScene->createVolume(new NxOgre::Box(NxOgre::Vec3(m_fSizeX, 0.1, m_fSizeZ)), 
		NxOgre::Matrix44(NxOgre::Real3(m_fXPos, m_fYPos, m_fZPos)),	this, NxOgre::Enums::VolumeCollisionType_All);
}

void CDrainer::onVolumeEvent(NxOgre::Volume* volume, NxOgre::Shape* volumeShape, NxOgre::RigidBody* rigidBody, 
		NxOgre::Shape* rigidBodyShape, unsigned int collisionEvent)
{
	NxOgre::Actor* actor = static_cast<NxOgre::Actor*>(rigidBody);

	if ((volume == m_pVolume) && (actor == m_pPlayer->getCurBall()))
	{
		// reduce energy while in the drain volume
		if(collisionEvent == NxOgre::Enums::VolumeCollisionType_OnPresence)
		{
			m_pPlayer->reduceEnergy(m_fAmount);
			m_pRenderer->getAudio()->playSound(5);	// play drain sound
		}
	}
}
