OpenGL Errors
Detecting OpenGL errors has been a common problem, since
OpenGL does not give you error messages unless you ask for them.
Even if you don't have any visual problems in your code,
resolving OpenGL errors is still important, because
most OpenGL implementations generate error codes without waiting for you
to ask for them, and this may affect the performance of your code.
This solution provides a simple way to retrieve OpenGL error strings
that help you locate the problem.
1. Retrieving OpenGL Errors
OpenGL errors can be retrieved using glGetError function, which
returns a GLenum value that can be converted to a string
using gluErrorString function as follows:
GLenum error = glGetError();
cout << gluErrorString( error );
2. Simple Error Checking
For keeping things simple I prefer to use the following macro:
#define CHECK_OPENGL_ERROR \
{ GLenum error; \
while ( (error = glGetError()) != GL_NO_ERROR) { \
printf( "OpenGL ERROR: %s\nCHECK POINT: %s (line %d)\n", \
gluErrorString(error), __FILE__, __LINE__ ); \
} \
}
Simply copy and paste it into one of your source files,
preferably a header file that all other OpenGL related source files include.
Then place CHECK_OPENGL_ERROR before and after suspicious
OpenGL calls. For example, the following code calls glTranslatef
between glBegin and glEnd, which is invalid.
To detect this error, we place two CHECK_OPENGL_ERROR lines
as follows:
CHECK_OPENGL_ERROR
glBegin( GL_POINTS );
glVertex3f( 1.0f, 0.0f, 0.0f );
glTranslatef( 2.0f, 2.0f, 2.0f );
glVertex3f( 1.0f, 0.0f, 0.0f );
glEnd();
CHECK_OPENGL_ERROR
When you execute this code, it prints "invalid operation" with the source
file name and the line number where the second CHECK_OPENGL_ERROR is
placed. Note that, CHECK_OPENGL_ERROR only prints the errors that
occurred before the macro. Therefore, to be able to locate the error we
need to use two CHECK_OPENGL_ERROR macros as shown above. If the first
one does not generate an error message, we can be sure that the error
happens between the two CHECK_OPENGL_ERROR macros.
3. Removing Error Checking
Once you make sure that your code does not have OpenGL errors, you may want
to disable the error checking. One way to do it is, of course, deleting all
the CHECK_OPENGL_ERROR lines. However, you may want to
enable them later, after you make couple more changes in the code.
Here I will offer another simple way to disable the error checking
without actually removing CHECK_OPENGL_ERROR lines:
#ifndef DISABLE_CHECK_OPENGL_ERROR
#define CHECK_OPENGL_ERROR \
{ GLenum error; \
while ( (error = glGetError()) != GL_NO_ERROR) { \
printf( "OpenGL ERROR: %s\nCHECK POINT: %s (line %d)\n", \
gluErrorString(error), __FILE__, __LINE__ ); \
} \
}
#else
#define CHECK_OPENGL_ERROR
#endif
Here, just by uncommenting the first line you can disable all OpenGL error
checking.
|