-
Notifications
You must be signed in to change notification settings - Fork 0
/
Apollo.cpp
1443 lines (1208 loc) · 56.1 KB
/
Apollo.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "pch.h"
#include "Apollo.h"
#include "DDSTextureLoader12.h"
#include "QuadSphereGenerator.h"
#include "ReadData.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx12.h"
extern void ExitGame() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
Apollo::Apollo() noexcept :
m_window(nullptr),
m_outputWidth(1280),
m_outputHeight(720),
m_backBufferIndex(0),
m_rtvDescriptorSize(0),
m_dsvDescriptorSize(0),
m_cbvSrvDescriptorSize(0),
m_featureLevel(D3D_FEATURE_LEVEL_11_0),
m_fenceValues{}
{
}
Apollo::~Apollo()
{
// Ensure that the GPU is no longer referencing resources that are about to be destroyed.
WaitForGpu();
// Reset fullscreen state on destroy.
if (m_fullScreenMode)
DX::ThrowIfFailed(m_swapChain->SetFullscreenState(FALSE, NULL));
}
// Initialize the Direct3D resources required to run.
void Apollo::InitializeD3DResources(HWND window, int width, int height, UINT subDivideCount, UINT shadowMapSize, BOOL fullScreenMode)
{
m_window = window;
m_outputWidth = std::max(width, 1);
m_outputHeight = std::max(height, 1);
m_aspectRatio = static_cast<float>(m_outputWidth) / static_cast<float>(m_outputHeight);
m_fullScreenMode = fullScreenMode;
// Initialize values.
m_isFlightMode = true;
m_subDivideCount = subDivideCount;
m_shadowMapSize = shadowMapSize;
m_totalIBSize = 0;
m_totalIndexCount = 0;
m_staticVBSize = 0;
m_staticVertexCount = 0;
m_culledQuadCount = 0;
m_renderShadow = true;
m_lightRotation = true;
m_wireframe = false;
m_sceneBounds.Center = XMFLOAT3(0.0f, 0.0f, 0.0f);
m_sceneBounds.Radius = 160.0f;
m_camUp = DEFAULT_UP_VECTOR;
m_camForward = DEFAULT_FORWARD_VECTOR;
m_camRight = DEFAULT_RIGHT_VECTOR;
m_camYaw = 0.0f;
m_camPitch = 0.0f;
m_camPosition = XMVectorSet(0.0f, 0.0f, -500.0f, 0.0f);
m_camLookTarget = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
m_orbitMode = false;
m_camMoveSpeed = 30.0f;
m_camRotateSpeed = 0.5f;
m_worldMatrix = XMMatrixIdentity();
m_viewMatrix = XMMatrixLookAtLH(m_camPosition, m_camLookTarget, DEFAULT_UP_VECTOR);
m_lightDirection = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f);
m_lightDirection = XMVector3TransformCoord(m_lightDirection, XMMatrixRotationY(3.0f));
m_shadowTransform = IDENTITY_MATRIX;
m_lightNearZ = 0.0f;
m_lightFarZ = 0.0f;
m_lightPosition = XMFLOAT3(0.0f, 0.0f, 0.0f);
m_lightView = IDENTITY_MATRIX;
m_lightProj = IDENTITY_MATRIX;
m_quadWidth = 300.0f / pow(2.0f, TESS_GROUP_QUAD_LEVEL);
m_unitCount = pow(2.0f, m_subDivideCount - TESS_GROUP_QUAD_LEVEL);
m_tessMin = 0;
m_tessMax = 8;
CreateDeviceResources();
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
CreateCommandListDependentResources();
}
// Executes the basic game loop.
void Apollo::Tick()
{
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
}
void Apollo::OnKeyDown(UINT8 key)
{
if (key == VK_ESCAPE) // Exit game.
{
ExitGame();
return;
}
if (key == 'X') // Change mouse mode.
{
m_isFlightMode = !m_isFlightMode;
ShowCursor(!m_isFlightMode);
return;
}
m_keyTracker.insert_or_assign(key, true);
}
void Apollo::OnKeyUp(UINT8 key)
{
m_keyTracker.insert_or_assign(key, false);
}
void Apollo::OnMouseWheel(float delta)
{
// Scroll to adjust move speed.
m_camMoveSpeed = std::max(m_camMoveSpeed + delta * 0.05f, 0.0f);
}
void Apollo::OnMouseMove(int x, int y)
{
// If it's not flight mode, return.
if (!m_isFlightMode)
return;
// Flight mode camera rotation.
m_camYaw += x * 0.001f * m_camRotateSpeed;
m_camPitch = std::min(std::max(m_camPitch + y * 0.001f * m_camRotateSpeed, -XM_PIDIV2), XM_PIDIV2);
// Reset cursor position.
POINT pt = { m_outputWidth / 2, m_outputHeight / 2 };
ClientToScreen(m_window, &pt);
SetCursorPos(pt.x, pt.y);
}
// Updates the world.
void Apollo::Update(DX::StepTimer const& timer)
{
const auto elapsedTime = static_cast<float>(timer.GetElapsedSeconds());
// Set view matrix based on camera position and orientation.
m_camRotationMatrix = XMMatrixRotationRollPitchYaw(m_camPitch, m_camYaw, 0.0f);
m_camLookTarget = XMVector3TransformCoord(DEFAULT_FORWARD_VECTOR, m_camRotationMatrix);
m_camLookTarget = XMVector3Normalize(m_camLookTarget);
m_camRight = XMVector3TransformCoord(DEFAULT_RIGHT_VECTOR, m_camRotationMatrix);
m_camUp = XMVector3TransformCoord(DEFAULT_UP_VECTOR, m_camRotationMatrix);
m_camForward = XMVector3TransformCoord(DEFAULT_FORWARD_VECTOR, m_camRotationMatrix);
// Flight mode.
const float verticalMove = (m_keyTracker['W'] ? 1.0f : m_keyTracker['S'] ? -1.0f : 0.0f) * elapsedTime * m_camMoveSpeed;
const float horizontalMove = (m_keyTracker['A'] ? -1.0f : m_keyTracker['D'] ? 1.0f : 0.0f) * elapsedTime * m_camMoveSpeed;
m_camPosition += horizontalMove * m_camRight;
m_camPosition += verticalMove * m_camForward;
m_camLookTarget = m_camPosition + m_camLookTarget;
m_viewMatrix = XMMatrixLookAtLH(m_camPosition, m_camLookTarget, m_camUp);
// Do frustum culling.
{
// Update projection matrix.
m_projectionMatrix = XMMatrixPerspectiveFovLH(
XM_PIDIV4,
m_aspectRatio,
0.01f,
XMVector3Length(m_camPosition).m128_f32[0]);
// Update frustum.
BoundingFrustum bf;
auto det = XMMatrixDeterminant(m_viewMatrix);
BoundingFrustum(m_projectionMatrix).Transform(bf, XMMatrixInverse(&det, m_viewMatrix));
// Update index data each face tree.
m_culledQuadCount = 0;
for (int i = 0; i < 6; i++)
{
const uint32_t culledQuadCount = m_faceTrees[i]->UpdateIndexData(bf, m_totalIndexData);
m_culledQuadCount += culledQuadCount;
}
}
// Light rotation update.
if (m_lightRotation)
m_lightDirection = XMVector3TransformCoord(m_lightDirection, XMMatrixRotationY(elapsedTime / 24.0f));
// Update Shadow Transform.
{
XMVECTOR lightDir = m_lightDirection;
XMVECTOR lightPos = -2.0f * m_sceneBounds.Radius * lightDir;
XMVECTOR targetPos = XMLoadFloat3(&m_sceneBounds.Center);
XMVECTOR lightUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX lightView = XMMatrixLookAtLH(lightPos, targetPos, lightUp);
XMStoreFloat3(&m_lightPosition, lightPos);
// Transform bounding sphere to light space.
XMFLOAT3 sphereCenterLS;
XMStoreFloat3(&sphereCenterLS, XMVector3TransformCoord(targetPos, lightView));
// Ortho frustum in light space encloses scene.
float l = sphereCenterLS.x - m_sceneBounds.Radius;
float b = sphereCenterLS.y - m_sceneBounds.Radius;
float n = sphereCenterLS.z - m_sceneBounds.Radius;
float r = sphereCenterLS.x + m_sceneBounds.Radius;
float t = sphereCenterLS.y + m_sceneBounds.Radius;
float f = sphereCenterLS.z + m_sceneBounds.Radius;
m_lightNearZ = n;
m_lightFarZ = f;
XMMATRIX lightProj = XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f);
// Transform NDC space [-1,+1]^2 to texture space [0,1]^2
XMMATRIX T(
0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f);
XMMATRIX S = lightView * lightProj * T;
XMStoreFloat4x4(&m_lightView, lightView);
XMStoreFloat4x4(&m_lightProj, lightProj);
XMStoreFloat4x4(&m_shadowTransform, S);
}
}
// Draws the scene.
void Apollo::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
// Upload index data to GPU.
{
DX::ThrowIfFailed(m_commandAllocators[m_backBufferIndex]->Reset());
DX::ThrowIfFailed(m_commandList->Reset(m_commandAllocators[m_backBufferIndex].Get(), nullptr));
// Update dynamic index buffer and upload to static index buffer.
{
for (FaceTree* faceTree : m_faceTrees)
faceTree->Upload(m_commandList.Get());
}
DX::ThrowIfFailed(m_commandList->Close());
m_commandQueue->ExecuteCommandLists(1, CommandListCast(m_commandList.GetAddressOf()));
}
WaitForGpu();
// ----------> Prepare command list.
DX::ThrowIfFailed(m_commandAllocators[m_backBufferIndex]->Reset());
DX::ThrowIfFailed(m_commandList->Reset(m_commandAllocators[m_backBufferIndex].Get(), nullptr));
// Set descriptor heaps.
m_commandList->SetDescriptorHeaps(1, m_srvDescriptorHeap.GetAddressOf());
// Set root signature & descriptor table.
m_commandList->SetGraphicsRootSignature(m_rootSignature.Get());
m_commandList->SetGraphicsRootDescriptorTable(0, m_srvDescriptorHeap->GetGPUDescriptorHandleForHeapStart());
// PASS 1 - Shadow Map
if (m_renderShadow)
{
// Update ShadowCB Data
{
ShadowCB cbShadow;
const XMMATRIX lightWorld = XMLoadFloat4x4(&IDENTITY_MATRIX);
const XMMATRIX lightView = XMLoadFloat4x4(&m_lightView);
const XMMATRIX lightProj = XMLoadFloat4x4(&m_lightProj);
cbShadow.lightWorldMatrix = XMMatrixTranspose(lightWorld);
cbShadow.lightViewProjMatrix = XMMatrixTranspose(lightView * lightProj);
cbShadow.cameraPosition = m_camPosition;
cbShadow.parameters = XMFLOAT4(m_quadWidth, m_unitCount, m_tessMin, m_tessMax - 2);
memcpy(&m_cbShadowMappedData[m_backBufferIndex], &cbShadow, sizeof(ShadowCB));
// Bind the constants to the shader.
const auto baseGpuAddress = m_cbShadowGpuAddress + m_backBufferIndex * sizeof(ShadowCB);
m_commandList->SetGraphicsRootConstantBufferView(2, baseGpuAddress);
}
// Set render target as nullptr.
const auto dsv = m_shadowMap->Dsv();
m_commandList->OMSetRenderTargets(0, nullptr, false, &dsv);
// Set PSO.
m_commandList->SetPipelineState(m_shadowPSO.Get());
// Set the viewport and scissor rect.
const auto viewport = m_shadowMap->Viewport();
const auto scissorRect = m_shadowMap->ScissorRect();
m_commandList->RSSetViewports(1, &viewport);
m_commandList->RSSetScissorRects(1, &scissorRect);
// Translate depth/stencil buffer to DEPTH_WRITE.
const D3D12_RESOURCE_BARRIER toWrite = CD3DX12_RESOURCE_BARRIER::Transition(
m_shadowMap->Resource(),
D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_DEPTH_WRITE);
m_commandList->ResourceBarrier(1, &toWrite);
// ---> DEPTH_WRITE
{
// Clear DSV.
m_commandList->ClearDepthStencilView(
m_shadowMap->Dsv(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
// Set Topology and VB.
m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);
m_commandList->IASetVertexBuffers(0, 1, &m_staticVBV);
// Set index buffer & draw all face trees.
for (const FaceTree* faceTree : m_faceTrees)
{
faceTree->Draw(m_commandList.Get());
}
}
// <--- GENERIC_READ
// Translate depth/stencil buffer to GENERIC_READ.
const D3D12_RESOURCE_BARRIER toRead = CD3DX12_RESOURCE_BARRIER::Transition(
m_shadowMap->Resource(),
D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_GENERIC_READ);
m_commandList->ResourceBarrier(1, &toRead);
}
// PASS 2 - Opaque.
{
// Update OpaqueCB data.
{
OpaqueCB cbOpaque;
cbOpaque.worldMatrix = XMMatrixTranspose(m_worldMatrix);
cbOpaque.viewProjMatrix = XMMatrixTranspose(m_viewMatrix * m_projectionMatrix);
XMStoreFloat4(&cbOpaque.cameraPosition, m_camPosition);
XMStoreFloat4(&cbOpaque.lightDirection, m_lightDirection);
cbOpaque.lightColor = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
cbOpaque.shadowTransform = XMMatrixTranspose(XMLoadFloat4x4(&m_shadowTransform));
cbOpaque.parameters = XMFLOAT4(m_quadWidth, m_unitCount, m_tessMin, m_tessMax);
memcpy(&m_cbOpaqueMappedData[m_backBufferIndex], &cbOpaque, sizeof(OpaqueCB));
// Bind OpaqueCB data to the shader.
const auto baseGPUAddress = m_cbOpaqueGpuAddress + m_backBufferIndex * sizeof(OpaqueCB);
m_commandList->SetGraphicsRootConstantBufferView(1, baseGPUAddress);
}
// Get handle of RTV, DSV.
const CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(
m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(),
static_cast<INT>(m_backBufferIndex), m_rtvDescriptorSize);
const CD3DX12_CPU_DESCRIPTOR_HANDLE dsvHandle(m_dsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
// Set render target.
m_commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
// Set PSO.
m_commandList->SetPipelineState(
m_wireframe ? m_wireframePSO.Get() : m_renderShadow ? m_opaquePSO.Get() : m_noShadowPSO.Get());
// Set the viewport and scissor rect.
m_commandList->RSSetViewports(1, &m_viewport);
m_commandList->RSSetScissorRects(1, &m_scissorRect);
// Translate render target to WRITE state.
const D3D12_RESOURCE_BARRIER toWrite = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
m_commandList->ResourceBarrier(1, &toWrite);
// ---> D3D12_RESOURCE_STATE_RENDER_TARGET
{
// Clear RTV, DSV.
m_commandList->ClearRenderTargetView(rtvHandle, Colors::Black, 0, nullptr);
m_commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set Topology and VB.
m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);
m_commandList->IASetVertexBuffers(0, 1, &m_staticVBV);
// Set index buffer & draw all face trees.
for (const FaceTree* faceTree : m_faceTrees)
{
faceTree->Draw(m_commandList.Get());
}
// Draw imgui.
{
ImGui_ImplDX12_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
{
const auto io = ImGui::GetIO();
ImGui::Begin("apollo");
ImGui::SetWindowSize(ImVec2(450, 550), ImGuiCond_Always);
ImGui::Text("%d x %d (Resolution)", m_outputWidth, m_outputHeight);
ImGui::Text("%d x %d (Shadow Map Resolution)", m_shadowMapSize, m_shadowMapSize);
ImGui::TextColored(ImVec4(1, 1, 0, 1), "%.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Dummy(ImVec2(0.0f, 20.0f));
ImGui::Text("Before Tessellation (Input of VS)");
ImGui::BulletText("Subdivision count: %d", m_subDivideCount);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::BulletText("QuadSphere initial quad count: %d", m_totalIndexCount / 4);
ImGui::BulletText("QuadSphere initial triangle count: %d (converted)", m_totalIndexCount * 2 / 4);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::BulletText("Render quad count: %d", (m_totalIndexCount - m_culledQuadCount) / 4);
ImGui::BulletText("Render triangle count: %d (converted)", (m_totalIndexCount - m_culledQuadCount) * 2 / 4);
ImGui::Dummy(ImVec2(0.0f, 10.0f));
ImGui::BulletText("Culled quad count: %d (%.3f %%)",
m_culledQuadCount, static_cast<float>(m_culledQuadCount) * 100 / (m_totalIndexCount / 4));
ImGui::Dummy(ImVec2(0.0f, 20.0f));
ImGui::SliderInt("Max Tess 2^n", &m_tessMax, 5, 8);
ImGui::SliderFloat("Rotate speed", &m_camRotateSpeed, 0.0f, 1.0f);
ImGui::Text("Move speed: %.3f (Scroll to Adjust)", m_camMoveSpeed);
ImGui::Dummy(ImVec2(0.0f, 20.0f));
ImGui::Checkbox("Rotate Light", &m_lightRotation);
ImGui::Checkbox("Render Shadow", &m_renderShadow);
ImGui::Checkbox("Wireframe", &m_wireframe);
ImGui::Dummy(ImVec2(0.0f, 20.0f));
if (ImGui::Button("Reset Camera"))
{
m_camYaw = 0.0f;
m_camPitch = 0.0f;
m_camPosition = XMVectorSet(0.0f, 0.0f, -500.0f, 0.0f);
m_camLookTarget = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
}
ImGui::Dummy(ImVec2(0.0f, 20.0f));
ImGui::Text("Press X to Switch mouse mode");
ImGui::Text("(GUI Mode <-> Flight Mode)");
ImGui::End();
}
ImGui::Render();
ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), m_commandList.Get());
}
}
// <--- D3D12_RESOURCE_STATE_PRESENT
// Translate render target to READ state.
const D3D12_RESOURCE_BARRIER toRead = CD3DX12_RESOURCE_BARRIER::Transition(
m_renderTargets[m_backBufferIndex].Get(),
D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
m_commandList->ResourceBarrier(1, &toRead);
}
// <---------- Close and execute command list.
DX::ThrowIfFailed(m_commandList->Close());
m_commandQueue->ExecuteCommandLists(1, CommandListCast(m_commandList.GetAddressOf()));
// Present back buffer.
const HRESULT hr = m_swapChain->Present(0, m_fullScreenMode ? 0 : DXGI_PRESENT_ALLOW_TEARING);
// If the device was reset we must completely reinitialize the renderer.
if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
{
OnDeviceLost();
}
else
{
DX::ThrowIfFailed(hr);
MoveToNextFrame();
}
}
// Message handlers
void Apollo::OnActivated()
{
// TODO: Game is becoming active window.
}
void Apollo::OnDeactivated()
{
// TODO: Game is becoming background window.
}
void Apollo::OnSuspending()
{
// TODO: Game is being power-suspended (or minimized).
}
void Apollo::OnResuming()
{
m_timer.ResetElapsedTime();
// TODO: Game is being power-resumed (or returning from minimize).
}
void Apollo::OnWindowSizeChanged(int width, int height)
{
if (!m_window)
return;
m_outputWidth = std::max(width, 1);
m_outputHeight = std::max(height, 1);
m_aspectRatio = static_cast<float>(m_outputWidth) / static_cast<float>(m_outputHeight);
CreateWindowSizeDependentResources();
}
// These are the resources that depend on the device.
void Apollo::CreateDeviceResources()
{
// Enable the debug layer.
#if defined(_DEBUG)
ComPtr<ID3D12Debug> debugController;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(debugController.GetAddressOf()))))
{
debugController->EnableDebugLayer();
}
#endif
// ================================================================================================================
// #01. Create DXGI Device.
// ================================================================================================================
{
// Create the DXGI factory.
DWORD dxgiFactoryFlags = 0;
DX::ThrowIfFailed(CreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(m_dxgiFactory.ReleaseAndGetAddressOf())));
// Get adapter.
ComPtr<IDXGIAdapter1> adapter;
GetAdapter(adapter.GetAddressOf());
// Create the DX12 API device object.
DX::ThrowIfFailed(
D3D12CreateDevice(
adapter.Get(),
m_featureLevel,
IID_PPV_ARGS(m_d3dDevice.ReleaseAndGetAddressOf())
));
// Check Shader Model 6 support.
D3D12_FEATURE_DATA_SHADER_MODEL shaderModel = { D3D_SHADER_MODEL_6_0 };
if (FAILED(m_d3dDevice->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &shaderModel, sizeof(shaderModel)))
|| (shaderModel.HighestShaderModel < D3D_SHADER_MODEL_6_0))
{
#ifdef _DEBUG
OutputDebugStringA("ERROR: Shader Model 6.0 is not supported!\n");
#endif
throw std::runtime_error("Shader Model 6.0 is not supported!");
}
#ifndef NDEBUG
// Configure debug device (if active).
ComPtr<ID3D12InfoQueue> d3dInfoQueue;
if (SUCCEEDED(m_d3dDevice.As(&d3dInfoQueue)))
{
#ifdef _DEBUG
d3dInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
d3dInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
#endif
D3D12_MESSAGE_ID hide[] =
{
D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE,
D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE,
// Workarounds for debug layer issues on hybrid-graphics systems
D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_WRONGSWAPCHAINBUFFERREFERENCE,
D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISMATCHING_COMMAND_LIST_TYPE,
};
D3D12_INFO_QUEUE_FILTER filter = {};
filter.DenyList.NumIDs = static_cast<UINT>(std::size(hide));
filter.DenyList.pIDList = hide;
d3dInfoQueue->AddStorageFilterEntries(&filter);
}
#endif
// Get descriptor sizes.
m_rtvDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
m_dsvDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
m_cbvSrvDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
// ================================================================================================================
// #02. Create fence objects.
// ================================================================================================================
{
DX::ThrowIfFailed(
m_d3dDevice->CreateFence(
m_fenceValues[m_backBufferIndex],
D3D12_FENCE_FLAG_NONE,
IID_PPV_ARGS(m_fence.ReleaseAndGetAddressOf())));
m_fenceValues[m_backBufferIndex]++;
m_fenceEvent.Attach(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
if (!m_fenceEvent.IsValid())
{
throw std::system_error(
std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEventEx");
}
}
// ================================================================================================================
// #03. Create command objects.
// ================================================================================================================
{
// Create command queue.
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
DX::ThrowIfFailed(
m_d3dDevice->CreateCommandQueue(
&queueDesc,
IID_PPV_ARGS(m_commandQueue.ReleaseAndGetAddressOf())));
// Create a command allocator for each back buffer that will be rendered to.
for (UINT n = 0; n < c_swapBufferCount; n++)
{
DX::ThrowIfFailed(
m_d3dDevice->CreateCommandAllocator(
D3D12_COMMAND_LIST_TYPE_DIRECT,
IID_PPV_ARGS(m_commandAllocators[n].ReleaseAndGetAddressOf())));
}
// Create a command list for recording graphics commands.
DX::ThrowIfFailed(
m_d3dDevice->CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE_DIRECT,
m_commandAllocators[0].Get(),
nullptr,
IID_PPV_ARGS(m_commandList.ReleaseAndGetAddressOf())));
DX::ThrowIfFailed(m_commandList->Close());
}
}
void Apollo::CreateDeviceDependentResources()
{
// ================================================================================================================
// #01. Create descriptor heaps.
// ================================================================================================================
{
// Create RTV descriptor heap.
D3D12_DESCRIPTOR_HEAP_DESC rtvDescriptorHeapDesc = {};
rtvDescriptorHeapDesc.NumDescriptors = c_swapBufferCount;
rtvDescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
DX::ThrowIfFailed(
m_d3dDevice->CreateDescriptorHeap(
&rtvDescriptorHeapDesc,
IID_PPV_ARGS(m_rtvDescriptorHeap.ReleaseAndGetAddressOf())));
// Create DSV descriptor heap.
D3D12_DESCRIPTOR_HEAP_DESC dsvDescriptorHeapDesc = {};
dsvDescriptorHeapDesc.NumDescriptors = 2; // one for shadow pass, one for opaque pass.
dsvDescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
DX::ThrowIfFailed(
m_d3dDevice->CreateDescriptorHeap(
&dsvDescriptorHeapDesc,
IID_PPV_ARGS(m_dsvDescriptorHeap.ReleaseAndGetAddressOf())));
// Create SRV descriptor heap.
D3D12_DESCRIPTOR_HEAP_DESC srvDescriptorHeapDesc = {};
srvDescriptorHeapDesc.NumDescriptors = 6; // color map (2), displacement map (2), shadow map (1), imgui (1).
srvDescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
srvDescriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
DX::ThrowIfFailed(
m_d3dDevice->CreateDescriptorHeap(
&srvDescriptorHeapDesc,
IID_PPV_ARGS(m_srvDescriptorHeap.ReleaseAndGetAddressOf())));
}
// ================================================================================================================
// #02. Create root signature.
// ================================================================================================================
{
// Define root parameters.
CD3DX12_DESCRIPTOR_RANGE srvTable;
srvTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 6, 0);
CD3DX12_ROOT_PARAMETER rootParameters[3] = {};
rootParameters[0].InitAsDescriptorTable(1, &srvTable); // register (t0)
rootParameters[1].InitAsConstantBufferView(0); // register (c0)
rootParameters[2].InitAsConstantBufferView(1); // register (c1)
// Define samplers.
const CD3DX12_STATIC_SAMPLER_DESC anisotropicClamp(
0, // register (s0)
D3D12_FILTER_ANISOTROPIC, // filter
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressU
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressV
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressW
0.0f, // mipLODBias
16, // maxAnisotropy
D3D12_COMPARISON_FUNC_LESS_EQUAL,
D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE,
0.0f, // minLOD
D3D12_FLOAT32_MAX, // maxLOD
D3D12_SHADER_VISIBILITY_ALL
);
const CD3DX12_STATIC_SAMPLER_DESC shadow(
1, // register (s1)
D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, // filter
D3D12_TEXTURE_ADDRESS_MODE_BORDER, // addressU
D3D12_TEXTURE_ADDRESS_MODE_BORDER, // addressV
D3D12_TEXTURE_ADDRESS_MODE_BORDER, // addressW
0.0f, // mipLODBias
16, // maxAnisotropy
D3D12_COMPARISON_FUNC_LESS,
D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK
);
const CD3DX12_STATIC_SAMPLER_DESC anisotropicClampMip1(
2, // register (s2)
D3D12_FILTER_ANISOTROPIC, // filter
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressU
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressV
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressW
0.0f, // mipLODBias
16, // maxAnisotropy
D3D12_COMPARISON_FUNC_LESS_EQUAL,
D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE,
1, // minLOD
D3D12_FLOAT32_MAX // maxLOD
);
CD3DX12_STATIC_SAMPLER_DESC staticSamplers[3] =
{
anisotropicClamp, shadow, anisotropicClampMip1
};
// Create root signature.
CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
rootSignatureDesc.Init(
_countof(rootParameters), rootParameters,
_countof(staticSamplers), staticSamplers,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT
);
ComPtr<ID3DBlob> signatureBlob;
ComPtr<ID3DBlob> errorBlob;
DX::ThrowIfFailed(
D3D12SerializeRootSignature(
&rootSignatureDesc,
D3D_ROOT_SIGNATURE_VERSION_1,
&signatureBlob,
&errorBlob));
DX::ThrowIfFailed(
m_d3dDevice->CreateRootSignature(
0,
signatureBlob->GetBufferPointer(),
signatureBlob->GetBufferSize(),
IID_PPV_ARGS(m_rootSignature.ReleaseAndGetAddressOf())));
}
// ================================================================================================================
// #03. Create PSO.
// ================================================================================================================
{
static constexpr D3D12_INPUT_ELEMENT_DESC c_inputElementDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "QUAD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
// Load compiled shaders.
auto vertexShaderBlob = DX::ReadData(L"VS.cso");
auto hullShaderBlob = DX::ReadData(L"HS.cso");
auto domainShaderBlob = DX::ReadData(L"DS.cso");
auto pixelShaderBlob = DX::ReadData(L"PS.cso");
// Create Opaque PSO.
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.InputLayout = { c_inputElementDesc, _countof(c_inputElementDesc) };
psoDesc.pRootSignature = m_rootSignature.Get();
psoDesc.VS = { vertexShaderBlob.data(), vertexShaderBlob.size() };
psoDesc.HS = { hullShaderBlob.data(), hullShaderBlob.size() };
psoDesc.DS = { domainShaderBlob.data(), domainShaderBlob.size() };
psoDesc.PS = { pixelShaderBlob.data(), pixelShaderBlob.size() };
psoDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
psoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK;
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
psoDesc.DSVFormat = c_depthBufferFormat;
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = c_rtvFormat;
psoDesc.SampleDesc.Count = 1;
DX::ThrowIfFailed(
m_d3dDevice->CreateGraphicsPipelineState(
&psoDesc,
IID_PPV_ARGS(m_opaquePSO.ReleaseAndGetAddressOf())));
// Create No Shadow Opaque PSO.
auto noShadowPSBlob = DX::ReadData(L"NoShadowPS.cso");
auto noShadowPSODesc = D3D12_GRAPHICS_PIPELINE_STATE_DESC(psoDesc);
noShadowPSODesc.PS = { noShadowPSBlob.data(), noShadowPSBlob.size() };
DX::ThrowIfFailed(
m_d3dDevice->CreateGraphicsPipelineState(
&noShadowPSODesc,
IID_PPV_ARGS(m_noShadowPSO.ReleaseAndGetAddressOf())));
// Create Wireframe PSO.
auto wireframePSBlob = DX::ReadData(L"DebugPS.cso");
auto wireframePSODesc = D3D12_GRAPHICS_PIPELINE_STATE_DESC(psoDesc);
wireframePSODesc.PS = { wireframePSBlob.data(), wireframePSBlob.size() };
wireframePSODesc.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME;
DX::ThrowIfFailed(
m_d3dDevice->CreateGraphicsPipelineState(
&wireframePSODesc,
IID_PPV_ARGS(m_wireframePSO.ReleaseAndGetAddressOf())));
// Load compiled shadow shaders.
auto shadowVSBlob = DX::ReadData(L"ShadowVS.cso");
auto shadowHSBlob = DX::ReadData(L"ShadowHS.cso");
auto shadowDSBlob = DX::ReadData(L"ShadowDS.cso");
auto shadowPSBlob = DX::ReadData(L"ShadowPS.cso");
// Create Shadow Map PSO.
auto shadowPSODesc = D3D12_GRAPHICS_PIPELINE_STATE_DESC(psoDesc);
shadowPSODesc.VS = { shadowVSBlob.data(), shadowVSBlob.size() };
shadowPSODesc.HS = { shadowHSBlob.data(), shadowHSBlob.size() };
shadowPSODesc.DS = { shadowDSBlob.data(), shadowDSBlob.size() };
shadowPSODesc.PS = { shadowPSBlob.data(), shadowPSBlob.size() };
shadowPSODesc.RasterizerState.DepthBias = 100000;
shadowPSODesc.RasterizerState.DepthBiasClamp = 0.0f;
shadowPSODesc.RasterizerState.SlopeScaledDepthBias = 1.0f;
shadowPSODesc.pRootSignature = m_rootSignature.Get();
shadowPSODesc.DSVFormat = c_depthBufferFormat;
shadowPSODesc.RTVFormats[0] = DXGI_FORMAT_UNKNOWN;
shadowPSODesc.NumRenderTargets = 0;
DX::ThrowIfFailed(
m_d3dDevice->CreateGraphicsPipelineState(
&shadowPSODesc,
IID_PPV_ARGS(m_shadowPSO.ReleaseAndGetAddressOf())));
}
// ================================================================================================================
// #04. Create constant buffer and map.
// ================================================================================================================
{
// Create opaque constant buffer.
{
CD3DX12_HEAP_PROPERTIES uploadHeapProp(D3D12_HEAP_TYPE_UPLOAD);
CD3DX12_RESOURCE_DESC resDesc = CD3DX12_RESOURCE_DESC::Buffer(c_swapBufferCount * sizeof(OpaqueCB));
DX::ThrowIfFailed(
m_d3dDevice->CreateCommittedResource(
&uploadHeapProp,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(m_cbOpaqueUploadHeap.ReleaseAndGetAddressOf())));
// Mapping.
DX::ThrowIfFailed(m_cbOpaqueUploadHeap->Map(0, nullptr, reinterpret_cast<void**>(&m_cbOpaqueMappedData)));
m_cbOpaqueGpuAddress = m_cbOpaqueUploadHeap->GetGPUVirtualAddress();
}
// Create shadow constant buffer.
{
CD3DX12_HEAP_PROPERTIES uploadHeapProp(D3D12_HEAP_TYPE_UPLOAD);
CD3DX12_RESOURCE_DESC resDesc = CD3DX12_RESOURCE_DESC::Buffer(c_swapBufferCount * sizeof(OpaqueCB));
DX::ThrowIfFailed(
m_d3dDevice->CreateCommittedResource(
&uploadHeapProp,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(m_cbShadowUploadHeap.ReleaseAndGetAddressOf())));
// Mapping.
DX::ThrowIfFailed(m_cbShadowUploadHeap->Map(0, nullptr, reinterpret_cast<void**>(&m_cbShadowMappedData)));
m_cbShadowGpuAddress = m_cbShadowUploadHeap->GetGPUVirtualAddress();
}
}
// ================================================================================================================
// #05. Build shadow resources.
// ================================================================================================================
{
m_shadowMap = std::make_unique<ShadowMap>(m_d3dDevice.Get(), m_shadowMapSize, m_shadowMapSize);
m_shadowMap->BuildDescriptors(
CD3DX12_CPU_DESCRIPTOR_HANDLE(m_srvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 4, m_cbvSrvDescriptorSize),
CD3DX12_GPU_DESCRIPTOR_HANDLE(m_srvDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 4, m_cbvSrvDescriptorSize),
CD3DX12_CPU_DESCRIPTOR_HANDLE(m_dsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 1, m_dsvDescriptorSize));
}
// ================================================================================================================
// #06. Setup imgui context.
// ================================================================================================================
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
auto io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(m_window);
ImGui_ImplDX12_Init(
m_d3dDevice.Get(),
c_swapBufferCount,
c_rtvFormat,
m_srvDescriptorHeap.Get(),
CD3DX12_CPU_DESCRIPTOR_HANDLE(m_srvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 5, m_cbvSrvDescriptorSize),
CD3DX12_GPU_DESCRIPTOR_HANDLE(m_srvDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 5, m_cbvSrvDescriptorSize));
// Setup Dear ImGui style
ImGui::StyleColorsDark();
}
}
// Allocate all memory resources that change on a window SizeChanged event.
void Apollo::CreateWindowSizeDependentResources()
{
// Release resources that are tied to the swap chain and update fence values.
for (UINT n = 0; n < c_swapBufferCount; n++)
{
m_renderTargets[n].Reset();
m_fenceValues[n] = m_fenceValues[m_backBufferIndex];
}
const UINT backBufferWidth = static_cast<UINT>(m_outputWidth);
const UINT backBufferHeight = static_cast<UINT>(m_outputHeight);
// ================================================================================================================
// #01. Create/Resize swap chain.
// ================================================================================================================
{
// If the swap chain already exists, resize it, otherwise create one.
if (m_swapChain)
{
const HRESULT hr = m_swapChain->ResizeBuffers(
c_swapBufferCount, backBufferWidth, backBufferHeight, c_backBufferFormat, 0);
if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
{
// If the device was removed for any reason, a new device and swap chain will need to be created.
OnDeviceLost();
return;
}
DX::ThrowIfFailed(hr);
}
else
{
// If swap chain does not exist, create it.
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.Width = backBufferWidth;
swapChainDesc.Height = backBufferHeight;
swapChainDesc.Format = c_backBufferFormat;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;