/*-------------------------------------------------------------------------------------
Copyright (c) 2006 John Judnich

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
	1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
	2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
	3. This notice may not be removed or altered from any source distribution.
-------------------------------------------------------------------------------------*/

/// \file BatchPageHw.cpp
/// \brief BatchPageHw is an extension to PagedGeometry which displays entities as hardware instanced geometry.
//-------------------------------------------------------------------------------------

#include <OgreRoot.h>
#include <OgreCamera.h>
#include <OgreVector3.h>
#include <OgreQuaternion.h>
#include <OgreEntity.h>
#include <OgreRenderSystem.h>
#include <OgreRenderSystemCapabilities.h>
#include <OgreHighLevelGpuProgram.h>
#include <OgreHighLevelGpuProgramManager.h>
#include <OgreLogManager.h>
#include <OgreTechnique.h>
#include <OgrePass.h>
#include "BatchPageHw.h"
#include "BatchedGeometryHw.h"


using namespace Ogre;
using namespace Forests;



unsigned long BatchPageHw::s_nRefCount = 0;
unsigned long BatchPageHw::s_nGUID = 0;
Ogre::String BatchPageHw::s_CustomPSName = "";
Ogre::String BatchPageHw::s_CustomVSName = "";

//-----------------------------------------------------------------------------
/// Default constructor
BatchPageHw::BatchPageHw() :
m_pPagedGeom         (NULL),
m_pSceneMgr          (NULL),
m_pBatchGeom         (NULL),
m_nLODLevel          (0),
m_bFadeEnabled       (false),
m_bShadersSupported  (false),
m_fVisibleDist       (Ogre::Real(0.)),
m_fInvisibleDist     (Ogre::Real(0.))
{}
void BatchPageHw::setCustomShadersNames(const Ogre::String & vsName,const Ogre::String & psName)
{
	s_CustomPSName=psName;
    s_CustomVSName=vsName;
}
//-----------------------------------------------------------------------------
///
void BatchPageHw::init(PagedGeometry *geom_, const Any &data)
{
	assert(geom_ && "Can any code set null pointer?");

	bool castsShadows = true;
	if (!data.isEmpty())
	{
		Forests::BatchPageHw::Params* params = reinterpret_cast<Forests::BatchPageHw::Params*>(Ogre::any_cast<int>(data));
		if (params)
		{
			m_nLODLevel = params->lod;
			castsShadows = params->shadows;
		}
	}
	
	m_pPagedGeom   = geom_;
	m_pSceneMgr    = m_pPagedGeom->getSceneManager();
    m_pBatchGeom.reset(new BatchedGeometryHw(Id::generateNewId<BatchedGeometryHw>()
        , &m_pSceneMgr->_getEntityMemoryManager(Ogre::SCENE_STATIC)
        , RENDER_QUEUE_MAIN,m_pSceneMgr, m_pPagedGeom->getSceneNode(), castsShadows));
    m_pBatchGeom->setRenderQueueGroup(m_pPagedGeom ? m_pPagedGeom->getRenderQueue() : RENDER_QUEUE_6);

	if (!m_pPagedGeom->getShadersEnabled())
		m_bShadersSupported = false;     // shaders disabled by config
	else
	{
		// determine if shaders available
		const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities();
		
		m_bShadersSupported = caps->hasCapability (RSC_VERTEX_BUFFER_INSTANCE_DATA);
	}

	++s_nRefCount;
}

