#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <math.h>
#include "globals.h"
#include "waves.h"
#include "system.h"
#include "objgen.h"


void init_Twirler ()
{
	glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
	glEnable (GL_BLEND);
	glEnable (GL_TEXTURE_2D);
	glEnable (GL_TEXTURE_GEN_S);
	glEnable (GL_TEXTURE_GEN_T);
	glFogf (GL_FOG_START, 200.0);
	glFogf (GL_FOG_END, 400.0);

	GLfloat fogCol[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
	glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
	glFogfv (GL_FOG_COLOR, fogCol);
	cam.directional = false;
	cam.pos[0] = 0;
	cam.pos[1] = 0;
	cam.pos[2] = 100;
	cam.tgt[0] = 0;
	cam.tgt[1] = 0;
	cam.tgt[2] = 0;
	fov = 100;
	genCube (*cube);
	cube->pX = cube->pY = cube->pZ = 0;
}

void drawTwirlCubes ()
{
	static GLfloat rot[3][8][3];
	static GLfloat crot[3];
	static double transferTime = 0, pulseTime = 0;
	static double lastTime;
	double delta;
	int i, j;

	if (transferTime == 0)
	{
		crot[0] = crot[1] = crot[2] = 0;
		memset (rot, 0, sizeof(rot));
		transferTime = time + 0.03;
		pulseTime = time + 1.0;
		lastTime = time;
	}

	delta = time - lastTime;

	if (time > transferTime)
	{
		for (i = 7; i > 0; i--)
		{
			for (j = 0; j < 3; j++)
			{
				rot[j][i][0] = rot[j][i-1][0];
				rot[j][i][1] = rot[j][i-1][1];
				rot[j][i][2] = rot[j][i-1][2];
			}
		}
		
		rot[0][0][0] = crot[0]*3;		rot[0][0][1] = crot[1]*3;		rot[0][0][2] = crot[2]*3;
		rot[1][0][0] = crot[0]*3;		rot[1][0][1] = crot[1]*3;		rot[1][0][2] = crot[2]*3;
		rot[2][0][0] = crot[0]*3;		rot[2][0][1] = crot[1]*3;		rot[2][0][2] = crot[2]*3;
		transferTime += 0.03;
	}

	if (time > pulseTime)
	{

		pulseTime += 1.0;
	}

	crot[0] += (GLfloat)(75 * delta);
	crot[1] += (GLfloat)(65 * delta);
	crot[2] += (GLfloat)(85 * delta);

	for (int r = 1; r < 5; r++)
	{
		for (j = 0; j < 3; j++)
		{
			glPushMatrix ();
				glRotatef (rot[j][r-1][0], 1, 0, 0);
				glRotatef (rot[j][r-1][1], 0, 1, 0);
				glRotatef (rot[j][r-1][2], 0, 0, 1);
				if (j == 0)
					glTranslatef ((GLfloat)(15.0f * r), 0, 0);
				else if (j == 1)
					glTranslatef (0, (GLfloat)(15.0f * r), 0);
				else
					glTranslatef (0, 0, (GLfloat)(15.0f * r));
				glScalef (1.0f/(GLfloat)(5-r), 1.0f/(GLfloat)(5-r), 1.0f/(GLfloat)(5-r));
				cube->render ();
			glPopMatrix ();
			glPushMatrix ();
				glRotatef (rot[j][r-1][0], 1, 0, 0);
				glRotatef (rot[j][r-1][1], 0, 1, 0);
				glRotatef (rot[j][r-1][2], 0, 0, 1);
				if (j == 0)
					glTranslatef ((GLfloat)(-15.0f * r), 0, 0);
				else if (j == 1)
					glTranslatef (0, (GLfloat)(-15.0f * r), 0);
				else
					glTranslatef (0, 0, (GLfloat)(-15.0f * r));
				glScalef (1.0f/(GLfloat)(5-r), 1.0f/(GLfloat)(5-r), 1.0f/(GLfloat)(5-r));
				cube->render ();
			glPopMatrix ();
		}
	}
	lastTime = time;
}

void part_Twirler ()
{
	SetProjection ();

	glRotatef (-45.0f, 0.4f, 1.0f, 0);
	glCullFace (GL_FRONT);
	drawTwirlCubes ();
	glCullFace (GL_BACK);
	drawTwirlCubes ();
}