volmetrics
view src/sdr.cc @ 37:1d935677d3ab
Created new branch non-qt-version
author | Eleni Maria Stea <elene.mst@gmail.com> |
---|---|
date | Mon, 17 Apr 2017 13:26:24 +0000 |
parents | 4e120dcd55ec |
children |
line source
1 #include "opengl.h"
3 #include <errno.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 #include "sdr.h"
10 char* sdr_load(const char* fname)
11 {
12 if(!fname) {
13 return 0;
14 }
16 FILE *fp;
17 int ctr = 0;
19 if(!(fp = fopen(fname, "rb"))) {
20 fprintf(stderr, "Failed to open file %s: %s\n", fname, strerror(errno));
21 return 0;
22 }
23 fseek(fp, 0, SEEK_END);
24 ctr = ftell(fp);
25 rewind(fp);
27 char *glsl;
28 if(!(glsl = (char*) malloc(ctr + 1))) {
29 perror("Failed to allocate memory");
30 return 0;
31 }
32 fread(glsl, 1, ctr, fp);
33 fclose(fp);
35 glsl[ctr] = 0;
37 return glsl;
38 }
40 bool sdr_compile(unsigned int sdr)
41 {
42 int status, loglen;
43 char infolog[512];
45 glCompileShader(sdr);
46 glGetShaderiv(sdr, GL_COMPILE_STATUS, &status);
47 glGetShaderInfoLog(sdr, sizeof infolog, &loglen, infolog);
48 if(status == GL_FALSE) {
49 fprintf(stderr, "Failed to compile shader: %s\n", infolog);
50 return false;
51 } else if(loglen) {
52 fprintf(stderr, "%s\n", infolog);
53 }
54 return true;
55 }
57 unsigned int sdr_getprog(const char* vfname, const char* ffname)
58 {
59 char *vsdr_glsl = NULL;
60 char *fsdr_glsl = NULL;
62 GLuint vsdr; GLuint fsdr;
63 vsdr = glCreateShader(GL_VERTEX_SHADER);
64 fsdr = glCreateShader(GL_FRAGMENT_SHADER);
66 if(!(vsdr_glsl = sdr_load(vfname)))
67 return 0;
68 if(!(fsdr_glsl = sdr_load(ffname)))
69 return 0;
71 glShaderSource(vsdr, 1, (const GLchar**)&vsdr_glsl, NULL);
72 glShaderSource(fsdr, 1, (const GLchar**)&fsdr_glsl, NULL);
74 free(vsdr_glsl);
75 free(fsdr_glsl);
77 if(!sdr_compile(vsdr)) {
78 fprintf(stderr, "Shader %s failed to compile.\n", vfname);
79 return 0;
80 }
81 if(!sdr_compile(fsdr)) {
82 fprintf(stderr, "Shader %s failed to compile.\n", ffname);
83 return 0;
84 }
86 unsigned int sprog;
87 int status, loglen;
88 char infolog[512];
90 sprog = glCreateProgram();
91 glAttachShader(sprog, vsdr);
92 glAttachShader(sprog, fsdr);
93 glLinkProgram(sprog);
94 glGetProgramiv(sprog, GL_LINK_STATUS, &status);
95 glGetProgramInfoLog(sprog, sizeof infolog, &loglen, infolog);
96 if(status == GL_FALSE) {
97 fprintf(stderr, "Error while linking shader program:\n%s\n", infolog);
98 return 0;
99 } else if(loglen) {
100 fprintf(stderr, "%s\n", infolog);
101 }
102 return sprog;
103 }