forked from d3dcoder/d3d12book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstancingAndCullingApp.cpp
1025 lines (817 loc) · 34.7 KB
/
InstancingAndCullingApp.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
//***************************************************************************************
// InstancingAndCullingApp.cpp by Frank Luna (C) 2015 All Rights Reserved.
//***************************************************************************************
#include "../../Common/d3dApp.h"
#include "../../Common/MathHelper.h"
#include "../../Common/UploadBuffer.h"
#include "../../Common/GeometryGenerator.h"
#include "../../Common/Camera.h"
#include "FrameResource.h"
using Microsoft::WRL::ComPtr;
using namespace DirectX;
using namespace DirectX::PackedVector;
#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "D3D12.lib")
const int gNumFrameResources = 3;
// Lightweight structure stores parameters to draw a shape. This will
// vary from app-to-app.
struct RenderItem
{
RenderItem() = default;
RenderItem(const RenderItem& rhs) = delete;
// World matrix of the shape that describes the object's local space
// relative to the world space, which defines the position, orientation,
// and scale of the object in the world.
XMFLOAT4X4 World = MathHelper::Identity4x4();
XMFLOAT4X4 TexTransform = MathHelper::Identity4x4();
// Dirty flag indicating the object data has changed and we need to update the constant buffer.
// Because we have an object cbuffer for each FrameResource, we have to apply the
// update to each FrameResource. Thus, when we modify obect data we should set
// NumFramesDirty = gNumFrameResources so that each frame resource gets the update.
int NumFramesDirty = gNumFrameResources;
// Index into GPU constant buffer corresponding to the ObjectCB for this render item.
UINT ObjCBIndex = -1;
Material* Mat = nullptr;
MeshGeometry* Geo = nullptr;
// Primitive topology.
D3D12_PRIMITIVE_TOPOLOGY PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
BoundingBox Bounds;
std::vector<InstanceData> Instances;
// DrawIndexedInstanced parameters.
UINT IndexCount = 0;
UINT InstanceCount = 0;
UINT StartIndexLocation = 0;
int BaseVertexLocation = 0;
};
class InstancingAndCullingApp : public D3DApp
{
public:
InstancingAndCullingApp(HINSTANCE hInstance);
InstancingAndCullingApp(const InstancingAndCullingApp& rhs) = delete;
InstancingAndCullingApp& operator=(const InstancingAndCullingApp& rhs) = delete;
~InstancingAndCullingApp();
virtual bool Initialize()override;
private:
virtual void OnResize()override;
virtual void Update(const GameTimer& gt)override;
virtual void Draw(const GameTimer& gt)override;
virtual void OnMouseDown(WPARAM btnState, int x, int y)override;
virtual void OnMouseUp(WPARAM btnState, int x, int y)override;
virtual void OnMouseMove(WPARAM btnState, int x, int y)override;
void OnKeyboardInput(const GameTimer& gt);
void AnimateMaterials(const GameTimer& gt);
void UpdateInstanceData(const GameTimer& gt);
void UpdateMaterialBuffer(const GameTimer& gt);
void UpdateMainPassCB(const GameTimer& gt);
void LoadTextures();
void BuildRootSignature();
void BuildDescriptorHeaps();
void BuildShadersAndInputLayout();
void BuildSkullGeometry();
void BuildPSOs();
void BuildFrameResources();
void BuildMaterials();
void BuildRenderItems();
void DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems);
std::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> GetStaticSamplers();
private:
std::vector<std::unique_ptr<FrameResource>> mFrameResources;
FrameResource* mCurrFrameResource = nullptr;
int mCurrFrameResourceIndex = 0;
UINT mCbvSrvDescriptorSize = 0;
ComPtr<ID3D12RootSignature> mRootSignature = nullptr;
ComPtr<ID3D12DescriptorHeap> mSrvDescriptorHeap = nullptr;
std::unordered_map<std::string, std::unique_ptr<MeshGeometry>> mGeometries;
std::unordered_map<std::string, std::unique_ptr<Material>> mMaterials;
std::unordered_map<std::string, std::unique_ptr<Texture>> mTextures;
std::unordered_map<std::string, ComPtr<ID3DBlob>> mShaders;
std::unordered_map<std::string, ComPtr<ID3D12PipelineState>> mPSOs;
std::vector<D3D12_INPUT_ELEMENT_DESC> mInputLayout;
// List of all the render items.
std::vector<std::unique_ptr<RenderItem>> mAllRitems;
// Render items divided by PSO.
std::vector<RenderItem*> mOpaqueRitems;
UINT mInstanceCount = 0;
bool mFrustumCullingEnabled = true;
BoundingFrustum mCamFrustum;
PassConstants mMainPassCB;
Camera mCamera;
POINT mLastMousePos;
};
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
PSTR cmdLine, int showCmd)
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
try
{
InstancingAndCullingApp theApp(hInstance);
if(!theApp.Initialize())
return 0;
return theApp.Run();
}
catch(DxException& e)
{
MessageBox(nullptr, e.ToString().c_str(), L"HR Failed", MB_OK);
return 0;
}
}
InstancingAndCullingApp::InstancingAndCullingApp(HINSTANCE hInstance)
: D3DApp(hInstance)
{
}
InstancingAndCullingApp::~InstancingAndCullingApp()
{
if(md3dDevice != nullptr)
FlushCommandQueue();
}
bool InstancingAndCullingApp::Initialize()
{
if(!D3DApp::Initialize())
return false;
// Reset the command list to prep for initialization commands.
ThrowIfFailed(mCommandList->Reset(mDirectCmdListAlloc.Get(), nullptr));
// Get the increment size of a descriptor in this heap type. This is hardware specific,
// so we have to query this information.
mCbvSrvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
mCamera.SetPosition(0.0f, 2.0f, -15.0f);
LoadTextures();
BuildRootSignature();
BuildDescriptorHeaps();
BuildShadersAndInputLayout();
BuildSkullGeometry();
BuildMaterials();
BuildRenderItems();
BuildFrameResources();
BuildPSOs();
// Execute the initialization commands.
ThrowIfFailed(mCommandList->Close());
ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
// Wait until initialization is complete.
FlushCommandQueue();
return true;
}
void InstancingAndCullingApp::OnResize()
{
D3DApp::OnResize();
mCamera.SetLens(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
BoundingFrustum::CreateFromMatrix(mCamFrustum, mCamera.GetProj());
}
void InstancingAndCullingApp::Update(const GameTimer& gt)
{
OnKeyboardInput(gt);
// Cycle through the circular frame resource array.
mCurrFrameResourceIndex = (mCurrFrameResourceIndex + 1) % gNumFrameResources;
mCurrFrameResource = mFrameResources[mCurrFrameResourceIndex].get();
// Has the GPU finished processing the commands of the current frame resource?
// If not, wait until the GPU has completed commands up to this fence point.
if(mCurrFrameResource->Fence != 0 && mFence->GetCompletedValue() < mCurrFrameResource->Fence)
{
HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS);
ThrowIfFailed(mFence->SetEventOnCompletion(mCurrFrameResource->Fence, eventHandle));
WaitForSingleObject(eventHandle, INFINITE);
CloseHandle(eventHandle);
}
AnimateMaterials(gt);
UpdateInstanceData(gt);
UpdateMaterialBuffer(gt);
UpdateMainPassCB(gt);
}
void InstancingAndCullingApp::Draw(const GameTimer& gt)
{
auto cmdListAlloc = mCurrFrameResource->CmdListAlloc;
// Reuse the memory associated with command recording.
// We can only reset when the associated command lists have finished execution on the GPU.
ThrowIfFailed(cmdListAlloc->Reset());
// A command list can be reset after it has been added to the command queue via ExecuteCommandList.
// Reusing the command list reuses memory.
ThrowIfFailed(mCommandList->Reset(cmdListAlloc.Get(), mPSOs["opaque"].Get()));
mCommandList->RSSetViewports(1, &mScreenViewport);
mCommandList->RSSetScissorRects(1, &mScissorRect);
// Indicate a state transition on the resource usage.
mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
// Clear the back buffer and depth buffer.
mCommandList->ClearRenderTargetView(CurrentBackBufferView(), Colors::LightSteelBlue, 0, nullptr);
mCommandList->ClearDepthStencilView(DepthStencilView(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
// Specify the buffers we are going to render to.
mCommandList->OMSetRenderTargets(1, &CurrentBackBufferView(), true, &DepthStencilView());
ID3D12DescriptorHeap* descriptorHeaps[] = { mSrvDescriptorHeap.Get() };
mCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
mCommandList->SetGraphicsRootSignature(mRootSignature.Get());
// Bind all the materials used in this scene. For structured buffers, we can bypass the heap and
// set as a root descriptor.
auto matBuffer = mCurrFrameResource->MaterialBuffer->Resource();
mCommandList->SetGraphicsRootShaderResourceView(1, matBuffer->GetGPUVirtualAddress());
auto passCB = mCurrFrameResource->PassCB->Resource();
mCommandList->SetGraphicsRootConstantBufferView(2, passCB->GetGPUVirtualAddress());
// Bind all the textures used in this scene.
mCommandList->SetGraphicsRootDescriptorTable(3, mSrvDescriptorHeap->GetGPUDescriptorHandleForHeapStart());
DrawRenderItems(mCommandList.Get(), mOpaqueRitems);
// Indicate a state transition on the resource usage.
mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));
// Done recording commands.
ThrowIfFailed(mCommandList->Close());
// Add the command list to the queue for execution.
ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
// Swap the back and front buffers
ThrowIfFailed(mSwapChain->Present(0, 0));
mCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;
// Advance the fence value to mark commands up to this fence point.
mCurrFrameResource->Fence = ++mCurrentFence;
// Add an instruction to the command queue to set a new fence point.
// Because we are on the GPU timeline, the new fence point won't be
// set until the GPU finishes processing all the commands prior to this Signal().
mCommandQueue->Signal(mFence.Get(), mCurrentFence);
}
void InstancingAndCullingApp::OnMouseDown(WPARAM btnState, int x, int y)
{
mLastMousePos.x = x;
mLastMousePos.y = y;
SetCapture(mhMainWnd);
}
void InstancingAndCullingApp::OnMouseUp(WPARAM btnState, int x, int y)
{
ReleaseCapture();
}
void InstancingAndCullingApp::OnMouseMove(WPARAM btnState, int x, int y)
{
if((btnState & MK_LBUTTON) != 0)
{
// Make each pixel correspond to a quarter of a degree.
float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));
mCamera.Pitch(dy);
mCamera.RotateY(dx);
}
mLastMousePos.x = x;
mLastMousePos.y = y;
}
void InstancingAndCullingApp::OnKeyboardInput(const GameTimer& gt)
{
const float dt = gt.DeltaTime();
if(GetAsyncKeyState('W') & 0x8000)
mCamera.Walk(20.0f*dt);
if(GetAsyncKeyState('S') & 0x8000)
mCamera.Walk(-20.0f*dt);
if(GetAsyncKeyState('A') & 0x8000)
mCamera.Strafe(-20.0f*dt);
if(GetAsyncKeyState('D') & 0x8000)
mCamera.Strafe(20.0f*dt);
if(GetAsyncKeyState('1') & 0x8000)
mFrustumCullingEnabled = true;
if(GetAsyncKeyState('2') & 0x8000)
mFrustumCullingEnabled = false;
mCamera.UpdateViewMatrix();
}
void InstancingAndCullingApp::AnimateMaterials(const GameTimer& gt)
{
}
void InstancingAndCullingApp::UpdateInstanceData(const GameTimer& gt)
{
XMMATRIX view = mCamera.GetView();
XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view);
auto currInstanceBuffer = mCurrFrameResource->InstanceBuffer.get();
for(auto& e : mAllRitems)
{
const auto& instanceData = e->Instances;
int visibleInstanceCount = 0;
for(UINT i = 0; i < (UINT)instanceData.size(); ++i)
{
XMMATRIX world = XMLoadFloat4x4(&instanceData[i].World);
XMMATRIX texTransform = XMLoadFloat4x4(&instanceData[i].TexTransform);
XMMATRIX invWorld = XMMatrixInverse(&XMMatrixDeterminant(world), world);
// View space to the object's local space.
XMMATRIX viewToLocal = XMMatrixMultiply(invView, invWorld);
// Transform the camera frustum from view space to the object's local space.
BoundingFrustum localSpaceFrustum;
mCamFrustum.Transform(localSpaceFrustum, viewToLocal);
// Perform the box/frustum intersection test in local space.
if((localSpaceFrustum.Contains(e->Bounds) != DirectX::DISJOINT) || (mFrustumCullingEnabled==false))
{
InstanceData data;
XMStoreFloat4x4(&data.World, XMMatrixTranspose(world));
XMStoreFloat4x4(&data.TexTransform, XMMatrixTranspose(texTransform));
data.MaterialIndex = instanceData[i].MaterialIndex;
// Write the instance data to structured buffer for the visible objects.
currInstanceBuffer->CopyData(visibleInstanceCount++, data);
}
}
e->InstanceCount = visibleInstanceCount;
std::wostringstream outs;
outs.precision(6);
outs << L"Instancing and Culling Demo" <<
L" " << e->InstanceCount <<
L" objects visible out of " << e->Instances.size();
mMainWndCaption = outs.str();
}
}
void InstancingAndCullingApp::UpdateMaterialBuffer(const GameTimer& gt)
{
auto currMaterialBuffer = mCurrFrameResource->MaterialBuffer.get();
for(auto& e : mMaterials)
{
// Only update the cbuffer data if the constants have changed. If the cbuffer
// data changes, it needs to be updated for each FrameResource.
Material* mat = e.second.get();
if(mat->NumFramesDirty > 0)
{
XMMATRIX matTransform = XMLoadFloat4x4(&mat->MatTransform);
MaterialData matData;
matData.DiffuseAlbedo = mat->DiffuseAlbedo;
matData.FresnelR0 = mat->FresnelR0;
matData.Roughness = mat->Roughness;
XMStoreFloat4x4(&matData.MatTransform, XMMatrixTranspose(matTransform));
matData.DiffuseMapIndex = mat->DiffuseSrvHeapIndex;
currMaterialBuffer->CopyData(mat->MatCBIndex, matData);
// Next FrameResource need to be updated too.
mat->NumFramesDirty--;
}
}
}
void InstancingAndCullingApp::UpdateMainPassCB(const GameTimer& gt)
{
XMMATRIX view = mCamera.GetView();
XMMATRIX proj = mCamera.GetProj();
XMMATRIX viewProj = XMMatrixMultiply(view, proj);
XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view);
XMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj);
XMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj);
XMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view));
XMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView));
XMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj));
XMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj));
XMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj));
XMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj));
mMainPassCB.EyePosW = mCamera.GetPosition3f();
mMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight);
mMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight);
mMainPassCB.NearZ = 1.0f;
mMainPassCB.FarZ = 1000.0f;
mMainPassCB.TotalTime = gt.TotalTime();
mMainPassCB.DeltaTime = gt.DeltaTime();
mMainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f };
mMainPassCB.Lights[0].Direction = { 0.57735f, -0.57735f, 0.57735f };
mMainPassCB.Lights[0].Strength = { 0.8f, 0.8f, 0.8f };
mMainPassCB.Lights[1].Direction = { -0.57735f, -0.57735f, 0.57735f };
mMainPassCB.Lights[1].Strength = { 0.4f, 0.4f, 0.4f };
mMainPassCB.Lights[2].Direction = { 0.0f, -0.707f, -0.707f };
mMainPassCB.Lights[2].Strength = { 0.2f, 0.2f, 0.2f };
auto currPassCB = mCurrFrameResource->PassCB.get();
currPassCB->CopyData(0, mMainPassCB);
}
void InstancingAndCullingApp::LoadTextures()
{
auto bricksTex = std::make_unique<Texture>();
bricksTex->Name = "bricksTex";
bricksTex->Filename = L"../../Textures/bricks.dds";
ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
mCommandList.Get(), bricksTex->Filename.c_str(),
bricksTex->Resource, bricksTex->UploadHeap));
auto stoneTex = std::make_unique<Texture>();
stoneTex->Name = "stoneTex";
stoneTex->Filename = L"../../Textures/stone.dds";
ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
mCommandList.Get(), stoneTex->Filename.c_str(),
stoneTex->Resource, stoneTex->UploadHeap));
auto tileTex = std::make_unique<Texture>();
tileTex->Name = "tileTex";
tileTex->Filename = L"../../Textures/tile.dds";
ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
mCommandList.Get(), tileTex->Filename.c_str(),
tileTex->Resource, tileTex->UploadHeap));
auto crateTex = std::make_unique<Texture>();
crateTex->Name = "crateTex";
crateTex->Filename = L"../../Textures/WoodCrate01.dds";
ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
mCommandList.Get(), crateTex->Filename.c_str(),
crateTex->Resource, crateTex->UploadHeap));
auto iceTex = std::make_unique<Texture>();
iceTex->Name = "iceTex";
iceTex->Filename = L"../../Textures/ice.dds";
ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
mCommandList.Get(), iceTex->Filename.c_str(),
iceTex->Resource, iceTex->UploadHeap));
auto grassTex = std::make_unique<Texture>();
grassTex->Name = "grassTex";
grassTex->Filename = L"../../Textures/grass.dds";
ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
mCommandList.Get(), grassTex->Filename.c_str(),
grassTex->Resource, grassTex->UploadHeap));
auto defaultTex = std::make_unique<Texture>();
defaultTex->Name = "defaultTex";
defaultTex->Filename = L"../../Textures/white1x1.dds";
ThrowIfFailed(DirectX::CreateDDSTextureFromFile12(md3dDevice.Get(),
mCommandList.Get(), defaultTex->Filename.c_str(),
defaultTex->Resource, defaultTex->UploadHeap));
mTextures[bricksTex->Name] = std::move(bricksTex);
mTextures[stoneTex->Name] = std::move(stoneTex);
mTextures[tileTex->Name] = std::move(tileTex);
mTextures[crateTex->Name] = std::move(crateTex);
mTextures[iceTex->Name] = std::move(iceTex);
mTextures[grassTex->Name] = std::move(grassTex);
mTextures[defaultTex->Name] = std::move(defaultTex);
}
void InstancingAndCullingApp::BuildRootSignature()
{
CD3DX12_DESCRIPTOR_RANGE texTable;
texTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 7, 0, 0);
// Root parameter can be a table, root descriptor or root constants.
CD3DX12_ROOT_PARAMETER slotRootParameter[4];
// Perfomance TIP: Order from most frequent to least frequent.
slotRootParameter[0].InitAsShaderResourceView(0, 1);
slotRootParameter[1].InitAsShaderResourceView(1, 1);
slotRootParameter[2].InitAsConstantBufferView(0);
slotRootParameter[3].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);
auto staticSamplers = GetStaticSamplers();
// A root signature is an array of root parameters.
CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4, slotRootParameter,
(UINT)staticSamplers.size(), staticSamplers.data(),
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
// create a root signature with a single slot which points to a descriptor range consisting of a single constant buffer
ComPtr<ID3DBlob> serializedRootSig = nullptr;
ComPtr<ID3DBlob> errorBlob = nullptr;
HRESULT hr = D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1,
serializedRootSig.GetAddressOf(), errorBlob.GetAddressOf());
if(errorBlob != nullptr)
{
::OutputDebugStringA((char*)errorBlob->GetBufferPointer());
}
ThrowIfFailed(hr);
ThrowIfFailed(md3dDevice->CreateRootSignature(
0,
serializedRootSig->GetBufferPointer(),
serializedRootSig->GetBufferSize(),
IID_PPV_ARGS(mRootSignature.GetAddressOf())));
}
void InstancingAndCullingApp::BuildDescriptorHeaps()
{
//
// Create the SRV heap.
//
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = 7;
srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
ThrowIfFailed(md3dDevice->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&mSrvDescriptorHeap)));
//
// Fill out the heap with actual descriptors.
//
CD3DX12_CPU_DESCRIPTOR_HANDLE hDescriptor(mSrvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
auto bricksTex = mTextures["bricksTex"]->Resource;
auto stoneTex = mTextures["stoneTex"]->Resource;
auto tileTex = mTextures["tileTex"]->Resource;
auto crateTex = mTextures["crateTex"]->Resource;
auto iceTex = mTextures["iceTex"]->Resource;
auto grassTex = mTextures["grassTex"]->Resource;
auto defaultTex = mTextures["defaultTex"]->Resource;
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.Format = bricksTex->GetDesc().Format;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = bricksTex->GetDesc().MipLevels;
srvDesc.Texture2D.ResourceMinLODClamp = 0.0f;
md3dDevice->CreateShaderResourceView(bricksTex.Get(), &srvDesc, hDescriptor);
// next descriptor
hDescriptor.Offset(1, mCbvSrvDescriptorSize);
srvDesc.Format = stoneTex->GetDesc().Format;
srvDesc.Texture2D.MipLevels = stoneTex->GetDesc().MipLevels;
md3dDevice->CreateShaderResourceView(stoneTex.Get(), &srvDesc, hDescriptor);
// next descriptor
hDescriptor.Offset(1, mCbvSrvDescriptorSize);
srvDesc.Format = tileTex->GetDesc().Format;
srvDesc.Texture2D.MipLevels = tileTex->GetDesc().MipLevels;
md3dDevice->CreateShaderResourceView(tileTex.Get(), &srvDesc, hDescriptor);
// next descriptor
hDescriptor.Offset(1, mCbvSrvDescriptorSize);
srvDesc.Format = crateTex->GetDesc().Format;
srvDesc.Texture2D.MipLevels = crateTex->GetDesc().MipLevels;
md3dDevice->CreateShaderResourceView(crateTex.Get(), &srvDesc, hDescriptor);
// next descriptor
hDescriptor.Offset(1, mCbvSrvDescriptorSize);
srvDesc.Format = iceTex->GetDesc().Format;
srvDesc.Texture2D.MipLevels = iceTex->GetDesc().MipLevels;
md3dDevice->CreateShaderResourceView(iceTex.Get(), &srvDesc, hDescriptor);
// next descriptor
hDescriptor.Offset(1, mCbvSrvDescriptorSize);
srvDesc.Format = grassTex->GetDesc().Format;
srvDesc.Texture2D.MipLevels = grassTex->GetDesc().MipLevels;
md3dDevice->CreateShaderResourceView(grassTex.Get(), &srvDesc, hDescriptor);
// next descriptor
hDescriptor.Offset(1, mCbvSrvDescriptorSize);
srvDesc.Format = defaultTex->GetDesc().Format;
srvDesc.Texture2D.MipLevels = defaultTex->GetDesc().MipLevels;
md3dDevice->CreateShaderResourceView(defaultTex.Get(), &srvDesc, hDescriptor);
}
void InstancingAndCullingApp::BuildShadersAndInputLayout()
{
const D3D_SHADER_MACRO alphaTestDefines[] =
{
"ALPHA_TEST", "1",
NULL, NULL
};
mShaders["standardVS"] = d3dUtil::CompileShader(L"Shaders\\Default.hlsl", nullptr, "VS", "vs_5_1");
mShaders["opaquePS"] = d3dUtil::CompileShader(L"Shaders\\Default.hlsl", nullptr, "PS", "ps_5_1");
mInputLayout =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
}
void InstancingAndCullingApp::BuildSkullGeometry()
{
std::ifstream fin("Models/skull.txt");
if(!fin)
{
MessageBox(0, L"Models/skull.txt not found.", 0, 0);
return;
}
UINT vcount = 0;
UINT tcount = 0;
std::string ignore;
fin >> ignore >> vcount;
fin >> ignore >> tcount;
fin >> ignore >> ignore >> ignore >> ignore;
XMFLOAT3 vMinf3(+MathHelper::Infinity, +MathHelper::Infinity, +MathHelper::Infinity);
XMFLOAT3 vMaxf3(-MathHelper::Infinity, -MathHelper::Infinity, -MathHelper::Infinity);
XMVECTOR vMin = XMLoadFloat3(&vMinf3);
XMVECTOR vMax = XMLoadFloat3(&vMaxf3);
std::vector<Vertex> vertices(vcount);
for(UINT i = 0; i < vcount; ++i)
{
fin >> vertices[i].Pos.x >> vertices[i].Pos.y >> vertices[i].Pos.z;
fin >> vertices[i].Normal.x >> vertices[i].Normal.y >> vertices[i].Normal.z;
XMVECTOR P = XMLoadFloat3(&vertices[i].Pos);
// Project point onto unit sphere and generate spherical texture coordinates.
XMFLOAT3 spherePos;
XMStoreFloat3(&spherePos, XMVector3Normalize(P));
float theta = atan2f(spherePos.z, spherePos.x);
// Put in [0, 2pi].
if(theta < 0.0f)
theta += XM_2PI;
float phi = acosf(spherePos.y);
float u = theta / (2.0f*XM_PI);
float v = phi / XM_PI;
vertices[i].TexC = { u, v };
vMin = XMVectorMin(vMin, P);
vMax = XMVectorMax(vMax, P);
}
BoundingBox bounds;
XMStoreFloat3(&bounds.Center, 0.5f*(vMin + vMax));
XMStoreFloat3(&bounds.Extents, 0.5f*(vMax - vMin));
fin >> ignore;
fin >> ignore;
fin >> ignore;
std::vector<std::int32_t> indices(3 * tcount);
for(UINT i = 0; i < tcount; ++i)
{
fin >> indices[i * 3 + 0] >> indices[i * 3 + 1] >> indices[i * 3 + 2];
}
fin.close();
//
// Pack the indices of all the meshes into one index buffer.
//
const UINT vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
const UINT ibByteSize = (UINT)indices.size() * sizeof(std::int32_t);
auto geo = std::make_unique<MeshGeometry>();
geo->Name = "skullGeo";
ThrowIfFailed(D3DCreateBlob(vbByteSize, &geo->VertexBufferCPU));
CopyMemory(geo->VertexBufferCPU->GetBufferPointer(), vertices.data(), vbByteSize);
ThrowIfFailed(D3DCreateBlob(ibByteSize, &geo->IndexBufferCPU));
CopyMemory(geo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);
geo->VertexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
mCommandList.Get(), vertices.data(), vbByteSize, geo->VertexBufferUploader);
geo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
mCommandList.Get(), indices.data(), ibByteSize, geo->IndexBufferUploader);
geo->VertexByteStride = sizeof(Vertex);
geo->VertexBufferByteSize = vbByteSize;
geo->IndexFormat = DXGI_FORMAT_R32_UINT;
geo->IndexBufferByteSize = ibByteSize;
SubmeshGeometry submesh;
submesh.IndexCount = (UINT)indices.size();
submesh.StartIndexLocation = 0;
submesh.BaseVertexLocation = 0;
submesh.Bounds = bounds;
geo->DrawArgs["skull"] = submesh;
mGeometries[geo->Name] = std::move(geo);
}
void InstancingAndCullingApp::BuildPSOs()
{
D3D12_GRAPHICS_PIPELINE_STATE_DESC opaquePsoDesc;
//
// PSO for opaque objects.
//
ZeroMemory(&opaquePsoDesc, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
opaquePsoDesc.InputLayout = { mInputLayout.data(), (UINT)mInputLayout.size() };
opaquePsoDesc.pRootSignature = mRootSignature.Get();
opaquePsoDesc.VS =
{
reinterpret_cast<BYTE*>(mShaders["standardVS"]->GetBufferPointer()),
mShaders["standardVS"]->GetBufferSize()
};
opaquePsoDesc.PS =
{
reinterpret_cast<BYTE*>(mShaders["opaquePS"]->GetBufferPointer()),
mShaders["opaquePS"]->GetBufferSize()
};
opaquePsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
opaquePsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
opaquePsoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
opaquePsoDesc.SampleMask = UINT_MAX;
opaquePsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
opaquePsoDesc.NumRenderTargets = 1;
opaquePsoDesc.RTVFormats[0] = mBackBufferFormat;
opaquePsoDesc.SampleDesc.Count = m4xMsaaState ? 4 : 1;
opaquePsoDesc.SampleDesc.Quality = m4xMsaaState ? (m4xMsaaQuality - 1) : 0;
opaquePsoDesc.DSVFormat = mDepthStencilFormat;
ThrowIfFailed(md3dDevice->CreateGraphicsPipelineState(&opaquePsoDesc, IID_PPV_ARGS(&mPSOs["opaque"])));
}
void InstancingAndCullingApp::BuildFrameResources()
{
for(int i = 0; i < gNumFrameResources; ++i)
{
mFrameResources.push_back(std::make_unique<FrameResource>(md3dDevice.Get(),
1, mInstanceCount, (UINT)mMaterials.size()));
}
}
void InstancingAndCullingApp::BuildMaterials()
{
auto bricks0 = std::make_unique<Material>();
bricks0->Name = "bricks0";
bricks0->MatCBIndex = 0;
bricks0->DiffuseSrvHeapIndex = 0;
bricks0->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
bricks0->FresnelR0 = XMFLOAT3(0.02f, 0.02f, 0.02f);
bricks0->Roughness = 0.1f;
auto stone0 = std::make_unique<Material>();
stone0->Name = "stone0";
stone0->MatCBIndex = 1;
stone0->DiffuseSrvHeapIndex = 1;
stone0->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
stone0->FresnelR0 = XMFLOAT3(0.05f, 0.05f, 0.05f);
stone0->Roughness = 0.3f;
auto tile0 = std::make_unique<Material>();
tile0->Name = "tile0";
tile0->MatCBIndex = 2;
tile0->DiffuseSrvHeapIndex = 2;
tile0->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
tile0->FresnelR0 = XMFLOAT3(0.02f, 0.02f, 0.02f);
tile0->Roughness = 0.3f;
auto crate0 = std::make_unique<Material>();
crate0->Name = "checkboard0";
crate0->MatCBIndex = 3;
crate0->DiffuseSrvHeapIndex = 3;
crate0->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
crate0->FresnelR0 = XMFLOAT3(0.05f, 0.05f, 0.05f);
crate0->Roughness = 0.2f;
auto ice0 = std::make_unique<Material>();
ice0->Name = "ice0";
ice0->MatCBIndex = 4;
ice0->DiffuseSrvHeapIndex = 4;
ice0->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
ice0->FresnelR0 = XMFLOAT3(0.1f, 0.1f, 0.1f);
ice0->Roughness = 0.0f;
auto grass0 = std::make_unique<Material>();
grass0->Name = "grass0";
grass0->MatCBIndex = 5;
grass0->DiffuseSrvHeapIndex = 5;
grass0->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
grass0->FresnelR0 = XMFLOAT3(0.05f, 0.05f, 0.05f);
grass0->Roughness = 0.2f;
auto skullMat = std::make_unique<Material>();
skullMat->Name = "skullMat";
skullMat->MatCBIndex = 6;
skullMat->DiffuseSrvHeapIndex = 6;
skullMat->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
skullMat->FresnelR0 = XMFLOAT3(0.05f, 0.05f, 0.05f);
skullMat->Roughness = 0.5f;
mMaterials["bricks0"] = std::move(bricks0);
mMaterials["stone0"] = std::move(stone0);
mMaterials["tile0"] = std::move(tile0);
mMaterials["crate0"] = std::move(crate0);
mMaterials["ice0"] = std::move(ice0);
mMaterials["grass0"] = std::move(grass0);
mMaterials["skullMat"] = std::move(skullMat);
}
void InstancingAndCullingApp::BuildRenderItems()
{
auto skullRitem = std::make_unique<RenderItem>();
skullRitem->World = MathHelper::Identity4x4();
skullRitem->TexTransform = MathHelper::Identity4x4();
skullRitem->ObjCBIndex = 0;
skullRitem->Mat = mMaterials["tile0"].get();
skullRitem->Geo = mGeometries["skullGeo"].get();
skullRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
skullRitem->InstanceCount = 0;
skullRitem->IndexCount = skullRitem->Geo->DrawArgs["skull"].IndexCount;
skullRitem->StartIndexLocation = skullRitem->Geo->DrawArgs["skull"].StartIndexLocation;
skullRitem->BaseVertexLocation = skullRitem->Geo->DrawArgs["skull"].BaseVertexLocation;
skullRitem->Bounds = skullRitem->Geo->DrawArgs["skull"].Bounds;
// Generate instance data.
const int n = 5;
mInstanceCount = n*n*n;
skullRitem->Instances.resize(mInstanceCount);
float width = 200.0f;
float height = 200.0f;
float depth = 200.0f;
float x = -0.5f*width;
float y = -0.5f*height;
float z = -0.5f*depth;
float dx = width / (n - 1);
float dy = height / (n - 1);
float dz = depth / (n - 1);
for(int k = 0; k < n; ++k)
{
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
int index = k*n*n + i*n + j;
// Position instanced along a 3D grid.
skullRitem->Instances[index].World = XMFLOAT4X4(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
x + j*dx, y + i*dy, z + k*dz, 1.0f);
XMStoreFloat4x4(&skullRitem->Instances[index].TexTransform, XMMatrixScaling(2.0f, 2.0f, 1.0f));
skullRitem->Instances[index].MaterialIndex = index % mMaterials.size();
}
}
}
mAllRitems.push_back(std::move(skullRitem));
// All the render items are opaque.
for(auto& e : mAllRitems)
mOpaqueRitems.push_back(e.get());
}
void InstancingAndCullingApp::DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems)
{
// For each render item...
for(size_t i = 0; i < ritems.size(); ++i)
{
auto ri = ritems[i];
cmdList->IASetVertexBuffers(0, 1, &ri->Geo->VertexBufferView());
cmdList->IASetIndexBuffer(&ri->Geo->IndexBufferView());
cmdList->IASetPrimitiveTopology(ri->PrimitiveType);
// Set the instance buffer to use for this render-item. For structured buffers, we can bypass
// the heap and set as a root descriptor.
auto instanceBuffer = mCurrFrameResource->InstanceBuffer->Resource();
mCommandList->SetGraphicsRootShaderResourceView(0, instanceBuffer->GetGPUVirtualAddress());
cmdList->DrawIndexedInstanced(ri->IndexCount, ri->InstanceCount, ri->StartIndexLocation, ri->BaseVertexLocation, 0);
}
}
std::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> InstancingAndCullingApp::GetStaticSamplers()
{
// Applications usually only need a handful of samplers. So just define them all up front
// and keep them available as part of the root signature.
const CD3DX12_STATIC_SAMPLER_DESC pointWrap(
0, // shaderRegister
D3D12_FILTER_MIN_MAG_MIP_POINT, // filter
D3D12_TEXTURE_ADDRESS_MODE_WRAP, // addressU
D3D12_TEXTURE_ADDRESS_MODE_WRAP, // addressV
D3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW
const CD3DX12_STATIC_SAMPLER_DESC pointClamp(
1, // shaderRegister
D3D12_FILTER_MIN_MAG_MIP_POINT, // filter
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressU
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressV
D3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW
const CD3DX12_STATIC_SAMPLER_DESC linearWrap(
2, // shaderRegister
D3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter
D3D12_TEXTURE_ADDRESS_MODE_WRAP, // addressU
D3D12_TEXTURE_ADDRESS_MODE_WRAP, // addressV
D3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW
const CD3DX12_STATIC_SAMPLER_DESC linearClamp(
3, // shaderRegister
D3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressU
D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // addressV
D3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW