Sign in to follow this  

OpenGL Problem with glBegin(GL_TRIANGLES)

Recommended Posts

I've been trying to learn OpenGL so I was using NeHe's guide to help. So I'm on lesson #2, and I just recently compiled the code to see if everything works so far. Now, using Dev-C++ I get an error from the following code:
    glBegin(GL_TRIANGLES);                               //Drawing using triangles
            glVertex3f(0.0f,1.0f,0.0f);                  //Top
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom left
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottomg right
It says that there is a syntax error in glBegin() before the '(' token. Does anybody know what is wrong with this? I have it exzctly as it says in the tuturial and it simply will not accept that line of code ... EDIT: Ugh I'm so stupid, I had an error like 3 lines before it where I forgot the ";" :( EDIT #2: Ok I figured now would be a good time to ask this question as well. I get en error with the:
part. A undefined refrence error @32. Here is the total code (some written, some copied and pasted)
 *		This Code Was Created By Jeff Molofee 2000
 *		A HUGE Thanks To Fredric Echols For Cleaning Up
 *		And Optimizing This Code, Making It More Flexible!
 *		If You've Found This Code Useful, Please Let Me Know.
 *		Visit My Site At

#include <windows.h>		// Header File For Windows
#include <gl\gl.h>			// Header File For The OpenGL32 Library
#include <gl\glu.h>			// Header File For The GLu32 Library
//#include <gl\glaux.h>		// Header File For The Glaux Library

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	keys[256];			// Array Used For The Keyboard Routine
bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default


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

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix
//setup for OpenGL
int InitGL(GLvoid)
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClearDepth(1.0f);            //Depth Buffer Setup
    glEnable(GL_DEPTH_TEST);       //Enables Depth Testing
    glDepthFunc(GL_LEQUAL);        //The type of depth test to do
   	return TRUE;				  // Initialization Went OK

int DrawGLScene(GLvoid)
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);    //Clear the screen and the depth buffer
    glLoadIdentity();                                    //Reset the view
    glTranslatef(-1.5f,0.0f,-6.0f);                      //Move left 1.5 units and into the screen 6.0 units
    glBegin(GL_TRIANGLES);                               //Drawing using triangles
            glVertex3f(0.0f,1.0f,0.0f);                  //Top
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom left
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottomg right
    glEnd();                                             //Finished drawing the triangle
    glTranslatef(3.0f,0.0f,0.0f);                        //Move right 3 units
    glBegin(GL_QUADS);                                   //Draw a Quad
            glVertex3f(-1.0f,1.0f,0.0f);                 //Top Left
            glVertex3f(1.0f,1.0f,0.0f);                  //Top Right
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottom Left
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom Right
    glEnd();                                             //Finished Drawing the triangle
    return TRUE;                                         //Keep going

