From abef6c368fdd7c264d1dba6c09d2048a4f5a45ea Mon Sep 17 00:00:00 2001
From: Abdelrahman <said.abdelrahman89@gmail.com>
Date: Sun, 22 Sep 2024 14:46:12 +0100
Subject: [PATCH] Add uniform values

---
 shaders/frag.glsl |  4 +++-
 shaders/vert.glsl |  4 +++-
 src/main.cc       | 19 +++++++++++++++++++
 3 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/shaders/frag.glsl b/shaders/frag.glsl
index 2730cb0..a1f2128 100644
--- a/shaders/frag.glsl
+++ b/shaders/frag.glsl
@@ -3,6 +3,8 @@
 in vec3 vert_colours;
 out vec4 color;
 
+uniform float u_offset;
+
 void main() {
-  color = vec4(vert_colours.r, vert_colours.g, vert_colours.b, 1.0f);
+  color = vec4(vert_colours.r, vert_colours.g + u_offset, vert_colours.b, 1.0f);
 };
diff --git a/shaders/vert.glsl b/shaders/vert.glsl
index eeafdeb..526d9a3 100644
--- a/shaders/vert.glsl
+++ b/shaders/vert.glsl
@@ -3,9 +3,11 @@
 layout(location=0) in vec3 position;
 layout(location=1) in vec3 vert_colour;
 
+uniform float u_offset;
+
 out vec3 vert_colours;
 
 void main() {
   vert_colours = vert_colour;
-  gl_Position = vec4(position.x, position.y, position.z, 1.0f);
+  gl_Position = vec4(position.x, position.y + u_offset, position.z, 1.0f);
 };
diff --git a/src/main.cc b/src/main.cc
index 0316a6a..370adb8 100644
--- a/src/main.cc
+++ b/src/main.cc
@@ -1,3 +1,4 @@
+#include "SDL_keycode.h"
 #include "glad/glad.h"
 #include <SDL2/SDL.h>
 #include <SDL2/SDL_error.h>
@@ -41,6 +42,11 @@ struct App {
   // OpenGL refers to as element, hence the name Element Buffer Object
   GLuint        ebo;
 
+  // offset value passed to shaders as uniform
+  float         offset;
+  // offset uniform index
+  GLint         u_offset_idx;
+
   GLuint        shader_program;
   bool          running;
 };
@@ -191,6 +197,12 @@ void create_graphics_pipeline(App &app) {
   const std::string fs_source = load_shader("shaders/frag.glsl");
 
   app.shader_program = create_shader_program(vs_source, fs_source);
+
+  const char *u_offset = "u_offset";
+  app.u_offset_idx = glGetUniformLocation(app.shader_program, u_offset);
+  if (app.u_offset_idx < 0) {
+    printf("Can't find uniform %s", u_offset);
+  }
 }
 
 void run_main_loop(App &app) {
@@ -202,6 +214,12 @@ void run_main_loop(App &app) {
       case SDL_QUIT:
         app.running = false;
         break;
+      case SDL_KEYDOWN:
+        if (app.event.key.keysym.sym == SDLK_UP) {
+          app.offset += 0.01f;
+        } else if (app.event.key.keysym.sym == SDLK_DOWN) {
+          app.offset -= 0.01f;
+        }
       }
     }
 
@@ -214,6 +232,7 @@ void run_main_loop(App &app) {
     glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
 
     glUseProgram(app.shader_program);
+    glUniform1f(app.u_offset_idx, app.offset);
     // End pre draw setup
 
     // Draw call