#define NO_SDL_GLEXT

#include <GL/glew.h>
#include <SDL/SDL_OpenGL.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <math.h>

#include "demo_script.h"
#include "demo_textures.h"
#include "demo_shaders.h"
#include "demo_screen.h"

#include "part_bump.h"

GLuint bmpTexture;
GLuint lgtTexture;

bool bump_init = false;

GLint bp_posx;
GLint bp_posy;
GLint bp_htex;
GLint bp_ltex;

int programm2 = PR_BUMP;

void bump_precalcs()
{
	bmpTexture = GenTexture(512, 512, GEN_BUMP, 2);
	lgtTexture = GenTexture(256, 256, GEN_LIGHT, 2);

	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

	bp_posx = MyGetUniformLocation(programm2, "lx");
	bp_posy = MyGetUniformLocation(programm2, "ly");
	bp_htex = MyGetUniformLocation(programm2, "htex");
	bp_ltex = MyGetUniformLocation(programm2, "ltex");

    bump_init = true;
}

void DrawQuad2(float l)
{
	glBegin(GL_QUADS);
		glTexCoord2f(0.0f, 0.0f); glVertex2f(-l, -l);
		glTexCoord2f(1.0f, 0.0f); glVertex2f( l, -l);
		glTexCoord2f(1.0f, 1.0f); glVertex2f( l, l);
		glTexCoord2f(0.0f, 1.0f); glVertex2f(-l, l);
	glEnd();
}

void DrawBump(int ptime)
{
	float plx = (float)(sin(ptime / 1215.0f) * 0.45);
	float ply = (float)(sin(ptime / 1789.0f) * 0.35);

	MyUseProgram(programm2);
	MyUniform1f(bp_posx, plx);
	MyUniform1f(bp_posy, ply);
	MyUniform1i(bp_htex, 0);
	MyUniform1i(bp_ltex, 1);

	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);
	glEnable(GL_TEXTURE_2D);

	glActiveTextureARB(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, bmpTexture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	glActiveTextureARB(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, lgtTexture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	glLoadIdentity();
	glTranslatef(0.0f, 0.0f, -2.4f * 16.0f);
	DrawQuad2(16.0f);
}

void bump_run(int ptime)
{
	if (!bump_init) bump_precalcs();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	DrawBump(ptime);
}
