-
Notifications
You must be signed in to change notification settings - Fork 0
/
Shader.cpp
73 lines (64 loc) · 1.92 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
#include "Shader.h"
Shader::Shader(const char* vertexPath, const char* fragmentPath)
{
std::string vertexSource = readFile(vertexPath);
std::string fragmentSource = readFile(fragmentPath);
int vertexShader = compileShader(vertexSource.c_str(), GL_VERTEX_SHADER);
int fragmentShader = compileShader(fragmentSource.c_str(), GL_FRAGMENT_SHADER);
ID = linkShaderProgram(vertexShader, fragmentShader);
}
std::string Shader::readFile(const char* filePath)
{
std::ifstream file(filePath);
if(file.fail())
{
std::cerr << "failed to open file" << std::endl;
return NULL;
}
return std::string ((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
}
void errorCallback(int id, const char* message)
{
std::cout << "Failed to create GLFW window" << std::endl;
}
int compileShader(const char *shaderSource, unsigned int shaderType)
{
int shader = glCreateShader(shaderType);
if(shader == 0)
{
errorCallback(0, "");
return 0;
}
glShaderSource(shader, 1, &shaderSource, NULL);
glCompileShader(shader);
int success;
char infoLog[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 512, NULL, infoLog);
errorCallback(0, "");
return 0;
}
return shader;
}
int linkShaderProgram(int vertexShader, int fragmentShader)
{
int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
int success;
char infoLog[512];
glGetShaderiv(shaderProgram, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shaderProgram, 512, NULL, infoLog);
errorCallback(0, "");
return 0;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}