Valid OpenGL context

瘦欲@ 提交于 2019-12-30 07:12:11

问题


How and at what stage is a valid OpenGL context created in my code? I'm getting errors on even simple OpenGL code.


回答1:


From the posts on comp.graphics.api.opengl, it seems like most newbies burn their hands on their first OpenGL program. In most cases, the error is caused due to OpenGL functions being called even before a valid OpenGL context is created. OpenGL is a state machine. Only after the machine has been started and humming in the ready state, can it be put to work.

Here is some simple code to create a valid OpenGL context:

#include <stdlib.h>
#include <GL/glut.h>

// Window attributes
static const unsigned int WIN_POS_X = 30;
static const unsigned int WIN_POS_Y = WIN_POS_X;
static const unsigned int WIN_WIDTH = 512;
static const unsigned int WIN_HEIGHT = WIN_WIDTH;

void glInit(int, char **);

int main(int argc, char * argv[])
{
    // Initialize OpenGL
    glInit(argc, argv);

    // A valid OpenGL context has been created.
    // You can call OpenGL functions from here on.

    glutMainLoop();

    return 0;
}

void glInit(int argc, char ** argv)
{
    // Initialize GLUT
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE);
    glutInitWindowPosition(WIN_POS_X, WIN_POS_Y);
    glutInitWindowSize(WIN_WIDTH, WIN_HEIGHT);
    glutCreateWindow("Hello OpenGL!");

    return;
}

Note:

  • The call of interest here is glutCreateWindow(). It not only creates a window, but also creates an OpenGL context.
  • The window created with glutCreateWindow() is not visible until glutMainLoop() is called.


来源:https://stackoverflow.com/questions/14364/valid-opengl-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!