void KillGLWindow(GLvoid)
    if (fullscreen)
    if (hRC)
        if (!wglMakeCurrent(NULL,NULL))
                MessageBox(NULL,"Release of DC and RC failes.","SHUTDOWN ERROR",
                MB_OK | MB_ICONINFORMATION);
        if (!wglDeleteContext(hRC))
                MessageBox(NULL,"Release of Rendering Context Failed.","Shutdown Error",
                MB_OK | MB_ICONINFORMATION);
    if (hDC && !ReleaseDC(hWnd,hDC))
        MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERR",
    if (hWnd && !DestroyWindow(hWnd))
        MessageBox(NULL,"Could NOt Release hWnd.","SHUTDOWN ERR",
    if (!UnregisterClass("OpenGL",hInstance))
        MessageBox(NULL,"Couldn't unregister class.","SHUTDOWN ERR",

//not to create the godblessed window
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
    GLuint  PixelFormat;        //holds the results after searing for a match
    WNDCLASS	wc;
    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;    //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 instnace for our window			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;    //Redraw on Move, 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 daya
    wc.hInstance    = hInstance;    //Set the instance
    wc.hIcon    = LoadIcon(NULL, IDI_WINLOGO); //Load the default icon
    wc.hCursor    = LoadCursor(NULL, IDC_ARROW); //Load Arrow Pointer
    wc.hbrBackground    =NULL;    //No background required for GL
    wc.lpszMenuName    =NULL;    //we dont want a menu
    wc.lpszClassName    ="OpenGL";    //Set the Class Name
    //The Following code will result in an error message in the even anything goes wrong
    //If it does go wrong, pressing the OK box will close the program
    if (!RegisterClass(&wc))    //This will tell us if the attempt to register the class failed
        MessageBox(NULL,"Failed to Register the Window CLass.","ERROR",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    //Checks if the program should run in fullscreen or windowed mode, should go into full screen
    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 Sceen Width
        dmScreenSettings.dmPelsHeight=height;        //selected screen height
        dmScreenSettings.dmBitsPerPel=bits;        //selected Bits per pixel
        //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 Run in a window.
                if (MessageBox(NULL,"Use Windowed mode instead?","NEHE GL", MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
                        fullscreen=FALSE;                //Selected Window mode (FULLSCREEN=FALSE)
                        //Pop up a messagebox to let user know program is going byebye
                        MessageBox(NULL,"Program is going byebye now.","Sucker...",MB_OK|MB_ICONSTOP);
                        return FALSE;                        //exist and return FALSE, GG noob comp
	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
		dwExstyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended style
		dwstyle=WS_OVERLAPPEDWINDOW;							// Windows style
    //Makes all things the speacified resolution
    AdjustWindowRectEx(&WindowRect, dwstyle, FALSE, dwExstyle);       //Adjust window to true requested size
    if (!(hWnd=CreateWindowEx(    dwExstyle,                 //Extended style for windows
                                  "OpenGL",                  //CLass name
                                  title,                     //Window Title
                                  WS_CLIPSIBLINGS |          //Required Window style
                                  WS_CLIPCHILDREN |          //Required Window style
                                  dwstyle,                   //Selected Window Stlye
                                  0, 0,                      //Window Postion
                                  WindowRect.right-WindowRect.left,                 //Calculage Adjusted Window Width
                        ,                 //Calculate Adjusted 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;
    /*04/12/04 16:00*/
    /*This section of code describes a Pixel Format. Using a format that supports OPenGL and double buffering
     * We try to find a pixel format that matches the bits we deced on (16,24,32). Finally we set up a 16bit z-buffer.
     *The remaining paramets are eighre not used or not important
    static PIXELFORMATDESCRIPTOR pfd=     //pfd tells the windows how we want stuff to be
        sizeof(PIXELFORMATDESCRIPTOR),    //size of this pixel format dexriptor
        1,                                //Verstion of 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,                   //Requests  an RGBA format
        bits,                           //Select our color depth
        0, 0, 0, 0, 0, 0,                //Color bits ignored
        0,                                //No alpha buffer
        0,                                //shift bits ignored
        0,                                //No accumilation 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 later
        0,                                //Reserved
        0,0,0                             //Layer masks ignroed
    /*If there were no erros while creating the window, we'll attempt to get an OpenGL device context
     *if we cant get a DC an error messae will pop up and program will quit*/
     if(!(hDC=GetDC(hWnd)))     //Did we get a device context?
          KillGLWindow();     //Reset the display'
          return FALSE;          //Return false and close the program
     /***IF we managed to get a device context for our OpenGL window we'll try to find a pixel forma that matches the one
      *described above. If Windows can't find a mataching pixel format, an error message will pop up and the program will
      *quit (return false)***/
     if(!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))      //Did windows find a mataching pixel format?
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't find a suitable PixelFormat.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return False (duh?)
     /***If windows found a pixel format we'll try setting the pixel format, blah blah blah error etc.***/
     if(!SetPixelFormat(hDC,PixelFormat,&pfd))     //Are we able to set the Pixel Format?
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't set the PixelFormat.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     /*If pixel format was set properly we'll try to get a rednering context. If we can't get a rendering context ANOTHER
      *ERROR will pop up and the program will, once again, close*/
     if(!(hRC=wglCreateContext(hDC)))      //Are we able to get a rendering Context?
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Cant create a GL Rendering Context.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     /*IF there are no errors so far, and we've manated to create both a Device Context and a rednering context all we have
      *to do now is make the rendering context active. If we can't make the rendering context active an error message will
      *pop up on the screen and the program will quit*/
     if(!wglMakeCurrent(hDC,hRC))      //Try to active the rendering context
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't activate the GL Rendering Context.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     /*If everything went somoothly, and our OpenGL window was created we'll show the window, set it to be the foreground,
      *and set the focus on that window, then we'll call ReSizeG:SCene passing the screen width and height to set up our
      *perspective OpenGL sceren*/
     ShowWindow(hWnd,SW_SHOW);      //show the window
     SetForegroundWindow(hWnd);     //Slighlt higher priority
     SetFocus(hWnd);               //Sets the keboad focus to the window
     ReSizeGLScene(width, height); //set up our perspective GL Screen
     /*FINALLY, we jump to InitGL() where can set up lighting, texture, and anything else that needs to be setup. */
     if(!InitGL())     //Initialize our newly created GL Window
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Initialization Failed.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return False
     /*If it has gone this far, it is safe to assume window creation was succesful, we return true to WinMain() preventing it
      *(the program) from crashing*/
     return TRUE;      //Success!
//05/12/04 12:40
/*The next part is where all the window messages are dealth with. When we registeeed the window class we told it to come here 
 *to deal with window message */
/*+++BEGIN CASES+++*/
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 winows messages
            case WM_ACTIVATE: //watch for window activate message
                 if(!HIWORD(wParam))  //Check for Minimization state
                      active=TRUE;  //Program is active
                     active=FALSE;  //Program is no longer active
                 return 0;
            case WM_SYSCOMMAND:     //intercept System COmmands
                 switch (wParam)    //Check system calls
                        case SC_SCREENSAVE: //Screensaver is trying to start
                        case SC_MONITORPOWER:             //Monitor trying to enter powersave?
                        return 0;                         //prevent from happenning
            case WM_CLOSE:     //Did we receive a cloase 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_SIZE:            //Resize the OpenGL Window
                 ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); //LoWord=width, Hiord=Height
                 return 0;                                     //jump back
     //pass all unhandled mesages to DefWindowProc
     return DefWindowProc(hWnd,uMsg,wParam,lParam);
/*+++END CASES+++*/

/*This is the entry point of our Windows Application. This is where we call our window creation routine, deal with window
 messages, and watch for human interaction.*/
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 variablo to exit loop
     //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("NeHe's OpenGL Freamework",640,480,16,fullscreen))
          return 0;             //Windowed Mode
     while(!done)               //Loop that runs until done=TRUE
          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 form DrawGLScene()
                   if (active)       //Program active?
                        if(keys[VK_ESCAPE])    //Was ESC pressed?
                             done=TRUE;        //ESC signalled a quit
                             else              //Not time to quit, update screne
                                  DrawGLScene();     //Draw The Scene 
                                  SwapBuffers(hDC);  //Swap Buffers
                        //now to allow for switching between fullscreen and windoed
			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("NeHe's OpenGL Framework",640,480,16,fullscreen))
					return 0;						// Quit If Window Was Not Created
         //if Done=TRUE program should quit
          KillGLWindow();        //Kill the window
          return(msg.wParam);   //Exit the program

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By test opty
      Hi all,
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
  • Popular Now