1 #include "shaderprogram.h"
6 ShaderProgram::~ShaderProgram()
8 for(auto shader : m_shaders)
10 glDetachShader(m_program, shader.obj);
11 glDeleteShader(shader.obj);
15 glDeleteProgram(m_program);
19 * This is only called once, does it need a function?
21 void ShaderProgram::LazyCreateProgram()
25 m_program = glCreateProgram();
30 * Get GLSL shader source from a file as a string
31 * @param src_file filename to get the shader source from
32 * @returns a char* string allocated with new[] (remember to delete[] it)
34 char * ShaderProgram::GetShaderSource(const char * src_file) const
37 FILE * file = fopen(src_file, "r");
40 Error("Could not open shader source file \"%s\": %s", src_file, strerror(errno));
43 long start = ftell(file);
45 if (fseek(file, 0, SEEK_END) != 0)
47 Error("Couldn't seek to end of file \"%s\": %s", src_file, strerror(errno));
50 long end = ftell(file);
51 if (start < 0 || end < 0 || end < start)
53 // I bet that now I've put this message here, it will occur at least once in the life of this code
54 Error("Insane results from ftell(3) on file \"%s\"", src_file);
57 size_t size = end - start;
58 src = new char[size+1]; // Warning! Allocation of memory occuring! We might all die!
60 if (fread(src, 1,size, file) != size)
62 Error("Error in fread on \"%s\": %s", src_file, strerror(errno));
73 bool ShaderProgram::AttachShader(const char * src_file, GLenum type)
75 GLuint shader_obj = glCreateShader(type);
76 char * src = GetShaderSource(src_file);
79 Error("Couldn't get shader source.");
84 glShaderSource(shader_obj, 1, &src, 0);
85 glCompileShader(shader_obj);
87 glGetShaderiv(shader_obj, GL_COMPILE_STATUS, &did_compile);
88 delete [] src; // Oh my goodness memory management is hard guys
93 glGetShaderInfoLog(shader_obj, 2048, nullptr, info_log);
94 Error("Shader compile error (file \"%s\"): %s (type %d)", src_file, info_log, type);
98 m_shaders.push_back(Shader{type, shader_obj});
99 LazyCreateProgram(); // um... why?
100 glAttachShader(m_program, shader_obj);
105 bool ShaderProgram::Link()
107 glLinkProgram(m_program);
111 const void ShaderProgram::Use() const
113 glUseProgram(m_program);
116 const GLint ShaderProgram::GetUniformLocation(const char *name) const
118 return glGetUniformLocation(m_program, name);