//-----------------------------------------------------------------------------
///
void BatchPageHw::addEntity(Entity *ent, const Vector3 &position, const Quaternion &rotation,
                          const Vector3 &scale, const Ogre::ColourValue &color)
{
	const size_t numManLod = ent->getNumManualLodLevels();

#ifdef _DEBUG
	//Warns if using LOD batch and entities does not have enough LOD support.
	if (m_nLODLevel > 0 && numManLod < m_nLODLevel)
    {
		Ogre::LogManager::getSingleton().logMessage("BatchPageHw::addEntity: " + ent->getName() +
         " entity has less than " + Ogre::StringConverter::toString(m_nLODLevel) +
         " manual lod level(s). Performance warning.");
    }
#endif

	if (m_nLODLevel == 0 || numManLod == 0)
		m_pBatchGeom->addEntity(ent, position, rotation, scale, color);
	else
	{
		const size_t bestLod = numManLod < m_nLODLevel - 1 ? numManLod : m_nLODLevel - 1;
		Ogre::Entity * lod = ent->getManualLodLevel(bestLod);
		m_pBatchGeom->addEntity(lod, position, rotation, scale, color);
	}
}


//-----------------------------------------------------------------------------
///
void BatchPageHw::build()
{
	m_pBatchGeom->build();
	BatchedGeometryHw::TSubBatchIterator it = m_pBatchGeom->getSubBatchIterator();

	while (it.hasMoreElements())
    {
		BatchedGeometryHw::SubBatchHw *subBatch = it.getNext();
		const MaterialPtr &ptrMat = subBatch->getMaterial();

		//Disable specular unless a custom shader is being used.
		//This is done because the default shader applied by BatchPageHw
		//doesn't support specular, and fixed-function needs to look
		//the same as the shader (for computers with no shader support)
		for (unsigned short t = 0, tCnt = ptrMat->getNumTechniques(); t < tCnt; ++t)
		{
			Technique *tech = ptrMat->getTechnique(t);
			for (unsigned short p = 0, pCnt = tech->getNumPasses(); p < pCnt; ++p)
			{
				Pass *pass = tech->getPass(p);
			
				//if (pass->getVertexProgramName() == "")
				//	pass->setSpecular(0, 0, 0, 1);
				if (!pass->hasVertexProgram())
					pass->setSpecular(0.f, 0.f, 0.f, 1.f);
			}
		}

		//Store the original materials
		m_vecUnfadedMaterials.push_back(subBatch->getMaterial());
	}

	_updateShaders();
}


//-----------------------------------------------------------------------------
///
void BatchPageHw::removeEntities()
{
	m_pBatchGeom->clear();
	m_vecUnfadedMaterials.clear();
	m_bFadeEnabled = false;
}

//-----------------------------------------------------------------------------
///
void BatchPageHw::setVisible(bool visible)
{
	m_pBatchGeom->setVisible(visible);
}


//-----------------------------------------------------------------------------
///
void BatchPageHw::setFade(bool enabled, Real visibleDist, Real invisibleDist)
{
	if (!m_bShadersSupported)
		return;

	//If fade status has changed...
	if (m_bFadeEnabled != enabled)
	{
		m_bFadeEnabled	  = enabled;
		m_fVisibleDist    = visibleDist;
		m_fInvisibleDist  = invisibleDist;
		_updateShaders();
	}
}


