#include "SM_CommonFXPCH.h"
#include "SM_DemoEffect.h"
#include "SM_MaxScene.h"
#include "SM_Main.h"
#include "MSystemFunctions.h"
#include "SM_Engine3DPCH.h"
#include "FX3DFont.h"



Font3DFx::Font3DFx(char const* pcName) : SM_DemoEffect(pcName)
{
  m_bLoaded        =false;
  m_uBufferedOffset=0;
  m_fLineSeparation=10.0f;
}

Font3DFx::~Font3DFx()
{
  Shutdown();
}

  
int      Font3DFx::LoadChars()
{
  char pcChar[2];

  pcChar[1]=0;

  int i;

  for (i=0 ; i<256 ; i++)
  {
    pcChar[0]=char(i);

    D3DMesh* pMesh=m_Font.GetMesh(pcChar);
    m_Glyphs[i].m_pGeometry=m_Font.GetGeometry(pcChar);

    if (pMesh && m_Glyphs[i].m_pGeometry)
    {  
      m_Glyphs[i].m_pGeometry->PreTransform(&pMesh->m_Position, &pMesh->m_Quaternion);
      m_Glyphs[i].m_pGeometry->AABB(&m_Glyphs[i].m_AABB);
    }

  }

  return 0;
}

int      Font3DFx::LoadFont(const char* pcToken)
{
  char pcPath[256];
  MVFSFILE* pFile=0;
  char* pcCopy =0;
  int iReturn=0;



  strcpy(pcPath, "data/scenes/");
  strcat(pcPath, pcToken);    

  char pcCompiledName[_MAX_PATH];
  char pcBaseName[_MAX_PATH];
  MExtractBasename(pcBaseName, pcPath);

  strcpy(pcCompiledName,  "data/scenesbin/");
  strcat(pcCompiledName, pcBaseName);
  strcat(pcCompiledName, ".3PX");

  

  #ifdef MAXSCENE_IMPORTER  
  if ( !(pFile=MVFS::fopen(pcCompiledName, "rb")) )
  {
    pFile=MVFS::fopen(pcCompiledName, "wb");
  
    if (m_Font.CompileML(pcPath, pFile)!=0)
    {
      goto EXIT;
    }        
  }
  MVFS::fclose(pFile);    
  #endif

  pFile=MVFS::fopen(pcCompiledName, "rb");
  if (!pFile || m_Font.LoadBin(pFile)!=0)
  {
    iReturn=-1;
    MVFS::unlink(pcCompiledName);
    goto EXIT;
  }
  MVFS::fclose(pFile);            
  pFile=0;

  m_bLoaded=true;

  EXIT:
  if (pFile)  { MVFS::fclose(pFile); pFile=0; }
  if (pcCopy) { delete[] pcCopy; pcCopy=0; }
  return iReturn;
}


int      Font3DFx::Init(const char* pcCommand)
{
  return (0);
}

int      Font3DFx::Shutdown()
{
  m_bLoaded        =false;
  m_uBufferedOffset=0;

  return (0);
}

int      Font3DFx::Reset()
{
  return (0);
}

int Font3DFx::Start(float fTime)
{
  return 0;
}

int Font3DFx::Stop ()
{
  return 0;
}



int      Font3DFx::Command           (float fTime, const char* pcCommand)
{
  SM_DemoEffect::Command(fTime, pcCommand);

  char* pcToken;

  char* pcAux=new char[strlen(pcCommand)+1];
  strcpy(pcAux, pcCommand);

  pcToken=strtok(pcAux, " \t");
  if (strcmp(pcToken, "LOAD")==0)
  {      
    pcToken=strtok(0, " \t");
    if (LoadFont(pcToken)!=0)
    {
      SM_Main::OutputError("Failed to load font %s", pcToken);
      return -1;
    }

    if (LoadChars()!=0)
    {
      return -1;
    }
  }
  else if (strcmp(pcToken, "SEPARATION")==0)
  {
    pcToken=strtok(0, " \t");
    m_fLineSeparation=(float) atof(pcToken);
  }
     
  
  delete[] pcAux;

  return (0);
} 
 

DEFINE_EFFECT(Font3DFx)

Font3DFx Font00("FONT00");
Font3DFx Font01("FONT01");
Font3DFx Font02("FONT02");
Font3DFx Font03("FONT03");
