1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #include <iostream>
- #include "rendering/Shader.h"
- #include "rendering/GL.h"
- static const GLchar* vertexShader =
- "#version 430\n"
- "layout (location = 0) in vec2 position;\n"
- "layout (location = 1) in vec3 color;\n"
- "out vec3 varColor;\n"
- "void main() {\n"
- "gl_Position = vec4(position, 0.0, 1.0);\n"
- "varColor = color;\n"
- "}";
- static const GLchar* fragmentShader =
- "#version 430\n"
- "in vec3 varColor;\n"
- "out vec4 color;"
- "void main() {\n"
- "color = vec4(varColor, 1.0);"
- "}";
- Shader::Shader() : vShader(0), fShader(0), program(0) {
- if(compile(vShader, vertexShader, GL_VERTEX_SHADER) || compile(fShader, fragmentShader, GL_FRAGMENT_SHADER)) {
- return;
- }
- program = glCreateProgram();
- glAttachShader(program, vShader);
- glAttachShader(program, fShader);
- glLinkProgram(program);
- if(GL::checkAndPrintError("shader linking error")) {
- clean();
- return;
- }
- GLint linked;
- glGetProgramiv(program, GL_LINK_STATUS, &linked);
- if(linked == GL_FALSE) {
- GLchar buffer[512];
- glGetProgramInfoLog(program, 512, nullptr, buffer);
- std::cout << "programm linking info log: " << buffer << "\n";
- clean();
- return;
- }
- }
- Shader::~Shader() {
- clean();
- }
- void Shader::clean() {
- glDeleteProgram(program);
- glDeleteShader(vShader);
- glDeleteShader(fShader);
- program = 0;
- vShader = 0;
- fShader = 0;
- }
- bool Shader::hasError() const {
- return vShader == 0 || fShader == 0 || program == 0;
- }
- bool Shader::compile(GLuint& shader, const GLchar* code, GLenum shaderType) {
- shader = glCreateShader(shaderType);
- glShaderSource(shader, 1, &code, nullptr);
- glCompileShader(shader);
- if(GL::checkAndPrintError("shader error")) {
- return true;
- }
- GLint compiled;
- glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
- if(compiled == GL_FALSE) {
- GLchar buffer[512];
- glGetShaderInfoLog(shader, 512, nullptr, buffer);
- std::cout << "shader info log: " << buffer << "\n";
- return true;
- }
- return false;
- }
- void Shader::use() const {
- glUseProgram(program);
- }
|