-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCore.h
More file actions
616 lines (532 loc) · 24.8 KB
/
Copy pathCore.h
File metadata and controls
616 lines (532 loc) · 24.8 KB
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
#pragma once
#include <algorithm>
#include <d3d12.h>
#include <dxgi1_6.h>
#include <d3dcompiler.h>
#include <vector>
#include <dxgidebug.h>
#pragma comment(lib, "d3d12")
#pragma comment(lib, "dxgi")
#pragma comment(lib, "d3dcompiler.lib")
class DescriptorHeap {
public:
ID3D12DescriptorHeap* heap;
D3D12_CPU_DESCRIPTOR_HANDLE cpuHandle;
D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle;
unsigned int incrementSize;
int used;
void init(ID3D12Device5* device, int num)
{
D3D12_DESCRIPTOR_HEAP_DESC uavcbvHeapDesc = {};
uavcbvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
uavcbvHeapDesc.NumDescriptors = num;
uavcbvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
device->CreateDescriptorHeap(&uavcbvHeapDesc, IID_PPV_ARGS(&heap));
cpuHandle = heap->GetCPUDescriptorHandleForHeapStart();
gpuHandle = heap->GetGPUDescriptorHandleForHeapStart();
incrementSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
used = 0;
}
//Replaced singular getNextcpuHandle as only gets cpu, increments internally, modifies internal state, single use
int allocate() {
return used++;
}
D3D12_CPU_DESCRIPTOR_HANDLE getCpuHandle(int index) {
D3D12_CPU_DESCRIPTOR_HANDLE handle = cpuHandle;
handle.ptr += index * incrementSize;
return handle;
}
D3D12_GPU_DESCRIPTOR_HANDLE getGpuHandle(int index) {
D3D12_GPU_DESCRIPTOR_HANDLE handle = gpuHandle;
handle.ptr += index * incrementSize;
return handle;
}
};
class Barrier { //Barrier ensures each resources is in the correct state before GPU uses it
public:
static void add(ID3D12Resource* res, D3D12_RESOURCE_STATES first, D3D12_RESOURCE_STATES second,
ID3D12GraphicsCommandList4* commandList, UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) {
D3D12_RESOURCE_BARRIER rb = {};
rb.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;//transition type
rb.Transition.pResource = res; // resource (e.g texture, buffer, etc)
rb.Transition.StateBefore = first;// current state
rb.Transition.StateAfter = second;// next state to be in
rb.Transition.Subresource = subresource; // apply the state transition to every mip levels and every array layer of the texture. Almost always used
commandList->ResourceBarrier(1, &rb);// Places the barrier into the command stream
}
};
class GPUFence { //signal to the cpu for a when a queue in the GPU has finished - cpu waiting for signal
public:
ID3D12Fence* fence;
HANDLE eventHandle;
UINT64 value = 0;
void create(ID3D12Device5* device) {
device->CreateFence(value, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
eventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
}
void signal(ID3D12CommandQueue* queue) {
queue->Signal(fence, ++value);
}
void wait() {
if (fence->GetCompletedValue() < value) {
fence->SetEventOnCompletion(value, eventHandle);
WaitForSingleObject(eventHandle, INFINITE);
}
}
~GPUFence() {
CloseHandle(eventHandle);
fence->Release();
}
};
class Core
{
public:
IDXGIAdapter1* adapter; //GPU hardware used
ID3D12Device5* device; //DX12 interfce to create GPU resources
ID3D12CommandQueue* graphicsQueue; //submits rendering commands to GPU -- only going to use this queue
ID3D12CommandQueue* copyQueue; // Handles GPU memory copy operations
ID3D12CommandQueue* computeQueue; // Runs compute shdaer options
IDXGISwapChain3* swapchain; // Manages backbuffers for presenting frames
ID3D12CommandAllocator* graphicsCommandAllocator[2]; // per-fame memory for command lists
ID3D12GraphicsCommandList4* graphicsCommandList[2]; //Recor GPU rendering commands
ID3D12DescriptorHeap* backbufferHeap; //Stores RTV descriptors for backbuffers
ID3D12Resource** backbuffers; //Actual render targets for each frame
GPUFence graphicsQueueFence[2]; // sync cpu/gpu per backbuffer frame
ID3D12DescriptorHeap* dsvHeap; // stores depth-stencil view descriptor
ID3D12Resource* dsv; //GPU depth - buffer texture
D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle; //CPU pointer to depth view descriptor
D3D12_VIEWPORT viewport; //Defines rendering area size
D3D12_RECT scissorRect; // Clip rectangle for rasterization
ID3D12RootSignature* rootSignature;
DescriptorHeap srvHeap;
ID3D12RootSignature* mipGenRootSignature;
ID3D12PipelineState* mipGenPipeline;
void init(HWND hwnd, int _width, int _height) //window width height and handle to the window
{
//Makes a pointer to your gpus and an array of your gpus
IDXGIAdapter1* adapterf;
std::vector<IDXGIAdapter1*> adapters;
IDXGIFactory6* factory = NULL;
//Creates system inteface that manages all dxgi stuff
//DXGI is the gearbox and dashboard to D3D12 being the engine. Handles where things go and how the user sees them
CreateDXGIFactory(__uuidof(IDXGIFactory6), (void**)&factory);
int i = 0;
while (factory->EnumAdapters1(i, &adapterf) != DXGI_ERROR_NOT_FOUND)
{
adapters.push_back(adapterf); //loops through adapters and puts them into a list
i++;
}
long long maxVideoMemory = 0;
int useAdapterIndex = 0;
for (int i = 0; i < adapters.size(); i++)
{
DXGI_ADAPTER_DESC desc;
adapters[i]->GetDesc(&desc);
if (desc.DedicatedVideoMemory > maxVideoMemory)
{
maxVideoMemory = desc.DedicatedVideoMemory;
useAdapterIndex = i;
}
}
adapter = adapters[useAdapterIndex]; //Selected best GPU - Highest VRAM
#if defined(_DEBUG) //debugging bind errors
{
ID3D12Debug* debugController = nullptr;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
{
debugController->EnableDebugLayer(); // enable debug layer
debugController->Release();
}
}
#endif
D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_1, IID_PPV_ARGS(&device)); // Creates DX12 device based on your gpu
//Command queue is the thread where you submit work
D3D12_COMMAND_QUEUE_DESC graphicsQueueDesc = {};
graphicsQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
device->CreateCommandQueue(&graphicsQueueDesc, IID_PPV_ARGS(&graphicsQueue)); // rendering, rasterization, pixel shaders
D3D12_COMMAND_QUEUE_DESC copyQueueDesc = {};
copyQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
device->CreateCommandQueue(©QueueDesc, IID_PPV_ARGS(©Queue)); // memory copies and uploads - no shaders, copies CPU to and from GPU
D3D12_COMMAND_QUEUE_DESC computeQueueDesc = {};
computeQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
device->CreateCommandQueue(&computeQueueDesc, IID_PPV_ARGS(&computeQueue));// Compute shaders, async particle sim, async post processing, AI/physics, Parallelism
// Queues can run in parallel on GPUs
//will only use Direct queues in this project
//Swapchain description
DXGI_SWAP_CHAIN_DESC1 scDesc = {};
scDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //Standard 8-bit channel - most common channel
scDesc.Width = _width;
scDesc.Height = _height;
scDesc.SampleDesc.Count = 1; // MSAA - multisampling - 1 = no msaa - requires special setup and rarely used in swapchains
scDesc.SampleDesc.Quality = 0;
scDesc.BufferCount = 2; //number of buffers
scDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; //Only correct swap effect for dx12
//Manages how frames are presented
IDXGISwapChain1* swapChain1; //Swaps the buffers
factory->CreateSwapChainForHwnd(graphicsQueue, hwnd, &scDesc, NULL, NULL, &swapChain1);
swapChain1->QueryInterface(&swapchain);//swaps buffers
swapChain1->Release();//releases swapchain
factory->Release();
// 1 allocator and command list for each back buffer
device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, // Stores the commands written by the command list in heavy memory
IID_PPV_ARGS(&graphicsCommandAllocator[0]));
device->CreateCommandList1(0, D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_FLAG_NONE,// writes the commands for the gpu onto the allocator
IID_PPV_ARGS(&graphicsCommandList[0]));
device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
IID_PPV_ARGS(&graphicsCommandAllocator[1]));
device->CreateCommandList1(0, D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_FLAG_NONE,
IID_PPV_ARGS(&graphicsCommandList[1]));
//It creates a descriptor heap capable of holding N RTV descriptors - N number of backbuffers, desc = handle to a BB render target
//heap then used to create RTV for each BB and bind those RTV to render target
//RTV is a view to tell the gpu to use this as a texture as something you can render into
D3D12_DESCRIPTOR_HEAP_DESC renderTargetViewHeapDesc = {};
renderTargetViewHeapDesc.NumDescriptors = scDesc.BufferCount;
renderTargetViewHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
device->CreateDescriptorHeap(&renderTargetViewHeapDesc, IID_PPV_ARGS(&backbufferHeap));
//Defining the backbuffers
backbuffers = new ID3D12Resource * [scDesc.BufferCount];
//creates a pointer to the start of our RTV
D3D12_CPU_DESCRIPTOR_HANDLE renderTargetViewHandle = backbufferHeap->GetCPUDescriptorHandleForHeapStart();
unsigned int renderTargetViewDescriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
for (unsigned int i = 0; i < 2; i++)
{
swapchain->GetBuffer(i, IID_PPV_ARGS(&backbuffers[i]));//Gets backbufer resource
device->CreateRenderTargetView(backbuffers[i], nullptr, renderTargetViewHandle); //create RTV for said backbuffer that points to the image
renderTargetViewHandle.ptr += renderTargetViewDescriptorSize; //move the descriptor handle forward one
}
graphicsQueueFence[0].create(device);
graphicsQueueFence[1].create(device);
//creates desc heap for depth buffer, z-buffer
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc;
memset(&dsvHeapDesc, 0, sizeof(D3D12_DESCRIPTOR_HEAP_DESC));
dsvHeapDesc.NumDescriptors = 1;
dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&dsvHeap));
dsvHandle = dsvHeap->GetCPUDescriptorHandleForHeapStart();
//defines how the depth buffer will be view when bound to the pipeline
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;
//the value the depth buffer will be cleared to each frame
D3D12_CLEAR_VALUE depthClearValue = {};
depthClearValue.Format = DXGI_FORMAT_D32_FLOAT;
depthClearValue.DepthStencil.Depth = 1.0f;
depthClearValue.DepthStencil.Stencil = 0;
//Defines where the depth buffer memory lives
D3D12_HEAP_PROPERTIES heapprops = {};
heapprops.Type = D3D12_HEAP_TYPE_DEFAULT;
heapprops.CreationNodeMask = 1;
heapprops.VisibleNodeMask = 1;
//describes the depth buffer texture resource itself
D3D12_RESOURCE_DESC dsvDesc = {};
dsvDesc.Format = DXGI_FORMAT_D32_FLOAT;
dsvDesc.Width = _width;
dsvDesc.Height = _height;
dsvDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
dsvDesc.DepthOrArraySize = 1;
dsvDesc.MipLevels = 1;
dsvDesc.SampleDesc.Count = 1;
dsvDesc.SampleDesc.Quality = 0;
dsvDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
dsvDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
//allocates the gpu memory for the depth buffer and put it into the inital depth_write state
device->CreateCommittedResource(&heapprops, D3D12_HEAP_FLAG_NONE, &dsvDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE, &depthClearValue, IID_PPV_ARGS(&dsv));
//creates the DSV view that is used for the pipline depth testing each frame
device->CreateDepthStencilView(dsv, &depthStencilDesc, dsvHandle);
//Defines the rectangle on the render target where the GPU draws the final image after proj and rast
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
viewport.Width = (float)_width;
viewport.Height = (float)_height;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
//cuts part out of rendering
scissorRect.left = 0;
scissorRect.top = 0;
scissorRect.right = _width;
scissorRect.bottom = _height;
std::vector<D3D12_ROOT_PARAMETER> parameters;
D3D12_ROOT_PARAMETER rootParameterCBVS;
rootParameterCBVS.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
rootParameterCBVS.Descriptor.ShaderRegister = 0; // Register(b0)
rootParameterCBVS.Descriptor.RegisterSpace = 0;
rootParameterCBVS.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
parameters.push_back(rootParameterCBVS);
D3D12_ROOT_PARAMETER rootParameterCBPS;
rootParameterCBPS.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
rootParameterCBPS.Descriptor.ShaderRegister = 0; // Register(b0)
rootParameterCBPS.Descriptor.RegisterSpace = 0;
rootParameterCBPS.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
parameters.push_back(rootParameterCBPS);
//adding a range of textures
D3D12_DESCRIPTOR_RANGE srvRange = {};
srvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
srvRange.NumDescriptors = 8; // number of SRVs (t0t7)
srvRange.BaseShaderRegister = 0; // starting at t0
srvRange.RegisterSpace = 0;
srvRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
D3D12_ROOT_PARAMETER rootParameterTex;
rootParameterTex.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParameterTex.DescriptorTable.NumDescriptorRanges = 1;
rootParameterTex.DescriptorTable.pDescriptorRanges = &srvRange;
rootParameterTex.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
parameters.push_back(rootParameterTex);
//texture sampler for rendering pipeline
D3D12_STATIC_SAMPLER_DESC staticSampler = {};
staticSampler.Filter = D3D12_FILTER_ANISOTROPIC;
staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
staticSampler.MipLODBias = -0.5f;
staticSampler.MaxAnisotropy = 8;
staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK;
staticSampler.MinLOD = 0.0f;
staticSampler.MaxLOD = D3D12_FLOAT32_MAX;
staticSampler.ShaderRegister = 0;
staticSampler.RegisterSpace = 0;
staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
D3D12_ROOT_SIGNATURE_DESC desc = {};
desc.NumParameters = (UINT)parameters.size();
desc.pParameters = parameters.data();
desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
desc.NumStaticSamplers = 1;
desc.pStaticSamplers = &staticSampler;
ID3DBlob* serialized;
ID3DBlob* error;
D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, &error);
device->CreateRootSignature(1, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&rootSignature));
serialized->Release();
srvHeap.init(device, 16384);
D3D12_DESCRIPTOR_RANGE ranges[2] = {};
//srvRange
ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
ranges[0].NumDescriptors = 1;
ranges[0].BaseShaderRegister = 0;
ranges[0].RegisterSpace = 0;
ranges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
//uavRange
ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
ranges[1].NumDescriptors = 1;
ranges[1].BaseShaderRegister = 0;
ranges[1].RegisterSpace = 0;
ranges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
D3D12_ROOT_PARAMETER rootParams[3] = {};
//srv table
rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParams[0].DescriptorTable.NumDescriptorRanges = 1;
rootParams[0].DescriptorTable.pDescriptorRanges = &ranges[0];
rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
//uav table
rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParams[1].DescriptorTable.NumDescriptorRanges = 1;
rootParams[1].DescriptorTable.pDescriptorRanges = &ranges[1];
rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
//constants - texelSize for compute shader
rootParams[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
rootParams[2].Constants.ShaderRegister = 0;
rootParams[2].Constants.RegisterSpace = 0;
rootParams[2].Constants.Num32BitValues = 2;
rootParams[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
D3D12_ROOT_SIGNATURE_DESC rootSigDesc = {};
rootSigDesc.NumParameters = 3;
rootSigDesc.pParameters = rootParams;
rootSigDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
ID3DBlob* MipSignature;
ID3DBlob* MipError;
D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1, &MipSignature, &MipError);
device->CreateRootSignature(0, MipSignature->GetBufferPointer(), MipSignature->GetBufferSize(), IID_PPV_ARGS(&mipGenRootSignature));
MipSignature->Release();
ID3DBlob* mipShader;
ID3DBlob* mipShaderError;
D3DCompileFromFile(L"Resources/Shaders/MipGeneration.txt", nullptr, nullptr
, "main", "cs_5_1", D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION, 0, &mipShader, &mipShaderError);
D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.pRootSignature = mipGenRootSignature;
psoDesc.CS.pShaderBytecode = mipShader->GetBufferPointer();
psoDesc.CS.BytecodeLength = mipShader->GetBufferSize();
device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&mipGenPipeline));
if (mipShader) mipShader->Release();
}
void release() {
rootSignature->Release();
graphicsCommandList[0]->Release();
graphicsCommandAllocator[0]->Release();
graphicsCommandList[1]->Release();
graphicsCommandAllocator[1]->Release();
swapchain->Release();
computeQueue->Release();
copyQueue->Release();
graphicsQueue->Release();
device->Release();
}
int frameIndex() {
return swapchain->GetCurrentBackBufferIndex();
}
void resetCommandList()
{
unsigned int frameIndex = swapchain->GetCurrentBackBufferIndex();
//graphicsQueueFence[frameIndex].wait();// added wait here to wait for alloctor in use rather than every frame in begin frame
graphicsCommandAllocator[frameIndex]->Reset();
//must not reset an allocator while GPU is still using it
graphicsCommandList[frameIndex]->Reset(graphicsCommandAllocator[frameIndex], NULL);
}
ID3D12GraphicsCommandList4* getCommandList()
{
unsigned int frameIndex = swapchain->GetCurrentBackBufferIndex();
return graphicsCommandList[frameIndex]; // reutrns the current command list
}
void runCommandList()
{
getCommandList()->Close();//closes the current list
ID3D12CommandList* lists[] = { getCommandList() };//inputs your list into the command list
graphicsQueue->ExecuteCommandLists(1, lists);//execute command list - sends list to allocator/GPU
}
//marks end of GPU work
void flushGraphicsQueue() {
graphicsQueueFence[0].signal(graphicsQueue);
graphicsQueueFence[0].wait();
}
void beginFrame()
{
unsigned int frameIndex = swapchain->GetCurrentBackBufferIndex();
graphicsQueueFence[frameIndex].wait(); //Waiting here changes frames in flight to 1 rather than 2
D3D12_CPU_DESCRIPTOR_HANDLE renderTargetViewHandle = backbufferHeap -> GetCPUDescriptorHandleForHeapStart();
unsigned int renderTargetViewDescriptorSize = device -> GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
renderTargetViewHandle.ptr += frameIndex * renderTargetViewDescriptorSize;
resetCommandList();
//swtiching the backbuffer from presnt to render_target
Barrier::add(backbuffers[frameIndex], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET, getCommandList());
getCommandList()->OMSetRenderTargets(1, &renderTargetViewHandle, FALSE, &dsvHandle);
float color[4];
color[0] = 0;
color[1] = 0;
color[2] = 1.0;
color[3] = 1.0;
getCommandList()->ClearRenderTargetView(renderTargetViewHandle, color, 0, NULL);
getCommandList()->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, NULL);
}
void finishFrame()
{
unsigned int frameIndex = swapchain->GetCurrentBackBufferIndex();
Barrier::add(backbuffers[frameIndex], D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_PRESENT, getCommandList());
runCommandList();
graphicsQueueFence[frameIndex].signal(graphicsQueue);
swapchain->Present(1, 0);
}
//vertex buffer upload - copy from cpu to upload heap, then from upload heap to gpu memory - not using copy queues or asynchronization
void uploadResource(ID3D12Resource* dstResource, const void* data, unsigned int size,
D3D12_RESOURCE_STATES targetState, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* texFootprint = NULL) {
ID3D12Resource* uploadBuffer;
D3D12_HEAP_PROPERTIES heapProps = {};
heapProps.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC bufferDesc = {};
bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
bufferDesc.Width = size;
bufferDesc.Height = 1;
bufferDesc.DepthOrArraySize = 1;
bufferDesc.MipLevels = 1;
bufferDesc.SampleDesc.Count = 1;
bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
device->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &bufferDesc,
D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer));
void* mappeddata = NULL; //standard CPU pointer for that buffer
uploadBuffer->Map(0, NULL, &mappeddata);
/*char buffer[512];
sprintf_s(buffer, "About to memcpy: data=%p, mappeddata=%p, size=%u\n", data, mappeddata, size);
OutputDebugStringA(buffer);*/
memcpy(mappeddata, data, size);//copy data into mappeddata
uploadBuffer->Unmap(0, NULL);//finished with cpu pointer
resetCommandList();
//issue copy command - if statment checks for texture
if (texFootprint != NULL)
{
D3D12_TEXTURE_COPY_LOCATION src = {};
src.pResource = uploadBuffer;
src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
src.PlacedFootprint = *texFootprint;
D3D12_TEXTURE_COPY_LOCATION dst = {};
dst.pResource = dstResource;
dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
dst.SubresourceIndex = 0;
getCommandList()->CopyTextureRegion(&dst, 0, 0, 0, &src, NULL);
}
else
{
getCommandList()->CopyBufferRegion(dstResource, 0, uploadBuffer, 0, size);
}
Barrier::add(dstResource, D3D12_RESOURCE_STATE_COPY_DEST, targetState, getCommandList());
runCommandList();
flushGraphicsQueue();
uploadBuffer->Release();
}
void beginRenderPass()
{
getCommandList()->RSSetViewports(1, &viewport);
getCommandList()->RSSetScissorRects(1, &scissorRect);
getCommandList()->SetGraphicsRootSignature(rootSignature);
getCommandList()->SetDescriptorHeaps(1, &srvHeap.heap);
}
void generateMips(ID3D12Resource* tex, int width, int height, UINT mipLevels, int arraySize = 1) {
if (mipLevels <= 1) return;
resetCommandList();
getCommandList()->SetPipelineState(mipGenPipeline);
getCommandList()->SetComputeRootSignature(mipGenRootSignature);
ID3D12DescriptorHeap* heaps[] = { srvHeap.heap };
getCommandList()->SetDescriptorHeaps(1, heaps);
for (int slice = 0; slice < arraySize; slice++) {
UINT sourceWidth = width;
UINT sourceHeight = height;
for (UINT mip = 0; mip < mipLevels - 1; mip++) {
UINT destWidth = sourceWidth / 2;
UINT destHeight = sourceHeight / 2;
if (destWidth < 1) destWidth = 1;
if (destHeight < 1) destHeight = 1;
UINT destSubresource = (mip + 1) + (slice * mipLevels);
// Transition only dest mip to UAV
Barrier::add(tex, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, getCommandList(), destSubresource);
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.Texture2DArray.MostDetailedMip = mip;
srvDesc.Texture2DArray.MipLevels = 1;
srvDesc.Texture2DArray.FirstArraySlice = slice;
srvDesc.Texture2DArray.ArraySize = 1;
D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
uavDesc.Texture2DArray.MipSlice = mip + 1;
uavDesc.Texture2DArray.FirstArraySlice = slice;
uavDesc.Texture2DArray.ArraySize = 1;
int srvSlot = srvHeap.allocate();
int uavSlot = srvHeap.allocate();
device->CreateShaderResourceView(tex, &srvDesc, srvHeap.getCpuHandle(srvSlot));
device->CreateUnorderedAccessView(tex, nullptr, &uavDesc, srvHeap.getCpuHandle(uavSlot));
getCommandList()->SetComputeRootDescriptorTable(0, srvHeap.getGpuHandle(srvSlot));
getCommandList()->SetComputeRootDescriptorTable(1, srvHeap.getGpuHandle(uavSlot));
float texelSize[2] = { 1.0f / sourceWidth, 1.0f / sourceHeight };
getCommandList()->SetComputeRoot32BitConstants(2, 2, texelSize, 0);
// Thread group alignment
UINT groupsX = (destWidth + 7) / 8;
UINT groupsY = (destHeight + 7) / 8;
getCommandList()->Dispatch(groupsX, groupsY, 1);
// Transition dest back to readable
Barrier::add(tex, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, getCommandList(), destSubresource);
sourceWidth = destWidth;
sourceHeight = destHeight;
}
}
// Final transition - all subresources to pixel shader resource
Barrier::add(tex, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, getCommandList());
runCommandList();
flushGraphicsQueue();
}
};