feat: add time uniform to shader

This commit is contained in:
Cat Flynn 2023-07-27 21:54:06 +02:00
parent 1c5350b67d
commit c73f7f74db
3 changed files with 25 additions and 3 deletions

View File

@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.27)
project(HelloGLEW)
project(HelloTriangle)
# Define platform-specific paths and libraries
if(WIN32)

View File

@ -2,7 +2,9 @@
out vec4 FragColor;
uniform float _Time;
void main()
{
FragColor = vec4(1.0, 0.5, 0.2, 1.0);
FragColor = vec4(1.0, 0.5, 0.2, 1.0) * sin(_Time) / 2.0 + 0.5;
}

View File

@ -40,6 +40,8 @@
#include <sstream>
#include <string>
#include <chrono>
std::string readFile(const std::string& filePath)
{
std::ifstream fileStream(filePath, std::ios::in);
@ -82,13 +84,21 @@ GLuint compileShader(const std::string& shaderPath, GLenum shaderType)
return shader;
}
std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now();
float getTime()
{
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
std::chrono::duration<float> timeSpan = std::chrono::duration_cast<std::chrono::duration<float>>(now - startTime);
return timeSpan.count();
}
int main()
{
// Set up GLFW, OpenGL and GLEW.
if (!glfwInit())
return -1;
GLFWwindow* window = glfwCreateWindow(640, 480, "Hello GLEW", NULL, NULL);
GLFWwindow* window = glfwCreateWindow(640, 480, "Hello Triangle", NULL, NULL);
if (!window)
{
glfwTerminate();
@ -150,12 +160,22 @@ int main()
glDeleteShader(vertShader);
glDeleteShader(fragShader);
// Main loop
while (!glfwWindowShouldClose(window))
{
glClearColor(0.2, 0.3, 0.3, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
GLint timeLocation = glGetUniformLocation(shaderProgram, "_Time");
if (timeLocation == -1)
{
std::cerr << "Could not find uniform: _Time" << std::endl;
}
float timeValue = getTime();
glUniform1f(timeLocation, timeValue);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);