-
Notifications
You must be signed in to change notification settings - Fork 63
/
CrateApp.cs
570 lines (474 loc) · 22.7 KB
/
CrateApp.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
using System.Collections.Generic;
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
{
public class CrateApp : D3DApp
{
private readonly List<FrameResource> _frameResources = new List<FrameResource>(NumFrameResources);
private readonly List<AutoResetEvent> _fenceEvents = new List<AutoResetEvent>(NumFrameResources);
private int _currFrameResourceIndex;
private DescriptorHeap _srvDescriptorHeap;
private DescriptorHeap[] _descriptorHeaps;
private RootSignature _rootSignature;
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 PipelineState _opaquePso;
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>>(1)
{
[RenderLayer.Opaque] = new List<RenderItem>()
};
private PassConstants _mainPassCB = PassConstants.Default;
private Vector3 _eyePos;
private Matrix _proj = Matrix.Identity;
private Matrix _view = Matrix.Identity;
private float _theta = 1.3f * MathUtil.Pi;
private float _phi = 0.4f * MathUtil.Pi;
private float _radius = 5.0f;
private Point _lastMousePos;
public CrateApp()
{
MainWindowCaption = "Crate";
}
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);
LoadTextures();
BuildRootSignature();
BuildDescriptorHeaps();
BuildShadersAndInputLayout();
BuildShapeGeometry();
BuildMaterials();
BuildRenderItems();
BuildFrameResources();
BuildPSOs();
// Execute the initialization commands.
CommandList.Close();
CommandQueue.ExecuteCommandList(CommandList);
// Wait until initialization is complete.
FlushCommandQueue();
}
protected override void OnResize()
{
base.OnResize();
// The window resized, so update the aspect ratio and recompute the projection matrix.
_proj = Matrix.PerspectiveFovLH(MathUtil.PiOverFour, AspectRatio, 1.0f, 1000.0f);
}
protected override void Update(GameTimer gt)
{
UpdateCamera();
// 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();
}
UpdateObjectCBs();
UpdateMaterialCBs();
UpdateMainPassCB(gt);
}
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, _opaquePso);
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);
CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0);
// Specify the buffers we are going to render to.
CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView);
CommandList.SetDescriptorHeaps(1, _descriptorHeaps);
CommandList.SetGraphicsRootSignature(_rootSignature);
Resource passCB = CurrFrameResource.PassCB.Resource;
CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress);
DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]);
// 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));
// Update angles based on input to orbit camera around box.
_theta += dx;
_phi += dy;
// Restrict the angle mPhi.
_phi = MathUtil.Clamp(_phi, 0.1f, MathUtil.Pi - 0.1f);
}
else if ((button & MouseButtons.Right) != 0)
{
// Make each pixel correspond to a quarter of a degree.
float dx = 0.005f * (location.X - _lastMousePos.X);
float dy = 0.005f * (location.Y - _lastMousePos.Y);
// Update the camera radius based on input.
_radius += dx - dy;
// Restrict the radius.
_radius = MathUtil.Clamp(_radius, 3.0f, 15.0f);
}
_lastMousePos = location;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_srvDescriptorHeap?.Dispose();
_opaquePso?.Dispose();
_rootSignature?.Dispose();
foreach (Texture texture in _textures.Values) texture.Dispose();
foreach (FrameResource frameResource in _frameResources) frameResource.Dispose();
foreach (MeshGeometry geometry in _geometries.Values) geometry.Dispose();
}
base.Dispose(disposing);
}
private void UpdateCamera()
{
// Convert Spherical to Cartesian coordinates.
_eyePos.X = _radius * MathHelper.Sinf(_phi) * MathHelper.Cosf(_theta);
_eyePos.Z = _radius * MathHelper.Sinf(_phi) * MathHelper.Sinf(_theta);
_eyePos.Y = _radius * MathHelper.Cosf(_phi);
// Build the view matrix.
_view = Matrix.LookAtLH(_eyePos, Vector3.Zero, Vector3.Up);
}
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)
};
CurrFrameResource.ObjectCB.CopyData(e.ObjCBIndex, ref objConstants);
// Next FrameResource need to be updated too.
e.NumFramesDirty--;
}
}
}
private void UpdateMaterialCBs()
{
UploadBuffer<MaterialConstants> currMaterialCB = CurrFrameResource.MaterialCB;
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 MaterialConstants
{
DiffuseAlbedo = mat.DiffuseAlbedo,
FresnelR0 = mat.FresnelR0,
Roughness = mat.Roughness,
MatTransform = Matrix.Transpose(mat.MatTransform)
};
currMaterialCB.CopyData(mat.MatCBIndex, ref matConstants);
// Next FrameResource need to be updated too.
mat.NumFramesDirty--;
}
}
}
private void UpdateMainPassCB(GameTimer gt)
{
Matrix viewProj = _view * _proj;
Matrix invView = Matrix.Invert(_view);
Matrix invProj = Matrix.Invert(_proj);
Matrix invViewProj = Matrix.Invert(viewProj);
_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.EyePosW = _eyePos;
_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.25f, 0.25f, 0.35f, 1.0f);
_mainPassCB.Lights[0].Direction = new Vector3(0.57735f, -0.57735f, 0.57735f);
_mainPassCB.Lights[0].Strength = new Vector3(0.6f);
_mainPassCB.Lights[1].Direction = new Vector3(-0.57735f, -0.57735f, 0.57735f);
_mainPassCB.Lights[1].Strength = new Vector3(0.3f);
_mainPassCB.Lights[2].Direction = new Vector3(0.0f, -0.707f, -0.707f);
_mainPassCB.Lights[2].Strength = new Vector3(0.15f);
CurrFrameResource.PassCB.CopyData(0, ref _mainPassCB);
}
private void LoadTextures()
{
var woodCrateTex = new Texture
{
Name = "woodCrateTex",
Filename = "Textures/WoodCrate01.dds"
};
woodCrateTex.Resource = TextureUtilities.CreateTextureFromDDS(Device, woodCrateTex.Filename);
_textures[woodCrateTex.Name] = woodCrateTex;
}
private void BuildRootSignature()
{
var texTable = new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0);
var descriptor1 = new RootDescriptor(0, 0);
var descriptor2 = new RootDescriptor(1, 0);
var descriptor3 = new RootDescriptor(2, 0);
// 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.Pixel, texTable),
new RootParameter(ShaderVisibility.Vertex, descriptor1, RootParameterType.ConstantBufferView),
new RootParameter(ShaderVisibility.All, descriptor2, RootParameterType.ConstantBufferView),
new RootParameter(ShaderVisibility.All, descriptor3, RootParameterType.ConstantBufferView)
};
// A root signature is an array of root parameters.
var rootSigDesc = new RootSignatureDescription(
RootSignatureFlags.AllowInputAssemblerInputLayout,
slotRootParameters,
GetStaticSamplers());
_rootSignature = Device.CreateRootSignature(rootSigDesc.Serialize());
}
private void BuildDescriptorHeaps()
{
//
// Create the SRV heap.
//
var srvHeapDesc = new DescriptorHeapDescription
{
DescriptorCount = 1,
Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
Flags = DescriptorHeapFlags.ShaderVisible
};
_srvDescriptorHeap = Device.CreateDescriptorHeap(srvHeapDesc);
_descriptorHeaps = new[] { _srvDescriptorHeap };
//
// Fill out the heap with actual descriptors.
//
var hDescriptor = _srvDescriptorHeap.CPUDescriptorHandleForHeapStart;
Resource woodCrateTexture = _textures["woodCrateTex"].Resource;
var srvDesc = new ShaderResourceViewDescription
{
// TODO: API suggestion: Expose DefaultShader4ComponentMapping through ShaderComponentMapping enumeration.
// TODO: Turn from int to ShaderComponentMapping enum.
Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
Format = woodCrateTexture.Description.Format,
Dimension = ShaderResourceViewDimension.Texture2D,
Texture2D = new ShaderResourceViewDescription.Texture2DResource
{
MostDetailedMip = 0,
MipLevels = woodCrateTexture.Description.MipLevels,
ResourceMinLODClamp = 0.0f
}
};
Device.CreateShaderResourceView(woodCrateTexture, srvDesc, hDescriptor);
}
private void BuildShadersAndInputLayout()
{
_shaders["standardVS"] = D3DUtil.CompileShader("Shaders\\Default.hlsl", "VS", "vs_5_0");
_shaders["opaquePS"] = D3DUtil.CompileShader("Shaders\\Default.hlsl", "PS", "ps_5_0");
_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)
});
}
private void BuildShapeGeometry()
{
GeometryGenerator.MeshData box = GeometryGenerator.CreateBox(1.0f, 1.0f, 1.0f, 3);
var boxSubmesh = new SubmeshGeometry
{
IndexCount = box.Indices32.Count,
StartIndexLocation = 0,
BaseVertexLocation = 0
};
Vertex[] vertices = box.Vertices.Select(x => new Vertex
{
Pos = x.Position,
Normal = x.Normal,
TexC = x.TexC
}).ToArray();
short[] indices = box.GetIndices16().ToArray();
var geo = MeshGeometry.New(Device, CommandList, vertices, indices, "boxGeo");
geo.DrawArgs["box"] = boxSubmesh;
_geometries[geo.Name] = geo;
}
private void BuildPSOs()
{
//
// PSO for opaque objects.
//
var opaquePsoDesc = new GraphicsPipelineStateDescription
{
InputLayout = _inputLayout,
RootSignature = _rootSignature,
VertexShader = _shaders["standardVS"],
PixelShader = _shaders["opaquePS"],
RasterizerState = RasterizerStateDescription.Default(),
BlendState = BlendStateDescription.Default(),
DepthStencilState = DepthStencilStateDescription.Default(),
SampleMask = int.MaxValue,
PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
RenderTargetCount = 1,
SampleDescription = new SampleDescription(MsaaCount, MsaaQuality),
DepthStencilFormat = DepthStencilFormat
};
opaquePsoDesc.RenderTargetFormats[0] = BackBufferFormat;
_opaquePso = Device.CreateGraphicsPipelineState(opaquePsoDesc);
}
private void BuildFrameResources()
{
for (int i = 0; i < NumFrameResources; i++)
{
_frameResources.Add(new FrameResource(Device, 1, _allRitems.Count, _materials.Count));
_fenceEvents.Add(new AutoResetEvent(false));
}
}
private void BuildMaterials()
{
AddMaterial(new Material
{
Name = "woodCrate",
MatCBIndex = 0,
DiffuseSrvHeapIndex = 0,
DiffuseAlbedo = Color.White.ToVector4(),
FresnelR0 = new Vector3(0.05f),
Roughness = 0.2f
});
}
private void AddMaterial(Material mat) => _materials[mat.Name] = mat;
private void BuildRenderItems()
{
MeshGeometry geo = _geometries["boxGeo"];
SubmeshGeometry submesh = geo.DrawArgs["box"];
var boxRitem = new RenderItem
{
ObjCBIndex = 0,
Mat = _materials["woodCrate"],
Geo = geo,
PrimitiveType = PrimitiveTopology.TriangleList,
IndexCount = submesh.IndexCount,
StartIndexLocation = submesh.StartIndexLocation,
BaseVertexLocation = submesh.BaseVertexLocation
};
_allRitems.Add(boxRitem);
// All the render items are opaque.
_ritemLayers[RenderLayer.Opaque].AddRange(_allRitems);
}
private void DrawRenderItems(GraphicsCommandList cmdList, List<RenderItem> ritems)
{
int objCBByteSize = D3DUtil.CalcConstantBufferByteSize<ObjectConstants>();
int matCBByteSize = D3DUtil.CalcConstantBufferByteSize<MaterialConstants>();
Resource objectCB = CurrFrameResource.ObjectCB.Resource;
Resource matCB = CurrFrameResource.MaterialCB.Resource;
foreach (RenderItem ri in ritems)
{
cmdList.SetVertexBuffer(0, ri.Geo.VertexBufferView);
cmdList.SetIndexBuffer(ri.Geo.IndexBufferView);
cmdList.PrimitiveTopology = ri.PrimitiveType;
GpuDescriptorHandle tex = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart +
ri.Mat.DiffuseSrvHeapIndex * CbvSrvUavDescriptorSize;
long objCBAddress = objectCB.GPUVirtualAddress + ri.ObjCBIndex * objCBByteSize;
long matCBAddress = matCB.GPUVirtualAddress + ri.Mat.MatCBIndex * matCBByteSize;
cmdList.SetGraphicsRootDescriptorTable(0, tex);
cmdList.SetGraphicsRootConstantBufferView(1, objCBAddress);
cmdList.SetGraphicsRootConstantBufferView(3, matCBAddress);
cmdList.DrawIndexedInstanced(ri.IndexCount, 1, ri.StartIndexLocation, ri.BaseVertexLocation, 0);
}
}
// 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.
private static StaticSamplerDescription[] GetStaticSamplers() => new[]
{
// PointWrap
new StaticSamplerDescription(ShaderVisibility.All, 0, 0)
{
Filter = Filter.MinMagMipPoint,
AddressUVW = TextureAddressMode.Wrap
},
// PointClamp
new StaticSamplerDescription(ShaderVisibility.All, 1, 0)
{
Filter = Filter.MinMagMipPoint,
AddressUVW = TextureAddressMode.Clamp
},
// LinearWrap
new StaticSamplerDescription(ShaderVisibility.All, 2, 0)
{
Filter = Filter.MinMagMipLinear,
AddressUVW = TextureAddressMode.Wrap
},
// LinearClamp
new StaticSamplerDescription(ShaderVisibility.All, 3, 0)
{
Filter = Filter.MinMagMipLinear,
AddressUVW = TextureAddressMode.Clamp
},
// AnisotropicWrap
new StaticSamplerDescription(ShaderVisibility.All, 4, 0)
{
Filter = Filter.Anisotropic,
AddressUVW = TextureAddressMode.Wrap,
MipLODBias = 0.0f,
MaxAnisotropy = 8
},
// AnisotropicClamp
new StaticSamplerDescription(ShaderVisibility.All, 5, 0)
{
Filter = Filter.Anisotropic,
AddressUVW = TextureAddressMode.Clamp,
MipLODBias = 0.0f,
MaxAnisotropy = 8
}
};
}
}