forked from GameTechDev/SamplerFeedbackStreaming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scene.cpp
1759 lines (1478 loc) · 65.2 KB
/
Scene.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
//*********************************************************
//
// Copyright 2020 Intel Corporation
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files(the "Software"), to deal in the Software
// without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to
// whom the Software is furnished to do so, subject to the
// following conditions :
// The above copyright notice and this permission notice shall
// be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//*********************************************************
#include "pch.h"
#include "Scene.h"
#include "D3D12GpuTimer.h"
#include "Gui.h"
#include "TextureViewer.h"
#include "BufferViewer.h"
#include "FrustumViewer.h"
#include "WindowCapture.h"
#pragma comment(lib, "d3d12.lib")
#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "TileUpdateManager.lib")
using namespace DirectX;
// NOTE: the last value must be 0 for TSS. It signifies the pixel has been written to
const FLOAT Scene::m_clearColor[4] = { 0, 0, 0.05f, 0 };
enum class DescriptorHeapOffsets
{
FRAME_CBV, // b0
GUI,
SHARED_MIN_MIP_MAP,
NumEntries
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
Scene::Scene(const CommandLineArgs& in_args, HWND in_hwnd) :
m_args(in_args)
, m_hwnd(in_hwnd)
, m_windowInfo{}
, m_windowedSupportsTearing(false)
, m_deviceRemoved(false)
, m_frameIndex(0)
, m_renderFenceValue(0)
, m_frameFenceValues{}
, m_renderFenceEvent(0)
, m_rtvDescriptorSize(0)
, m_srvUavCbvDescriptorSize(0)
, m_dsvDescriptorSize(0)
, m_aspectRatio(0)
, m_pFrameConstantData(nullptr)
// visuals
, m_showFrustum(!in_args.m_visualizeFrustum) // need to force first-time creation
, m_useDirectStorage(in_args.m_useDirectStorage)
, m_pGui(nullptr)
, m_pTextureViewer(nullptr)
, m_pMinMipMapViewer(nullptr)
, m_pFeedbackViewer(nullptr)
, m_pFrustumViewer(nullptr)
// thread
, m_queueFeedbackIndex(0)
, m_prevNumFeedbackObjects(SharedConstants::SWAP_CHAIN_BUFFER_COUNT, 1)
// statistics
, m_renderThreadTimes(in_args.m_statisticsNumFrames)
, m_updateFeedbackTimes(in_args.m_statisticsNumFrames)
, m_pGpuTimer(nullptr)
{
m_windowInfo.cbSize = sizeof(WINDOWINFO);
#if ENABLE_DEBUG_LAYER
InitDebugLayer();
#endif
UINT flags = 0;
#ifdef _DEBUG
flags |= DXGI_CREATE_FACTORY_DEBUG;
#endif
if (FAILED(CreateDXGIFactory2(flags, IID_PPV_ARGS(&m_factory))))
{
flags &= ~DXGI_CREATE_FACTORY_DEBUG;
ThrowIfFailed(CreateDXGIFactory2(flags, IID_PPV_ARGS(&m_factory)));
}
ComPtr<IDXGIAdapter1> adapter;
DXGI_ADAPTER_DESC1 desc;
if (m_args.m_adapterDescription.size())
{
std::wstring lowerCaseAdapterDesc = m_args.m_adapterDescription;
for (auto& c : lowerCaseAdapterDesc) { c = ::towlower(c); }
for (UINT i = 0; m_factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i)
{
ThrowIfFailed(adapter->GetDesc1(&desc));
std::wstring description(desc.Description);
for (auto& c : description) { c = ::towlower(c); }
std::size_t found = description.find(lowerCaseAdapterDesc);
if (found != std::string::npos)
{
break;
}
}
}
else
{
ThrowIfFailed(m_factory->EnumAdapters1(0, &adapter));
ThrowIfFailed(adapter->GetDesc1(&desc));
}
std::wstring adapterDescription = desc.Description;
// does this device support sampler feedback?
D3D12_FEATURE_DATA_D3D12_OPTIONS7 feedbackOptions{};
HRESULT hr = D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&m_device));
if (SUCCEEDED(hr))
{
m_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &feedbackOptions, sizeof(feedbackOptions));
}
if (0 == feedbackOptions.SamplerFeedbackTier)
{
std::wstring msg = L"Sampler Feedback not supported by\n";
msg += adapterDescription;
MessageBox(0, msg.c_str(), L"Error", MB_OK);
exit(-1);
}
D3D12_FEATURE_DATA_D3D12_OPTIONS tileOptions{};
m_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &tileOptions, sizeof(tileOptions));
if (0 == tileOptions.TiledResourcesTier)
{
std::wstring msg = L"Tiled Resources not supported by\n";
msg += adapterDescription;
MessageBox(0, msg.c_str(), L"Error", MB_OK);
exit(-1);
}
m_pGpuTimer = new D3D12GpuTimer(m_device.Get(), 8, D3D12GpuTimer::TimerType::Direct);
// get the adapter this device was created with
LUID adapterLUID = m_device->GetAdapterLuid();
ThrowIfFailed(m_factory->EnumAdapterByLuid(adapterLUID, IID_PPV_ARGS(&m_adapter)));
// descriptor sizes
m_rtvDescriptorSize = m_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
m_srvUavCbvDescriptorSize = m_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
m_dsvDescriptorSize = m_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
// creation order below matters
CreateDescriptorHeaps();
CreateCommandQueue();
CreateSwapChain();
CreateFence();
StartStreamingLibrary();
CreateSampler();
CreateConstantBuffers();
float eyePos = 100.0f;
XMVECTOR vEyePt = XMVectorSet(eyePos, eyePos, eyePos, 1.0f);
XMVECTOR lookAt = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
XMVECTOR vUpVec = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f);
m_viewMatrix = XMMatrixLookAtLH(vEyePt, lookAt, vUpVec);
XMVECTOR pDet;
m_viewMatrixInverse = XMMatrixInverse(&pDet, m_viewMatrix);
m_pGui = new Gui(m_hwnd, m_device.Get(), m_srvHeap.Get(), (UINT)DescriptorHeapOffsets::GUI, m_swapBufferCount, SharedConstants::SWAP_CHAIN_FORMAT, adapterDescription, m_args);
m_pFrustumViewer = new FrustumViewer(m_device.Get(),
SharedConstants::SWAP_CHAIN_FORMAT,
SharedConstants::DEPTH_FORMAT,
m_args.m_sampleCount,
[&](ID3D12Resource* out_pBuffer, const void* in_pBytes, size_t in_numBytes, D3D12_RESOURCE_STATES in_finalState)
{
SceneObjects::InitializeBuffer(out_pBuffer, in_pBytes, in_numBytes, in_finalState);
});
// statistics gathering
if (m_args.m_timingFrameFileName.size() && (m_args.m_timingStopFrame >= m_args.m_timingStartFrame))
{
m_csvFile = std::make_unique<FrameEventTracing>(m_args.m_timingFrameFileName, adapterDescription);
}
}
Scene::~Scene()
{
WaitForGpu();
if (GetSystemMetrics(SM_REMOTESESSION) == 0)
{
m_swapChain->SetFullscreenState(FALSE, nullptr);
}
::CloseHandle(m_renderFenceEvent);
m_frameConstantBuffer->Unmap(0, nullptr);
delete m_pGpuTimer;
delete m_pGui;
DeleteTerrainViewers();
delete m_pFrustumViewer;
for (auto o : m_objects)
{
delete o;
}
for (auto h : m_sharedHeaps)
{
delete h;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
RECT Scene::GetGuiRect()
{
RECT r{};
r.right = (LONG)m_pGui->GetWidth();
r.bottom = (LONG)m_pGui->GetHeight();
return r;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void Scene::MoveView(int in_x, int in_y, int in_z)
{
float translationRate = 0.1f * GetFrameTime();
if (0x8000 & GetKeyState(VK_SHIFT))
{
translationRate *= 8;
}
float x = in_x * translationRate;
float y = in_y * translationRate;
float z = in_z * -translationRate;
XMMATRIX translation = XMMatrixTranslation(x, y, z);
m_viewMatrix = XMMatrixMultiply(m_viewMatrix, translation);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void Scene::RotateView(float in_x, float in_y, float in_z)
{
XMMATRIX rotation = XMMatrixRotationRollPitchYaw(in_x, 0, in_z);
if (in_y)
{
// NOTE: locking the "up" axis feels great when navigating the terrain
// however, it breaks the controls when flying to other planets
XMMATRIX rotY = XMMatrixIdentity();
if (m_args.m_cameraUpLock)
{
// this prevents spin while panning the terrain, but breaks if the user intentionally rotates in Z
rotY = XMMatrixRotationAxis(XMVectorSet(0, 1, 0, 1), in_y);
}
else
{
// this rotates correctly with any z axis rotation, but "up" can drift:
XMVECTOR yAxis = m_viewMatrixInverse.r[1];
rotY = XMMatrixRotationNormal(yAxis, in_y);
}
XMVECTOR xLate = XMVectorSetW(m_viewMatrixInverse.r[3], 0);
rotY = XMMatrixMultiply(XMMatrixTranslationFromVector(-xLate), rotY);
rotY = XMMatrixMultiply(rotY, XMMatrixTranslationFromVector(xLate));
m_viewMatrix = XMMatrixMultiply(rotY, m_viewMatrix);
}
m_viewMatrix = XMMatrixMultiply(m_viewMatrix, rotation);
XMVECTOR pDet;
m_viewMatrixInverse = XMMatrixInverse(&pDet, m_viewMatrix);
}
void Scene::RotateViewKey(int in_x, int in_y, int in_z)
{
float rotationRate = 0.001f * GetFrameTime();
float x = in_x * -rotationRate;
float y = in_y * rotationRate;
float z = in_z * -rotationRate;
RotateView(x, y, z);
}
void Scene::RotateViewPixels(int in_x, int in_y)
{
float xRadians = (sin(m_fieldOfView) / m_viewport.Width) * 2.0f;
float x = float(in_x) * xRadians;
float y = float(in_y) * xRadians;
RotateView(x, y, 0);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
float Scene::GetFrameTime()
{
return 1000.0f * m_renderThreadTimes.GetAverageTotal();
}
//-----------------------------------------------------------------------------
// common behavior for device removed/reset
//-----------------------------------------------------------------------------
bool Scene::IsDeviceOk(HRESULT in_hr)
{
bool success = true;
if ((DXGI_ERROR_DEVICE_REMOVED == in_hr) || (DXGI_ERROR_DEVICE_RESET == in_hr))
{
//HRESULT hr = m_device->GetDeviceRemovedReason();
m_deviceRemoved = true;
success = false;
}
else
{
ThrowIfFailed(in_hr);
}
return success;
}
//-----------------------------------------------------------------------------
// handle in/out of fullscreen immediately. defer render target size changes
// FIXME: 1st transition to full-screen on multi-gpu, app disappears (?) - hit ESC and try again
// FIXME: full-screen does not choose the nearest display for the associated adapter, it chooses the 1st
//-----------------------------------------------------------------------------
void Scene::Resize()
{
if (m_fullScreen != m_desiredFullScreen)
{
WaitForGpu();
// can't full screen with remote desktop
bool canFullScreen = (GetSystemMetrics(SM_REMOTESESSION) == 0);
if (m_desiredFullScreen)
{
// remember the current placement so we can restore via vk_esc
GetWindowPlacement(m_hwnd, &m_windowPlacement);
// take the first attached monitor
// FIXME? could search for the nearest monitor.
MONITORINFO monitorInfo;
monitorInfo.cbSize = sizeof(monitorInfo);
GetMonitorInfo(MonitorFromWindow(m_hwnd, MONITOR_DEFAULTTONEAREST), &monitorInfo);
ComPtr<IDXGIOutput> dxgiOutput;
HRESULT result = m_adapter->EnumOutputs(0, &dxgiOutput);
if (SUCCEEDED(result))
{
if (canFullScreen)
{
ThrowIfFailed(m_swapChain->SetFullscreenState(true, dxgiOutput.Get()));
}
// FIXME? borderless window would be nice when using remote desktop
}
else // enumerate may fail when multi-gpu and cloning displays
{
canFullScreen = false;
auto width = ::GetSystemMetrics(SM_CXSCREEN);
auto height = ::GetSystemMetrics(SM_CYSCREEN);
SetWindowPos(m_hwnd, NULL, 0, 0, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
}
}
else
{
if (canFullScreen)
{
ThrowIfFailed(m_swapChain->SetFullscreenState(false, nullptr));
}
// when leaving full screen, the previous window state isn't restored by the OS
// however, we saved it earlier...
int left = m_windowPlacement.rcNormalPosition.left;
int top = m_windowPlacement.rcNormalPosition.top;
int width = m_windowPlacement.rcNormalPosition.right - left;
int height = m_windowPlacement.rcNormalPosition.bottom - top;
SetWindowPos(m_hwnd, NULL, left, top, width, height, SWP_SHOWWINDOW);
}
m_fullScreen = m_desiredFullScreen;
}
RECT rect{};
GetClientRect(m_hwnd, &rect);
UINT width = rect.right - rect.left;
UINT height = rect.bottom - rect.top;
// ignore resize events for 0-sized window
// not a fatal error. just ignore it.
if ((0 == height) || (0 == width))
{
return;
}
if ((width != m_windowWidth) || (height != m_windowHeight))
{
m_windowWidth = width;
m_windowHeight = height;
WaitForGpu();
m_viewport = CD3DX12_VIEWPORT(0.0f, 0.0f, static_cast<FLOAT>(width), static_cast<FLOAT>(height));
m_scissorRect = CD3DX12_RECT(0, 0, width, height);
m_aspectRatio = m_viewport.Width / m_viewport.Height;
float nearZ = 1.0f;
float farZ = 100000.0f;
m_projection = DirectX::XMMatrixPerspectiveFovLH(m_fieldOfView, m_aspectRatio, nearZ, farZ);
for (UINT i = 0; i < m_swapBufferCount; i++)
{
m_renderTargets[i] = nullptr;
}
UINT flags = 0;
if (m_windowedSupportsTearing)
{
flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
}
HRESULT hr = m_swapChain->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, flags);
if (IsDeviceOk(hr))
{
// Create a RTV for each frame.
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart());
for (UINT i = 0; i < m_swapBufferCount; i++)
{
ThrowIfFailed(m_swapChain->GetBuffer(i, IID_PPV_ARGS(&m_renderTargets[i])));
m_device->CreateRenderTargetView(m_renderTargets[i].Get(), nullptr, rtvHandle);
rtvHandle.Offset(1, m_rtvDescriptorSize);
}
CreateRenderTargets();
m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();
// UI uses window dimensions
m_args.m_windowWidth = width;
m_args.m_windowHeight = height;
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void Scene::CreateDescriptorHeaps()
{
// shader resource view (SRV) heap for e.g. textures
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = (UINT)DescriptorHeapOffsets::NumEntries +
(m_args.m_maxNumObjects * (UINT)SceneObjects::Descriptors::NumEntries);
srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
ThrowIfFailed(m_device->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&m_srvHeap)));
NAME_D3D12_OBJECT(m_srvHeap);
// render target view heap
// NOTE: we have an MSAA target plus a swap chain, so m_swapBufferCount + 1
D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
rtvHeapDesc.NumDescriptors = m_swapBufferCount + 1;
rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
ThrowIfFailed(m_device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&m_rtvHeap)));
// depth buffer view heap
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.NumDescriptors = 1;
ThrowIfFailed(m_device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&m_dsvHeap)));
NAME_D3D12_OBJECT(m_dsvHeap);
}
//-----------------------------------------------------------------------------
// Create synchronization objects and wait until assets have been uploaded to the GPU.
//-----------------------------------------------------------------------------
void Scene::CreateFence()
{
ThrowIfFailed(m_device->CreateFence(
m_renderFenceValue,
D3D12_FENCE_FLAG_NONE,
IID_PPV_ARGS(&m_renderFence)));
// Create an event handle to use for frame synchronization.
m_renderFenceEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
if (m_renderFenceEvent == nullptr)
{
ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError()));
}
}
//-----------------------------------------------------------------------------
// creates queue, direct command list, and command allocators
//-----------------------------------------------------------------------------
void Scene::CreateCommandQueue()
{
// Describe and create the command queue.
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
ThrowIfFailed(m_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_commandQueue)));
m_commandQueue->SetName(L"m_commandQueue");
for (UINT i = 0; i < m_swapBufferCount; i++)
{
ThrowIfFailed(m_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&m_commandAllocators[i])));
std::wstringstream cmdAllocName;
cmdAllocName << "m_commandAllocators #" << i;
m_commandAllocators[i]->SetName(cmdAllocName.str().c_str());
}
m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_commandAllocators[0].Get(), nullptr, IID_PPV_ARGS(&m_commandList));
m_commandList->SetName(L"m_commandList");
m_commandList->Close();
}
//-----------------------------------------------------------------------------
// note creating the swap chain requires a command queue
// hence, if the command queue changes, we must re-create the swap chain
// command queue can change if we toggle the Intel command queue extension
//-----------------------------------------------------------------------------
void Scene::CreateSwapChain()
{
BOOL allowTearing = FALSE;
const HRESULT result = m_factory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing));
m_windowedSupportsTearing = SUCCEEDED(result) && allowTearing;
GetWindowInfo(m_hwnd, &m_windowInfo);
// Describe and create the swap chain.
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.BufferCount = SharedConstants::SWAP_CHAIN_BUFFER_COUNT;
swapChainDesc.Width = m_windowInfo.rcClient.right - m_windowInfo.rcClient.left;
swapChainDesc.Height = m_windowInfo.rcClient.bottom - m_windowInfo.rcClient.top;
swapChainDesc.Format = SharedConstants::SWAP_CHAIN_FORMAT;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.Flags = 0;
if (m_windowedSupportsTearing)
{
swapChainDesc.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
}
DXGI_SWAP_CHAIN_FULLSCREEN_DESC* pFullScreenDesc = nullptr;
// if full screen mode, launch into the current settings
DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullScreenDesc = {};
IDXGIOutput* pOutput = nullptr;
ComPtr<IDXGISwapChain1> swapChain;
ThrowIfFailed(m_factory->CreateSwapChainForHwnd(m_commandQueue.Get(), m_hwnd,
&swapChainDesc, pFullScreenDesc, pOutput, &swapChain));
/*
want full screen with tearing.
from MSDN, DXGI_PRESENT_ALLOW_TEARING:
- The swap chain must be created with the DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING flag.
- It can only be used in windowed mode.
- To use this flag in full screen Win32 apps, the application should present to a fullscreen borderless window
and disable automatic ALT+ENTER fullscreen switching using IDXGIFactory::MakeWindowAssociation.
*/
ThrowIfFailed(m_factory->MakeWindowAssociation(m_hwnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_PRINT_SCREEN));
ThrowIfFailed(swapChain.As(&m_swapChain));
m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();
}
//-----------------------------------------------------------------------------
// Enable the D3D12 debug layer.
//-----------------------------------------------------------------------------
void Scene::InitDebugLayer()
{
OutputDebugString(L"<<< WARNING: DEBUG LAYER ENABLED >>>\n");
{
ID3D12Debug1* pDebugController = nullptr;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&pDebugController))))
{
//pDebugController->SetEnableGPUBasedValidation(TRUE);
pDebugController->EnableDebugLayer();
pDebugController->Release();
}
}
}
//-----------------------------------------------------------------------------
// modified next-frame logic to return a handle if a wait is required.
// NOTE: be sure to check for non-null handle before WaitForSingleObjectEx() (or equivalent)
//-----------------------------------------------------------------------------
void Scene::MoveToNextFrame()
{
// Assign the current fence value to the current frame.
m_frameFenceValues[m_frameIndex] = m_renderFenceValue;
// Signal and increment the fence value.
ThrowIfFailed(m_commandQueue->Signal(m_renderFence.Get(), m_renderFenceValue));
m_renderFenceValue++;
// Update the frame index.
m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();
// If the next frame is not ready to be rendered yet, wait until it is ready.
if (m_renderFence->GetCompletedValue() < m_frameFenceValues[m_frameIndex])
{
ThrowIfFailed(m_renderFence->SetEventOnCompletion(m_frameFenceValues[m_frameIndex], m_renderFenceEvent));
WaitForSingleObject(m_renderFenceEvent, INFINITE);
}
}
//-----------------------------------------------------------------------------
// Wait for pending GPU work to complete.
// not interacting with swap chain.
//-----------------------------------------------------------------------------
void Scene::WaitForGpu()
{
// Add a signal command to the queue.
ThrowIfFailed(m_commandQueue->Signal(m_renderFence.Get(), m_renderFenceValue));
// Instruct the fence to set the event object when the signal command completes.
ThrowIfFailed(m_renderFence->SetEventOnCompletion(m_renderFenceValue, m_renderFenceEvent));
m_renderFenceValue++;
// Wait until the signal command has been processed.
WaitForSingleObject(m_renderFenceEvent, INFINITE);
}
//-----------------------------------------------------------------------------
// initialize TileUpdateManager
//-----------------------------------------------------------------------------
void Scene::StartStreamingLibrary()
{
TileUpdateManagerDesc tumDesc;
tumDesc.m_maxNumCopyBatches = m_args.m_numStreamingBatches;
tumDesc.m_maxTileCopiesPerBatch = m_args.m_streamingBatchSize;
tumDesc.m_maxTileCopiesInFlight = m_args.m_maxTilesInFlight;
tumDesc.m_maxTileMappingUpdatesPerApiCall = m_args.m_maxTileUpdatesPerApiCall;
tumDesc.m_swapChainBufferCount = SharedConstants::SWAP_CHAIN_BUFFER_COUNT;
tumDesc.m_useDirectStorage = m_args.m_useDirectStorage;
m_pTileUpdateManager = std::make_unique<TileUpdateManager>(m_device.Get(), m_commandQueue.Get(), tumDesc);
// create 1 or more heaps to contain our StreamingResources
for (UINT i = 0; i < m_args.m_numHeaps; i++)
{
m_sharedHeaps.push_back(m_pTileUpdateManager->CreateStreamingHeap(m_args.m_streamingHeapSize));
}
}
//-----------------------------------------------------------------------------
// generate a random scale, position, and rotation
// also space the spheres so they do not touch
//-----------------------------------------------------------------------------
XMMATRIX Scene::SetSphereMatrix()
{
static std::default_random_engine gen(42);
static std::uniform_real_distribution<float> dis(-1, 1);
const float MIN_SPHERE_SIZE = 1.f;
const float MAX_SPHERE_SIZE = float(SharedConstants::MAX_SPHERE_SCALE);
const float SPHERE_SPACING = float(100 + SharedConstants::MAX_SPHERE_SCALE) / 100.f;
static std::uniform_real_distribution<float> scaleDis(MIN_SPHERE_SIZE, MAX_SPHERE_SIZE);
bool tryAgain = true;
UINT maxTries = 1000;
XMMATRIX matrix = XMMatrixIdentity();
while (tryAgain)
{
if (maxTries)
{
maxTries--;
}
else
{
MessageBox(0, L"Failed to fit planet in universe. Universe too small?", L"ERROR", MB_OK);
exit(-1);
}
float sphereScale = scaleDis(gen) * SharedConstants::SPHERE_SCALE;
float worldScale = SharedConstants::UNIVERSE_SIZE;
float x = worldScale * std::abs(dis(gen));
// position sphere far from terrain
x += (MAX_SPHERE_SIZE + 2) * SharedConstants::SPHERE_SCALE;
float rx = (2*XM_PI) * dis(gen);
float ry = (2*XM_PI) * dis(gen);
float rz = (2*XM_PI) * dis(gen);
XMMATRIX xlate = XMMatrixTranslation(x, 0, 0);
XMMATRIX rtate = XMMatrixRotationRollPitchYaw(rx, ry, rz);
XMMATRIX scale = XMMatrixScaling(sphereScale, sphereScale, sphereScale);
matrix = scale * xlate * rtate;
tryAgain = false;
// spread the spheres out
{
XMVECTOR p0 = matrix.r[3];
float s0 = sphereScale;
for (const auto o : m_objects)
{
if (o == m_pSky)
{
continue;
}
XMVECTOR p1 = o->GetModelMatrix().r[3];
float dist = XMVectorGetX(XMVector3LengthEst(p1 - p0));
float s1 = XMVectorGetX(XMVector3LengthEst(o->GetModelMatrix().r[0]));
// bigger planets are further apart
if (dist < SPHERE_SPACING * (s0 + s1))
{
tryAgain = true;
break;
}
}
}
}
// pre-rotate to randomize axes
float rx = (1.5f * XM_PI) * dis(gen);
float ry = (2.5f * XM_PI) * dis(gen);
float rz = (2.0f * XM_PI) * dis(gen); // rotation around polar axis of sphere model
XMMATRIX rtate = XMMatrixRotationRollPitchYaw(rx, ry, rz);
matrix = rtate * matrix;
return matrix;
}
//-----------------------------------------------------------------------------
// progressively over multiple frames, if there are many
//-----------------------------------------------------------------------------
void Scene::LoadSpheres()
{
if (m_numSpheresLoaded < (UINT)m_args.m_numSpheres)
{
// sphere descriptors start after the terrain descriptor
CD3DX12_CPU_DESCRIPTOR_HANDLE descCPU = CD3DX12_CPU_DESCRIPTOR_HANDLE(m_srvHeap->GetCPUDescriptorHandleForHeapStart(), (UINT)DescriptorHeapOffsets::NumEntries, m_srvUavCbvDescriptorSize);
// offset by all the spheres that have been loaded so far
descCPU.Offset(m_numSpheresLoaded * (UINT)SceneObjects::Descriptors::NumEntries, m_srvUavCbvDescriptorSize);
const UINT numSpheresToLoad = m_args.m_numSpheres - m_numSpheresLoaded;
for (UINT i = 0; i < numSpheresToLoad; i++)
{
// this object's index-to-be
UINT objectIndex = (UINT)m_objects.size();
// put this resource into one of our shared heaps
UINT heapIndex = objectIndex % m_sharedHeaps.size();
auto pHeap = m_sharedHeaps[heapIndex];
// grab the next texture
UINT fileIndex = objectIndex % m_args.m_textures.size();
const auto& textureFilename = m_args.m_textures[fileIndex];
SceneObjects::BaseObject* o = nullptr;
SphereGen::Properties sphereProperties;
sphereProperties.m_numLat = m_args.m_sphereLat;
sphereProperties.m_numLong = m_args.m_sphereLong;
sphereProperties.m_mirrorU = true;
// 3 options: sphere, earth, sky
// sky has to be first because it disables depth when drawn
if ((nullptr == m_pSky) && (m_args.m_skyTexture.size())) // only 1 sky
{
auto tf = m_args.m_mediaDir + L"\\\\" + m_args.m_skyTexture;
m_pSky = new SceneObjects::Sky(tf, m_pTileUpdateManager.get(), pHeap, m_device.Get(), m_args.m_sampleCount, descCPU);
o = m_pSky;
}
else if (nullptr == m_pTerrainSceneObject)
{
m_pTerrainSceneObject = new SceneObjects::Terrain(m_args.m_textureFilename, m_pTileUpdateManager.get(), pHeap, m_device.Get(), m_args.m_sampleCount, descCPU, m_args);
m_terrainObjectIndex = objectIndex;
o = m_pTerrainSceneObject;
}
// earth
else if (m_args.m_earthTexture.size() && (std::wstring::npos != textureFilename.find(m_args.m_earthTexture)))
{
if (nullptr == m_pEarth)
{
sphereProperties.m_mirrorU = false;
o = new SceneObjects::Planet(textureFilename, m_pTileUpdateManager.get(), pHeap, m_device.Get(), m_args.m_sampleCount, descCPU, sphereProperties);
m_pEarth = o;
}
else
{
o = new SceneObjects::Planet(textureFilename, m_pTileUpdateManager.get(), pHeap, m_device.Get(), descCPU, m_pEarth);
}
o->GetModelMatrix() = SetSphereMatrix();
}
// planet
else
{
if (nullptr == m_pFirstSphere)
{
sphereProperties.m_mirrorU = true;
o = new SceneObjects::Planet(textureFilename, m_pTileUpdateManager.get(), pHeap, m_device.Get(), m_args.m_sampleCount, descCPU, sphereProperties);
m_pFirstSphere = o;
}
else
{
o = new SceneObjects::Planet(textureFilename, m_pTileUpdateManager.get(), pHeap, m_device.Get(), descCPU, m_pFirstSphere);
}
o->GetModelMatrix() = SetSphereMatrix();
}
m_objects.push_back(o);
m_numSpheresLoaded++;
// offset to the next sphere
descCPU.Offset((UINT)SceneObjects::Descriptors::NumEntries, m_srvUavCbvDescriptorSize);
}
}
// evict spheres?
else if (m_numSpheresLoaded > (UINT)m_args.m_numSpheres)
{
WaitForGpu();
while (m_numSpheresLoaded > (UINT)m_args.m_numSpheres)
{
auto i = m_objects.end();
i--;
SceneObjects::BaseObject* pObject = *i;
delete pObject;
m_objects.erase(i);
if (m_pTerrainSceneObject == pObject)
{
DeleteTerrainViewers();
m_pTerrainSceneObject = nullptr;
}
if (m_pFirstSphere == pObject)
{
m_pFirstSphere = nullptr;
}
if (m_pEarth == pObject)
{
m_pEarth = nullptr;
}
if (m_pSky == pObject)
{
m_pSky = nullptr;
}
m_numSpheresLoaded--;
}
}
}
//-----------------------------------------------------------------------------
// create MSAA color and depth targets
//-----------------------------------------------------------------------------
void Scene::CreateRenderTargets()
{
D3D12_DEPTH_STENCIL_VIEW_DESC dsv = {};
D3D12_RESOURCE_DESC desc = CD3DX12_RESOURCE_DESC::Tex2D(
SharedConstants::SWAP_CHAIN_FORMAT,
(UINT64)m_viewport.Width, (UINT)m_viewport.Height,
1, 1, m_args.m_sampleCount);
// create color buffer
{
D3D12_RESOURCE_DESC colorDesc = desc;
colorDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
D3D12_CLEAR_VALUE clearValue = {};
memcpy(&clearValue.Color, &m_clearColor, sizeof(m_clearColor));
clearValue.Format = desc.Format;
const auto heapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
ThrowIfFailed(m_device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&colorDesc,
D3D12_RESOURCE_STATE_RENDER_TARGET,
&clearValue,
IID_PPV_ARGS(&m_colorBuffer)));
}
// create depth buffer
{
D3D12_RESOURCE_DESC depthDesc = desc;
depthDesc.Format = SharedConstants::DEPTH_FORMAT;
depthDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
D3D12_CLEAR_VALUE clearValue = {};
clearValue.DepthStencil.Depth = 1.0f;
clearValue.Format = SharedConstants::DEPTH_FORMAT;
const auto heapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
ThrowIfFailed(m_device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&depthDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
&clearValue,
IID_PPV_ARGS(&m_depthBuffer)));
dsv.Format = depthDesc.Format;
}
if (1 == m_args.m_sampleCount)
{
dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
}
else
{
dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS;
}
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(m_rtvHeap->GetCPUDescriptorHandleForHeapStart(), m_swapBufferCount, m_rtvDescriptorSize);
CD3DX12_CPU_DESCRIPTOR_HANDLE dsvDescriptor(m_dsvHeap->GetCPUDescriptorHandleForHeapStart());
m_device->CreateRenderTargetView(m_colorBuffer.Get(), nullptr, rtvDescriptor);
m_device->CreateDepthStencilView(m_depthBuffer.Get(), &dsv, dsvDescriptor);
}
//-----------------------------------------------------------------------------
// 1 static and 1 dynamic constant buffers
// NOTE: do this within LoadAssets, as it will create a staging resource and rely on command list submission
//-----------------------------------------------------------------------------
void Scene::CreateConstantBuffers()
{
// dynamic constant buffer
{
UINT bufferSize = sizeof(FrameConstantData);
const UINT multipleSize = 256; // required
bufferSize = (bufferSize + multipleSize - 1) / multipleSize;
bufferSize *= multipleSize;
const auto heapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
const auto resourceDesc = CD3DX12_RESOURCE_DESC::Buffer(bufferSize);
ThrowIfFailed(m_device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&m_frameConstantBuffer)));
CD3DX12_RANGE readRange(0, bufferSize);
ThrowIfFailed(m_frameConstantBuffer->Map(0, &readRange, reinterpret_cast<void**>(&m_pFrameConstantData)));
m_pFrameConstantData->g_lightDir = XMFLOAT4(-0.449135751f, 0.656364977f, 0.25f, 0);
m_pFrameConstantData->g_lightColor = XMFLOAT4(1, 1, 1, 40.0f);
m_pFrameConstantData->g_specColor = XMFLOAT4(1, 1, 1, 1);
D3D12_CONSTANT_BUFFER_VIEW_DESC constantBufferView = {};
constantBufferView.SizeInBytes = bufferSize;
constantBufferView.BufferLocation = m_frameConstantBuffer->GetGPUVirtualAddress();
m_device->CreateConstantBufferView(&constantBufferView, CD3DX12_CPU_DESCRIPTOR_HANDLE(
m_srvHeap->GetCPUDescriptorHandleForHeapStart(), (UINT)DescriptorHeapOffsets::FRAME_CBV, m_srvUavCbvDescriptorSize));