7 static GLuint compile_and_attach_shader(GLenum type, const char *path, const char *name, GLuint program)
9 char full_path[strlen(path) + 1 + strlen(name) + 1 + 4 + 1];
10 sprintf(full_path, "%s/%s.glsl", path, name);
12 FILE *file = fopen(full_path, "r");
18 if (fseek(file, 0, SEEK_END) == -1) {
24 long size = ftell(file);
32 if (fseek(file, 0, SEEK_SET) == -1) {
40 if (fread(code, 1, size, file) != (size_t) size) {
48 GLuint id = glCreateShader(type);
50 char const *codeptr = code;
51 const int isize = (int) size;
52 glShaderSource(id, 1, &codeptr, &isize);
57 glGetShaderiv(id, GL_COMPILE_STATUS, &success);
60 glGetShaderInfoLog(id, BUFSIZ, NULL, errbuf);
61 fprintf(stderr, "Failed to compile %s shader: %s\n", name, errbuf);
66 glAttachShader(program, id);
72 ShaderProgram *create_shader_program(const char *path)
74 GLuint id = glCreateProgram();
78 if (! (vert = compile_and_attach_shader(GL_VERTEX_SHADER, path, "vertex", id))) {
83 if (! (frag = compile_and_attach_shader(GL_FRAGMENT_SHADER, path, "fragment", id))) {
94 glGetProgramiv(id, GL_LINK_STATUS, &success);
97 glGetProgramInfoLog(id, BUFSIZ, NULL, errbuf);
98 fprintf(stderr, "Failed to link shader program: %s\n", errbuf);
103 ShaderProgram *prog = malloc(sizeof(ShaderProgram));
105 prog->loc_model = glGetUniformLocation(id, "model");
106 prog->loc_view = glGetUniformLocation(id, "view");
107 prog->loc_projection = glGetUniformLocation(id, "projection");
112 void delete_shader_program(ShaderProgram *prog)
114 glDeleteProgram(prog->id);