From 4f71382d5a5e1cd95796576aa5c790645bd6f7bb Mon Sep 17 00:00:00 2001
From: Vanessa Karolek <vaka1997@uni-koblenz.de>
Date: Sun, 20 Jun 2021 22:16:24 +0200
Subject: [PATCH] [#60] handle reconnecting gamepad

Currently, only the first window is referenced.... If we use more windows, we need to know how to handle this. Maybe we have to bind a gamepadIndex to a specific window.
---
 include/vkcv/Window.hpp |  7 +++++++
 src/vkcv/Window.cpp     | 12 +++++++++++-
 2 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/include/vkcv/Window.hpp b/include/vkcv/Window.hpp
index 7dc6c1b7..d2b5854b 100644
--- a/include/vkcv/Window.hpp
+++ b/include/vkcv/Window.hpp
@@ -74,6 +74,13 @@ namespace vkcv {
          */
 		static void onCharEvent(GLFWwindow *callbackWindow, unsigned int c);
 
+        /**
+         * @brief A callback function for handling gamepad re-connection.
+         * @param gamepadIndex The gamepad index.
+         * @param gamepadEvent The gamepad connection event.
+         */
+        static void onGamepadConnection(int gamepadIndex, int gamepadEvent);
+
         /**
          * @brief A callback function for gamepad input events.
          * @param gamepadIndex The gamepad index.
diff --git a/src/vkcv/Window.cpp b/src/vkcv/Window.cpp
index 03ac915a..fad9a2a6 100644
--- a/src/vkcv/Window.cpp
+++ b/src/vkcv/Window.cpp
@@ -23,7 +23,7 @@ namespace vkcv {
 		glfwSetScrollCallback(m_window, Window::onMouseScrollEvent);
 		glfwSetCharCallback(m_window, Window::onCharEvent);
 	
-		glfwSetJoystickCallback(nullptr);
+		glfwSetJoystickCallback(Window::onGamepadConnection);
 		glfwSetJoystickUserPointer(GLFW_JOYSTICK_1, this);
     }
 
@@ -127,6 +127,16 @@ namespace vkcv {
 		}
     }
 
+    void Window::onGamepadConnection(int gamepadIndex, int gamepadEvent) {
+        if (gamepadEvent == GLFW_CONNECTED) {
+            auto window = static_cast<Window *>(glfwGetWindowUserPointer(s_Windows[0]));    // todo check for correct window
+
+            if (window != nullptr) {
+                glfwSetJoystickUserPointer(gamepadIndex, window);
+            }
+        }
+    }
+
     void Window::onGamepadEvent(int gamepadIndex) {
         auto window = static_cast<Window *>(glfwGetJoystickUserPointer(gamepadIndex));
 
-- 
GitLab