From 5bb839136bab80e2c4605e40442edb138ecb83b5 Mon Sep 17 00:00:00 2001 From: Clownacy Date: Fri, 3 Apr 2020 16:53:58 +0100 Subject: [PATCH] Added controller support to GLFW3 backend --- src/Backends/GLFW3/Controller.cpp | 64 +++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 4 deletions(-) diff --git a/src/Backends/GLFW3/Controller.cpp b/src/Backends/GLFW3/Controller.cpp index 88d6b057..eecd271e 100644 --- a/src/Backends/GLFW3/Controller.cpp +++ b/src/Backends/GLFW3/Controller.cpp @@ -1,7 +1,17 @@ #include "../Controller.h" +#define GLFW_INCLUDE_NONE +#include + #include "../../WindowsWrapper.h" +#define DEADZONE (10000.0f / 32767.0f) + +static BOOL joystick_connected; +static int connected_joystick_id; +static float joystick_neutral_x; +static float joystick_neutral_y; + void ControllerBackend_Deinit(void) { @@ -9,17 +19,63 @@ void ControllerBackend_Deinit(void) BOOL ControllerBackend_Init(void) { - return FALSE; + for (int i = GLFW_JOYSTICK_1; i < GLFW_JOYSTICK_LAST; ++i) + { + if (glfwJoystickPresent(i) == GLFW_TRUE && glfwJoystickIsGamepad(i) == GLFW_TRUE) + { + joystick_connected = TRUE; + connected_joystick_id = i; + break; + } + } + + return joystick_connected; } BOOL ControllerBackend_GetJoystickStatus(JOYSTICK_STATUS *status) { - (void)status; + if (!joystick_connected) + return FALSE; - return FALSE; + if (glfwJoystickPresent(connected_joystick_id) == GLFW_FALSE || glfwJoystickIsGamepad(connected_joystick_id) == GLFW_FALSE) + return FALSE; + + int total_axis; + const float *axis = glfwGetJoystickAxes(connected_joystick_id, &total_axis); + + status->bLeft = axis[0] < joystick_neutral_x - DEADZONE; + status->bRight = axis[0] > joystick_neutral_x + DEADZONE; + status->bUp = axis[1] < joystick_neutral_x - DEADZONE; + status->bDown = axis[1] > joystick_neutral_x + DEADZONE; + + int total_buttons; + const unsigned char *buttons = glfwGetJoystickButtons(connected_joystick_id, &total_buttons); + + if (total_buttons > 32) + total_buttons = 32; + + for (int i = 0; i < total_buttons; ++i) + status->bButton[i] = buttons[i] == GLFW_PRESS; + + for (int i = total_buttons; i < 32; ++i) + status->bButton[i] = FALSE; + + return TRUE; } BOOL ControllerBackend_ResetJoystickStatus(void) { - return FALSE; + if (!joystick_connected) + return FALSE; + + if (glfwJoystickPresent(connected_joystick_id) == GLFW_FALSE || glfwJoystickIsGamepad(connected_joystick_id) == GLFW_FALSE) + return FALSE; + + int total_axis; + const float *axis = glfwGetJoystickAxes(connected_joystick_id, &total_axis); + + joystick_neutral_x = axis[0]; + joystick_neutral_y = axis[1]; + + return TRUE; }