-
Notifications
You must be signed in to change notification settings - Fork 226
/
DirectXTKSimpleSample12.cpp
508 lines (398 loc) · 15.2 KB
/
DirectXTKSimpleSample12.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
//--------------------------------------------------------------------------------------
// DirectXTKSimpleSample12.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "DirectXTKSimpleSample12.h"
extern void ExitSample() noexcept;
using namespace DirectX;
using namespace DirectX::SimpleMath;
using Microsoft::WRL::ComPtr;
Sample::Sample() noexcept(false)
{
m_deviceResources = std::make_unique<DX::DeviceResources>();
m_deviceResources->RegisterDeviceNotify(this);
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation)
{
m_gamePad = std::make_unique<GamePad>();
m_keyboard = std::make_unique<Keyboard>();
m_keyboard->SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window));
m_mouse = std::make_unique<Mouse>();
m_mouse->SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window));
m_deviceResources->SetWindow(window, width, height, rotation);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
// Create DirectXTK for Audio objects
AUDIO_ENGINE_FLAGS eflags = AudioEngine_Default;
#ifdef _DEBUG
eflags = eflags | AudioEngine_Debug;
#endif
m_audEngine = std::make_unique<AudioEngine>(eflags);
m_audioEvent = 0;
m_audioTimerAcc = 10.f;
m_retryDefault = false;
m_waveBank = std::make_unique<WaveBank>(m_audEngine.get(), L"adpcmdroid.xwb");
m_soundEffect = std::make_unique<SoundEffect>(m_audEngine.get(), L"MusicMono_adpcm.wav");
m_effect1 = m_soundEffect->CreateInstance();
m_effect2 = m_waveBank->CreateInstance(10);
m_effect1->Play(true);
m_effect2->Play();
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
m_timer.Tick([&]()
{
Update(m_timer);
});
// Only update audio engine once per frame
if (!m_audEngine->IsCriticalError() && m_audEngine->Update())
{
// Setup a retry in 1 second
m_audioTimerAcc = 1.f;
m_retryDefault = true;
}
Render();
}
// Updates the world.
void Sample::Update(DX::StepTimer const& timer)
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update");
Vector3 eye(0.0f, 0.7f, 1.5f);
Vector3 at(0.0f, -0.1f, 0.0f);
m_view = Matrix::CreateLookAt(eye, at, Vector3::UnitY);
m_world = Matrix::CreateRotationY(float(timer.GetTotalSeconds() * XM_PIDIV4));
m_lineEffect->SetView(m_view);
m_lineEffect->SetWorld(Matrix::Identity);
m_shapeEffect->SetView(m_view);
m_audioTimerAcc -= (float)timer.GetElapsedSeconds();
if (m_audioTimerAcc < 0)
{
if (m_retryDefault)
{
m_retryDefault = false;
if (m_audEngine->Reset())
{
// Restart looping audio
m_effect1->Play(true);
}
}
else
{
m_audioTimerAcc = 4.f;
m_waveBank->Play(m_audioEvent++);
if (m_audioEvent >= 11)
m_audioEvent = 0;
}
}
auto pad = m_gamePad->GetState(0);
if (pad.IsConnected())
{
m_gamePadButtons.Update(pad);
if (pad.IsViewPressed())
{
ExitSample();
}
}
else
{
m_gamePadButtons.Reset();
}
auto kb = m_keyboard->GetState();
m_keyboardButtons.Update(kb);
if (kb.Escape)
{
ExitSample();
}
auto mouse = m_mouse->GetState();
mouse;
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 command list to render a new frame.
m_deviceResources->Prepare();
Clear();
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Render");
// Draw procedurally generated dynamic grid
const XMVECTORF32 xaxis = { 20.f, 0.f, 0.f };
const XMVECTORF32 yaxis = { 0.f, 0.f, 20.f };
DrawGrid(xaxis, yaxis, g_XMZero, 20, 20, Colors::Gray);
// Set the descriptor heaps
ID3D12DescriptorHeap* heaps[] = { m_resourceDescriptors->Heap(), m_states->Heap() };
commandList->SetDescriptorHeaps(_countof(heaps), heaps);
// Draw sprite
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Draw sprite");
m_sprites->Begin(commandList);
m_sprites->Draw(m_resourceDescriptors->GetGpuHandle(Descriptors::WindowsLogo), GetTextureSize(m_texture2.Get()),
XMFLOAT2(10, 75));
m_font->DrawString(m_sprites.get(), L"DirectXTK Simple Sample", XMFLOAT2(100, 10), Colors::Yellow);
m_sprites->End();
PIXEndEvent(commandList);
// Draw 3D object
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Draw teapot");
XMMATRIX local = m_world * Matrix::CreateTranslation(-2.f, -2.f, -4.f);
m_shapeEffect->SetWorld(local);
m_shapeEffect->Apply(commandList);
m_shape->Draw(commandList);
PIXEndEvent(commandList);
// Draw model
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Draw model");
const XMVECTORF32 scale = { 0.01f, 0.01f, 0.01f };
const XMVECTORF32 translate = { 3.f, -2.f, -4.f };
XMVECTOR rotate = Quaternion::CreateFromYawPitchRoll(XM_PI / 2.f, 0.f, -XM_PI / 2.f);
local = m_world * XMMatrixTransformation(g_XMZero, Quaternion::Identity, scale, g_XMZero, rotate, translate);
Model::UpdateEffectMatrices(m_modelEffects, local, m_view, m_projection);
heaps[0] = m_modelResources->Heap();
commandList->SetDescriptorHeaps(_countof(heaps), heaps);
m_model->Draw(commandList, m_modelEffects.begin());
PIXEndEvent(commandList);
PIXEndEvent(commandList);
// Show the new frame.
PIXBeginEvent(m_deviceResources->GetCommandQueue(), PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
m_graphicsMemory->Commit(m_deviceResources->GetCommandQueue());
PIXEndEvent(m_deviceResources->GetCommandQueue());
}
// Helper method to clear the back buffers.
void Sample::Clear()
{
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto dsvDescriptor = m_deviceResources->GetDepthStencilView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, &dsvDescriptor);
commandList->ClearRenderTargetView(rtvDescriptor, Colors::CornflowerBlue, 0, nullptr);
commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
PIXEndEvent(commandList);
}
void XM_CALLCONV Sample::DrawGrid(FXMVECTOR xAxis, FXMVECTOR yAxis, FXMVECTOR origin, size_t xdivs, size_t ydivs, GXMVECTOR color)
{
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Draw grid");
m_lineEffect->Apply(commandList);
m_batch->Begin(commandList);
xdivs = std::max<size_t>(1, xdivs);
ydivs = std::max<size_t>(1, ydivs);
for (size_t i = 0; i <= xdivs; ++i)
{
float fPercent = float(i) / float(xdivs);
fPercent = (fPercent * 2.0f) - 1.0f;
XMVECTOR vScale = XMVectorScale(xAxis, fPercent);
vScale = XMVectorAdd(vScale, origin);
VertexPositionColor v1(XMVectorSubtract(vScale, yAxis), color);
VertexPositionColor v2(XMVectorAdd(vScale, yAxis), color);
m_batch->DrawLine(v1, v2);
}
for (size_t i = 0; i <= ydivs; i++)
{
float fPercent = float(i) / float(ydivs);
fPercent = (fPercent * 2.0f) - 1.0f;
XMVECTOR vScale = XMVectorScale(yAxis, fPercent);
vScale = XMVectorAdd(vScale, origin);
VertexPositionColor v1(XMVectorSubtract(vScale, xAxis), color);
VertexPositionColor v2(XMVectorAdd(vScale, xAxis), color);
m_batch->DrawLine(v1, v2);
}
m_batch->End();
PIXEndEvent(commandList);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnActivated()
{
}
void Sample::OnDeactivated()
{
}
void Sample::OnSuspending()
{
m_audEngine->Suspend();
}
void Sample::OnResuming()
{
m_timer.ResetElapsedTime();
m_gamePadButtons.Reset();
m_keyboardButtons.Reset();
m_audEngine->Resume();
}
void Sample::OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation)
{
if (!m_deviceResources->WindowSizeChanged(width, height, rotation))
return;
CreateWindowSizeDependentResources();
}
void Sample::ValidateDevice()
{
m_deviceResources->ValidateDevice();
}
void Sample::NewAudioDevice()
{
if (m_audEngine && !m_audEngine->IsAudioDevicePresent())
{
// Setup a retry in 1 second
m_audioTimerAcc = 1.f;
m_retryDefault = true;
}
}
// Properties
void Sample::GetDefaultSize(int& width, int& height) const
{
width = 1280;
height = 720;
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Sample::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
m_graphicsMemory = std::make_unique<GraphicsMemory>(device);
m_states = std::make_unique<CommonStates>(device);
m_resourceDescriptors = std::make_unique<DescriptorHeap>(device, Descriptors::Count);
m_batch = std::make_unique<PrimitiveBatch<VertexPositionColor>>(device);
m_shape = GeometricPrimitive::CreateTeapot(4.f, 8);
// SDKMESH has to use clockwise winding with right-handed coordinates, so textures are flipped in U
m_model = Model::CreateFromSDKMESH(device, L"tiny.sdkmesh");
{
ResourceUploadBatch resourceUpload(device);
resourceUpload.Begin();
m_model->LoadStaticBuffers(device, resourceUpload);
DX::ThrowIfFailed(
CreateDDSTextureFromFile(device, resourceUpload, L"assets\\seafloor.dds", m_texture1.ReleaseAndGetAddressOf())
);
CreateShaderResourceView(device, m_texture1.Get(), m_resourceDescriptors->GetCpuHandle(Descriptors::SeaFloor));
DX::ThrowIfFailed(
CreateDDSTextureFromFile(device, resourceUpload, L"assets\\windowslogo.dds", m_texture2.ReleaseAndGetAddressOf())
);
CreateShaderResourceView(device, m_texture2.Get(), m_resourceDescriptors->GetCpuHandle(Descriptors::WindowsLogo));
RenderTargetState rtState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
{
EffectPipelineStateDescription pd(
&VertexPositionColor::InputLayout,
CommonStates::Opaque,
CommonStates::DepthNone,
CommonStates::CullNone,
rtState,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE);
m_lineEffect = std::make_unique<BasicEffect>(device, EffectFlags::VertexColor, pd);
}
{
EffectPipelineStateDescription pd(
&GeometricPrimitive::VertexType::InputLayout,
CommonStates::Opaque,
CommonStates::DepthDefault,
CommonStates::CullNone,
rtState);
m_shapeEffect = std::make_unique<BasicEffect>(device, EffectFlags::PerPixelLighting | EffectFlags::Texture, pd);
m_shapeEffect->EnableDefaultLighting();
m_shapeEffect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::SeaFloor), m_states->AnisotropicWrap());
}
{
SpriteBatchPipelineStateDescription pd(rtState);
m_sprites = std::make_unique<SpriteBatch>(device, resourceUpload, pd);
}
m_modelResources = m_model->LoadTextures(device, resourceUpload, L"assets\\");
{
EffectPipelineStateDescription psd(
nullptr,
CommonStates::Opaque,
CommonStates::DepthDefault,
CommonStates::CullClockwise, // Using RH coordinates, and SDKMESH is in LH coordiantes
rtState);
EffectPipelineStateDescription alphapsd(
nullptr,
CommonStates::NonPremultiplied, // Using straight alpha
CommonStates::DepthRead,
CommonStates::CullClockwise, // Using RH coordinates, and SDKMESH is in LH coordiantes
rtState);
m_modelEffects = m_model->CreateEffects(psd, alphapsd, m_modelResources->Heap(), m_states->Heap());
}
m_font = std::make_unique<SpriteFont>(device, resourceUpload,
L"SegoeUI_18.spritefont",
m_resourceDescriptors->GetCpuHandle(Descriptors::SegoeFont),
m_resourceDescriptors->GetGpuHandle(Descriptors::SegoeFont));
// Upload the resources to the GPU.
auto uploadResourcesFinished = resourceUpload.End(m_deviceResources->GetCommandQueue());
// Wait for the upload thread to terminate
uploadResourcesFinished.wait();
}
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
auto size = m_deviceResources->GetOutputSize();
float aspectRatio = float(size.right) / float(size.bottom);
float fovAngleY = 70.0f * XM_PI / 180.0f;
// This is a simple example of change that can be made when the app is in
// portrait or snapped view.
if (aspectRatio < 1.0f)
{
fovAngleY *= 2.0f;
}
// Note that the OrientationTransform3D matrix is post-multiplied here
// in order to correctly orient the scene to match the display orientation.
// This post-multiplication step is required for any draw calls that are
// made to the swap chain render target. For draw calls to other targets,
// this transform should not be applied.
// This sample makes use of a right-handed coordinate system using row-major matrices.
Matrix perspectiveMatrix = Matrix::CreatePerspectiveFieldOfView(
fovAngleY,
aspectRatio,
0.01f,
100.0f
);
Matrix orientationMatrix = m_deviceResources->GetOrientationTransform3D();
m_projection = perspectiveMatrix * orientationMatrix;
m_lineEffect->SetProjection(m_projection);
m_shapeEffect->SetProjection(m_projection);
auto viewport = m_deviceResources->GetScreenViewport();
m_sprites->SetViewport(viewport);
m_sprites->SetRotation(m_deviceResources->GetRotation());
}
void Sample::OnDeviceLost()
{
m_texture1.Reset();
m_texture2.Reset();
m_font.reset();
m_batch.reset();
m_shape.reset();
m_model.reset();
m_lineEffect.reset();
m_shapeEffect.reset();
m_modelEffects.clear();
m_modelResources.reset();
m_sprites.reset();
m_resourceDescriptors.reset();
m_states.reset();
m_graphicsMemory.reset();
}
void Sample::OnDeviceRestored()
{
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
#pragma endregion