-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathshader.h
More file actions
71 lines (57 loc) · 2.27 KB
/
shader.h
File metadata and controls
71 lines (57 loc) · 2.27 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
#ifndef SHADER_H
#define SHADER_H
#include "common.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include "OpenGLHelper.h"
#include <variant>
/*
@brief:
Utility class to create, build and run a shader.
- After creating the shader, call Build()
- You can set static uniforms that don't change every frame by calling shader.Use()
and then SetUniform(), and optionally shader.Release()
- Frame-dynamic uniforms are called the same way, but inside the render loop
All uniform locations are cached for better performance. They're generally cached upon
first use, but you can force pre-caching by calling CacheUniform() for each uniform
after building and activating the shader.
If you want even more control over the uniforms, you can always do something like:
Cache the uniform yourself:
u_ticks = glGetUniformLocation(shader.ID, "ticks");
Assign the uniform in the render loop:
glUniform1i(u_ticks, SDL_GetTicks());
*/
using UniformValue = std::variant<
bool,int,uint32_t,float,
glm::vec2,glm::ivec2,glm::uvec2,
glm::vec3,glm::vec4,
glm::mat2,glm::mat3,glm::mat4
>;
class Shader
{
public:
unsigned int ID = 0;
bool isReady = false; // Shader is useless until you call build()
bool isInUse = false;
// Build from vertex and fragment shaders (could be combined using VERTEX and FRAGMENT #define)
void Build(const char* vertexPath, const char* fragmentPath);
void _Compile(const std::string* pvertexCode, const std::string* pfragmentCode);
// de/activate the shader
void Use() { glUseProgram(ID); glGetError() == GL_NO_ERROR ? isInUse = true : isInUse = false; };
void Release() { glUseProgram(0); isInUse = false; };
const std::string GetVertexPath() { return s_vertexPath; }
const std::string GetFragmentPath() { return s_fragmentPath; }
void CacheUniform(std::string const& name);
void SetUniform(std::string const& name, UniformValue const& v);
private:
std::string s_vertexPath;
std::string s_fragmentPath;
std::unordered_map<std::string,GLint> uniformCache;
std::vector<std::string> _uniformNames;
std::vector<GLint> _uniformLocs;
// utility function for checking shader compilation/linking errors.
void CheckCompileErrors(GLuint shader, std::string type);
};
#endif