Debian Codegraph @

avogadro/rendering/shader.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "shader.h"
7
8 #include "avogadrogl.h"
9
10 namespace Avogadro::Rendering {
11
12 Shader::Shader(Type type_, const std::string& source_)
13 : m_type(type_), m_handle(0), m_dirty(true), m_source(source_)
14 {
15 }
16
17 Shader::~Shader() {}
18
19 void Shader::setType(Type type_)
20 {
21 m_type = type_;
22 m_dirty = true;
23 }
24
25 void Shader::setSource(const std::string& source_)
26 {
27 m_source = source_;
28 m_dirty = true;
29 }
30
31 bool Shader::compile()
32 {
33 if (m_source.empty() || m_type == Unknown || !m_dirty)
34 return false;
35
36 // Ensure we delete the previous shader if necessary.
37 if (m_handle != 0) {
38 glDeleteShader(static_cast<GLuint>(m_handle));
39 m_handle = 0;
40 }
41
42 GLenum type_ = m_type == Vertex ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER;
43 GLuint handle_ = glCreateShader(type_);
44 const auto* source_ = static_cast<const GLchar*>(m_source.c_str());
45 glShaderSource(handle_, 1, &source_, nullptr);
46 glCompileShader(handle_);
47 GLint isCompiled;
48 glGetShaderiv(handle_, GL_COMPILE_STATUS, &isCompiled);
49
50 // Handle shader compilation failures.
51 if (!isCompiled) {
52 GLint length(0);
53 glGetShaderiv(handle_, GL_INFO_LOG_LENGTH, &length);
54 if (length > 1) {
55 char* logMessage = new char[length];
56 glGetShaderInfoLog(handle_, length, nullptr, logMessage);
57 m_error = logMessage;
58 delete[] logMessage;
59 }
60 glDeleteShader(handle_);
61 return false;
62 }
63
64 // The shader compiled, store its handle and return success.
65 m_handle = static_cast<Index>(handle_);
66 m_dirty = false;
67
68 return true;
69 }
70
71 void Shader::cleanup()
72 {
73 if (m_type == Unknown || m_handle == 0)
74 return;
75
76 glDeleteShader(static_cast<GLuint>(m_handle));
77 m_handle = 0;
78 m_dirty = false;
79 }
80
81 } // namespace Avogadro::Rendering