-
Notifications
You must be signed in to change notification settings - Fork 0
/
InitShader.cpp
99 lines (78 loc) · 3.1 KB
/
InitShader.cpp
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
#include "Angel-yjc.hpp"
using namespace std;
namespace Angel {
// 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 = new char[size + 1];
fread(buf, 1, size, fp);
buf[size] = '\0';
fclose(fp);
// In case there are illegal non-ASCII characters (due to different
// encoding systems), the following code will replace each of them
// with a space ' '.
for (int i = 0; i < size + 1; i++) {
if (!(buf[i] >= 0 && buf[i] < 128)) buf[i] = ' ';
}
return buf;
}
// Create a GLSL program object from vertex and fragment shader files
GLuint InitShader(const char* vShaderFile, const char* fShaderFile) {
struct Shader {
const char* filename;
GLenum type;
GLchar* source;
} shaders[2] = {{vShaderFile, GL_VERTEX_SHADER, NULL},
{fShaderFile, GL_FRAGMENT_SHADER, NULL}};
GLuint program = glCreateProgram();
for (int i = 0; i < 2; ++i) {
Shader& s = shaders[i];
s.source = readShaderSource(s.filename);
if (shaders[i].source == NULL) {
cerr << "Failed to read " << s.filename << endl;
exit(EXIT_FAILURE);
} else
cout << "Successfully read " << s.filename << endl;
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) {
cerr << s.filename << " failed to compile:" << endl;
GLint logSize;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize);
char* logMsg = new char[logSize];
glGetShaderInfoLog(shader, logSize, NULL, logMsg);
cerr << logMsg << endl;
delete[] logMsg;
exit(EXIT_FAILURE);
} else
cout << "Successfully compiled " << s.filename << endl;
delete[] s.source;
glAttachShader(program, shader);
}
/* link and error check */
glLinkProgram(program);
GLint linked;
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked) {
cerr << "Shader program failed to link" << endl;
GLint logSize;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logSize);
char* logMsg = new char[logSize];
glGetProgramInfoLog(program, logSize, NULL, logMsg);
cerr << logMsg << endl;
delete[] logMsg;
exit(EXIT_FAILURE);
} else
cout << "Successfully linked program object" << endl << endl;
return program;
}
} // namespace Angel