Repository navigation
Expand file tree
/
Copy pathgamepad.cpp
More file actions
99 lines (80 loc) · 2.63 KB
/
Copy pathgamepad.cpp
File metadata and controls
99 lines (80 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "gamepad.h"
#include <iostream>
#define CONTROLLER_WAIT_MS 1000
#define THREAD_SLEEP_TIME_MS 5
#define AUTO_SHAKE_DUR_MS 4000
constexpr uint16_t AUTO_SHAKE_DUR = AUTO_SHAKE_DUR_MS / THREAD_SLEEP_TIME_MS;
using std::cout;
using namespace std::chrono;
SDL_Gamepad *findController() {
SDL_UpdateGamepads();
int32_t count = 0;
SDL_JoystickID* gamepads = SDL_GetGamepads(&count);
return count > 0 ? SDL_OpenGamepad(gamepads[0]) : nullptr;
}
Gamepad::Gamepad(std::vector<ConfiguredButton> buttons)
: configButtons_(std::move(buttons)) {
controller_ = findController();
}
void Gamepad::Start() {
stopFlag_ = false;
thread_.reset(new std::thread(&Gamepad::run, this));
}
void Gamepad::Stop() {
stopFlag_ = true;
if (thread_.get() != nullptr) {
thread_->join();
}
}
std::vector<ConfiguredButton> &Gamepad::GetButtonStates() {
return configButtons_;
}
bool Gamepad::IsAutomaticShakeActive() const {
return automaticShake_;
}
void Gamepad::processAutoShake() {
if (!automaticShake_ && SDL_GetGamepadButton(controller_, SDL_GAMEPAD_BUTTON_BACK) &&
SDL_GetGamepadButton(controller_, SDL_GAMEPAD_BUTTON_START)) {
cout << "Automatic shake started\n";
automaticShake_ = true;
}
static uint16_t automatic_cnt = 0;
if (automaticShake_) {
automatic_cnt++;
if (automatic_cnt == AUTO_SHAKE_DUR) {
cout << "Automatic shake ended\n";
automaticShake_ = false;
automatic_cnt = 0;
}
}
}
void Gamepad::run() {
while (!stopFlag_) {
if (controller_ == nullptr) {
controller_ = findController();
while (controller_ == nullptr && !stopFlag_) {
controller_ = findController();
std::this_thread::sleep_for(milliseconds(CONTROLLER_WAIT_MS));
}
if (!stopFlag_)
cout << "Controller reconnected\n";
}
SDL_UpdateGamepads();
processAutoShake();
for (size_t i = 0; i < configButtons_.size(); i++) {
if (SDL_GetGamepadButton(controller_, configButtons_[i].button)) {
configButtons_[i].pending = true;
}
}
std::this_thread::sleep_for(milliseconds(THREAD_SLEEP_TIME_MS));
}
}
void Gamepad::HandleControllerDisconnected(SDL_Event const &event) {
if (event.type == SDL_EVENT_GAMEPAD_REMOVED) {
cout << "Controller disconnected\n";
if (controller_ && event.cdevice.which == SDL_GetJoystickID(SDL_GetGamepadJoystick(controller_))) {
SDL_CloseGamepad(controller_);
controller_ = nullptr;
}
}
}