-
Notifications
You must be signed in to change notification settings - Fork 4
/
shader.cpp
83 lines (73 loc) · 2.17 KB
/
shader.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
#include "shader.h"
#include "scope_guard.h"
#include <glad/glad.h>
#include <cassert>
ShaderProgram::ShaderProgram()
: program_(0)
{
}
ShaderProgram::~ShaderProgram()
{
glDeleteProgram(program_);
}
bool ShaderProgram::Init(const char *vertexShaderSource,
const char *fragmentShaderSource,
std::string &errorLog)
{
assert(program_ == 0);
int success;
char info_log[1024];
// vertex shader
GLuint vertex = glCreateShader(GL_VERTEX_SHADER);
auto vertex_guard = scopeGuard([&vertex]{ glDeleteShader(vertex); });
glShaderSource(vertex, 1, &vertexShaderSource, NULL);
glCompileShader(vertex);
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertex, 1024, NULL, info_log);
errorLog = "compile vertex shader: ";
errorLog += info_log;
return false;
}
// fragment Shader
GLuint fragment = glCreateShader(GL_FRAGMENT_SHADER);
auto fragment_guard = scopeGuard([&fragment]{ glDeleteShader(fragment); });
glShaderSource(fragment, 1, &fragmentShaderSource, NULL);
glCompileShader(fragment);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragment, 1024, NULL, info_log);
errorLog = "compile fragment shader: ";
errorLog += info_log;
return false;
}
// shader Program
program_ = glCreateProgram();
auto program_guard = scopeGuard([&]{ glDeleteProgram(program_); program_ = 0; });
glAttachShader(program_, vertex);
glAttachShader(program_, fragment);
glLinkProgram(program_);
glGetProgramiv(program_, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(program_, 1024, NULL, info_log);
errorLog = "link: ";
errorLog += info_log;
return false;
}
program_guard.dismiss();
return true;
}
void ShaderProgram::Use(bool use)
{
assert(program_ != 0);
GLuint prog = use ? program_ : 0;
glUseProgram(prog);
}
int ShaderProgram::GetUniformLocation(const char *name)
{
assert(program_ != 0);
return glGetUniformLocation(program_, name);
}