//-----------------------------------------------------------------------------
///
void BatchPageHw::_updateShaders()
{
	if (!m_bShadersSupported)
		return;

	unsigned int i = 0;
	BatchedGeometryHw::TSubBatchIterator it = m_pBatchGeom->getSubBatchIterator();
	while (it.hasMoreElements())
	{
		BatchedGeometryHw::SubBatchHw& subBatch = *it.getNext();
		const MaterialPtr& material = m_vecUnfadedMaterials[i++];

		//Check if lighting should be enabled
		bool lightingEnabled = false;
		for (unsigned short t = 0, tCnt = material->getNumTechniques(); t < tCnt; ++t)
		{
			Technique *tech = material->getTechnique(t);
			for (unsigned short p = 0, pCnt = tech->getNumPasses(); p < pCnt; ++p)
			{
				if (tech->getPass(p)->getLightingEnabled())
				{
					lightingEnabled = true;
					break;
				}
			}
			if (lightingEnabled)
				break;
		}
				
		//Compile the CG shader script based on various material / fade options
		Ogre::String vertexProgName = createVertexProgName (lightingEnabled, m_bFadeEnabled, subBatch);
		Ogre::String vertexCasterProgName = createVertexCasterProgName (vertexProgName);
		
		String shaderLanguage = getShaderLanguage();
		
		//If the shader hasn't been created yet, create it
		if (HighLevelGpuProgramManager::getSingleton().getByName (vertexProgName).isNull())
		{
			String vertexProgSource;
			createVertexProgSource (subBatch, lightingEnabled, vertexProgSource);
			loadShader (vertexProgName, shaderLanguage, vertexProgSource);

			if (HighLevelGpuProgramManager::getSingleton().getByName (vertexCasterProgName).isNull())
			{
				String vertexCasterProgSource;
				createVertexCasterProgSource (subBatch, vertexCasterProgSource);
				loadShader (vertexCasterProgName, shaderLanguage, vertexCasterProgSource);

				// debug: log caster source and program name
				//Ogre::LogManager::getSingleton().logMessage ("BatchPageHw::_updateShaders() caster name: " + vertexCasterProgName);
				//Ogre::LogManager::getSingleton().logMessage ("BatchPageHw::_updateShaders() caster source: " + vertexCasterProgSource);
			}

			// debug: log source and program name.
			//Ogre::LogManager::getSingleton().logMessage ("BatchPageHw::_updateShaders() subbatch: " + vertexProgName);
			//Ogre::LogManager::getSingleton().logMessage ("BatchPageHw::_updateShaders() source: " + vertexProgSource);
		}

		//Now that the shader is ready to be applied, apply it
		Ogre::String materialSignature = getMaterialSignature (material, m_bFadeEnabled);

		//Search for the desired material
		MaterialPtr generatedMaterial = MaterialManager::getSingleton().getByName (materialSignature);
		if (generatedMaterial.isNull())
			generatedMaterial = createInstanceMaterial (material, materialSignature, vertexProgName, vertexCasterProgName, lightingEnabled, m_bFadeEnabled, shaderLanguage);
		
		subBatch.setMaterial (generatedMaterial);
	}

}

Ogre::String BatchPageHw::getShaderLanguage()
{
	if (Root::getSingleton().getRenderSystem()->getName() == "Direct3D9 Rendering Subsystem")
		return "hlsl";
	
	return "cg";
}

Ogre::String BatchPageHw::createVertexProgName (bool lightingEnabled, bool fadeEnabled, BatchedGeometryHw::SubBatchHw& subBatch)
{
	StringStream vertexProgName;

	vertexProgName << "BatchPageHw_";
	if (m_bFadeEnabled)
		vertexProgName << "fade_";
	if (lightingEnabled)
		vertexProgName << "lit_";
	if (subBatch.m_pVertexData->vertexDeclaration->findElementBySemantic(VES_DIFFUSE) != NULL)
		vertexProgName << "clr_";

	for (size_t i = 0, iCnt = subBatch.m_pVertexData->vertexDeclaration->getElementCount(); i < iCnt; ++i)
	{
		const VertexElement *el = subBatch.m_pVertexData->vertexDeclaration->getElement(i);
		if (el->getSemantic() == VES_TEXTURE_COORDINATES)
		{
			String uvType;
			switch (el->getType())
			{
			case VET_FLOAT1: uvType = "1"; break;
			case VET_FLOAT2: uvType = "2"; break;
			case VET_FLOAT3: uvType = "3"; break;
			case VET_FLOAT4: uvType = "4"; break;
			}
			vertexProgName << uvType << '_';
		}
	}

	vertexProgName << "vp";

	return vertexProgName.str();
}

Ogre::String BatchPageHw::createVertexCasterProgName (const Ogre::String& vertexProgName)
{
	return vertexProgName + "_ShadowCaster";
}

