Last active
October 27, 2023 10:10
-
-
Save justcore69/1f013bfa757029c74b872f8abdb15a22 to your computer and use it in GitHub Desktop.
Function that loads OpenGL shader program from .vert and .frag files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<fstream> | |
#include<algorithm> | |
#include<string> | |
#include<glad/glad.h> | |
#include<GLFW/glfw3.h> | |
// Example: GLuint program = loadShader("src/shaders/vertexShader.vert", "src/shaders/fragmentShader.frag"); | |
GLuint loadShader(const char* vertex_path, const char* fragment_path) { // Returns OpenGL shaderProgram | |
GLuint vertShader = glCreateShader(GL_VERTEX_SHADER); | |
GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER); | |
// Read shaders | |
std::string vertShaderStr = readFile(vertex_path); | |
std::string fragShaderStr = readFile(fragment_path); | |
const char* vertShaderSrc = vertShaderStr.c_str(); | |
const char* fragShaderSrc = fragShaderStr.c_str(); | |
// Compile vertex shader | |
glShaderSource(vertShader, 1, &vertShaderSrc, NULL); | |
glCompileShader(vertShader); | |
// Compile fragment shader | |
glShaderSource(fragShader, 1, &fragShaderSrc, NULL); | |
glCompileShader(fragShader); | |
GLuint program = glCreateProgram(); | |
glAttachShader(program, vertShader); | |
glAttachShader(program, fragShader); | |
glLinkProgram(program); | |
glDeleteShader(vertShader); | |
glDeleteShader(fragShader); | |
// Check is program was linked successfully | |
char log[512]; | |
GLint success; | |
glGetProgramiv(program, GL_LINK_STATUS, &success); | |
if (success == GL_FALSE) { | |
glGetProgramInfoLog(program, 512, NULL, log); | |
std::cerr << "ERROR: Failed to link shader program " << &program << ". Check log for more information: \n" << log << "\n"; | |
return -1; | |
} | |
std::cout << "Program " << &program << " has been successfully linked.\n"; | |
return program; | |
} | |
std::string readFile(const char* filePath) { | |
std::string content; | |
std::ifstream fileStream(filePath, std::ios::in); | |
if (!fileStream.is_open()) { | |
std::cerr << "ERROR: Could not read file " << filePath << ". File does not exist.\n"; | |
return ""; | |
} | |
std::string line = ""; | |
while (!fileStream.eof()) { | |
std::getline(fileStream, line); | |
content.append(line + "\n"); | |
} | |
fileStream.close(); | |
return content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment