#include "CFadeMaterial .h"



void CFadeMaterial::OnSetConstants(video::IMaterialRendererServices* services, s32 userData)
{
   video::IVideoDriver* driver = services->getVideoDriver();

   // World/View/Projection matrix
   core::matrix4 worldViewProj;
   worldViewProj = driver->getTransform(video::ETS_PROJECTION);
   worldViewProj *= driver->getTransform(video::ETS_VIEW);
   worldViewProj *= driver->getTransform(video::ETS_WORLD);
   services->setVertexShaderConstant("mWorldViewProj", &worldViewProj[0], 16);

   services->setPixelShaderConstant("fadeFactor", &m_fadeFactor, 1);
};

bool CFadeMaterial::init(ISceneManager* smgr, IVideoDriver* driver)
{
   if (!smgr || ! driver)
      return false;

   video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices();
   if (!gpu) return false;

   video::E_DRIVER_TYPE edt = driver->getDriverType();

    c8* hlsl_shader =
"uniform float4x4 mWorldViewProj;"
"uniform float fadeFactor;"
"sampler2D diffuseTexture : register(s0);"
" "
"struct VS_OUT {"
"   float4 Pos : POSITION;"
"   float2 TexCoord0 : TEXCOORD0;"
"};"
" "
"VS_OUT vertexMain(float3 Pos : POSITION, float2 Tex0 : TEXCOORD0)"
"{"
"   VS_OUT o = (VS_OUT)0;"
"   o.Pos = mul(float4(Pos,1), mWorldViewProj);"
"   o.TexCoord0 = Tex0;"
"   return o;"
"}"
""
    "float4 pixelMain(VS_OUT i) : COLOR"
    "{"
   "float4 gl_FragColor;"
   "gl_FragColor.rgb = tex2D(diffuseTexture, i.TexCoord0.xy);"
   "gl_FragColor.a = fadeFactor;"
    "return gl_FragColor;"
    "  } ";




   if (edt == video::EDT_OPENGL) {
/*
      m_fadeMaterial = gpu->addHighLevelShaderMaterialFromFiles(
         "fademesh.vp", "main", video::EVST_VS_1_1,
         "fademesh.fp", "main", video::EPST_PS_1_1,
         this, video::EMT_TRANSPARENT_ALPHA_CHANNEL);
*/
   } else if (edt == video::EDT_DIRECT3D9) {

       printf("%s\n",hlsl_shader);
      m_fadeMaterial = gpu->addHighLevelShaderMaterial(
         hlsl_shader, "vertexMain", video::EVST_VS_1_1,
         hlsl_shader, "pixelMain", video::EPST_PS_1_1,
         this, video::EMT_TRANSPARENT_ALPHA_CHANNEL);
   } else {
      m_fadeMaterial = video::EMT_SOLID;
   }

   return true;
}
