-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathSsaoApp.cs
1301 lines (1080 loc) · 55.1 KB
/
SsaoApp.cs
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D12;
using SharpDX.DXGI;
using Resource = SharpDX.Direct3D12.Resource;
using ShaderResourceViewDimension = SharpDX.Direct3D12.ShaderResourceViewDimension;
namespace DX12GameProgramming
{
// TODO: Fix ssao computation.
public class SsaoApp : D3DApp
{
private const int ShadowMapSize = 2048;
private readonly List<FrameResource> _frameResources = new List<FrameResource>(NumFrameResources);
private readonly List<AutoResetEvent> _fenceEvents = new List<AutoResetEvent>(NumFrameResources);
private int _currFrameResourceIndex;
private RootSignature _rootSignature;
private RootSignature _ssaoRootSignature;
private DescriptorHeap _srvDescriptorHeap;
private DescriptorHeap[] _descriptorHeaps;
private readonly Dictionary<string, MeshGeometry> _geometries = new Dictionary<string, MeshGeometry>();
private readonly Dictionary<string, Material> _materials = new Dictionary<string, Material>();
private readonly Dictionary<string, Texture> _textures = new Dictionary<string, Texture>();
private readonly Dictionary<string, ShaderBytecode> _shaders = new Dictionary<string, ShaderBytecode>();
private readonly Dictionary<string, PipelineState> _psos = new Dictionary<string, PipelineState>();
private InputLayoutDescription _inputLayout;
// List of all the render items.
private readonly List<RenderItem> _allRitems = new List<RenderItem>();
// Render items divided by PSO.
private readonly Dictionary<RenderLayer, List<RenderItem>> _ritemLayers = new Dictionary<RenderLayer, List<RenderItem>>
{
[RenderLayer.Opaque] = new List<RenderItem>(),
[RenderLayer.Debug] = new List<RenderItem>(),
[RenderLayer.Sky] = new List<RenderItem>()
};
private int _skyTexHeapIndex;
private int _shadowMapHeapIndex;
private int _ssaoHeapIndexStart;
private GpuDescriptorHandle _nullSrv;
private PassConstants _mainPassCB = PassConstants.Default; // Index 0 of pass cbuffer.
private PassConstants _shadowPassCB = PassConstants.Default; // Index 1 of pass cbuffer.
private readonly Camera _camera = new Camera();
private ShadowMap _shadowMap;
private Ssao _ssao;
private SsaoConstants _ssaoCB = SsaoConstants.Default;
private readonly float[] _blurWeights = new float[12];
private BoundingSphere _sceneBounds;
private float _lightNearZ;
private float _lightFarZ;
private Vector3 _lightPosW;
private Matrix _lightView = Matrix.Identity;
private Matrix _lightProj = Matrix.Identity;
private Matrix _shadowTransform = Matrix.Identity;
private float _lightRotationAngle;
private readonly Vector3[] _baseLightDirections =
{
new Vector3(0.57735f, -0.57735f, 0.57735f),
new Vector3(-0.57735f, -0.57735f, 0.57735f),
new Vector3(0.0f, -0.707f, -0.707f)
};
private readonly Vector3[] _rotatedLightDirections = new Vector3[3];
private Point _lastMousePos;
public SsaoApp()
{
MainWindowCaption = "Ssao";
// Estimate the scene bounding sphere manually since we know how the scene was constructed.
// The grid is the "widest object" with a width of 20 and depth of 30.0f, and centered at
// the world space origin. In general, you need to loop over every world space vertex
// position and compute the bounding sphere.
_sceneBounds.Center = Vector3.Zero;
_sceneBounds.Radius = MathHelper.Sqrtf(10.0f * 10.0f + 15.0f * 15.0f);
}
private FrameResource CurrFrameResource => _frameResources[_currFrameResourceIndex];
private AutoResetEvent CurrentFenceEvent => _fenceEvents[_currFrameResourceIndex];
public override void Initialize()
{
base.Initialize();
// Reset the command list to prep for initialization commands.
CommandList.Reset(DirectCmdListAlloc, null);
_camera.Position = new Vector3(0.0f, 2.0f, -15.0f);
_shadowMap = new ShadowMap(Device, ShadowMapSize, ShadowMapSize);
_ssao = new Ssao(Device, CommandList, ClientWidth, ClientHeight);
LoadTextures();
BuildRootSignature();
BuildSsaoRootSignature();
BuildDescriptorHeaps();
BuildShadersAndInputLayout();
BuildShapeGeometry();
BuildSkullGeometry();
BuildMaterials();
BuildRenderItems();
BuildFrameResources();
BuildPSOs();
_ssao.SetPSOs(_psos["ssao"], _psos["ssaoBlur"]);
// Execute the initialization commands.
CommandList.Close();
CommandQueue.ExecuteCommandList(CommandList);
// Wait until initialization is complete.
FlushCommandQueue();
}
// Add +1 for screen normal map, +2 for ambient maps.
protected override int RtvDescriptorCount => SwapChainBufferCount + 3;
// Add +1 DSV for shadow map.
protected override int DsvDescriptorCount => 2;
protected override void OnResize()
{
base.OnResize();
// The window resized, so update the aspect ratio and recompute the projection matrix.
_camera.SetLens(MathUtil.PiOverFour, AspectRatio, 1.0f, 1000.0f);
_ssao?.OnResize(ClientWidth, ClientHeight);
// Resources changed, so need to rebuild descriptors.
_ssao?.RebuildDescriptors(DepthStencilBuffer);
}
protected override void Update(GameTimer gt)
{
OnKeyboardInput(gt);
// Cycle through the circular frame resource array.
_currFrameResourceIndex = (_currFrameResourceIndex + 1) % NumFrameResources;
// 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 (CurrFrameResource.Fence != 0 && Fence.CompletedValue < CurrFrameResource.Fence)
{
Fence.SetEventOnCompletion(CurrFrameResource.Fence, CurrentFenceEvent.SafeWaitHandle.DangerousGetHandle());
CurrentFenceEvent.WaitOne();
}
//
// Animate the lights (and hence shadows).
//
_lightRotationAngle += 0.1f * gt.DeltaTime;
Matrix r = Matrix.RotationY(_lightRotationAngle);
for (int i = 0; i < 3; i++)
_rotatedLightDirections[i] = Vector3.TransformNormal(_baseLightDirections[i], r);
UpdateObjectCBs();
UpdateMaterialBuffer();
UpdateShadowTransform();
UpdateMainPassCB(gt);
UpdateShadowPassCB();
UpdateSsaoCB();
}
protected override void Draw(GameTimer gt)
{
CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc;
// Reuse the memory associated with command recording.
// We can only reset when the associated command lists have finished execution on the GPU.
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.
CommandList.Reset(cmdListAlloc, _psos["opaque"]);
CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps);
CommandList.SetGraphicsRootSignature(_rootSignature);
//
// Shadow map pass.
//
// Bind all the materials used in this scene. For structured buffers, we can bypass the heap and
// set as a root descriptor.
Resource matBuffer = CurrFrameResource.MaterialBuffer.Resource;
CommandList.SetGraphicsRootShaderResourceView(2, matBuffer.GPUVirtualAddress);
// Bind null SRV for shadow map pass.
CommandList.SetGraphicsRootDescriptorTable(3, _nullSrv);
// Bind all the textures used in this scene. Observe
// that we only have to specify the first descriptor in the table.
// The root signature knows how many descriptors are expected in the table.
CommandList.SetGraphicsRootDescriptorTable(4, _srvDescriptorHeap.GPUDescriptorHandleForHeapStart);
DrawSceneToShadowMap();
//
// Normal/depth pass.
//
DrawNormalsAndDepth();
//
// Compute SSAO.
//
CommandList.SetGraphicsRootSignature(_ssaoRootSignature);
_ssao.ComputeSsao(CommandList, CurrFrameResource, 3);
//
// Main rendering pass.
//
CommandList.SetGraphicsRootSignature(_rootSignature);
// Rebind state whenever graphics root signature changes.
// Bind all the materials used in this scene. For structured buffers, we can bypass the heap and
// set as a root descriptor.
matBuffer = CurrFrameResource.MaterialBuffer.Resource;
CommandList.SetGraphicsRootShaderResourceView(2, matBuffer.GPUVirtualAddress);
CommandList.SetViewport(Viewport);
CommandList.SetScissorRectangles(ScissorRectangle);
// Indicate a state transition on the resource usage.
CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget);
// Clear the back buffer and depth buffer.
CommandList.ClearRenderTargetView(CurrentBackBufferView, Color.LightSteelBlue);
// WE ALREADY WROTE THE DEPTH INFO TO THE DEPTH BUFFER IN DrawNormalsAndDepth,
// SO DO NOT CLEAR DEPTH.
// Specify the buffers we are going to render to.
CommandList.SetRenderTargets(1, CurrentBackBufferView, DepthStencilView);
// Bind all the textures used in this scene. Observe
// that we only have to specify the first descriptor in the table.
// The root signature knows how many descriptors are expected in the table.
CommandList.SetGraphicsRootDescriptorTable(4, _srvDescriptorHeap.GPUDescriptorHandleForHeapStart);
Resource passCB = CurrFrameResource.PassCB.Resource;
CommandList.SetGraphicsRootConstantBufferView(1, passCB.GPUVirtualAddress);
// Bind the sky cube map. For our demos, we just use one "world" cube map representing the environment
// from far away, so all objects will use the same cube map and we only need to set it once per-frame.
// If we wanted to use "local" cube maps, we would have to change them per-object, or dynamically
// index into an array of cube maps.
GpuDescriptorHandle skyTexDescriptor = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart;
skyTexDescriptor += _skyTexHeapIndex * CbvSrvUavDescriptorSize;
CommandList.SetGraphicsRootDescriptorTable(3, skyTexDescriptor);
CommandList.PipelineState = _psos["opaque"];
DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]);
CommandList.PipelineState = _psos["debug"];
DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Debug]);
CommandList.PipelineState = _psos["sky"];
DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Sky]);
// Indicate a state transition on the resource usage.
CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present);
// Done recording commands.
CommandList.Close();
// Add the command list to the queue for execution.
CommandQueue.ExecuteCommandList(CommandList);
// Present the buffer to the screen. Presenting will automatically swap the back and front buffers.
SwapChain.Present(0, PresentFlags.None);
// Advance the fence value to mark commands up to this fence point.
CurrFrameResource.Fence = ++CurrentFence;
// 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().
CommandQueue.Signal(Fence, CurrentFence);
}
protected override void OnMouseDown(MouseButtons button, Point location)
{
base.OnMouseDown(button, location);
_lastMousePos = location;
}
protected override void OnMouseMove(MouseButtons button, Point location)
{
if ((button & MouseButtons.Left) != 0)
{
// Make each pixel correspond to a quarter of a degree.
float dx = MathUtil.DegreesToRadians(0.25f * (location.X - _lastMousePos.X));
float dy = MathUtil.DegreesToRadians(0.25f * (location.Y - _lastMousePos.Y));
_camera.Pitch(dy);
_camera.RotateY(dx);
}
_lastMousePos = location;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_ssao?.Dispose();
_shadowMap?.Dispose();
_srvDescriptorHeap?.Dispose();
_rootSignature?.Dispose();
_ssaoRootSignature?.Dispose();
foreach (Texture texture in _textures.Values) texture.Dispose();
foreach (FrameResource frameResource in _frameResources) frameResource.Dispose();
foreach (MeshGeometry geometry in _geometries.Values) geometry.Dispose();
foreach (PipelineState pso in _psos.Values) pso.Dispose();
}
base.Dispose(disposing);
}
private void OnKeyboardInput(GameTimer gt)
{
float dt = gt.DeltaTime;
if (IsKeyDown(Keys.W))
_camera.Walk(10.0f * dt);
if (IsKeyDown(Keys.S))
_camera.Walk(-10.0f * dt);
if (IsKeyDown(Keys.A))
_camera.Strafe(-10.0f * dt);
if (IsKeyDown(Keys.D))
_camera.Strafe(10.0f * dt);
_camera.UpdateViewMatrix();
}
private void UpdateObjectCBs()
{
foreach (RenderItem e in _allRitems)
{
// Only update the cbuffer data if the constants have changed.
// This needs to be tracked per frame resource.
if (e.NumFramesDirty > 0)
{
var objConstants = new ObjectConstants
{
World = Matrix.Transpose(e.World),
TexTransform = Matrix.Transpose(e.TexTransform),
MaterialIndex = e.Mat.MatCBIndex
};
CurrFrameResource.ObjectCB.CopyData(e.ObjCBIndex, ref objConstants);
// Next FrameResource need to be updated too.
e.NumFramesDirty--;
}
}
}
private void UpdateMaterialBuffer()
{
UploadBuffer<MaterialData> currMaterialCB = CurrFrameResource.MaterialBuffer;
foreach (Material mat in _materials.Values)
{
// Only update the cbuffer data if the constants have changed. If the cbuffer
// data changes, it needs to be updated for each FrameResource.
if (mat.NumFramesDirty > 0)
{
var matConstants = new MaterialData
{
DiffuseAlbedo = mat.DiffuseAlbedo,
FresnelR0 = mat.FresnelR0,
Roughness = mat.Roughness,
MatTransform = Matrix.Transpose(mat.MatTransform),
DiffuseMapIndex = mat.DiffuseSrvHeapIndex,
NormalMapIndex = mat.NormalSrvHeapIndex
};
currMaterialCB.CopyData(mat.MatCBIndex, ref matConstants);
// Next FrameResource need to be updated too.
mat.NumFramesDirty--;
}
}
}
private void UpdateShadowTransform()
{
// Only the first "main" light casts a shadow.
Vector3 lightDir = _rotatedLightDirections[0];
Vector3 lightPos = -2.0f * _sceneBounds.Radius * lightDir;
Vector3 targetPos = _sceneBounds.Center;
Vector3 lightUp = Vector3.Up;
_lightView = Matrix.LookAtLH(lightPos, targetPos, lightUp);
_lightPosW = lightPos;
// Transform bounding sphere to light space.
Vector3 sphereCenterLS = Vector3.TransformCoordinate(targetPos, _lightView);
// Ortho frustum in light space encloses scene.
float l = sphereCenterLS.X - _sceneBounds.Radius;
float b = sphereCenterLS.Y - _sceneBounds.Radius;
float n = sphereCenterLS.Z - _sceneBounds.Radius;
float r = sphereCenterLS.X + _sceneBounds.Radius;
float t = sphereCenterLS.Y + _sceneBounds.Radius;
float f = sphereCenterLS.Z + _sceneBounds.Radius;
_lightNearZ = n;
_lightFarZ = f;
_lightProj = Matrix.OrthoOffCenterLH(l, r, b, t, n, f);
// Transform NDC space [-1,+1]^2 to texture space [0,1]^2
var ndcToTexture = new Matrix(
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);
_shadowTransform = _lightView * _lightProj * ndcToTexture;
}
private void UpdateMainPassCB(GameTimer gt)
{
Matrix view = _camera.View;
Matrix proj = _camera.Proj;
Matrix viewProj = view * proj;
Matrix invView = Matrix.Invert(view);
Matrix invProj = Matrix.Invert(proj);
Matrix invViewProj = Matrix.Invert(viewProj);
// Transform NDC space [-1,+1]^2 to texture space [0,1]^2
var ndcToTexture = new Matrix(
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);
Matrix viewProjTex = viewProj * ndcToTexture;
_mainPassCB.View = Matrix.Transpose(view);
_mainPassCB.InvView = Matrix.Transpose(invView);
_mainPassCB.Proj = Matrix.Transpose(proj);
_mainPassCB.InvProj = Matrix.Transpose(invProj);
_mainPassCB.ViewProj = Matrix.Transpose(viewProj);
_mainPassCB.InvViewProj = Matrix.Transpose(invViewProj);
_mainPassCB.ViewProjTex = Matrix.Transpose(viewProjTex);
_mainPassCB.ShadowTransform = Matrix.Transpose(_shadowTransform);
_mainPassCB.EyePosW = _camera.Position;
_mainPassCB.RenderTargetSize = new Vector2(ClientWidth, ClientHeight);
_mainPassCB.InvRenderTargetSize = 1.0f / _mainPassCB.RenderTargetSize;
_mainPassCB.NearZ = 1.0f;
_mainPassCB.FarZ = 1000.0f;
_mainPassCB.TotalTime = gt.TotalTime;
_mainPassCB.DeltaTime = gt.DeltaTime;
_mainPassCB.AmbientLight = new Vector4(0.4f, 0.4f, 0.6f, 1.0f);
_mainPassCB.Lights[0].Direction = _rotatedLightDirections[0];
_mainPassCB.Lights[0].Strength = new Vector3(0.4f, 0.4f, 0.5f);
_mainPassCB.Lights[1].Direction = _rotatedLightDirections[1];
_mainPassCB.Lights[1].Strength = new Vector3(0.1f);
_mainPassCB.Lights[2].Direction = _rotatedLightDirections[2];
_mainPassCB.Lights[2].Strength = new Vector3(0.0f);
CurrFrameResource.PassCB.CopyData(0, ref _mainPassCB);
}
private void UpdateShadowPassCB()
{
Matrix view = _lightView;
Matrix proj = _lightProj;
Matrix viewProj = view * proj;
Matrix invView = Matrix.Invert(view);
Matrix invProj = Matrix.Invert(proj);
Matrix invViewProj = Matrix.Invert(viewProj);
_shadowPassCB.View = Matrix.Transpose(view);
_shadowPassCB.InvView = Matrix.Transpose(invView);
_shadowPassCB.Proj = Matrix.Transpose(proj);
_shadowPassCB.InvProj = Matrix.Transpose(invProj);
_shadowPassCB.ViewProj = Matrix.Transpose(viewProj);
_shadowPassCB.InvViewProj = Matrix.Transpose(invViewProj);
_shadowPassCB.EyePosW = _lightPosW;
_shadowPassCB.RenderTargetSize = new Vector2(_shadowMap.Width, _shadowMap.Height);
_shadowPassCB.InvRenderTargetSize = 1.0f / _shadowPassCB.RenderTargetSize;
_shadowPassCB.NearZ = _lightNearZ;
_shadowPassCB.FarZ = _lightFarZ;
CurrFrameResource.PassCB.CopyData(1, ref _shadowPassCB);
}
private void UpdateSsaoCB()
{
// Transform NDC space [-1,+1]^2 to texture space [0,1]^2
var ndcToTexture = new Matrix(
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);
_ssaoCB.Proj = _mainPassCB.Proj;
_ssaoCB.InvProj = _mainPassCB.InvProj;
_ssaoCB.ProjTex = Matrix.Transpose(_camera.Proj * ndcToTexture);
_ssao.GetOffsetVectors(_ssaoCB.OffsetVectors);
_ssao.CalcGaussWeights(2.5f, _blurWeights);
_ssaoCB.BlurWeights[0] = new Vector4(_blurWeights[0], _blurWeights[1], _blurWeights[2], _blurWeights[3]);
_ssaoCB.BlurWeights[1] = new Vector4(_blurWeights[4], _blurWeights[5], _blurWeights[6], _blurWeights[7]);
_ssaoCB.BlurWeights[2] = new Vector4(_blurWeights[8], _blurWeights[9], _blurWeights[10], _blurWeights[11]);
_ssaoCB.InvRenderTargetSize = 1.0f / new Vector2(_ssao.SsaoMapWidth, _ssao.SsaoMapHeight);
// Coordinates given in view space.
_ssaoCB.OcclusionRadius = 0.5f;
_ssaoCB.OcclusionFadeStart = 0.2f;
_ssaoCB.OcclusionFadeEnd = 1.0f;
_ssaoCB.SurfaceEpsilon = 0.05f;
CurrFrameResource.SsaoCB.CopyData(0, ref _ssaoCB);
}
private void LoadTextures()
{
AddTexture("bricksDiffuseMap", "bricks2.dds");
AddTexture("bricksNormalMap", "bricks2_nmap.dds");
AddTexture("tileDiffuseMap", "tile.dds");
AddTexture("tileNormalMap", "tile_nmap.dds");
AddTexture("defaultDiffuseMap", "white1x1.dds");
AddTexture("defaultNormalMap", "default_nmap.dds");
AddTexture("skyCubeMap", "sunsetcube1024.dds");
}
private void AddTexture(string name, string filename)
{
var tex = new Texture
{
Name = name,
Filename = $"Textures\\{filename}"
};
tex.Resource = TextureUtilities.CreateTextureFromDDS(Device, tex.Filename);
_textures[tex.Name] = tex;
}
private void BuildRootSignature()
{
// Root parameter can be a table, root descriptor or root constants.
// Perfomance TIP: Order from most frequent to least frequent.
var slotRootParameters = new[]
{
new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 0), RootParameterType.ConstantBufferView),
new RootParameter(ShaderVisibility.All, new RootDescriptor(1, 0), RootParameterType.ConstantBufferView),
new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 1), RootParameterType.ShaderResourceView),
new RootParameter(ShaderVisibility.Pixel, new DescriptorRange(DescriptorRangeType.ShaderResourceView, 3, 0, 0, -1)),
new RootParameter(ShaderVisibility.Pixel, new DescriptorRange(DescriptorRangeType.ShaderResourceView, 10, 3, 0 , -1))
};
// A root signature is an array of root parameters.
var rootSigDesc = new RootSignatureDescription(
RootSignatureFlags.AllowInputAssemblerInputLayout,
slotRootParameters,
GetStaticSamplers());
_rootSignature = Device.CreateRootSignature(rootSigDesc.Serialize());
}
private void BuildSsaoRootSignature()
{
// Root parameter can be a table, root descriptor or root constants.
// Perfomance TIP: Order from most frequent to least frequent.
var slotRootParameters = new[]
{
new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 0), RootParameterType.ConstantBufferView),
new RootParameter(ShaderVisibility.All, new RootConstants(1, 0, 1)),
new RootParameter(ShaderVisibility.Pixel, new DescriptorRange(DescriptorRangeType.ShaderResourceView, 2, 0, 0, -1)),
new RootParameter(ShaderVisibility.Pixel, new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 2, 0, -1))
};
StaticSamplerDescription[] staticSamplers =
{
new StaticSamplerDescription(ShaderVisibility.All, 0, 0)
{
Filter = Filter.MinMagMipPoint,
AddressUVW = TextureAddressMode.Clamp,
MinLOD = 0.0f,
ComparisonFunc = Comparison.LessEqual
},
new StaticSamplerDescription(ShaderVisibility.All, 1, 0)
{
Filter = Filter.MinMagMipLinear,
AddressUVW = TextureAddressMode.Clamp,
ComparisonFunc = Comparison.LessEqual
},
new StaticSamplerDescription(ShaderVisibility.All, 2, 0)
{
Filter = Filter.MinMagMipLinear,
AddressUVW = TextureAddressMode.Border,
MipLODBias = 0.0f,
MaxAnisotropy = 0,
ComparisonFunc = Comparison.LessEqual,
BorderColor = StaticBorderColor.OpaqueWhite,
MinLOD = 0.0f
},
new StaticSamplerDescription(ShaderVisibility.All, 3, 0)
{
Filter = Filter.MinMagMipLinear,
AddressUVW = TextureAddressMode.Wrap,
MinLOD = 0.0f,
ComparisonFunc = Comparison.LessEqual
}
};
// A root signature is an array of root parameters.
var rootSigDesc = new RootSignatureDescription(
RootSignatureFlags.AllowInputAssemblerInputLayout,
slotRootParameters,
staticSamplers);
_ssaoRootSignature = Device.CreateRootSignature(rootSigDesc.Serialize());
}
private void BuildDescriptorHeaps()
{
//
// Create the SRV heap.
//
var srvHeapDesc = new DescriptorHeapDescription
{
DescriptorCount = 18, // TODO: 16 are required.
Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
Flags = DescriptorHeapFlags.ShaderVisible
};
_srvDescriptorHeap = Device.CreateDescriptorHeap(srvHeapDesc);
_descriptorHeaps = new[] { _srvDescriptorHeap };
//
// Fill out the heap with actual descriptors.
//
CpuDescriptorHandle hDescriptor = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;
Resource[] tex2DList =
{
_textures["bricksDiffuseMap"].Resource,
_textures["bricksNormalMap"].Resource,
_textures["tileDiffuseMap"].Resource,
_textures["tileNormalMap"].Resource,
_textures["defaultDiffuseMap"].Resource,
_textures["defaultNormalMap"].Resource,
};
Resource skyCubeMap = _textures["skyCubeMap"].Resource;
var srvDesc = new ShaderResourceViewDescription
{
Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
Dimension = ShaderResourceViewDimension.Texture2D,
Texture2D = new ShaderResourceViewDescription.Texture2DResource
{
MostDetailedMip = 0,
ResourceMinLODClamp = 0.0f
}
};
foreach (Resource tex2D in tex2DList)
{
srvDesc.Format = tex2D.Description.Format;
srvDesc.Texture2D.MipLevels = tex2D.Description.MipLevels;
Device.CreateShaderResourceView(tex2D, srvDesc, hDescriptor);
// Next descriptor.
hDescriptor += CbvSrvUavDescriptorSize;
}
srvDesc.Dimension = ShaderResourceViewDimension.TextureCube;
srvDesc.TextureCube = new ShaderResourceViewDescription.TextureCubeResource
{
MostDetailedMip = 0,
MipLevels = skyCubeMap.Description.MipLevels,
ResourceMinLODClamp = 0.0f
};
srvDesc.Format = skyCubeMap.Description.Format;
Device.CreateShaderResourceView(skyCubeMap, srvDesc, hDescriptor);
_skyTexHeapIndex = tex2DList.Length;
_shadowMapHeapIndex = _skyTexHeapIndex + 1;
_ssaoHeapIndexStart = _shadowMapHeapIndex + 1;
int nullCubeSrvIndex = _ssaoHeapIndexStart + 5;
CpuDescriptorHandle nullSrv = GetCpuSrv(nullCubeSrvIndex);
_nullSrv = GetGpuSrv(nullCubeSrvIndex);
Device.CreateShaderResourceView(null, srvDesc, nullSrv);
nullSrv += CbvSrvUavDescriptorSize;
srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
srvDesc.Format = Format.R8G8B8A8_UNorm;
srvDesc.Texture2D = new ShaderResourceViewDescription.Texture2DResource
{
MostDetailedMip = 0,
MipLevels = 1,
ResourceMinLODClamp = 0.0f
};
Device.CreateShaderResourceView(null, srvDesc, nullSrv);
nullSrv += CbvSrvUavDescriptorSize;
Device.CreateShaderResourceView(null, srvDesc, nullSrv);
_shadowMap.BuildDescriptors(
GetCpuSrv(_shadowMapHeapIndex),
GetGpuSrv(_shadowMapHeapIndex),
GetDsv(1));
_ssao.BuildDescriptors(
DepthStencilBuffer,
GetCpuSrv(_ssaoHeapIndexStart),
GetGpuSrv(_ssaoHeapIndexStart),
GetRtv(SwapChainBufferCount),
CbvSrvUavDescriptorSize,
RtvDescriptorSize);
}
private void BuildShadersAndInputLayout()
{
ShaderMacro[] alphaTestDefines =
{
new ShaderMacro("ALPHA_TEST", "1")
};
_shaders["standardVS"] = D3DUtil.CompileShader("Shaders\\Default.hlsl", "VS", "vs_5_1");
_shaders["opaquePS"] = D3DUtil.CompileShader("Shaders\\Default.hlsl", "PS", "ps_5_1");
_shaders["shadowVS"] = D3DUtil.CompileShader("Shaders\\Shadows.hlsl", "VS", "vs_5_1");
_shaders["shadowOpaquePS"] = D3DUtil.CompileShader("Shaders\\Shadows.hlsl", "PS", "ps_5_1");
_shaders["shadowAlphaTestedPS"] = D3DUtil.CompileShader("Shaders\\Shadows.hlsl", "PS", "ps_5_1", alphaTestDefines);
_shaders["debugVS"] = D3DUtil.CompileShader("Shaders\\ShadowDebug.hlsl", "VS", "vs_5_1");
_shaders["debugPS"] = D3DUtil.CompileShader("Shaders\\ShadowDebug.hlsl", "PS", "ps_5_1");
_shaders["drawNormalsVS"] = D3DUtil.CompileShader("Shaders\\DrawNormals.hlsl", "VS", "vs_5_1");
_shaders["drawNormalsPS"] = D3DUtil.CompileShader("Shaders\\DrawNormals.hlsl", "PS", "ps_5_1");
_shaders["ssaoVS"] = D3DUtil.CompileShader("Shaders\\Ssao.hlsl", "VS", "vs_5_1");
_shaders["ssaoPS"] = D3DUtil.CompileShader("Shaders\\Ssao.hlsl", "PS", "ps_5_1");
_shaders["ssaoBlurVS"] = D3DUtil.CompileShader("Shaders\\SsaoBlur.hlsl", "VS", "vs_5_1");
_shaders["ssaoBlurPS"] = D3DUtil.CompileShader("Shaders\\SsaoBlur.hlsl", "PS", "ps_5_1");
_shaders["skyVS"] = D3DUtil.CompileShader("Shaders\\Sky.hlsl", "VS", "vs_5_1");
_shaders["skyPS"] = D3DUtil.CompileShader("Shaders\\Sky.hlsl", "PS", "ps_5_1");
_inputLayout = new InputLayoutDescription(new[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0),
new InputElement("TANGENT", 0, Format.R32G32B32_Float, 32, 0)
});
}
private void BuildShapeGeometry()
{
//
// We are concatenating all the geometry into one big vertex/index buffer. So
// define the regions in the buffer each submesh covers.
//
var vertices = new List<Vertex>();
var indices = new List<short>();
SubmeshGeometry box = AppendMeshData(GeometryGenerator.CreateBox(1.0f, 1.0f, 1.0f, 3), vertices, indices);
SubmeshGeometry grid = AppendMeshData(GeometryGenerator.CreateGrid(20.0f, 30.0f, 60, 40), vertices, indices);
SubmeshGeometry sphere = AppendMeshData(GeometryGenerator.CreateSphere(0.5f, 20, 20), vertices, indices);
SubmeshGeometry cylinder = AppendMeshData(GeometryGenerator.CreateCylinder(0.5f, 0.3f, 3.0f, 20, 20), vertices, indices);
SubmeshGeometry quad = AppendMeshData(GeometryGenerator.CreateQuad(0.0f, 0.0f, 1.0f, 1.0f, 0.0f), vertices, indices);
var geo = MeshGeometry.New(Device, CommandList, vertices, indices, "shapeGeo");
geo.DrawArgs["box"] = box;
geo.DrawArgs["grid"] = grid;
geo.DrawArgs["sphere"] = sphere;
geo.DrawArgs["cylinder"] = cylinder;
geo.DrawArgs["quad"] = quad;
_geometries[geo.Name] = geo;
}
private SubmeshGeometry AppendMeshData(GeometryGenerator.MeshData meshData, List<Vertex> vertices, List<short> indices)
{
//
// Define the SubmeshGeometry that cover different
// regions of the vertex/index buffers.
//
var submesh = new SubmeshGeometry
{
IndexCount = meshData.Indices32.Count,
StartIndexLocation = indices.Count,
BaseVertexLocation = vertices.Count
};
//
// Extract the vertex elements we are interested in and pack the
// vertices and indices of all the meshes into one vertex/index buffer.
//
vertices.AddRange(meshData.Vertices.Select(vertex => new Vertex
{
Pos = vertex.Position,
Normal = vertex.Normal,
TexC = vertex.TexC,
TangentU = vertex.TangentU
}));
indices.AddRange(meshData.GetIndices16());
return submesh;
}
private void BuildSkullGeometry()
{
var vertices = new List<Vertex>();
var indices = new List<int>();
int vCount = 0, tCount = 0;
var vMin = new Vector3(float.MaxValue);
var vMax = new Vector3(float.MinValue);
using (var reader = new StreamReader("Models\\Skull.txt"))
{
var input = reader.ReadLine();
if (input != null)
vCount = Convert.ToInt32(input.Split(':')[1].Trim());
input = reader.ReadLine();
if (input != null)
tCount = Convert.ToInt32(input.Split(':')[1].Trim());
do
{
input = reader.ReadLine();
} while (input != null && !input.StartsWith("{", StringComparison.Ordinal));
for (int i = 0; i < vCount; i++)
{
input = reader.ReadLine();
if (input != null)
{
string[] vals = input.Split(' ');
var pos = new Vector3(
Convert.ToSingle(vals[0].Trim(), CultureInfo.InvariantCulture),
Convert.ToSingle(vals[1].Trim(), CultureInfo.InvariantCulture),
Convert.ToSingle(vals[2].Trim(), CultureInfo.InvariantCulture));
var normal = new Vector3(
Convert.ToSingle(vals[3].Trim(), CultureInfo.InvariantCulture),
Convert.ToSingle(vals[4].Trim(), CultureInfo.InvariantCulture),
Convert.ToSingle(vals[5].Trim(), CultureInfo.InvariantCulture));
// Generate a tangent vector so normal mapping works. We aren't applying
// a texture map to the skull, so we just need any tangent vector so that
// the math works out to give us the original interpolated vertex normal.
Vector3 tangent = Math.Abs(Vector3.Dot(normal, Vector3.Up)) < 1.0f - 0.001f
? Vector3.Normalize(Vector3.Cross(normal, Vector3.Up))
: Vector3.Normalize(Vector3.Cross(normal, Vector3.ForwardLH));
vertices.Add(new Vertex
{
Pos = pos,
Normal = normal,
TangentU = tangent
});
vMin = Vector3.Min(vMin, pos);
vMax = Vector3.Max(vMax, pos);
}
}
do
{
input = reader.ReadLine();
} while (input != null && !input.StartsWith("{", StringComparison.Ordinal));
for (var i = 0; i < tCount; i++)
{
input = reader.ReadLine();
if (input == null)
{
break;
}
var m = input.Trim().Split(' ');
indices.Add(Convert.ToInt32(m[0].Trim()));
indices.Add(Convert.ToInt32(m[1].Trim()));
indices.Add(Convert.ToInt32(m[2].Trim()));
}
}
var geo = MeshGeometry.New(Device, CommandList, vertices.ToArray(), indices.ToArray(), "skullGeo");
var submesh = new SubmeshGeometry
{
IndexCount = indices.Count,
StartIndexLocation = 0,
BaseVertexLocation = 0,
Bounds = new BoundingBox(vMin, vMax)
};
geo.DrawArgs["skull"] = submesh;
_geometries[geo.Name] = geo;
}
private void BuildPSOs()
{
var basePsoDesc = new GraphicsPipelineStateDescription
{
InputLayout = _inputLayout,
RootSignature = _rootSignature,
VertexShader = _shaders["standardVS"],
PixelShader = _shaders["opaquePS"],
RasterizerState = RasterizerStateDescription.Default(),
BlendState = BlendStateDescription.Default(),
DepthStencilState = DepthStencilStateDescription.Default(),
SampleMask = unchecked((int)uint.MaxValue),
PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
RenderTargetCount = 1,
SampleDescription = new SampleDescription(MsaaCount, MsaaQuality),
DepthStencilFormat = DepthStencilFormat
};
basePsoDesc.RenderTargetFormats[0] = BackBufferFormat;
//
// PSO for opaque objects.
//
GraphicsPipelineStateDescription opaquePsoDesc = basePsoDesc.Copy();
opaquePsoDesc.DepthStencilState.DepthComparison = Comparison.Equal;
opaquePsoDesc.DepthStencilState.DepthWriteMask = DepthWriteMask.Zero;
_psos["opaque"] = Device.CreateGraphicsPipelineState(opaquePsoDesc);
//
// PSO for shadow map pass.
//
GraphicsPipelineStateDescription smapPsoDesc = basePsoDesc.Copy();
smapPsoDesc.RasterizerState.DepthBias = 100000;
smapPsoDesc.RasterizerState.DepthBiasClamp = 0.0f;
smapPsoDesc.RasterizerState.SlopeScaledDepthBias = 1.0f;
smapPsoDesc.VertexShader = _shaders["shadowVS"];
smapPsoDesc.PixelShader = _shaders["shadowOpaquePS"];
// Shadow map pass does not have a render target.
smapPsoDesc.RenderTargetFormats[0] = Format.Unknown;
smapPsoDesc.RenderTargetCount = 0;
_psos["shadow_opaque"] = Device.CreateGraphicsPipelineState(smapPsoDesc);
//
// PSO for debug layer.
//
GraphicsPipelineStateDescription debugPsoDesc = basePsoDesc.Copy();
debugPsoDesc.VertexShader = _shaders["debugVS"];
debugPsoDesc.PixelShader = _shaders["debugPS"];
_psos["debug"] = Device.CreateGraphicsPipelineState(debugPsoDesc);
//
// PSO for drawing normals.
//
GraphicsPipelineStateDescription drawNormalsPsoDesc = basePsoDesc.Copy();
drawNormalsPsoDesc.VertexShader = _shaders["drawNormalsVS"];
drawNormalsPsoDesc.PixelShader = _shaders["drawNormalsPS"];
drawNormalsPsoDesc.RenderTargetFormats[0] = Ssao.NormalMapFormat;
drawNormalsPsoDesc.SampleDescription = new SampleDescription(1, 0);
_psos["drawNormals"] = Device.CreateGraphicsPipelineState(drawNormalsPsoDesc);
//
// PSO for SSAO.