#include "Maze.h"
#include "Player.h"

#include "../vsgl3/LiteMath.h"

Maze2D::Maze2D(int a_sizeX, int a_sizeY)
{
  if (a_sizeX < 2 || a_sizeY < 2)
   RUN_TIME_ERROR("Maze2D, sizxe must be gt 2x2");

  if (a_sizeX != a_sizeY)
    RUN_TIME_ERROR("Maze2D, size must be square for current (a_sizeX == a_sizeY)");

  m_sizeX = a_sizeX;
  m_sizeY = a_sizeY;

  // graphics crap
  //
  {
    float scale   = float(a_sizeX);
    float texMult = float(a_sizeX) / 2.0f;

    m_pMazePlaneGraphics = CreateMazeGraphics(scale, texMult);

    m_cellSize = 2.0f*scale;
    m_zeroPos  = float3(0, 0, 0) - 0.5f*m_cellSize*float3(float(m_sizeX-1), 0.0f, float(m_sizeY-1));
  }

  //
  //

  m_objects.resize(0);
  m_objects.push_back(new Player(4, 4));
  m_pPlayer = m_objects[0];
}

Maze2D::~Maze2D()
{
  for (size_t i = 0; i < m_objects.size(); i++)
  {
    delete m_objects[i];
    m_objects[i] = NULL;
  }

  delete m_pMazePlaneGraphics; m_pMazePlaneGraphics = NULL;
}


std::vector<IGraphicsObject*> Maze2D::getDrawList()
{
  std::vector<IGraphicsObject*> res; res.reserve(m_objects.size()+1);
  std::vector<float3>           translatePos; translatePos.reserve(m_objects.size());

  for (size_t i = 0; i < m_objects.size(); i++)
  {
    const std::vector<IGraphicsObject*>& dump = m_objects[i]->getDrawList();
    res.insert(res.end(), dump.begin(), dump.end());

    float3 tPos(float(m_objects[i]->posX), float(m_objects[i]->posZ), float(m_objects[i]->posY));
    for (size_t j = 0; j < dump.size(); j++)
      translatePos.push_back(tPos);
  }

  // translate all objects to world space according their positions on Maze
  //

  for (size_t i = 0; i < res.size(); i++)
  {
    float3 tPos = translatePos[i];
    float3 wPos = m_zeroPos + (m_cellSize*(tPos + float3(0.0f, 0.0f, 0.0f)));

    res[i]->translate(wPos);
  }

  res.push_back(m_pMazePlaneGraphics);

  return res;
}

