| 1 | // Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). |
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | #include "qgamepadinput_p.h" |
| 5 | |
| 6 | #include <QtCore/QMetaEnum> |
| 7 | #include <QtGamepad/QGamepadManager> |
| 8 | |
| 9 | #include <Qt3DInput/private/qabstractphysicaldevice_p.h> |
| 10 | |
| 11 | QT_BEGIN_NAMESPACE |
| 12 | namespace Qt3DInput { |
| 13 | class QGamepadInputPrivate : public QAbstractPhysicalDevicePrivate { |
| 14 | public: |
| 15 | QGamepadInputPrivate() |
| 16 | : QAbstractPhysicalDevicePrivate() |
| 17 | , m_deviceId(0) |
| 18 | {} |
| 19 | |
| 20 | int m_deviceId; |
| 21 | }; |
| 22 | |
| 23 | static void setValuesFromEnum(QHash<QString, int> &hash, const QMetaEnum &metaEnum) |
| 24 | { |
| 25 | hash.reserve(metaEnum.keyCount() - 1); |
| 26 | for (int i = 0; i < metaEnum.keyCount(); i++) { |
| 27 | if (metaEnum.value(i) != -1) |
| 28 | hash[QLatin1String(metaEnum.key(i))] = metaEnum.value(i); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | QGamepadInput::QGamepadInput(Qt3DCore::QNode *parent) |
| 33 | : QAbstractPhysicalDevice(*new QGamepadInputPrivate, parent) |
| 34 | { |
| 35 | Q_D(QGamepadInput); |
| 36 | auto metaObject = QGamepadManager::instance()->metaObject(); |
| 37 | for (int i = metaObject->enumeratorOffset(); i < metaObject->enumeratorCount(); ++i) { |
| 38 | auto metaEnum = metaObject->enumerator(i); |
| 39 | if (metaEnum.name() == std::string("GamepadButton")) |
| 40 | setValuesFromEnum(d->m_buttonsHash, metaEnum); |
| 41 | else if (metaEnum.name() == std::string("GamepadAxis")) |
| 42 | setValuesFromEnum(d->m_axesHash, metaEnum); |
| 43 | } |
| 44 | connect(QGamepadManager::instance(), &QGamepadManager::gamepadAxisEvent, this, [this, d](int deviceId, QGamepadManager::GamepadAxis axis, double value) { |
| 45 | if (deviceId == d_func()->m_deviceId) |
| 46 | d->postAxisEvent(axis, value); |
| 47 | }); |
| 48 | connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonPressEvent, this, [this, d](int deviceId, QGamepadManager::GamepadButton button, double value) { |
| 49 | if (deviceId == d_func()->m_deviceId) |
| 50 | d->postButtonEvent(button, value); |
| 51 | }); |
| 52 | connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonReleaseEvent, this, [this, d](int deviceId, QGamepadManager::GamepadButton button) { |
| 53 | if (deviceId == d_func()->m_deviceId) |
| 54 | d->postButtonEvent(button, 0); |
| 55 | }); |
| 56 | } |
| 57 | |
| 58 | int QGamepadInput::deviceId() const |
| 59 | { |
| 60 | return d_func()->m_deviceId; |
| 61 | } |
| 62 | |
| 63 | void QGamepadInput::setDeviceId(int deviceId) |
| 64 | { |
| 65 | Q_D(QGamepadInput); |
| 66 | if (d->m_deviceId == deviceId) |
| 67 | return; |
| 68 | |
| 69 | d->m_deviceId = deviceId; |
| 70 | emit deviceIdChanged(); |
| 71 | } |
| 72 | |
| 73 | } // Qt3DInput |
| 74 | QT_END_NAMESPACE |