-
Notifications
You must be signed in to change notification settings - Fork 226
/
SimpleTextureUWP12.cpp
503 lines (407 loc) · 17.3 KB
/
SimpleTextureUWP12.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
//--------------------------------------------------------------------------------------
// SimpleTextureUWP12.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "SimpleTextureUWP12.h"
#include "ATGColors.h"
#include "ReadData.h"
extern void ExitSample() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
struct Vertex
{
XMFLOAT4 position;
XMFLOAT2 texcoord;
};
std::vector<uint8_t> LoadBGRAImage(const wchar_t* filename, uint32_t& width, uint32_t& height)
{
ComPtr<IWICImagingFactory> wicFactory;
DX::ThrowIfFailed(CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wicFactory)));
ComPtr<IWICBitmapDecoder> decoder;
DX::ThrowIfFailed(wicFactory->CreateDecoderFromFilename(filename, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()));
ComPtr<IWICBitmapFrameDecode> frame;
DX::ThrowIfFailed(decoder->GetFrame(0, frame.GetAddressOf()));
DX::ThrowIfFailed(frame->GetSize(&width, &height));
WICPixelFormatGUID pixelFormat;
DX::ThrowIfFailed(frame->GetPixelFormat(&pixelFormat));
uint32_t rowPitch = width * sizeof(uint32_t);
uint32_t imageSize = rowPitch * height;
std::vector<uint8_t> image;
image.resize(size_t(imageSize));
if (memcmp(&pixelFormat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID)) == 0)
{
DX::ThrowIfFailed(frame->CopyPixels(nullptr, rowPitch, imageSize, reinterpret_cast<BYTE*>(image.data())));
}
else
{
ComPtr<IWICFormatConverter> formatConverter;
DX::ThrowIfFailed(wicFactory->CreateFormatConverter(formatConverter.GetAddressOf()));
BOOL canConvert = FALSE;
DX::ThrowIfFailed(formatConverter->CanConvert(pixelFormat, GUID_WICPixelFormat32bppBGRA, &canConvert));
if (!canConvert)
{
throw std::exception("CanConvert");
}
DX::ThrowIfFailed(formatConverter->Initialize(frame.Get(), GUID_WICPixelFormat32bppBGRA,
WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut));
DX::ThrowIfFailed(formatConverter->CopyPixels(nullptr, rowPitch, imageSize, reinterpret_cast<BYTE*>(image.data())));
}
return image;
}
}
Sample::Sample() noexcept(false)
{
// Use gamma-correct rendering.
m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB);
m_deviceResources->RegisterDeviceNotify(this);
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation)
{
m_gamePad = std::make_unique<GamePad>();
m_keyboard = std::make_unique<Keyboard>();
m_keyboard->SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window));
m_deviceResources->SetWindow(window, width, height, rotation);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
}
// Updates the world.
void Sample::Update(DX::StepTimer const&)
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update");
auto pad = m_gamePad->GetState(0);
if (pad.IsConnected())
{
if (pad.IsViewPressed())
{
ExitSample();
}
}
auto kb = m_keyboard->GetState();
if (kb.Escape)
{
ExitSample();
}
PIXEndEvent();
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Sample::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
// Prepare the command list to render a new frame.
m_deviceResources->Prepare();
Clear();
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Render");
commandList->SetGraphicsRootSignature(m_rootSignature.Get());
commandList->SetPipelineState(m_pipelineState.Get());
auto heap = m_srvHeap.Get();
commandList->SetDescriptorHeaps(1, &heap);
commandList->SetGraphicsRootDescriptorTable(0, m_srvHeap->GetGPUDescriptorHandleForHeapStart());
// Set necessary state.
commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
commandList->IASetVertexBuffers(0, 1, &m_vertexBufferView);
commandList->IASetIndexBuffer(&m_indexBufferView);
// Draw quad.
commandList->DrawIndexedInstanced(6, 1, 0, 0, 0);
PIXEndEvent(commandList);
// Show the new frame.
PIXBeginEvent(m_deviceResources->GetCommandQueue(), PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
m_graphicsMemory->Commit(m_deviceResources->GetCommandQueue());
PIXEndEvent(m_deviceResources->GetCommandQueue());
}
// Helper method to clear the back buffers.
void Sample::Clear()
{
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto dsvDescriptor = m_deviceResources->GetDepthStencilView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, &dsvDescriptor);
// Use linear clear color for gamma-correct rendering.
commandList->ClearRenderTargetView(rtvDescriptor, ATG::ColorsLinear::Background, 0, nullptr);
commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
PIXEndEvent(commandList);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnActivated()
{
}
void Sample::OnDeactivated()
{
}
void Sample::OnSuspending()
{
}
void Sample::OnResuming()
{
m_timer.ResetElapsedTime();
}
void Sample::OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation)
{
if (!m_deviceResources->WindowSizeChanged(width, height, rotation))
return;
CreateWindowSizeDependentResources();
}
void Sample::ValidateDevice()
{
m_deviceResources->ValidateDevice();
}
// Properties
void Sample::GetDefaultSize(int& width, int& height) const
{
width = 1280;
height = 720;
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Sample::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
m_graphicsMemory = std::make_unique<GraphicsMemory>(device);
// Create descriptor heaps.
{
// Describe and create a shader resource view (SRV) heap for the texture.
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = 1;
srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
DX::ThrowIfFailed(
device->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(m_srvHeap.ReleaseAndGetAddressOf())));
}
// Create a root signature with one sampler and one texture
{
CD3DX12_DESCRIPTOR_RANGE descRange = {};
descRange.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);
CD3DX12_ROOT_PARAMETER rp = {};
rp.InitAsDescriptorTable(1, &descRange, D3D12_SHADER_VISIBILITY_PIXEL);
// Use a static sampler that matches the defaults
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn913202(v=vs.85).aspx#static_sampler
D3D12_STATIC_SAMPLER_DESC samplerDesc = {};
samplerDesc.Filter = D3D12_FILTER_ANISOTROPIC;
samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
samplerDesc.MaxAnisotropy = 16;
samplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
samplerDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D12_FLOAT32_MAX;
samplerDesc.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc = {};
rootSignatureDesc.Init(1, &rp, 1, &samplerDesc,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT
| D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS
| D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS
| D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS);
ComPtr<ID3DBlob> signature;
ComPtr<ID3DBlob> error;
HRESULT hr = D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error);
if (FAILED(hr))
{
if (error)
{
OutputDebugStringA(reinterpret_cast<const char*>(error->GetBufferPointer()));
}
throw DX::com_exception(hr);
}
DX::ThrowIfFailed(
device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(),
IID_PPV_ARGS(m_rootSignature.ReleaseAndGetAddressOf())));
}
// Create the pipeline state, which includes loading shaders.
auto vertexShaderBlob = DX::ReadData(L"VertexShader.cso");
auto pixelShaderBlob = DX::ReadData(L"PixelShader.cso");
static const D3D12_INPUT_ELEMENT_DESC s_inputElementDesc[2] =
{
{ "SV_Position", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
// Describe and create the graphics pipeline state object (PSO).
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.InputLayout = { s_inputElementDesc, _countof(s_inputElementDesc) };
psoDesc.pRootSignature = m_rootSignature.Get();
psoDesc.VS = { vertexShaderBlob.data(), vertexShaderBlob.size() };
psoDesc.PS = { pixelShaderBlob.data(), pixelShaderBlob.size() };
psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState.DepthEnable = FALSE;
psoDesc.DepthStencilState.StencilEnable = FALSE;
psoDesc.DSVFormat = m_deviceResources->GetDepthBufferFormat();
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = m_deviceResources->GetBackBufferFormat();
psoDesc.SampleDesc.Count = 1;
DX::ThrowIfFailed(
device->CreateGraphicsPipelineState(&psoDesc,
IID_PPV_ARGS(m_pipelineState.ReleaseAndGetAddressOf())));
CD3DX12_HEAP_PROPERTIES heapUpload(D3D12_HEAP_TYPE_UPLOAD);
// Create vertex buffer.
{
static const Vertex s_vertexData[4] =
{
{ { -0.5f, -0.5f, 0.5f, 1.0f },{ 0.f, 1.f } },
{ { 0.5f, -0.5f, 0.5f, 1.0f },{ 1.f, 1.f } },
{ { 0.5f, 0.5f, 0.5f, 1.0f },{ 1.f, 0.f } },
{ { -0.5f, 0.5f, 0.5f, 1.0f },{ 0.f, 0.f } },
};
// Note: using upload heaps to transfer static data like vert buffers is not
// recommended. Every time the GPU needs it, the upload heap will be marshalled
// over. Please read up on Default Heap usage. An upload heap is used here for
// code simplicity and because there are very few verts to actually transfer.
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(s_vertexData));
DX::ThrowIfFailed(
device->CreateCommittedResource(&heapUpload,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(m_vertexBuffer.ReleaseAndGetAddressOf())));
// Copy the quad data to the vertex buffer.
UINT8* pVertexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
DX::ThrowIfFailed(
m_vertexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin)));
memcpy(pVertexDataBegin, s_vertexData, sizeof(s_vertexData));
m_vertexBuffer->Unmap(0, nullptr);
// Initialize the vertex buffer view.
m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress();
m_vertexBufferView.StrideInBytes = sizeof(Vertex);
m_vertexBufferView.SizeInBytes = sizeof(s_vertexData);
}
// Create index buffer.
{
static const uint16_t s_indexData[6] =
{
3,1,0,
2,1,3,
};
// See note above
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(s_indexData));
DX::ThrowIfFailed(
device->CreateCommittedResource(&heapUpload,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(m_indexBuffer.ReleaseAndGetAddressOf())));
// Copy the data to the index buffer.
UINT8* pVertexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
DX::ThrowIfFailed(
m_indexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin)));
memcpy(pVertexDataBegin, s_indexData, sizeof(s_indexData));
m_indexBuffer->Unmap(0, nullptr);
// Initialize the index buffer view.
m_indexBufferView.BufferLocation = m_indexBuffer->GetGPUVirtualAddress();
m_indexBufferView.Format = DXGI_FORMAT_R16_UINT;
m_indexBufferView.SizeInBytes = sizeof(s_indexData);
}
// Create texture.
auto commandList = m_deviceResources->GetCommandList();
commandList->Reset(m_deviceResources->GetCommandAllocator(), nullptr);
ComPtr<ID3D12Resource> textureUploadHeap;
{
D3D12_RESOURCE_DESC txtDesc = {};
txtDesc.MipLevels = txtDesc.DepthOrArraySize = 1;
txtDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; // sunset.jpg is in sRGB colorspace
txtDesc.SampleDesc.Count = 1;
txtDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
UINT width, height;
auto image = LoadBGRAImage(L"sunset.jpg", width, height);
txtDesc.Width = width;
txtDesc.Height = height;
CD3DX12_HEAP_PROPERTIES heapDefault(D3D12_HEAP_TYPE_DEFAULT);
DX::ThrowIfFailed(
device->CreateCommittedResource(
&heapDefault,
D3D12_HEAP_FLAG_NONE,
&txtDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS(m_texture.ReleaseAndGetAddressOf())));
const UINT64 uploadBufferSize = GetRequiredIntermediateSize(m_texture.Get(), 0, 1);
// Create the GPU upload buffer.
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(uploadBufferSize);
DX::ThrowIfFailed(
device->CreateCommittedResource(
&heapUpload,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(textureUploadHeap.GetAddressOf())));
D3D12_SUBRESOURCE_DATA textureData = {};
textureData.pData = image.data();
textureData.RowPitch = static_cast<LONG_PTR>(txtDesc.Width * sizeof(uint32_t));
textureData.SlicePitch = image.size();
UpdateSubresources(commandList, m_texture.Get(), textureUploadHeap.Get(), 0, 0, 1, &textureData);
auto barrier = CD3DX12_RESOURCE_BARRIER::Transition(m_texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
commandList->ResourceBarrier(1, &barrier);
// Describe and create a SRV for the texture.
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.Format = txtDesc.Format;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
device->CreateShaderResourceView(m_texture.Get(), &srvDesc, m_srvHeap->GetCPUDescriptorHandleForHeapStart());
}
DX::ThrowIfFailed(commandList->Close());
m_deviceResources->GetCommandQueue()->ExecuteCommandLists(1, CommandListCast(&commandList));
// Wait until assets have been uploaded to the GPU.
m_deviceResources->WaitForGpu();
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
}
void Sample::OnDeviceLost()
{
m_texture.Reset();
m_indexBuffer.Reset();
m_vertexBuffer.Reset();
m_pipelineState.Reset();
m_rootSignature.Reset();
m_srvHeap.Reset();
m_graphicsMemory.reset();
}
void Sample::OnDeviceRestored()
{
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
#pragma endregion