forked from briankendall/xboxToVJoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controllerremapper.cpp
616 lines (507 loc) · 19.5 KB
/
controllerremapper.cpp
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
#define NOMINMAX
#include <windows.h>
#include <XInput.h>
#include <QDebug>
#include "controllerremapper.h"
#include "public.h"
#include "vjoyinterface.h"
#include "dinputcorrelation.h"
#include <comdef.h>
#include <QSignalMapper>
#include <QDateTime>
#include <QSettings>
typedef DWORD (WINAPI* XInputGetStateEx_t)(DWORD dwUserIndex, XINPUT_STATE *pState);
XInputGetStateEx_t XInputGetStateEx = NULL;
const int buttonFlags[kButtonCount] = {XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_X, XINPUT_GAMEPAD_Y,
XINPUT_GAMEPAD_LEFT_SHOULDER, XINPUT_GAMEPAD_RIGHT_SHOULDER, XINPUT_GAMEPAD_BACK,
XINPUT_GAMEPAD_START, XINPUT_GAMEPAD_LEFT_THUMB, XINPUT_GAMEPAD_RIGHT_THUMB,
XINPUT_GAMEPAD_GUIDE};
const int directionFlags[4] = {XINPUT_GAMEPAD_DPAD_LEFT, XINPUT_GAMEPAD_DPAD_UP, XINPUT_GAMEPAD_DPAD_RIGHT,
XINPUT_GAMEPAD_DPAD_DOWN};
#define XBOX_REMAP_LT HID_USAGE_Z
#define XBOX_REMAP_RT HID_USAGE_RZ
#define XBOX_REMAP_LX HID_USAGE_X
#define XBOX_REMAP_LY HID_USAGE_Y
#define XBOX_REMAP_RX HID_USAGE_RX
#define XBOX_REMAP_RY HID_USAGE_RY
#define XBOX_REMAP_LT_NAME "Z"
#define XBOX_REMAP_RT_NAME "RZ"
#define XBOX_REMAP_LX_NAME "X"
#define XBOX_REMAP_LY_NAME "Y"
#define XBOX_REMAP_RX_NAME "RX"
#define XBOX_REMAP_RY_NAME "RY"
long clamp(long val, long min, long max)
{
if (val < min) {
val = min;
}
if (val > max) {
val = max;
}
return val;
}
long xboxAxisToVJoy(SHORT val, bool reverse)
{
long n = long(val) / 2 + 16384;
if (reverse) {
n = 32767 - n;
}
return clamp(n + 1, 1, 32768);
}
long xboxTriggerToVJoy(BYTE val)
{
return 1 + (val << 7) + (val >> 1);
}
bool directionPressed(const QVector<bool> &buttons, bool left, bool up, bool right, bool down)
{
return buttons[0] == left && buttons[1] == up && buttons[2] == right && buttons[3] == down;
}
void resetVJoyDevice(int deviceId)
{
ResetVJD(deviceId);
SetContPov(-1, deviceId, 1);
SetAxis(xboxTriggerToVJoy(0), deviceId, XBOX_REMAP_LT);
SetAxis(xboxTriggerToVJoy(0), deviceId, XBOX_REMAP_RT);
SetAxis(xboxAxisToVJoy(0, false), deviceId, XBOX_REMAP_LX);
SetAxis(xboxAxisToVJoy(0, true), deviceId, XBOX_REMAP_LY);
SetAxis(xboxAxisToVJoy(0, false), deviceId, XBOX_REMAP_RX);
SetAxis(xboxAxisToVJoy(0, true), deviceId, XBOX_REMAP_RY);
for (int i = 0; i < kButtonCount; ++i) {
SetBtn(false, deviceId, i+1);
}
}
#define kInteractionWaitTime 100
void Controller::initialize()
{
buttonsDown.fill(false, kButtonCount);
directionDown.fill(false, 4);
lastLeftTrigger = kAxisUnset;
lastRightTrigger = kAxisUnset;
lastLX = kAxisUnset;
lastLY = kAxisUnset;
lastRX = kAxisUnset;
lastRY = kAxisUnset;
lastPacketNumber = 0;
handledFirstPacket = false;
lastConnected = false;
}
void Controller::doControllerMap(UINT vjoyDeviceId)
{
XINPUT_STATE controllerState;
ZeroMemory(&controllerState, sizeof(XINPUT_STATE));
DWORD result = XInputGetStateEx(deviceIndex, &controllerState);
bool connected = (result == ERROR_SUCCESS);
if (!connected) {
if (lastConnected) {
qDebug() << "reseting device:" << vjoyDeviceId;
reset(vjoyDeviceId);
}
lastConnected = false;
return;
} else {
lastConnected = true;
}
if (lastPacketNumber == controllerState.dwPacketNumber && handledFirstPacket) {
// Xbox controller state hasn't changed, no need to do anything
return;
}
const XINPUT_GAMEPAD &state = controllerState.Gamepad;
handledFirstPacket = true;
lastPacketNumber = controllerState.dwPacketNumber;
for (int i = 0; i < kButtonCount; ++i) {
bool playerButtonDown = (state.wButtons & buttonFlags[i]) != 0;
if (playerButtonDown && !buttonsDown[i]) {
SetBtn(true, vjoyDeviceId, i+1);
} else if (!playerButtonDown && buttonsDown[i]) {
SetBtn(false, vjoyDeviceId, i+1);
}
buttonsDown[i] = playerButtonDown;
}
bool directionChanged = false;
for (int i = 0; i < 4; ++i) {
bool playerButtonDown = (state.wButtons & directionFlags[i]) != 0;
if (directionDown[i] != playerButtonDown) {
directionChanged = true;
directionDown[i] = playerButtonDown;
}
}
if (directionChanged) {
if (directionPressed(directionDown, true, false, false, false)) {
SetContPov(27000, vjoyDeviceId, 1);
} else if (directionPressed(directionDown, true, true, false, false)) {
SetContPov(31500, vjoyDeviceId, 1);
} else if (directionPressed(directionDown, false, true, false, false)) {
SetContPov(0, vjoyDeviceId, 1);
} else if (directionPressed(directionDown, false, true, true, false)) {
SetContPov(4500, vjoyDeviceId, 1);
} else if (directionPressed(directionDown, false, false, true, false)) {
SetContPov(9000, vjoyDeviceId, 1);
} else if (directionPressed(directionDown, false, false, true, true)) {
SetContPov(13500, vjoyDeviceId, 1);
} else if (directionPressed(directionDown, false, false, false, true)) {
SetContPov(18000, vjoyDeviceId, 1);
} else if (directionPressed(directionDown, true, false, false, true)) {
SetContPov(22500, vjoyDeviceId, 1);
} else {
SetContPov(-1, vjoyDeviceId, 1);
}
}
if (state.bLeftTrigger != lastLeftTrigger) {
SetAxis(xboxTriggerToVJoy(state.bLeftTrigger), vjoyDeviceId, XBOX_REMAP_LT);
lastLeftTrigger = state.bLeftTrigger;
}
if (state.bRightTrigger != lastRightTrigger) {
SetAxis(xboxTriggerToVJoy(state.bRightTrigger), vjoyDeviceId, XBOX_REMAP_RT);
lastRightTrigger = state.bRightTrigger;
}
if (state.sThumbLX != lastLX) {
SetAxis(xboxAxisToVJoy(state.sThumbLX, false), vjoyDeviceId, XBOX_REMAP_LX);
lastLX = state.sThumbLX;
}
if (state.sThumbLY != lastLY) {
SetAxis(xboxAxisToVJoy(state.sThumbLY, true), vjoyDeviceId, XBOX_REMAP_LY);
lastLY = state.sThumbLY;
}
if (state.sThumbRX != lastRX) {
SetAxis(xboxAxisToVJoy(state.sThumbRX, false), vjoyDeviceId, XBOX_REMAP_RX);
lastRX = state.sThumbRX;
}
if (state.sThumbRY != lastRY) {
SetAxis(xboxAxisToVJoy(state.sThumbRY, true), vjoyDeviceId, XBOX_REMAP_RY);
lastRY = state.sThumbRY;
}
}
void Controller::reset(UINT vjoyDeviceId)
{
initialize();
resetVJoyDevice(vjoyDeviceId);
}
ControllerRemapper::ControllerRemapper(HWND win, bool inEnabled, QObject *parent) :
QThread(parent), dinputWindow(win), errorOccurred(false), enabled(inEnabled)
{
}
void ControllerRemapper::throwInitError(QString msg)
{
emit initializationError(msg);
errorOccurred = true;
exit(1);
}
bool ControllerRemapper::checkAxisExists(UINT deviceId, UINT axis, QString axisName)
{
if (!GetVJDAxisExist(deviceId, axis)) {
throwInitError(QString("vJoy device %1 does not have the following axis: %2\nPlease make sure the first four vJoy devices have "
"this axis before launching.").arg(deviceId).arg(axisName));
return false;
} else {
return true;
}
}
bool ControllerRemapper::initializeVJoy()
{
if (!vJoyEnabled()) {
throwInitError("Failed Getting vJoy attributes. vJoy is not enabled.");
return false;
}
// Test interface DLL matches vJoy driver
// Compare versions
WORD VerDll, VerDrv;
if (!DriverMatch(&VerDll, &VerDrv)) {
throwInitError(QString("vJoy Driver (version %1) does not match vJoyInterface DLL (version %2)")
.arg(uint(VerDrv), 4, 16, QChar('0')).arg(uint(VerDll), 4, 16, QChar('0')));
return false;
}
return true;
}
void ControllerRemapper::initializeDevice(UINT deviceId)
{
// Get the state of the requested device
VjdStat status = GetVJDStatus(deviceId);
switch (status) {
case VJD_STAT_OWN:
qDebug("vJoy Device %d is already owned by this feeder", deviceId);
break;
case VJD_STAT_FREE:
qDebug("vJoy Device %d is free", deviceId);
break;
case VJD_STAT_BUSY:
throwInitError(QString("vJoy Device %1 is already owned by another feeder\nCannot continue.").arg(deviceId));
return;
case VJD_STAT_MISS:
throwInitError(QString("vJoy Device %1 is not installed or disabled\nCannot continue").arg(deviceId));
return;
default:
throwInitError(QString("vJoy Device %1 general error. Cannot continue.").arg(deviceId));
return;
}
if (!checkAxisExists(deviceId, XBOX_REMAP_LX, XBOX_REMAP_LX_NAME)) {
return;
}
if (!checkAxisExists(deviceId, XBOX_REMAP_LY, XBOX_REMAP_LY_NAME)) {
return;
}
if (!checkAxisExists(deviceId, XBOX_REMAP_RX, XBOX_REMAP_RX_NAME)) {
return;
}
if (!checkAxisExists(deviceId, XBOX_REMAP_RY, XBOX_REMAP_RY_NAME)) {
return;
}
if (!checkAxisExists(deviceId, XBOX_REMAP_LT, XBOX_REMAP_LT_NAME)) {
return;
}
if (!checkAxisExists(deviceId, XBOX_REMAP_RT, XBOX_REMAP_RT_NAME)) {
return;
}
// Get the number of buttons and POV Hat switches supported by this vJoy device
if (GetVJDButtonNumber(deviceId) < kButtonCount) {
throwInitError(QString("vJoy Device %1 does not have at least %2 buttons.\nPlease make sure "
"the first four vJoy devices all have %3 buttons or more before "
"launching.").arg(deviceId).arg(kButtonCount).arg(kButtonCount));
return;
}
if (GetVJDContPovNumber(deviceId) < 1) {
throwInitError(QString("vJoy Device %1 does not have at least one continuous POV hat switch.\nPlease make sure "
"the first four vJoy devices all have one or more continuous POV hat switches before launching.").arg(deviceId));
return;
}
// Acquire the target
if ((status == VJD_STAT_OWN) || ((status == VJD_STAT_FREE) && (!AcquireVJD(deviceId)))) {
throwInitError(QString("Failed to acquire vJoy device number %d.").arg(deviceId));
return;
} else {
qDebug() << "Acquired: vJoy device number" << deviceId;
}
initializedDevices.insert(deviceId);
}
HINSTANCE ControllerRemapper::getXInputDLLHandle()
{
HINSTANCE result = LoadLibrary(XINPUT_DLL);
if (result) {
return result;
}
result = LoadLibrary(L"xinput1_4.dll");
if (result) {
return result;
}
result = LoadLibrary(L"xinput9_1_0.dll");
if (result) {
return result;
}
result = LoadLibrary(L"xinput1_3");
if (result) {
return result;
}
return NULL;
}
void ControllerRemapper::initialize()
{
if (!initializeVJoy()) {
return;
}
controllerCount = 0;
for(UINT index = 0; index < 4; ++index) {
if (GetVJDStatus(index+1) == VJD_STAT_MISS) {
break;
} else {
controllerCount++;
}
}
if (controllerCount == 0) {
throwInitError("There doesn't seem to be any vJoy controllers.");
return;
}
for(UINT index = 0; index < controllerCount; ++index) {
initializeDevice(index+1);
if (errorOccurred) {
return;
}
controllers[index].deviceIndex = index;
controllers[index].initialize();
}
// Get access to XInputGetStateEx so we can query the state of the Guide/Home button:
if(!XInputGetStateEx) {
HINSTANCE hXInput = getXInputDLLHandle();
if (!hXInput) {
throwInitError("Could not get a handle to the XInput DLL.");
return;
}
XInputGetStateEx = (XInputGetStateEx_t) GetProcAddress(hXInput, (LPCSTR) 100);
if(!XInputGetStateEx) { // Might help with wrappers compatibility
XInputGetStateEx = (XInputGetStateEx_t) GetProcAddress(hXInput, "XInputGetState");
}
}
// In order to allow xboxToVJoy to be safely closed and reopened however many times the user likes
// (as pressing buttons on the controller can have unintended consequences)
// we will determine the dinput / vJoy correlation only when the app is launched the first time
// after the computer reboots. And we will keep track of when we need to determine the correlation
// by saving it and the date of when the computer last rebooted.
QSettings settings("xboxToVJoy");
QDateTime bootTime = QDateTime::currentDateTime().addMSecs(0LL - (LONGLONG)GetTickCount64());
QDateTime storedBootTime = settings.value("lastBoot").toDateTime();
QVariantMap storedXboxToVJoyMap = settings.value("xboxToVJoyMap").toMap();
if (storedBootTime.isValid() && storedXboxToVJoyMap.count() == 4 && abs(bootTime.msecsTo(storedBootTime)) < 5000) {
qDebug() << "Using last correlation results as the computer has not rebooted since then";
foreach(const QString &key, storedXboxToVJoyMap.keys()) {
xboxToVJoyMap[key.toUInt()] = storedXboxToVJoyMap[key].toUInt();
}
} else {
qDebug() << "Determining correlation...";
HRESULT winResult;
int result;
determineCorrelation(winResult, result, xboxToVJoyMap, dinputWindow, controllerCount);
if (FAILED(winResult)) {
_com_error err(winResult);
QString errorString = (LPSTR)err.ErrorMessage();
throwInitError(QString("vJoy controller correlation failed. Windows error: ") + errorString);
return;
}
if (result == kErrorNotEnoughVJoyDevices) {
throwInitError("There were fewer vJoy devices as reported by DirectInput than the number of vJoy Devices "
"as reported by vJoy itself.");
return;
}
if (result == kErrorCouldntCorrelate) {
throwInitError("One or more vJoy Devices could not be correlated with their DirectInput counterpart.");
return;
}
QVariantMap xboxToVJoyMapWritable;
foreach(UINT key, xboxToVJoyMap.keys()) {
xboxToVJoyMapWritable[QString::number(key)] = xboxToVJoyMap[key];
}
settings.setValue("lastBoot", QVariant(bootTime));
settings.setValue("xboxToVJoyMap", QVariant(xboxToVJoyMapWritable));
settings.sync();
}
for(UINT index = 0; index < controllerCount; ++index) {
controllers[index].reset(xboxToVJoyMap[index]);
}
}
void ControllerRemapper::deinitialize()
{
foreach(UINT deviceId, initializedDevices) {
qDebug() << "Resetting and relinquishing device" << deviceId;
resetVJoyDevice(deviceId);
RelinquishVJD(deviceId);
}
}
void ControllerRemapper::poll()
{
for(UINT index = 0; index < controllerCount; ++index) {
controllers[index].doControllerMap(xboxToVJoyMap[index]);
}
}
void ControllerRemapper::run()
{
initialize();
setPriority(QThread::HighestPriority);
pollTimer = new QTimer();
pollTimer->moveToThread(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(poll()), Qt::DirectConnection);
pollTimer->setTimerType(Qt::PreciseTimer);
pollTimer->setInterval(4);
if (enabled) {
pollTimer->start();
}
exec();
qDebug() << "Remap thread deinitializing...";
pollTimer->stop();
delete pollTimer;
deinitialize();
qDebug() << "Remap thread finished";
}
// Note: the following four functions are only meant to be used from the controller window,
// especially because they will block
void ControllerRemapper::pressButton(UINT controller, UINT xboxButton)
{
UINT vjoyDeviceId = xboxToVJoyMap[controller];
UCHAR button = 0;
for(UCHAR i = 0; i < kButtonCount; ++i) {
if (buttonFlags[i] == xboxButton) {
button = i+1;
break;
}
}
if (button == 0) {
qDebug() << "Error: tried to press invalid button";
return;
}
SetBtn(true, vjoyDeviceId, button);
Sleep(kInteractionWaitTime);
SetBtn(false, vjoyDeviceId, button);
}
void ControllerRemapper::moveJoystick(UINT controller, bool right, double xVal, double yVal)
{
UINT vjoyDeviceId = xboxToVJoyMap[controller];
UINT xAxis, yAxis;
if (right) {
xAxis = XBOX_REMAP_RX;
yAxis = XBOX_REMAP_RY;
} else {
xAxis = XBOX_REMAP_LX;
yAxis = XBOX_REMAP_LY;
}
int steps = 20;
int moveTimeMS = 100;
// We're gradually moving the joystick's position in order to simulate it actually
// being moved. This was necessary to get the controller window working with ePSXe.
for(int i = 0; i < steps; ++i) {
double u = double(i) / double(steps -1 );
SetAxis(LONG((xVal*u + 1.0)*16383.5) + 1, vjoyDeviceId, xAxis);
SetAxis(LONG((yVal*u + 1.0)*16383.5) + 1, vjoyDeviceId, yAxis);
Sleep(moveTimeMS/steps);
}
SetAxis(LONG((xVal + 1.0)*16383.5) + 1, vjoyDeviceId, xAxis);
SetAxis(LONG((yVal + 1.0)*16383.5) + 1, vjoyDeviceId, yAxis);
Sleep(kInteractionWaitTime);
for(int i = 0; i < steps; ++i) {
double u = 1.0 - (double(i) / double(steps -1 ));
SetAxis(LONG((xVal*u + 1.0)*16383.5) + 1, vjoyDeviceId, xAxis);
SetAxis(LONG((yVal*u + 1.0)*16383.5) + 1, vjoyDeviceId, yAxis);
Sleep(moveTimeMS/steps);
}
SetAxis(0x4000, vjoyDeviceId, xAxis);
SetAxis(0x4000, vjoyDeviceId, yAxis);
}
void ControllerRemapper::pressTrigger(UINT controller, bool right, double val)
{
UINT vjoyDeviceId = xboxToVJoyMap[controller];
UINT axis;
if (right) {
axis = XBOX_REMAP_RT;
} else {
axis = XBOX_REMAP_LT;
}
SetAxis(LONG(val*32767.0) + 1, vjoyDeviceId, axis);
Sleep(kInteractionWaitTime);
SetAxis(16384, vjoyDeviceId, axis);
}
void ControllerRemapper::moveDPad(UINT controller, int direction)
{
UINT vjoyDeviceId = xboxToVJoyMap[controller];
SetContPov(direction * 4500, vjoyDeviceId, 1);
Sleep(kInteractionWaitTime);
SetContPov(-1, vjoyDeviceId, 1);
}
bool ControllerRemapper::isEnabled()
{
return enabled;
}
void ControllerRemapper::setEnabled(bool inEnabled)
{
if (QThread::currentThread() != this) {
QMetaObject::invokeMethod(this, "setEnabled", Qt::QueuedConnection, Q_ARG(bool, inEnabled));
return;
}
if (!enabled && inEnabled) {
qDebug() << "Enabling remapping...";
pollTimer->start();
XInputEnable(true);
} else if (enabled && !inEnabled) {
qDebug() << "Disabling remapping...";
pollTimer->stop();
XInputEnable(false);
foreach(UINT deviceId, initializedDevices) {
resetVJoyDevice(deviceId);
}
}
enabled = inEnabled;
}