12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- #include <GL/glew.h>
- #include <GLFW/glfw3.h>
- #include <iostream>
- #include "input/Controller.h"
- Controller::ButtonState::ButtonState() : downTime(0), justReleased(false) {
- }
- Controller::Controller() : activeController(GLFW_JOYSTICK_1) {
- }
- void Controller::tick() {
- if(!glfwJoystickPresent(activeController) && findController()) {
- std::cout << "cannot find any controller - resetting buttons\n";
- reset();
- return;
- }
- int buttonCount = 0;
- const u8* buttonMap = glfwGetJoystickButtons(activeController, &buttonCount);
- int axisCount = 0;
- const float* axisMap = glfwGetJoystickAxes(activeController, &axisCount);
- if(buttonCount < 10 || axisCount < 2) {
- std::cout << "cannot find any supported controller - resetting buttons\n";
- std::cout << "buttons found: " << buttonCount << "\n";
- std::cout << "axes found: " << axisCount << "\n";
- reset();
- return;
- }
- increment(Button::A, buttonMap, 1);
- increment(Button::B, buttonMap, 2);
- increment(Button::X, buttonMap, 0);
- increment(Button::Y, buttonMap, 3);
- increment(Button::L, buttonMap, 4);
- increment(Button::R, buttonMap, 5);
- increment(Button::SELECT, buttonMap, 8);
- increment(Button::START, buttonMap, 9);
- increment(Button::LEFT, axisMap[0] < -0.5f);
- increment(Button::RIGHT, axisMap[0] > 0.5f);
- increment(Button::UP, axisMap[1] < -0.5f);
- increment(Button::DOWN, axisMap[1] > 0.5f);
- }
- bool Controller::findController() {
- for(uint i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++) {
- if(glfwJoystickPresent(i)) {
- activeController = i;
- return false;
- }
- }
- return true;
- }
- void Controller::reset() {
- for(ButtonState& b : buttons) {
- b.downTime = 0;
- }
- }
- void Controller::increment(uint button, const u8* mapping, uint index) {
- increment(button, mapping[index] != GLFW_RELEASE);
- }
- void Controller::increment(uint button, bool notReleased) {
- buttons[button].justReleased = (buttons[button].downTime > 0 && !notReleased && !buttons[button].justReleased);
- bool b = notReleased || buttons[button].justReleased;
- buttons[button].downTime = buttons[button].downTime * b + b;
- }
- uint Controller::getButtonAmount() const {
- return buttons.getLength();
- }
- const char* Controller::getName(uint button) const {
- static constexpr const char* buttonNames[] = {
- "A", "B", "X", "Y", "L", "R", "Select", "Start", "Left", "Right", "Up", "Down"
- };
- return buttonNames[button];
- }
- uint Controller::getDownTime(uint button) const {
- return buttons[button].downTime;
- }
- bool Controller::isDown(uint button) const {
- return buttons[button].downTime > 0;
- }
- bool Controller::wasReleased(uint button) const {
- return buttons[button].justReleased;
- }
|