-
Notifications
You must be signed in to change notification settings - Fork 2
/
shader.hpp
398 lines (316 loc) · 9.24 KB
/
shader.hpp
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#ifndef SHADER_HPP_INCLUDED
#define SHADER_HPP_INCLUDED
#include <string>
#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>
#include <memory>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
namespace
{
inline std::string fetchGLError(const std::string &def = std::string())
{
std::string val;
while (GLenum err = glGetError())
{
if (!val.empty()) {
val.append(", ");
}
switch (err) {
case GL_INVALID_ENUM: val += "GL_INVALID_ENUM"; break;
case GL_INVALID_VALUE: val += "GL_INVALID_VALUE"; break;
case GL_INVALID_OPERATION: val += "GL_INVALID_OPERATION"; break;
case GL_OUT_OF_MEMORY: val += "GL_OUT_OF_MEMORY"; break;
default: val += "(unknown)";
};
}
return val.empty() ? def : val;
}
}
struct GLError : public std::runtime_error
{
GLError(const std::string &msg)
: std::runtime_error(msg + ": " + fetchGLError("no error"))
{}
GLError(const std::string &msg, const std::string &error)
: std::runtime_error(msg + ": " + error)
{}
};
inline void checkGLError(const std::string &msg)
{
std::string e(fetchGLError());
if (!e.empty()) {
throw GLError(msg, e);
}
}
struct ShaderError : public std::runtime_error {
ShaderError(const std::string &msg) : std::runtime_error(msg) {}
};
struct ProgramError : public std::runtime_error {
ProgramError(const std::string &msg) : std::runtime_error(msg) {}
};
struct ShaderSource
{
const char* data;
int length;
ShaderSource(const char *src)
: data(src), length(strlen(src)) {}
ShaderSource(const std::string &src)
: data(src.data()), length(src.length()) {}
template<typename T, int size>
ShaderSource(const T(&data)[size])
: data((const char*) data), length(size) {}
typedef std::vector<ShaderSource> list;
};
struct Definitions
{
Definitions() {}
template<typename A, typename B>
Definitions(const A &name, const B &value) {
defs.push_back(Def(name, value));
}
template<typename A, typename B>
Definitions& operator()(const A &name, const B &value) {
defs.push_back(Def(name, value));
return *this;
}
typedef std::pair<std::string, std::string> Def;
typedef std::vector<Def> DefVector;
DefVector defs;
std::string toString() const
{
std::string result;
for (const auto &pair : defs) {
result += std::string("#define ") + pair.first + " " + pair.second + "\n";
}
return result;
}
};
template<GLenum Kind>
class Shader
{
public:
Shader() {}
Shader(int version, const ShaderSource::list &sources,
const Definitions &defs = Definitions())
{
load(version, sources, defs);
}
GLuint get() const {
return shader_ ? *shader_ : 0;
}
bool valid() const {
return shader_ != nullptr;
}
operator GLuint() const {
return get();
}
void load(int version, const ShaderSource::list sources,
const Definitions &defs = Definitions())
{
shader_ptr shader(new GLuint(0), &Shader::deleter);
*shader = glCreateShader(Kind);
if (!*shader) {
throw GLError(std::string("Cannot create shader ") + glKindName());
}
std::vector<const GLchar*> strings(sources.size() + 1);
std::vector<GLint> lengths(strings.size());
char buf[200];
sprintf(buf, "#version %d\n#define %s 1\n", version, glslDefName());
std::string preamble = std::string(buf) + defs.toString();
strings[0] = preamble.data();
lengths[0] = preamble.length();
for (unsigned i = 0; i < sources.size(); i++) {
strings[i+1] = sources[i].data;
lengths[i+1] = sources[i].length;
}
glShaderSource(*shader, strings.size(), strings.data(), lengths.data());
glCompileShader(*shader);
GLint compiled;
glGetShaderiv(*shader, GL_COMPILE_STATUS, &compiled);
if (!compiled)
{
GLint il = 0;
glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &il);
if (il > 1) {
std::vector<char> log;
log.resize(il);
glGetShaderInfoLog(*shader, il, 0x0, &log[0]);
throw ShaderError
(std::string("Error compiling shader:\n") + &log[0]);
}
throw ShaderError("cannot compile shader");
}
// everything went OK, we can replace shader
shader_ = shader;
}
protected:
static void deleter(const GLuint *s)
{
if (s && *s) {
glDeleteShader(*s);
}
}
static const char* glKindName()
{
switch (Kind) {
case GL_VERTEX_SHADER: return "GL_VERTEX_SHADER";
case GL_TESS_CONTROL_SHADER: return "GL_TESS_CONTROL_SHADER";
case GL_TESS_EVALUATION_SHADER: return "GL_TESS_EVALUATION_SHADER";
case GL_FRAGMENT_SHADER: return "GL_FRAGMENT_SHADER";
case GL_COMPUTE_SHADER: return "GL_COMPUTE_SHADER";
default: return "???";
}
}
static const char* glslDefName()
{
switch (Kind) {
case GL_VERTEX_SHADER: return "_VERTEX_";
case GL_TESS_CONTROL_SHADER: return "_TESS_CONTROL_";
case GL_TESS_EVALUATION_SHADER: return "_TESS_EVAL_";
case GL_FRAGMENT_SHADER: return "_FRAGMENT_";
case GL_COMPUTE_SHADER: return "_COMPUTE_";
default: return "???";
}
}
typedef std::shared_ptr<GLuint> shader_ptr;
shader_ptr shader_;
};
typedef Shader<GL_VERTEX_SHADER> VertexShader;
typedef Shader<GL_TESS_CONTROL_SHADER> TessControlShader;
typedef Shader<GL_TESS_EVALUATION_SHADER> TessEvalShader;
typedef Shader<GL_FRAGMENT_SHADER> FragmentShader;
typedef Shader<GL_COMPUTE_SHADER> ComputeShader;
struct Attributes
{
Attributes() {}
Attributes(GLuint index, const GLchar *name) {
attrs.push_back(Attr(index, name));
}
Attributes& operator()(GLuint index, const GLchar *name) {
attrs.push_back(Attr(index, name));
return *this;
}
typedef std::pair<GLuint, const GLchar *> Attr;
typedef std::vector<Attr> AttrVector;
AttrVector attrs;
};
class Program
{
public:
Program() {}
void link(const VertexShader &vs, const FragmentShader &fs
, const Attributes &attrs = Attributes())
{
link(vs, {}, {}, fs, {}, attrs);
}
void link(const VertexShader &vs, const TessControlShader &tcs,
const TessEvalShader &tes, const FragmentShader &fs
, const Attributes &attrs = Attributes())
{
link(vs, tcs, tes, fs, {}, attrs);
}
void link(const ComputeShader &cs
, const Attributes &attrs = Attributes())
{
link({}, {}, {}, {}, cs, attrs);
}
void link(const VertexShader &vs, const TessControlShader &tcs,
const TessEvalShader &tes, const FragmentShader &fs,
const ComputeShader &cs
, const Attributes &attrs = Attributes())
{
// create invalid program
ProgramId id(new GLuint(0), &Program::deleter);
// having valid pointer we can safely create program
*id = glCreateProgram();
if (!*id) throw GLError("cannot create shader");
if (vs.valid()) {
glAttachShader(*id, vs);
}
if (tcs.valid()) {
glAttachShader(*id, tcs);
}
if (tes.valid()) {
glAttachShader(*id, tes);
}
if (fs.valid()) {
glAttachShader(*id, fs);
}
if (cs.valid()) {
glAttachShader(*id, cs);
}
for (const Attributes::Attr &a : attrs.attrs) {
glBindAttribLocation(*id, a.first, a.second);
}
glLinkProgram(*id);
GLint linked;
glGetProgramiv(*id, GL_LINK_STATUS, &linked);
if (!linked)
{
GLint il = 0;
glGetProgramiv(*id, GL_INFO_LOG_LENGTH, &il);
if (il > 1) {
std::vector<char> log;
log.resize(il);
glGetProgramInfoLog(*id, il, 0x0, &log[0]);
throw ProgramError
(std::string("cannot link program: ") + &log[0]);
}
throw ProgramError("cannot link program");
}
programId_ = id;
vs_ = vs;
tcs_ = tcs;
tes_ = tes;
fs_ = fs;
cs_ = cs;
}
GLuint get() const {
return programId_ ? *programId_ : 0;
}
operator GLuint() const {
return get();
}
void use() const {
glUseProgram(get());
}
void stop() const {
glUseProgram(0);
}
GLint uniform(const char *name) const {
return glGetUniformLocation(get(), name);
}
GLint uniform(const std::string &name) const {
return glGetUniformLocation(get(), name.c_str());
}
GLint attribute(const char *name) const {
return glGetAttribLocation(get(), name);
}
GLint attribute(const std::string &name) const {
return glGetAttribLocation(get(), name.c_str());
}
/// Return local work group size of a compute shader.
void localSize(GLint lsize[3]) {
glGetProgramiv(get(), GL_COMPUTE_WORK_GROUP_SIZE, lsize);
}
private:
static void deleter(const GLuint *p) {
if (p && *p) {
glDeleteProgram(*p);
}
}
VertexShader vs_;
TessControlShader tcs_;
TessEvalShader tes_;
FragmentShader fs_;
ComputeShader cs_;
typedef std::shared_ptr<GLuint> ProgramId;
ProgramId programId_;
};
#endif // SHADER_HPP_INCLUDED