#include "SM_Engine3DPCH.h"
#include "SM_ScalarSequence.h"

ScalarSequence::ScalarSequence()
{
  m_uScalars    =0;  
  m_pScalars    =0;
  m_uSamplingRate =0;
}

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

int ScalarSequence::Init()
{
  return (0);
}

int ScalarSequence::Shutdown()
{
  m_uScalars=0;
  if (m_pScalars) { delete[] m_pScalars; m_pScalars=0; }
  m_uSamplingRate =0;

  return (0);
}

float*  ScalarSequence::GetScalar(float fTime, float fStartTime, float* pScalar)
{
  float fFrame=(fTime-fStartTime)*(float)m_uSamplingRate;

  int iFrameA=((int)floorf(fFrame))%m_uScalars;
  int iFrameB=(iFrameA+1)%m_uScalars;
  float fLerp=fFrame-floorf(fFrame);

  assert(iFrameA>=0    && iFrameA<m_uScalars);
  assert(iFrameB>=0    && iFrameB<m_uScalars);
  assert(fLerp>=0.0f && fLerp<=1.0f);

  if (iFrameA==0)
  {
   // assert(0);
  }

  *pScalar=m_pScalars[iFrameA]*(1.0f-fLerp)+m_pScalars[iFrameB]*(fLerp);
  
  return (pScalar);
}

int ScalarSequence::Load(MVFSFILE* f)
{
  if (MVFS::fread(&m_uScalars, sizeof(unsigned), 1, f)!=1) return -1;
  if (MVFS::fread(&m_uSamplingRate, sizeof(unsigned), 1, f)!=1) return -1;

  m_pScalars=new float[m_uScalars];
  if (!m_pScalars)
  {
    return -1;
  }

  if (MVFS::fread(m_pScalars, sizeof(float)*m_uScalars, 1, f)!=1) return -1;


  return 0;
}

int ScalarSequence::Save(MVFSFILE* f)
{
  if (MVFS::fwrite(&m_uScalars, sizeof(unsigned), 1, f)!=1) return -1;
  if (MVFS::fwrite(&m_uSamplingRate, sizeof(unsigned), 1, f)!=1) return -1;
  if (MVFS::fwrite(m_pScalars, sizeof(float)*m_uScalars, 1, f)!=1) return -1;

  return 0;
}

