Code re-work: gamma correction.

This commit is contained in:
Joey de Vries
2017-04-22 17:25:08 +02:00
parent cdcc3be029
commit 33dd340549
4 changed files with 203 additions and 156 deletions

View File

@@ -3,7 +3,7 @@ layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal; layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords; layout (location = 2) in vec2 aTexCoords;
// Declare an interface block; see 'Advanced GLSL' for what these are. // declare an interface block; see 'Advanced GLSL' for what these are.
out VS_OUT { out VS_OUT {
vec3 FragPos; vec3 FragPos;
vec3 Normal; vec3 Normal;

View File

@@ -16,18 +16,18 @@ uniform bool gamma;
vec3 BlinnPhong(vec3 normal, vec3 fragPos, vec3 lightPos, vec3 lightColor) vec3 BlinnPhong(vec3 normal, vec3 fragPos, vec3 lightPos, vec3 lightColor)
{ {
// Diffuse // diffuse
vec3 lightDir = normalize(lightPos - fragPos); vec3 lightDir = normalize(lightPos - fragPos);
float diff = max(dot(lightDir, normal), 0.0); float diff = max(dot(lightDir, normal), 0.0);
vec3 diffuse = diff * lightColor; vec3 diffuse = diff * lightColor;
// Specular // specular
vec3 viewDir = normalize(viewPos - fragPos); vec3 viewDir = normalize(viewPos - fragPos);
vec3 reflectDir = reflect(-lightDir, normal); vec3 reflectDir = reflect(-lightDir, normal);
float spec = 0.0; float spec = 0.0;
vec3 halfwayDir = normalize(lightDir + viewDir); vec3 halfwayDir = normalize(lightDir + viewDir);
spec = pow(max(dot(normal, halfwayDir), 0.0), 64.0); spec = pow(max(dot(normal, halfwayDir), 0.0), 64.0);
vec3 specular = spec * lightColor; vec3 specular = spec * lightColor;
// Simple attenuation // simple attenuation
float max_distance = 1.5; float max_distance = 1.5;
float distance = length(lightPos - fragPos); float distance = length(lightPos - fragPos);
float attenuation = 1.0 / (gamma ? distance * distance : distance); float attenuation = 1.0 / (gamma ? distance * distance : distance);
@@ -47,5 +47,5 @@ void main()
color *= lighting; color *= lighting;
if(gamma) if(gamma)
color = pow(color, vec3(1.0/2.2)); color = pow(color, vec3(1.0/2.2));
FragColor = vec4(color, 1.0f); FragColor = vec4(color, 1.0);
} }

View File

@@ -1,7 +1,7 @@
#version 330 core #version 330 core
layout (location = 0) in vec3 position; layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 normal; layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 texCoords; layout (location = 2) in vec2 aTexCoords;
out VS_OUT { out VS_OUT {
vec3 FragPos; vec3 FragPos;
@@ -14,8 +14,8 @@ uniform mat4 view;
void main() void main()
{ {
gl_Position = projection * view * vec4(position, 1.0f); vs_out.FragPos = aPos;
vs_out.FragPos = position; vs_out.Normal = aNormal;
vs_out.Normal = normal; vs_out.TexCoords = aTexCoords;
vs_out.TexCoords = texCoords; gl_Position = projection * view * vec4(aPos, 1.0);
} }

View File

@@ -1,104 +1,123 @@
// GLEW #include <glad/glad.h>
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
#include <stb_image.h>
// GL includes
#include <learnopengl/shader.h>
#include <learnopengl/camera.h>
// GLM Mathemtics
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp> #include <glm/gtc/type_ptr.hpp>
// Other Libs
#include <SOIL.h>
#include <learnopengl/filesystem.h> #include <learnopengl/filesystem.h>
#include <learnopengl/shader_m.h>
#include <learnopengl/camera.h>
#include <learnopengl/model.h>
// Properties #include <iostream>
const GLuint SCR_WIDTH = 800, SCR_HEIGHT = 600;
// Function prototypes void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_callback(GLFWwindow* window, double xpos, double ypos); void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void Do_Movement(); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
GLuint loadTexture(GLchar const * path, bool gammaCorrection); void processInput(GLFWwindow *window);
unsigned int loadTexture(const char *path, bool gammaCorrection);
// Camera // settings
const unsigned int SCR_WIDTH = 1280;
const unsigned int SCR_HEIGHT = 720;
bool gamma = false;
bool gammaKeyPressed = false;
// camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = (float)SCR_WIDTH / 2.0;
float lastY = (float)SCR_HEIGHT / 2.0;
bool firstMouse = true;
// Delta // timing
GLfloat deltaTime = 0.0f; float deltaTime = 0.0f;
GLfloat lastFrame = 0.0f; float lastFrame = 0.0f;
// Options
GLboolean gammaEnabled = false;
// The MAIN function, from here we start our application and run our Game loop
int main() int main()
{ {
// Init GLFW // glfw: initialize and configure
// ------------------------------
glfwInit(); glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed // glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
glfwMakeContextCurrent(window); glfwMakeContextCurrent(window);
if (window == NULL)
// Set the required callback functions {
glfwSetKeyCallback(window, key_callback); std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback); glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback); glfwSetScrollCallback(window, scroll_callback);
// Options // tell GLFW to capture our mouse
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// Initialize GLEW to setup the OpenGL Function pointers // glad: load all OpenGL function pointers
glewExperimental = GL_TRUE; // ---------------------------------------
glewInit(); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// Define the viewport dimensions // configure global opengl state
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT); // -----------------------------
// Setup some OpenGL options
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
//glEnable(GL_FRAMEBUFFER_SRGB); // This enables OpenGL's built-in sRGB support. Once enabled, all subsequent fragment outputs (into framebuffer's color buffer(s)) are first gamma corrected. glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Setup and compile our shaders // build and compile shaders
Shader shader("gamma_correction.vs", "gamma_correction.frag"); // -------------------------
Shader shader("2.gamma_correction.vs", "2.gamma_correction.fs");
GLfloat planeVertices[] = { // set up vertex data (and buffer(s)) and configure vertex attributes
// Positions // Normals // Texture Coords // ------------------------------------------------------------------
5.0f, -0.5f, 5.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, float planeVertices[] = {
-5.0f, -0.5f, 5.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, // positions // normals // texcoords
-5.0f, -0.5f, -5.0f, 0.0f, 1.0f, 0.0f, 0.0f, 5.0f, 10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
5.0f, -0.5f, 5.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, 10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-5.0f, -0.5f, -5.0f, 0.0f, 1.0f, 0.0f, 0.0f, 5.0f, -10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
5.0f, -0.5f, -5.0f, 0.0f, 1.0f, 0.0f, 5.0f, 5.0f 10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 10.0f
}; };
// Setup plane VAO // plane VAO
GLuint planeVAO, planeVBO; unsigned int planeVAO, planeVBO;
glGenVertexArrays(1, &planeVAO); glGenVertexArrays(1, &planeVAO);
glGenBuffers(1, &planeVBO); glGenBuffers(1, &planeVBO);
glBindVertexArray(planeVAO); glBindVertexArray(planeVAO);
glBindBuffer(GL_ARRAY_BUFFER, planeVBO); glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), planeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0); glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1); glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(2); glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glBindVertexArray(0); glBindVertexArray(0);
// Light sources // load textures
// -------------
unsigned int floorTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), false);
unsigned int floorTextureGammaCorrected = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), true);
// shader configuration
// --------------------
shader.use();
shader.setInt("floorTexture", 0);
// lighting info
// -------------
glm::vec3 lightPositions[] = { glm::vec3 lightPositions[] = {
glm::vec3(-3.0f, 0.0f, 0.0f), glm::vec3(-3.0f, 0.0f, 0.0f),
glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f),
@@ -112,121 +131,99 @@ int main()
glm::vec3(1.00) glm::vec3(1.00)
}; };
// Load textures // render loop
GLuint floorTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), false); // -----------
GLuint floorTextureGammaCorrected = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str(), true);
// Game loop
while (!glfwWindowShouldClose(window)) while (!glfwWindowShouldClose(window))
{ {
// Set frame time // per-frame time logic
GLfloat currentFrame = glfwGetTime(); // --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame; deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame; lastFrame = currentFrame;
// Check and call events // input
glfwPollEvents(); // -----
Do_Movement(); processInput(window);
// Clear the colorbuffer // render
// ------
glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw objects // draw objects
shader.Use(); shader.use();
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 view = camera.GetViewMatrix();
glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); shader.setMat4("projection", projection);
// Set light uniforms shader.setMat4("view", view);
glUniform3fv(glGetUniformLocation(shader.Program, "lightPositions"), 4, &lightPositions[0][0]); // set light uniforms
glUniform3fv(glGetUniformLocation(shader.Program, "lightColors"), 4, &lightColors[0][0]); glUniform3fv(glGetUniformLocation(shader.ID, "lightPositions"), 4, &lightPositions[0][0]);
glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]); glUniform3fv(glGetUniformLocation(shader.ID, "lightColors"), 4, &lightColors[0][0]);
glUniform1i(glGetUniformLocation(shader.Program, "gamma"), gammaEnabled); shader.setVec3("viewPos", camera.Position);
// Floor shader.setInt("gamma", gamma);
// floor
glBindVertexArray(planeVAO); glBindVertexArray(planeVAO);
glBindTexture(GL_TEXTURE_2D, gammaEnabled ? floorTextureGammaCorrected : floorTexture); glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gamma ? floorTextureGammaCorrected : floorTexture);
glDrawArrays(GL_TRIANGLES, 0, 6); glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
std::cout << (gammaEnabled ? "Gamma enabled" : "Gamma disabled") << std::endl; std::cout << (gamma ? "Gamma enabled" : "Gamma disabled") << std::endl;
// Swap the buffers // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window); glfwSwapBuffers(window);
glfwPollEvents();
} }
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &planeVAO);
glDeleteBuffers(1, &planeVBO);
glfwTerminate(); glfwTerminate();
return 0; return 0;
} }
// This function loads a texture from file. Note: texture loading functions like these are usually // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// managed by a 'Resource Manager' that manages all resources (like textures, models, audio). // ---------------------------------------------------------------------------------------------------------
// For learning purposes we'll just define it as a utility function. void processInput(GLFWwindow *window)
GLuint loadTexture(GLchar const * path, bool gammaCorrection)
{ {
// Generate texture ID and load texture data if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
GLuint textureID; glfwSetWindowShouldClose(window, true);
glGenTextures(1, &textureID);
int width, height;
unsigned char* image = SOIL_load_image(path, &width, &height, 0, SOIL_LOAD_RGB);
// Assign texture to ID
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, gammaCorrection ? GL_SRGB : GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
// Parameters float cameraSpeed = 2.5 * deltaTime;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
SOIL_free_image_data(image);
return textureID;
}
bool keys[1024];
bool keysPressed[1024];
// Moves/alters the camera positions based on user input
void Do_Movement()
{
// Camera controls
if (keys[GLFW_KEY_W])
camera.ProcessKeyboard(FORWARD, deltaTime); camera.ProcessKeyboard(FORWARD, deltaTime);
if (keys[GLFW_KEY_S]) if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime); camera.ProcessKeyboard(BACKWARD, deltaTime);
if (keys[GLFW_KEY_A]) if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime); camera.ProcessKeyboard(LEFT, deltaTime);
if (keys[GLFW_KEY_D]) if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime); camera.ProcessKeyboard(RIGHT, deltaTime);
if (keys[GLFW_KEY_SPACE] && !keysPressed[GLFW_KEY_SPACE]) if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS && !gammaKeyPressed)
{ {
gammaEnabled = !gammaEnabled; gamma = !gamma;
keysPressed[GLFW_KEY_SPACE] = true; gammaKeyPressed = true;
}
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_RELEASE)
{
gammaKeyPressed = false;
} }
} }
GLfloat lastX = 400, lastY = 300; // glfw: whenever the window size changed (by OS or user resize) this callback function executes
bool firstMouse = true; // ---------------------------------------------------------------------------------------------
// Is called whenever a key is pressed/released via GLFW void framebuffer_size_callback(GLFWwindow* window, int width, int height)
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{ {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) // make sure the viewport matches the new window dimensions; note that width and
glfwSetWindowShouldClose(window, GL_TRUE); // height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
if (key >= 0 && key <= 1024)
{
if (action == GLFW_PRESS)
keys[key] = true;
else if (action == GLFW_RELEASE)
{
keys[key] = false;
keysPressed[key] = false;
}
}
} }
// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xpos, double ypos) void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{ {
if (firstMouse) if (firstMouse)
@@ -236,8 +233,8 @@ void mouse_callback(GLFWwindow* window, double xpos, double ypos)
firstMouse = false; firstMouse = false;
} }
GLfloat xoffset = xpos - lastX; float xoffset = xpos - lastX;
GLfloat yoffset = lastY - ypos; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos; lastX = xpos;
lastY = ypos; lastY = ypos;
@@ -245,7 +242,57 @@ void mouse_callback(GLFWwindow* window, double xpos, double ypos)
camera.ProcessMouseMovement(xoffset, yoffset); camera.ProcessMouseMovement(xoffset, yoffset);
} }
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ----------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{ {
camera.ProcessMouseScroll(yoffset); camera.ProcessMouseScroll(yoffset);
} }
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path, bool gammaCorrection)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum internalFormat;
GLenum dataFormat;
if (nrComponents == 1)
{
internalFormat = dataFormat = GL_RED;
}
else if (nrComponents == 3)
{
internalFormat = gammaCorrection ? GL_SRGB : GL_RGB;
dataFormat = GL_RGB;
}
else if (nrComponents == 4)
{
internalFormat = gammaCorrection ? GL_SRGB_ALPHA : GL_RGBA;
dataFormat = GL_RGBA;
}
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, dataFormat, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}