File indexing completed on 2024-05-12 05:35:40

0001 /*
0002     SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
0003     SPDX-FileCopyrightText: 2023 Jeremy Whiting <jpwhiting@kde.org>
0004     SPDX-FileCopyrightText: 2023 Niccolò Venerandi <niccolo@venerandi.com>
0005 
0006     SPDX-License-Identifier: GPL-2.0-or-later
0007 */
0008 
0009 #include "gamepad.h"
0010 
0011 #include <QTimer>
0012 #include <SDL2/SDL.h>
0013 #include <SDL2/SDL_gamecontroller.h>
0014 
0015 Gamepad::Gamepad(SDL_Joystick *joystick, SDL_GameController *controller, QObject *parent)
0016     : QObject(parent)
0017     , m_joystick(joystick)
0018     , m_gameController(controller)
0019 {
0020     m_name = QString::fromLocal8Bit(SDL_JoystickName(m_joystick));
0021     m_path = QString::fromLocal8Bit(SDL_JoystickPath(m_joystick));
0022 }
0023 
0024 QString Gamepad::name() const
0025 {
0026     return m_name;
0027 }
0028 
0029 QString Gamepad::path() const
0030 {
0031     return m_path;
0032 }
0033 
0034 void Gamepad::onButtonEvent(const SDL_ControllerButtonEvent sdlEvent)
0035 {
0036     Q_EMIT buttonStateChanged(static_cast<SDL_GameControllerButton>(sdlEvent.button));
0037 }
0038 
0039 void Gamepad::onAxisEvent(const SDL_ControllerAxisEvent sdlEvent)
0040 {
0041     const float value = static_cast<float>(sdlEvent.value) / std::numeric_limits<Sint16>::max();
0042     if (sdlEvent.axis == SDL_CONTROLLER_AXIS_LEFTX) {
0043         m_axis.setX(value);
0044         Q_EMIT axisValueChanged();
0045     } else if (sdlEvent.axis == SDL_CONTROLLER_AXIS_LEFTY) {
0046         m_axis.setY(value);
0047         Q_EMIT axisValueChanged();
0048     }
0049 
0050     Q_EMIT axisStateChanged(sdlEvent.axis);
0051 }
0052 
0053 SDL_Joystick *Gamepad::joystick() const
0054 {
0055     return m_joystick;
0056 }
0057 
0058 SDL_GameController *Gamepad::gamecontroller() const
0059 {
0060     return m_gameController;
0061 }
0062 
0063 QVector2D Gamepad::axisValue() const
0064 {
0065     return QVector2D(m_axis);
0066 }
0067 
0068 #include "moc_gamepad.cpp"