Skip to content

Instantly share code, notes, and snippets.

@andy-thomason
Created July 25, 2017 10:45
Show Gist options
  • Save andy-thomason/98c8a4d17c18084280190d879c6789cf to your computer and use it in GitHub Desktop.
Save andy-thomason/98c8a4d17c18084280190d879c6789cf to your computer and use it in GitHub Desktop.
Short SDL triangle example
#define GL_GLEXT_PROTOTYPES 1
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengles2.h>
int main() {
auto window = SDL_CreateWindow(
"triangle", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
512, 512, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
);
auto glcontext = SDL_GL_CreateContext(window);
GLuint vbo = 0;
glGenBuffers(1, &vbo);
static const float vertices[] = { 0.0f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f };
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
auto vertexSource =
"attribute vec4 pos;\n"
"void main() { gl_Position = pos; }\n"
;
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, nullptr);
glCompileShader(vertexShader);
auto fragmentSource =
"void main() { gl_FragColor = vec4(1, 0, 0, 1); }\n"
;
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, nullptr);
glCompileShader(fragmentShader);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
auto posAttr = glGetAttribLocation(shaderProgram, "pos");
for(;;) {
SDL_Event e;
while(SDL_PollEvent(&e)) {
if(e.type == SDL_QUIT) return 0;
}
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glEnableVertexAttribArray(posAttr);
glVertexAttribPointer(posAttr, 2, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
SDL_GL_SwapWindow(window);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment