Skip to content

Instantly share code, notes, and snippets.

@branan
Created January 4, 2012 21:56
Show Gist options
  • Save branan/1562391 to your computer and use it in GitHub Desktop.
Save branan/1562391 to your computer and use it in GitHub Desktop.
Example OpenGL3.2 buffer/shader usage
#include <GL/glew.h>
#include <GL/glut.h>
GLfloat vert_data[] = {
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
0.0, 1.0, 0.0,
};
GLfloat col_data[] = {
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0
};
#define POSITION_ATTRIB 0
#define COLOR_ATTRIB 1
const char* vert_shader =
"\
#version 150\n\
\n\
in vec3 position;\n\
in vec3 color;\n\
out vec3 vcol;\n\
\n\
void main(void) { \n\
vcol = color;\n\
gl_Position = vec4(position, 1.0);\n\
}\n\
";
const char* frag_shader =
"\
#version 150\n\
\n\
in vec3 vcol;\n\
out vec4 fcol;\n\
\n\
void main(void) { \n\
fcol = vec4(vcol,1.0);\n\
}\n\
";
void init(void) {
glewInit();
GLuint vao;
GLuint bufs[2];
glGenVertexArrays(1, &vao);
glGenBuffers(2, bufs);
glBindVertexArray(vao);
glEnableVertexAttribArray(POSITION_ATTRIB);
glEnableVertexAttribArray(COLOR_ATTRIB);
glBindBuffer(GL_ARRAY_BUFFER, bufs[0]);
glBufferData(GL_ARRAY_BUFFER, 3*3*sizeof(GLfloat), vert_data, GL_STATIC_DRAW);
glVertexAttribPointer(POSITION_ATTRIB, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, bufs[1]);
glBufferData(GL_ARRAY_BUFFER, 3*3*sizeof(GLfloat), col_data, GL_STATIC_DRAW);
glVertexAttribPointer(COLOR_ATTRIB, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLuint prog;
GLuint vert;
GLuint frag;
prog = glCreateProgram();
vert = glCreateShader(GL_VERTEX_SHADER);
frag = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vert, 1, &vert_shader, 0);
glShaderSource(frag, 1, &frag_shader, 0);
glCompileShader(vert);
glCompileShader(frag);
glAttachShader(prog, vert);
glAttachShader(prog, frag);
glBindAttribLocation(prog, POSITION_ATTRIB, "position");
glBindAttribLocation(prog, COLOR_ATTRIB, "color");
glLinkProgram(prog);
glUseProgram(prog);
}
void render(void) {
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
glutSwapBuffers();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowPosition(0, 0);
glutInitWindowSize(300, 300);
glutCreateWindow("gltext demo");
glutDisplayFunc(render);
init();
glutMainLoop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment