-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathShader.cpp
More file actions
79 lines (67 loc) · 2.29 KB
/
Copy pathShader.cpp
File metadata and controls
79 lines (67 loc) · 2.29 KB
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
#include "shader.h"
std::string get_file_contents(const char* filename) {
std::ifstream in(filename, std::ios::binary);
if (in) {
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
}
Shader::Shader(const char* vertexFile, const char* fragmentFile) {
std::string vertexCode = get_file_contents(vertexFile);
std::string fragmentCode = get_file_contents(fragmentFile);
//Conversion from std::string to const char*
const char* vertexSource = vertexCode.c_str();
const char* fragmentSource = fragmentCode.c_str();
// Vertex Shader attaching and creation
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, NULL);
glCompileShader(vertexShader);
compileErrors(vertexShader, "VERTEX");
// Fragment shader attaching and creation
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
glCompileShader(fragmentShader);
compileErrors(fragmentShader, "FRAGMENT");
// Shader Program creation and linking
ID = glCreateProgram();
glAttachShader(ID, vertexShader);
glAttachShader(ID, fragmentShader);
glLinkProgram(ID);
compileErrors(ID, "PROGRAM");
// Delete shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
void Shader::Activate() {
glUseProgram(ID);
}
void Shader::Delete() {
glDeleteProgram(ID);
}
void Shader::SetVec3(const std::string& name, const glm::vec3& value) {
glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void Shader::compileErrors(unsigned int shader, const char* type) {
GLint hasCompiled;
char infoLog[1024];
if (type != "PROGRAM") {
glGetShaderiv(shader, GL_COMPILE_STATUS, &hasCompiled);
if (hasCompiled == GL_FALSE) {
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "SHADER_COMPILATION_ERROR for:" << type << "\n" << infoLog << std::endl;
}
}
else {
glGetProgramiv(shader, GL_LINK_STATUS, &hasCompiled);
if (hasCompiled == GL_FALSE) {
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
std::cout << "SHADER_LINKING_ERROR for:" << type << "\n" << infoLog << std::endl;
}
}
}