讨厌做一个"找到我的错误"发布,但互联网似乎严重缺乏任何超简单的OpenGL ES2三角绘图的例子。 从技术上讲,这是使用OpenGL 2.1,但OpenGL ES2只是其中的一部分......对吗?
无论如何,这是我的代码(我删除了记录/错误检查,我知道它通过了)
#include <SDL.h>
#include <SDL_opengl.h>
int main(int argc, char* argv[])
{
SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION,2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION,1);
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL,1);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
SDL_Window* window = SDL_CreateWindow("Test", 0,0,100,100, SDL_WINDOW_OPENGL);
SDL_GLContext gl = SDL_GL_CreateContext(window);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
GLuint gl_program_id;
GLuint gl_vs_id;
GLuint gl_fs_id;
GLuint gl_pos_attrib_id;
GLuint gl_pos_buff_id;
char vs_file[2048]; //assume I successfully loaded vertex shader code into this array
char *vs_file_p = &vs_file[0];
char fs_file[2048]; //assume I successfully loaded fragment shader code into this array
char *fs_file_p = &fs_file[0];
gl_vs_id = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(gl_vs_id, 1, &vs_file_p, NULL);
glCompileShader(gl_vs_id);
gl_fs_id = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(gl_fs_id, 1, &fs_file_p, NULL);
glCompileShader(gl_fs_id);
gl_program_id = glCreateProgram();
glAttachShader(gl_program_id, gl_vs_id);
glAttachShader(gl_program_id, gl_fs_id);
glLinkProgram(gl_program_id);
glDeleteShader(gl_vs_id);
glDeleteShader(gl_fs_id);
glUseProgram(gl_program_id);
gl_pos_attrib_id = glGetAttribLocation(gl_program_id, "position");
float verts[] = {0.0,0.0,0.5,1.0,1.0,0.0};
glGenBuffers(1, &gl_pos_buff_id);
glBindBuffer(GL_ARRAY_BUFFER, gl_pos_buff_id);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*3, verts, GL_STATIC_DRAW);
glVertexAttribPointer(gl_pos_attrib_id, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(gl_pos_attrib_id);
glViewport(0,0,100,100);
glClearColor(0.,0.,0.,1.);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(gl_program_id);
glBindBuffer(GL_ARRAY_BUFFER, gl_pos_buff_id);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*3, verts, GL_STATIC_DRAW);
glVertexAttribPointer(gl_pos_attrib_id, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(gl_pos_attrib_id);
glDrawArrays(GL_TRIANGLES,0,3*3);
SDL_GL_SwapWindow(window);
//while loop waiting on input to quit goes here...
SDL_GL_DeleteContext(gl);
SDL_Quit();
exit(0);
return 0;
}
我的着色器如下:
顶点:
#version 110
attribute vec2 position;
void main()
{
gl_Position = vec4(position,1.,1.);
}
片段:
#version 110
void main()
{
gl_FragColor = vec4(1.);
}
另一个注意事项是所有着色器都编译,程序编译,上下文和窗口创建都顺利完成。它最终只有一个黑色的100x100px窗口。任何帮助将不胜感激!
(另外,如果有人可以在opengl es2上推荐体面,一致,直接的文档资源,这将非常棒。版本/平台之间的文档很多不一致。谢谢!)