-
Notifications
You must be signed in to change notification settings - Fork 0
/
initShader.c
100 lines (79 loc) · 2.12 KB
/
initShader.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* initShader.c
*
* Created on: Aug 28, 2017
* Author: Thumrongsak Kosiyatrakul
*/
#include "initShader.h"
#include <stdio.h>
#include <stdlib.h>
// Create a NULL-terminated string by reading the provided file
static char *readShaderSource(const char *shaderFile)
{
FILE *fp = fopen(shaderFile, "r");
if (fp == NULL)
return NULL;
fseek(fp, 0L, SEEK_END);
long size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char *buf = (char *)malloc(size + 1);
fread(buf, 1, size, fp);
buf[size] = '\0';
fclose(fp);
return buf;
}
// Create a GLSL program object from vertex and fragment shader files
GLuint initShader(const char *vShaderFile, const char *fShaderFile)
{
int i;
struct Shader shaders[2] = {
{vShaderFile, GL_VERTEX_SHADER, NULL},
{fShaderFile, GL_FRAGMENT_SHADER, NULL}};
GLuint program = glCreateProgram();
for (i = 0; i < 2; ++i)
{
struct Shader s = shaders[i];
s.source = readShaderSource(s.filename);
if (s.source == NULL)
{
fprintf(stderr, "Failed to read %s\n", s.filename);
exit(EXIT_FAILURE);
}
GLuint shader = glCreateShader(s.type);
glShaderSource(shader, 1, (const GLchar **)&s.source, NULL);
glCompileShader(shader);
GLint compiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled)
{
fprintf(stderr, "%s failed to compile:\n", s.filename);
GLint logSize;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize);
char *logMsg = (char *)malloc(logSize);
glGetShaderInfoLog(shader, logSize, NULL, logMsg);
fprintf(stderr, "%s\n", logMsg);
free(logMsg);
exit(EXIT_FAILURE);
}
free(s.source);
glAttachShader(program, shader);
}
/* link and error check */
glLinkProgram(program);
GLint linked;
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked)
{
fprintf(stderr, "Shader program failed to link\n");
GLint logSize;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logSize);
char *logMsg = (char *)malloc(logSize);
glGetProgramInfoLog(program, logSize, NULL, logMsg);
fprintf(stderr, "%s\n", logMsg);
free(logMsg);
exit(EXIT_FAILURE);
}
/* use program object */
glUseProgram(program);
return program;
}