
//***********************************************************************

void gl3axis() 
{ 
    //Gl.glClear(Gl.GL_COLOR_BUFFER_BIT) 
    //glPushMatrix(); 
    //glRotatef(4, 2, 3, 1) 
    glLineWidth(5); 
    //Horizontal() 
    glColor3f(1, 0, 0); 
    glBegin(GL_LINES); 
    glVertex2f(-100, 0); 
    glVertex2f(100, 0); 
    glEnd(); 
    /**/
    //vertical 
    glColor3f(0, 0, 1); 
    glBegin(GL_LINES); 
    glVertex2f(0, -100); 
    glVertex2f(0, 100); 
    glEnd(); 
    
    //other 
    glColor3f(0, 1, 0); 
    glBegin(GL_LINES); 
    glVertex3f(0, 0, -100); 
    glVertex3f(0, 0, 100); 
    glEnd(); 
    
    //glPopMatrix(); 
    //Gl.glFlush() 
} 
void Draw_Grid()
{																	
	glLineWidth(1); 
	glColor3f(.8, 0.0, 0.0);
	for(float i = -50; i <= 50; i += 5)
	{
		glBegin(GL_LINES);
			glVertex3f(-50, i, 0.10);									
			glVertex3f(50, i, 0.1);
			glVertex3f(i, -50, 0.1);								
			glVertex3f(i, 50, 0.1);
		glEnd();
	}
}
void Draw_Plain()
{	
	glBegin(GL_QUADS);
		// Front Face
	glColor3f(1.0f,1.0f,1.0f);
		glTexCoord2f(0.0f, 0.0f); glVertex3f(-100.0f, -100.0f,  -0.0f);
//	glColor3f(0.0f,1.0f,0.3f);
		glTexCoord2f(1.0f, 0.0f); glVertex3f( 100.0f, -100.0f,  -0.0f);
//	glColor3f(0.0f,0.0f,1.0f);
		glTexCoord2f(1.0f, 1.0f); glVertex3f( 100.0f,  100.0f,  -0.0f);
//	glColor3f(1.0f,0.0f,0.0f);
		glTexCoord2f(0.0f, 1.0f); glVertex3f(-100.0f,  100.0f,  -0.0f);
	glEnd();
}

int DrawGLScene3(GLvoid)	
{ 
	simLoop(0);
	gl3axis();
	Draw_Grid();
	//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer
	//glLoadIdentity();

	//
	return TRUE;
}

