/**
 * Copyright (C) 2016  Alexander Schmidt
 *
 * This file is part of Seamulator.
 *
 * Seamulator is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Seamulator is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Seamulator.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "watersurface.h"

#include <GL/glut.h>

WaterSurface::WaterSurface(int size, double extend) :
  m_size{size},
  m_extend{extend}
{
  m_points.resize(size*size);
}

SurfacePoint& WaterSurface::at(int x, int y)
{
  return m_points.at(x + m_size*y);
}

const SurfacePoint& WaterSurface::at(int x, int y) const
{
  return m_points.at(x + m_size*y);
}

int WaterSurface::size() const
{
  return m_size;
}

double WaterSurface::extend() const
{
  return m_extend;
}

void WaterSurface::draw() const
{
  const double scaleFactor{m_extend / m_size};

  glScalef(scaleFactor, scaleFactor, 1.0f);
  glTranslatef(-(float)(m_size - 1) / 2, -(float)(m_size - 1) / 2, 0);

  for (int y = 0; y < m_size - 1; ++y) {
    for (int x = 0; x < m_size - 1; ++x) {
      drawSingleTile(x, y);
    }
  }
}

void WaterSurface::drawSingleTile(int x, int y) const
{
  glBegin(GL_TRIANGLES);

  glVertex3f(x, y, at(x, y).getHeight());
  glVertex3f(x+1, y, at(x+1, y).getHeight());
  glVertex3f(x+1, y+1, at(x+1, y+1).getHeight());

  glVertex3f(x, y, at(x, y).getHeight());
  glVertex3f(x, y+1, at(x, y+1).getHeight());
  glVertex3f(x+1, y+1, at(x+1, y+1).getHeight());

  glEnd();
}
