Problems with making a light reader

Started by
16 comments, last by Enigma 19 years, 5 months ago
Hey, i've been having problems adding some light to NeHe's lesson 10 (i'm further than that, just didn't play with that code until now.), no i'm not just adding a little light, i'm trying to load the light from a level file (world.txt). I get these errors when compiling with Dev-C++: - C:\Documents and Settings\Joost\My Documents\Mijn ontvangen bestanden\forumfun\lesson10\lesson10.cpp In function `void SetupWorld()': - 132 C:\Documents and Settings\Joost\My Documents\Mijn ontvangen bestanden\forumfun\lesson10\lesson10.cpp invalid initializer - C:\Documents and Settings\Joost\My Documents\Mijn ontvangen bestanden\forumfun\lesson10\Makefile.win [Build Error] [lesson10.o] Error 1 This is my function 'SetupWorld()': code: void SetupWorld() { float x, y, z, u, v; int numtriangles; FILE *filein; FILE *filein2; char oneline[255]; filein = fopen("data/world.txt", "rt"); // File To Load World Data From filein2 = fopen("data/world.txt", "rt"); readstr(filein,oneline); readlight(filein2,oneline2); char nothing; float light1; float light2; float light3; float light4; float light5; float light6; float light7; float light8; float light9; float light10; float light11; float light12; sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles); sscanf(oneline2, "%c %f %f %f %f %f %f %f %f %f %f %f %f ", &nothing, &light1, &light2, &light3, &light4, &light5, &light6, &light7, &light8, &light9, &light10, &light11, &light12); sector1.triangle = new TRIANGLE[numtriangles]; sector1.numtriangles = numtriangles; for (int loop = 0; loop < numtriangles; loop++) { for (int vert = 0; vert < 3; vert++) { readstr(filein,oneline); sscanf(oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v); sector1.triangle[loop].vertex[vert].x = x; sector1.triangle[loop].vertex[vert].y = y; sector1.triangle[loop].vertex[vert].z = z; sector1.triangle[loop].vertex[vert].u = u; sector1.triangle[loop].vertex[vert].v = v; } } GLfloat LightAmbient[]= (light1, light2, light3, light4); GLfloat LightDiffuse[]= { light5, light6, light7, light8 }; // Diffuse Light Values ( NEW ) GLfloat LightPosition[]= { light9, light10, light11, light12}; glEnable(GL_LIGHT1); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); 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 fclose(filein); return; } This is the structure of light lines in my world.txt file: code: l 0.5 0.5 0.5 1.0 1.0 1.0 1.0 1.0 0.0 0.0 2.0 1.0 // ambient 1, 2, 3, 4 diffuse 1, 2, 3 4, position 1, 2, 3, 4 This is my readlight function: code: void readlight(FILE *f2,char *string2) { do { fgets(string2, 255, f2); } while ((string2[0] != 'l')); return; } Please tell me what is causing these errors. Cheers.
Advertisement
Okay, when it comes to these things I tend to get fuzzy, but let me ask about this line:

sector1.triangle = new TRIANGLE[numtriangles];


the new function in C++ returns a pointer to the newly allocated object and expects you to provide the correct constructor for the object.

You are obviously trying to create an array of dynamic size. However, TRIANGLE[some value] is of type "pointer" and is initialized to the addresss of the first object in the array. Essentially then, by your statement above, if it is legal, you are asking for a pointer to a pointer to a TRIANGLE. I do not belive that this is a legal option in c++.

What I would suggest doing is using a LIST structure. The STL::LIST is really easy to use and would go great here.

First, change sector1.triangle to type of STL::List<TRIANGLE>

Second, when adding the triangles to the list, each time through dynamically create a new TRIANGLE:

ie.
TRIANGLE *pTemp = new TRIAGLE();

Next, add the values to the triangle:

ie.
pTemp->VERTEX[index].x = x;
pTemp->VERTEX[index].y = y;
etc...

Lastly, add the new vertex to the LIST:

ie.
sector1.triangle.push_back(*pTemp);

I was always taught that this is the implement a "dynamic array" but then again, depending on your implementation of C++ newer ways may be legal as well. Still, if you cant get it to work, try my way...

Hope it helps.
Hard work USUALLY pays off in the future, but laziness ALWAYS pays off right now.
hrm... that line comes straight from the tutorial.

Guess I was wrong.

Sorry bout that... I'll have to do some more checking.
Hard work USUALLY pays off in the future, but laziness ALWAYS pays off right now.
Yeah, that's straight from the tutorial. :p
Which line is line 132?

By the way, since you're using C++ you would be much better off using std::deque instead of a raw array for your triangles and fstreams instead of file pointers and non-typesafe C io functions.

Enigma
Line 132 is the line that begins with GLFloat LightAmbient.
Ah. That immediately shows the problem. You're using parenthesis when you should be using braces.

Enigma
Thanks man, someone mentioned this at OpenGL.org.
My light reader is finished, but i'm having way more trouble making a texture reader. :p
Ok, i've got a simple 'dynamic' texture reader. (Dynamic as in different textures in the world possible).
But it doesn't really work, no errors though.
The scene just gets drawn without textures.

Here is my code:

bool NeHeLoadBitmap(LPTSTR szFileName, GLuint &texid) // Creates Texture From A Bitmap File
{
HBITMAP hBMP; // Handle Of The Bitmap
BITMAP BMP; // Bitmap Structure

glGenTextures(1, &texturefinaldynamic[0]); // Create The Texture
hBMP=(HBITMAP)LoadImage(GetModuleHandle(NULL), szFileName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE );

if (!hBMP) // Does The Bitmap Exist?
return FALSE; // If Not Return False

GetObject(hBMP, sizeof(BMP), &BMP); // Get The Object
// hBMP: Handle To Graphics Object
// sizeof(BMP): Size Of Buffer For Object Information
// &BMP: Buffer For Object Information

glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // Pixel Storage Mode (Word Alignment / 4 Bytes)

// Typical Texture Generation Using Data From The Bitmap
// Create Nearest Filtered Texture

// Create MipMapped Texture
glBindTexture(GL_TEXTURE_2D, texturefinaldynamic[texid]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, BMP.bmWidth, BMP.bmHeight, GL_RGB, GL_UNSIGNED_BYTE, BMP.bmBits);

DeleteObject(hBMP); // Delete The Object

return TRUE; // Loading Was Successful
}

int LoadDynamicTextures(int texturenumber, char texturetoload[255]) // Load Bitmaps And Convert To Textures
{
if(NeHeLoadBitmap(texturetoload, textureloader[texturenumber]))
{
glBindTexture(GL_TEXTURE_2D, texturefinaldynamic[texturenumber]);
return TRUE;
}
return FALSE;
}

void readtextures(FILE *f3,char *string3)
{
do
{
fgets(string3, 255, f3);
} while ((string3[0] != 't'));
return;
}




void SetupWorld()
{
float x, y, z, u, v;
int numtriangles;
FILE *filein;
FILE *filein2;
FILE *filein3;
char oneline[255];
char oneline2[255];
char oneline3[255];
char nothing2;
char loadthistexture[255];
int itisthetexturenumber;
filein = fopen("data/world.txt", "rt"); // File To Load World Data From
filein2 = fopen("data/world.txt", "rt");
filein3 = fopen("data/world.txt", "rt");
readstr(filein,oneline);
readlight(filein2,oneline2);
readtextures(filein3,oneline3);
sscanf(oneline3, "%c %s %d", &nothing2, &loadthistexture, &itisthetexturenumber);
LoadDynamicTextures(itisthetexturenumber, loadthistexture);
char nothing;
float light1;
float light2;
float light3;
float light4;
float light5;
float light6;
float light7;
float light8;
float light9;
float light10;
float light11;
float light12;
sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles);
sscanf(oneline2, "%c %f %f %f %f %f %f %f %f %f %f %f %f ", &nothing, &light1, &light2, &light3, &light4, &light5, &light6, &light7, &light8, &light9, &light10, &light11, &light12);

sector1.triangle = new TRIANGLE[numtriangles];
sector1.numtriangles = numtriangles;
for (int loop = 0; loop < numtriangles; loop++)
{
for (int vert = 0; vert < 3; vert++)
{
readstr(filein,oneline);
sscanf(oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v);
sector1.triangle[loop].vertex[vert].x = x;
sector1.triangle[loop].vertex[vert].y = y;
sector1.triangle[loop].vertex[vert].z = z;
sector1.triangle[loop].vertex[vert].u = u;
sector1.triangle[loop].vertex[vert].v = v;
}
}

GLfloat LightAmbient[]= {light1, light2, light3, light4};
GLfloat LightDiffuse[]= {light5, light6, light7, light8 }; // Diffuse Light Values ( NEW )
GLfloat LightPosition[]= {light9, light10, light11, light12};

glEnable(GL_LIGHT1);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);

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
fclose(filein);
return;
}

I think the problem might be that i'm using glBindTexture(); on the wrong place. Is this correct?

If it might be needed:
The texture loading code in world.txt looks like this:

t Shot0054.bmp 1

Is some more information needed?

Please help me
Cheers.
First, two comments:
1. Please use [source] tags when posting large code snippets (and [code] tags for small snippets).
2. I hope you don't mind me saying so, but your code is absolutely horrible!

I suspect the reason your code isn't working is because of the line glBindTexture(GL_TEXTURE_2D, texture[filter]); in the DrawGLScene function. This will be overriding your texture if you haven't changed it.

Here's a much neater version that does what you want. It's still far from perfect, but it's a lot better than what you've got.
#include <cmath>#include <deque>#include <fstream>#include <map>#include <string>#include <windows.h>#include <GL/gl.h>#include <GL/glu.h>/* Don't worry about this, it's just a more bullet proof version of NULL */class NullPtr{	public:		template <typename TYPE>		operator const TYPE*() const		{			return 0;		}		operator void*() const		{			return 0;		}		template <typename TYPE, class CLASS>		operator const TYPE CLASS::*() const		{			return 0;		}	private:		void operator&() const;} nullptr;HDC hDC = nullptr;HGLRC hRC = nullptr;HWND hWnd = nullptr;HINSTANCE hInstance = nullptr;bool keys[256];bool active = true;bool fullscreen = true;bool blend;bool bp;bool fp;const float piover180 = 3.14159f / 180;float heading;float xpos;float zpos;GLfloat yrot;GLfloat walkbias = 0;GLfloat walkbiasangle = 0;GLfloat lookupdown = 0.0f;GLfloat z = 0.0f;/* This is C++, so there is no need to typedef the structs */struct Vertex{	float x, y, z;	float u, v;};struct Triangle{	Vertex vertex[3];};/* Why use a raw array when you can use a deque? */struct Sector{	std::deque<Triangle> triangle;};Sector sector1;/* Let's store our textures in a map to make things easier */std::map<std::string, GLuint> textures;LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);/* Prefer std::string to char*.  Also changed the id to a string for ease of use */bool neHeLoadBitmap(std::string fileName, std::string textureName){	HBITMAP bitmapHandle;	BITMAP bitmap;	GLuint textureId;	glGenTextures(1, &textureId);	/* Use proper named casts in C++.  In this case we use static_cast */	bitmapHandle = static_cast<HBITMAP>(LoadImage(GetModuleHandle(nullptr), fileName.c_str(), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE));	if (!bitmapHandle)	{		return false;	}	GetObject(bitmapHandle, sizeof(bitmap), &bitmap);	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);	glBindTexture(GL_TEXTURE_2D, textureId);	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);	/* Prefer named constant GL_RGB to literal 3 for the second parameter.  Also bitmaps are stored in BGR format */	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, bitmap.bmWidth, bitmap.bmHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, bitmap.bmBits);	/* Add the texture id to our list.  It's named so we can retrieve it easily later */	textures.insert(std::pair<std::string, GLuint>(textureName, textureId));	DeleteObject(bitmapHandle);	return true;}/* Read a colour from a file stream */void readFloatColour(std::ifstream& reader, float* colourArray){	reader >> colourArray[0];	reader >> colourArray[1];	reader >> colourArray[2];	reader >> colourArray[3];}/* Read light data */void readLight(std::ifstream& reader){	/* Ignore the '|' identifier */	reader.ignore(1);	float lightColour[4];	readFloatColour(reader, lightColour);	glLightfv(GL_LIGHT1, GL_AMBIENT, lightColour);	readFloatColour(reader, lightColour);	glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColour);	readFloatColour(reader, lightColour);	glLightfv(GL_LIGHT1, GL_POSITION, lightColour);}/* Read a texture from a file stream */void readTexture(std::ifstream& reader){	/* Ignore the 't' identifier */	reader.ignore(1);	/* Read the file name and the name to identify the texture by */	std::string fileName;	std::string textureName;	reader >> fileName;	reader >> textureName;	/* Load the texture.  Throw an exception if the texture was not found */	if (!neHeLoadBitmap(fileName, textureName))	{		throw "Texture not found: " + fileName;	}}/* Read a vertex from a file stream */void readVertex(std::ifstream& reader, Vertex& vertex){	reader >> vertex.x;	reader >> vertex.y;	reader >> vertex.z;	reader >> vertex.u;	reader >> vertex.v;}/* Read a triangle from a file stream */void readTriangle(std::ifstream& reader){	Triangle triangle;	readVertex(reader, triangle.vertex[0]);	readVertex(reader, triangle.vertex[1]);	readVertex(reader, triangle.vertex[2]);	/* We use a deque, so push the triangle onto the back of it */	sector1.triangle.push_back(triangle);}bool setupWorld(){	/* Use streams, not raw file pointers */	std::ifstream reader("data/world.txt");	if (!reader)	{		return false;	}	/* Get the length of the file */	reader.seekg(0, std::ios::end);	int fileSize = reader.tellg();	reader.seekg(0, std::ios::beg);	while (!reader.eof())	{		/* Skip any leading whitespace */		while (reader.peek() == 10 || reader.peek() == 13 || reader.peek() == ' ' || reader.peek() == '\t')		{			reader.ignore(1);		}		/* Does this line contain light information? */		if (reader.peek() == '|')		{			readLight(reader);		}		/* Does this line contain texture information? */		else if (reader.peek() == 't')		{			readTexture(reader);		}		/* Does this line contain a comment or the number of polygons? */		/* Because we use a deque we don't need the number of polygons, so we just ignore it */		else if (reader.peek() == 'N' || reader.peek() == '/')		{			reader.ignore(fileSize, '\n');		}		/* Not anything else, so it must be triangle information */		else		{			readTriangle(reader);		}	}	glEnable(GL_LIGHT1);	glEnable(GL_LIGHTING);	glEnable(GL_COLOR_MATERIAL);	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{	glEnable(GL_TEXTURE_2D);							// Enable Texture Mapping	glBlendFunc(GL_SRC_ALPHA,GL_ONE);					// Set The Blending Function For Translucency	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);				// This Will Clear The Background Color To Black	glClearDepth(1.0);									// Enables Clearing Of The Depth Buffer	glDepthFunc(GL_LESS);								// The Type Of Depth Test To Do	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing	glShadeModel(GL_SMOOTH);							// Enables Smooth Color Shading	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations	setupWorld();	return TRUE;										// Initialization Went OK}int DrawGLScene(GLvoid)									// Here's Where We Do All The Drawing{	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear The Screen And The Depth Buffer	glLoadIdentity();									// Reset The View	GLfloat x_m, y_m, z_m, u_m, v_m;	GLfloat xtrans = -xpos;	GLfloat ztrans = -zpos;	GLfloat ytrans = -walkbias-0.25f;	GLfloat sceneroty = 360.0f - yrot;	int numtriangles;	glRotatef(lookupdown,1.0f,0,0);	glRotatef(sceneroty,0,1.0f,0);		glTranslatef(xtrans, ytrans, ztrans);	glBindTexture(GL_TEXTURE_2D, textures["1"]);		// Process Each Triangle	for (int loop_m = 0; loop_m < sector1.triangle.size(); loop_m++)	{		glBegin(GL_TRIANGLES);			glNormal3f( 0.0f, 0.0f, 1.0f);			x_m = sector1.triangle[loop_m].vertex[0].x;			y_m = sector1.triangle[loop_m].vertex[0].y;			z_m = sector1.triangle[loop_m].vertex[0].z;			u_m = sector1.triangle[loop_m].vertex[0].u;			v_m = sector1.triangle[loop_m].vertex[0].v;			glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m);						x_m = sector1.triangle[loop_m].vertex[1].x;			y_m = sector1.triangle[loop_m].vertex[1].y;			z_m = sector1.triangle[loop_m].vertex[1].z;			u_m = sector1.triangle[loop_m].vertex[1].u;			v_m = sector1.triangle[loop_m].vertex[1].v;			glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m);						x_m = sector1.triangle[loop_m].vertex[2].x;			y_m = sector1.triangle[loop_m].vertex[2].y;			z_m = sector1.triangle[loop_m].vertex[2].z;			u_m = sector1.triangle[loop_m].vertex[2].u;			v_m = sector1.triangle[loop_m].vertex[2].v;			glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m);		glEnd();	}	return TRUE;										// Everything Went OK}GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window{	if (fullscreen)										// Are We In Fullscreen Mode?	{		ChangeDisplaySettings(nullptr,0);					// If So Switch Back To The Desktop		ShowCursor(TRUE);								// Show Mouse Pointer	}	if (hRC)											// Do We Have A Rendering Context?	{		if (!wglMakeCurrent(nullptr,nullptr))					// Are We Able To Release The DC And RC Contexts?		{			MessageBox(nullptr,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		}		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?		{			MessageBox(nullptr,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		}		hRC=nullptr;										// Set RC To NULL	}	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC	{		MessageBox(nullptr,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		hDC=nullptr;										// Set DC To NULL	}	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?	{		MessageBox(nullptr,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		hWnd=nullptr;										// Set hWnd To NULL	}	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class	{		MessageBox(nullptr,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		hInstance=nullptr;									// 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){	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(nullptr);				// 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(nullptr, IDI_WINLOGO);			// Load The Default Icon	wc.hCursor			= LoadCursor(nullptr, IDC_ARROW);			// Load The Arrow Pointer	wc.hbrBackground	= nullptr;									// No Background Required For GL	wc.lpszMenuName		= nullptr;									// We Don't Want A Menu	wc.lpszClassName	= "OpenGL";								// Set The Class Name	if (!RegisterClass(&wc))									// Attempt To Register The Window Class	{		MessageBox(nullptr,"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(nullptr,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe 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(nullptr,"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		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								nullptr,								// No Parent Window								nullptr,								// No Menu								hInstance,							// Instance								nullptr)))								// Dont Pass Anything To WM_CREATE	{		KillGLWindow();								// Reset The Display		MessageBox(nullptr,"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(nullptr,"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(nullptr,"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(nullptr,"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(nullptr,"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(nullptr,"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(nullptr,"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_ACTIVATE:							// Watch For Window Activate Message		{			if (!HIWORD(wParam))					// Check Minimization State			{				active=TRUE;						// Program Is Active			}			else			{				active=FALSE;						// Program Is No Longer Active			}			return 0;								// Return To The Message Loop		}		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			return 0;								// Jump Back		}		case WM_KEYUP:								// Has A Key Been Released?		{			keys[wParam] = FALSE;					// If So, Mark It As FALSE			return 0;								// Jump Back		}		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	// Ask The User Which Screen Mode They Prefer	if (MessageBox(nullptr,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)	{		fullscreen=FALSE;							// Windowed Mode	}	// Create Our OpenGL Window	if (!CreateGLWindow("Lionel Brits & NeHe's 3D World Tutorial",640,480,16,fullscreen))	{		return 0;									// Quit If Window Was Not Created	}	while(!done)									// Loop That Runs While done=FALSE	{		if (PeekMessage(&msg,nullptr,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()			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?			{				done=TRUE;							// ESC or DrawGLScene Signalled A Quit			}			else									// Not Time To Quit, Update Screen			{				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)				if (keys['B'] && !bp)				{					bp=TRUE;					blend=!blend;					if (!blend)					{						glDisable(GL_BLEND);						glEnable(GL_DEPTH_TEST);					}					else					{						glEnable(GL_BLEND);						glDisable(GL_DEPTH_TEST);					}				}				if (!keys['B'])				{					bp=FALSE;				}				if (keys['F'] && !fp)				{					fp=TRUE;				}				if (!keys['F'])				{					fp=FALSE;				}				if (keys[VK_PRIOR])				{					z-=0.02f;				}				if (keys[VK_NEXT])				{					z+=0.02f;				}				if (keys[VK_UP])				{					xpos -= (float)std::sin(heading*piover180) * 0.05f;					zpos -= (float)std::cos(heading*piover180) * 0.05f;					if (walkbiasangle >= 359.0f)					{						walkbiasangle = 0.0f;					}					else					{						walkbiasangle+= 10;					}					walkbias = (float)std::sin(walkbiasangle * piover180)/20.0f;				}				if (keys[VK_DOWN])				{					xpos += (float)std::sin(heading*piover180) * 0.05f;					zpos += (float)std::cos(heading*piover180) * 0.05f;					if (walkbiasangle <= 1.0f)					{						walkbiasangle = 359.0f;					}					else					{						walkbiasangle-= 10;					}					walkbias = (float)std::sin(walkbiasangle * piover180)/20.0f;				}				if (keys[VK_RIGHT])				{					heading -= 1.0f;					yrot = heading;				}				if (keys[VK_LEFT])				{					heading += 1.0f;						yrot = heading;				}				if (keys[VK_PRIOR])				{					lookupdown-= 1.0f;				}				if (keys[VK_NEXT])				{					lookupdown+= 1.0f;				}				if (keys[VK_F1])						// Is F1 Being Pressed?				{					keys[VK_F1]=FALSE;					// If So Make Key FALSE					KillGLWindow();						// Kill Our Current Window					fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode					// Recreate Our OpenGL Window					if (!CreateGLWindow("Lionel Brits & NeHe's 3D World Tutorial",640,480,16,fullscreen))					{						return 0;						// Quit If Window Was Not Created					}				}			}		}	}	// Shutdown	KillGLWindow();										// Kill The Window	return (msg.wParam);								// Exit The Program}


Enigma

This topic is closed to new replies.

Advertisement