int DrawGLScene(GLvoid)	
{ 
	int i;
	dVector3 ss;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer

	const float *poswBuggy=dBodyGetPosition(body[0]);
	const float *poswPillar=dBodyGetPosition(miBox[0].body);
	const float *poswPillar1=dBodyGetPosition(miBox[lPillar].body);
	const float *posSphere1=dBodyGetPosition(mySphere[0].body);
	const float *lvelSphere1=dBodyGetLinearVel(mySphere[0].body);
	glLoadIdentity();
	glTranslatef(0.0f,0.0f,-1.0f);
	glColor3f(1, 0, 0);
	glRasterPos2f(-.45f, -0.33f);
	glPrint("sleepTime:[%.2f]fpsNow[%.2f],Gravity:[%.5f],boxMass:[%.5f]",sleepTime,fpsNow,sGravity,boxMass);	// Print GL Text To The Screen
	//glRasterPos2f(-.45f, -0.35f);
	//glPrint("posx:[%f%], posy:[%f], posz:[%f]",poswChair[0],poswChair[1],poswChair[2]);	// Print GL Text To The Screen
	glRasterPos2f(-.45f, -0.37f);
	glPrint("BALL : posx:[%f%], posy:[%f], posz:[%f], zforce:[%f], zinc:[%f]",posSphere1[0],posSphere1[1],posSphere1[2],zforce,zinc);	// Print GL Text To The Screen
	glRasterPos2f(-.45f, -0.35f);
	glPrint("poswBuggy: x:[%f%], y:[%f], z:[%f], steer:[%f], speed:[%f]",poswBuggy[0],poswBuggy[1],poswBuggy[2],steer,speed);	// Print GL Text To The Screen

	if(lvelSphere1[2]<15){
		//dBodySetPosition (mySphere[0].body, lvelSphere1[0], lvelSphere1[1], lvelSphere1[2]+.1);
};

/*	
if(posSphere1[2]<500){
		zforce=zforce+zinc;
	}
	else
	{
		zforce=zforce-zinc;
		//if (zinc>0.0001) zinc=zinc-0.00001;
	}
*/
//	dBodySetLinearVel (mySphere[0].body, 0.0, 0.0, zforce);


	if(lvelSphere1[2]<0)
		dBodyAddForce(mySphere[0].body, 0.0,  0.0, zforce);


	glPopAttrib();

	if(camera==1)
	{
		dVector3 camPos;
		dBodyGetRelPointPos(body[0], -2, 0, .3, camPos);
		gluLookAt(camPos[0],camPos[1],camPos[2],poswBuggy[0],poswBuggy[1],poswBuggy[2],0,0,1);
	}

	if(camera==2)
	{
		gluLookAt(10,10,5,poswBuggy[0],poswBuggy[1],poswBuggy[2],0,0,1);
	}

	if(textOn)
	{
		glBindTexture(GL_TEXTURE_2D, texture[3]);
		Draw_Plain();
	}
	else
	{
		gl3axis();
		Draw_Plain();
		Draw_Grid();

	}
	
/* 
	for(cntBox=5;cntBox<6;cntBox++) // wall , roof , floor
	{ 
	  dGeomBoxGetLengths (wall[cntBox],ss);
	  dsDrawBox (dGeomGetPosition(wall[cntBox]),dGeomGetRotation(wall[cntBox]),ss);
	}
*/
	//drawing cloured sphere ruins textured stuff
	 glColor3f(0, 1, 0); 
	dsDrawSphere  (dGeomGetPosition(mySphere[0].geom),dGeomGetRotation(mySphere[0].geom),dGeomSphereGetRadius (mySphere[0].geom));

	glColor3f(1, 1, 0); 

	if(textOn)glBindTexture(GL_TEXTURE_2D, texture[5]);
	dGeomBoxGetLengths (miBB[0].geom,ss);
	dsDrawBox (dGeomGetPosition(miBB[0].geom),dGeomGetRotation(miBB[0].geom),ss);

	glColor3f(.1, .1, .5); 
	for(cntBox=0;cntBox<nPillars;cntBox++)
	{
		if (dBodyIsEnabled (miBox[cntBox].body)) {
			isactive=true;
			if(textOn)glBindTexture(GL_TEXTURE_2D, boxtex[cntBox-1]);
		}
		else
		{
			if(textOn)glBindTexture(GL_TEXTURE_2D, texture[0]);
			isactive=false;
		}

		dGeomBoxGetLengths (miBox[cntBox].geom,ss);
		dsDrawBox (dBodyGetPosition(miBox[cntBox].body),dBodyGetRotation(miBox[cntBox].body),ss);
	}

	if(textOn)glBindTexture(GL_TEXTURE_2D, texture[2]);
		dGeomBoxGetLengths (miChair.geom,ss);
		dsDrawBox (dBodyGetPosition(miChair.body),dBodyGetRotation(miChair.body),ss);
	
	/// Car here
		glColor3f(.1, .5, .1); 
		dGeomBoxGetLengths (box[0],ss);
		dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),ss);
		
		glColor3f(.1, .2, .1); 
		for (i=1; i<=3; i++) {
		dsDrawSphere(dGeomGetPosition(sphere[i-1]),dGeomGetRotation(sphere[i-1]),dGeomSphereGetRadius (sphere[i-1]));
		}
	////////////

	return TRUE;
}

//***********************************************************************

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	glViewport(0,0,width,height);						// Reset The Current Viewport

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

	// Calculate The Aspect Ratio Of The Window
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix
}

//***********************************************************************

int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{

		glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
		glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// 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

		glEnable (GL_LIGHTING);
		glEnable (GL_LIGHT0);
		glEnable(GL_COLOR_MATERIAL);


	if (textOn){

		if (!BuildTexture("data\\lowres.bmp", texture[0],-1))						// Load The Wall Texture
		return FALSE;
	
		if (!BuildTexture("data\\pac.bmp", texture[2],-1))						// Load The Wall Texture
		return FALSE;		
		if (!BuildTexture("data\\map.bmp", texture[3],-1))						// Load The Wall Texture
		return FALSE;

//		if (!BuildTexture("http://www.ittefaq.com/data/up/07/03/10/1stpage.jpg", texture[5],0))						// Load The Wall Texture
		if (!BuildTexture("data\\bb1.jpg", texture[5],0))						// Load The Wall Texture
		return FALSE;
		if (!BuildTexture("data\\bb3.gif", texture[6],1))						// Load The Wall Texture
		return FALSE;
		if (!BuildTexture("data\\bb2.jpg", texture[7],2))						// Load The Wall Texture
		return FALSE;

		if (!BuildTexture("info\\1.jpg", boxtex[0],-1))return FALSE;
		if (!BuildTexture("info\\2.jpg", boxtex[1],-1))return FALSE;
		if (!BuildTexture("info\\3.jpg", boxtex[2],-1))return FALSE;
		if (!BuildTexture("info\\4.jpg", boxtex[3],-1))return FALSE;
		if (!BuildTexture("info\\5.jpg", boxtex[4],-1))return FALSE;

		glEnable(GL_TEXTURE_2D);							// Enable Texture Mapping ( NEW )
	}

   return TRUE;										// Initialization Went OK
}

//***********************************************************************

GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window
{
	if (fullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer
	}

	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
	}

}
//***********************************************************************

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Fullscreen Mode				*
 *	height			- Height Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag,DWORD dwStyle,HWND hPwnd)
{
	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

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	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			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	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
	}
	
	if (fullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
		ShowCursor(FALSE);										// Hide Mouse Pointer
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended 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
								hPwnd,								// 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.","OpenGL! ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}