无法使 OpenGL、glew 和 SDL2 协同工作

Can't make OpenGL, glew, and SDL2 work together

// SDL 2.0.6, glew 2.1.0

SDL_Init(SDL_INIT_EVENTS | SDL_INIT_VIDEO);

SDL_Window *w = SDL_CreateWindow("Open GL", 0, 0, 1000, 1000, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

SDL_GLContext ctx = SDL_GL_CreateContext(w);

// values returned by SDL_GL_GetAttribute are commented
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // doesn't help
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_CONTEXT_MAJOR_VERSION, 4); // 4
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_CONTEXT_MINOR_VERSION, 5); // 5, these two accept even 10.10 without error actually, I also tried not calling them and had 2.1 in return
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_DOUBLEBUFFER, 1); // 1
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_RED_SIZE, 8); // 8
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_GREEN_SIZE, 8); // 8
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_BLUE_SIZE, 8); // 8
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_DEPTH_SIZE, 24); // 16
SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_STENCIL_SIZE, 8); // 0

//SDL_GLContext ctx = SDL_GL_CreateContext(w); // nothing gets rendered if this is called here instead

//SDL_GL_MakeCurrent(w, ctx); // doesn't help

if (ctx == 0){ // never fails
    cout << "context creation error" << endl;
}

glewExperimental = true;
GLenum e = GLEW_OK;
e = glewInit();
if (e != GLEW_OK){ // never fails
    cout << "glew error" << endl;
}

我的模板缓冲区没有工作,所以我在调查中遇到了这个问题。所有 SDL_GL_SetAttribute 函数 return 0。相同的代码(不包括 glew)已在 Ubuntu 和 returns 24/8 for depth/stencil 的笔记本电脑上进行了测试。我做错了什么?

documentation of SDL_GL_SetAttribute 状态

Use this function to set an OpenGL window attribute before window creation.

如果在创建 window 之后调用此函数,则没有任何效果。

您不能更改现有上下文的属性。 SDL_GL_SetAttribute 将设置 SDL 将在下次创建 GL 上下文时使用的属性。

现在您实际上稍后尝试创建上下文:

//SDL_GLContext ctx = SDL_GL_CreateContext(w); // nothing gets rendered if this is called here instead

最可能的解释是

SDL_GL_SetAttribute(SDL_GLattr::SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // doesn't help

确实有效,只是您的代码与核心配置文件不兼容。