Repository navigation
Expand file tree
/
Copy pathtitle_device.cpp
More file actions
3592 lines (3553 loc) · 204 KB
/
Copy pathtitle_device.cpp
File metadata and controls
3592 lines (3553 loc) · 204 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
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
#include "radeon_device.h"
#include "constant_buffer.h"
#include "depth16.h"
#include "desktop_present.h"
#include "dxr_device.h"
#include "frame_timing.h"
#include "gdk_command_memory.h"
#include "mip_compute.h"
#include "monitored_fence.h"
#include "placed_buffer.h"
#include "placed_surface.h"
#include "placed_texture.h"
#include "render_target_encoder.h"
#include "startup_draw.h"
#include "title_device_abi.h"
#include "title_memory.h"
#include "scarlett_raw_srv.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <bitset>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <new>
#include <numeric>
#include <optional>
#include <set>
#include <type_traits>
#include <tuple>
#include <utility>
#include <variant>
#include <vector>
namespace {
using namespace title_d3d;
using Microsoft::WRL::ComPtr;
using Method = void (WINAPI*)();
struct GraphicsObject {
const Method* methods{};
LONG flags{};
LONG references{1};
};
struct DevicePrefix : GraphicsObject {
UINT64 null_constant_address{};
UINT inline_flags[16]{1}; // Ask the title to dispatch the GXDK's out-of-line device methods.
};
struct DescriptorHeap;
struct Resource;
struct TargetBlock {
ComPtr<ID3D12DescriptorHeap> heap;
std::atomic<UINT64> used{};
};
struct TargetView {
title_rtv::Encoding encoding{};
std::shared_ptr<TargetBlock> block;
UINT index{};
D3D12_CPU_DESCRIPTOR_HANDLE native{};
~TargetView() { if (block) block->used.fetch_and(~(UINT64{1} << index)); }
};
struct CommittedTexture;
struct Sampler {
std::array<UINT, 4> words{};
D3D12_CPU_DESCRIPTOR_HANDLE native{};
};
struct PagePool {
UINT64 base;
UINT count;
ComPtr<IRdnaPageRuns> pages;
};
struct Device : DevicePrefix {
ComPtr<ID3D12Device11> host;
FenceDevice fences;
ComPtr<ID3D12Resource> null_constants;
bool enhanced_barriers{};
bool depth_bounds_supported{};
D3D12_COMMAND_LIST_SUPPORT_FLAGS immediate_writes{};
bool copy_timestamps{};
D3D12_FEATURE_DATA_D3D12_OPTIONS6 shading_options{};
D3D12_FEATURE_DATA_D3D12_OPTIONS10 shading_combiners{};
FrameTiming frames;
QueueMemoryWaits memory_waits;
std::mutex descriptor_lock;
std::map<SIZE_T, DescriptorHeap*> heaps;
std::multimap<UINT64, Resource*> resources;
std::set<const Resource*> target_sources;
std::weak_ptr<PlacedBuffer> last_buffer_pages;
SurfaceHeaps surface_heaps;
using PlacedKey = std::tuple<UINT64, D3D12_RESOURCE_DIMENSION, UINT64, UINT64, UINT, UINT16, UINT16,
DXGI_FORMAT, D3D12_TEXTURE_LAYOUT, D3D12_RESOURCE_FLAGS>;
std::map<PlacedKey, std::weak_ptr<PlacedTexture>> placed_textures;
UINT textures_created{};
QueueSubmissions resource_transfers;
ConstantPool constant_pool;
SampledBuffers sampled_buffers;
std::vector<std::weak_ptr<TargetBlock>> target_blocks;
title_rtv::Encoder target_encoder;
std::map<title_rtv::SamplerRequest, Sampler> samplers;
std::map<std::array<UINT, 4>, D3D12_CPU_DESCRIPTOR_HANDLE> sampler_sources;
std::vector<ComPtr<ID3D12DescriptorHeap>> sampler_pages;
std::mutex page_pool_lock;
std::map<UINT_PTR, PagePool> page_pools;
};
enum ComputeCommand { direct_dispatch, indirect_dispatch, translated_direct, translated_indirect, compute_command_count };
using ComputeCommands = std::bitset<compute_command_count>;
struct Queue : GraphicsObject {
D3D12_COMMAND_LIST_TYPE type{};
Device* parent{};
ComPtr<ID3D12CommandQueue> host;
std::mutex order_lock;
ComPtr<ID3D12Fence> mapping_fence;
UINT64 mapping_value{};
QueueSubmissions queue_submissions;
std::unique_ptr<DesktopPresentation> display;
std::optional<ComputeCommands> traced_compute;
};
struct Fence : GraphicsObject {
Device* parent{};
FenceMapping mapping;
ComPtr<ID3D12Fence1> host;
D3D12_FENCE_FLAGS creation_flags{};
};
struct QueryHeap : GraphicsObject {
Device* parent{};
ComPtr<ID3D12QueryHeap> host;
D3D12_QUERY_HEAP_DESC desc{};
};
struct CommandSignature : GraphicsObject {
Device* parent{};
ComPtr<ID3D12CommandSignature> host;
D3D12_INDIRECT_ARGUMENT_TYPE type{};
UINT stride{};
};
struct Allocator : GraphicsObject {
D3D12_COMMAND_LIST_TYPE type{};
Device* parent{};
ComPtr<ID3D12CommandAllocator> host;
std::mutex callback_lock;
std::shared_ptr<gdk_commands::Allocator> command_memory;
bool callback_enabled{};
};
struct ListPrefix : GraphicsObject {
D3D12_COMMAND_LIST_TYPE type{};
UINT padding{};
// Scarlett checks inline packet cursors and writes its own pipeline shadow here.
// Zero cursors direct it to our methods. Host pointers must follow this area.
std::array<BYTE, 0x980> inline_state{};
};
struct RootTables {
struct Range { UINT64 first; UINT count; bool writable; };
struct Parameter { D3D12_ROOT_PARAMETER_TYPE type; std::vector<Range> ranges; };
std::vector<Parameter> parameters;
bool directly_indexed{};
bool root_uav{};
};
struct SampledRange {
SIZE_T end;
ComPtr<ID3D12DescriptorHeap> heap;
UINT64 input_revision;
};
struct BoundRoot {
std::shared_ptr<const RootTables> layout;
ComPtr<ID3D12RootSignature> native;
struct Table { SIZE_T sampled_base; D3D12_GPU_DESCRIPTOR_HANDLE native; };
std::map<UINT, Table> tables;
std::map<UINT, D3D12_GPU_VIRTUAL_ADDRESS> srvs;
std::vector<std::shared_ptr<BufferViewCopy>> inputs;
UINT64 input_revision{};
bool may_write{};
bool dirty{true};
};
struct TimestampPage {
static constexpr UINT capacity = 128;
ComPtr<ID3D12QueryHeap> heap;
UINT used{};
};
struct List : ListPrefix {
Device* parent{};
ComPtr<ID3D12GraphicsCommandList7> host;
ComPtr<ID3D12GraphicsCommandList7> tail;
ComPtr<ID3D12CommandAllocator> native_allocator;
ComPtr<ID3D12PipelineState> pipeline;
std::shared_ptr<ComputeTable> compute_table;
std::set<SIZE_T> raw_compute_outputs;
ComputeCommands recorded_compute;
UINT traced_draws{};
struct WaitPoint {
ComPtr<ID3D12GraphicsCommandList7> before;
std::shared_ptr<WaitWord> word;
UINT64 reference;
};
std::vector<WaitPoint> waits;
ID3D12GraphicsCommandList7* current() const { return tail ? tail.Get() : host.Get(); }
std::shared_ptr<gdk_commands::List> command_memory;
ListParameters parameters{};
std::array<DescriptorHeap*, 2> bound_heaps{};
std::array<BoundRoot, 2> roots;
std::map<std::pair<size_t, SIZE_T>, SampledRange> sampled_tables;
std::set<std::shared_ptr<BufferViewCopy>> copied_inputs;
// Source pages may change between submissions, at a CPU wait or after a GPU write.
// Repeated read-only draws in one uninterrupted segment can share their first GPU copy.
std::set<const BufferViewCopy*> current_gathers;
UINT64 gathered_bytes{}, gathered_copies{};
std::map<IUnknown*, std::shared_ptr<void>> gpu_owners;
std::map<CommittedTexture*, D3D12_BARRIER_LAYOUT> display_layouts;
std::vector<TextureLayoutChange> sampled_layouts;
MappedTextureUses mapped_targets;
std::shared_ptr<TimestampPage> timestamps;
D3D12_PRIMITIVE_TOPOLOGY topology{D3D_PRIMITIVE_TOPOLOGY_UNDEFINED};
bool native_topology{};
std::optional<D3D12_INDEX_BUFFER_VIEW> indices;
std::array<D3D12_VERTEX_BUFFER_VIEW, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> vertices{};
UINT vertex_slots{};
struct ShadingRate {
D3D12_SHADING_RATE rate;
std::array<D3D12_SHADING_RATE_COMBINER, D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT> combiners{};
};
std::optional<ShadingRate> shading_rate;
std::optional<UINT> stencil_ref;
std::optional<std::array<FLOAT, 2>> depth_bounds;
std::optional<std::array<FLOAT, 4>> blend_factor;
UINT64 quad_sample_mask{UINT64_MAX};
struct OutputTargets {
std::array<D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> colors{};
std::array<std::shared_ptr<PlacedTexture>, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> mapped_colors{};
ID3D12Resource* first_color{};
D3D12_CPU_DESCRIPTOR_HANDLE depth{};
std::shared_ptr<PlacedTexture> mapped_depth;
bool depth_writable{};
UINT count{};
void bind(ID3D12GraphicsCommandList& native) const {
native.OMSetRenderTargets(count, count ? colors.data() : nullptr, FALSE, depth.ptr ? &depth : nullptr);
}
} targets;
UINT active_queries{}, viewport_count{}, scissor_count{};
std::array<D3D12_VIEWPORT, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> viewports;
std::array<D3D12_RECT, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE> scissors;
HRESULT recording_status{S_OK};
bool closed{};
bool segment_closed{};
bool compute_pipeline{};
};
struct Root : GraphicsObject {
Device* parent{};
ComPtr<ID3D12RootSignature> host;
std::shared_ptr<const RootTables> tables;
ComPtr<ID3D12VersionedRootSignatureDeserializer> layout;
};
struct CommittedTexture {
D3D12_RESOURCE_DESC desc{};
D3D12_RESOURCE_FLAGS requested_flags{};
D3D12_RESOURCE_DESC view_resource() const {
auto result = desc;
result.Format = color_storage_format(desc);
return result;
}
std::shared_ptr<SurfacePlacement> placement;
ComPtr<ID3D12Resource> native;
ComPtr<IUnknown> guest_allocation;
UINT64 address{};
std::optional<std::array<UINT, 8>> full_srv;
std::optional<std::atomic<D3D12_BARRIER_LAYOUT>> submitted_display_layout;
using TargetKey = std::pair<D3D12_DESCRIPTOR_HEAP_TYPE, std::array<BYTE, sizeof(D3D12_RENDER_TARGET_VIEW_DESC)>>;
std::map<TargetKey, std::unique_ptr<TargetView>> targets;
std::map<std::array<BYTE, sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC)>, std::array<UINT, 8>> writable_views;
};
std::shared_ptr<PlacedTexture> texture_transfer(const std::shared_ptr<CommittedTexture>& texture) {
if (!texture->placement || !texture->placement->transfer) return {};
// Retain the placement in the guest alias registry until the last GPU access completes.
return {texture, texture->placement->transfer.get()};
}
struct Resource : GraphicsObject {
Device* parent{};
std::shared_ptr<PlacedBuffer> backing;
std::shared_ptr<CommittedTexture> texture;
ComPtr<ID3D12Resource> host;
ComPtr<IUnknown> buffer_reservation;
UINT64 buffer_address{};
D3D12_RESOURCE_STATES buffer_state{};
UINT64 address() const {
if (backing) return backing->guest_address();
return texture ? texture->address : buffer_address;
}
};
UINT64 descriptor_allocation_attributes() {
// The title's D3D allocation callback places descriptor storage for object type 4.
return MAKE_XALLOC_ATTRIBUTES(eXALLOCAllocatorId_D3D, 4, XALLOC_MEMTYPE_HEAP_CACHEABLE,
XALLOC_PAGESIZE_4KB, XALLOC_ALIGNMENT_256, 0);
}
struct DescriptorHeap : GraphicsObject {
Device* parent{};
ComPtr<ID3D12DescriptorHeap> host;
void* memory{};
SIZE_T bytes{};
struct RawOutput { std::shared_ptr<void> resource; };
struct TextureOutput { std::shared_ptr<PlacedTexture> texture; };
using Owner = std::variant<std::shared_ptr<void>, std::shared_ptr<PlacedTexture>, std::shared_ptr<BufferViewCopy>, RawOutput, TextureOutput>;
std::map<SIZE_T, Owner> view_owners;
static constexpr UINT page_slots = 256;
struct CopyPage { ComPtr<ID3D12DescriptorHeap> storage; std::bitset<page_slots> initialized; };
std::map<UINT, CopyPage> copy_pages;
std::atomic<UINT64> input_revision{};
void set_owner(SIZE_T address, Owner owner) {
const auto previous = view_owners.find(address);
const bool changed = std::holds_alternative<std::shared_ptr<BufferViewCopy>>(owner) ||
(previous != view_owners.end() && std::holds_alternative<std::shared_ptr<BufferViewCopy>>(previous->second));
view_owners.insert_or_assign(previous, address, std::move(owner));
if (changed) input_revision.fetch_add(1, std::memory_order_release);
}
void erase_owner(SIZE_T address) {
const auto it = view_owners.find(address);
if (it == view_owners.end()) return;
const bool changed = std::holds_alternative<std::shared_ptr<BufferViewCopy>>(it->second);
view_owners.erase(it);
if (changed) input_revision.fetch_add(1, std::memory_order_release);
}
~DescriptorHeap() {
if (memory) XMemFree(memory, descriptor_allocation_attributes());
}
};
struct alignas(16) PipelinePrefix : GraphicsObject {
// The Scarlett ABI reserves eight inline packet words before any host state.
std::array<UINT, 8> packet{};
};
struct Pipeline : PipelinePrefix {
Device* parent{};
ComPtr<ID3D12PipelineState> host;
std::shared_ptr<ComputeTable> compute_table;
bool compute{};
};
static_assert(sizeof(GraphicsObject) == 16 && sizeof(DevicePrefix) == 88);
static_assert(sizeof(PipelinePrefix) == 48);
static_assert(sizeof(ListPrefix) == 0x998);
Device* current_device{};
std::mutex device_lock;
template<class T> const Method* methods();
template<class T> bool supports(REFIID iid) {
if (iid == __uuidof(IUnknown) || iid == graphics_unknown || iid == __uuidof(ID3D12Object)) return true;
if constexpr (std::is_same_v<T, Device>) {
return iid == __uuidof(ID3D12Device) || iid == __uuidof(ID3D12Device1) || iid == __uuidof(ID3D12Device2) ||
iid == __uuidof(ID3D12Device3) || iid == __uuidof(ID3D12Device4) || iid == __uuidof(ID3D12Device5) ||
iid == __uuidof(ID3D12Device6) || iid == __uuidof(ID3D12Device7) || iid == __uuidof(ID3D12Device8) ||
iid == scarlett_device8 || iid == __uuidof(ID3D12Device9) || iid == __uuidof(ID3D12Device10) ||
iid == __uuidof(ID3D12Device11);
} else {
if (iid == __uuidof(ID3D12DeviceChild)) return true;
if (!std::is_same_v<T, Root> && !std::is_same_v<T, List> && iid == __uuidof(ID3D12Pageable)) return true;
if constexpr (std::is_same_v<T, Queue>) return iid == __uuidof(ID3D12CommandQueue);
else if constexpr (std::is_same_v<T, Fence>) return iid == __uuidof(ID3D12Fence) || iid == __uuidof(ID3D12Fence1);
else if constexpr (std::is_same_v<T, QueryHeap>) return iid == __uuidof(ID3D12QueryHeap);
else if constexpr (std::is_same_v<T, CommandSignature>) return iid == __uuidof(ID3D12CommandSignature);
else if constexpr (std::is_same_v<T, Allocator>) return iid == __uuidof(ID3D12CommandAllocator);
else if constexpr (std::is_same_v<T, Resource>) return iid == __uuidof(ID3D12Resource);
else if constexpr (std::is_same_v<T, DescriptorHeap>) return iid == __uuidof(ID3D12DescriptorHeap);
else if constexpr (std::is_same_v<T, Pipeline>) return iid == __uuidof(ID3D12PipelineState);
else if constexpr (std::is_same_v<T, List>)
return iid == graphics_list || iid == __uuidof(ID3D12CommandList) || iid == __uuidof(ID3D12GraphicsCommandList) ||
iid == __uuidof(ID3D12GraphicsCommandList1) || iid == __uuidof(ID3D12GraphicsCommandList2) ||
iid == __uuidof(ID3D12GraphicsCommandList3) || iid == __uuidof(ID3D12GraphicsCommandList4) ||
iid == __uuidof(ID3D12GraphicsCommandList5) || iid == __uuidof(ID3D12GraphicsCommandList6);
else return iid == __uuidof(ID3D12RootSignature);
}
}
ULONG WINAPI retain(GraphicsObject* object) { return InterlockedIncrement(&object->references); }
ULONG WINAPI release_device(Device* device) {
std::unique_lock lock(device_lock);
const ULONG count = InterlockedDecrement(&device->references);
if (count) return count;
RdnaClearGpuPageMappings();
current_device = nullptr;
lock.unlock();
delete device;
return 0;
}
template<class T> ULONG WINAPI release_child(T* object) {
const ULONG count = InterlockedDecrement(&object->references);
if (!count) {
auto* device = object->parent;
if constexpr (std::is_same_v<T, DescriptorHeap>) {
std::lock_guard lock(device->descriptor_lock);
device->heaps.erase(reinterpret_cast<SIZE_T>(object->memory));
} else if constexpr (std::is_same_v<T, Resource>) {
std::lock_guard lock(device->descriptor_lock);
device->target_sources.erase(object);
const auto [begin, end] = device->resources.equal_range(object->address());
for (auto it = begin; it != end; ++it) {
if (it->second == object) { device->resources.erase(it); break; }
}
}
delete object;
release_device(device);
}
return count;
}
template<class T> HRESULT WINAPI query(T* object, REFIID iid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!supports<T>(iid)) return E_NOINTERFACE;
retain(object);
*out = object;
return S_OK;
}
template<class T> HRESULT WINAPI get_private(T* object, REFGUID key, UINT* size, void* data) {
return object->host->GetPrivateData(key, size, data);
}
template<class T> HRESULT WINAPI set_private(T* object, REFGUID key, UINT size, const void* data) {
const HRESULT hr = object->host->SetPrivateData(key, size, data);
if (SUCCEEDED(hr) && size) InterlockedOr(&object->flags, 8);
return hr;
}
template<class T> HRESULT WINAPI set_interface(T* object, REFGUID key, const IUnknown* value) {
const HRESULT hr = object->host->SetPrivateDataInterface(key, value);
if (SUCCEEDED(hr) && value) InterlockedOr(&object->flags, 8);
return hr;
}
template<class T> HRESULT WINAPI set_name(T* object, PCWSTR name) {
const HRESULT hr = object->host->SetName(name);
if (SUCCEEDED(hr) && name) InterlockedOr(&object->flags, 8);
return hr;
}
template<class T> HRESULT WINAPI get_parent(T* object, REFIID iid, void** out) {
return query(object->parent, iid, out);
}
template<class T, class Native> HRESULT publish_child(Device* device, ComPtr<Native>& host, void** out,
D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) {
auto child = std::unique_ptr<T>(new(std::nothrow) T);
if (!child) return E_OUTOFMEMORY;
child->methods = methods<T>();
if constexpr (std::is_same_v<T, Queue>) child->type = host->GetDesc().Type;
if constexpr (std::is_same_v<T, Allocator> || std::is_same_v<T, List>) child->type = type;
child->host = std::move(host);
child->parent = device;
retain(device);
*out = child.release();
return S_OK;
}
UINT WINAPI node_count(Device* device) { return device->host->GetNodeCount(); }
HRESULT WINAPI removed_reason(Device* device) { return device->host->GetDeviceRemovedReason(); }
UINT WINAPI descriptor_stride(Device*, D3D12_DESCRIPTOR_HEAP_TYPE type) {
return guest_descriptor_stride(static_cast<UINT>(type));
}
HRESULT WINAPI create_descriptor_heap(Device* device, const D3D12_DESCRIPTOR_HEAP_DESC* desc, REFIID iid, void** out) {
if (out) *out = nullptr;
if (!desc || !desc->NumDescriptors) return E_INVALIDARG;
if (!supports<DescriptorHeap>(iid)) return E_NOINTERFACE;
if (static_cast<UINT>(desc->Type) >= D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES) return DXGI_ERROR_UNSUPPORTED;
if (!out) return device->host->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), nullptr);
auto heap = std::unique_ptr<DescriptorHeap>(new(std::nothrow) DescriptorHeap);
if (!heap) return E_OUTOFMEMORY;
const HRESULT hr = device->host->CreateDescriptorHeap(desc, IID_PPV_ARGS(&heap->host));
if (FAILED(hr)) return hr;
heap->bytes = SIZE_T(desc->NumDescriptors) * descriptor_stride(device, desc->Type);
heap->memory = XMemAlloc(heap->bytes, descriptor_allocation_attributes());
if (!heap->memory) return E_OUTOFMEMORY;
const auto address = reinterpret_cast<SIZE_T>(heap->memory);
{
std::lock_guard lock(device->descriptor_lock);
const auto next = device->heaps.lower_bound(address);
if (next != device->heaps.end() && next->first - address < heap->bytes) return E_INVALIDARG;
if (next != device->heaps.begin()) {
const auto previous = std::prev(next);
if (address - previous->first < previous->second->bytes) return E_INVALIDARG;
}
try { device->heaps.emplace_hint(next, address, heap.get()); }
catch (const std::bad_alloc&) { return E_OUTOFMEMORY; }
}
heap->methods = methods<DescriptorHeap>();
heap->parent = device;
retain(device);
*out = heap.release();
return S_OK;
}
void WINAPI descriptor_heap_desc(DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP_DESC* out) { *out = heap->host->GetDesc(); }
D3D12_CPU_DESCRIPTOR_HANDLE WINAPI cpu_start(DescriptorHeap* heap) { return {reinterpret_cast<SIZE_T>(heap->memory)}; }
D3D12_GPU_DESCRIPTOR_HANDLE WINAPI gpu_start(DescriptorHeap* heap) {
return {heap->host->GetDesc().Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE ? reinterpret_cast<UINT64>(heap->memory) : 0};
}
[[noreturn]] void unsupported_view(const char* reason) {
OutputDebugStringA(reason);
std::fputs(reason, stderr);
std::fflush(stderr);
RaiseFailFastException(nullptr, nullptr, 0);
std::terminate();
}
// Callers hold descriptor_lock until the native write and guest update are both complete.
D3D12_CPU_DESCRIPTOR_HANDLE native_cpu_handle(Device* device, D3D12_CPU_DESCRIPTOR_HANDLE guest,
D3D12_DESCRIPTOR_HEAP_TYPE type, DescriptorHeap** owner) {
const auto after = device->heaps.upper_bound(guest.ptr);
if (after == device->heaps.begin()) unsupported_view("rdna4rage: descriptor destination outside a live heap\n");
const auto entry = std::prev(after);
const auto* heap = entry->second;
const SIZE_T offset = guest.ptr - entry->first;
const UINT stride = descriptor_stride(device, type);
if (heap->host->GetDesc().Type != type || offset >= heap->bytes || offset % stride)
unsupported_view("rdna4rage: descriptor destination outside its heap or misaligned\n");
auto dest = heap->host->GetCPUDescriptorHandleForHeapStart();
dest.ptr += (offset / stride) * device->host->GetDescriptorHandleIncrementSize(type);
*owner = entry->second;
return dest;
}
DescriptorHeap* containing_heap(Device* device, SIZE_T address) {
const auto next = device->heaps.upper_bound(address);
if (next == device->heaps.begin()) return nullptr;
const auto entry = std::prev(next);
return address - entry->first < entry->second->bytes ? entry->second : nullptr;
}
struct DescriptorRange {
D3D12_CPU_DESCRIPTOR_HANDLE storage, live;
DescriptorHeap::CopyPage* page;
UINT offset, available;
void require_source(UINT count) const {
if (page) for (UINT i = offset; i < offset + count; ++i)
if (!page->initialized.test(i)) unsupported_view("rdna4rage: uninitialized shader-visible descriptor copy source\n");
}
void publish(Device* device, UINT count = 1) const {
if (!page) return;
device->host->CopyDescriptorsSimple(count, live, storage, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
for (UINT i = offset; i < offset + count; ++i) page->initialized.set(i);
}
};
// Windows permits descriptor copies only from a CPU-readable heap. Keep those descriptors
// in small pages for the portions of a shader-visible Scarlett resource heap that GTA writes.
DescriptorRange descriptor_range(Device* device, D3D12_CPU_DESCRIPTOR_HANDLE guest, D3D12_DESCRIPTOR_HEAP_TYPE type,
DescriptorHeap** owner, bool writing) {
const auto live = native_cpu_handle(device, guest, type, owner);
auto& heap = **owner;
const auto desc = heap.host->GetDesc();
const UINT index = UINT((guest.ptr - reinterpret_cast<SIZE_T>(heap.memory)) / descriptor_stride(device, type));
if (type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !(desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE))
return {live, live, nullptr, 0, desc.NumDescriptors - index};
const UINT block = index / heap.page_slots, offset = index % heap.page_slots;
const UINT size = (std::min)(heap.page_slots, desc.NumDescriptors - block * heap.page_slots);
auto it = heap.copy_pages.find(block);
if (it == heap.copy_pages.end()) {
if (!writing) unsupported_view("rdna4rage: shader-visible copy source has no stored descriptors\n");
DescriptorHeap::CopyPage page{};
const D3D12_DESCRIPTOR_HEAP_DESC cpu{type, size, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, desc.NodeMask};
if (FAILED(device->host->CreateDescriptorHeap(&cpu, IID_PPV_ARGS(&page.storage))))
unsupported_view("rdna4rage: could not create CPU descriptor storage\n");
it = heap.copy_pages.emplace(block, std::move(page)).first;
}
auto handle = it->second.storage->GetCPUDescriptorHandleForHeapStart();
handle.ptr += SIZE_T(offset) * device->host->GetDescriptorHandleIncrementSize(type);
return {handle, live, &it->second, offset, size - offset};
}
void WINAPI create_sampler_x(Device* device, const void* source, D3D12_CPU_DESCRIPTOR_HANDLE guest) try {
if (!source || !guest.ptr || guest.ptr % 16) unsupported_view("rdna4rage: invalid Scarlett sampler destination\n");
title_rtv::SamplerRequest request{};
std::memcpy(request.data(), source, sizeof(request));
std::lock_guard lock(device->descriptor_lock);
auto sampler = device->samplers.find(request);
if (sampler == device->samplers.end()) {
Sampler value{};
D3D12_SAMPLER_DESC desc{};
const HRESULT hr = device->target_encoder.sampler(guest.ptr, request, value.words, desc);
if (FAILED(hr)) {
char why[144]{};
std::snprintf(why, sizeof(why), "rdna4rage: GDK sampler encoding or desktop equivalence returned 0x%08lx\n", hr);
unsupported_view(why);
}
constexpr UINT page_slots = 64;
const size_t index = device->samplers.size();
if (index / page_slots == device->sampler_pages.size()) {
const D3D12_DESCRIPTOR_HEAP_DESC heap{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, page_slots, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 1};
ComPtr<ID3D12DescriptorHeap> page;
if (FAILED(device->host->CreateDescriptorHeap(&heap, IID_PPV_ARGS(&page)))) unsupported_view("rdna4rage: sampler heap allocation failed\n");
device->sampler_pages.push_back(std::move(page));
}
value.native = device->sampler_pages[index / page_slots]->GetCPUDescriptorHandleForHeapStart();
value.native.ptr += index % page_slots * device->host->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
device->host->CreateSampler(&desc, value.native);
device->sampler_sources.try_emplace(value.words, value.native);
sampler = device->samplers.emplace(request, value).first;
}
if (auto* heap = containing_heap(device, guest.ptr)) {
auto dest = native_cpu_handle(device, guest, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, &heap);
device->host->CopyDescriptorsSimple(1, dest, sampler->second.native, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
}
std::memcpy(reinterpret_cast<void*>(guest.ptr), sampler->second.words.data(), sizeof(sampler->second.words));
} catch (const std::bad_alloc&) { unsupported_view("rdna4rage: out of memory retaining sampler\n"); }
void WINAPI copy_descriptors_simple(Device* device, UINT count, D3D12_CPU_DESCRIPTOR_HANDLE dest,
D3D12_CPU_DESCRIPTOR_HANDLE source, D3D12_DESCRIPTOR_HEAP_TYPE type) try {
if (!count) return;
const UINT stride = descriptor_stride(device, type);
const SIZE_T bytes = SIZE_T(count) * stride;
if (!stride || !dest.ptr || !source.ptr || (dest.ptr | source.ptr) % 16 || dest.ptr > SIZE_MAX - bytes || source.ptr > SIZE_MAX - bytes)
unsupported_view("rdna4rage: invalid descriptor copy range\n");
std::lock_guard lock(device->descriptor_lock);
auto in_bounds = [&](const DescriptorHeap* heap, SIZE_T base) {
if (!heap) return true;
const SIZE_T offset = base - reinterpret_cast<SIZE_T>(heap->memory);
return heap->host->GetDesc().Type == type && offset % stride == 0 && bytes <= heap->bytes - offset;
};
auto* from = containing_heap(device, source.ptr);
auto* to = containing_heap(device, dest.ptr);
if (!in_bounds(from, source.ptr) || !in_bounds(to, dest.ptr)) unsupported_view("rdna4rage: descriptor copy exceeds heap\n");
if (dest.ptr == source.ptr) return;
if (type != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) {
if (!from || !to) {
char message[180]{};
std::snprintf(message, sizeof(message), "rdna4rage: unsupported descriptor copy type %u from 0x%llx (heap flags %d) to 0x%llx (heap flags %d)\n",
UINT(type), source.ptr, from ? int(from->host->GetDesc().Flags) : -1,
dest.ptr, to ? int(to->host->GetDesc().Flags) : -1);
unsupported_view(message);
}
// Snapshot the sparse ownership records before changing any source or destination slots.
decltype(to->view_owners) owners;
bool inputs_changed{};
const auto source_end = from->view_owners.lower_bound(source.ptr + bytes);
for (auto it = from->view_owners.lower_bound(source.ptr); it != source_end; ++it) {
owners.emplace_hint(owners.end(), dest.ptr + (it->first - source.ptr), it->second);
inputs_changed |= std::holds_alternative<std::shared_ptr<BufferViewCopy>>(it->second);
}
const auto first = to->view_owners.lower_bound(dest.ptr), last = to->view_owners.lower_bound(dest.ptr + bytes);
inputs_changed |= std::any_of(first, last, [](const auto& entry) {
return std::holds_alternative<std::shared_ptr<BufferViewCopy>>(entry.second);
});
const bool overlap = from == to && dest.ptr < source.ptr + bytes && source.ptr < dest.ptr + bytes;
auto transfer = [&](bool execute) {
for (UINT done = 0; done < count;) {
const UINT index = execute && overlap && dest.ptr > source.ptr ? count - done - 1 : done;
const SIZE_T offset = SIZE_T(index) * stride;
const auto input = descriptor_range(device, {source.ptr + offset}, type, &from, false);
const auto output = descriptor_range(device, {dest.ptr + offset}, type, &to, true);
const UINT n = execute && overlap ? 1 : (std::min)({count - done, input.available, output.available});
if (!execute || count == 1) input.require_source(n);
if (execute) {
device->host->CopyDescriptorsSimple(n, output.storage, input.storage, type);
output.publish(device, n);
}
done += n;
}
};
if (count > 1) transfer(false);
transfer(true);
to->view_owners.erase(first, last);
to->view_owners.merge(owners);
if (inputs_changed) ++to->input_revision;
} else if (to) {
auto handle = native_cpu_handle(device, dest, type, &to);
const auto increment = device->host->GetDescriptorHandleIncrementSize(type);
for (UINT i = 0; i < count; ++i) {
std::array<UINT, 4> words{};
std::memcpy(words.data(), reinterpret_cast<const void*>(source.ptr + SIZE_T(i) * stride), sizeof(words));
const auto sampler = device->sampler_sources.find(words);
if (sampler == device->sampler_sources.end()) unsupported_view("rdna4rage: unknown source sampler encoding\n");
device->host->CopyDescriptorsSimple(1, handle, sampler->second, type);
handle.ptr += increment;
}
}
std::memmove(reinterpret_cast<void*>(dest.ptr), reinterpret_cast<const void*>(source.ptr), bytes);
} catch (const std::bad_alloc&) { unsupported_view("rdna4rage: out of memory copying descriptor owners\n"); }
struct TargetOperations {
UINT (WINAPI* is_depth)(const void*);
};
// The installed GDK symbols place the one-entry color and depth view tables consecutively.
UINT WINAPI target_zero(const void*) { return 0; }
UINT WINAPI target_one(const void*) { return 1; }
const TargetOperations color_operations{target_zero}, depth_operations{target_one};
bool color_description(const D3D12_RESOURCE_DESC& texture, const D3D12_RENDER_TARGET_VIEW_DESC* input,
D3D12_RENDER_TARGET_VIEW_DESC& view) {
if (!input) {
view.Format = texture.Format;
const bool array = texture.DepthOrArraySize > 1;
switch (texture.Dimension) {
case D3D12_RESOURCE_DIMENSION_TEXTURE1D:
view.ViewDimension = array ? D3D12_RTV_DIMENSION_TEXTURE1DARRAY : D3D12_RTV_DIMENSION_TEXTURE1D;
if (array) view.Texture1DArray.ArraySize = texture.DepthOrArraySize;
return true;
case D3D12_RESOURCE_DIMENSION_TEXTURE2D:
if (texture.SampleDesc.Count > 1) {
view.ViewDimension = array ? D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY : D3D12_RTV_DIMENSION_TEXTURE2DMS;
if (array) view.Texture2DMSArray.ArraySize = texture.DepthOrArraySize;
} else {
view.ViewDimension = array ? D3D12_RTV_DIMENSION_TEXTURE2DARRAY : D3D12_RTV_DIMENSION_TEXTURE2D;
if (array) view.Texture2DArray.ArraySize = texture.DepthOrArraySize;
}
return true;
case D3D12_RESOURCE_DIMENSION_TEXTURE3D:
view.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
view.Texture3D.WSize = texture.DepthOrArraySize;
return true;
default: return false;
}
}
view.Format = input->Format;
view.ViewDimension = input->ViewDimension;
switch (view.ViewDimension) {
case D3D12_RTV_DIMENSION_TEXTURE1D: view.Texture1D = input->Texture1D; break;
case D3D12_RTV_DIMENSION_TEXTURE1DARRAY: view.Texture1DArray = input->Texture1DArray; break;
case D3D12_RTV_DIMENSION_TEXTURE2D: view.Texture2D = input->Texture2D; break;
case D3D12_RTV_DIMENSION_TEXTURE2DARRAY: view.Texture2DArray = input->Texture2DArray; break;
case D3D12_RTV_DIMENSION_TEXTURE2DMS: break;
case D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY: view.Texture2DMSArray = input->Texture2DMSArray; break;
case D3D12_RTV_DIMENSION_TEXTURE3D: view.Texture3D = input->Texture3D; break;
default: return false;
}
return true;
}
bool depth_description(const D3D12_RESOURCE_DESC& texture, const D3D12_DEPTH_STENCIL_VIEW_DESC* input,
D3D12_DEPTH_STENCIL_VIEW_DESC& view) {
if (texture.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || !texture.SampleDesc.Count) return false;
const bool msaa = texture.SampleDesc.Count > 1;
const auto plain = msaa ? D3D12_DSV_DIMENSION_TEXTURE2DMS : D3D12_DSV_DIMENSION_TEXTURE2D;
const auto array = msaa ? D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY : D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
switch (UINT(texture.Format)) {
case scarlett_d16s8: view.Format = scarlett_d16s8; break;
case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: view.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; break;
case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: view.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; break;
case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_D32_FLOAT: view.Format = DXGI_FORMAT_D32_FLOAT; break;
case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_D16_UNORM: view.Format = DXGI_FORMAT_D16_UNORM; break;
default: return false;
}
if (input) {
if ((input->Format != view.Format && !(input->Format == DXGI_FORMAT_UNKNOWN && texture.Format == view.Format)) ||
(UINT(input->Flags) & ~UINT(D3D12_DSV_FLAG_READ_ONLY_DEPTH | D3D12_DSV_FLAG_READ_ONLY_STENCIL)))
return false;
if ((input->Flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) && (view.Format == DXGI_FORMAT_D32_FLOAT || view.Format == DXGI_FORMAT_D16_UNORM))
return false;
view.Flags = input->Flags;
view.ViewDimension = input->ViewDimension;
} else {
if (texture.Format != view.Format) return false;
view.ViewDimension = texture.DepthOrArraySize == 1 ? plain : array;
}
const UINT mips = texture.MipLevels ? texture.MipLevels : std::bit_width(std::max(texture.Width, UINT64(texture.Height)));
if (view.ViewDimension == plain) {
if (!msaa && input) view.Texture2D = input->Texture2D;
return texture.DepthOrArraySize == 1 && (msaa || view.Texture2D.MipSlice < mips);
}
if (view.ViewDimension != array) return false;
UINT first{}, count = texture.DepthOrArraySize;
if (msaa) {
if (input) view.Texture2DMSArray = input->Texture2DMSArray;
else view.Texture2DMSArray.ArraySize = count;
first = view.Texture2DMSArray.FirstArraySlice;
count = view.Texture2DMSArray.ArraySize;
} else {
if (input) view.Texture2DArray = input->Texture2DArray;
else view.Texture2DArray.ArraySize = count;
if (view.Texture2DArray.MipSlice >= mips) return false;
first = view.Texture2DArray.FirstArraySlice;
count = view.Texture2DArray.ArraySize;
}
return count && first < texture.DepthOrArraySize && count <= UINT(texture.DepthOrArraySize) - first;
}
HRESULT allocate_target_handle(Device* device, D3D12_DESCRIPTOR_HEAP_TYPE type, TargetView& target) {
std::erase_if(device->target_blocks, [](const auto& page) { return page.expired(); });
std::shared_ptr<TargetBlock> block;
for (auto& weak : device->target_blocks) {
auto current = weak.lock();
if (current && current->heap->GetDesc().Type == type && current->used.load() != UINT64_MAX) { block = std::move(current); break; }
}
if (!block) {
block = std::make_shared<TargetBlock>();
const D3D12_DESCRIPTOR_HEAP_DESC desc{type, 64, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 1};
const HRESULT hr = device->host->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&block->heap));
if (FAILED(hr)) return hr;
device->target_blocks.emplace_back(block);
}
target.index = std::countr_one(block->used.load());
block->used.fetch_or(UINT64{1} << target.index);
target.block = std::move(block);
target.native = target.block->heap->GetCPUDescriptorHandleForHeapStart();
target.native.ptr += SIZE_T(target.index) * device->host->GetDescriptorHandleIncrementSize(type);
return S_OK;
}
template<class View> void WINAPI target_view(Device* device, Resource* resource, const View* input,
D3D12_CPU_DESCRIPTOR_HANDLE guest) try {
constexpr bool depth = std::is_same_v<View, D3D12_DEPTH_STENCIL_VIEW_DESC>;
constexpr auto type = depth ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
constexpr auto usage = depth ? D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL : D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
if (!resource || resource->methods != methods<Resource>() || resource->parent != device || !resource->texture ||
!(resource->texture->desc.Flags & usage) || !guest.ptr || guest.ptr % 16)
unsupported_view("rdna4rage: invalid target resource or descriptor handle\n");
auto& texture = *resource->texture;
View view{};
if constexpr (depth) {
if (!depth_description(texture.desc, input, view)) unsupported_view("rdna4rage: unsupported depth-stencil view description\n");
} else if (!color_description(texture.desc, input, view)) unsupported_view("rdna4rage: unsupported render-target dimension\n");
const CommittedTexture::TargetKey key{type, std::bit_cast<std::array<BYTE, sizeof(D3D12_RENDER_TARGET_VIEW_DESC)>>(view)};
std::lock_guard lock(device->descriptor_lock);
auto found = texture.targets.find(key);
if (found == texture.targets.end()) {
auto target = std::make_unique<TargetView>();
HRESULT hr;
if constexpr (depth) hr = device->target_encoder.depth_stencil(texture.address, texture.desc, view, target->encoding);
else hr = device->target_encoder.render_target(texture.address, texture.view_resource(), view, target->encoding);
if (SUCCEEDED(hr)) hr = allocate_target_handle(device, type, *target);
ID3D12Resource* target_image = texture.native.Get();
if constexpr (depth) {
if (SUCCEEDED(hr) && texture.placement && texture.placement->depth)
hr = texture.placement->depth->get(*device->host.Get(), target_image);
}
if (FAILED(hr)) {
char message[128]{};
std::snprintf(message, sizeof(message), "rdna4rage: %s view creation returned 0x%08lx\n", depth ? "depth-stencil" : "render-target", hr);
unsupported_view(message);
}
if constexpr (depth) {
auto desktop_view = view;
desktop_view.Format = host_depth_view(view.Format);
device->host->CreateDepthStencilView(target_image, &desktop_view, target->native);
}
else device->host->CreateRenderTargetView(target_image, &view, target->native);
found = texture.targets.emplace(key, std::move(target)).first;
}
device->target_sources.insert(resource);
const auto after = device->heaps.upper_bound(guest.ptr);
if (after != device->heaps.begin()) {
const auto heap = std::prev(after);
if (guest.ptr - heap->first < heap->second->bytes) {
DescriptorHeap* owner{};
const auto dest = native_cpu_handle(device, guest, type, &owner);
owner->set_owner(guest.ptr, resource->texture);
device->host->CopyDescriptorsSimple(1, dest, found->second->native, type);
}
}
// Scarlett also accepts slots in the game's own CPU descriptor pool. Copied slots retain their meaning.
auto* dest = reinterpret_cast<BYTE*>(guest.ptr);
const auto& encoding = found->second->encoding;
constexpr size_t bytes = depth ? title_rtv::depth_bytes : title_rtv::color_bytes;
for (size_t i = 0; i < bytes; ++i) {
const BYTE mask = encoding.mask[i];
if (mask) dest[i] = (dest[i] & ~mask) | (encoding.value[i] & mask);
}
const auto* ops = depth ? &depth_operations : &color_operations;
std::memcpy(dest, &ops, sizeof(ops));
std::memcpy(dest + 16, &resource, sizeof(resource));
} catch (const std::bad_alloc&) { unsupported_view("rdna4rage: out of memory creating a render-target view\n"); }
HRESULT resolve_target(List& list, D3D12_CPU_DESCRIPTOR_HANDLE guest, D3D12_DESCRIPTOR_HEAP_TYPE type,
D3D12_CPU_DESCRIPTOR_HANDLE& native, ID3D12Resource** source = nullptr,
std::shared_ptr<PlacedTexture>* mapped = nullptr, bool* writable = nullptr, bool* depth16 = nullptr) {
if (!guest.ptr) return E_INVALIDARG;
const bool depth = type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
const size_t size = depth ? title_rtv::depth_bytes : title_rtv::color_bytes;
auto& device = *list.parent;
std::lock_guard lock(device.descriptor_lock);
auto* heap = containing_heap(&device, guest.ptr);
if (heap && (heap->host->GetDesc().Type != type ||
(guest.ptr - reinterpret_cast<SIZE_T>(heap->memory)) % size)) return E_INVALIDARG;
const auto* bytes = reinterpret_cast<const BYTE*>(guest.ptr);
const TargetOperations* operations{};
Resource* identity{};
std::memcpy(&operations, bytes, sizeof(operations));
std::memcpy(&identity, bytes + 16, sizeof(identity));
if (operations != (depth ? &depth_operations : &color_operations)) return E_INVALIDARG;
std::shared_ptr<CommittedTexture> texture;
if (device.target_sources.contains(identity)) texture = identity->texture;
else if (heap) {
const auto entry = heap->view_owners.find(guest.ptr);
if (entry != heap->view_owners.end()) {
if (const auto owner = std::get_if<std::shared_ptr<void>>(&entry->second))
texture = std::static_pointer_cast<CommittedTexture>(*owner);
}
}
if (!texture) return E_INVALIDARG;
// The title can copy a descriptor into its own memory. Match only the bits the GXDK writes.
for (const auto& [key, view] : texture->targets) {
if (key.first != type) continue;
const auto& encoding = view->encoding;
size_t i = 0;
while (i < size && !((bytes[i] ^ encoding.value[i]) & encoding.mask[i])) ++i;
if (i == size) {
native = view->native;
list.gpu_owners.try_emplace(texture->native.Get(), texture);
if (source) *source = texture->native.Get();
if (depth16) *depth16 = texture->desc.Format == scarlett_d16s8;
if (mapped) {
auto transfer = texture_transfer(texture);
if (transfer && transfer->mapped) {
*mapped = std::move(transfer);
if (depth && writable) {
D3D12_DEPTH_STENCIL_VIEW_DESC desc{};
std::memcpy(&desc, key.second.data(), sizeof(desc));
const bool stencil = desc.Format == scarlett_d16s8 || desc.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT ||
desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT;
*writable = !(desc.Flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) || (stencil && !(desc.Flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL));
}
}
}
return S_OK;
}
}
return DXGI_ERROR_UNSUPPORTED;
}
void WINAPI set_render_targets(List* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* colors,
BOOL contiguous, const D3D12_CPU_DESCRIPTOR_HANDLE* depth) try {
if (FAILED(list->recording_status)) return;
List::OutputTargets targets{};
if (list->closed || list->type != D3D12_COMMAND_LIST_TYPE_DIRECT || count > targets.colors.size() || (count && !colors)) {
list->recording_status = E_INVALIDARG;
return;
}
const auto stride = title_rtv::color_bytes;
if (count && contiguous && colors[0].ptr > SIZE_MAX - (count - 1) * stride) { list->recording_status = E_INVALIDARG; return; }
for (UINT i = 0; i < count; ++i) {
const auto guest = contiguous ? D3D12_CPU_DESCRIPTOR_HANDLE{colors[0].ptr + i * stride} : colors[i];
list->recording_status = resolve_target(*list, guest, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, targets.colors[i],
i == 0 ? &targets.first_color : nullptr, &targets.mapped_colors[i]);
if (FAILED(list->recording_status)) return;
}
if (depth) {
list->recording_status = resolve_target(*list, *depth, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, targets.depth, nullptr,
&targets.mapped_depth, &targets.depth_writable);
if (FAILED(list->recording_status)) return;
}
targets.count = count;
targets.bind(*list->current());
list->targets = targets;
} catch (const std::bad_alloc&) { list->recording_status = E_OUTOFMEMORY; }
void WINAPI clear_color(List* list, D3D12_CPU_DESCRIPTOR_HANDLE target, const FLOAT color[4],
UINT count, const D3D12_RECT* rects) try {
if (FAILED(list->recording_status)) return;
if (list->closed || list->type != D3D12_COMMAND_LIST_TYPE_DIRECT || !color || (count && !rects)) {
list->recording_status = E_INVALIDARG;
return;
}
D3D12_CPU_DESCRIPTOR_HANDLE native{};
ID3D12Resource* source{};
std::shared_ptr<PlacedTexture> mapped;
list->recording_status = resolve_target(*list, target, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, native, &source, &mapped);
if (SUCCEEDED(list->recording_status)) {
if (mapped) list->mapped_targets[list->waits.size()][mapped] = true;
list->current()->ClearRenderTargetView(native, color, count, rects);
if (trace_frames_enabled())
trace_frame("rdna4rage: frame clear list=%p target=%p rgba=%g,%g,%g,%g rects=%u\n", static_cast<void*>(list),
static_cast<void*>(source), color[0], color[1], color[2], color[3], count);
}
} catch (const std::bad_alloc&) { list->recording_status = E_OUTOFMEMORY; }
void WINAPI clear_depth(List* list, D3D12_CPU_DESCRIPTOR_HANDLE target, D3D12_CLEAR_FLAGS flags, FLOAT depth,
UINT8 stencil, UINT count, const D3D12_RECT* rects) try {
if (FAILED(list->recording_status)) return;
constexpr UINT allowed = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL;
if (list->closed || list->type != D3D12_COMMAND_LIST_TYPE_DIRECT || !flags || (UINT(flags) & ~allowed) || (count && !rects)) {
list->recording_status = E_INVALIDARG;
return;
}
D3D12_CPU_DESCRIPTOR_HANDLE native{};
std::shared_ptr<PlacedTexture> mapped;
bool depth16{};
list->recording_status = resolve_target(*list, target, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, native, nullptr, &mapped, nullptr, &depth16);
if (SUCCEEDED(list->recording_status)) {
if (mapped) list->mapped_targets[list->waits.size()][mapped] = true;
list->current()->ClearDepthStencilView(native, flags, depth16 ? quantize_depth16(depth) : depth, stencil, count, rects);
}
} catch (const std::bad_alloc&) { list->recording_status = E_OUTOFMEMORY; }
// Keep the guest address reservation and Windows resource alive for the same GPU access.
struct CommittedBufferOwner {
ComPtr<ID3D12Resource> native;
ComPtr<IUnknown> address;
};
struct BufferLocation {
ID3D12Resource* native{};
UINT64 gpu{};
D3D12_RESOURCE_STATES state{D3D12_RESOURCE_STATE_COMMON};
std::shared_ptr<void> owner;
};
HRESULT buffer_location(Device* device, UINT64 address, UINT64 bytes, D3D12_RESOURCE_STATES use, BufferLocation& result) {
auto use_pages = [&](const std::shared_ptr<PlacedBuffer>& pages) {
if (!pages || address < pages->guest_address()) return false;
UINT64 offset = address - pages->guest_address();
auto* native = pages->native_range(offset, bytes);
if (!native || !pages->has_current_pages()) return false;
result = {native, native->GetGPUVirtualAddress() + offset, D3D12_RESOURCE_STATE_COMMON, pages};
return true;
};
if (use_pages(device->last_buffer_pages.lock())) return S_OK;
auto it = device->resources.upper_bound(address);
while (it != device->resources.begin()) {
const auto& [base, resource] = *--it;
if (resource->texture) continue;
if (resource->backing) {
if (use_pages(resource->backing)) return S_OK;
continue;
}
const UINT64 offset = address - base;
const UINT64 width = resource->host->GetDesc().Width;