
#include "stdAfx.h"
#include <windows.h>		// Header File For Windows
#include <stdlib.h>
#include <stdio.h>			// Header File For Standard Input/Output

#include "resource.h"

#include "initializer.h"


using namespace std;



LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

string intToString(int num)
{
	int x=1000000;
	int dig = 0;
	bool notZero = false;
	string mot="";
	while(x > 0)
	{
		dig = num%x;
		if(dig == 0 && notZero) mot=mot+"0";
		else if(dig == 1)
		{
			mot=mot+"1";
			notZero = true;
		}
		else if(dig == 2)
		{
			mot=mot+"2";
			notZero = true;
		}
		else if(dig == 3)
		{
			mot=mot+"3";
			notZero = true;
		}
		else if(dig == 4)
		{
			mot=mot+"4";
			notZero = true;
		}
		else if(dig == 5)
		{
			mot=mot+"5";
			notZero = true;
		}
		else if(dig == 6)
		{
			mot=mot+"6";
			notZero = true;
		}
		else if(dig == 7)
		{
			mot=mot+"7";
			notZero = true;
		}
		else if(dig == 8)
		{
			mot=mot+"8";
			notZero = true;
		}
		else if(dig == 9)
		{
			mot=mot+"9";
			notZero = true;
		}
		//MessageBox(NULL,mot.c_str(),"ERROR",MB_OK|MB_ICONEXCLAMATION);
		x/=10;
	}
	return mot;
}

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window
{

	if (width > height)										// Prevent A Divide By Zero By
	{	
		
	  glViewport(0,0,width,width);						// Reset The Current Viewport						// Making Height Equal One
	}
    else
	{
		glViewport(0,0,height,height);
	}

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); 
	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix
}

int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{
	if (!LoadGLTextures())								// Jump To Texture Loading Routine
	{
		return FALSE;									// If Texture Didn't Load Return FALSE
	}

	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.05f, 0.05f, 0.05f, 0.0f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations

	glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient);		// Setup The Ambient Light
	glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse);		// Setup The Diffuse Light
	glLightfv(GL_LIGHT1, GL_POSITION,LightPosition);	// Position The Light
	glEnable(GL_LIGHT1);								// Enable Light One
	//glEnable(GL_LIGHTING);


	glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); // Set The Texture Generation Mode For S To Sphere Mapping (NEW)
	glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); // Set The Texture Generation Mode For T To Sphere Mapping (NEW)

	BuildFont();

	return TRUE;										// Initialization Went OK
}


GLvoid glDrawCube(char tex1,char tex2,char tex3,char tex4,GLfloat x,GLfloat y,GLfloat z,GLfloat r)
{
	glPushMatrix();
		glTranslatef(x, y, z);
		glRotatef(r,1.0f,0.0f,0.0f);
		glScalef(0.07f,0.07f,0.07f);
		// Front Face
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, texture[charToInt(tex1)]);
			glBegin(GL_QUADS);	
				//glNormal3f( 0.0f, 0.0f, 0.5f);
				glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
				glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
				glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
				glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
			glEnd();
		glDisable(GL_TEXTURE_2D);

		// Top Face
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, texture[charToInt(tex2)]);
			glBegin(GL_QUADS);
				//glNormal3f( 0.0f, 0.5f, 0.0f);
				glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
				glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
				glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
				glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);
			glEnd();
		glDisable(GL_TEXTURE_2D);

		// Back Face
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, texture[charToInt(tex3)]);
			glBegin(GL_QUADS);
				//glNormal3f( 0.0f, 0.0f,-0.5f);
				glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
				glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
				glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f,  1.0f, -1.0f);
				glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, -1.0f, -1.0f);
			glEnd();
		glDisable(GL_TEXTURE_2D);

		// Bottom Face
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, texture[charToInt(tex4)]);
			glBegin(GL_QUADS);
				//glNormal3f( 0.0f,-0.5f, 0.0f);
				glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
				glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
				glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
				glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
			glEnd();
		glDisable(GL_TEXTURE_2D);

		// Right Face
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, texture[charToInt(' ')]);
			glBegin(GL_QUADS);
				//glNormal3f( 0.5f, 0.0f, 0.0f);
				glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
				glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);
				glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
				glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
			glEnd();
		glDisable(GL_TEXTURE_2D);

		// Left Face
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, texture[charToInt(' ')]);
			glBegin(GL_QUADS);
				glNormal3f(-0.5f, 0.0f, 0.0f);
				glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
				glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
				glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
				glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
			glEnd();
		glDisable(GL_TEXTURE_2D);
	glPopMatrix();
}

