-
Notifications
You must be signed in to change notification settings - Fork 226
/
GamepadVibration.cpp
575 lines (471 loc) · 19.3 KB
/
GamepadVibration.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
//--------------------------------------------------------------------------------------
// GamepadVibration.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "GamepadVibration.h"
#include "ATGColors.h"
#include "ControllerFont.h"
extern void ExitSample() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
using namespace Windows::Xbox::Input;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
namespace
{
static const wchar_t* c_TRIGGER_EFFECT_NAME_TEXT[Sample::TRIGGEREFFECTS_MAX] =
{
L"<Trigger Test>\n",
L"<Flat Tire>\n",
L"<Gun with Recoil>\n",
L"<Heartbeat>\n",
L"<Footsteps>\n"
};
static const wchar_t* c_TRIGGER_EFFECT_DESC_TEXT[Sample::TRIGGEREFFECTS_MAX] =
{
L"Use the [LT] and [RT] to test the feedback\n"
L"function of the gamepad. The envelope is set based on\n"
L"the trigger position. The more you pull the triggers,\n"
L"the more feedback you will feel.",
L"Impulse triggers can provide feedback about the environment.\n"
L"Assuming the player is driving a car, this example uses\n"
L"the impulse triggers to inform a flat tire on the left side.",
L"Demonstrates how impulse triggers can be combined with the\n"
L"vibration motors to simulate weapon firing and recoil.\n"
L"Press the [LT] to activate the effect.",
L"Impulse triggers can relay information about the player\'s\n"
L"in-game representation. Here we relay the character\'s\n"
L"heartbeat, which can be used to let the player know that\n"
L"their character is exhausted.",
L"Impulse triggers can relay information external to the\n"
L"player. This example use the impulse triggers to simulate\n"
L"footsteps which could indicate the presence of a nearby\n"
L"character."
};
uint32_t flatTireLeftTriggerDurations[] = { 33, 80, 16 };
float flatTireLeftTriggerLevels[] = { 0.8f, 0.0f, 0.0f };
uint32_t gunWithRecoilLeftTriggerDurations[] = { 20, 10, 90, 10000 };
float gunWithRecoilLeftTriggerLevels[] = { 1.0f, 0.0f, 0.0f, 0.0f };
uint32_t heartbeatLeftTriggerDurations[] = { 25, 200, 25, 10, 745 };
float heartbeatLeftTriggerLevels[] = { 0.2f, 0.0f, 0.0f, 0.0f, 0.0f };
uint32_t heartbeatRightTriggerDurations[] = { 25, 200, 25, 10, 745 };
float heartbeatRightTriggerLevels[] = { 0.0f, 0.0f, 0.2f, 0.02f, 0.0f };
uint32_t footstepsLeftTriggerDurations[] = { 25, 600, 25, 600 };
float footstepsLeftTriggerLevels[] = { 0.3f, 0.0f, 0.0f, 0.0f };
uint32_t footstepsRightTriggerDurations[] = { 25, 600, 25, 600 };
float footstepsRightTriggerLevels[] = { 0.0f, 0.0f, 0.3f, 0.0f };
}
//--------------------------------------------------------------------------------------
// Helper class for managing the gamepads
//--------------------------------------------------------------------------------------
namespace GamepadManager
{
IGamepad^ GetMostRecentGamepad()
{
IGamepad^ gamepad = nullptr;
auto allGamepads = Gamepad::Gamepads;
if (allGamepads->Size > 0)
{
gamepad = allGamepads->GetAt(0);
}
return gamepad;
}
bool IsGamepadValid(IGamepad^ gamepad)
{
IIterator<IGamepad^>^ it = Gamepad::Gamepads->First();
while (it->HasCurrent)
{
if (gamepad == it->Current)
{
return true;
}
it->MoveNext();
}
return false;
}
};
Sample::Sample() noexcept(false) :
m_currentGamepadNeedsRefresh(false),
m_connected(false),
m_leftMotorSpeed(0),
m_leftTriggerLevel(0),
m_rightMotorSpeed(0),
m_rightTriggerLevel(0),
m_dPadPressed(false),
m_selectedTriggerEffect(TRIGGEREFFECTS::TRIGGEREFFECTS_IMPULSETEST),
m_triggerEffectCounter(0),
m_leftTriggerArraySize(0),
m_pLeftTriggerDurations(nullptr),
m_pLeftTriggerLevels(nullptr),
m_rightTriggerArraySize(0),
m_pRightTriggerDurations(nullptr),
m_pRightTriggerLevels(nullptr),
m_leftTriggerIndex(0),
m_rightTriggerIndex(0),
m_frequency(0),
m_counter(0),
m_leftTriggerIndexUpdateTime(0),
m_rightTriggerIndexUpdateTime(0)
{
m_deviceResources = std::make_unique<DX::DeviceResources>();
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(IUnknown* window)
{
m_deviceResources->SetWindow(window);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
m_selectedTriggerEffect = TRIGGEREFFECTS::TRIGGEREFFECTS_IMPULSETEST;
m_currentGamepad = GamepadManager::GetMostRecentGamepad();
m_currentGamepadNeedsRefresh = false;
m_connected = false;
Gamepad::GamepadAdded += ref new EventHandler<GamepadAddedEventArgs^ >([=](Platform::Object^, GamepadAddedEventArgs^ args)
{
m_currentGamepadNeedsRefresh = true;
});
Gamepad::GamepadRemoved += ref new EventHandler<GamepadRemovedEventArgs^ >([=](Platform::Object^, GamepadRemovedEventArgs^ args)
{
m_currentGamepadNeedsRefresh = true;
});
QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER *>(&m_frequency));
}
void Sample::InitializeCurrentGamepad()
{
if (m_currentGamepad)
{
m_reading = m_currentGamepad->GetCurrentReading();
ZeroMemory(&m_vibration, sizeof(GamepadVibration));
m_dPadPressed = false;
m_selectedTriggerEffect = TRIGGEREFFECTS::TRIGGEREFFECTS_IMPULSETEST;
InitializeImpulseTriggerEffects();
}
}
void Sample::ShutdownCurrentGamepad()
{
if (m_currentGamepad && GamepadManager::IsGamepadValid(m_currentGamepad))
{
GamepadVibration vibration = {};
m_currentGamepad->SetVibration(vibration);
}
}
//--------------------------------------------------------------------------------------
// Name: InitializeImpulseTriggerEffects()
// Desc: Clear variables used by the tigger effects and initialize them as needed for
// the currently selected effect.
//--------------------------------------------------------------------------------------
void Sample::InitializeImpulseTriggerEffects()
{
m_leftTriggerIndex = 0;
m_rightTriggerIndex = 0;
m_leftMotorSpeed = 0;
m_leftTriggerLevel = 0;
m_rightMotorSpeed = 0;
m_rightTriggerLevel = 0;
m_triggerEffectCounter = 0;
switch (m_selectedTriggerEffect)
{
case TRIGGEREFFECTS::TRIGGEREFFECTS_IMPULSETEST:
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_FLATTIRE:
m_leftTriggerArraySize = 3;
m_pLeftTriggerDurations = flatTireLeftTriggerDurations;
m_pLeftTriggerLevels = flatTireLeftTriggerLevels;
// Set the timing for the transition to the second vibration level
// Further transition timings will be handled by the transition code.
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_GUNWITHRECOIL:
m_leftTriggerArraySize = 4;
m_pLeftTriggerDurations = gunWithRecoilLeftTriggerDurations;
m_pLeftTriggerLevels = gunWithRecoilLeftTriggerLevels;
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_HEARTBEAT:
m_leftTriggerArraySize = 5;
m_rightTriggerArraySize = 5;
m_pLeftTriggerDurations = heartbeatLeftTriggerDurations;
m_pLeftTriggerLevels = heartbeatLeftTriggerLevels;
m_pRightTriggerDurations = heartbeatRightTriggerDurations;
m_pRightTriggerLevels = heartbeatRightTriggerLevels;
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
m_rightTriggerIndexUpdateTime = m_counter + (m_frequency * m_pRightTriggerDurations[m_rightTriggerIndex]) / 1000;
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_FOOTSTEPS:
m_leftTriggerArraySize = 4;
m_rightTriggerArraySize = 4;
m_pLeftTriggerDurations = footstepsLeftTriggerDurations;
m_pLeftTriggerLevels = footstepsLeftTriggerLevels;
m_pRightTriggerDurations = footstepsRightTriggerDurations;
m_pRightTriggerLevels = footstepsRightTriggerLevels;
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
m_rightTriggerIndexUpdateTime = m_counter + (m_frequency * m_pRightTriggerDurations[m_rightTriggerIndex]) / 1000;
break;
default:
assert(false);
}
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame");
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
PIXEndEvent();
}
// Updates the world.
void Sample::Update(DX::StepTimer const& )
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update");
if (m_currentGamepadNeedsRefresh)
{
auto mostRecentGamepad = GamepadManager::GetMostRecentGamepad();
if (m_currentGamepad != mostRecentGamepad)
{
ShutdownCurrentGamepad();
m_currentGamepad = mostRecentGamepad;
InitializeCurrentGamepad();
}
m_currentGamepadNeedsRefresh = false;
}
if (m_currentGamepad == nullptr)
{
m_connected = false;
PIXEndEvent();
return;
}
m_connected = true;
m_reading = m_currentGamepad->GetCurrentReading();
if (m_reading->IsViewPressed)
{
ExitSample();
}
if (!m_dPadPressed)
{
if (m_reading->IsDPadRightPressed)
{
m_dPadPressed = true;
m_selectedTriggerEffect = static_cast<TRIGGEREFFECTS>((static_cast<int>(m_selectedTriggerEffect) + 1) % TRIGGEREFFECTS_MAX);
InitializeImpulseTriggerEffects();
}
else if (m_reading->IsDPadLeftPressed)
{
m_dPadPressed = true;
m_selectedTriggerEffect = static_cast<TRIGGEREFFECTS>((static_cast<int>(m_selectedTriggerEffect) + TRIGGEREFFECTS_MAX - 1) % TRIGGEREFFECTS_MAX);
InitializeImpulseTriggerEffects();
}
}
else
{
if (static_cast<int>(m_reading->Buttons & (GamepadButtons::DPadRight | GamepadButtons::DPadLeft)) == 0)
{
m_dPadPressed = false;
}
}
switch (m_selectedTriggerEffect)
{
case TRIGGEREFFECTS::TRIGGEREFFECTS_IMPULSETEST:
// This example uses a very simple vibration envelope waveform by setting the vibration
// levels to the current trigger values. This means the more you pull the triggers, the more
// vibration you will feel.
m_leftTriggerLevel = m_reading->LeftTrigger;
m_rightTriggerLevel = m_reading->RightTrigger;
m_leftMotorSpeed = m_reading->LeftTrigger;
m_rightMotorSpeed = m_reading->RightTrigger;
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_FLATTIRE:
m_leftTriggerLevel = m_pLeftTriggerLevels[m_leftTriggerIndex];
// If we've reached or passed the transition time, update m_leftTriggerIndexUpdateTime
// with the next transition time and update the effect index.
// This will cause the effect to change in the next loop iteration.
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
if (m_counter > m_leftTriggerIndexUpdateTime)
{
m_leftTriggerIndex = (m_leftTriggerIndex + 1) % m_leftTriggerArraySize;
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
}
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_GUNWITHRECOIL:
switch (m_triggerEffectCounter)
{
case 0: // Wait for the trigger to be fully released before
// the effect can begin
if (m_reading->LeftTrigger <= 1.0f / 255.0f)
{
m_triggerEffectCounter = 1;
}
break;
case 1: // Wait for the trigger to be depressed enough to cause the gun to fire
if (m_reading->LeftTrigger >= 32.0f / 255.0f)
{
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
m_triggerEffectCounter = 2;
}
break;
case 2: // Delay recoil a little after the bullet has left the gun
m_leftTriggerLevel = m_pLeftTriggerLevels[m_leftTriggerIndex];
if (m_leftTriggerIndex == 2)
{
m_leftMotorSpeed = 1.0f;
m_rightMotorSpeed = 1.0f;
}
else
{
m_leftMotorSpeed = 0.0f;
m_rightMotorSpeed = 0.0f;
}
if (m_leftTriggerIndex == 3)
{
m_leftTriggerIndex = 0;
m_triggerEffectCounter = 0;
break;
}
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
if (m_counter > m_leftTriggerIndexUpdateTime)
{
m_leftTriggerIndex = (m_leftTriggerIndex + 1) % m_leftTriggerArraySize;
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
}
break;
}
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_HEARTBEAT:
// use the left level/duration for both triggers
m_leftTriggerLevel = m_pLeftTriggerLevels[m_leftTriggerIndex];
m_rightTriggerLevel = m_pRightTriggerLevels[m_rightTriggerIndex];
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
if (m_counter > m_leftTriggerIndexUpdateTime)
{
m_leftTriggerIndex = (m_leftTriggerIndex + 1) % m_leftTriggerArraySize;
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
}
if (m_counter > m_rightTriggerIndexUpdateTime)
{
m_rightTriggerIndex = (m_rightTriggerIndex + 1) % m_rightTriggerArraySize;
m_rightTriggerIndexUpdateTime = m_counter + (m_frequency * m_pRightTriggerDurations[m_rightTriggerIndex]) / 1000;
}
break;
case TRIGGEREFFECTS::TRIGGEREFFECTS_FOOTSTEPS:
m_leftTriggerLevel = m_pLeftTriggerLevels[m_leftTriggerIndex];
m_rightTriggerLevel = m_pRightTriggerLevels[m_rightTriggerIndex];
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER *>(&m_counter));
if (m_counter > m_leftTriggerIndexUpdateTime)
{
m_leftTriggerIndex = (m_leftTriggerIndex + 1) % m_leftTriggerArraySize;
m_leftTriggerIndexUpdateTime = m_counter + (m_frequency * m_pLeftTriggerDurations[m_leftTriggerIndex]) / 1000;
}
if (m_counter > m_rightTriggerIndexUpdateTime)
{
m_rightTriggerIndex = (m_rightTriggerIndex + 1) % m_rightTriggerArraySize;
m_rightTriggerIndexUpdateTime = m_counter + (m_frequency * m_pRightTriggerDurations[m_rightTriggerIndex]) / 1000;
}
break;
default:
assert(false);
}
m_vibration.LeftMotorLevel = m_leftMotorSpeed;
m_vibration.RightMotorLevel = m_rightMotorSpeed;
m_vibration.LeftTriggerLevel = m_leftTriggerLevel;
m_vibration.RightTriggerLevel = m_rightTriggerLevel;
m_currentGamepad->SetVibration(m_vibration);
PIXEndEvent();
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Sample::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
// Prepare the render target to render a new frame.
m_deviceResources->Prepare();
Clear();
auto context = m_deviceResources->GetD3DDeviceContext();
PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Render");
auto rect = m_deviceResources->GetOutputSize();
auto safeRect = SimpleMath::Viewport::ComputeTitleSafeArea(rect.right, rect.bottom);
XMFLOAT2 pos(float(safeRect.left), float(safeRect.top));
m_spriteBatch->Begin();
m_spriteBatch->Draw(m_background.Get(), m_deviceResources->GetOutputSize());
if (m_connected)
{
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(),
L"Use the [DPad] Left and Right to select a vibration effect.", pos, ATG::Colors::OffWhite);
pos.y += m_font->GetLineSpacing() * 2.f;
// Draw description
m_font->DrawString(m_spriteBatch.get(), c_TRIGGER_EFFECT_NAME_TEXT[static_cast<int>(m_selectedTriggerEffect)], pos, ATG::Colors::Green);
pos.y += m_font->GetLineSpacing() * 1.5f;
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(), c_TRIGGER_EFFECT_DESC_TEXT[static_cast<int>(m_selectedTriggerEffect)], pos);
}
else
{
m_font->DrawString(m_spriteBatch.get(), L"No controller connected", pos, ATG::Colors::Orange);
}
m_spriteBatch->End();
PIXEndEvent(context);
// Show the new frame.
PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
m_graphicsMemory->Commit();
PIXEndEvent(context);
}
// Helper method to clear the back buffers.
void Sample::Clear()
{
auto context = m_deviceResources->GetD3DDeviceContext();
PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto renderTarget = m_deviceResources->GetRenderTargetView();
context->ClearRenderTargetView(renderTarget, ATG::Colors::Background);
context->OMSetRenderTargets(1, &renderTarget, nullptr);
// Set the viewport.
auto viewport = m_deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
PIXEndEvent(context);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnSuspending()
{
auto context = m_deviceResources->GetD3DDeviceContext();
context->Suspend(0);
}
void Sample::OnResuming()
{
auto context = m_deviceResources->GetD3DDeviceContext();
context->Resume();
m_timer.ResetElapsedTime();
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Sample::CreateDeviceDependentResources()
{
auto context = m_deviceResources->GetD3DDeviceContext();
auto device = m_deviceResources->GetD3DDevice();
m_graphicsMemory = std::make_unique<GraphicsMemory>(device, m_deviceResources->GetBackBufferCount());
m_spriteBatch = std::make_unique<SpriteBatch>(context);
m_font = std::make_unique<SpriteFont>(device, L"SegoeUI_18.spritefont");
m_ctrlFont = std::make_unique<SpriteFont>(device, L"XboxOneControllerLegendSmall.spritefont");
DX::ThrowIfFailed(CreateDDSTextureFromFile(device, L"gamepad.dds", nullptr, m_background.ReleaseAndGetAddressOf()));
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
}
#pragma endregion