Skip to content

Instantly share code, notes, and snippets.

@AregevDev
Last active November 7, 2019 15:24
Show Gist options
  • Save AregevDev/0932a213dd5205c8e4ca8e0768202e1b to your computer and use it in GitHub Desktop.
Save AregevDev/0932a213dd5205c8e4ca8e0768202e1b to your computer and use it in GitHub Desktop.
Pls review
//
// Created by AregevDev on 11/5/2019.
//
#pragma once
#include <glad/glad.h>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
class Shader
{
public:
GLuint programId;
Shader()
{
programId = glCreateProgram();
}
void LoadFile(const std::string &filepath, GLenum type)
{
if (!linked)
{
std::string source = ReadText(filepath);
LoadSource(source, type);
}
}
void LoadSource(const std::string &source, GLenum type)
{
if (!linked)
{
GLuint sh = CreateShader(source, type);
glAttachShader(programId, sh);
attached.push_back(sh);
}
}
void Link()
{
glLinkProgram(programId);
int result;
glGetProgramiv(programId, GL_LINK_STATUS, &result);
if (!result)
{
int logLen;
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logLen);
std::string infoLog;
infoLog.resize(logLen);
glGetProgramInfoLog(programId, logLen, nullptr, infoLog.data());
std::cout << infoLog << std::endl;
}
linked = true;
for (auto &i : attached)
{
glDetachShader(programId, i);
glDeleteShader(i);
}
}
void Bind()
{
glUseProgram(programId);
}
~Shader()
{
glDeleteProgram(programId);
}
private:
bool linked{};
std::vector<GLuint> attached{};
static std::string ReadText(const std::string &filepath)
{
std::ifstream ifs(filepath);
return std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
}
static GLuint CreateShader(const std::string &source, GLenum type)
{
const char *p = source.c_str();
GLuint sh = glCreateShader(type);
glShaderSource(sh, 1, &p, nullptr);
glCompileShader(sh);
int result;
glGetShaderiv(sh, GL_COMPILE_STATUS, &result);
if (!result)
{
int logLen;
glGetShaderiv(sh, GL_INFO_LOG_LENGTH, &logLen);
std::string infoLog;
infoLog.resize(logLen);
glGetShaderInfoLog(sh, logLen, nullptr, infoLog.data());
std::cout << infoLog << std::endl;
}
return sh;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment