-
Notifications
You must be signed in to change notification settings - Fork 1
/
ShaderBase.cpp
91 lines (80 loc) · 2.33 KB
/
ShaderBase.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
#include "ShaderBase.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
GLuint ShaderBase::compile(GLuint type, const std::string &path) {
std::ifstream reader(path);
if (!reader.good()) {
std::cerr << "Bad reader to path: " << path << "?" << std::endl;
return GL_NONE;
}
GLuint shader = glCreateShader(type);
std::stringstream ss;
ss << reader.rdbuf();
std::string str = ss.str();
const char *raw = str.c_str();
glShaderSource(shader, 1, &raw, nullptr);
glCompileShader(shader);
GLint state = GL_FALSE;
glGetShaderiv(shader, GL_COMPILE_STATUS, &state);
if (state == GL_FALSE) {
char log[512] = {0};
glGetShaderInfoLog(shader, sizeof(log), nullptr, log);
std::cerr << "Failed to compile " << path << "?: " << log << std::endl;
glDeleteShader(shader);
return GL_NONE;
}
return shader;
}
GLuint ShaderBase::link(GLuint vertexShader, GLuint fragmentShader) {
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
GLint state = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &state);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
if (state == GL_FALSE) {
char log[512] = {0};
glGetProgramInfoLog(program, sizeof(log), nullptr, log);
std::cerr << "Failed to link program?: " << log << std::endl;
glDeleteProgram(program);
return GL_NONE;
}
return program;
}
ShaderBase::~ShaderBase()
{
if (_valid)
{
glDeleteProgram(_program);
}
}
void ShaderBase::update(const WindowBase &window)
{
}
void ShaderBase::use(const DrawBase &draw)
{
if (_valid)
{
glUseProgram(_program);
}
}
ShaderBase::ShaderBase(const std::string &vertexShaderPath, const std::string &fragmentShaderPath)
{
GLuint vs = ShaderBase::compile(GL_VERTEX_SHADER, vertexShaderPath);
GLuint fs = ShaderBase::compile(GL_FRAGMENT_SHADER, fragmentShaderPath);
if (vs == GL_NONE || fs == GL_NONE)
{
std::cerr << "Invalid shaders supplied?" << std::endl;
return;
}
_program = ShaderBase::link(vs, fs);
if (_program == GL_NONE)
{
std::cerr << "Invalid program?" << std::endl;
return;
}
_valid = true;
}