Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm writing cross-platform (iOS, Android, OSX, Windows) library code that draws its output using OpenGL. I expect my users will often try to call my library's rendering functions without a valid OpenGL context (especially when they are first getting started), so how can I cleanly handle the error?

So far I have tried calling some OpenGL function and then calling glGetError() to see if it failed (and printing my user a helpful error message), but glGetError() segfaults if there is no context:

// Test for OpenGL Context

glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This line segfaults

if (glGetError() != GL_NO_ERROR)
    printf("You tried to call a rendering function but no OpenGL context was found!");

Is there a way to check for a valid context within OpenGL without getting a segfault?

share|improve this question

You can use these vendor specific functions:

  • wglGetCurrentContext() on Windows,
  • aglGetCurrentContext() on OSX,
  • glxGetCurrentContext() on unixoid systems with X and
  • eglGetCurrentContext() on GLES based systems like iOS or Android

They all return NULL (except for eglGetCurrentContext, which returns EGL_NO_CONTEXT) if there is no valid context currently active.

share|improve this answer
    
The problem with this is I don't have any control over the context creation/management. Could I assume that these functions will work however my users decide to create their context? – Dan Halliday Nov 25 '13 at 13:36
1  
No you cannot safely assume that. Depending on what is used to create the context those functions might not even be present. If you don't have control over the context management you can't check the active context directly. But maybe you could make it mandatory for the user to provide a callback that returns whether or not a context is active. – kolrabi Nov 25 '13 at 13:54
    
Ok thanks, that's what I featured looking through the header I found aglGetCurrentContext() in on OSX. It's hard to believe there's no function/macro in the OpenGL API to check current context. Surely, it's just a case of reading one thread-local variable! – Dan Halliday Nov 25 '13 at 14:04
2  
No, it is implementation-dependent, which is why these functions are in the OS-level implementations and not GL itself. – Josh Petrie Nov 25 '13 at 16:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.