#include "../include/zf.h"

#define SPEED 0.002f

static CLtexture* texture;
static GLdouble   clip_plane[4];
static float offset;
static float water_level;
static float map_width, map_length;
static float map_width_2, map_length_2;

static void 
initClipPlane(void)
{
  GLint n;

  glGetIntegerv(GL_MAX_CLIP_PLANES, &n);

  if (n < 1)
  {
      printf("need at least one opengl clip plane\n");
      exit(1);
  }

  clip_plane[0] = 0.0f;
  clip_plane[1] = -1.0f;
  clip_plane[2] = 0.0f;
  clip_plane[3] = water_level;

  glClipPlane(GL_CLIP_PLANE0, clip_plane);
}


void 
zf_water_init(float water, float width, float length)
{
    water_level = water;
    map_width = width;
    map_width_2 = width/2.0f;
    map_length = length;
    map_length_2 = length/2.0f;

    initClipPlane();

    if (!(texture = clioLoadTexture("../data/textures/water.png")))
    {
	printf("could not load water texture\n");
	exit(1);
    }
    
    clUpdateTexture(texture);
    
    offset = 0.0f;


}

void 
zf_water_close(void)
{
  clDeleteTexture(texture);
}

/* not sure what this does yet. leave it as it is*/
void gmStepWater(float dt)
{
  offset += SPEED * dt;
}

/* This does not go into the render system - needs to be treated specially*/
void 
zf_water_render(void)
{
    glMatrixMode(GL_TEXTURE);
    glPushMatrix();
    glLoadIdentity();
    glScalef(32.0f, 32.0f, 1.0f);
    glTranslatef(offset, 0.0f, 0.0f);
    
    glMatrixMode(GL_MODELVIEW);
    clLoadTexture(texture);
    glEnable(GL_TEXTURE_2D);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    
    glColor4f(0.3f, 0.5f, 0.6f, 0.6f);
    glBegin(GL_QUADS);
    glNormal3f(0.0f, 1.0f, 0.0f);
    glTexCoord2f(0.0f, .0f); 
    glVertex3f(-map_width, water_level, -map_length);
    glTexCoord2f(0.0f, 1.0f); 
    glVertex3f(-map_width, water_level, map_length);
    glTexCoord2f(1.0f, 1.0f); 
    glVertex3f(map_width, water_level, map_length);
    glTexCoord2f(1.0f, 0.0f); 
    glVertex3f(map_width, water_level, -map_length);
    glEnd();
    
    glDisable(GL_TEXTURE_2D);
    
    glMatrixMode(GL_TEXTURE);
    glPopMatrix();
    
    glMatrixMode(GL_MODELVIEW);
}

void 
zf_water_render_quad(void)
{
    glBegin(GL_QUADS);
    glVertex3f(-map_width, water_level, -map_length);
    glVertex3f(-map_width, water_level, map_length);
    glVertex3f(map_width, water_level, map_length);
    glVertex3f(map_width, water_level, -map_length);
    glEnd();
}

void 
zf_water_load_clip_plane(void)
{
    glClipPlane(GL_CLIP_PLANE0, clip_plane);
}

float
zf_water_query_level(void)
{
    return water_level;
}
