hyporo-cpp/source/hpr/gpu/shader.hpp

129 lines
2.3 KiB
C++
Raw Normal View History

2022-09-24 16:07:46 +05:00
#pragma once
#include <string>
2023-01-11 14:46:49 +05:00
#ifndef __gl_h_
#include <glad/glad.h>
#endif
2022-09-24 16:07:46 +05:00
namespace hpr::gpu
{
2023-01-11 14:46:49 +05:00
class Shader
2022-09-24 16:07:46 +05:00
{
public:
2023-01-11 14:46:49 +05:00
enum class Type
2022-09-24 16:07:46 +05:00
{
2023-01-11 14:46:49 +05:00
Vertex = GL_VERTEX_SHADER,
TessControl = GL_TESS_CONTROL_SHADER,
TessEvaluation = GL_TESS_EVALUATION_SHADER,
Geometry = GL_GEOMETRY_SHADER,
Fragment = GL_FRAGMENT_SHADER,
Compute = GL_COMPUTE_SHADER,
Unknown = -1
2022-09-24 16:07:46 +05:00
};
2022-10-05 21:10:51 +05:00
protected:
std::string p_filename;
2023-01-11 14:46:49 +05:00
std::string p_source;
2022-10-05 21:10:51 +05:00
std::string p_label;
2023-01-11 14:46:49 +05:00
Type p_type;
unsigned int p_index;
2022-10-05 21:10:51 +05:00
public:
2022-09-24 16:07:46 +05:00
// Constructors
2023-01-11 14:46:49 +05:00
inline
Shader() :
p_filename {},
p_source {},
p_label {},
p_type {Type::Unknown},
p_index {0}
{}
inline
Shader(Type type) :
p_filename {},
p_source {},
p_label {},
p_type {type}
{}
inline
Shader(Type type, const std::string& source) :
p_filename {},
p_source {source},
p_label {},
p_type {type},
p_index {0}
{}
virtual
~Shader() = default;
2022-09-24 16:07:46 +05:00
// Member functions
2022-11-18 21:50:49 +05:00
[[nodiscard]]
2023-01-11 14:46:49 +05:00
std::string filename() const
{
return p_filename;
}
[[nodiscard]]
std::string label() const
{
return p_label;
}
2022-09-24 16:07:46 +05:00
2022-11-18 21:50:49 +05:00
[[nodiscard]]
2023-01-11 14:46:49 +05:00
Type type() const
{
return p_type;
}
2022-09-24 16:07:46 +05:00
2022-11-18 21:50:49 +05:00
[[nodiscard]]
2023-01-11 14:46:49 +05:00
unsigned int index() const
{
return p_index;
}
void create(const std::string& label = "")
{
if (p_type == Type::Unknown)
throw std::runtime_error("Unknown shader type");
p_index = glCreateShader(static_cast<GLenum>(p_type));
if (p_index == 0)
throw std::runtime_error("Cannot create shader");
const char* shaderSource = p_source.c_str();
glShaderSource(p_index, 1, &shaderSource, nullptr);
GLenum result = glGetError();
glCompileShader(p_index);
int shaderStatus;
glGetShaderiv(p_index, GL_COMPILE_STATUS, &shaderStatus);
if (!shaderStatus)
{
char error[2048 + 1];
glGetShaderInfoLog(p_index, 2048, nullptr, error);
throw std::runtime_error(error);
}
p_label = label;
}
void destroy()
{
glDeleteShader(p_index);
}
2022-09-24 16:07:46 +05:00
};
2023-01-11 14:46:49 +05:00
}