int DrawGLScene(GLvoid)									// Here's Where We Do All The Drawing
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer
	glLoadIdentity();									// Reset The Current Modelview Matrix

	glPushMatrix();
	glTranslatef(0.0f, 0.0f,-1.0f);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture[29]);                                              // draw two rectangles with texture coordinates 
		glBegin(GL_QUADS);
			glTexCoord2d(0.0, 0.0); glVertex3f(-1.0, -1.0, 0.0f);
			glTexCoord2d(0.0, 1.0); glVertex3f(-1.0, 1.0, 0.0f);
			glTexCoord2d(1.0, 1.0); glVertex3f(1.0, 1.0, 0.0f);
			glTexCoord2d(1.0, 0.0); glVertex3f(1.0, -1.0, 0.0f);
		glEnd();
	glDisable(GL_TEXTURE_2D);
	glPopMatrix();

	glDisable(GL_TEXTURE_2D);

	GLfloat lx=-0.9f;

	for(int i=0;i<13;i++)
	{
		if(! mySquare[i].empty())
		  glDrawCube(mySquare[i].front,mySquare[i].top,mySquare[i].back,mySquare[i].bottom,lx,0.0f,0.0f,mySquare[i].rot);	
		else
		  glDrawCube(mySquare[i].front,mySquare[i].top,mySquare[i].back,mySquare[i].bottom,lx,-0.05f,0.0f,mySquare[i].rot);	
		lx+=0.15f;
	}
	glDrawCube(mySquare[13].front,mySquare[13].top,mySquare[13].back,mySquare[13].bottom,0.0f,-0.6f,0.0f,mySquare[13].rot);	

	glPushMatrix();
		//glColor3f(0.0f,0.0f,1.0f);
		glRasterPos2f(-0.1f, 0.4f);
 		glPrint(intToString(score).c_str());	// Print GL Text To The Screen
		//glColor3f(1.0f,0.0f,1.0f);
		glRasterPos2f(-0.95f, -0.95f);
 		glPrint(dico.hint.c_str());	// Print GL Text To The Screen
	glPopMatrix();
	return TRUE;										// Everything Went OK
}

GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window
{
	
	if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}

	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL
	}
	KillFont();
}

BOOL CreateGLWindow(char* title, int width, int height, int bits)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height


	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= (HICON)LoadImage(hInstance,MAKEINTRESOURCE(IDI_ICON1),IMAGE_ICON,0,0,LR_DEFAULTSIZE);
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}
	
	
	
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeGLScene(width, height);					// Set Up Our Perspective GL Screen

	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}


LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	switch (uMsg)									// Check For Windows Messages
	{
	

	case WM_CREATE:
		{
			BuildFont();
			dico.readFile("book.txt");	
	        start();


			return 0;
		}
		case WM_SYSCOMMAND:							// Intercept System Commands
		{
			switch (wParam)							// Check System Calls
			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
				return 0;							// Prevent From Happening
			}
			break;									// Exit
		}

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{
			keys[wParam] = TRUE;					// If So, Mark It As TRUE
			deep-=1.0f;
			return 0;								// Jump Back
		}

		case WM_KEYUP:								// Has A Key Been Released?
		{
			keys[wParam] = FALSE;					// If So, Mark It As FALSE
			//z+=1.0f;
			return 0;								// Jump Back
		}

		case WM_LBUTTONDOWN:
		{
			int flags = wParam; // "flags" contains flags that say whether certain
							   // virtual keys (such as the CTRL key) are being pushed or not
							  // More info on this is supplied at the bottom of this file

			int xPos = LOWORD(lParam);  // This gives us the horizontal (the X position) of
									   // the cursor

			int yPos = HIWORD(lParam); 
			//PrintMouseCoords(hWnd,xPos,yPos);
			GLint val = getSquare(xPos,yPos);
			if(val >= 0 && val <= 12)
			{
				mySquare[val].rotateForw();
			}

			if(xPos >=297 && xPos <= 341 && yPos >= 329 && yPos <= 374)
			{
				mySquare[13].rotateForw();
			}

			if(countPoints()) start();
			deep-= 1.0f;

			return 0;

		}
		case WM_LBUTTONUP:
		{
			int xPos = LOWORD(lParam);  
			int yPos = HIWORD(lParam);

			if(xPos >=297 && xPos <= 341 && yPos >= 329 && yPos <= 374)
			{
				mySquare[13].rotateForw();
				start();
			}
			
			return 0;
		}
		case WM_RBUTTONDOWN:
		{deep+= 1.0f;
			int flags = wParam; // "flags" contains flags that say whether certain
							   // virtual keys (such as the CTRL key) are being pushed or not
							  // More info on this is supplied at the bottom of this file

			int xPos = LOWORD(lParam);  // This gives us the horizontal (the X position) of
									   // the cursor

			int yPos = HIWORD(lParam);
			GLint val = getSquare(xPos,yPos);
			if(val >= 0 && val <= 12)
			{
				mySquare[val].rotateBack();
			}

			if(yPos >=320)
			{
				for(int i=0;i<13;i++) mySquare[i].rotateForw();
			}
			return 0;

		}
		case WM_SIZE:								// Resize The OpenGL Window
		{
			ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
			return 0;								// Jump Back
		}
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}


int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop
	//makeRasterFont();
	
	// Create Our OpenGL Window
	if (!CreateGLWindow("Biblichar",640,480,16))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			DrawGLScene();	// Active?  Was There A Quit Received?
			
			SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
				
		
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}