void BatchPageHw::createVertexProgSource (BatchedGeometryHw::SubBatchHw& subBatch, bool lightingEnabled, Ogre::String& progSource)
{
	progSource =
		"void main( \n"
		"	float4		iPosition : POSITION, \n"
		"	float3		iNormal   : NORMAL,	\n"
		"	out float4	oPosition : POSITION, \n";

	if (subBatch.m_pVertexData->vertexDeclaration->findElementBySemantic(VES_DIFFUSE) != NULL) progSource +=
		"	float4 iColor    : COLOR, \n";

	createTexcoordParams (subBatch, progSource);

	progSource +=
		"	out float oFog : FOG,	\n"
		"	out float4 oColor : COLOR, \n";

	if (lightingEnabled) progSource +=
		"	uniform float4 lightPositionL,	\n"
		"	uniform float4 lightDiffuse,	\n"
		"	uniform float4 lightAmbient,	\n";

	if (m_bFadeEnabled) progSource +=
		"	uniform float3 viewPositionL, \n";

	progSource +=
		"	uniform float4x4 viewProj,	\n"
		"	uniform float fadeGap, \n"
		"   uniform float invisibleDist )\n"
		"{	\n";

	progSource += 
		"float3x4 world;	\n";

	createTexCoordLocals (subBatch, progSource);
	
	// unpack instancing data and build a worldViewProj transform.
	progSource += 
		"float4 positionW	= float4 (mul (world, iPosition).xyz, 1.0f);	\n"
		"float3 normalW		= normalize (mul ((float3x3)world, iNormal));	\n"
		"oPosition			= mul (viewProj, positionW);	\n"
		"oFog				= oPosition.z; \n";
	
	if (lightingEnabled)
	{
		//Perform lighting calculations (no specular)
		progSource +=
			"	float3 light = normalize(lightPositionL.xyz - (iPosition.xyz * lightPositionL.w)); \n"
			"	float diffuseFactor = max (dot (normalW, light), 0); \n";
		if (subBatch.m_pVertexData->vertexDeclaration->findElementBySemantic(VES_DIFFUSE) != NULL)
			progSource += "oColor = (lightAmbient + diffuseFactor * lightDiffuse) * iColor; \n";
		else
			progSource += "oColor = (lightAmbient + diffuseFactor * lightDiffuse); \n";
	}
	else
	{
		if (subBatch.m_pVertexData->vertexDeclaration->findElementBySemantic(VES_DIFFUSE) != NULL)
			progSource += "oColor = iColor; \n";
		else
			progSource += "oColor = float4(1, 1, 1, 1); \n";
	}

	// add in the per instance color
	progSource += "oColor *= instColor; \n";

	if (m_bFadeEnabled) progSource +=
		//Fade out in the distance
		"	float dist = distance (viewPositionL.xz, positionW.xz);	\n"
		"	oColor.a *= (invisibleDist - dist) / fadeGap;   \n";

	progSource += 
		"}";
}

void BatchPageHw::createVertexCasterProgSource (BatchedGeometryHw::SubBatchHw& subBatch, Ogre::String& progSource)
{
	progSource =
		"void main( \n"
		"	float4		iPosition	: POSITION, \n"
		"	out float4	oPosition	: POSITION, \n"
		"	out float4	oColor		: COLOR, \n";

	createTexcoordParams (subBatch, progSource);

	progSource +=
		"	uniform float4x4 viewProj,	\n"
		"	uniform float4 ambient) \n"
		"{	\n";

	progSource += 
		"float3x4 world;	\n";

	createTexCoordLocals (subBatch, progSource);

	// unpack instancing data and build a worldViewProj transform.
	progSource += 
		"float4 positionW	= float4 (mul (world, iPosition).xyz, 1.0f);	\n"
		"oPosition			= mul (viewProj, positionW);	\n"
		"oColor				= ambient; \n"
		"}";
}

