-
Notifications
You must be signed in to change notification settings - Fork 226
/
SimpleESRAM.cpp
1250 lines (1038 loc) · 47.9 KB
/
SimpleESRAM.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//--------------------------------------------------------------------------------------
// SimpleESRAM.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "SimpleESRAM.h"
#include "PIXHelpers.h"
#include "ATGColors.h"
#include "ControllerFont.h"
extern void ExitSample() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
//--------------------------------------
// Definitions
// Barebones definition of scene objects.
struct ObjectDefinition
{
size_t modelIndex;
SimpleMath::Matrix world;
};
//--------------------------------------
// Constants
const float c_defaultPhi = XM_2PI / 6.0f;
const float c_defaultRadius = 3.3f;
// Assest paths.
const wchar_t* s_modelPaths[] =
{
L"scanner.sdkmesh",
L"occcity.sdkmesh",
L"column.sdkmesh",
};
// Barebones definition of a scene.
const ObjectDefinition s_sceneDefinition[] =
{
{ 0, XMMatrixIdentity() },
{ 0, XMMatrixRotationY(XM_2PI * (1.0f / 6.0f)) },
{ 0, XMMatrixRotationY(XM_2PI * (2.0f / 6.0f)) },
{ 0, XMMatrixRotationY(XM_2PI * (3.0f / 6.0f)) },
{ 0, XMMatrixRotationY(XM_2PI * (4.0f / 6.0f)) },
{ 0, XMMatrixRotationY(XM_2PI * (5.0f / 6.0f)) },
{ 1, XMMatrixIdentity() },
{ 2, XMMatrixIdentity() },
};
// Full screen triangle geometry definition.
std::vector<GeometricPrimitive::VertexType> s_triVertex =
{
{ XMFLOAT3{ -1.0f, 1.0f, 0.0f }, XMFLOAT3{ 0.0f, 0.0f, -1.0f }, XMFLOAT2{ 0.0f, 0.0f } }, // Top-left
{ XMFLOAT3{ 3.0f, 1.0f, 0.0f }, XMFLOAT3{ 0.0f, 0.0f, -1.0f }, XMFLOAT2{ 0.0f, 2.0f } }, // Top-right
{ XMFLOAT3{ -1.0f, -3.0f, 0.0f }, XMFLOAT3{ 0.0f, 0.0f, -1.0f }, XMFLOAT2{ 2.0f, 0.0f } }, // Bottom-left
};
std::vector<uint16_t> s_triIndex = { 0, 1, 2 };
const DXGI_FORMAT c_colorFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
const XG_FORMAT c_colorXGFormat = XG_FORMAT_R8G8B8A8_UNORM;
const DXGI_FORMAT c_depthFormat = DXGI_FORMAT_D32_FLOAT;
const XG_FORMAT c_depthXGFormat = XG_FORMAT_D32_FLOAT;
const int c_esramPageCount = 512;
const int c_pageSize = 64 * 1024;
const int c_esramTexWidth = 4096;
const int c_esramTexHeight = 2048;
//--------------------------------------
// Helper Functions
template <typename T>
constexpr T DivRoundUp(T num, T denom)
{
return (num + denom - 1) / denom;
}
template <typename T>
constexpr T PageCount(T byteSize)
{
return DivRoundUp(byteSize, T(c_pageSize));
}
template <typename T, typename U, typename V>
constexpr T Clamp(T value, U min, V max)
{
return (value < min) ? min : ((value > max) ? max : value);
}
constexpr float Saturate(float value)
{
return Clamp(value, 0.0f, 1.0f);
}
bool IsMetadataPlane(const XG_PLANE_LAYOUT& layout)
{
return layout.Usage == XG_PLANE_USAGE_COLOR_MASK
|| layout.Usage == XG_PLANE_USAGE_FRAGMENT_MASK
|| layout.Usage == XG_PLANE_USAGE_HTILE
#if _XDK_VER >= 0x3F6803F3 /* XDK Edition 170600 */
|| layout.Usage == XG_PLANE_USAGE_DELTA_COLOR_COMPRESSION
#endif
;
}
void FillLayoutDesc(XG_RESOURCE_LAYOUT layout, MetadataDesc& desc)
{
desc.count = 0;
// Iterate through the resource planes and find the page ranges that contain resource metadata.
for (unsigned i = 0; i < layout.Planes; ++i)
{
auto& plane = layout.Plane[i];
// Only process metadata planes.
if (IsMetadataPlane(plane))
{
int startPage = int(plane.BaseOffsetBytes / c_pageSize);
int endPage = int((plane.BaseOffsetBytes + plane.SizeBytes) / c_pageSize);
if (desc.count > 0 && startPage == desc.ranges[desc.count - 1].End() - 1)
{
// Merge the ranges if the current page range is adjacent to the previous one.
desc.ranges[desc.count - 1].count += endPage - startPage;
}
else
{
// Add a new range since it's disjoint from the previous one.
desc.ranges[desc.count++] = { startPage, endPage - startPage + 1 };
}
}
}
}
// Xbox One X doesn't have ESRAM, and attempted ESRAM allocations will throw an error.
bool SupportsESRAM()
{
#if _XDK_VER >= 0x3F6803F3 /* XDK Edition 170600 */
return GetConsoleType() <= CONSOLE_TYPE::CONSOLE_TYPE_XBOX_ONE_S;
#else
return true;
#endif
}
// Creates a D3D11 resource by either ID3D11DeviceX::CreatePlacedResourceX(...), if a virtual
// address is supplied, or ID3D11DeviceX::CreateCommittedResource(...) using the supplied descriptor.
void CreateResource(
_In_ ID3D11DeviceX* device,
const D3D11_TEXTURE2D_DESC& desc,
UINT tileModeIndex,
_In_opt_ const XG_GPU_VIRTUAL_ADDRESS* placementAddress,
_In_opt_ const wchar_t* name,
_Outptr_ ID3D11Texture2D** outResource)
{
assert(device != nullptr);
if (placementAddress == nullptr)
{
device->CreateTexture2D(&desc, nullptr, outResource);
}
else
{
device->CreatePlacementTexture2D(&desc, tileModeIndex, 0, (void*)*placementAddress, outResource);
}
if (name != nullptr)
{
assert(outResource != nullptr);
(*outResource)->SetName(name);
}
}
// Creates a color D3D11 texture 2D and render target view for that resource.
void CreateColorResourceAndView(
_In_ ID3D11DeviceX* device,
const D3D11_TEXTURE2D_DESC& desc,
_In_opt_ const XG_GPU_VIRTUAL_ADDRESS* placementAddress,
_In_opt_ const wchar_t* name,
_Outptr_ ID3D11Texture2D** outResource,
_Outptr_ ID3D11RenderTargetView** outView)
{
assert(device != nullptr);
if (outResource == nullptr)
{
return;
}
XG_TILE_MODE colorTileMode = XGComputeOptimalTileMode(
XG_RESOURCE_DIMENSION_TEXTURE2D,
XG_FORMAT(desc.Format),
UINT(desc.Width),
desc.Height,
desc.ArraySize,
desc.SampleDesc.Count,
XG_BIND_RENDER_TARGET);
CreateResource(device, desc, colorTileMode, placementAddress, name, outResource);
D3D11_RTV_DIMENSION dim = desc.SampleDesc.Count == 1 ? D3D11_RTV_DIMENSION_TEXTURE2D : D3D11_RTV_DIMENSION_TEXTURE2DMS;
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc =
{
desc.Format, // DXGI_FORMAT Format;
dim, // D3D11_RTV_DIMENSION ViewDimension;
{ // D3D11_TEX2DMS_RTV Texture2D;
0, // UINT UnusedField_NothingToDefine;
},
};
device->CreateRenderTargetView(*outResource, &rtvDesc, outView);
}
// Creates a depth D3D11 texture 2D and depth stencil view for that resource.
void CreateDepthResourceAndView(
_In_ ID3D11DeviceX* device,
const D3D11_TEXTURE2D_DESC& desc,
_In_opt_ const XG_GPU_VIRTUAL_ADDRESS* placementAddress,
_In_opt_ const wchar_t* name,
_Outptr_ ID3D11Texture2D** outResource,
_Outptr_ ID3D11DepthStencilView** outView)
{
assert(device != nullptr);
if (outResource == nullptr)
{
return;
}
XG_TILE_MODE depthTileMode;
XG_TILE_MODE stencilTileMode;
#if _XDK_VER >= 0x3F6803F3 /* XDK Edition 170600 */
XGComputeOptimalDepthStencilTileModes(
XG_FORMAT(desc.Format),
UINT32(desc.Width),
desc.Height,
desc.ArraySize,
desc.SampleDesc.Count,
(desc.MiscFlags & D3D11X_RESOURCE_MISC_NO_DEPTH_COMPRESSION) == 0,
FALSE,
FALSE,
&depthTileMode,
&stencilTileMode);
#else
XGComputeOptimalDepthStencilTileModes(
XG_FORMAT(desc.Format),
UINT32(desc.Width),
desc.Height,
desc.ArraySize,
desc.SampleDesc.Count,
TRUE,
&depthTileMode,
&stencilTileMode);
#endif
CreateResource(device, desc, depthTileMode, placementAddress, name, outResource);
D3D11_DSV_DIMENSION dim = desc.SampleDesc.Count == 1 ? D3D11_DSV_DIMENSION_TEXTURE2D : D3D11_DSV_DIMENSION_TEXTURE2DMS;
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc =
{
desc.Format, // DXGI_FORMAT Format;
dim, // D3D11_DSV_DIMENSION ViewDimension;
0, // UINT Flags
{ // D3D11_TEX2DMS_DSV Texture2D;
0, // UINT UnusedField_NothingToDefine;
},
};
device->CreateDepthStencilView(*outResource, &dsvDesc, outView);
}
// Computes the optimal tile mode and calculates the number of 64 KiB pages necessary for the resource.
// Optionally computes the ranges of 64KiB pages the resource metadata consumes if present.
int CalculatePagesForColorResource(D3D11_TEXTURE2D_DESC& desc, XG_FORMAT colorFormat, MetadataDesc* layoutDesc = nullptr)
{
// Determine the size and alignment for resource
XG_TILE_MODE colorTileMode = XGComputeOptimalTileMode(
XG_RESOURCE_DIMENSION_TEXTURE2D,
colorFormat,
UINT(desc.Width),
desc.Height,
desc.ArraySize,
desc.SampleDesc.Count,
XG_BIND_RENDER_TARGET);
struct XG_TEXTURE2D_DESC xgDesc =
{
desc.Width, // UINT Width;
desc.Height, // UINT Height;
desc.MipLevels, // UINT MipLevels;
desc.ArraySize, // UINT ArraySize;
colorFormat, // XG_FORMAT Format;
{ // XG_SAMPLE_DESC SampleDesc;
desc.SampleDesc.Count, // UINT Count;
desc.SampleDesc.Quality, // UINT Quality;
},
XG_USAGE(desc.Usage), // XG_USAGE Usage;
desc.BindFlags, // UINT BindFlags;
desc.CPUAccessFlags, // UINT CPUAccessFlags;
desc.MiscFlags, // UINT MiscFlags;
0, // UINT ESRAMOffsetBytes;
0, // UINT ESRAMUsageBytes;
colorTileMode, // XG_TILE_MODE TileMode;
0, // UINT Pitch;
};
ComPtr<XGTextureAddressComputer> computer;
DX::ThrowIfFailed(XGCreateTexture2DComputer(&xgDesc, computer.GetAddressOf()));
XG_RESOURCE_LAYOUT layout;
DX::ThrowIfFailed(computer->GetResourceLayout(&layout));
if (layoutDesc != nullptr)
{
FillLayoutDesc(layout, *layoutDesc);
}
return (int)PageCount(layout.SizeBytes);
}
// Computes the optimal tile mode and calculates the number of 64 KiB pages necessary for the resource.
// Optionally computes the ranges of 64KiB pages the resource metadata consumes if present.
int CalculatePagesForDepthResource(D3D11_TEXTURE2D_DESC& desc, XG_FORMAT depthFormat, MetadataDesc* layoutDesc = nullptr)
{
XG_TILE_MODE depthTileMode;
XG_TILE_MODE stencilTileMode;
#if _XDK_VER >= 0x3F6803F3 /* XDK Edition 170600 */
XGComputeOptimalDepthStencilTileModes(
depthFormat,
UINT32(desc.Width),
desc.Height,
desc.ArraySize,
desc.SampleDesc.Count,
(desc.MiscFlags & D3D11X_RESOURCE_MISC_NO_DEPTH_COMPRESSION) == 0,
FALSE,
FALSE,
&depthTileMode,
&stencilTileMode);
#else
XGComputeOptimalDepthStencilTileModes(
depthFormat,
UINT32(desc.Width),
desc.Height,
desc.ArraySize,
desc.SampleDesc.Count,
TRUE,
&depthTileMode,
&stencilTileMode);
#endif
struct XG_TEXTURE2D_DESC xgDesc =
{
desc.Width, // UINT Width;
desc.Height, // UINT Height;
desc.MipLevels, // UINT MipLevels;
desc.ArraySize, // UINT ArraySize;
depthFormat, // XG_FORMAT Format;
{ // XG_SAMPLE_DESC SampleDesc;
desc.SampleDesc.Count, // UINT Count;
desc.SampleDesc.Quality, // UINT Quality;
},
XG_USAGE(desc.Usage), // XG_USAGE Usage;
desc.BindFlags, // UINT BindFlags;
desc.CPUAccessFlags, // UINT CPUAccessFlags;
desc.MiscFlags, // UINT MiscFlags;
0, // UINT ESRAMOffsetBytes;
0, // UINT ESRAMUsageBytes;
depthTileMode, // XG_TILE_MODE TileMode;
0, // UINT Pitch;
};
ComPtr<XGTextureAddressComputer> computer;
DX::ThrowIfFailed(XGCreateTexture2DComputer(&xgDesc, computer.GetAddressOf()));
XG_RESOURCE_LAYOUT layout;
DX::ThrowIfFailed(computer->GetResourceLayout(&layout));
if (layoutDesc != nullptr)
{
FillLayoutDesc(layout, *layoutDesc);
}
return (int)PageCount(layout.SizeBytes);
}
}
Sample::Sample()
: m_displayWidth(0)
, m_displayHeight(0)
, m_frame(0)
, m_theta(0.f)
, m_phi(c_defaultPhi)
, m_radius(c_defaultRadius)
, m_generator(std::random_device()())
, m_showOverlay(SupportsESRAM())
, m_mapScheme(SupportsESRAM() ? EMS_Simple : EMS_None)
, m_colorDesc{}
, m_depthDesc{}
, m_esramOverlayDesc{}
{
m_deviceResources = std::make_unique<DX::DeviceResources>(c_colorFormat, DXGI_FORMAT_UNKNOWN);
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(IUnknown* window)
{
m_deviceResources->SetWindow(window);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %llu", m_frame);
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
PIXEndEvent();
m_frame++;
}
void Sample::Update(const DX::StepTimer& timer)
{
using ButtonState = DirectX::GamePad::ButtonStateTracker::ButtonState;
ScopedPixEvent Update(PIX_COLOR_DEFAULT, L"Update");
float elapsedTime = float(timer.GetElapsedSeconds());
auto pad = m_gamePad.GetState(0);
if (pad.IsConnected())
{
m_gamePadButtons.Update(pad);
if (pad.IsViewPressed())
{
ExitSample();
}
bool recreateResources = false;
if (SupportsESRAM())
{
if (m_gamePadButtons.dpadLeft == ButtonState::RELEASED)
{
m_mapScheme = EsramMappingScheme((m_mapScheme == 0 ? EMS_Count : m_mapScheme) - 1);
recreateResources = true;
}
else if (m_gamePadButtons.dpadRight == ButtonState::RELEASED)
{
m_mapScheme = EsramMappingScheme((m_mapScheme + 1) % EMS_Count);
recreateResources = true;
}
if (m_gamePadButtons.a == ButtonState::RELEASED)
{
m_showOverlay = !m_showOverlay;
}
}
const float splitSpeed = 0.2f * elapsedTime;
switch (m_mapScheme)
{
case EMS_Simple:
if (pad.IsLeftShoulderPressed())
{
int maxPageCount = std::min(m_colorPageCount, c_esramPageCount);
m_colorEsramPageCount = std::min(m_colorEsramPageCount + 1, maxPageCount);
m_depthEsramPageCount = std::min(m_depthEsramPageCount, c_esramPageCount - m_colorEsramPageCount);
recreateResources = true;
}
if (pad.IsLeftTriggerPressed())
{
m_colorEsramPageCount = std::max(m_colorEsramPageCount - 1, 0);
recreateResources = true;
}
if (pad.IsRightShoulderPressed())
{
int maxPageCount = std::min(m_depthPageCount, c_esramPageCount);
m_depthEsramPageCount = std::min(m_depthEsramPageCount + 1, maxPageCount);
m_colorEsramPageCount = std::min(m_colorEsramPageCount, c_esramPageCount - m_depthEsramPageCount);
recreateResources = true;
}
if (pad.IsRightTriggerPressed())
{
m_depthEsramPageCount = std::max(m_depthEsramPageCount - 1, 0);
recreateResources = true;
}
break;
case EMS_Split:
if (pad.IsLeftShoulderPressed())
{
m_bottomPercent = std::min(m_bottomPercent + splitSpeed, m_topPercent);
recreateResources = true;
}
if (pad.IsLeftTriggerPressed())
{
m_bottomPercent = std::max(m_bottomPercent - splitSpeed, 0.0f);
recreateResources = true;
}
if (pad.IsRightShoulderPressed())
{
m_topPercent = std::min(m_topPercent + splitSpeed, 1.0f);
recreateResources = true;
}
if (pad.IsRightTriggerPressed())
{
m_topPercent = std::max(m_topPercent - splitSpeed, m_bottomPercent);
recreateResources = true;
}
break;
case EMS_Metadata:
if (m_gamePadButtons.b == ButtonState::RELEASED)
{
m_metadataEnabled = !m_metadataEnabled;
recreateResources = true;
}
break;
case EMS_Random:
if (m_gamePadButtons.leftShoulder == ButtonState::RELEASED)
{
m_esramProbability = std::max(m_esramProbability - 0.1f, 0.0f); // Decrease by 10% per press.
recreateResources = true;
}
if (m_gamePadButtons.rightShoulder == ButtonState::RELEASED)
{
m_esramProbability = std::min(m_esramProbability + 0.1f, 1.0f); // Increase by 10% per press.
recreateResources = true;
}
break;
}
if (recreateResources)
{
UpdateResourceMappings();
}
if (pad.IsRightStickPressed())
{
m_theta = 0.f;
m_phi = c_defaultPhi;
m_radius = c_defaultRadius;
}
else
{
m_theta += pad.thumbSticks.rightX * XM_PI * elapsedTime;
m_phi -= pad.thumbSticks.rightY * XM_PI * elapsedTime;
m_radius -= pad.thumbSticks.leftY * 5.f * elapsedTime;
}
}
else
{
m_gamePadButtons.Reset();
}
// Limit to avoid looking directly up or down
m_phi = std::max(1e-2f, std::min(XM_PIDIV2, m_phi));
m_radius = std::max(1.f, std::min(10.f, m_radius));
if (m_theta > XM_PI)
{
m_theta -= XM_PI * 2.f;
}
else if (m_theta < -XM_PI)
{
m_theta += XM_PI * 2.f;
}
XMVECTOR lookFrom = XMVectorSet(
m_radius * sinf(m_phi) * cosf(m_theta),
m_radius * cosf(m_phi),
m_radius * sinf(m_phi) * sinf(m_theta),
0);
m_view = XMMatrixLookAtLH(lookFrom, g_XMZero, g_XMIdentityR1);
}
#pragma endregion
#pragma region Frame Render
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();
auto context = m_deviceResources->GetD3DDeviceContext();
// Begin frame
m_profiler->BeginFrame(context);
m_profiler->Start(context);
// Set descriptor heaps
{
ScopedPixEvent Update(context, PIX_COLOR_DEFAULT, L"Clear");
ID3D11RenderTargetView* rtvs[] = { m_colorRTV.Get() };
context->OMSetRenderTargets(1, rtvs, m_depthDSV.Get());
auto viewport = m_deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
// Perform a manual full screen clear operation.
// NOTE: The ClearRenderTargetView() call on a compressed render target defers the clear to a barrier
// transition. Since we are "tinting" the color buffer via the ESRAM overlay before the ResourceBarrier
// transition this produces the wrong result.
// An alternative workaround is to simply use D3D11X_RESOURCE_MISC_NO_COLOR_COMPRESSION & D3D11X_RESOURCE_MISC_NO_COLOR_EXPAND when creating
// the aliased buffer. Of course, this disables potential optimizations created by that compression data.
if (SupportsESRAM())
{
m_manualClearEffect->Apply(context);
m_fullScreenTri->Draw(m_manualClearEffect.get(), m_inputLayout.Get());
}
else
{
context->ClearRenderTargetView(m_colorRTV.Get(), ATG::ColorsLinear::Background);
}
context->ClearDepthStencilView(m_depthDSV.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
}
{
ScopedPixEvent Render(context, PIX_COLOR_DEFAULT, L"Render");
{
ScopedPixEvent Scene(context, PIX_COLOR_DEFAULT, L"Scene");
// Draw the scene.
for (auto& obj : m_scene)
{
obj.model->Draw(context, *m_commonStates, obj.world, m_view, m_proj);
}
}
// Visualize ESRAM by performing a full screen draw on a render target that covers
// the entirety of ESRAM with alpha blending. This thrashes all non-color targets
// residing in ESRAM (including compression textures.)
if (m_showOverlay)
{
ScopedPixEvent VisEsram(context, PIX_COLOR_DEFAULT, L"Visualize ESRAM");
ID3D11RenderTargetView* rtvs[] = { m_esramOverlayRTV.Get() };
context->OMSetRenderTargets(1, rtvs, nullptr);
auto viewport = CD3D11_VIEWPORT(0.0f, 0.0f, float(c_esramTexWidth), float(c_esramTexHeight));
context->RSSetViewports(1, &viewport);
m_esramBlendEffect->Apply(context);
m_fullScreenTri->Draw(m_esramBlendEffect.get(), m_inputLayout.Get(), true);
}
// Only profile pertinent ESRAM resource usage.
m_profiler->Stop(context);
m_profiler->EndFrame(context);
// Since our render target is a 2xMSAA target this ResolveSubresource(...) call is required on all platforms.
// However be wary about lingering copies from ESRAM to DRAM when porting to Xbox One X. On the One X all
// resources are in DRAM, so these seemingly innocuous and routine copies may ultimately be a non-trivial
// waste of GPU bandwidth and copy fences.
{
ScopedPixEvent Resolve(context, PIX_COLOR_DEFAULT, L"Resolve");
context->ResolveSubresource(m_deviceResources->GetRenderTarget(), 0, m_colorTexture.Get(), 0, c_colorFormat);
}
// Draw the HUD.
{
ScopedPixEvent HUD(context, PIX_COLOR_DEFAULT, L"HUD");
ID3D11RenderTargetView* rtvs[] = { m_deviceResources->GetRenderTargetView() };
context->OMSetRenderTargets(1, rtvs, nullptr);
auto viewport = m_deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
m_hudBatch->Begin();
auto size = m_deviceResources->GetOutputSize();
auto safe = SimpleMath::Viewport::ComputeTitleSafeArea(size.right, size.bottom);
wchar_t textBuffer[128] = {};
XMFLOAT2 textPos = XMFLOAT2(float(safe.left), float(safe.left));
XMVECTOR textColor = Colors::DarkKhaki;
// Draw title.
m_smallFont->DrawString(m_hudBatch.get(), L"Simple ESRAM", textPos, textColor);
textPos.y += m_smallFont->GetLineSpacing();
// Draw ESRAM usage.
const wchar_t* titleText = nullptr;
switch (m_mapScheme)
{
case EMS_None:
titleText = L"DRAM Mapping";
textBuffer[0] = '\0';
break;
case EMS_Simple:
titleText = L"Simple Mapping";
_snwprintf_s(textBuffer, _TRUNCATE, L"ESRAM Page Count: Color = %d, Depth = %d", m_colorEsramPageCount, m_depthEsramPageCount);
break;
case EMS_Split:
titleText = L"Split Mapping";
_snwprintf_s(textBuffer, _TRUNCATE, L"Bottom Percent = %0.2f%%, Top Percent %0.2f%%", m_bottomPercent * 100.0f, m_topPercent * 100.0f);
break;
case EMS_Metadata:
titleText = L"Metadata Mapping";
_snwprintf_s(textBuffer, _TRUNCATE, L"Metadata Mapping: %s", m_metadataEnabled ? L"Enabled" : L"Disabled");
break;
case EMS_Random:
titleText = L"Random Mapping";
_snwprintf_s(textBuffer, _TRUNCATE, L"Probability = %0.2f%%", m_esramProbability * 100.0f);
break;
}
m_smallFont->DrawString(m_hudBatch.get(), titleText, textPos, textColor);
textPos.y += m_smallFont->GetLineSpacing();
m_smallFont->DrawString(m_hudBatch.get(), textBuffer, textPos, textColor);
textPos.y += m_smallFont->GetLineSpacing();
// Draw Frame Stats
_snwprintf_s(textBuffer, _TRUNCATE, L"GPU time = %3.3lf ms", m_profiler->GetAverageMS());
m_smallFont->DrawString(m_hudBatch.get(), textBuffer, textPos, textColor);
// Draw Controllers
textPos.y = float(safe.bottom) - 2.0f * m_smallFont->GetLineSpacing();
const wchar_t* commonCtrl = nullptr;
if (SupportsESRAM())
{
commonCtrl = L"[LThumb] Toward/Away [RThumb]: Orbit Camera [DPad] Switch Mapping Schemes [A] Toggle Overlay [View] Exit ";
}
else
{
commonCtrl = L"[LThumb] Toward/Away [RThumb]: Orbit Camera [View] Exit ";
}
DX::DrawControllerString(m_hudBatch.get(), m_smallFont.get(), m_ctrlFont.get(), commonCtrl, textPos, textColor);
textPos.y += m_smallFont->GetLineSpacing();
const wchar_t* controlLUT[] =
{
// None
L"\0",
// Simple
L"[LB]/[LT] Increase/Decrease Color ESRAM Page Count [RB]/[RT] Increase/Decrease Depth ESRAM Page Count",
// Split
L"[LB]/[LT] Increase/Decrease ESRAM Begin Address [RB]/[RT] Increase/Decrease ESRAM End Address",
// Metadata
L"[B] Toggle Metadata ESRAM Mapping",
// Random
L"[LB]/[RB] Decrease/Increase ESRAM Page Probability"
};
DX::DrawControllerString(m_hudBatch.get(), m_smallFont.get(), m_ctrlFont.get(), controlLUT[m_mapScheme], textPos, textColor);
m_hudBatch->End();
}
}
// Show the new frame.
{
ScopedPixEvent(context, PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
m_graphicsMemory->Commit();
}
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnSuspending()
{
auto context = m_deviceResources->GetD3DDeviceContext();
context->Suspend(0);
}
void Sample::OnResuming()
{
auto context = m_deviceResources->GetD3DDeviceContext();
context->Resume();
m_timer.ResetElapsedTime();
m_gamePadButtons.Reset();
}
#pragma endregion
#pragma region Direct3D Resources
void Sample::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
auto context = m_deviceResources->GetD3DDeviceContext();
m_profiler = std::make_unique<DX::GPUTimer>(device);
m_graphicsMemory = std::make_unique<GraphicsMemory>(device, m_deviceResources->GetBackBufferCount());
m_commonStates = std::make_unique<DirectX::CommonStates>(device);
m_effectFactory = std::make_unique<DirectX::EffectFactory>(device);
// Load models from disk.
m_models.resize(_countof(s_modelPaths));
for (int i = 0; i < m_models.size(); ++i)
{
m_models[i] = Model::CreateFromSDKMESH(device, s_modelPaths[i], *m_effectFactory, ModelLoader_CounterClockwise);
}
// HUD
m_hudBatch = std::make_unique<SpriteBatch>(context);
//-------------------------------------------------------
// Instantiate objects from basic scene definition.
m_scene.resize(_countof(s_sceneDefinition));
for (int i = 0; i < m_scene.size(); i++)
{
size_t index = s_sceneDefinition[i].modelIndex;
assert(index < m_models.size());
auto& model = *m_models[index];
m_scene[i].world = s_sceneDefinition[i].world;
m_scene[i].model = &model;
model.UpdateEffects([&](IEffect* e)
{
static_cast<BasicEffect*>(e)->SetEmissiveColor(XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f));
});
}
//----------------------------------------
// Create post process effects.
// Create a full-screen triangle for full buffer pixel shader operations.
m_fullScreenTri = GeometricPrimitive::CreateCustom(context, s_triVertex, s_triIndex);
// Manual full screen clear - required to properly clear ESRAM-overlayed, compressed MSAA target
m_manualClearEffect = std::make_unique<BasicEffect>(device);
m_manualClearEffect->SetDiffuseColor(XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f)); // Disable lighting
m_manualClearEffect->SetEmissiveColor(ATG::ColorsLinear::Background); // Set emissive
// ESRAM color blend operation - Manipulate BasicEffect shader's math to perform direct, single-color blend.
m_esramBlendEffect = std::make_unique<BasicEffect>(device);
m_esramBlendEffect->SetDiffuseColor(XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f)); // Disable lighting
m_esramBlendEffect->SetEmissiveColor(XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)); // Set emissive & alpha (direct color & alpha blend)
m_esramBlendEffect->SetAlpha(0.25f);
m_fullScreenTri->CreateInputLayout(m_manualClearEffect.get(), &m_inputLayout);
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
const auto size = m_deviceResources->GetOutputSize();
// Calculate display dimensions.
m_displayWidth = size.right - size.left;
m_displayHeight = size.bottom - size.top;
// Set hud sprite viewport
m_hudBatch->SetViewport(m_deviceResources->GetScreenViewport());
// Set camera parameters.
m_proj = XMMatrixPerspectiveFovLH(XM_PIDIV4, float(m_displayWidth) / float(m_displayHeight), 0.1f, 500.0f);
// Begin uploading texture resources
m_smallFont = std::make_unique<SpriteFont>(device, L"SegoeUI_18.spritefont");
m_ctrlFont = std::make_unique<SpriteFont>(device, L"XboxOneControllerLegendSmall.spritefont");
//------------------------------------------------
// Step One:
// Create the resource descriptors as usual.
// DRAM color target - ensure aligned to ESRAM page boundary.
m_colorDesc = CD3D11_TEXTURE2D_DESC(
c_colorFormat, // DXGI_FORMAT Format;
UINT(m_displayWidth), // UINT width;
UINT(m_displayHeight), // UINT height;
1, // UINT arraySize;
1, // UINT mipLevels;
D3D11_BIND_RENDER_TARGET, // UINT bindFlags;
D3D11_USAGE_DEFAULT, // D3D11_USAGE usage;
0, // UINT cpuaccessFlags;
2, // UINT sampleCount;
0, // UINT sampleQuality;
0, // UINT miscFlags;
0, // UINT esramOffsetBytes;
0 // UINT esramUsageBytes;
);
// DRAM depth target - ensure aligned to ESRAM page boundary.
m_depthDesc = CD3D11_TEXTURE2D_DESC(
c_depthFormat, // DXGI_FORMAT Format;
UINT(m_displayWidth), // UINT width;
UINT(m_displayHeight), // UINT height;
1, // UINT arraySize;
1, // UINT mipLevels;
D3D11_BIND_DEPTH_STENCIL, // UINT bindFlags;
D3D11_USAGE_DEFAULT, // D3D11_USAGE usage;
0, // UINT cpuaccessFlags;
2, // UINT sampleCount;
0, // UINT sampleQuality;
0, // UINT miscFlags;
0, // UINT esramOffsetBytes;
0 // UINT esramUsageBytes;
);
// Create a resource descriptor that fills all 32 MB of ESRAM.
m_esramOverlayDesc = CD3D11_TEXTURE2D_DESC(
c_colorFormat, // DXGI_FORMAT Format;
c_esramTexWidth, // UINT width;
c_esramTexHeight, // UINT height;
1, // UINT arraySize;
1, // UINT mipLevels;
D3D11_BIND_RENDER_TARGET // UINT bindFlags;
);
//-----------------------------------------------------------------------------------------------
// Step Two:
// Calculate resource page counts via the resource descriptors and XG library functions.
// Calculate total number of pages for the offscreen color & depth buffers for their respective format/dimensions/layout.
m_colorPageCount = CalculatePagesForColorResource(m_colorDesc, c_colorXGFormat, &m_colorLayoutDesc);
m_depthPageCount = CalculatePagesForDepthResource(m_depthDesc, c_depthXGFormat, &m_depthLayoutDesc);
m_esramOverlayPageCount = CalculatePagesForColorResource(m_esramOverlayDesc, c_colorXGFormat);
// Determine initial number of pages to map to ESRAM - map all of color, then map depth to remaining pages.
m_colorEsramPageCount = std::min(m_colorPageCount, c_esramPageCount);
m_depthEsramPageCount = std::min(m_depthPageCount, c_esramPageCount - m_colorEsramPageCount);
// Initialize the XGMemoryEngine with maximum page counts.
// Note that even on Durango we allocate enough system pages to hold our color & depth targets,
// since the sample's parameterized mapping schemes allow targets to be pushed completely to DRAM.
UINT32 numEsramPages = SupportsESRAM() ? c_esramPageCount : 0;
UINT32 numSystemPages = UINT32(m_colorPageCount + m_depthPageCount);
DX::ThrowIfFailed(m_layoutEngine.InitializeWithPageCounts(numSystemPages, numEsramPages, 0));
// Step Three & Four (inside): Create the resources using the current mapping scheme.
UpdateResourceMappings();
}
void Sample::UpdateResourceMappings()
{
//----------------------------------------------------------------------
// Step Three:
// Create the memory mapping using the XGMemory library.
//
// The XGMemoryLayoutEngine is simply used to create XGMemoryLayouts, intiailized with page counts using
// InitializeWithPageCounts() or InitializeWithPageArrays(). Multiple XGMemoryLayoutEngines can be used with