-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshader.cpp
81 lines (63 loc) · 2.1 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
#include "shader.h"
#include <GL/glew.h>
#include <fstream>
#include <sstream>
#include "renderer.h"
unsigned int Shader::loadShader(const std::string& path, unsigned int type) {
std::ifstream file(path);
std::stringstream buffer;
buffer << file.rdbuf();
std::string code = buffer.str();
const char* shaderCode = code.c_str();
unsigned int shader = glCreateShader(type);
glShaderSource(shader, 1, &shaderCode, nullptr);
glCompileShader(shader);
return shader;
}
Shader::Shader(const std::string& vertexPath, const std::string& fragmentPath) {
unsigned int vertexShader = loadShader(vertexPath, GL_VERTEX_SHADER);
unsigned int fragmentShader = loadShader(fragmentPath, GL_FRAGMENT_SHADER);
programID = glCreateProgram();
glAttachShader(programID, vertexShader);
glAttachShader(programID, fragmentShader);
glLinkProgram(programID);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
void Shader::use() const{
glUseProgram(programID);
}
unsigned int Shader::GetUniformLocation(const std::string &name)
{
if (m_UniformLocationCache.find(name)!= m_UniformLocationCache.end()){
return m_UniformLocationCache[name];
}
GLCall(int location = glGetUniformLocation(programID, name.c_str()));
if (location == -1){
std::cout<<"Warning: uniform '"<< name << "' doesn't exist!"<<std::endl;
}
m_UniformLocationCache[name] = location;
return location;
}
Shader::~Shader(){
glUseProgram(programID);
}
void Shader::Bind() const
{
GLCall(glUseProgram(programID));
}
void Shader::Unbind() const
{
GLCall(glUseProgram(0));
}
void Shader::setUniform3fv(const std::string &name, const glm::vec3 vector)
{
GLCall(glUniform3fv(GetUniformLocation(name),1, &vector[0]));
}
void Shader::setUniformMat4(const std::string& name, const glm::mat4& matrix) const {
unsigned int location = glGetUniformLocation(programID, name.c_str());
if (location == -1) {
std::cerr << "WARNING: Uniform '" << name << "' doesn't exist!" << std::endl;
}
glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]);
}