void BatchPageHw::createTexCoordLocals (BatchedGeometryHw::SubBatchHw &subBatch, Ogre::String& progSource)
{
	unsigned texNum = 0;
	unsigned worldIndex = 0;

	for (size_t i = 0, iCnt = subBatch.m_pVertexData->vertexDeclaration->getElementCount(); i < iCnt; ++i)
	{
		const VertexElement *el = subBatch.m_pVertexData->vertexDeclaration->getElement(i);
		unsigned short source = el->getSource();
		Ogre::VertexElementSemantic semantic = el->getSemantic();

		if (semantic != VES_TEXTURE_COORDINATES)
			continue;

		if (source == subBatch.instanceSource())
		{
			if (worldIndex < 3)
			{
				progSource += 
					"world[" + StringConverter::toString(worldIndex) + "] = iInst" + StringConverter::toString(texNum) + ";\n";

				++worldIndex;
			}
			else
			{
				progSource +=
					"float4 instColor = iInst" + StringConverter::toString(texNum) + ";\n";
			}
		}
		else 
		{
			progSource += 
				"	oUV" + StringConverter::toString(texNum) + " = iUV" + StringConverter::toString(texNum) + ";	\n";
		}

		++texNum;
	}
}

void BatchPageHw::createTexcoordParams (BatchedGeometryHw::SubBatchHw& subBatch, String& progSource)
{
	unsigned texNum = 0;
	for (unsigned short i = 0; i < subBatch.m_pVertexData->vertexDeclaration->getElementCount(); ++i)
	{
		const VertexElement *el = subBatch.m_pVertexData->vertexDeclaration->getElement(i);
		if (el->getSemantic() == VES_TEXTURE_COORDINATES)
		{
			String uvType;
			switch (el->getType())
			{
				case VET_FLOAT1: uvType = "float"; break;
				case VET_FLOAT2: uvType = "float2"; break;
				case VET_FLOAT3: uvType = "float3"; break;
				case VET_FLOAT4: uvType = "float4"; break;
			}

			unsigned short source = el->getSource();
			if (source == subBatch.instanceSource())
			{
				progSource +=
					"	" + uvType + " iInst" + StringConverter::toString(texNum) + "		: TEXCOORD" + StringConverter::toString(texNum) + ",	\n";
			}
			else
			{
				progSource +=
					"	" + uvType + " iUV" + StringConverter::toString(texNum) + "			: TEXCOORD" + StringConverter::toString(texNum) + ",	\n"
					"	out " + uvType + " oUV" + StringConverter::toString(texNum) + "		: TEXCOORD" + StringConverter::toString(texNum) + ",	\n";
			}

			++texNum;
		}
	}	
}

void BatchPageHw::setVertexShaderConfig (const Ogre::String& shaderLanguage,  Ogre::HighLevelGpuProgramPtr& vertexShader)
{
	if (shaderLanguage == "hlsl")
	{
		vertexShader->setParameter("target", "vs_3_0");
		vertexShader->setParameter("entry_point", "main");
	}
	else // if(shaderLanguage == "cg")
	{
		vertexShader->setParameter("profiles", "vs_3_0 vp40");
		vertexShader->setParameter("entry_point", "main");
	}
}

void BatchPageHw::setVertexShaderParams (bool lightingEnabled, bool fadeEnabled, Ogre::GpuProgramParametersSharedPtr params, const Ogre::String& shaderLanguage, Ogre::Pass* pass)
{
	if (lightingEnabled)
	{
		params->setNamedAutoConstant("lightPositionL", GpuProgramParameters::ACT_LIGHT_POSITION_OBJECT_SPACE);
		params->setNamedAutoConstant("lightDiffuse", GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR);
		params->setNamedAutoConstant("lightAmbient", GpuProgramParameters::ACT_DERIVED_AMBIENT_LIGHT_COLOUR);
		//params->setNamedAutoConstant("matAmbient", GpuProgramParameters::ACT_SURFACE_AMBIENT_COLOUR);
	}

	params->setNamedAutoConstant("viewProj", GpuProgramParameters::ACT_VIEWPROJ_MATRIX);

	if (fadeEnabled)
	{
		params->setNamedAutoConstant("viewPositionL", GpuProgramParameters::ACT_CAMERA_POSITION);

		//Set fade ranges
		params->setNamedAutoConstant("invisibleDist", GpuProgramParameters::ACT_CUSTOM);
		params->setNamedConstant("invisibleDist", m_fInvisibleDist);

		params->setNamedAutoConstant("fadeGap", GpuProgramParameters::ACT_CUSTOM);
		params->setNamedConstant("fadeGap", m_fInvisibleDist - m_fVisibleDist);

		if (pass->getAlphaRejectFunction() == CMPF_ALWAYS_PASS)
			pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	}
}

