invisible

view src/sdr.cc @ 25:96b022f1210e

'w' to switch to wireframe
author Eleni Maria Stea <eleni@mutantstargoat.com>
date Sun, 17 Nov 2013 12:46:45 +0200
parents 38bf3eec0fac
children
line source
1 #include <GL/glew.h>
2 #include <GL/gl.h>
4 #include <errno.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #include "sdr.h"
11 char* sdr_load(const char* fname)
12 {
13 if(!fname) {
14 return 0;
15 }
17 FILE *fp;
18 int ctr = 0;
20 if(!(fp = fopen(fname, "rb"))) {
21 fprintf(stderr, "Failed to open file %s: %s\n", fname, strerror(errno));
22 return 0;
23 }
24 fseek(fp, 0, SEEK_END);
25 ctr = ftell(fp);
26 rewind(fp);
28 char *glsl;
29 if(!(glsl = (char*) malloc(ctr + 1))) {
30 perror("Failed to allocate memory");
31 return 0;
32 }
33 fread(glsl, 1, ctr, fp);
34 fclose(fp);
36 glsl[ctr] = 0;
38 return glsl;
39 }
41 bool sdr_compile(unsigned int sdr)
42 {
43 int status, loglen;
44 char infolog[512];
46 glCompileShader(sdr);
47 glGetShaderiv(sdr, GL_COMPILE_STATUS, &status);
48 glGetShaderInfoLog(sdr, sizeof infolog, &loglen, infolog);
49 if(status == GL_FALSE) {
50 fprintf(stderr, "Failed to compile shader: %s\n", infolog);
51 return false;
52 } else if(loglen) {
53 fprintf(stderr, "%s\n", infolog);
54 }
55 return true;
56 }
58 unsigned int sdr_getprog(const char* vfname, const char* ffname)
59 {
60 char *vsdr_glsl = NULL;
61 char *fsdr_glsl = NULL;
63 GLuint vsdr; GLuint fsdr;
64 vsdr = glCreateShader(GL_VERTEX_SHADER);
65 fsdr = glCreateShader(GL_FRAGMENT_SHADER);
67 if(!(vsdr_glsl = sdr_load(vfname)))
68 return 0;
69 if(!(fsdr_glsl = sdr_load(ffname)))
70 return 0;
72 glShaderSource(vsdr, 1, (const GLchar**)&vsdr_glsl, NULL);
73 glShaderSource(fsdr, 1, (const GLchar**)&fsdr_glsl, NULL);
75 free(vsdr_glsl);
76 free(fsdr_glsl);
78 if(!sdr_compile(vsdr)) {
79 fprintf(stderr, "Shader %s failed to compile.\n", vfname);
80 return 0;
81 }
82 if(!sdr_compile(fsdr)) {
83 fprintf(stderr, "Shader %s failed to compile.\n", ffname);
84 return 0;
85 }
87 unsigned int sprog;
88 int status, loglen;
89 char infolog[512];
91 sprog = glCreateProgram();
92 glAttachShader(sprog, vsdr);
93 glAttachShader(sprog, fsdr);
94 glLinkProgram(sprog);
95 glGetProgramiv(sprog, GL_LINK_STATUS, &status);
96 glGetProgramInfoLog(sprog, sizeof infolog, &loglen, infolog);
97 if(status == GL_FALSE) {
98 fprintf(stderr, "Error while linking shader program:\n%s\n", infolog);
99 return 0;
100 } else if(loglen) {
101 fprintf(stderr, "%s\n", infolog);
102 }
103 return sprog;
104 }