-
Notifications
You must be signed in to change notification settings - Fork 0
/
CompileShaders.cpp
76 lines (62 loc) · 2.11 KB
/
CompileShaders.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
#include "CompileShaders.h"
// STL
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
string
parseShader(const string& _shader) {
ifstream ifs(_shader);
ostringstream oss;
oss << ifs.rdbuf();
return oss.str();
}
GLuint
compileProgram(const string& _vertexShader,
const string& _fragmentShader) {
int success;
char infoLog[512];
// Compile the vertex shader
string vertexShaderFromFile = parseShader(_vertexShader);
const char* prog = vertexShaderFromFile.c_str();
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &prog, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success) {
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
cerr << "Error compiling vertex shader '" << _vertexShader
<< "'\n" << infoLog << endl;
exit(1);
}
// Compile the fragment shader
string fragmentShaderFromFile = parseShader(_fragmentShader);
prog = fragmentShaderFromFile.c_str();
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &prog, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if(!success) {
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
cerr << "Error compiling fragment shader '" << _fragmentShader
<< "'\n" << infoLog << endl;
exit(1);
}
// Link the vertex and fragment shader into a shader program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
cerr << "Error linking programs '" << _vertexShader
<< "' and '" << _fragmentShader << "'\n" << infoLog << endl;
exit(1);
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// Normally return, and specify this when needed
glUseProgram(shaderProgram);
return shaderProgram;
}