-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshader.cpp
99 lines (82 loc) · 2.79 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <fstream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
unsigned long getFileLength(std::ifstream& file)
{
if(!file.good()) return 0;
unsigned long pos = file.tellg();
file.seekg(0,std::ios::end);
unsigned long len = file.tellg();
file.seekg(std::ios::beg);
return len;
}
int loadShader(char filename[], GLchar** ShaderSource)
{
unsigned long len;
std::ifstream file;
file.open(filename,std::ios::in); // opens as ASCII!
if(!file) return -1;
len = getFileLength(file);
if (len == 0) return -2; // Error: Empty File
*ShaderSource = (GLchar*) new char[(len)+1];
if (*ShaderSource == 0) return -3; // can't reserve memory
// len isn't always strlen cause some characters are stripped in ascii read...
// it is important to 0-terminate the real length later, len is just max possible value...
(*ShaderSource)[len] = '\0';
unsigned int i = 0;
while (file.good())
{
file.get((*ShaderSource)[i]); // get character from file.
if (!file.eof())
i++;
}
(*ShaderSource)[i] = 0; // 0-terminate it at the correct position
file.close();
return 0; // No Error
}
int unloadShader(GLchar** ShaderSource)
{
if (*ShaderSource != 0)
delete[] *ShaderSource;
*ShaderSource = 0;
return 0;
}
GLuint makeShaderProgram(GLchar *pfragshadersrc, GLchar *pvertshadersrc){
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &pvertshadersrc, NULL);
glCompileShader(vertexShader);
GLint success;
GLchar log[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, log);
std::cout << "Vertex shader compilation failed:\n"
<< log << std::endl;
}
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &pfragshadersrc, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, log);
std::cout << "Fragment shader compilation failed:\n"
<< log << std::endl;
}
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, log);
std::cout << "Shader program linking failed:\n"
<< log << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}