// ++++++++++++++++++++++++++++++++++++++++++ // || James Grafton and || // || Ben Hacking || // || OpenGL First Person Shooter || // || || // ++++++++++++++++++++++++++++++++++++++++++ #include "Main.h" #define UPS 40.0f #define GRAVITY 0.0040f #define WIDTH 1024 #define HEIGHT 768 #define PIOVER180 0.0174532925f using namespace std; //--------STRUCTS---------------- // typedef struct Texture { GLuint texture; string name; } Texture; typedef struct tagVERTEX { float x, y, z; float u, v; } VERTEX; typedef struct tagTRIANGLE { Texture *texture; VERTEX vertex[3]; } TRIANGLE; typedef struct tagSECTOR { int numtriangles; TRIANGLE* triangle; } SECTOR; // ----------WINDOWS STUFF------------ // HDC hDC=NULL; // Private GDI Device Context HGLRC hRC=NULL; // Permanent Rendering Context HWND hWnd=NULL; // Holds Our Window Handle HINSTANCE hInstance; // Holds The Instance Of The Application bool active=true; // Window Active Flag Set To TRUE By Default bool fullscreen=true; // Fullscreen Flag Set To Fullscreen Mode By Default bool paused =false; // ------------ KEY INPUT STUFF ------------ // bool keys[256]; // Array Used For The Keyboard Routine bool spacep; // SPACE Pressed? bool wp; bool sp; bool ap; bool dp; // ---- CAMERA STUFF ---- // Camera* camera=NULL; CCamera objCamera; // ---- Player STUFF ---- // Player* player = NULL; // ---- CONSOLE STUFF ---- // Console* console = NULL; // ---- FPS/UPS MEASURER ---- // PerformenceMeasurer* perf_measurer=NULL; float distToPlane =0; int colliding=0; // ----------TIMER STUFF------------ // Timer* timer=NULL; //Timer object // ---- MOUSE STUFF ---- // Mouse* mouse = NULL; // Mouse // --------------------- // // ---- STATE STUFF ---- // enum States { INTRO = 1, INGAME =2 }; int gCurrentState=2; // ---- LEVEL STUFF ---- // SECTOR sector1; // Only one sector in this map vector texture_cache; // ---- FONT STUFF ---- // GLuint base; // Base Display List For The Font Set GLfloat cnt1; // 1st Counter Used To Move Text & For Coloring GLfloat cnt2; // 2nd Counter Used To Move Text & For Coloring GLYPHMETRICSFLOAT gmf[256]; // Storage For Information About Our Font inline GLdouble ABS(GLdouble A) { if (A < 0) A = -A; return A; } // ----------------------------------- // // ---- FUNCTION DECLARATIONS ---- // LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc inline float dotProduct3f(float* v1,float* v2); inline float* matrixMultiply3f(float* v1,float* v2); inline float* crossProduct3f(float* v1,float* v2); inline float* matrixMinus3f(float* v1,float* v2); inline float* convertVertex(VERTEX v1); void collisionDetect(tVector3* oldMPos,tVector3* oldMView); boolean sameSide(float* p1, float* p2,float* A,float* B); int insideTriangle(float* point,float* A,float* B,float* C); void getInput(); void updateGame(); void update(); void readstr(FILE *f,char *string); int SetupWorld(); AUX_RGBImageRec *LoadBMP(char *Filename); Texture* LoadGLTextures(char* path); GLvoid ReSizeGLScene(GLsizei width, GLsizei height); int InitGL(); int DrawGLScene(GLvoid); void drawDebug(); GLvoid KillGLWindow(GLvoid); BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag); GLvoid glPrint(const char *fmt, ...); GLvoid KillFont(GLvoid); GLvoid BuildFont(GLvoid); // ----------------------------------- // /************VSYNC SHIZZLE***********/ //function pointer typdefs typedef void (APIENTRY *PFNWGLEXTSWAPCONTROLPROC) (int); typedef int (*PFNWGLEXTGETSWAPINTERVALPROC) (void); //declare functions PFNWGLEXTSWAPCONTROLPROC wglSwapIntervalEXT = NULL; PFNWGLEXTGETSWAPINTERVALPROC wglGetSwapIntervalEXT = NULL; //init VSync func void InitVSync() { //get extensions of graphics card char* extensions = (char*)glGetString(GL_EXTENSIONS); //is WGL_EXT_swap_control in the string? VSync switch possible? if (strstr(extensions,"WGL_EXT_swap_control")) { //get address's of both functions and save them wglSwapIntervalEXT = (PFNWGLEXTSWAPCONTROLPROC) wglGetProcAddress("wglSwapIntervalEXT"); wglGetSwapIntervalEXT = (PFNWGLEXTGETSWAPINTERVALPROC) wglGetProcAddress("wglGetSwapIntervalEXT"); } } bool VSyncEnabled() { //if interval is positif, it is not 0 so enabled ;) return (wglGetSwapIntervalEXT() > 0); } void SetVSyncState(bool enable) { if (enable) wglSwapIntervalEXT(1); //set interval to 1 -> enable else wglSwapIntervalEXT(0); //disable } inline float dotProduct3f(float* v1,float* v2){ return((v1[0]*v2[0])+(v1[1]*v2[1])+(v1[2]*v2[2])); } inline float* matrixMultiply3f(float* v1,float* v2){ float* result = new float[3]; result[0] = v1[0]*v2[0]; result[1] = v1[1]*v2[1]; result[2] = v1[2]*v2[2]; return result; } inline float* crossProduct3f(float* v1,float* v2){ float* result = new float[3]; // memset(result, 0, sizeof(float) * 3); would clear the memory in the above line as new doesn't do it for you result[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]); result[1] = -((v1[2] * v2[0]) - (v1[0] * v2[2])); result[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]); return result; } inline float* matrixMinus3f(float* v1,float* v2){ float* result = new float[3]; result[0] = v1[0]-v2[0]; result[1] = v1[1]-v2[1]; result[2] = v1[2]-v2[2]; return result; } inline float* convertVertex(VERTEX v1){ float* result = new float[3]; result[0]=v1.x; result[1]=v1.y; result[2]=v1.z; return result; } void updateGame() { // -- Are we jumping? Add player jump velocity -- // player->ypos = (!player->jumping)? 0: player->ypos + player->jump_velocity; if(player->jumping){player->jump_velocity-= (GRAVITY)*(timer->timeSinceLastUpdate/timer->ups_ms);} if(player->ypos<0.0F){player->jumping=false;player->ypos=0;player->jump_velocity=0;} // ----------------------------------- // //Detect mouse movement objCamera.Mouse_Move(WIDTH,HEIGHT); tVector3 oldMPos = objCamera.mPos; tVector3 oldMView = objCamera.mView; //Get keyboard input getInput(); //Do collision detection collisionDetect(&oldMPos,&oldMView); } void collisionDetect(tVector3* oldMPos,tVector3* oldMView){ //If we are moving in no direction then return if(!wp&&!ap&&!sp&&!dp){return;} colliding=0; for(unsigned int i =sector1.numtriangles;i--;){ //First work out normal TRIANGLE tri = sector1.triangle[i]; float* A = convertVertex(tri.vertex[0]); float* B = convertVertex(tri.vertex[1]); float* C = convertVertex(tri.vertex[2]); //B-A and C-A float* result1 = matrixMinus3f(B,A); float* result2 = matrixMinus3f(C,A); //The normal of this plane! float* normal = crossProduct3f(result1,result2); //Normalize values in the vector float total = normal[0]+normal[1]+normal[2]; normal[0]/=total; normal[1]/=total; normal[2]/=total; //Get normal . P-A to get distance from the plane 0 means we are on the plane float* oldCameraPosition = new float[3]; oldCameraPosition[0] = oldMPos->x; oldCameraPosition[1] = oldMPos->y; oldCameraPosition[2] = oldMPos->z; //Figure out distance to plane distToPlane = dotProduct3f(normal,matrixMinus3f(oldCameraPosition,A)); //Store new position in float array float* newCameraPosition = new float[3]; newCameraPosition[0] = objCamera.mPos.x; newCameraPosition[1] = objCamera.mPos.y; newCameraPosition[2] = objCamera.mPos.z; //Figure out the distance to the plane as result of latest update float newDist = dotProduct3f(normal,matrixMinus3f(newCameraPosition,A)); if((newDist>=0&&distToPlane<=0)||(newDist<=0&&distToPlane>=0)||ABS(newDist)<0.16f){ //If we have crossed through a triangle if(insideTriangle(newCameraPosition,A,B,C)){ colliding=1; if(colliding){ //new pos = oldpos tVector3 t = (objCamera.mPos-*oldMPos); float* trajectory = new float[3]; trajectory[0]=t.x; trajectory[1]=t.y; trajectory[2]=t.z; float* response = matrixMultiply3f(trajectory,normal); tVector3* tres = new tVector3(response[0],response[1],response[2]); objCamera.mPos = objCamera.mPos-*tres; objCamera.mView = objCamera.mView-*tres; //objCamera.mView=*oldMView; } } } } } boolean sameSide(float* p1, float* p2,float* A,float* B){ float * cp1 = crossProduct3f(matrixMinus3f(B,A), matrixMinus3f(p1,A)); float * cp2 = crossProduct3f(matrixMinus3f(B,A), matrixMinus3f(p2,A)); if(dotProduct3f(cp1, cp2) >= 0){ return true; } return false; } int insideTriangle(float* point,float* A,float* B,float* C){ if(sameSide(point,A,B,C)&&sameSide(point,B,A,C)&&sameSide(point,C,A,B)){ return 1; } return 0; } void getInput(){ wp=false; sp=false; ap=false; dp=false; if (keys['W']) { wp=true; objCamera.Move_Camera(player->run_velocity*(timer->timeSinceLastUpdate/timer->ups_ms)); //player->xpos -= ((GLfloat)sin(player->heading*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); //player->zpos -= ((GLfloat)cos(player->heading*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); } if (keys['S']) { sp=true; objCamera.Move_Camera(-player->run_velocity*(timer->timeSinceLastUpdate/timer->ups_ms)); //player->xpos += ((GLfloat)sin(player->heading*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); //player->zpos += ((GLfloat)cos(player->heading*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); } if (keys['D']) // Is The Right Arrow Being Pressed? { dp=true; objCamera.Strafe_Camera(player->run_velocity*(timer->timeSinceLastUpdate/timer->ups_ms)); //player->xpos += ((GLfloat)sin((player->heading+90)*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); //player->zpos += ((GLfloat)cos((player->heading+90)*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); } if (keys['A']) // Is The Left Arrow Being Pressed? { ap=true; objCamera.Strafe_Camera(-player->run_velocity*(timer->timeSinceLastUpdate/timer->ups_ms)); //player->xpos += ((GLfloat)sin((player->heading-90)*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); //player->zpos += ((GLfloat)cos((player->heading-90)*PIOVER180) * player->run_velocity)*(timer->timeSinceLastUpdate/timer->ups_ms); } if (keys[VK_SPACE] && !spacep&&player->jump_velocity==0) { spacep=TRUE; player->jumping=true; player->jump_velocity=0.05f; } if (!keys[VK_SPACE]) { spacep=FALSE; } 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("OpenGL Game",WIDTH,HEIGHT,16,fullscreen)) { exit(0); } } } void update() { switch(gCurrentState) { case INTRO: //updateIntro(); break; case INGAME: updateGame(); break; } } // ------ FUNCTION - READ STRING FROM FILE ------ // void readstr(FILE *f,char *string) { do { fgets(string, 255, f); } while ((string[0] == '/') || (string[0] == '\n')); return; } // ---------------------------------------------- // // ---------- FUNCTION - WORLD SETUP ---------- // int SetupWorld() { float x, y, z, u, v; int numtriangles; FILE *filein; char oneline[255]; filein = fopen("data/world.txt", "rt"); // File To Load World Data From texture_cache.clear(); //Make sure texture cache is empty readstr(filein,oneline); sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles); sector1.triangle = new TRIANGLE[numtriangles]; sector1.numtriangles = numtriangles; char currentTexture[255]; for (int loop = 0; loop < numtriangles; loop++) { //load new texture every 6 lines if(loop%2==0){ readstr(filein,currentTexture); currentTexture[strlen(currentTexture)-1]=NULL; } 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; } sector1.triangle[loop].texture = LoadGLTextures(currentTexture); } fclose(filein); return 1; } // --------------------------------------------- // // ------------- FUNCTION - LOADING BMPS -------------- // AUX_RGBImageRec *LoadBMP(char *Filename) // Loads A Bitmap Image { FILE *File=NULL; // File Handle if (!Filename) // Make Sure A Filename Was Given { return NULL; // If Not Return NULL } File=fopen(Filename,"r"); // Check To See If The File Exists if (File) // Does The File Exist? { fclose(File); // Close The Handle return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer } return NULL; // If Load Failed Return NULL } // ---------------------------------------------------- // // ------------ FUNCTION - LOADING TEXTURES ----------- // Texture* LoadGLTextures(char *path) // Load Bitmaps And Convert To Textures { //See if we have this texure cached for(unsigned int i=0;iname.c_str(),path)){ return cached_texture; } } //If not add it to texture cache Texture *new_texture = new Texture; new_texture->name+=path; int Status=FALSE; // Status Indicator AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture memset(TextureImage,0,sizeof(void *)*1); // Set The Pointer To NULL // Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit if (TextureImage[0]=LoadBMP(path)) { Status=true; // Set The Status To TRUE glGenTextures(1,&new_texture->texture); // Create One Textures // Create MipMapped Texture glBindTexture(GL_TEXTURE_2D, new_texture->texture); 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, TextureImage[0]->sizeX, TextureImage[0]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); } if (TextureImage[0]) // If Texture Exists { if (TextureImage[0]->data) // If Texture Image Exists { free(TextureImage[0]->data); // Free The Texture Image Memory } free(TextureImage[0]); // Free The Image Structure } texture_cache.push_back(new_texture); return new_texture; //Return new texture } // ---------------------------------------------------- // // --------- FUNCTION - RESIZE&INIT GL WINDOW --------- // 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(60.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } // ---------------------------------------------------- // GLvoid BuildFont(GLvoid) // Build Our Bitmap Font { HFONT font; // Windows Font ID HFONT oldfont; // Used For Good House Keeping base = glGenLists(96); // Storage For 96 Characters font = CreateFont( -24, // Height Of Font 0, // Width Of Font 0, // Angle Of Escapement 0, // Orientation Angle FW_BOLD, // Font Weight FALSE, // Italic FALSE, // Underline FALSE, // Strikeout ANSI_CHARSET, // Character Set Identifier OUT_TT_PRECIS, // Output Precision CLIP_DEFAULT_PRECIS, // Clipping Precision ANTIALIASED_QUALITY, // Output Quality FF_DONTCARE|DEFAULT_PITCH, // Family And Pitch "Courier New"); // Font Name oldfont = (HFONT)SelectObject(hDC, font); // Selects The Font We Want wglUseFontBitmaps(hDC, 32, 96, base); // Builds 96 Characters Starting At Character 32 SelectObject(hDC, oldfont); // Selects The Font We Want DeleteObject(font); // Delete The Font } GLvoid KillFont(GLvoid) // Delete The Font List { glDeleteLists(base, 96); // Delete All 96 Characters } GLvoid glPrint(const char *fmt, ...) // Custom GL "Print" Routine { char text[256]; // Holds Our String va_list ap; // Pointer To List Of Arguments if (fmt == NULL) // If There's No Text return; // Do Nothing va_start(ap, fmt); // Parses The String For Variables vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers va_end(ap); // Results Are Stored In Text glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits glListBase(base - 32); // Sets The Base Character to 32 glCallLists((GLsizei)strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text glPopAttrib(); // Pops The Display List Bits } // ------------ FUNCTION - SETUP FOR OPENGL ----------- // int InitGL() // All Setup For OpenGL Goes Here { glEnable(GL_TEXTURE_2D); // Enable Texture Mapping //glEnable(GL_LIGHTING); 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 BuildFont(); //Make font list if(fullscreen){ objCamera.Position_Camera(0, 0.25f, 0.0f, 0.0f, 0.25f, -1.0f, 0, 1, 0); } else{ objCamera.Position_Camera(0, 0.25f, 0.0f, -0.7f, 1.25f, -1.0f, 0, 1, 0); } return SetupWorld(); //Load in all info from file } // ---------------------------------------------------- // // ------------ FUNCTION - DRAW EVERYTHING ------------ // 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 #ifdef DEBUG drawDebug(); #endif glColor3f(1.0f,1.0f,1.0f); //Detect if player is jumping and add their jump to y view float mViewy=objCamera.mView.y; float mPosy = objCamera.mPos.y; if(player->jumping){ mViewy+=player->ypos; mPosy+=player->ypos; } gluLookAt(objCamera.mPos.x, mPosy, objCamera.mPos.z, objCamera.mView.x, mViewy, objCamera.mView.z, objCamera.mUp.x, objCamera.mUp.y, objCamera.mUp.z); //Draw all triangles GLfloat x_m, y_m, z_m, u_m, v_m; int numtriangles; numtriangles = sector1.numtriangles; for (int loop_m = 0; loop_m < numtriangles; loop_m++) { glBindTexture(GL_TEXTURE_2D,sector1.triangle[loop_m].texture->texture); //Change in texture only done when glBegin called. 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 } // ---------------------------------------------------- // void drawDebug(){ glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho (0.0, WIDTH, HEIGHT,0.0 , 0.0,1.0f); glMatrixMode(GL_MODELVIEW); glColor3f(1.0, 1.0, 1.0); glRasterPos2i(100, 50); glPrint("Xpos%f,Ypos%f,Zpos%f",objCamera.mPos.x,objCamera.mPos.y+player->ypos,objCamera.mPos.z); // Print GL Text To The Screen glRasterPos2i(800, 50); glPrint("UPS/FPS:%d,%d",perf_measurer->average_ups,perf_measurer->average_fps); glRasterPos2i(100, 100); glPrint("Dist to plane/Colliding:%f,%i",distToPlane,colliding); glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(60.0f,(GLfloat)WIDTH/(GLfloat)HEIGHT,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix glEnable(GL_TEXTURE_2D); } // -------------- FUNCTION - KILL WINDOW -------------- // 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 } } // ---------------------------------------------------- // // ---------- FUNCTION - CREATE GL WINDOW ---------- // 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(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?","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(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 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 //Enable vsync InitVSync(); SetVSyncState(TRUE); 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 }// ------------------------------------------------ // // -------- FUNCTION - CALLBACK MESSAGE HANDLING -------- // 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 paused=FALSE; } else { active=FALSE; // Program Is No Longer Active paused=TRUE; } 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); } // ------------------------------------------------------ // // --------------- FUNCTION - MAIN ---------------- // 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 //Init all objects camera = new Camera(); camera->jumpPosition(0,0,0); timer = new Timer(1000.0f/UPS); //Make timer timer->TimerInit(); //Init timer player = new Player(); player->warpPlayer(0,0,0); mouse = new Mouse(); #ifdef DEBUG perf_measurer = new PerformenceMeasurer(); perf_measurer->game_start_time = timer->TimerGetTime(); perf_measurer->last_sample_time_fps=perf_measurer->last_sample_time_ups =timer->TimerGetTime(); #endif // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,"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("OpenGL Game",WIDTH,HEIGHT,16,fullscreen)) { return 0; // Quit If Window Was Not Created } //Set game start time and update start time and last sample time timer->dwStartTime=timer->TimerGetTime(); #ifdef CONSOLE console = new Console(); console->startConsoleWin(300,50,NULL); #endif 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 { DrawGLScene(); SwapBuffers(hDC); // Swap Buffers (Double Buffering) //Get fps count #ifdef DEBUG perf_measurer->updateFps(timer); #endif // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if (keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=true; // ESC or DrawGLScene Signalled A Quit } //Get time since last update timer->timeSinceLastUpdate = timer->TimerGetTime()-timer->dwStartTime; timer->dwStartTime = timer->TimerGetTime(); //Get ups count #ifdef DEBUG perf_measurer->updateUps(timer); #endif //Update all objects in game and get keyboard input if(paused!=TRUE){update();} } } // Shutdown KillGLWindow(); // Kill The Window return ((int)msg.wParam); // Exit The Program } // ---------------------------------------------------- //