void BatchPageHw::setVertexCasterShaderParams (Ogre::GpuProgramParametersSharedPtr params)
{
	params->setNamedAutoConstant ("viewProj", GpuProgramParameters::ACT_VIEWPROJ_MATRIX);
	//params->setNamedAutoConstant ("ambient", GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR);
}

Ogre::String BatchPageHw::getMaterialSignature (const MaterialPtr material, bool fadeEnabled)
{
	StringStream materialSignature;
	materialSignature << "BatchMat|";
	materialSignature << material->getName() << "|";

	if (fadeEnabled)
	{
		materialSignature << m_fVisibleDist << "|";
		materialSignature << m_fInvisibleDist << "|";
	}

	return materialSignature.str();
}

Ogre::MaterialPtr BatchPageHw::createInstanceMaterial (const Ogre::MaterialPtr material, const Ogre::String& materialSignature, 
	const Ogre::String& vertexProgName, const Ogre::String& vertexCasterProgName, bool lightingEnabled, bool fadeEnabled, const Ogre::String& shaderLanguage)
{
	//Clone the material
	MaterialPtr generatedMaterial = material->clone (materialSignature);

	//And apply the fade shader
	for (unsigned short t = 0, tCnt = generatedMaterial->getNumTechniques(); t < tCnt; ++t)
	{
		Technique *tech = generatedMaterial->getTechnique(t);
		for (unsigned short p = 0, pCnt = tech->getNumPasses(); p < pCnt; ++p)
		{
			Pass *pass = tech->getPass(p);

            if(s_CustomVSName == "")
            {
			    if (!pass->hasVertexProgram())
			    {
				    pass->setVertexProgram (vertexProgName);
			    }

			    if (!pass->hasShadowCasterVertexProgram())
			    {
				    pass->setShadowCasterVertexProgram (vertexCasterProgName);
			    }

			    if (pass->hasFragmentProgram())
			    {
				    lightingEnabled = false;  // disable lighting if the material has it's own fragment program.
			    }

			    try
			    {
				    GpuProgramParametersSharedPtr params = pass->getVertexProgramParameters();
				    setVertexShaderParams (lightingEnabled, fadeEnabled, params, shaderLanguage, pass);

				    GpuProgramParametersSharedPtr casterParams = pass->getShadowCasterVertexProgramParameters();
				    setVertexCasterShaderParams (casterParams);
			    }
			    catch (Ogre::Exception&)
			    {
				    OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
					    "Error configuring batched geometry transitions. If you're using materials with custom vertex shaders, \
					    they will need to implement fade transitions to be compatible with BatchPageHw.", "BatchPageHw::_updateShaders()");
			    }
            }
            else // user specified programs
            {
                pass->setVertexProgram (s_CustomVSName);
                if(s_CustomPSName!="")
                {
                  pass->setFragmentProgram (s_CustomPSName);
                }
            }
		}
	}	
	
	return generatedMaterial;
}

Ogre::HighLevelGpuProgramPtr BatchPageHw::loadShader (const Ogre::String& progName, const Ogre::String& language, const Ogre::String& source)
{
	HighLevelGpuProgramPtr shader = HighLevelGpuProgramManager::getSingleton().createProgram(
		progName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, language, GPT_VERTEX_PROGRAM);

	shader->setSource (source);
	setVertexShaderConfig (language, shader);
	shader->load();

	return shader;
}
