Compare commits

...
Author SHA1 Message Date
Ateş f0a45544ee Merge pull request #809 from MacosPorters/track-c/dispatchx-copyresourcex
d3d12_xs: implement DispatchX and CopyResourceX
2026-12-02 14:46:20 +03:00
ates 123afb2e9a Merge remote-tracking branch 'origin/main' into track-c/dispatchx-copyresourcex
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	shims/d3d12_xs/xbox_tables_generated.cpp
2026-12-02 14:42:49 +03:00
Ateş b805b2bd81 Merge pull request #808 from MacosPorters/track-c/806-allocate-from-command-allocator
d3d12_xs: AllocateFromCommandAllocatorX returns memory instead of null (#806)
2026-12-02 14:42:35 +03:00
ates f120ecbc1c Merge remote-tracking branch 'origin/main' into track-c/806-allocate-from-command-allocator
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	shims/d3d12_xs/xbox_tables_generated.cpp
2026-12-02 14:40:55 +03:00
Ateş 3f0cce3b34 Merge pull request #801 from MacosPorters/track-c/782-lazy-texture-memory
d3d12_xs: map host memory for read-only placed textures at first use (#782)
2026-12-02 14:40:34 +03:00
ates b2a10cb233 Merge remote-tracking branch 'origin/main' into track-c/782-lazy-texture-memory
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-12-02 14:39:04 +03:00
Ateş 6797d664d2 Merge pull request #811 from MacosPorters/track-c/782-shadow-index
d3d12_xs: indexed lookups for title-memory host resources (#782)
2026-12-02 14:38:43 +03:00
ates 38e7a6e13f Merge remote-tracking branch 'origin/main' into track-c/782-shadow-index
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 14:38:33 +03:00
Ateş d891a17081 Merge pull request #810 from MacosPorters/track-c/value-wait-order
d3d12_xs: GPU value waits recorded after a write run after it
2026-12-02 14:38:26 +03:00
ates 6d8c0874ab d3d12_xs: DispatchX knows every GDK dispatch flag; CopyResourceX logs flags it does not apply
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 14:36:59 +03:00
ates 3e8805c986 d3d12_xs: index title-memory host resources (#782)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 14:29:10 +03:00
ates 95ea34eeb0 d3d12_xs: implement DispatchX and CopyResourceX
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 14:28:57 +03:00
ates 7beff3e8b6 d3d12_xs: AllocateFromCommandAllocatorX returns allocator-owned memory (#806)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 14:28:51 +03:00
ates 8a88e018a1 Merge remote-tracking branch 'origin/main' into track-c/782-lazy-texture-memory
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	shims/d3d12_xs/xbox_tables_generated.cpp
2026-12-02 11:39:06 +03:00
ates 0a71d3366b d3d12_xs: map host memory for read-only placed textures at first use (#782)
A read-only 2D texture of at least 64 KiB placed in title memory is now a reserved host resource with no memory. One heap holding all its tiles is mapped when its contents are first uploaded for a draw (on the submitting queue, ahead of the upload), or when a title's CopyTextureRegion(X), CopyResource or ResolveSubresource writes it (on the shim's own queue, waited for). The memory is released with the texture. CopyResource and ResolveSubresource get hand-written slots (tables regenerated with gen_xbox_tables.py). BX_LAZY_TEXTURES=0 restores committed textures; BX_LAZY_TEXTURES_MIN sets the threshold. New tests: test_d3d12_lazy_texture_memory and test_d3d12_console_texture_contents_reserved.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 07:34:17 +03:00
16 changed files with 1412 additions and 86 deletions

No files matched your search

+13
View File
@@ -18,6 +18,18 @@ remains unsupported.
- Tests: `test_stub_caller`, plus unit tests for the report and the lookup.
### Fixed
- **`DispatchX` and `CopyResourceX` are implemented.** Both Xbox command-list slots (80 and 86) were logging stubs. `DispatchX` forwards to `Dispatch`; with `USE_THREAD_DIMENSIONS` the counts are threads, so they are divided (rounding up) by the bound compute shader's `[numthreads]`, read from its `PSV0` part when the pipeline is created. A thread-count dispatch on a pipeline whose `[numthreads]` is unknown is logged and skipped rather than run with wrong counts; unknown flags are logged. `CopyResourceX` forwards to `CopyResource`. New `test_d3d12_dispatch_copy_x` (the `[numthreads]` conversion is not covered by it).
- **`AllocateFromCommandAllocatorX` returns memory instead of null (#806).** The Xbox command-list slot 148 was a logging stub. The GDK's ray-tracing BVH builder takes its upload buffer from it, and on null it throws an exception the target build does not catch, which ended the run through the title's crash reporter (exit status 99). The slot now returns aligned memory carved from 1 MiB chunks owned by the list's command allocator: the chunks are reused when the allocator is reset and freed when it is released, and a non-power-of-two alignment is refused and logged. New `test_d3d12_allocate_from_allocator`.
- **`d3d12_xs`: host memory for read-only placed textures is mapped at first use** (#782).
- **Before:** every texture a title placed got a full host copy at once. On the target build's Series S runs, 23,105 live host textures held 5.9 GB while translated draws read 16 of them (24 MB).
- **Now:** a read-only 2D texture of at least 64 KiB (not a render target, depth-stencil or UAV texture) is a reserved resource with no memory. One heap holding all its tiles is mapped:
- when its contents are first uploaded for a draw, on the submitting queue ahead of the upload;
- or when a title's `CopyTextureRegion(X)`, `CopyResource` or `ResolveSubresource` writes it, on a queue of the shim's own, waited for.
- **Unchanged:** the resource and its views stay the same, and unmapped tiles read as zero, as a texture never filled did before. The memory is released with the texture.
- **Measured:** on D3DMetal, 2,000 unmapped 1024×1024 BC1 textures add 9 MB, and 1.3 GB once mapped. On a Series S run of the target build the footprint at 2 minutes was 7.2 GB, against 12 GB before.
- **Settings:** `BX_LAZY_TEXTURES=0` restores committed textures; `BX_LAZY_TEXTURES_MIN` changes the 64 KiB threshold.
- **Generated tables:** `CopyResource` and `ResolveSubresource` now go through hand-written slots, regenerated with `gen_xbox_tables.py`.
- **Tests:** new `test_d3d12_lazy_texture_memory`, which also fails when a copy into a texture without memory is not mapped first; new `test_d3d12_console_texture_contents_reserved`, the texture-contents test with every texture reserved.
- **GPU value waits recorded after a write no longer run before it.** Since #791 every `WaitOnBitValueX`-family wait of a command list ran before the list. A title that makes two queues hand over to each other (one list writes a value and then waits for the other's, the other waits and then writes) therefore waited in a cycle that only the 10 s timeout broke, on every frame. Waits recorded before the list's first write still run in front of it; a wait recorded after a write now runs after the list's GPU work and those writes, and later writes are stored once that wait holds. `test_d3d12_gpu_value_order` gains the two-queue case.
- **`XCRDAPI`: the Xbox DirectStorage interfaces have the `dstorage_xs.h` slots, and a partial zlib read no longer allocates up to 2 GiB** (#769).
- **Factory** (`IDStorageFactoryX`/`X1`/`X2`): slot 3 `CreateQueue(DSTORAGE_QUEUE_DESC*)` creates a queue with auto-submit on, where it used to return `E_NOTIMPL`. Slot 6 is `SetCpuAffinity` and returns an HRESULT; it used to be a `void` `SetDebugFlags`. Slot 7 is `SetDebugFlags`. Slot 9 `GetStats` writes a zeroed 256-byte `DSTORAGE_STATS`, logged as a stub. Slot 10 is `CreateQueue1`, which also checks `DSTORAGE_PRIORITY`. Slots 11 and 12, which don't exist, are gone. `DStorageGetFactory` and `QueryInterface` accept all three factory IIDs.
@@ -64,6 +76,7 @@ remains unsupported.
- **`gfx10-translate`: scan all `XBCH` candidates and support version 2/3 payloads** (#721). `container_code` previously stopped at the first `b"XBCH"` byte sequence in a container, so incidental `b"XBCH"` bytes earlier in the blob (for example in `STAT` or `DXIL` bitcode) caused it to read garbage sizes and fail with `XBCH record: compressed size past the end`. It now scans all `b"XBCH"` occurrences, validates the 24-byte header, bounds, version (`2` uncompressed `FSSM`, `1` and `3` zlib-compressed `FSSM`), and `FSSM` magic, and skips non-matching candidates. Covered by synthetic unit tests in `gfx10_translate::container::tests`.
### Changed
- **`d3d12_xs` looks up title-memory host resources through indexes instead of scanning them all (#782).** A title can keep 100,000+ of them alive, and every view creation, root-buffer bind, texture-contents check, `Map` and submit-time sync scanned the whole table under one lock. Lookups by host pointer now use a hash map, lookups by address an ordered map (plus a short list of resources of 1 MiB or more), and the submit-time sync visits only mapped buffers. Behaviour is unchanged; the existing placed-memory and console tests cover every replaced lookup. On the target build's post-loading phase this roughly doubled the rate of view creation; creating the host resources themselves remains the larger cost there.
- **Open-source DXC (`dxcompiler.dll`) replaces the GDK's shader compiler as the primary source** (#757, ADR 0010).
- `.github/workflows/dxc-build.yml` builds x64 Release `dxcompiler.dll` from `microsoft/DirectXShaderCompiler` at pinned tag `v1.9.2609` on a Windows runner and uploads it as a workflow artifact.
- `bx-cli setup --dxc-dir <dir>` (and `BX_DXC_DIR`) records the local open-source DXC folder in `local.conf` (`dxc_dir`).
+2 -2
View File
@@ -351,7 +351,7 @@ void bx_console_submit(ID3D12CommandQueue* queue, ID3D12CommandList* const* host
if (draws.empty()) return;
UploadContext* ctx = queue ? upload_context(queue) : nullptr;
std::unique_lock<std::mutex> held;
BxTextureUploads uploads{nullptr, nullptr, 0, false};
BxTextureUploads uploads{nullptr, nullptr, 0, false, nullptr};
UINT turn = 0;
if (ctx) {
held = std::unique_lock<std::mutex>(ctx->lock);
@@ -361,7 +361,7 @@ void bx_console_submit(ID3D12CommandQueue* queue, ID3D12CommandList* const* host
WaitForSingleObject(ctx->event, 2000);
}
if (SUCCEEDED(ctx->allocators[turn]->Reset()) && SUCCEEDED(ctx->list->Reset(ctx->allocators[turn], nullptr))) {
uploads = BxTextureUploads{ctx->list, ctx->fence, ctx->next, false};
uploads = BxTextureUploads{ctx->list, ctx->fence, ctx->next, false, queue};
}
}
std::unordered_set<uint64_t> done; // entries written for this submission
+246
View File
@@ -25,6 +25,7 @@
#include "proxy.h"
#include "shader_gate.h"
#include <array>
#include <atomic>
#include <cstdio>
#include <cstring>
@@ -243,6 +244,42 @@ void log_extended(const char* kind, UINT count) {
* (null_render_skip), as every dispatch of untranslated compute is today. Serialized and derived
* pipelines still fail (refused_always_fail), so a title creates them from shaders instead.
*/
/*
* [numthreads] of compute pipelines, for DispatchX with USE_THREAD_DIMENSIONS (thread counts, not
* group counts). A DXIL container's PSV0 part carries it: a uint32 size, then PSVRuntimeInfo, whose
* version 2 adds NumThreadsX/Y/Z at byte 36 (after the 36 bytes of PSVRuntimeInfo1; public DXC
* DxilPipelineStateValidation.h, MIT; noted for console containers on #755).
*/
std::mutex g_threads_lock;
std::unordered_map<const void*, std::array<UINT, 3>> g_pipeline_threads; // host compute pipeline -> numthreads
std::unordered_map<const void*, const void*> g_list_pipeline; // host list -> bound host pipeline
bool psv0_numthreads(const void* bytes, size_t len, std::array<UINT, 3>* out) {
const auto* b = static_cast<const uint8_t*>(bytes);
auto u32 = [&](size_t at) {
uint32_t v = 0;
std::memcpy(&v, b + at, 4);
return v;
};
if (!b || len < 32 || std::memcmp(b, "DXBC", 4) != 0) return false;
const uint32_t count = u32(28);
if (count > 64 || 32 + 4ull * count > len) return false;
for (uint32_t i = 0; i < count; ++i) {
const uint32_t at = u32(32 + 4 * i);
if (at + 8ull > len || std::memcmp(b + at, "PSV0", 4) != 0) continue;
const uint32_t size = u32(at + 4);
if (at + 8ull + size > len || size < 4) return false;
const uint32_t info = u32(at + 8);
if (info < 48 || 4ull + 48 > size) return false;
const size_t base = at + 12;
(*out)[0] = u32(base + 36);
(*out)[1] = u32(base + 40);
(*out)[2] = u32(base + 44);
return (*out)[0] && (*out)[1] && (*out)[2];
}
return false;
}
HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
@@ -253,6 +290,11 @@ HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc
HRESULT hr = gate.admit("compute", "CS", desc->CS, admitted.CS);
if (SUCCEEDED(hr)) hr = device->CreateComputePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv, nullptr, true);
std::array<UINT, 3> threads{};
if (*ppv && psv0_numthreads(desc->CS.pShaderBytecode, desc->CS.BytecodeLength, &threads)) {
std::lock_guard<std::mutex> guard(g_threads_lock);
g_pipeline_threads[*ppv] = threads;
}
return bx_xbox_wrap_result(hr, riid, ppv);
}
@@ -349,11 +391,19 @@ bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title) {
}
void bx_xbox_pipeline_forget(IUnknown* host) {
{
std::lock_guard<std::mutex> threads(g_threads_lock);
g_pipeline_threads.erase(host);
}
std::lock_guard<std::mutex> guard(g_lock);
erase(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
}
void bx_xbox_list_forget(IUnknown* host) {
{
std::lock_guard<std::mutex> threads(g_threads_lock);
g_list_pipeline.erase(host);
}
bx_xbox_rect_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
bx_console_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
bx_console_descriptors_reset(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
@@ -413,6 +463,10 @@ void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12Pipelin
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &console);
set_list_null(list, is_null, std::move(console));
bx_xbox_rect_note_pipeline(list, host);
{
std::lock_guard<std::mutex> guard(g_threads_lock);
g_list_pipeline[list] = is_null ? nullptr : host;
}
if (!is_null) list->SetPipelineState(host);
}
@@ -427,6 +481,7 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator*
bx_console_descriptors_reset(list);
bx_xbox_bound_memory_reset(list);
bx_xbox_rect_list_reset(list, host);
bx_xbox_list_note_allocator(list, bx_xbox_unwrap_as(allocator));
return list->Reset(bx_xbox_unwrap_as(allocator), host);
}
@@ -458,6 +513,74 @@ void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z)
if (!list_skips(list, "Dispatch")) list->Dispatch(x, y, z);
}
/* DispatchX (GDK d3d12_xs.h): Dispatch plus D3D12XBOX_DISPATCH_FLAGS. Most flags steer the
console's wave launch (start at 0,0,0, ordered append, out-of-order waves, vector L1), which the
host does not have, so the dispatch is the PC one. USE_THREAD_DIMENSIONS (0x20) makes the counts
thread counts; turning them into group counts needs the bound shader's [numthreads], which this
layer does not know, so such a dispatch is skipped and logged rather than run with the wrong size. */
void STDMETHODCALLTYPE bx_xbox_list_dispatch_x(void* self, UINT x, UINT y, UINT z, UINT flags) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DispatchX");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (list_skips(list, "DispatchX")) return;
constexpr UINT kUseThreadDimensions = 0x20;
if (flags & kUseThreadDimensions) {
// Thread counts: groups = ceil(threads / [numthreads]) of the bound pipeline.
std::array<UINT, 3> n{};
bool known = false;
{
std::lock_guard<std::mutex> guard(g_threads_lock);
auto bound = g_list_pipeline.find(list);
if (bound != g_list_pipeline.end() && bound->second) {
auto t = g_pipeline_threads.find(bound->second);
if (t != g_pipeline_threads.end()) {
n = t->second;
known = true;
}
}
}
if (!known) {
BX_STUB_LOG("d3d12_xs.dll", "DispatchX(thread dimensions, [numthreads] unknown)");
return;
}
x = (x + n[0] - 1) / n[0];
y = (y + n[1] - 1) / n[1];
z = (z + n[2] - 1) / n[2];
// A partial last group runs whole: its extra threads are not masked (the shader's own bounds
// checks, if any, apply).
}
// Every flag the GDK header defines. Other than the thread dimensions they tune how the console
// GPU launches and caches waves (ordering, ordered append, volatile L1 lines, wave size) and have
// no host equivalent.
constexpr UINT kKnown = 0x04 | 0x08 | 0x10 | kUseThreadDimensions | 0x40 | 0x80 | 0x200 | 0x400 | 0x800 | 0x8000;
if (flags & ~kKnown) {
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "DispatchX flags 0x%x include bits this layer does not know; dispatched as Dispatch", flags);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "dispatch_x", detail);
}
}
list->Dispatch(x, y, z);
}
/* CopyResourceX (GDK d3d12_xs.h): CopyResource plus D3D12XBOX_COPY_FLAGS, which steer the console's
compression metadata only, as for CopyTextureRegionX. */
void STDMETHODCALLTYPE bx_xbox_list_copy_resource_x(void* self, ID3D12Resource* dst, ID3D12Resource* src, UINT flags) {
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyResourceX");
if (flags) {
// D3D12XBOX_COPY_FLAGS ask for console-side decompression, resummarizing or sample-to-red
// copies, which a plain host copy does not perform.
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
char detail[96];
std::snprintf(detail, sizeof(detail), "CopyResourceX flags 0x%x are not applied; copied as CopyResource", flags);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "copy_resource_x", detail);
}
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyResource(bx_xbox_unwrap_as<ID3D12Resource>(dst),
bx_xbox_unwrap_as<ID3D12Resource>(src));
}
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
ID3D12Resource* arguments, UINT64 arguments_offset,
ID3D12Resource* count, UINT64 count_offset) {
@@ -546,6 +669,129 @@ void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT, UINT, D3D12_GPU_VIR
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(1, &barrier);
}
} // extern "C"
/*
* Memory from a command allocator (#806). AllocateFromCommandAllocatorX (GDK d3d12_xs.h,
* ID3D12GraphicsCommandList8) returns memory "with the same lifetime as the associated command
* list" whose address "is a valid GPU pointer and may be cast to D3D12_GPU_VIRTUAL_ADDRESS"; null
* only when memory is unavailable. The target build's ray-tracing BVH builder (the GDK's XDXR
* builder) takes its upload buffer from it and throws when it gets null, which ended the process.
*
* Here the memory is plain CPU memory, carved from chunks owned by the list's command allocator.
* Its address reaches the GPU the way any title memory does: a root buffer in plain title memory
* gets a host buffer filled at submission (descriptor_heaps.cpp). A command allocator may only be
* reset once the GPU has finished its lists, so its chunks are reused then, and freed with it. A
* list whose allocator this layer did not see keeps a pool of its own until it is released.
*/
namespace {
struct AllocatorChunk {
uint8_t* base;
size_t size;
size_t used;
};
std::mutex g_allocator_memory_lock;
std::unordered_map<const void*, std::vector<AllocatorChunk>> g_allocator_memory; // allocator (or list) -> chunks
std::unordered_map<const void*, const void*> g_list_allocator; // host list -> host allocator
constexpr size_t kAllocatorChunkBytes = 1u << 20;
std::atomic<uint64_t> g_allocator_bytes{0};
void free_chunks_locked(const void* owner) {
auto it = g_allocator_memory.find(owner);
if (it == g_allocator_memory.end()) return;
for (const AllocatorChunk& c : it->second) {
g_allocator_bytes -= c.size;
VirtualFree(c.base, 0, MEM_RELEASE);
}
g_allocator_memory.erase(it);
}
} // namespace
void bx_xbox_list_note_allocator(const void* host_list, const void* host_allocator) {
if (!host_list || !host_allocator) return;
std::lock_guard<std::mutex> guard(g_allocator_memory_lock);
g_list_allocator[host_list] = host_allocator;
}
void bx_xbox_command_memory_forget(const void* host) {
std::lock_guard<std::mutex> guard(g_allocator_memory_lock);
free_chunks_locked(host);
g_list_allocator.erase(host);
}
extern "C" {
void* STDMETHODCALLTYPE bx_xbox_list_allocate_from_command_allocator_x(void* self, UINT size, UINT alignment) {
BX_D3D_TRACE("XboxGraphicsCommandList", "AllocateFromCommandAllocatorX");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
const size_t align = alignment ? alignment : 16;
if ((align & (align - 1)) != 0 || align > kAllocatorChunkBytes) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
char detail[128];
std::snprintf(detail, sizeof(detail), "alignment %u is not a power of two up to 1 MiB; null returned", alignment);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "allocate_from_allocator", detail);
}
return nullptr;
}
std::lock_guard<std::mutex> guard(g_allocator_memory_lock);
auto owner_it = g_list_allocator.find(list);
const void* owner = owner_it != g_list_allocator.end() ? owner_it->second : list;
if (owner == list) {
static std::atomic<bool> noted{false};
if (!noted.exchange(true)) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "allocate_from_allocator",
"a list whose command allocator was not seen: its memory is kept until the list is released");
}
}
std::vector<AllocatorChunk>& chunks = g_allocator_memory[owner];
for (AllocatorChunk& c : chunks) {
const size_t at = (reinterpret_cast<uintptr_t>(c.base) + c.used + align - 1) / align * align - reinterpret_cast<uintptr_t>(c.base);
if (at + size <= c.size) {
c.used = at + size;
return c.base + at;
}
}
const size_t bytes = size + align > kAllocatorChunkBytes ? (size + align + 0xFFFF) & ~static_cast<size_t>(0xFFFF)
: kAllocatorChunkBytes;
auto* base = static_cast<uint8_t*>(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!base) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "allocate_from_allocator", "VirtualAlloc failed; null returned");
return nullptr;
}
const uint64_t total = g_allocator_bytes.fetch_add(bytes) + bytes;
const size_t at = (reinterpret_cast<uintptr_t>(base) + align - 1) / align * align - reinterpret_cast<uintptr_t>(base);
chunks.push_back(AllocatorChunk{base, bytes, at + size});
static std::atomic<uint64_t> made{0};
const uint64_t n = ++made;
if ((n & (n - 1)) == 0) {
char detail[160];
std::snprintf(detail, sizeof(detail), "chunk of %zu bytes for a command allocator; chunks=%llu live_bytes=%llu", bytes,
static_cast<unsigned long long>(n), static_cast<unsigned long long>(total));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "allocate_from_allocator", detail);
}
return base + at;
}
HRESULT STDMETHODCALLTYPE bx_xbox_allocator_reset(void* self) {
BX_D3D_TRACE("XboxCommandAllocator", "Reset");
auto* allocator = bx_xbox_host<ID3D12CommandAllocator>(self);
const HRESULT hr = allocator->Reset();
if (FAILED(hr)) {
bx_xbox_log_host_failure("XboxCommandAllocator", "Reset", hr);
return hr;
}
// The GPU has finished every list recorded with this allocator: its memory can be handed out again.
std::lock_guard<std::mutex> guard(g_allocator_memory_lock);
auto it = g_allocator_memory.find(allocator);
if (it != g_allocator_memory.end()) {
for (AllocatorChunk& c : it->second) c.used = 0;
}
return hr;
}
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, UINT64) {
BX_D3D_TRACE("XboxCommandAllocator", "SetAllocatorCallbackX");
static std::atomic<bool> logged{false};
+380 -48
View File
@@ -27,9 +27,12 @@
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <vector>
#include <unordered_set>
#include <map>
#include <unordered_map>
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
@@ -47,8 +50,133 @@ struct Shadow {
bool implicit = false; // made for a view of placed memory (implicit_shadow); owned by this table
bool simultaneous = false; // texture made with D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS
uint64_t span = 0; // implicit: the bytes of title memory the resource covers
bool reserved = false; // texture made as a reserved resource: memory mapped at first use
};
/*
* Texture memory on first use (#782). The host copy of every texture a title places costs as much
* as the texture, but only the textures a draw reads ever get contents: on the target build's
* Series S runs, 23,105 live host textures held 5.9 GB while translated draws read 16 of them
* (24 MB). A read-only 2D texture of at least 64 KiB is therefore made as a reserved resource (no
* memory: 2,000 unmapped 1024x1024 BC1 textures add 9 MB on D3DMetal, mapped 1.3 GB). Its memory,
* one heap holding every tile, is mapped when its contents are first uploaded for a draw (on the
* submitting queue, ahead of the upload) or when a title's GPU copy or resolve writes it (on a
* queue of this layer's own, waited for). The resource and every view of it stay the same. Unmapped
* tiles read as zero, as a texture never filled did before. BX_LAZY_TEXTURES=0 makes every texture
* committed, as before.
*/
constexpr uint64_t kLazyTextureMinBytes = 64 * 1024;
/* The smallest texture made reserved: 64 KiB, one tile, unless BX_LAZY_TEXTURES_MIN (bytes) says
otherwise (a conformance test uses 0 to put small textures on this path). */
uint64_t lazy_texture_min_bytes() {
static const uint64_t min = [] {
char v[24] = {};
const DWORD n = GetEnvironmentVariableA("BX_LAZY_TEXTURES_MIN", v, sizeof(v));
return n > 0 && n < sizeof(v) ? std::strtoull(v, nullptr, 10) : kLazyTextureMinBytes;
}();
return min;
}
bool lazy_textures_enabled() {
static const bool on = [] {
char v[4] = {};
return !(GetEnvironmentVariableA("BX_LAZY_TEXTURES", v, sizeof(v)) > 0 && v[0] == '0');
}();
return on;
}
struct TextureMemory {
ID3D12Heap* heap = nullptr; // null until mapped
uint64_t bytes = 0;
};
std::mutex g_memory_lock;
std::unordered_map<const void*, TextureMemory> g_texture_memory; // reserved host texture -> its memory
std::atomic<uint64_t> g_reserved_made{0}, g_mapped_count{0}, g_mapped_bytes{0};
void note_texture_memory(const char* what) {
const uint64_t n = g_mapped_count.load();
char detail[200];
std::snprintf(detail, sizeof(detail), "%s; reserved=%llu mapped=%llu mapped_bytes=%llu", what,
static_cast<unsigned long long>(g_reserved_made.load()), static_cast<unsigned long long>(n),
static_cast<unsigned long long>(g_mapped_bytes.load()));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "texture_memory", detail);
}
/* Maps one heap behind every tile of reserved texture `host` on `queue`, once. g_memory_lock held. */
HRESULT map_texture_memory_locked(ID3D12CommandQueue* queue, ID3D12Resource* host, TextureMemory& memory) {
if (memory.heap) return S_FALSE;
ID3D12Device* device = nullptr;
if (FAILED(host->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return E_FAIL;
const D3D12_RESOURCE_DESC desc = host->GetDesc();
const UINT slices = desc.DepthOrArraySize ? desc.DepthOrArraySize : 1;
const UINT mips = desc.MipLevels ? desc.MipLevels : 1;
UINT total = 0, count = mips * slices;
D3D12_PACKED_MIP_INFO packed{};
D3D12_TILE_SHAPE shape{};
std::vector<D3D12_SUBRESOURCE_TILING> tiling(count);
device->GetResourceTiling(host, &total, &packed, &shape, &count, 0, tiling.data());
D3D12_HEAP_DESC heap_desc{};
heap_desc.SizeInBytes = static_cast<UINT64>(total) * D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES;
heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
ID3D12Heap* heap = nullptr;
HRESULT hr = total ? device->CreateHeap(&heap_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap)) : E_FAIL;
device->Release();
if (FAILED(hr) || !heap) return FAILED(hr) ? hr : E_OUTOFMEMORY;
// One region per standard subresource, and one per array slice for its packed mips; the heap's
// tiles follow in that order.
std::vector<D3D12_TILED_RESOURCE_COORDINATE> coords;
std::vector<D3D12_TILE_REGION_SIZE> sizes;
UINT used = 0;
for (UINT slice = 0; slice < slices; ++slice) {
for (UINT mip = 0; mip < mips; ++mip) {
const UINT sub = slice * mips + mip;
D3D12_TILE_REGION_SIZE size{};
if (mip < packed.NumStandardMips) {
size.NumTiles = tiling[sub].WidthInTiles * tiling[sub].HeightInTiles * tiling[sub].DepthInTiles;
} else if (mip == packed.NumStandardMips && packed.NumPackedMips) {
size.NumTiles = packed.NumTilesForPackedMips;
} else {
continue;
}
if (!size.NumTiles) continue;
coords.push_back(D3D12_TILED_RESOURCE_COORDINATE{0, 0, 0, sub});
sizes.push_back(size);
used += size.NumTiles;
}
}
if (used > total) {
heap->Release();
return E_UNEXPECTED;
}
const D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE;
const UINT start = 0, range = used;
queue->UpdateTileMappings(host, static_cast<UINT>(coords.size()), coords.data(), sizes.data(), heap, 1, &flags, &start,
&range, D3D12_TILE_MAPPING_FLAG_NONE);
memory.heap = heap;
memory.bytes = heap_desc.SizeInBytes;
const uint64_t before = g_mapped_count.fetch_add(1);
g_mapped_bytes += memory.bytes;
// Logged for the first 16 mappings, then whenever the count passes a power of two.
if (before < 16 || (before & (before + 1)) == 0) note_texture_memory("texture memory mapped at first use");
return S_OK;
}
/* The memory of a reserved texture being released (or of a texture this layer drops). */
void release_texture_memory(const void* host) {
ID3D12Heap* heap = nullptr;
{
std::lock_guard<std::mutex> guard(g_memory_lock);
auto it = g_texture_memory.find(host);
if (it == g_texture_memory.end()) return;
heap = it->second.heap;
if (heap) g_mapped_bytes -= it->second.bytes;
g_texture_memory.erase(it);
}
if (heap) heap->Release();
}
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
if (!s.buffer || end <= begin || end > s.size) return false;
@@ -69,6 +197,83 @@ Shadow* g_shadows = nullptr;
size_t g_count = 0;
size_t g_capacity = 0;
/*
* Indexes over g_shadows (all under g_lock). A title can keep 100,000+ shadows alive (the target
* build makes views of new addresses every frame), and every view creation, root-buffer bind,
* texture-contents check and Map looked one up by scanning the whole array: on the target build's
* post-loading phase that held g_lock for most of each frame. Lookups by host pointer go through a
* hash map; lookups by title address through an ordered map of the shadows smaller than 1 MiB (one
* that holds or overlaps an address starts at most 1 MiB before it) plus a short list of the larger
* ones; buffers with outstanding Map calls are kept in a set for the per-submission sync.
*/
constexpr uint64_t kSmallExtent = 1ull << 20;
std::unordered_map<const void*, size_t> g_by_host;
std::multimap<uint64_t, const void*> g_by_va_small; // title_va -> host
std::vector<const void*> g_large; // hosts of shadows of 1 MiB or more
std::unordered_set<const void*> g_mapped_hosts; // shadows with outstanding Map calls
uint64_t extent_of(const Shadow& s) { return s.size > s.span ? s.size : s.span; }
void index_add_locked(size_t i) {
const Shadow& s = g_shadows[i];
g_by_host[s.host] = i;
if (extent_of(s) >= kSmallExtent) g_large.push_back(s.host);
else g_by_va_small.emplace(s.title_va, s.host);
}
void index_drop_locked(const Shadow& s) {
auto range = g_by_va_small.equal_range(s.title_va);
for (auto it = range.first; it != range.second; ++it) {
if (it->second == s.host) {
g_by_va_small.erase(it);
break;
}
}
for (size_t k = 0; k < g_large.size(); ++k) {
if (g_large[k] == s.host) {
g_large[k] = g_large.back();
g_large.pop_back();
break;
}
}
}
// Removes shadow i (swapped with the last) and keeps the indexes in step. g_lock must be held.
void remove_at_locked(size_t i) {
const Shadow gone = g_shadows[i];
index_drop_locked(gone);
g_by_host.erase(gone.host);
g_mapped_hosts.erase(gone.host);
--g_count;
if (i != g_count) {
g_shadows[i] = g_shadows[g_count];
g_by_host[g_shadows[i].host] = i;
}
}
size_t find_host_locked(const void* host) {
auto it = g_by_host.find(host);
return it == g_by_host.end() ? SIZE_MAX : it->second;
}
// Calls f(index) for every shadow that may overlap [lo, hi) (f checks exactly); stops when f returns true.
template <typename F>
void for_candidates_locked(uint64_t lo, uint64_t hi, F f) {
const uint64_t from = lo > kSmallExtent ? lo - kSmallExtent : 0;
std::vector<size_t> hits;
for (auto it = g_by_va_small.lower_bound(from); it != g_by_va_small.end() && it->first < hi; ++it) {
const size_t i = find_host_locked(it->second);
if (i != SIZE_MAX) hits.push_back(i);
}
for (const void* h : g_large) {
const size_t i = find_host_locked(h);
if (i != SIZE_MAX) hits.push_back(i);
}
for (size_t i : hits) {
if (f(i)) return;
}
}
bool remember(const Shadow& shadow) {
std::lock_guard<std::mutex> guard(g_lock);
if (g_count == g_capacity) {
@@ -81,6 +286,7 @@ bool remember(const Shadow& shadow) {
g_capacity = capacity;
}
g_shadows[g_count++] = shadow;
index_add_locked(g_count - 1);
return true;
}
@@ -117,10 +323,46 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
const bool simultaneous = !buffer && host_desc.SampleDesc.Count <= 1 && !(static_cast<UINT>(host_desc.Flags) & kGpuWrites);
if (simultaneous) host_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
ID3D12Resource* resource = nullptr;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
bool made_simultaneous = simultaneous && SUCCEEDED(hr);
if (simultaneous && FAILED(hr)) { // the host refuses the flag: without it, uploads use barriers from COMMON
HRESULT hr = E_FAIL;
bool made_simultaneous = false;
bool reserved = false;
// A read-only 2D texture of at least 64 KiB: reserved, its memory mapped at first use.
if (simultaneous && lazy_textures_enabled() && host_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D &&
host_desc.SampleDesc.Count <= 1) {
const UINT subs = (host_desc.MipLevels ? host_desc.MipLevels : 1) * (host_desc.DepthOrArraySize ? host_desc.DepthOrArraySize : 1);
UINT64 packed_bytes = 0;
device->GetCopyableFootprints(&host_desc, 0, subs, 0, nullptr, nullptr, nullptr, &packed_bytes);
if (packed_bytes >= lazy_texture_min_bytes()) {
D3D12_RESOURCE_DESC reserved_desc = host_desc;
reserved_desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
hr = device->CreateReservedResource(&reserved_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(&resource));
made_simultaneous = SUCCEEDED(hr);
if (FAILED(hr)) {
reserved_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(reserved_desc.Flags & ~D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS);
hr = device->CreateReservedResource(&reserved_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(&resource));
}
reserved = SUCCEEDED(hr) && resource;
if (!reserved) {
static std::atomic<bool> noted{false};
if (!noted.exchange(true)) {
char detail[160];
std::snprintf(detail, sizeof(detail), "the host refused a reserved texture (hr=0x%08lx); textures are committed",
static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_memory", detail);
}
} else if (g_reserved_made.fetch_add(1) == 0) {
note_texture_memory("read-only textures of 64 KiB or more are reserved; memory is mapped at first use");
}
}
}
if (!reserved) {
hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
made_simultaneous = simultaneous && SUCCEEDED(hr);
}
if (simultaneous && !reserved && FAILED(hr)) { // the host refuses the flag: without it, uploads use barriers from COMMON
static std::atomic<bool> noted{false};
if (!noted.exchange(true)) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "the host refuses simultaneous access on a texture; made without it");
@@ -154,7 +396,13 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
}
Shadow record{resource, title_va, desc.Width, buffer, desc, 0};
record.simultaneous = made_simultaneous;
record.reserved = reserved;
if (reserved) {
std::lock_guard<std::mutex> guard(g_memory_lock);
g_texture_memory[resource] = TextureMemory{};
}
if (!remember(record)) {
release_texture_memory(resource);
resource->Release();
return E_OUTOFMEMORY;
}
@@ -210,29 +458,35 @@ ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D
std::vector<ID3D12Resource*> replaced;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
}
for (size_t i = 0; i < g_count;) {
ID3D12Resource* same = nullptr;
std::vector<const void*> overlapping;
for_candidates_locked(title_va, title_va + span, [&](size_t i) {
const Shadow& s = g_shadows[i];
if (s.implicit && title_va < s.title_va + s.span && s.title_va < title_va + span) {
replaced.push_back(s.host);
g_shadows[i] = g_shadows[--g_count];
} else {
++i;
if (s.title_va == title_va && same_shape(s.desc, desc)) {
same = s.host;
return true;
}
if (s.implicit && title_va < s.title_va + s.span && s.title_va < title_va + span) overlapping.push_back(s.host);
return false;
});
if (same) return same;
for (const void* h : overlapping) {
const size_t i = find_host_locked(h);
if (i == SIZE_MAX) continue;
replaced.push_back(g_shadows[i].host);
remove_at_locked(i);
}
}
if (!replaced.empty()) retire_implicit(replaced);
ID3D12Resource* resource = nullptr;
if (FAILED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource))) return nullptr;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = g_count; i-- > 0;) {
if (g_shadows[i].host == resource) {
g_shadows[i].implicit = true;
g_shadows[i].span = span;
break;
}
const size_t i = find_host_locked(resource);
if (i != SIZE_MAX) {
index_drop_locked(g_shadows[i]); // its extent changes with the span
g_shadows[i].implicit = true;
g_shadows[i].span = span;
index_add_locked(i);
}
return resource;
}
@@ -483,6 +737,7 @@ void sweep_implicit() {
for (ID3D12Resource* host : release) {
bx_console_forget_resource(host);
host->Release();
release_texture_memory(host);
}
const uint64_t before = g_implicit_released_total.fetch_add(release.size());
const uint64_t after = before + release.size();
@@ -612,14 +867,16 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Reso
bool bx_xbox_try_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title, D3D12_GPU_VIRTUAL_ADDRESS* host) {
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
bool found = false;
for_candidates_locked(title, title + 1, [&](size_t i) {
const Shadow& s = g_shadows[i];
if (title >= s.title_va && title < s.title_va + s.size) {
*host = s.host->GetGPUVirtualAddress() + (title - s.title_va);
return true;
found = true;
}
}
return false;
return found;
});
return found;
}
/*
@@ -645,11 +902,13 @@ std::unordered_map<const void*, std::vector<BoundRange>> g_bound; // host list
// The index of a buffer shadow that holds the whole range, or SIZE_MAX. g_lock must be held.
size_t buffer_holding_locked(uint64_t va, uint64_t size) {
for (size_t i = 0; i < g_count; ++i) {
size_t found = SIZE_MAX;
for_candidates_locked(va, va + (size ? size : 1), [&](size_t i) {
const Shadow& s = g_shadows[i];
if (s.buffer && va >= s.title_va && va + size <= s.title_va + s.size) return i;
}
return SIZE_MAX;
if (s.buffer && va >= s.title_va && va + size <= s.title_va + s.size) found = i;
return found != SIZE_MAX;
});
return found;
}
} // namespace
@@ -725,11 +984,17 @@ void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT cou
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
if (!title) return title;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
D3D12_GPU_VIRTUAL_ADDRESS out = title; // not a title address this layer knows: a host address already, or untranslated
bool found = false;
for_candidates_locked(title, title + 1, [&](size_t i) {
const Shadow& s = g_shadows[i];
if (title >= s.title_va && title < s.title_va + s.size) return s.host->GetGPUVirtualAddress() + (title - s.title_va);
}
return title; // not a title address this layer knows: a host address already, or untranslated
if (title >= s.title_va && title < s.title_va + s.size) {
out = s.host->GetGPUVirtualAddress() + (title - s.title_va);
found = true;
}
return found;
});
return out;
}
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes) {
@@ -737,14 +1002,59 @@ bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64
attributes});
}
void bx_xbox_texture_memory_for_write(ID3D12Resource* host) {
if (!host) return;
{
std::lock_guard<std::mutex> guard(g_memory_lock);
auto it = g_texture_memory.find(host);
if (it == g_texture_memory.end() || it->second.heap) return;
}
// A GPU write into a reserved texture without memory would be dropped. The title's list runs
// later on a queue of its own, so the mapping is made on this layer's queue and waited for.
static std::mutex queue_lock;
static ID3D12CommandQueue* queue = nullptr;
static ID3D12Fence* fence = nullptr;
static UINT64 value = 0;
std::lock_guard<std::mutex> serial(queue_lock);
if (!queue) {
ID3D12Device* device = nullptr;
if (SUCCEEDED(host->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) && device) {
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
if (FAILED(device->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&queue)))) queue = nullptr;
if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence)))) fence = nullptr;
device->Release();
}
}
HRESULT hr = E_FAIL;
if (queue && fence) {
std::lock_guard<std::mutex> guard(g_memory_lock);
auto it = g_texture_memory.find(host);
hr = it == g_texture_memory.end() ? S_FALSE : map_texture_memory_locked(queue, host, it->second);
}
if (hr == S_OK) {
queue->Signal(fence, ++value);
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (done && SUCCEEDED(fence->SetEventOnCompletion(value, done))) WaitForSingleObject(done, 2000);
if (done) CloseHandle(done);
} else if (FAILED(hr)) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[160];
std::snprintf(detail, sizeof(detail), "texture memory for a GPU write not mapped (hr=0x%08lx); the write is lost",
static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_memory", detail);
}
}
}
ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads* uploads) {
if (!uploads || !uploads->list) return host;
Shadow shadow{};
{
std::lock_guard<std::mutex> guard(g_lock);
size_t i = 0;
while (i < g_count && g_shadows[i].host != host) ++i;
if (i == g_count || g_shadows[i].buffer) return host;
const size_t i = find_host_locked(host);
if (i == SIZE_MAX || g_shadows[i].buffer) return host;
shadow = g_shadows[i];
}
const TextureKind kind = texture_kind(shadow.desc);
@@ -819,6 +1129,26 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
known.rows.data(), static_cast<UINT>(known.footprints.size()), &subresources);
}
}
if (hr == S_OK && shadow.reserved) {
// Texture memory on first use: mapped on the submitting queue, which executes the upload
// list after it.
HRESULT mapped = E_FAIL;
if (uploads->queue) {
std::lock_guard<std::mutex> guard(g_memory_lock);
auto it = g_texture_memory.find(host);
mapped = it == g_texture_memory.end() ? E_UNEXPECTED : map_texture_memory_locked(uploads->queue, host, it->second);
}
if (FAILED(mapped)) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[160];
std::snprintf(detail, sizeof(detail), "texture memory not mapped (hr=0x%08lx); contents not uploaded",
static_cast<unsigned long>(mapped));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_memory", detail);
}
hr = mapped;
}
}
if (hr == S_OK) {
ID3D12GraphicsCommandList* list = uploads->list;
// A simultaneous-access shadow is promoted from COMMON by the copy and decays back after
@@ -880,12 +1210,10 @@ void bx_xbox_placed_forget(IUnknown* host) {
Shadow gone{};
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (static_cast<IUnknown*>(g_shadows[i].host) == host) {
gone = g_shadows[i];
g_shadows[i] = g_shadows[--g_count];
break;
}
const size_t i = find_host_locked(host);
if (i != SIZE_MAX) {
gone = g_shadows[i];
remove_at_locked(i);
}
}
{
@@ -896,6 +1224,7 @@ void bx_xbox_placed_forget(IUnknown* host) {
g_texture_uploads.erase(upload);
}
}
release_texture_memory(host);
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
}
@@ -904,9 +1233,8 @@ D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_add
auto* host = bx_xbox_host<ID3D12Resource>(self);
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].host == host) return g_shadows[i].title_va;
}
const size_t i = find_host_locked(host);
if (i != SIZE_MAX) return g_shadows[i].title_va;
}
return host->GetGPUVirtualAddress();
}
@@ -989,14 +1317,15 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subre
uint64_t title_va = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const size_t i = find_host_locked(host);
if (i != SIZE_MAX) {
Shadow& s = g_shadows[i];
if (s.host != host) continue;
title_va = s.title_va;
// Make GPU results visible: refresh the read range of title memory from the host.
const uint64_t begin = read ? read->Begin : 0, end = read ? read->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
++s.mapped;
g_mapped_hosts.insert(s.host);
}
}
if (!title_va) {
@@ -1020,13 +1349,14 @@ extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subres
auto* host = bx_xbox_host<ID3D12Resource>(self);
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const size_t i = find_host_locked(host);
if (i != SIZE_MAX) {
Shadow& s = g_shadows[i];
if (s.host != host) continue;
// Hand the CPU's writes to the host resource (a null range means all of it).
const uint64_t begin = written ? written->Begin : 0, end = written ? written->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
if (s.mapped > 0) --s.mapped;
if (!s.mapped) g_mapped_hosts.erase(s.host);
return;
}
}
@@ -1040,7 +1370,9 @@ extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subres
void bx_xbox_sync_mapped_buffers() {
constexpr uint64_t kLimit = 16ull << 20;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
for (const void* h : g_mapped_hosts) {
const size_t i = find_host_locked(h);
if (i == SIZE_MAX) continue;
const Shadow& s = g_shadows[i];
if (!s.mapped || !s.buffer) continue;
if (s.size > kLimit) {
+7 -1
View File
@@ -107,12 +107,16 @@ CUSTOM = {
"CopyPageMappingsX": "bx_xbox_queue_copy_page_mappings_x",
"ClearPageMappingsX": "bx_xbox_queue_clear_page_mappings_x",
"ExecuteCommandLists2X": "bx_xbox_queue_execute_command_lists2_x"},
"CommandAllocator": {"SetAllocatorCallbackX": "bx_xbox_allocator_set_callback_x"},
"CommandAllocator": {"SetAllocatorCallbackX": "bx_xbox_allocator_set_callback_x",
"Reset": "bx_xbox_allocator_reset"},
"DescriptorHeap": {"GetCPUDescriptorHandleForHeapStart": "bx_xbox_heap_cpu_start",
"GetGPUDescriptorHandleForHeapStart": "bx_xbox_heap_gpu_start"},
"GraphicsCommandList": {"ResourceBarrier": "bx_xbox_list_resource_barrier",
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
"CopyResource": "bx_xbox_list_copy_resource",
"ResolveSubresource": "bx_xbox_list_resolve_subresource",
"CopyTextureRegionX": "bx_xbox_list_copy_texture_region_x",
"AllocateFromCommandAllocatorX": "bx_xbox_list_allocate_from_command_allocator_x",
"Barrier": "bx_xbox_list_barrier",
"BeginRenderPass": "bx_xbox_list_begin_render_pass",
"DispatchRays": "bx_xbox_list_dispatch_rays",
@@ -141,6 +145,8 @@ CUSTOM = {
"DrawInstanced": "bx_xbox_list_draw_instanced",
"DrawIndexedInstanced": "bx_xbox_list_draw_indexed_instanced",
"Dispatch": "bx_xbox_list_dispatch",
"DispatchX": "bx_xbox_list_dispatch_x",
"CopyResourceX": "bx_xbox_list_copy_resource_x",
"ExecuteIndirect": "bx_xbox_list_execute_indirect"},
}
SHARED = {"QueryInterface": "bx_xbox_query_interface", "AddRef": "bx_xbox_add_ref",
+21
View File
@@ -236,6 +236,9 @@ ULONG STDMETHODCALLTYPE bx_xbox_release(void* self) {
erase_locked(object);
guard.unlock();
if (object->iface == &bx_xbox_Resource) bx_xbox_placed_forget(object->host);
if (object->iface == &bx_xbox_CommandAllocator || object->iface == &bx_xbox_GraphicsCommandList) {
bx_xbox_command_memory_forget(object->host);
}
if (object->iface == &bx_xbox_DescriptorHeap) bx_xbox_descriptor_heap_forget(object->host);
if (object->iface == &bx_xbox_Fence) bx_xbox_fence_forget(object->host);
if (object->iface == &bx_xbox_PipelineState) bx_xbox_pipeline_forget(object->host);
@@ -290,6 +293,7 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const
desc->NodeMask, desc->Type, bx_xbox_unwrap_as(allocator),
bx_xbox_pipeline_is_null(initial_state) ? nullptr : bx_xbox_unwrap_as(initial_state), riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateCommandListX", hr);
if (SUCCEEDED(hr) && *ppv) bx_xbox_list_note_allocator(*ppv, bx_xbox_unwrap_as(allocator));
return bx_xbox_wrap_result(hr, riid, ppv);
}
@@ -330,6 +334,7 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_
if (dst) {
d = *dst;
d.pResource = bx_xbox_unwrap_as(d.pResource);
bx_xbox_texture_memory_for_write(d.pResource);
}
if (src) {
s = *src;
@@ -338,6 +343,22 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
}
void STDMETHODCALLTYPE bx_xbox_list_copy_resource(void* self, ID3D12Resource* dst, ID3D12Resource* src) {
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyResource");
ID3D12Resource* d = bx_xbox_unwrap_as<ID3D12Resource>(dst);
bx_xbox_texture_memory_for_write(d);
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyResource(d, bx_xbox_unwrap_as<ID3D12Resource>(src));
}
void STDMETHODCALLTYPE bx_xbox_list_resolve_subresource(void* self, ID3D12Resource* dst, UINT dst_sub, ID3D12Resource* src,
UINT src_sub, DXGI_FORMAT format) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ResolveSubresource");
ID3D12Resource* d = bx_xbox_unwrap_as<ID3D12Resource>(dst);
bx_xbox_texture_memory_for_write(d);
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResolveSubresource(d, dst_sub, bx_xbox_unwrap_as<ID3D12Resource>(src), src_sub,
format);
}
/* CopyTextureRegionX (GDK d3d12_xs.h): CopyTextureRegion plus D3D12XBOX_COPY_FLAGS, which only
steer the console's compression metadata (HTILE resummarize, forced decompress, clear
propagation). The host keeps no such metadata, so the copy is the PC one. Leaving the call a
+16 -1
View File
@@ -230,6 +230,10 @@ bool bx_xbox_bind_title_memory(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUA
void bx_xbox_bound_memory_reset(IUnknown* host_list);
void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT count);
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
/* Command-allocator memory (pipelines.cpp, #806): which allocator a host list records with, and
the release of an allocator's (or a list's own) memory. */
void bx_xbox_list_note_allocator(const void* host_list, const void* host_allocator);
void bx_xbox_command_memory_forget(const void* host);
void bx_xbox_descriptor_heap_forget(IUnknown* host);
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes);
@@ -239,7 +243,8 @@ struct BxTextureUploads {
ID3D12GraphicsCommandList* list;
ID3D12Fence* fence;
UINT64 value;
bool recorded; // set when a copy was recorded on `list`
bool recorded; // set when a copy was recorded on `list`
ID3D12CommandQueue* queue; // the submitting queue: texture memory is mapped on it first
};
/* The resource a view of `host` should read so that it sees the texture's contents in title memory
(placed_x.cpp, #745): for a texture placed in title memory, a copy of its host texture filled
@@ -248,6 +253,9 @@ struct BxTextureUploads {
backed-off interval); `host` itself for everything else, without `uploads`, and until a copy
has been recorded (failures are logged). */
ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads* uploads);
/* Before a title's GPU copy or resolve writes `host` (a host resource): a texture whose memory is
mapped at first use (placed_x.cpp, #782) gets it now, so the write is kept. */
void bx_xbox_texture_memory_for_write(ID3D12Resource* host);
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
@@ -321,11 +329,15 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocato
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT sync_flags, UINT control_flags, D3D12_GPU_VIRTUAL_ADDRESS base,
SIZE_T size);
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void* self, void* callback, UINT64 context);
void* STDMETHODCALLTYPE bx_xbox_list_allocate_from_command_allocator_x(void* self, UINT size, UINT alignment);
HRESULT STDMETHODCALLTYPE bx_xbox_allocator_reset(void* self);
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance);
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
INT base_vertex, UINT first_instance);
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z);
void STDMETHODCALLTYPE bx_xbox_list_dispatch_x(void* self, UINT x, UINT y, UINT z, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_copy_resource_x(void* self, ID3D12Resource* dst, ID3D12Resource* src, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
ID3D12Resource* arguments, UINT64 arguments_offset,
ID3D12Resource* count, UINT64 count_offset);
@@ -471,6 +483,9 @@ void bx_xbox_placed_note_submission();
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers);
void STDMETHODCALLTYPE bx_xbox_list_copy_resource(void* self, ID3D12Resource* dst, ID3D12Resource* src);
void STDMETHODCALLTYPE bx_xbox_list_resolve_subresource(void* self, ID3D12Resource* dst, UINT dst_sub, ID3D12Resource* src,
UINT src_sub, DXGI_FORMAT format);
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box);
+8 -28
View File
@@ -964,12 +964,6 @@ static HRESULT STDMETHODCALLTYPE x_CommandAllocator_6(void* self, const WCHAR *
if (FAILED(hr)) bx_xbox_log_host_failure("XboxCommandAllocator", "SetName", hr);
return hr;
}
static HRESULT STDMETHODCALLTYPE x_CommandAllocator_8(void* self) {
BX_D3D_TRACE("XboxCommandAllocator", "Reset");
HRESULT hr = bx_xbox_host<ID3D12CommandAllocator>(self)->Reset();
if (FAILED(hr)) bx_xbox_log_host_failure("XboxCommandAllocator", "Reset", hr);
return hr;
}
const void* const kCommandAllocatorTable[] = {
reinterpret_cast<const void*>(&bx_xbox_query_interface),
@@ -980,7 +974,7 @@ const void* const kCommandAllocatorTable[] = {
reinterpret_cast<const void*>(&x_CommandAllocator_5),
reinterpret_cast<const void*>(&x_CommandAllocator_6),
reinterpret_cast<const void*>(&bx_xbox_get_device),
reinterpret_cast<const void*>(&x_CommandAllocator_8),
reinterpret_cast<const void*>(&bx_xbox_allocator_reset),
reinterpret_cast<const void*>(&bx_xbox_allocator_set_callback_x),
};
@@ -991,7 +985,7 @@ const IID kCommandAllocatorIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12CommandAllocator: 10 slots (5 forwarded, 5 shared, 0 stubs); hosted on ID3D12CommandAllocator. */
/* ID3D12CommandAllocator: 10 slots (4 forwarded, 6 shared, 0 stubs); hosted on ID3D12CommandAllocator. */
const IID kHostCommandAllocator = __uuidof(ID3D12CommandAllocator);
static HRESULT STDMETHODCALLTYPE x_QueryHeap_3(void* self, REFGUID a0, UINT * a1, void * a2) {
@@ -1268,18 +1262,10 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_15(void* self, ID3D12Resourc
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyBufferRegion");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyBufferRegion(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_unwrap_as<ID3D12Resource>(a2), a3, a4);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_17(void* self, ID3D12Resource * a0, ID3D12Resource * a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyResource");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyResource(bx_xbox_unwrap_as<ID3D12Resource>(a0), bx_xbox_unwrap_as<ID3D12Resource>(a1));
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_18(void* self, ID3D12Resource * a0, const D3D12_TILED_RESOURCE_COORDINATE * a1, const D3D12_TILE_REGION_SIZE * a2, ID3D12Resource * a3, UINT64 a4, D3D12_TILE_COPY_FLAGS a5) {
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyTiles");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTiles(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, a2, bx_xbox_unwrap_as<ID3D12Resource>(a3), a4, a5);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_19(void* self, ID3D12Resource * a0, UINT a1, ID3D12Resource * a2, UINT a3, DXGI_FORMAT a4) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ResolveSubresource");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResolveSubresource(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_unwrap_as<ID3D12Resource>(a2), a3, a4);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_21(void* self, UINT a0, const D3D12_VIEWPORT * a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "RSSetViewports");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->RSSetViewports(a0, a1);
@@ -1431,8 +1417,6 @@ static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_78(void*) { BX_VTABLE_STUB
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_79(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 79u, "ReadGDSX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_80(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 80u, "DispatchX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_81(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 81u, "SetHiStencilStateX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_82(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 82u, "RSSetMSAAParametersX"); return 0; }
@@ -1441,8 +1425,6 @@ static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_83(void*) { BX_VTABLE_STUB
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_84(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 84u, "NopX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_86(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 86u, "CopyResourceX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_87(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 87u, "Deprecated_SetPredicationBufferX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_88(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 88u, "Deprecated_AdvancePredicationX"); return 0; }
@@ -1577,8 +1559,6 @@ static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_145(void*) { BX_VTABLE_STU
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_147(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 147u, "OMSetFrontAndBackStencilRef"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_148(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 148u, "AllocateFromCommandAllocatorX"); return 0; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_GraphicsCommandList_149(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 149u, "RehydrateRaytracingAccelerationStructureBatchedX"); return E_NOTIMPL; }
const void* const kGraphicsCommandListTable[] = {
@@ -1599,9 +1579,9 @@ const void* const kGraphicsCommandListTable[] = {
reinterpret_cast<const void*>(&bx_xbox_list_dispatch),
reinterpret_cast<const void*>(&x_GraphicsCommandList_15),
reinterpret_cast<const void*>(&bx_xbox_list_copy_texture_region),
reinterpret_cast<const void*>(&x_GraphicsCommandList_17),
reinterpret_cast<const void*>(&bx_xbox_list_copy_resource),
reinterpret_cast<const void*>(&x_GraphicsCommandList_18),
reinterpret_cast<const void*>(&x_GraphicsCommandList_19),
reinterpret_cast<const void*>(&bx_xbox_list_resolve_subresource),
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_primitive_topology),
reinterpret_cast<const void*>(&x_GraphicsCommandList_21),
reinterpret_cast<const void*>(&x_GraphicsCommandList_22),
@@ -1662,13 +1642,13 @@ const void* const kGraphicsCommandListTable[] = {
reinterpret_cast<const void*>(&x_GraphicsCommandList_77),
reinterpret_cast<const void*>(&x_GraphicsCommandList_78),
reinterpret_cast<const void*>(&x_GraphicsCommandList_79),
reinterpret_cast<const void*>(&x_GraphicsCommandList_80),
reinterpret_cast<const void*>(&bx_xbox_list_dispatch_x),
reinterpret_cast<const void*>(&x_GraphicsCommandList_81),
reinterpret_cast<const void*>(&x_GraphicsCommandList_82),
reinterpret_cast<const void*>(&x_GraphicsCommandList_83),
reinterpret_cast<const void*>(&x_GraphicsCommandList_84),
reinterpret_cast<const void*>(&bx_xbox_list_copy_texture_region_x),
reinterpret_cast<const void*>(&x_GraphicsCommandList_86),
reinterpret_cast<const void*>(&bx_xbox_list_copy_resource_x),
reinterpret_cast<const void*>(&x_GraphicsCommandList_87),
reinterpret_cast<const void*>(&x_GraphicsCommandList_88),
reinterpret_cast<const void*>(&x_GraphicsCommandList_89),
@@ -1730,7 +1710,7 @@ const void* const kGraphicsCommandListTable[] = {
reinterpret_cast<const void*>(&x_GraphicsCommandList_145),
reinterpret_cast<const void*>(&bx_xbox_list_barrier),
reinterpret_cast<const void*>(&x_GraphicsCommandList_147),
reinterpret_cast<const void*>(&x_GraphicsCommandList_148),
reinterpret_cast<const void*>(&bx_xbox_list_allocate_from_command_allocator_x),
reinterpret_cast<const void*>(&x_GraphicsCommandList_149),
};
@@ -1749,7 +1729,7 @@ const IID kGraphicsCommandListIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12GraphicsCommandList8: 150 slots (55 forwarded, 36 shared, 59 stubs); hosted on ID3D12GraphicsCommandList7. */
/* ID3D12GraphicsCommandList8: 150 slots (53 forwarded, 41 shared, 56 stubs); hosted on ID3D12GraphicsCommandList7. */
const IID kHostGraphicsCommandList = __uuidof(ID3D12GraphicsCommandList7);
} // namespace
@@ -0,0 +1,5 @@
# AllocateFromCommandAllocatorX returns memory with the command list's lifetime (#806). Needs a host
# with the Xbox-layout device interface; skips without.
add_executable(test_d3d12_allocate_from_allocator main.cpp)
target_compile_definitions(test_d3d12_allocate_from_allocator PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_allocate_from_allocator PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,166 @@
/*
* Conformance test: ID3D12GraphicsCommandList8::AllocateFromCommandAllocatorX (#806).
*
* Contract (authorized GDK d3d12_xs.h and its reference page): void* AllocateFromCommandAllocatorX(
* UINT sizeBytes, UINT alignmentBytes) allocates memory "with the same lifetime as the associated
* command list", for data written on the CPU timeline and read on the GPU timeline. The result "is a
* valid GPU pointer and may be cast to D3D12_GPU_VIRTUAL_ADDRESS"; it is null only when memory is
* unavailable. The target build's ray-tracing BVH builder throws when it gets null, and the process
* then ends (status 99).
*
* Checked, from the contract alone:
* 1. Allocations of 100 bytes at 256-byte alignment, 64 at 16, and 3 MiB at 64 KiB are non-null,
* aligned as asked, do not overlap, and hold what the program writes into them.
* 2. After the list is closed, the allocator reset (its lists are done) and the list reset with
* it, a new allocation is non-null and writable.
* 3. The method is not logged as an unimplemented slot.
*
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
* 73 CreateCommandListX; command allocator 8 Reset; command list 9 Close, 10 Reset,
* 148 AllocateFromCommandAllocatorX.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommandListX = 73;
constexpr int kAllocatorReset = 8, kListClose = 9, kListReset = 10, kListAllocate = 148;
int g_checks = 0, g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_allocate_from_allocator:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using AllocatorResetFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using ListResetFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*);
using AllocateFn = void*(STDMETHODCALLTYPE*)(void*, UINT, UINT);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
bool fill_and_check(void* p, size_t n, uint8_t seed) {
auto* b = static_cast<uint8_t*>(p);
for (size_t i = 0; i < n; ++i) b[i] = static_cast<uint8_t>(i * 13 + seed);
for (size_t i = 0; i < n; ++i) {
if (b[i] != static_cast<uint8_t>(i * 13 + seed)) return false;
}
return true;
}
} // namespace
int main() {
setvbuf(stdout, nullptr, _IONBF, 0);
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_allocate_from_allocator: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const std::string before = read_log();
void* allocator = nullptr;
void* list = nullptr;
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
&allocator);
if (allocator) {
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
}
if (!allocator || !list) {
std::fprintf(stderr, "FAIL: test_d3d12_allocate_from_allocator: setup\n");
return 1;
}
auto allocate = slot<AllocateFn>(list, kListAllocate);
// 1. Three allocations, aligned as asked, not overlapping, writable.
void* a = allocate(list, 100, 256);
void* b = allocate(list, 64, 16);
const UINT big = 3u << 20;
void* c = allocate(list, big, 65536);
CHECK(a && (reinterpret_cast<uintptr_t>(a) % 256) == 0, "100 bytes at 256-byte alignment: %p", a);
CHECK(b && (reinterpret_cast<uintptr_t>(b) % 16) == 0, "64 bytes at 16-byte alignment: %p", b);
CHECK(c && (reinterpret_cast<uintptr_t>(c) % 65536) == 0, "3 MiB at 64 KiB alignment: %p", c);
if (a && b && c) {
const auto ua = reinterpret_cast<uintptr_t>(a), ub = reinterpret_cast<uintptr_t>(b), uc = reinterpret_cast<uintptr_t>(c);
CHECK((ua + 100 <= ub || ub + 64 <= ua) && (ua + 100 <= uc || uc + big <= ua) && (ub + 64 <= uc || uc + big <= ub),
"the three allocations do not overlap");
CHECK(fill_and_check(a, 100, 1) && fill_and_check(b, 64, 2) && fill_and_check(c, big, 3), "each allocation holds what is written");
CHECK(static_cast<uint8_t*>(a)[0] == 1 && static_cast<uint8_t*>(a)[99] == static_cast<uint8_t>(99 * 13 + 1),
"writing the others left the first allocation intact");
}
// 2. After the allocator's lists are done: reset, record again, allocate again.
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
CHECK(slot<AllocatorResetFn>(allocator, kAllocatorReset)(allocator) == S_OK, "allocator Reset");
CHECK(slot<ListResetFn>(list, kListReset)(list, allocator, nullptr) == S_OK, "list Reset with the allocator");
void* d = allocate(list, 128, 64);
CHECK(d && (reinterpret_cast<uintptr_t>(d) % 64) == 0 && fill_and_check(d, 128, 4),
"after the reset: 128 bytes at 64-byte alignment, writable (%p)", d);
// 3. Not an unimplemented slot.
const std::string log = read_log();
if (!log.empty()) {
const std::string mine = log.substr(before.size() <= log.size() ? before.size() : 0);
CHECK(mine.find("XboxGraphicsCommandList[148]::AllocateFromCommandAllocatorX") == std::string::npos,
"AllocateFromCommandAllocatorX is not logged as an unimplemented slot");
} else {
std::printf("note: no BX_LOG_FILE; the log check did not run\n");
}
slot<CloseFn>(list, kListClose)(list);
slot<ReleaseFn>(list, kRelease)(list);
slot<ReleaseFn>(allocator, kRelease)(allocator);
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) {
std::fprintf(stderr, "FAIL: test_d3d12_allocate_from_allocator (%d of %d checks failed)\n", g_failed, g_checks);
return 1;
}
std::printf("PASS: test_d3d12_allocate_from_allocator (%d of %d checks passed)\n", g_checks, g_checks);
return 0;
}
@@ -73,6 +73,15 @@
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
// Built twice: as test_d3d12_console_texture_contents, and with BX_TEST_RESERVED_TEXTURES as
// test_d3d12_console_texture_contents_reserved, where every read-only texture is a reserved
// resource whose memory is mapped when its contents are first uploaded for a draw (#782).
#ifdef BX_TEST_RESERVED_TEXTURES
#define BX_TEST_NAME "test_d3d12_console_texture_contents_reserved"
#else
#define BX_TEST_NAME "test_d3d12_console_texture_contents"
#endif
namespace {
constexpr int kRelease = 2;
@@ -115,7 +124,7 @@ int g_failed = 0;
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_console_texture_contents:%d: ", __LINE__); \
std::fprintf(stderr, "FAIL: " BX_TEST_NAME ":%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
@@ -320,6 +329,9 @@ int main() {
std::snprintf(cache, sizeof(cache), "%sbx-shader-cache-%lu-%lu", temp, static_cast<unsigned long>(GetCurrentProcessId()),
static_cast<unsigned long>(GetTickCount()));
SetEnvironmentVariableA("BX_CONSOLE_SHADERS", "1");
#ifdef BX_TEST_RESERVED_TEXTURES
SetEnvironmentVariableA("BX_LAZY_TEXTURES_MIN", "0"); // even these small textures are reserved
#endif
SetEnvironmentVariableA("BX_SHADER_CACHE", cache);
// The stand-in XG, loaded as xg_xs.dll before the device exists (as bx-cli stages the GDK's).
@@ -330,7 +342,7 @@ int main() {
wcscpy(slash + 1, L"texture_contents_fake_xg\\xg_xs.dll");
HMODULE fake = LoadLibraryW(path);
if (!fake) {
std::fprintf(stderr, "FAIL: test_d3d12_console_texture_contents: the stand-in XG library did not load (error %lu)\n",
std::fprintf(stderr, "FAIL: " BX_TEST_NAME ": the stand-in XG library did not load (error %lu)\n",
GetLastError());
return 1;
}
@@ -344,7 +356,7 @@ int main() {
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_console_texture_contents: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
std::printf("SKIP: " BX_TEST_NAME ": host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
@@ -355,7 +367,7 @@ int main() {
: nullptr;
HMODULE dxc = LoadLibraryA("dxcompiler.dll");
if (!serialize || !dxc) {
std::printf("SKIP: test_d3d12_console_texture_contents: %s\n",
std::printf("SKIP: " BX_TEST_NAME ": %s\n",
dxc ? "no root-signature serializer in this bottle"
: "no dxcompiler.dll beside the shims (run with bx-cli run --gdk-libraries)");
return 77;
@@ -514,7 +526,7 @@ int main() {
bool made = queue && allocator && list && fence && root && pipeline && textures[0] && textures[1] && upload && rtv_heap && view_heap;
for (int i = 0; i < kViews; ++i) made = made && targets[i] && readbacks[i];
if (!made) {
std::fprintf(stderr, "FAIL: test_d3d12_console_texture_contents: setup\n");
std::fprintf(stderr, "FAIL: " BX_TEST_NAME ": setup\n");
return 1;
}
// Console descriptor handles are addresses; an RTV descriptor is 112 bytes there.
@@ -709,6 +721,14 @@ int main() {
count_of(mine, "copied again: its title memory changed"));
CHECK(count_of(mine, "CreatePlacedResourceX(texture contents)") == 0,
"no texture-contents stub is logged with translation on (%zu)", count_of(mine, "CreatePlacedResourceX(texture contents)"));
#ifdef BX_TEST_RESERVED_TEXTURES
// The three textures whose contents were copied got their memory first; the one copied
// from unreadable memory never did.
CHECK(count_of(mine, "texture memory mapped at first use") == 3, "three textures mapped at first use (%zu)",
count_of(mine, "texture memory mapped at first use"));
CHECK(count_of(mine, "refused a reserved texture") == 0 && count_of(mine, "not mapped") == 0,
"no reserved texture refused and no mapping failed");
#endif
} else {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
@@ -719,7 +739,7 @@ int main() {
slot<ReleaseFn>(object, kRelease)(object);
}
VirtualFree(memory, 0, MEM_RELEASE);
std::printf("%s: test_d3d12_console_texture_contents (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS",
std::printf("%s: " BX_TEST_NAME " (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS",
g_checks - g_failed, g_checks);
return g_failed ? 1 : 0;
}
@@ -0,0 +1,7 @@
# test_d3d12_console_texture_contents with every read-only texture made reserved, its memory mapped
# when its contents are first uploaded for a draw (#782). Same program, same expectations, plus the
# mappings in the log. Needs what that test needs; skips without.
add_executable(test_d3d12_console_texture_contents_reserved ../test_d3d12_console_texture_contents/main.cpp)
target_compile_definitions(test_d3d12_console_texture_contents_reserved PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS BX_TEST_RESERVED_TEXTURES)
target_link_libraries(test_d3d12_console_texture_contents_reserved PRIVATE d3d12_xs kernel32 uuid)
add_dependencies(test_d3d12_console_texture_contents_reserved test_texture_contents_fake_xg)
@@ -0,0 +1,5 @@
# DispatchX and CopyResourceX follow Dispatch and CopyResource. Needs a host with the Xbox-layout
# device interface; skips without.
add_executable(test_d3d12_dispatch_copy_x main.cpp)
target_compile_definitions(test_d3d12_dispatch_copy_x PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_dispatch_copy_x PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,208 @@
/*
* Conformance test: DispatchX and CopyResourceX (Xbox-layout command-list slots 80 and 86).
*
* Contract (authorized GDK d3d12_xs.h and reference pages): DispatchX(x, y, z, Flags) is Dispatch
* with D3D12XBOX_DISPATCH_FLAGS; CopyResourceX(dst, src, Flags) is CopyResource with
* D3D12XBOX_COPY_FLAGS ("copies the entire contents of the source resource to the destination").
* Both were stubs; the target build calls them once it leaves its loading screen.
*
* Checked, from the contract and the program alone:
* 1. CopyResourceX copies a 64 KiB pattern from an upload buffer into a readback buffer.
* 2. With a compute pipeline the shim refuses bound (it comes back as the null pipeline, #722),
* DispatchX with flags 0 and with USE_THREAD_DIMENSIONS (0x20) records nothing harmful: the
* list executes and completes, and the dispatches are skipped as Dispatch's are.
* 3. Neither method is logged as an unimplemented slot.
*
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
* 27 CreateCommittedResource, 36 CreateFence, 48 CreateCommandQueueX, 62 CreateComputePipelineStateX,
* 73 CreateCommandListX; resource 8 Map; command list 9 Close, 25 SetPipelineState, 80 DispatchX,
* 86 CopyResourceX; queue 10 ExecuteCommandLists, 16 Signal; fence 9 SetEventOnCompletion.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateFence = 36;
constexpr int kDevCreateCommandQueueX = 48, kDevCreateComputePipelineStateX = 62, kDevCreateCommandListX = 73;
constexpr int kResMap = 8;
constexpr int kListClose = 9, kListSetPipelineState = 25, kListDispatchX = 80, kListCopyResourceX = 86;
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
constexpr UINT64 kBytes = 64 * 1024;
int g_checks = 0, g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_dispatch_copy_x:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct QueueDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, EngineOrPipeIndex, QueueIndex;
};
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using CreateComputeXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, UINT, const void*, REFIID,
void**);
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using SetPsoFn = void(STDMETHODCALLTYPE*)(void*, void*);
using DispatchXFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, UINT);
using CopyResourceXFn = void(STDMETHODCALLTYPE*)(void*, void*, void*, UINT);
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
} // namespace
int main() {
setvbuf(stdout, nullptr, _IONBF, 0);
SetEnvironmentVariableA("BX_NULL_RENDER", nullptr);
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004;
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_dispatch_copy_x: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const std::string before = read_log();
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
void* fence = nullptr;
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
&allocator);
if (allocator) {
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
}
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
D3D12_HEAP_PROPERTIES upload_heap{}, readback_heap{};
upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
D3D12_RESOURCE_DESC buf{};
buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buf.Width = kBytes;
buf.Height = 1;
buf.DepthOrArraySize = 1;
buf.MipLevels = 1;
buf.SampleDesc.Count = 1;
buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
void* src = nullptr;
void* dst = nullptr;
committed(dev, &upload_heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), &src);
committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, __uuidof(ID3D12Resource), &dst);
// A compute pipeline the shader gate refuses: the null pipeline comes back (#722).
static const uint8_t kRefused[16] = {0x44, 0x58, 0x42, 0x43};
D3D12_COMPUTE_PIPELINE_STATE_DESC cdesc{};
cdesc.CS.pShaderBytecode = kRefused;
cdesc.CS.BytecodeLength = sizeof(kRefused);
void* pso = nullptr;
slot<CreateComputeXFn>(dev, kDevCreateComputePipelineStateX)(dev, &cdesc, 0, nullptr, __uuidof(ID3D12PipelineState), &pso);
if (!queue || !allocator || !list || !fence || !src || !dst || !pso) {
std::fprintf(stderr, "FAIL: test_d3d12_dispatch_copy_x: setup\n");
return 1;
}
void* mapped = nullptr;
CHECK(slot<MapFn>(src, kResMap)(src, 0, nullptr, &mapped) == S_OK && mapped, "upload Map");
if (mapped) {
for (UINT64 i = 0; i < kBytes; ++i) static_cast<uint8_t*>(mapped)[i] = static_cast<uint8_t>(i * 11 + 5);
}
slot<CopyResourceXFn>(list, kListCopyResourceX)(list, dst, src, 0x60); // flags steer compression metadata only
slot<SetPsoFn>(list, kListSetPipelineState)(list, pso);
slot<DispatchXFn>(list, kListDispatchX)(list, 2, 1, 1, 0);
slot<DispatchXFn>(list, kListDispatchX)(list, 64, 1, 1, 0x20);
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
void* lists[] = {list};
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal");
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event");
CHECK(WaitForSingleObject(done, 5000) == WAIT_OBJECT_0, "the list with the copy and both dispatches completes");
CloseHandle(done);
void* data = nullptr;
const D3D12_RANGE all{0, static_cast<SIZE_T>(kBytes)};
CHECK(slot<MapFn>(dst, kResMap)(dst, 0, &all, &data) == S_OK && data, "readback Map");
UINT64 wrong = 0;
if (data) {
for (UINT64 i = 0; i < kBytes; ++i) {
if (static_cast<const uint8_t*>(data)[i] != static_cast<uint8_t>(i * 11 + 5)) ++wrong;
}
}
CHECK(data && wrong == 0, "CopyResourceX copied the whole buffer (%llu of %llu bytes differ)", static_cast<unsigned long long>(wrong),
static_cast<unsigned long long>(kBytes));
const std::string log = read_log();
if (!log.empty()) {
const std::string mine = log.substr(before.size() <= log.size() ? before.size() : 0);
CHECK(mine.find("XboxGraphicsCommandList[80]::DispatchX") == std::string::npos, "DispatchX is not an unimplemented slot");
CHECK(mine.find("XboxGraphicsCommandList[86]::CopyResourceX") == std::string::npos, "CopyResourceX is not an unimplemented slot");
CHECK(mine.find("null pipeline bound") != std::string::npos, "the dispatches with the null pipeline are skipped, as Dispatch's are");
} else {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
for (void* object : {pso, dst, src, fence, list, allocator, queue}) slot<ReleaseFn>(object, kRelease)(object);
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) {
std::fprintf(stderr, "FAIL: test_d3d12_dispatch_copy_x (%d of %d checks failed)\n", g_failed, g_checks);
return 1;
}
std::printf("PASS: test_d3d12_dispatch_copy_x (%d of %d checks passed)\n", g_checks, g_checks);
return 0;
}
@@ -0,0 +1,5 @@
# Read-only placed textures get host memory at first use, and a title's GPU copy into one keeps its
# data (#782). Needs a host with the Xbox-layout device interface; skips without.
add_executable(test_d3d12_lazy_texture_memory main.cpp)
target_compile_definitions(test_d3d12_lazy_texture_memory PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_lazy_texture_memory PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,297 @@
/*
* Conformance test: host memory for read-only placed textures is mapped at first use (#782).
*
* d3d12_xs backs a texture a title places in its memory (CreatePlacedResourceX) with a host
* texture. A read-only 2D texture of at least 64 KiB is now a reserved resource whose memory is
* mapped when a draw first needs its contents or when a GPU copy or resolve of the title writes it.
* A write into a reserved texture without memory is dropped, so the title's copies must map first.
*
* The program places five RGBA8 textures in its own memory (VirtualAlloc, 1 MiB apart):
* T1, T2, T5: 512x512, no flags (1 MiB each): reserved;
* T3: 64x64 (16 KiB): under 64 KiB, committed as before;
* T4: 512x512 with ALLOW_RENDER_TARGET: the GPU writes it, committed as before.
* One command list then copies a pattern from an upload buffer into T1 (CopyTextureRegion), copies
* T1 into T5 (CopyResource), and copies T1 and T5 into two readback buffers. T2 is never used.
* Expected, from the program alone:
* - both readbacks hold the pattern (the copies' writes were kept);
* - the shim logs that read-only textures are reserved, and exactly two first-use mappings, the
* second with `reserved=3 mapped=2` (T1, T2 and T5 reserved; T1 and T5 mapped; T2 never).
* Before #782 every texture was committed: no such log lines (the readbacks pass).
*
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
* 27 CreateCommittedResource, 36 CreateFence, 44 CreatePlacedResourceX, 48 CreateCommandQueueX,
* 73 CreateCommandListX; resource 8 Map; command list 9 Close, 16 CopyTextureRegion,
* 17 CopyResource, 26 ResourceBarrier; queue 10 ExecuteCommandLists, 16 Signal; fence 9
* SetEventOnCompletion.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateFence = 36;
constexpr int kDevCreatePlacedResourceX = 44, kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
constexpr int kResMap = 8;
constexpr int kListClose = 9, kListCopyTextureRegion = 16, kListCopyResource = 17, kListResourceBarrier = 26;
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
constexpr UINT kSize = 512, kPitch = kSize * 4;
constexpr UINT64 kBytes = UINT64(kPitch) * kSize;
constexpr UINT64 kApart = 1 << 20;
int g_checks = 0, g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_lazy_texture_memory:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct QueueDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, EngineOrPipeIndex, QueueIndex;
};
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using CreatePlacedXFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, const D3D12_RESOURCE_DESC*,
D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**);
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using CopyRegionFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT,
const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*);
using CopyResourceFn = void(STDMETHODCALLTYPE*)(void*, void*, void*);
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
return n;
}
D3D12_RESOURCE_DESC texture(UINT size, D3D12_RESOURCE_FLAGS flags) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = size;
d.Height = size;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
d.SampleDesc.Count = 1;
d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100); // the console's linear layout
d.Flags = flags;
return d;
}
D3D12_RESOURCE_BARRIER transition(void* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
D3D12_RESOURCE_BARRIER b{};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
b.Transition.pResource = static_cast<ID3D12Resource*>(resource);
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
b.Transition.StateBefore = before;
b.Transition.StateAfter = after;
return b;
}
uint8_t pattern(UINT64 i) {
return static_cast<uint8_t>(i * 7 + (i >> 11) * 3 + 1);
}
} // namespace
int main() {
setvbuf(stdout, nullptr, _IONBF, 0);
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_lazy_texture_memory: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const std::string before = read_log();
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
void* fence = nullptr;
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
&allocator);
if (allocator) {
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
}
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
// Upload and readback buffers.
D3D12_HEAP_PROPERTIES upload_heap{}, readback_heap{};
upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
D3D12_RESOURCE_DESC buf{};
buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buf.Width = kBytes;
buf.Height = 1;
buf.DepthOrArraySize = 1;
buf.MipLevels = 1;
buf.SampleDesc.Count = 1;
buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
void* upload = nullptr;
void* readback1 = nullptr;
void* readback5 = nullptr;
committed(dev, &upload_heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), &upload);
committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, __uuidof(ID3D12Resource), &readback1);
committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, __uuidof(ID3D12Resource), &readback5);
// Five placed textures in the program's own memory, 1 MiB apart.
auto* memory = static_cast<uint8_t*>(VirtualAlloc(nullptr, 5 * kApart, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!queue || !allocator || !list || !fence || !upload || !readback1 || !readback5 || !memory) {
std::fprintf(stderr, "FAIL: test_d3d12_lazy_texture_memory: setup\n");
return 1;
}
const uint64_t base = reinterpret_cast<uint64_t>(memory);
auto placed = slot<CreatePlacedXFn>(dev, kDevCreatePlacedResourceX);
void* t[5] = {};
const D3D12_RESOURCE_DESC read_only = texture(kSize, D3D12_RESOURCE_FLAG_NONE);
const D3D12_RESOURCE_DESC small = texture(64, D3D12_RESOURCE_FLAG_NONE);
const D3D12_RESOURCE_DESC target = texture(kSize, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
const D3D12_RESOURCE_DESC* descs[5] = {&read_only, &read_only, &small, &target, &read_only};
for (int i = 0; i < 5; ++i) {
hr = placed(dev, base + i * kApart, descs[i], D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), &t[i]);
CHECK(hr == S_OK && t[i], "CreatePlacedResourceX T%d hr=0x%08lx", i + 1, static_cast<unsigned long>(hr));
}
if (!t[0] || !t[4]) return 1;
void* mapped = nullptr;
CHECK(slot<MapFn>(upload, kResMap)(upload, 0, nullptr, &mapped) == S_OK && mapped, "upload Map");
if (mapped) {
for (UINT64 i = 0; i < kBytes; ++i) static_cast<uint8_t*>(mapped)[i] = pattern(i);
}
// The upload into T1, T1 into T5, both read back.
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
fp.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kPitch};
auto copy_region = slot<CopyRegionFn>(list, kListCopyTextureRegion);
auto barrier = slot<BarrierFn>(list, kListResourceBarrier);
D3D12_TEXTURE_COPY_LOCATION tex1{static_cast<ID3D12Resource*>(t[0]), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
D3D12_TEXTURE_COPY_LOCATION tex5{static_cast<ID3D12Resource*>(t[4]), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
D3D12_TEXTURE_COPY_LOCATION up{static_cast<ID3D12Resource*>(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
up.PlacedFootprint = fp;
D3D12_TEXTURE_COPY_LOCATION rb1{static_cast<ID3D12Resource*>(readback1), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
rb1.PlacedFootprint = fp;
D3D12_TEXTURE_COPY_LOCATION rb5{static_cast<ID3D12Resource*>(readback5), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
rb5.PlacedFootprint = fp;
D3D12_RESOURCE_BARRIER b[2] = {transition(t[0], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST),
transition(t[4], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)};
barrier(list, 2, b);
copy_region(list, &tex1, 0, 0, 0, &up, nullptr);
b[0] = transition(t[0], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
barrier(list, 1, b);
slot<CopyResourceFn>(list, kListCopyResource)(list, t[4], t[0]);
b[0] = transition(t[4], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
barrier(list, 1, b);
copy_region(list, &rb1, 0, 0, 0, &tex1, nullptr);
copy_region(list, &rb5, 0, 0, 0, &tex5, nullptr);
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
void* lists[] = {list};
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal");
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event");
CHECK(WaitForSingleObject(done, 5000) == WAIT_OBJECT_0, "the copies complete");
CloseHandle(done);
for (int k = 0; k < 2; ++k) {
void* rb = k ? readback5 : readback1;
void* data = nullptr;
const D3D12_RANGE all{0, static_cast<SIZE_T>(kBytes)};
CHECK(slot<MapFn>(rb, kResMap)(rb, 0, &all, &data) == S_OK && data, "readback Map");
UINT64 wrong = 0, first = kBytes;
if (data) {
for (UINT64 i = 0; i < kBytes; ++i) {
if (static_cast<const uint8_t*>(data)[i] != pattern(i)) {
if (!wrong) first = i;
++wrong;
}
}
}
CHECK(data && wrong == 0, "%s holds the uploaded pattern (%llu of %llu bytes differ, first at %llu)",
k ? "T5 (CopyResource from T1)" : "T1 (CopyTextureRegion from the upload)", static_cast<unsigned long long>(wrong),
static_cast<unsigned long long>(kBytes), static_cast<unsigned long long>(first));
}
const std::string log = read_log();
if (!log.empty()) {
const std::string mine = log.substr(before.size() <= log.size() ? before.size() : 0);
CHECK(count_of(mine, "read-only textures of 64 KiB or more are reserved") == 1, "the shim reports reserved textures");
CHECK(count_of(mine, "texture memory mapped at first use") == 2, "exactly two first-use mappings (T1, T5): %zu",
count_of(mine, "texture memory mapped at first use"));
CHECK(mine.find("reserved=3 mapped=2") != std::string::npos,
"three textures reserved (T1, T2, T5; not the small one or the render target), two mapped (not T2)");
CHECK(mine.find("refused a reserved texture") == std::string::npos && mine.find("not mapped") == std::string::npos,
"no refusal or failed mapping is logged");
} else {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
for (void* object : {t[0], t[1], t[2], t[3], t[4], readback5, readback1, upload, fence, list, allocator, queue}) {
if (object) slot<ReleaseFn>(object, kRelease)(object);
}
slot<ReleaseFn>(dev, kRelease)(dev);
VirtualFree(memory, 0, MEM_RELEASE);
if (g_failed) {
std::fprintf(stderr, "FAIL: test_d3d12_lazy_texture_memory (%d of %d checks failed)\n", g_failed, g_checks);
return 1;
}
std::printf("PASS: test_d3d12_lazy_texture_memory (%d of %d checks passed)\n", g_checks, g_checks);
return 0;
}