mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-12-01 13:12:28 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ead0599a2 | ||
|
|
952e9a315e | ||
|
|
711f977c7a | ||
|
|
e5314efe67 | ||
|
|
8783454bb0 | ||
|
|
ce562bf99d | ||
|
|
339ab9cb48 | ||
|
|
91455f43d5 | ||
|
|
ba81e8633d | ||
|
|
620eda1c62 | ||
|
|
a679c463dd | ||
|
|
55c31e71c6 | ||
|
|
3e456cf124 |
No files matched your search
@@ -197,6 +197,9 @@ remains unsupported.
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- **`d3d12_xs.dll`: `PresentX` composes its planes** (authorized GDK documentation, *Hardware overlays*). It copied plane 0 alone to the window and logged that plane 1, rectangles and scaling were not applied. The target build presents its scene in plane 0 (1920×1080) and its UI in plane 1 (3840×2160), so its first menus, drawn correctly into plane 1, never showed. Planes are now drawn in order, plane 1 in front, as premultiplied alpha (`ONE`, `INV_SRC_ALPHA`) over transparent black, each scaled from its source rectangle (`pSrcViewRects`, texels) to its destination rectangle (`pDestPlacementBase`, normalized), into a texture the size of the swapchain that is copied to the back buffer and dumped by `BX_PRESENT_DUMP`. The shaders are compiled at the first such present with the GDK's PC `dxcompiler.dll`; without it plane 0 is copied as before (logged). Colour spaces other than RGB full G2.2 P709 are composed as SDR in plane order (logged once). One plane without rectangles is copied as before. `test_d3d12_presentx_planes` presents two planes of its own with and without rectangles and checks the composed frames.
|
||||
- **`d3d12_xs.dll`: texture contents are uploaded by the GPU** (follow-up of #747). The texels of a texture placed in title memory were written into its copy from the CPU (`WriteToSubresource`), on the submitting thread; for the target build's two continually rewritten 3840×2160 textures that cost about 30 % of the frame rate. They are now written into an upload buffer of the copy's own (rows copied, or untiled by XG straight into it) and copied by the GPU, on a list of the shim's own executed on the submitting queue ahead of the title's lists; the copy lives on a default heap in the shim's own states. An upload buffer is not rewritten until the GPU is past its last copy, and buffers of released textures are freed only then.
|
||||
- **`d3d12_xs.dll`: a texture placed in title memory shows its pixels in a translated draw** (#745). With `BX_CONSOLE_SHADERS=1`, when a translated draw reads a texture that `CreatePlacedResourceX` placed in title memory, its contents are copied from that memory into a CPU-writable copy of the host texture, which the view then reads: the linear console layout (`0x100`) row by row at its 256-byte pitch, other console layouts untiled through the GDK's XG library (`CopyFromSubresource`, ADR 0010). A view reads the copy only once a copy has succeeded; until then, and after a failure, it reads the host texture and the next draw tries again. So that textures still being streamed fill in, a later draw checks a hash over a sample of the title memory (64 bytes every 64 KiB), at an interval that starts at 250 ms and doubles up to 4 s while nothing changes; only a change copies the texture again (logged). The contents live in this side copy, not in the host texture: copy commands and other views read the empty host texture, and the first `CopyTextureRegion(X)` out of such a texture is logged. Render-target, depth and UAV textures are not copied over. `CreatePlacedShaderResourceViewX` now writes the descriptor marker that `CreateShaderResourceView` writes, so translated draws find views made that way. Before, every such texture was sampled empty. `test_d3d12_console_texture_contents` draws a linear and a tiled texture of its own (through a stand-in XG), with a view made each way, and checks every pixel over three rounds: a copy from unreadable memory, its retry at the next draw, and a copy again after the title rewrites one texture (and not of the unchanged one).
|
||||
- **`d3d12_xs.dll`: a translated pipeline that reads a root constants or root descriptor parameter is no longer refused or mistaken for a table read** (#744). The shim read the translator's `USE ROOT <parameter>` layout line as `USE CB <entry>`: as a constant-buffer read of entry `<parameter>` of root parameter 0's table. With a parameter index of 8 or more the pipeline was refused ("reads table entry 8, beyond the 8 widened ones") and drew nothing; below 8 each submission looked up a table entry the shader never reads and logged it as an unresolved descriptor, which was most of the `console_descriptor` warnings on the target build's first screens and hid the real ones. Only `USE CB` and `USE TEX` lines now name table entries; other kinds are ignored, as `abi/include/bx_shader_bridge.h` says. `test_d3d12_console_root_constants` draws with a vertex shader that reads root parameter 8.
|
||||
- **Two causes of the target build's menu crashes are fixed** (#722). Before, most runs ended with exit status 5 within a few minutes.
|
||||
- **`d3d12_xs.dll`: `CopyTextureRegionX` is implemented**, as `CopyTextureRegion`; its `D3D12XBOX_COPY_FLAGS` steer console compression metadata the host does not have. As a stub it left a copy undone, the title's frame never completed, and its hang watchdog ended the process 30 s later (every watchdog crash followed its first call by 32–41 s). Test: `test_d3d12_copy_texture_region_x`, a box copy and a whole-texture copy through slot 85, read back. On the previous shim no pixel is copied.
|
||||
|
||||
@@ -152,7 +152,7 @@ std::atomic<uint64_t> g_resolved{0};
|
||||
std::atomic<uint64_t> g_unmarked{0};
|
||||
|
||||
/* Writes the host view for one table entry a translated draw reads. */
|
||||
void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uint64_t entry) {
|
||||
void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uint64_t entry, BxTextureUploads* uploads) {
|
||||
uint32_t words[8] = {};
|
||||
std::memcpy(words, reinterpret_cast<const void*>(entry), sizeof(words));
|
||||
View view;
|
||||
@@ -174,7 +174,8 @@ void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uin
|
||||
}
|
||||
++g_resolved;
|
||||
} else if (ok && use.texture && view.texture) {
|
||||
device->CreateShaderResourceView(view.resource, view.has_srv_desc ? &view.srv : nullptr, host);
|
||||
// A texture placed in title memory is read through a copy of its contents (#745).
|
||||
device->CreateShaderResourceView(bx_xbox_texture_contents(view.resource, uploads), view.has_srv_desc ? &view.srv : nullptr, host);
|
||||
++g_resolved;
|
||||
} else if (sampled(g_unmarked, &total)) {
|
||||
log(BX_LOG_WARN, "console_descriptor",
|
||||
@@ -242,7 +243,61 @@ void bx_console_descriptors_reset(ID3D12GraphicsCommandList* list) {
|
||||
g_tables.erase(list);
|
||||
}
|
||||
|
||||
void bx_console_submit(ID3D12CommandList* const* host_lists, UINT count) {
|
||||
namespace {
|
||||
|
||||
/* Per queue: a list of the shim's own that uploads texture contents (placed_x.cpp) ahead of the
|
||||
title's lists, its allocators in turn, and a fence for both (#745). */
|
||||
struct UploadContext {
|
||||
static constexpr UINT kTurns = 4;
|
||||
std::mutex lock;
|
||||
ID3D12CommandAllocator* allocators[kTurns] = {};
|
||||
UINT64 allocator_values[kTurns] = {};
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
HANDLE event = nullptr;
|
||||
UINT64 next = 1;
|
||||
UINT turn = 0;
|
||||
bool failed = false;
|
||||
};
|
||||
std::mutex g_upload_lock;
|
||||
std::unordered_map<const void*, std::unique_ptr<UploadContext>> g_uploads;
|
||||
|
||||
UploadContext* upload_context(ID3D12CommandQueue* queue) {
|
||||
UploadContext* ctx = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_upload_lock);
|
||||
auto& slot = g_uploads[queue];
|
||||
if (!slot) slot = std::make_unique<UploadContext>();
|
||||
ctx = slot.get();
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(ctx->lock);
|
||||
if (ctx->list || ctx->failed) return ctx->failed ? nullptr : ctx;
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
const D3D12_COMMAND_LIST_TYPE type = queue->GetDesc().Type;
|
||||
for (UINT i = 0; SUCCEEDED(hr) && i < UploadContext::kTurns; ++i) {
|
||||
hr = device->CreateCommandAllocator(type, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&ctx->allocators[i]));
|
||||
}
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommandList(0, type, ctx->allocators[0], nullptr, __uuidof(ID3D12GraphicsCommandList),
|
||||
reinterpret_cast<void**>(&ctx->list));
|
||||
}
|
||||
if (SUCCEEDED(hr)) hr = ctx->list->Close();
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&ctx->fence));
|
||||
if (device) device->Release();
|
||||
ctx->event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (FAILED(hr) || !ctx->event) {
|
||||
ctx->failed = true;
|
||||
log(BX_LOG_WARN, "texture_upload", "no upload list for this queue (hr=0x%08lx); texture contents are not uploaded on it",
|
||||
static_cast<unsigned long>(FAILED(hr) ? hr : E_OUTOFMEMORY));
|
||||
return nullptr;
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_submit(ID3D12CommandQueue* queue, ID3D12CommandList* const* host_lists, UINT count) {
|
||||
if (!bx_console_shaders_enabled()) return;
|
||||
std::vector<Draw> draws;
|
||||
{
|
||||
@@ -252,6 +307,22 @@ void bx_console_submit(ID3D12CommandList* const* host_lists, UINT count) {
|
||||
if (it != g_draws.end()) draws.insert(draws.end(), it->second.begin(), it->second.end());
|
||||
}
|
||||
}
|
||||
if (draws.empty()) return;
|
||||
UploadContext* ctx = queue ? upload_context(queue) : nullptr;
|
||||
std::unique_lock<std::mutex> held;
|
||||
BxTextureUploads uploads{nullptr, nullptr, 0, false};
|
||||
UINT turn = 0;
|
||||
if (ctx) {
|
||||
held = std::unique_lock<std::mutex>(ctx->lock);
|
||||
turn = ctx->turn % UploadContext::kTurns;
|
||||
if (ctx->fence->GetCompletedValue() < ctx->allocator_values[turn]) {
|
||||
ctx->fence->SetEventOnCompletion(ctx->allocator_values[turn], ctx->event);
|
||||
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};
|
||||
}
|
||||
}
|
||||
std::unordered_set<uint64_t> done; // entries written for this submission
|
||||
for (const Draw& draw : draws) {
|
||||
ID3D12Device* device = nullptr;
|
||||
@@ -264,7 +335,18 @@ void bx_console_submit(ID3D12CommandList* const* host_lists, UINT count) {
|
||||
const uint64_t entry = draw.tables[uses[u].param] + static_cast<uint64_t>(kDescriptorSize) * uses[u].entry;
|
||||
if (!bx_xbox_title_descriptors(entry, 1)) continue;
|
||||
if (!done.insert(entry * 2 + (uses[u].texture ? 1 : 0)).second) continue;
|
||||
resolve(device, key, uses[u], entry);
|
||||
resolve(device, key, uses[u], entry, uploads.list ? &uploads : nullptr);
|
||||
}
|
||||
}
|
||||
if (uploads.list) {
|
||||
ctx->list->Close();
|
||||
if (uploads.recorded) {
|
||||
ID3D12CommandList* lists[] = {ctx->list};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
queue->Signal(ctx->fence, uploads.value);
|
||||
ctx->allocator_values[turn] = uploads.value;
|
||||
++ctx->next;
|
||||
++ctx->turn;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -379,6 +379,10 @@ ID3DBlob* widen(const void* blob, size_t size) {
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_console_compile_hlsl(const char* source, bool pixel, std::vector<uint8_t>& out, std::string& why) {
|
||||
return compile(reinterpret_cast<const uint8_t*>(source), std::strlen(source), pixel, out, why);
|
||||
}
|
||||
|
||||
bool bx_console_shaders_enabled() {
|
||||
static const bool enabled = [] {
|
||||
const bool on = env_is_one("BX_CONSOLE_SHADERS");
|
||||
|
||||
@@ -8,8 +8,14 @@
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/* HLSL to DXIL with the GDK's PC dxcompiler.dll (entry `main`, vs_6_0 or ps_6_0), through the same
|
||||
disk cache as translated shaders. False with the reason in `why` when there is no compiler or it
|
||||
refuses the source. */
|
||||
bool bx_console_compile_hlsl(const char* source, bool pixel, std::vector<uint8_t>& out, std::string& why);
|
||||
|
||||
/* True when BX_CONSOLE_SHADERS=1 (opt-in while the draw path is being completed). */
|
||||
bool bx_console_shaders_enabled();
|
||||
|
||||
@@ -60,5 +66,7 @@ void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count);
|
||||
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle);
|
||||
void bx_console_record_draw(ID3D12GraphicsCommandList* list, const std::shared_ptr<BxConsolePipeline>& pipeline);
|
||||
void bx_console_descriptors_reset(ID3D12GraphicsCommandList* list);
|
||||
/* Before the host executes `host_lists`: writes the views their translated draws read. */
|
||||
void bx_console_submit(ID3D12CommandList* const* host_lists, UINT count);
|
||||
/* Before `queue` executes `host_lists`: writes the views their translated draws read. Texture
|
||||
contents copied for those views are uploaded by a list of the shim's own, executed on `queue`
|
||||
first. */
|
||||
void bx_console_submit(ID3D12CommandQueue* queue, ID3D12CommandList* const* host_lists, UINT count);
|
||||
@@ -6,15 +6,20 @@
|
||||
* XG12_RESOURCE_MISC_FLAG in place of D3D12_RESOURCE_FLAGS; the title's console flags
|
||||
* (render target, depth, UAV, deny-compression) are those values.
|
||||
* XGTextureAddressComputer vtable: 0 AddRef, 1 Release, 2 GetResourceLayout,
|
||||
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, ...
|
||||
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, 5 GetMipLevelOffsetBytes,
|
||||
* 6 GetTexelElementOffsetBytes, 7 GetTexelCoordinate, 8 CopyIntoSubresource,
|
||||
* 9 CopyFromSubresource(linear destination, plane, subresource, sample, tiled base, row pitch,
|
||||
* slice pitch): the untiled copy of one subresource.
|
||||
* void XGEnableExclusiveLocking(BOOL), to be called before any computer is created.
|
||||
*/
|
||||
#include "gdk_xg.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -25,6 +30,12 @@ struct XgComputerVtbl {
|
||||
void* GetResourceLayout;
|
||||
UINT64 (*GetResourceSizeBytes)(XgComputer*);
|
||||
UINT64 (*GetResourceBaseAlignmentBytes)(XgComputer*);
|
||||
void* GetMipLevelOffsetBytes;
|
||||
void* GetTexelElementOffsetBytes;
|
||||
void* GetTexelCoordinate;
|
||||
void* CopyIntoSubresource;
|
||||
HRESULT(__cdecl* CopyFromSubresource)(XgComputer*, void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
|
||||
const void* tiled_base, UINT32 row_pitch, UINT32 slice_pitch);
|
||||
};
|
||||
struct XgComputer {
|
||||
const XgComputerVtbl* vtbl;
|
||||
@@ -86,6 +97,63 @@ bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint
|
||||
return true;
|
||||
}
|
||||
|
||||
UINT bx_texture_element_bytes(DXGI_FORMAT f, bool* block) {
|
||||
*block = false;
|
||||
switch (f) {
|
||||
case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB:
|
||||
case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM:
|
||||
*block = true;
|
||||
return 8;
|
||||
case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB:
|
||||
case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB:
|
||||
case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM:
|
||||
case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16:
|
||||
case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB:
|
||||
*block = true;
|
||||
return 16;
|
||||
case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: case DXGI_FORMAT_R8_TYPELESS:
|
||||
return 1;
|
||||
case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM:
|
||||
case DXGI_FORMAT_R16_TYPELESS:
|
||||
return 2;
|
||||
case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
|
||||
case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
|
||||
case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_TYPELESS:
|
||||
case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R11G11B10_FLOAT:
|
||||
case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_TYPELESS:
|
||||
return 4;
|
||||
case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_TYPELESS:
|
||||
case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_TYPELESS:
|
||||
return 8;
|
||||
case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_TYPELESS:
|
||||
return 16;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT bx_gdk_xg_detile(const D3D12_RESOURCE_DESC& desc, const void* tiled, uint8_t* base,
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* footprints, const UINT* rows, UINT count, UINT* subresources) {
|
||||
*subresources = 0;
|
||||
const CreateTextureComputerFn create = create_computer();
|
||||
bool block = false;
|
||||
const UINT element = bx_texture_element_bytes(desc.Format, &block);
|
||||
if (!create || !tiled || !base || !footprints || !rows || !element || !bx_is_console_texture_layout(desc) ||
|
||||
desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count > 1) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
XgComputer* computer = nullptr;
|
||||
HRESULT hr = create(&desc, &computer);
|
||||
if (FAILED(hr) || !computer) return FAILED(hr) ? hr : E_FAIL;
|
||||
for (UINT sub = 0; sub < count && SUCCEEDED(hr); ++sub) {
|
||||
const UINT pitch = footprints[sub].Footprint.RowPitch;
|
||||
hr = computer->vtbl->CopyFromSubresource(computer, base + footprints[sub].Offset, 0, sub, 0, tiled, pitch, pitch * rows[sub]);
|
||||
if (SUCCEEDED(hr)) ++*subresources;
|
||||
}
|
||||
computer->vtbl->Release(computer);
|
||||
return hr;
|
||||
}
|
||||
|
||||
extern "C" void bx_gdk_xg_enable_locking() {
|
||||
HMODULE xg = microsoft_xg();
|
||||
if (!xg) return;
|
||||
|
||||
@@ -22,6 +22,18 @@ bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc);
|
||||
refuses the description; `size` and `alignment` are then untouched. */
|
||||
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment);
|
||||
|
||||
/* Untiles every subresource of a texture laid out as `desc` (a console layout) from title memory at
|
||||
`tiled` into CPU memory at `base`, subresource i at footprints[i] (D3D12 placed-footprint form,
|
||||
as GetCopyableFootprints gives them for the host texture), through XG's CopyFromSubresource.
|
||||
*subresources is the number untiled. E_NOTIMPL when XG is not available or the format has no
|
||||
known element size; the caller checks that the XG size of `desc` is readable at `tiled`. */
|
||||
HRESULT bx_gdk_xg_detile(const D3D12_RESOURCE_DESC& desc, const void* tiled, uint8_t* base,
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* footprints, const UINT* rows, UINT count, UINT* subresources);
|
||||
|
||||
/* Bytes per element (a texel, or a 4x4 block of a BC format) of the formats textures are copied
|
||||
for, or 0. *block is set for BC formats. */
|
||||
UINT bx_texture_element_bytes(DXGI_FORMAT format, bool* block);
|
||||
|
||||
/* Enables XG's internal lock (XGEnableExclusiveLocking) before any texture computer is created,
|
||||
so the title's threads and the shim can both create computers. Called at device creation. */
|
||||
extern "C" void bx_gdk_xg_enable_locking();
|
||||
@@ -158,7 +158,7 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
}
|
||||
bx_xbox_sync_mapped_buffers();
|
||||
bx_xbox_refresh_bound_memory(host.data(), count);
|
||||
bx_console_submit(host.data(), count);
|
||||
bx_console_submit(queue, host.data(), count);
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) apply_wait(queue, w);
|
||||
}
|
||||
|
||||
+322
-8
@@ -8,16 +8,22 @@
|
||||
*
|
||||
* - a buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's
|
||||
* memory when it is created;
|
||||
* - a texture gets a committed texture whose contents are not filled (logged); texture
|
||||
* contents need the console tiling translation (xg_xs) first.
|
||||
* - a texture gets a committed texture on a default heap. Its contents reach the host when a
|
||||
* translated draw reads it (bx_xbox_texture_contents, below: a CPU-writable copy filled from
|
||||
* title memory, untiled through the GDK's XG); other views of it read the empty texture
|
||||
* (logged at creation when translation is off).
|
||||
*
|
||||
* The title's address and the shadow are recorded, and the resource reports the title's address
|
||||
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
|
||||
* title addresses in GPU calls, are not done yet; both are logged when reached.
|
||||
*/
|
||||
#include "console_formats.h"
|
||||
#include "console_pipelines.h"
|
||||
#include "gdk_xg.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -131,7 +137,8 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
|
||||
}
|
||||
resource->Unmap(0, nullptr);
|
||||
}
|
||||
} else {
|
||||
} else if (!bx_console_shaders_enabled()) {
|
||||
// Contents are copied only for views of translated draws (bx_xbox_texture_contents).
|
||||
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
|
||||
}
|
||||
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
|
||||
@@ -182,6 +189,165 @@ uint64_t view_location(const void* xbox_desc) {
|
||||
return va;
|
||||
}
|
||||
|
||||
/*
|
||||
* Texture contents (#745). A texture placed in title memory gets its pixels from that memory when
|
||||
* a view of it is resolved for a translated draw (console_descriptors.cpp): into a copy of its host
|
||||
* texture on a default heap, which the view then reads. The texels are written into an upload
|
||||
* buffer of the copy's own (persistently mapped) and copied into it by the GPU, on a list the shim
|
||||
* executes on the submitting queue ahead of the title's lists (BxTextureUploads); the copy is only
|
||||
* ever in the shim's states (shader resource, or copy destination during that list). A linear layout (D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR, 0x100) is copied
|
||||
* row by row: rows in title memory are 256-byte aligned, the layout XG reports for linear
|
||||
* textures. Other console layouts are untiled through the GDK's XG library (ADR 0010).
|
||||
*
|
||||
* The copy is made the first time a translated draw reads the texture, and returned only once its
|
||||
* upload has been recorded (until then, and after a failure, the view reads `host` and the next
|
||||
* draw tries again). An upload buffer is not written again until the GPU is past its last copy;
|
||||
* until then a check is put off. Because a title may still be filling a texture (streaming) when it is first drawn, a
|
||||
* later draw checks whether the title memory changed: a hash over a sample of it (64 bytes every
|
||||
* 64 KiB, and the last 64), at most once per interval that starts at kTextureCheckMs and doubles up
|
||||
* to kTextureCheckMaxMs while nothing changes. Only a change copies the texture again (logged), and
|
||||
* resets the interval. Render targets, depth and UAV textures are written by the GPU and are
|
||||
* never copied over.
|
||||
*
|
||||
* Accepted risk: a change that falls entirely between the sampled 64-byte lines is not seen, and
|
||||
* the texture keeps its earlier contents until a sampled line changes too.
|
||||
*
|
||||
* Limit: the contents live in this side copy, not in the host texture. Only views resolved for
|
||||
* translated draws read it; a copy command out of the texture, or any other view, reads the empty
|
||||
* host texture (bx_xbox_note_texture_copy_source logs the first such copy).
|
||||
*/
|
||||
enum class TextureKind { None, Linear, Tiled };
|
||||
constexpr UINT kConsoleLayoutLinear = 0x100;
|
||||
constexpr uint64_t kTextureCheckMs = 250;
|
||||
constexpr uint64_t kTextureCheckMaxMs = 4000;
|
||||
|
||||
struct TextureCopy {
|
||||
ID3D12Resource* copy = nullptr; // owned; default heap, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE
|
||||
ID3D12Resource* upload = nullptr; // owned; upload heap, mapped at `mapped`
|
||||
uint8_t* mapped = nullptr;
|
||||
std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> footprints;
|
||||
std::vector<UINT> rows;
|
||||
uint64_t title_va = 0;
|
||||
bool filled = false; // an upload has been recorded
|
||||
uint64_t checked_at = 0; // GetTickCount64 of the last copy or check
|
||||
uint64_t interval = kTextureCheckMs;
|
||||
uint64_t sample = 0; // the sample hash the copy was made from
|
||||
ID3D12Fence* fence = nullptr; // the upload list's fence and the value after the last copy
|
||||
uint64_t fence_value = 0;
|
||||
};
|
||||
std::mutex g_texture_lock;
|
||||
std::unordered_map<const void*, TextureCopy> g_texture_copies; // host texture -> its copy
|
||||
|
||||
/* FNV-1a over 64 bytes every 64 KiB of [va, va + bytes), and the last 64 bytes. */
|
||||
uint64_t sample_hash(uint64_t va, uint64_t bytes) {
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
auto mix = [&](uint64_t at) {
|
||||
const uint64_t n = at + 64 <= bytes ? 64 : bytes - at;
|
||||
const auto* p = reinterpret_cast<const uint8_t*>(va + at);
|
||||
for (uint64_t i = 0; i < n; ++i) h = (h ^ p[i]) * 0x100000001b3ull;
|
||||
};
|
||||
for (uint64_t at = 0; at < bytes; at += 64 * 1024) mix(at);
|
||||
if (bytes > 64) mix(bytes - 64);
|
||||
return h;
|
||||
}
|
||||
|
||||
TextureKind texture_kind(const D3D12_RESOURCE_DESC& desc) {
|
||||
constexpr UINT kGpuWritten = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
|
||||
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count > 1 ||
|
||||
(static_cast<UINT>(desc.Flags) & kGpuWritten) || bx_is_console_only_format(desc.Format)) {
|
||||
return TextureKind::None;
|
||||
}
|
||||
bool block = false;
|
||||
if (!bx_texture_element_bytes(desc.Format, &block)) return TextureKind::None;
|
||||
const UINT layout = static_cast<UINT>(desc.Layout);
|
||||
if (layout == kConsoleLayoutLinear && !block && desc.MipLevels <= 1 && desc.DepthOrArraySize <= 1) return TextureKind::Linear;
|
||||
if (layout >= kConsoleLayoutLinear && bx_gdk_xg_available()) return TextureKind::Tiled;
|
||||
return TextureKind::None;
|
||||
}
|
||||
|
||||
void note_texture_skipped(const D3D12_RESOURCE_DESC& desc, const char* why) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) >= 16) return;
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "texture %llux%u layout=0x%x format=%d flags=0x%x: contents not copied (%s)",
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<UINT>(desc.Layout),
|
||||
static_cast<int>(desc.Format), static_cast<UINT>(desc.Flags), why);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_contents", detail);
|
||||
}
|
||||
|
||||
/* A default-heap copy of `host`'s description and an upload buffer for all its subresources. */
|
||||
bool make_texture_copy(ID3D12Resource* host, TextureCopy& t) {
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(host->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return false;
|
||||
const D3D12_RESOURCE_DESC desc = host->GetDesc();
|
||||
const UINT subresources = (desc.MipLevels ? desc.MipLevels : 1) * (desc.DepthOrArraySize ? desc.DepthOrArraySize : 1);
|
||||
t.footprints.resize(subresources);
|
||||
t.rows.resize(subresources);
|
||||
std::vector<UINT64> row_bytes(subresources);
|
||||
UINT64 total = 0;
|
||||
device->GetCopyableFootprints(&desc, 0, subresources, 0, t.footprints.data(), t.rows.data(), row_bytes.data(), &total);
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.copy));
|
||||
D3D12_RESOURCE_DESC buffer{};
|
||||
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer.Width = total;
|
||||
buffer.Height = 1;
|
||||
buffer.DepthOrArraySize = 1;
|
||||
buffer.MipLevels = 1;
|
||||
buffer.SampleDesc.Count = 1;
|
||||
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
if (SUCCEEDED(hr) && total) {
|
||||
hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.upload));
|
||||
}
|
||||
if (SUCCEEDED(hr) && t.upload) hr = t.upload->Map(0, nullptr, reinterpret_cast<void**>(&t.mapped));
|
||||
device->Release();
|
||||
if (FAILED(hr) || !total || !t.mapped) {
|
||||
bx_xbox_log_host_failure("XboxResource", "CreateCommittedResource(texture contents copy)", FAILED(hr) ? hr : E_FAIL);
|
||||
if (t.upload) t.upload->Release();
|
||||
if (t.copy) t.copy->Release();
|
||||
t = TextureCopy{};
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Upload buffers and copies the GPU may still be reading, released once their fence passes. */
|
||||
struct Retired {
|
||||
ID3D12Resource* resource;
|
||||
ID3D12Fence* fence;
|
||||
uint64_t value;
|
||||
};
|
||||
std::vector<Retired> g_retired; // under g_texture_lock
|
||||
|
||||
void retire_locked(TextureCopy& t) {
|
||||
for (ID3D12Resource* r : {t.upload, t.copy}) {
|
||||
if (!r) continue;
|
||||
if (t.fence && t.fence->GetCompletedValue() < t.fence_value) {
|
||||
g_retired.push_back({r, t.fence, t.fence_value});
|
||||
} else {
|
||||
r->Release();
|
||||
}
|
||||
}
|
||||
t.upload = t.copy = nullptr;
|
||||
}
|
||||
|
||||
void sweep_retired_locked() {
|
||||
for (size_t i = 0; i < g_retired.size();) {
|
||||
if (g_retired[i].fence->GetCompletedValue() >= g_retired[i].value) {
|
||||
g_retired[i].resource->Release();
|
||||
g_retired[i] = g_retired.back();
|
||||
g_retired.pop_back();
|
||||
} else {
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
@@ -236,9 +402,11 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Reso
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(
|
||||
bx_xbox_unwrap_as(resource), xbox_desc ? host.of(&pc, "CreatePlacedShaderResourceViewX") : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
ID3D12Resource* host_resource = bx_xbox_unwrap_as(resource);
|
||||
const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc = xbox_desc ? host.of(&pc, "CreatePlacedShaderResourceViewX") : nullptr;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
|
||||
// Translated draws find the view through its marker, as for CreateShaderResourceView (#745).
|
||||
bx_console_mark_srv(dest.ptr, host_resource, host_desc);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
@@ -377,6 +545,144 @@ bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64
|
||||
attributes});
|
||||
}
|
||||
|
||||
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;
|
||||
shadow = g_shadows[i];
|
||||
}
|
||||
const TextureKind kind = texture_kind(shadow.desc);
|
||||
if (kind == TextureKind::None) {
|
||||
note_texture_skipped(shadow.desc, "no copy for this layout or format");
|
||||
return host;
|
||||
}
|
||||
// The texture's entry, made on first use. The lock is held for the whole check and upload:
|
||||
// the upload writes the entry's buffer and records onto the submission's list.
|
||||
std::lock_guard<std::mutex> guard(g_texture_lock);
|
||||
sweep_retired_locked();
|
||||
TextureCopy& known = g_texture_copies[host];
|
||||
if (!known.copy || known.title_va != shadow.title_va) {
|
||||
retire_locked(known);
|
||||
known = TextureCopy{};
|
||||
if (!make_texture_copy(host, known)) {
|
||||
g_texture_copies.erase(host);
|
||||
note_texture_skipped(shadow.desc, "the host refused a copy or its upload buffer");
|
||||
return host;
|
||||
}
|
||||
known.title_va = shadow.title_va;
|
||||
}
|
||||
const uint64_t now = GetTickCount64();
|
||||
if (known.filled && now - known.checked_at < known.interval) return known.copy;
|
||||
// The GPU is still copying from this buffer (from an earlier submission): check later.
|
||||
if (known.fence && known.fence->GetCompletedValue() < known.fence_value) return known.filled ? known.copy : host;
|
||||
known.checked_at = now;
|
||||
// The title memory the texture occupies.
|
||||
uint64_t bytes = 0;
|
||||
UINT title_pitch = 0;
|
||||
bool block = false;
|
||||
const UINT element = bx_texture_element_bytes(shadow.desc.Format, &block);
|
||||
if (kind == TextureKind::Linear) {
|
||||
title_pitch = static_cast<UINT>((shadow.desc.Width * element + 255) / 256 * 256);
|
||||
bytes = static_cast<uint64_t>(title_pitch) * shadow.desc.Height;
|
||||
} else {
|
||||
uint64_t alignment = 0;
|
||||
if (!bx_gdk_xg_layout_size(shadow.desc, &bytes, &alignment)) bytes = 0;
|
||||
}
|
||||
HRESULT hr = E_FAIL;
|
||||
UINT subresources = 0;
|
||||
uint64_t sample = 0;
|
||||
const bool filled = known.filled;
|
||||
if (!bytes) {
|
||||
hr = E_NOTIMPL;
|
||||
} else if (!readable(reinterpret_cast<const void*>(shadow.title_va), bytes)) {
|
||||
hr = E_ACCESSDENIED;
|
||||
} else {
|
||||
sample = sample_hash(shadow.title_va, bytes);
|
||||
if (filled && sample == known.sample) {
|
||||
hr = S_FALSE; // checked, unchanged
|
||||
} else if (kind == TextureKind::Linear) {
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& fp = known.footprints[0];
|
||||
const size_t row = static_cast<size_t>(shadow.desc.Width) * element;
|
||||
for (UINT y = 0; y < shadow.desc.Height; ++y) {
|
||||
std::memcpy(known.mapped + fp.Offset + static_cast<size_t>(y) * fp.Footprint.RowPitch,
|
||||
reinterpret_cast<const uint8_t*>(shadow.title_va) + static_cast<size_t>(y) * title_pitch, row);
|
||||
}
|
||||
subresources = 1;
|
||||
hr = S_OK;
|
||||
} else {
|
||||
hr = bx_gdk_xg_detile(shadow.desc, reinterpret_cast<const void*>(shadow.title_va), known.mapped, known.footprints.data(),
|
||||
known.rows.data(), static_cast<UINT>(known.footprints.size()), &subresources);
|
||||
}
|
||||
}
|
||||
if (hr == S_OK) {
|
||||
ID3D12GraphicsCommandList* list = uploads->list;
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = known.copy;
|
||||
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
|
||||
b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
list->ResourceBarrier(1, &b);
|
||||
for (UINT sub = 0; sub < subresources; ++sub) {
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{known.copy, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
dst.SubresourceIndex = sub;
|
||||
D3D12_TEXTURE_COPY_LOCATION src{known.upload, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
|
||||
src.PlacedFootprint = known.footprints[sub];
|
||||
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
}
|
||||
std::swap(b.Transition.StateBefore, b.Transition.StateAfter);
|
||||
list->ResourceBarrier(1, &b);
|
||||
uploads->recorded = true;
|
||||
known.fence = uploads->fence;
|
||||
known.fence_value = uploads->value;
|
||||
known.filled = true;
|
||||
known.sample = sample;
|
||||
known.interval = kTextureCheckMs;
|
||||
} else if (hr == S_FALSE) {
|
||||
known.interval = known.interval * 2 > kTextureCheckMaxMs ? kTextureCheckMaxMs : known.interval * 2;
|
||||
} else if (!known.filled) {
|
||||
known.checked_at = 0; // the next draw tries again
|
||||
}
|
||||
if (hr != S_FALSE) {
|
||||
static std::atomic<int> logged{0};
|
||||
static std::atomic<int> failures{0};
|
||||
static std::atomic<int> recopied{0};
|
||||
const bool again = SUCCEEDED(hr) && filled;
|
||||
if (FAILED(hr) ? failures.fetch_add(1) < 16 : again ? recopied.fetch_add(1) < 8 : logged.fetch_add(1) < 8) {
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail), "%s texture %llux%u layout=0x%x format=%d mips=%u: %u subresource(s)%s, hr=0x%08lx",
|
||||
kind == TextureKind::Linear ? "linear" : "tiled", static_cast<unsigned long long>(shadow.desc.Width),
|
||||
shadow.desc.Height, static_cast<UINT>(shadow.desc.Layout), static_cast<int>(shadow.desc.Format),
|
||||
shadow.desc.MipLevels, subresources, again ? " copied again: its title memory changed" : "",
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "texture_contents", detail);
|
||||
}
|
||||
}
|
||||
return known.filled ? known.copy : host;
|
||||
}
|
||||
|
||||
void bx_xbox_note_texture_copy_source(ID3D12Resource* source) {
|
||||
if (!source) return;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_texture_lock);
|
||||
auto it = g_texture_copies.find(source);
|
||||
if (it == g_texture_copies.end() || !it->second.filled) return;
|
||||
}
|
||||
static std::atomic<bool> logged{false};
|
||||
if (logged.exchange(true)) return;
|
||||
const D3D12_RESOURCE_DESC d = source->GetDesc();
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"a copy command reads texture %llux%u format=%d, whose contents are in a side copy only; the copy reads the empty "
|
||||
"host texture (logged once)",
|
||||
static_cast<unsigned long long>(d.Width), d.Height, static_cast<int>(d.Format));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_contents", detail);
|
||||
}
|
||||
|
||||
void bx_xbox_placed_forget(IUnknown* host) {
|
||||
Shadow gone{};
|
||||
{
|
||||
@@ -389,6 +695,14 @@ void bx_xbox_placed_forget(IUnknown* host) {
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_texture_lock);
|
||||
auto copy = g_texture_copies.find(host);
|
||||
if (copy != g_texture_copies.end()) {
|
||||
retire_locked(copy->second);
|
||||
g_texture_copies.erase(copy);
|
||||
}
|
||||
}
|
||||
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
|
||||
}
|
||||
|
||||
@@ -480,8 +794,8 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void*, HANDLE ha
|
||||
* Map on a resource that has title-visible memory (placed at a title address, or committed with
|
||||
* XMemAlloc memory) returns that memory, as on the console, where CPU and GPU share it. Other
|
||||
* resources map their host resource. Writes through the title pointer reach the host resource
|
||||
* only where this layer copies them (buffers at creation; texture contents are not copied yet,
|
||||
* logged at creation).
|
||||
* only where this layer copies them (buffers at creation; texture contents when a translated draw
|
||||
* reads them, bx_xbox_texture_contents).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data) {
|
||||
BX_D3D_TRACE("XboxResource", "Map");
|
||||
|
||||
@@ -8,9 +8,21 @@
|
||||
* window (the visible window owned by this process), sized to plane 0's first resource. Each
|
||||
* present copies that resource into the current back buffer when formats and sizes match, and
|
||||
* otherwise leaves the back buffer unchanged (logged once), then presents with sync interval 0: frame pacing
|
||||
* is the title's own, through the frame events (frame_pacing.cpp). Plane 1, source and
|
||||
* destination rectangles, colour spaces and scaling are not applied (logged once).
|
||||
* is the title's own, through the frame events (frame_pacing.cpp).
|
||||
*
|
||||
* Several planes, or source and destination rectangles, are composed the way the console's display
|
||||
* hardware composes them (authorized GDK documentation, "Hardware overlays"): plane 0 is the
|
||||
* background plane and plane 1 the HUD plane in front of it; content is premultiplied alpha; a
|
||||
* plane's source rectangle (pSrcViewRects) is in texels of its resource, its destination rectangle
|
||||
* (pDestPlacementBase, D3D12XBOX_VIEW_RECT) is normalized to the output; a plane left out is black
|
||||
* with alpha 0. Each plane is drawn, scaled with a bilinear filter, over transparent black in plane
|
||||
* order with the blend ONE, INV_SRC_ALPHA into a texture of the swapchain's size, which is copied
|
||||
* to the back buffer. The shaders are compiled at the first such present with the GDK's PC
|
||||
* dxcompiler.dll (bx_console_compile_hlsl); without it plane 0 is copied as before (logged). Colour
|
||||
* spaces other than RGB full G2.2 P709 (the SDR case) are composed as SDR, in plane order (logged
|
||||
* once); for HDR the documentation puts the scene in plane 1 and the UI in plane 0.
|
||||
*/
|
||||
#include "console_pipelines.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <dxgi1_4.h>
|
||||
@@ -21,6 +33,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cwchar>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
@@ -58,6 +71,7 @@ struct Presenter {
|
||||
};
|
||||
Presenter g;
|
||||
|
||||
|
||||
struct FindWindow {
|
||||
DWORD pid;
|
||||
HWND found;
|
||||
@@ -167,6 +181,175 @@ void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_
|
||||
list->ResourceBarrier(1, &b);
|
||||
}
|
||||
|
||||
/* Plane composition (see the file comment). Created at the first present that needs it. */
|
||||
constexpr UINT kMaxPlanes = 4;
|
||||
|
||||
struct Composer {
|
||||
bool tried = false;
|
||||
bool ready = false;
|
||||
ID3D12RootSignature* root = nullptr;
|
||||
ID3D12PipelineState* pso = nullptr;
|
||||
ID3D12DescriptorHeap* srvs = nullptr; // shader-visible, kMaxPlanes per back buffer
|
||||
ID3D12DescriptorHeap* rtv = nullptr;
|
||||
ID3D12Resource* target = nullptr; // swapchain-sized, the composed frame
|
||||
UINT srv_size = 0;
|
||||
};
|
||||
Composer c;
|
||||
|
||||
const char kComposeRoot[] =
|
||||
"#define RS \"RootConstants(num32BitConstants=8, b0), DescriptorTable(SRV(t0)), "
|
||||
"StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)\"\n"
|
||||
"cbuffer Place : register(b0) { float4 dst; float4 src; };\n";
|
||||
|
||||
// A quad over the destination rectangle (normalized, y down), sampling the source rectangle (uv).
|
||||
const char kComposeVs[] =
|
||||
"struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; };\n"
|
||||
"[RootSignature(RS)] V main(uint id : SV_VertexID) {\n"
|
||||
" float2 c = float2(id & 1, id >> 1);\n"
|
||||
" float2 p = lerp(dst.xy, dst.zw, c);\n"
|
||||
" V o; o.pos = float4(p.x * 2.0 - 1.0, 1.0 - p.y * 2.0, 0.0, 1.0); o.uv = lerp(src.xy, src.zw, c); return o;\n"
|
||||
"}\n";
|
||||
|
||||
const char kComposePs[] =
|
||||
"Texture2D<float4> plane : register(t0);\n"
|
||||
"SamplerState linear_clamp : register(s0);\n"
|
||||
"[RootSignature(RS)] float4 main(float4 pos : SV_Position, float2 uv : TEXCOORD0) : SV_Target0 {\n"
|
||||
" return plane.Sample(linear_clamp, uv);\n"
|
||||
"}\n";
|
||||
|
||||
bool composer_ready(ID3D12Device* device) {
|
||||
if (c.tried) return c.ready;
|
||||
c.tried = true;
|
||||
std::vector<uint8_t> vs, ps;
|
||||
std::string why;
|
||||
const std::string vs_src = std::string(kComposeRoot) + kComposeVs;
|
||||
const std::string ps_src = std::string(kComposeRoot) + kComposePs;
|
||||
if (!bx_console_compile_hlsl(vs_src.c_str(), false, vs, why) || !bx_console_compile_hlsl(ps_src.c_str(), true, ps, why)) {
|
||||
const std::string detail = "plane composition unavailable (" + why + "); plane 0 is copied as is";
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail.c_str());
|
||||
return false;
|
||||
}
|
||||
HRESULT hr = device->CreateRootSignature(0, vs.data(), vs.size(), __uuidof(ID3D12RootSignature), reinterpret_cast<void**>(&c.root));
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
|
||||
d.pRootSignature = c.root;
|
||||
d.VS = {vs.data(), vs.size()};
|
||||
d.PS = {ps.data(), ps.size()};
|
||||
D3D12_RENDER_TARGET_BLEND_DESC& b = d.BlendState.RenderTarget[0];
|
||||
b.BlendEnable = TRUE; // premultiplied alpha: out = src + dst * (1 - src.a)
|
||||
b.SrcBlend = D3D12_BLEND_ONE;
|
||||
b.DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
b.BlendOp = D3D12_BLEND_OP_ADD;
|
||||
b.SrcBlendAlpha = D3D12_BLEND_ONE;
|
||||
b.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
b.BlendOpAlpha = D3D12_BLEND_OP_ADD;
|
||||
b.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
|
||||
d.SampleMask = UINT_MAX;
|
||||
d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
|
||||
d.RasterizerState.DepthClipEnable = TRUE;
|
||||
d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
d.NumRenderTargets = 1;
|
||||
d.RTVFormats[0] = g.format;
|
||||
d.SampleDesc.Count = 1;
|
||||
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&d, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&c.pso));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC heap{};
|
||||
heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
|
||||
heap.NumDescriptors = kMaxPlanes * kBuffers;
|
||||
heap.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
|
||||
if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&heap, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&c.srvs));
|
||||
heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
heap.NumDescriptors = 1;
|
||||
heap.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
|
||||
if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&heap, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&c.rtv));
|
||||
D3D12_HEAP_PROPERTIES props{};
|
||||
props.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
D3D12_RESOURCE_DESC t{};
|
||||
t.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
t.Width = g.width;
|
||||
t.Height = g.height;
|
||||
t.DepthOrArraySize = 1;
|
||||
t.MipLevels = 1;
|
||||
t.Format = g.format;
|
||||
t.SampleDesc.Count = 1;
|
||||
t.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &t, D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&c.target));
|
||||
}
|
||||
if (FAILED(hr)) {
|
||||
log_hr("plane composition resources (plane 0 is copied as is)", hr);
|
||||
return false;
|
||||
}
|
||||
device->CreateRenderTargetView(c.target, nullptr, c.rtv->GetCPUDescriptorHandleForHeapStart());
|
||||
c.srv_size = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
|
||||
c.ready = true;
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox", "plane composition ready: planes are composed in order, premultiplied alpha");
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Records the composition of `count` planes into c.target, then the copy to `back`. */
|
||||
void compose(ID3D12Device* device, const PlaneParameters* planes, UINT count, UINT index, ID3D12Resource* back) {
|
||||
ID3D12GraphicsCommandList* list = g.list;
|
||||
ID3D12Resource* sources[kMaxPlanes] = {};
|
||||
UINT n = 0;
|
||||
for (UINT i = 0; i < count && n < kMaxPlanes; ++i) {
|
||||
ID3D12Resource* r = planes[i].ResourceCount && planes[i].ppResources ? bx_xbox_unwrap_as(planes[i].ppResources[0]) : nullptr;
|
||||
bool repeated = false;
|
||||
for (UINT k = 0; k < n; ++k) repeated = repeated || sources[k] == r;
|
||||
sources[n++] = repeated ? nullptr : r; // a resource shown twice is transitioned once
|
||||
}
|
||||
for (UINT i = 0; i < n; ++i) {
|
||||
if (sources[i]) barrier(list, sources[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
|
||||
}
|
||||
barrier(list, c.target, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET);
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE rtv = c.rtv->GetCPUDescriptorHandleForHeapStart();
|
||||
const FLOAT clear[4] = {0, 0, 0, 0}; // a plane left out is black with alpha 0
|
||||
list->ClearRenderTargetView(rtv, clear, 0, nullptr);
|
||||
list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
|
||||
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(g.width), static_cast<float>(g.height), 0, 1};
|
||||
const D3D12_RECT scissor{0, 0, static_cast<LONG>(g.width), static_cast<LONG>(g.height)};
|
||||
list->RSSetViewports(1, &viewport);
|
||||
list->RSSetScissorRects(1, &scissor);
|
||||
list->SetGraphicsRootSignature(c.root);
|
||||
list->SetPipelineState(c.pso);
|
||||
list->SetDescriptorHeaps(1, &c.srvs);
|
||||
list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
|
||||
for (UINT i = 0; i < count && i < kMaxPlanes; ++i) {
|
||||
const PlaneParameters& p = planes[i];
|
||||
ID3D12Resource* r = p.ResourceCount && p.ppResources ? bx_xbox_unwrap_as(p.ppResources[0]) : nullptr;
|
||||
if (!r) continue;
|
||||
const D3D12_RESOURCE_DESC rd = r->GetDesc();
|
||||
float place[8] = {0, 0, 1, 1, 0, 0, 1, 1};
|
||||
if (p.pDestPlacementBase) std::memcpy(place, p.pDestPlacementBase, 4 * sizeof(float)); // D3D12XBOX_VIEW_RECT
|
||||
if (p.pSrcViewRects && rd.Width && rd.Height) {
|
||||
const D3D12_RECT& s = p.pSrcViewRects[0];
|
||||
place[4] = static_cast<float>(s.left) / static_cast<float>(rd.Width);
|
||||
place[5] = static_cast<float>(s.top) / static_cast<float>(rd.Height);
|
||||
place[6] = static_cast<float>(s.right) / static_cast<float>(rd.Width);
|
||||
place[7] = static_cast<float>(s.bottom) / static_cast<float>(rd.Height);
|
||||
}
|
||||
const UINT slot = index * kMaxPlanes + i;
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE cpu = c.srvs->GetCPUDescriptorHandleForHeapStart();
|
||||
cpu.ptr += static_cast<SIZE_T>(slot) * c.srv_size;
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE gpu = c.srvs->GetGPUDescriptorHandleForHeapStart();
|
||||
gpu.ptr += static_cast<UINT64>(slot) * c.srv_size;
|
||||
device->CreateShaderResourceView(r, nullptr, cpu);
|
||||
list->SetGraphicsRoot32BitConstants(0, 8, place, 0);
|
||||
list->SetGraphicsRootDescriptorTable(1, gpu);
|
||||
list->DrawInstanced(4, 1, 0, 0);
|
||||
}
|
||||
barrier(list, c.target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
barrier(list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{back, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{c.target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(list, back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT);
|
||||
barrier(list, c.target, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
for (UINT i = 0; i < n; ++i) {
|
||||
if (sources[i]) barrier(list, sources[i], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Diagnostics (off unless BX_PRESENT_DUMP=<folder>): every BX_PRESENT_DUMP_EVERY-th present (default
|
||||
// 64, at most 32 files) the presented buffer is copied to a readback buffer and written as a BMP,
|
||||
@@ -308,10 +491,19 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
g.failed = true;
|
||||
return S_OK; // the title keeps running; frames are not shown (logged)
|
||||
}
|
||||
static std::atomic<bool> logged_extra{false};
|
||||
if ((plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase) && !logged_extra.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox",
|
||||
"plane 1, view rectangles, placement and scaling are not applied; plane 0 is copied as is");
|
||||
const bool layered = plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase;
|
||||
if (layered) {
|
||||
static std::atomic<bool> logged_hdr{false};
|
||||
bool sdr = true;
|
||||
for (UINT i = 0; i < plane_count; ++i) sdr = sdr && planes[i].ColorSpace == 0; // DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709
|
||||
if (!sdr && !logged_hdr.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox",
|
||||
"a plane has a colour space other than RGB full G2.2 P709; planes are composed as SDR, in plane order");
|
||||
}
|
||||
if (plane_count > kMaxPlanes) {
|
||||
static std::atomic<bool> logged_many{false};
|
||||
if (!logged_many.exchange(true)) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", "more than 4 planes; the rest are not shown");
|
||||
}
|
||||
}
|
||||
const UINT index = g.swapchain->GetCurrentBackBufferIndex();
|
||||
if (g.fence->GetCompletedValue() < g.fence_values[index]) {
|
||||
@@ -328,7 +520,12 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
g.list->Reset(g.allocators[index], nullptr);
|
||||
const bool copyable = desc.Width == g.width && desc.Height == g.height && swapchain_format(desc.Format) == g.format &&
|
||||
desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1;
|
||||
if (copyable) {
|
||||
ID3D12Device* device = nullptr;
|
||||
queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
const bool composed = (layered || !copyable) && device && composer_ready(device);
|
||||
if (composed) {
|
||||
compose(device, planes, plane_count, index, back);
|
||||
} else if (copyable) {
|
||||
// The title's buffer is assumed to be presentable (PRESENT, i.e. COMMON) when PresentX is called.
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
@@ -346,6 +543,7 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
}
|
||||
if (device) device->Release();
|
||||
g.list->Close();
|
||||
ID3D12CommandList* lists[] = {g.list};
|
||||
g.queue->ExecuteCommandLists(1, lists);
|
||||
@@ -354,7 +552,13 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
g.fence_values[index] = g.next_value++;
|
||||
g.queue->Signal(g.fence, g.fence_values[index]);
|
||||
const UINT64 n = ++g.presents;
|
||||
if (dump_folder() && copyable && n % dump_every() == 0) dump_frame(g.queue, source, desc, n);
|
||||
if (dump_folder() && n % dump_every() == 0) {
|
||||
if (composed) {
|
||||
dump_frame(g.queue, c.target, c.target->GetDesc(), n); // the composed frame
|
||||
} else if (copyable) {
|
||||
dump_frame(g.queue, source, desc, n);
|
||||
}
|
||||
}
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "frames presented=%llu last hr=0x%08lx", static_cast<unsigned long long>(n),
|
||||
|
||||
@@ -310,6 +310,7 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_
|
||||
if (src) {
|
||||
s = *src;
|
||||
s.pResource = bx_xbox_unwrap_as(s.pResource);
|
||||
bx_xbox_note_texture_copy_source(s.pResource);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
|
||||
}
|
||||
|
||||
@@ -233,6 +233,23 @@ UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
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);
|
||||
/* Texture uploads of one submission (console_descriptors.cpp): an open list the shim executes on
|
||||
the queue ahead of the title's lists, and the fence value signaled after it. */
|
||||
struct BxTextureUploads {
|
||||
ID3D12GraphicsCommandList* list;
|
||||
ID3D12Fence* fence;
|
||||
UINT64 value;
|
||||
bool recorded; // set when a copy was recorded on `list`
|
||||
};
|
||||
/* 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
|
||||
from that memory (linear, or untiled through the GDK's XG) by a GPU copy recorded on
|
||||
`uploads->list`, and filled again when a sampled hash of that memory changes (checked at a
|
||||
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);
|
||||
/* Logs once when a copy command reads a texture whose contents are only in that side copy. */
|
||||
void bx_xbox_note_texture_copy_source(ID3D12Resource* source);
|
||||
|
||||
/* 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);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Texture contents in title memory reach a translated draw (#745). Needs D3DMetal,
|
||||
# bx_shader_bridge.dll and the GDK's PC dxcompiler.dll beside the shims (bx-cli run
|
||||
# --gdk-libraries); skips without them.
|
||||
#
|
||||
# A stand-in for the GDK's XG library with a layout the test writes by hand, built as xg_xs.dll in
|
||||
# its own folder so it never replaces the xg_xs shim beside the other DLLs. The test loads it by
|
||||
# full path.
|
||||
add_library(test_texture_contents_fake_xg SHARED fake_xg.cpp)
|
||||
set_target_properties(test_texture_contents_fake_xg PROPERTIES OUTPUT_NAME xg_xs PREFIX ""
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/texture_contents_fake_xg"
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/texture_contents_fake_xg_lib")
|
||||
target_link_libraries(test_texture_contents_fake_xg PRIVATE kernel32)
|
||||
|
||||
add_executable(test_d3d12_console_texture_contents main.cpp)
|
||||
target_compile_definitions(test_d3d12_console_texture_contents PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_console_texture_contents PRIVATE d3d12_xs kernel32 uuid)
|
||||
add_dependencies(test_d3d12_console_texture_contents test_texture_contents_fake_xg)
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* A stand-in for the GDK's XG library (xg_xs.dll) whose "tiled" layout the test can write by hand.
|
||||
* It has the documented shape the shim relies on (GDK xg_xs.h): the exports
|
||||
* XGComputeTexture2DLayout (whose presence marks Microsoft's library), XGCreateTextureComputer and
|
||||
* XGEnableExclusiveLocking, and a texture computer whose vtable is AddRef, Release,
|
||||
* GetResourceLayout, GetResourceSizeBytes, GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes,
|
||||
* GetTexelElementOffsetBytes, GetTexelCoordinate, CopyIntoSubresource, CopyFromSubresource.
|
||||
* It is not Microsoft's code and computes no real console layout.
|
||||
*
|
||||
* Its layout, for 4-byte texels and subresource 0 only: the rows of the texture stored bottom row
|
||||
* first, each row Width * 4 bytes with no padding. So texel (x, y) of a W x H texture is at byte
|
||||
* ((H - 1 - y) * W + x) * 4. Size = W * H * 4, alignment 0x1000.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Computer;
|
||||
struct Vtbl {
|
||||
ULONG(__cdecl* AddRef)(Computer*);
|
||||
ULONG(__cdecl* Release)(Computer*);
|
||||
HRESULT(__cdecl* GetResourceLayout)(Computer*, void*);
|
||||
UINT64 (*GetResourceSizeBytes)(Computer*);
|
||||
UINT64 (*GetResourceBaseAlignmentBytes)(Computer*);
|
||||
void* GetMipLevelOffsetBytes;
|
||||
void* GetTexelElementOffsetBytes;
|
||||
void* GetTexelCoordinate;
|
||||
void* CopyIntoSubresource;
|
||||
HRESULT(__cdecl* CopyFromSubresource)(Computer*, void*, UINT32, UINT32, UINT32, const void*, UINT32, UINT32);
|
||||
};
|
||||
struct Computer {
|
||||
const Vtbl* vtbl;
|
||||
LONG refs;
|
||||
UINT width;
|
||||
UINT height;
|
||||
};
|
||||
|
||||
LONG g_copies = 0;
|
||||
|
||||
ULONG __cdecl add_ref(Computer* c) { return static_cast<ULONG>(InterlockedIncrement(&c->refs)); }
|
||||
ULONG __cdecl release(Computer* c) {
|
||||
const LONG left = InterlockedDecrement(&c->refs);
|
||||
if (!left) HeapFree(GetProcessHeap(), 0, c);
|
||||
return static_cast<ULONG>(left);
|
||||
}
|
||||
HRESULT __cdecl layout(Computer*, void*) { return E_NOTIMPL; }
|
||||
UINT64 size_bytes(Computer* c) { return static_cast<UINT64>(c->width) * c->height * 4; }
|
||||
UINT64 alignment_bytes(Computer*) { return 0x1000; }
|
||||
|
||||
HRESULT __cdecl copy_from(Computer* c, void* linear, UINT32 plane, UINT32 subresource, UINT32 sample, const void* tiled,
|
||||
UINT32 row_pitch, UINT32) {
|
||||
if (!linear || !tiled || plane || subresource || sample || row_pitch < c->width * 4) return E_INVALIDARG;
|
||||
const auto* src = static_cast<const uint8_t*>(tiled);
|
||||
auto* dst = static_cast<uint8_t*>(linear);
|
||||
for (UINT y = 0; y < c->height; ++y) {
|
||||
std::memcpy(dst + static_cast<size_t>(y) * row_pitch, src + static_cast<size_t>(c->height - 1 - y) * c->width * 4,
|
||||
static_cast<size_t>(c->width) * 4);
|
||||
}
|
||||
InterlockedIncrement(&g_copies);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const Vtbl kVtbl = {add_ref, release, layout, size_bytes, alignment_bytes, nullptr, nullptr, nullptr, nullptr, copy_from};
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" __declspec(dllexport) HRESULT __cdecl XGComputeTexture2DLayout(const void*, void*) { return E_NOTIMPL; }
|
||||
|
||||
extern "C" __declspec(dllexport) HRESULT __cdecl XGCreateTextureComputer(const D3D12_RESOURCE_DESC* desc, Computer** out) {
|
||||
if (!desc || !out) return E_INVALIDARG;
|
||||
auto* c = static_cast<Computer*>(HeapAlloc(GetProcessHeap(), 0, sizeof(Computer)));
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
c->vtbl = &kVtbl;
|
||||
c->refs = 1;
|
||||
c->width = static_cast<UINT>(desc->Width);
|
||||
c->height = desc->Height;
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
extern "C" __declspec(dllexport) void __cdecl XGEnableExclusiveLocking(BOOL) {}
|
||||
|
||||
// For the test: how many subresources the shim untiled through this library.
|
||||
extern "C" __declspec(dllexport) LONG __cdecl FakeXGCopies() { return g_copies; }
|
||||
@@ -0,0 +1,666 @@
|
||||
/*
|
||||
* Conformance test: a texture placed in title memory shows its pixels in a translated draw (#745).
|
||||
*
|
||||
* On the console a title places a texture at an address of its own memory
|
||||
* (CreatePlacedResourceX) and writes the texels there, in the texture's layout; CPU and GPU read
|
||||
* the same memory. Here the host texture is a separate resource, so its contents have to be
|
||||
* copied from the title's memory before a draw samples it.
|
||||
*
|
||||
* The pair is a program of our own in GFX10.3 assembly (the `textured` case of gfx10-translate's
|
||||
* golden files, assembled with the public LLVM assembler):
|
||||
* vertex: reads four floats c from entry 0 of root parameter 0's table (a constant buffer) and
|
||||
* element 0 (x, y, z, w) of the vertex; position = (c0 * x, c1 * y + c3, 0, 1),
|
||||
* parameter 0 = (z, w, 0, 1);
|
||||
* pixel: samples the texture at entry 1 of the same table at (parameter 0 .x, .y) with the
|
||||
* translation's linear sampler, and exports (r * r, g, b, a).
|
||||
* With c = (1, 1, 0, 0), a full-target quad whose (z, w) run from (0, 0) at the top left to (1, 1)
|
||||
* at the bottom right samples every texel of a texture the size of the target at its centre, so
|
||||
* pixel (x, y) is texel (x, y), with red squared.
|
||||
*
|
||||
* The texture, 16 x 16 R8G8B8A8: texel (x, y) = (x < 8 ? 255 : 0, 16 * y, 16 * x, 255). Red is 0 or
|
||||
* 255, so squaring it changes nothing. Two copies of it in title memory:
|
||||
* 1. the linear console layout (D3D12XBOX_TEXTURE_LAYOUT 0x100): rows of 64 bytes at a pitch of
|
||||
* 256 bytes, the alignment of linear console textures;
|
||||
* 2. a tiled layout (0x105), untiled through XG. The XG library here is a stand-in
|
||||
* (fake_xg.cpp) whose layout stores the rows bottom row first; the test writes the texels in
|
||||
* that order by hand. So this checks that the shim untiles through XG's CopyFromSubresource,
|
||||
* not what the console's tiling is.
|
||||
* The linear texture's view is made with CreateShaderResourceView, the tiled one's with
|
||||
* CreatePlacedShaderResourceViewX (the PC description followed by the 8-byte resource location),
|
||||
* the two ways a title makes a view of a placed texture.
|
||||
* Each is drawn into its own target and read back; the expected image is the texel formula above,
|
||||
* independent of the shim. Without the copy the texture is empty and the draw is black.
|
||||
*
|
||||
* Three rounds of the two draws:
|
||||
* 1. the linear texture's memory (one page) is PAGE_NOACCESS: its copy fails (logged), the
|
||||
* tiled texture is drawn;
|
||||
* 2. at once, with the memory readable again: the failed copy is retried at this draw, not
|
||||
* after the 250 ms check interval, and both textures are drawn;
|
||||
* 3. after the title rewrites the linear texture (a second texel formula) and 700 ms: the
|
||||
* changed texture is copied again and drawn with its new texels; the unchanged tiled texture
|
||||
* is not copied again (the stand-in XG counts one untiling in all three rounds).
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
|
||||
* 14 CreateDescriptorHeap, 16 CreateRootSignature, 17 CreateConstantBufferView,
|
||||
* 18 CreateShaderResourceView, 20 CreateRenderTargetView, 27 CreateCommittedResource,
|
||||
* 36 CreateFence, 44 CreatePlacedResourceX, 46 CreatePlacedShaderResourceViewX, 48 CreateCommandQueueX, 73 CreateCommandListX,
|
||||
* 86 CreatePipelineState; resource 8 Map, 11 GetGPUVirtualAddress; descriptor heap 9
|
||||
* GetCPUDescriptorHandleForHeapStart; command allocator 8 Reset; resource 9 Unmap; command list 9 Close, 10 Reset, 12 DrawInstanced,
|
||||
* 16 CopyTextureRegion, 20 IASetPrimitiveTopology, 21 RSSetViewports, 22 RSSetScissorRects,
|
||||
* 25 SetPipelineState, 26 ResourceBarrier, 32 SetDescriptorHeaps, 34 SetGraphicsRootSignature,
|
||||
* 36 SetGraphicsRootDescriptorTable, 48 IASetVertexBuffers, 50 OMSetRenderTargets,
|
||||
* 52 ClearRenderTargetView; queue 10 ExecuteCommandLists, 16 Signal; fence 9 SetEventOnCompletion.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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, kDevCreateDescriptorHeap = 14, kDevCreateRootSignature = 16;
|
||||
constexpr int kDevCreateConstantBufferView = 17, kDevCreateShaderResourceView = 18, kDevCreateRenderTargetView = 20;
|
||||
constexpr int kDevCreateCommittedResource = 27, kDevCreateFence = 36, kDevCreatePlacedResourceX = 44;
|
||||
constexpr int kDevCreatePlacedShaderResourceViewX = 46;
|
||||
constexpr int kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73, kDevCreatePipelineState = 86;
|
||||
constexpr int kResMap = 8, kResUnmap = 9, kResGetGpuVirtualAddress = 11, kHeapGetCpuStart = 9;
|
||||
constexpr int kAllocatorReset = 8, kListReset = 10;
|
||||
constexpr int kListClose = 9, kListDrawInstanced = 12, kListCopyTextureRegion = 16;
|
||||
constexpr int kListIASetPrimitiveTopology = 20, kListRSSetViewports = 21, kListRSSetScissorRects = 22;
|
||||
constexpr int kListSetPipelineState = 25, kListResourceBarrier = 26, kListSetDescriptorHeaps = 32;
|
||||
constexpr int kListSetGraphicsRootSignature = 34, kListSetGraphicsRootDescriptorTable = 36;
|
||||
constexpr int kListIASetVertexBuffers = 48, kListOMSetRenderTargets = 50, kListClearRenderTargetView = 52;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
|
||||
constexpr UINT kSize = 16; // texture and render target, in texels
|
||||
constexpr UINT kReadPitch = 256; // readback rows (D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)
|
||||
constexpr UINT kLinearPitch = 256; // linear console layout: rows 256-byte aligned
|
||||
constexpr UINT kLayoutLinear = 0x100, kLayoutTiled = 0x105;
|
||||
|
||||
/* s_swappc_b64 s[4:5], s[4:5] ; s_load_dwordx4 s[12:15], s[8:9] ; s_buffer_load_dwordx4 s[16:19], s[12:15] ;
|
||||
* v_mul_f32 v0, s16, v4 ; v_fma_f32 v1, s17, v5, s19 ; v_mov_b32 v2, 0 ; v_mov_b32 v3, 1.0 ;
|
||||
* exp pos0, v0, v1, v2, v3 done ; exp param0, v6, v7, v2, v3 ; s_endpgm */
|
||||
const uint32_t kTableVs[] = {0xbe842104, 0xf4080304, 0xfa000000, 0xbf8cc07f, 0xf4280406, 0xfa000000, 0xbf8cc07f, 0x10000810, 0xd54b0001,
|
||||
0x004e0a11, 0x7e040280, 0x7e0602f2, 0xf80008cf, 0x03020100, 0xf800020f, 0x03020706, 0xbf810000};
|
||||
/* gfx10-translate tests/goldens/textured.ps.hex: interpolate parameter 0 .xy, load the texture
|
||||
* (entry 1) and the sampler descriptors, image_sample, v4 = v4 * v4, exp mrt0. */
|
||||
const uint32_t kTexturedPs[] = {0xbe8a047e, 0xbefe0a7e, 0xbefc0302, 0xc8080000, 0xc8090001, 0xc80c0100, 0xc80d0101,
|
||||
0xf40c0004, 0xfa000020, 0xf408030a, 0xfa000000, 0x87fe0a7e, 0xbf8cc07f, 0xf0800f08,
|
||||
0x00600402, 0xbf8c3f70, 0x10080904, 0xf800180f, 0x07060504, 0xbf810000};
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_console_texture_contents:%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 CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
|
||||
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateRootFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const void*, SIZE_T, REFIID, void**);
|
||||
using CreateRtvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_RENDER_TARGET_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreateSrvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreatePlacedSrvXFn = void(STDMETHODCALLTYPE*)(void*, void*, const void*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreateCbvFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_CONSTANT_BUFFER_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreateStreamFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**);
|
||||
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
|
||||
using UnmapFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*);
|
||||
using ResetAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using ResetListFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*);
|
||||
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using DrawFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, UINT);
|
||||
using CopyTextureFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT,
|
||||
const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*);
|
||||
using TopologyFn = void(STDMETHODCALLTYPE*)(void*, D3D12_PRIMITIVE_TOPOLOGY);
|
||||
using ViewportsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_VIEWPORT*);
|
||||
using ScissorsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RECT*);
|
||||
using SetObjectFn = void(STDMETHODCALLTYPE*)(void*, void*);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using SetVbFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
|
||||
using SetTargetsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE*);
|
||||
using ClearFn = void(STDMETHODCALLTYPE*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
using SetHeapsFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using SetTableFn = void(STDMETHODCALLTYPE*)(void*, UINT, D3D12_GPU_DESCRIPTOR_HANDLE);
|
||||
using SerializeRootFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
|
||||
using FakeCopiesFn = LONG(__cdecl*)();
|
||||
|
||||
void put32(std::vector<uint8_t>& out, size_t at, uint32_t value) { std::memcpy(out.data() + at, &value, 4); }
|
||||
void put64(std::vector<uint8_t>& out, size_t at, uint64_t value) { std::memcpy(out.data() + at, &value, 8); }
|
||||
|
||||
uint32_t adler32(const std::vector<uint8_t>& data) {
|
||||
uint32_t a = 1, b = 0;
|
||||
for (uint8_t byte : data) {
|
||||
a = (a + byte) % 65521;
|
||||
b = (b + a) % 65521;
|
||||
}
|
||||
return (b << 16) | a;
|
||||
}
|
||||
|
||||
/* A console-style container of one stage's code, as in test_d3d12_console_pipeline_first_draw:
|
||||
* a DXBC file with one ACCC chunk (a BetterXen FSPX v1 table and the XBCH code record).
|
||||
* `fspx_stage` is 1 for pixel, 2 for vertex. */
|
||||
std::vector<uint8_t> console_container(const uint32_t* words, size_t count, uint32_t fspx_stage) {
|
||||
std::vector<uint8_t> code(12 + count * 4, 0);
|
||||
put32(code, 0, 0xD5800000u);
|
||||
std::memcpy(code.data() + 12, words, count * 4);
|
||||
constexpr size_t kBase = 16, kRecord = 0x80, kCodeOffset = 0xA0;
|
||||
std::vector<uint8_t> fssm(kBase + kCodeOffset, 0);
|
||||
std::memcpy(fssm.data(), "FSSM", 4);
|
||||
for (size_t s = 0x18; s < 0x78; s += 8) put64(fssm, s, 0xDEADBEEFDEADBEEFull);
|
||||
put64(fssm, 0x30, kRecord);
|
||||
put64(fssm, kBase + kRecord, kCodeOffset);
|
||||
put64(fssm, kBase + kRecord + 8, code.size());
|
||||
fssm.insert(fssm.end(), code.begin(), code.end());
|
||||
std::vector<uint8_t> zlib = {0x78, 0x01, 0x01};
|
||||
const uint16_t len = static_cast<uint16_t>(fssm.size());
|
||||
const uint16_t nlen = static_cast<uint16_t>(~len);
|
||||
zlib.insert(zlib.end(), {static_cast<uint8_t>(len), static_cast<uint8_t>(len >> 8), static_cast<uint8_t>(nlen),
|
||||
static_cast<uint8_t>(nlen >> 8)});
|
||||
zlib.insert(zlib.end(), fssm.begin(), fssm.end());
|
||||
const uint32_t sum = adler32(fssm);
|
||||
zlib.insert(zlib.end(), {static_cast<uint8_t>(sum >> 24), static_cast<uint8_t>(sum >> 16), static_cast<uint8_t>(sum >> 8),
|
||||
static_cast<uint8_t>(sum)});
|
||||
std::vector<uint8_t> chunk(40 + 24, 0);
|
||||
std::memcpy(chunk.data(), "FSPX", 4);
|
||||
put32(chunk, 4, 1);
|
||||
put32(chunk, 8, 1);
|
||||
put32(chunk, 16, 1);
|
||||
put32(chunk, 20, 28);
|
||||
put32(chunk, 24, 12);
|
||||
put32(chunk, 28, fspx_stage);
|
||||
put32(chunk, 32, 6);
|
||||
std::memcpy(chunk.data() + 40, "XBCH", 4);
|
||||
put32(chunk, 44, 1);
|
||||
put64(chunk, 48, zlib.size());
|
||||
put64(chunk, 56, fssm.size());
|
||||
chunk.insert(chunk.end(), zlib.begin(), zlib.end());
|
||||
while (chunk.size() % 4) chunk.push_back(0);
|
||||
const uint32_t total = 32 + 4 + 8 + static_cast<uint32_t>(chunk.size());
|
||||
std::vector<uint8_t> out(total, 0);
|
||||
std::memcpy(out.data(), "DXBC", 4);
|
||||
put32(out, 20, 1);
|
||||
put32(out, 24, total);
|
||||
put32(out, 28, 1);
|
||||
put32(out, 32, 36);
|
||||
std::memcpy(out.data() + 36, "ACCC", 4);
|
||||
put32(out, 40, static_cast<uint32_t>(chunk.size()));
|
||||
std::memcpy(out.data() + 44, chunk.data(), chunk.size());
|
||||
return out;
|
||||
}
|
||||
|
||||
struct Stream {
|
||||
std::vector<uint8_t> bytes;
|
||||
template <typename T>
|
||||
void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const T& payload) {
|
||||
struct alignas(void*) Subobject {
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
T payload;
|
||||
};
|
||||
Subobject s{};
|
||||
s.type = type;
|
||||
s.payload = payload;
|
||||
const auto* raw = reinterpret_cast<const uint8_t*>(&s);
|
||||
bytes.insert(bytes.end(), raw, raw + sizeof(s));
|
||||
}
|
||||
};
|
||||
|
||||
/* Texel (x, y) of the test texture, as R8G8B8A8 bytes. Variant 1 is what the title writes later:
|
||||
red swapped between the halves and green reversed. */
|
||||
void texel(UINT x, UINT y, uint8_t out[4], int variant = 0) {
|
||||
out[0] = (x < kSize / 2) == (variant == 0) ? 255 : 0;
|
||||
out[1] = static_cast<uint8_t>(variant == 0 ? 16 * y : 255 - 16 * y);
|
||||
out[2] = static_cast<uint8_t>(16 * x);
|
||||
out[3] = 255;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/* Pixels of a read-back R8G8B8A8 image that differ from the texture by more than 2 in a channel. */
|
||||
unsigned wrong_pixels(const uint8_t* pixels, const char* name, int variant = 0) {
|
||||
unsigned wrong = 0;
|
||||
for (UINT y = 0; y < kSize; ++y) {
|
||||
for (UINT x = 0; x < kSize; ++x) {
|
||||
const uint8_t* p = pixels + static_cast<size_t>(y) * kReadPitch + static_cast<size_t>(x) * 4;
|
||||
uint8_t want[4];
|
||||
texel(x, y, want, variant);
|
||||
bool ok = true;
|
||||
for (int c = 0; c < 4; ++c) ok = ok && std::abs(p[c] - want[c]) <= 2;
|
||||
if (!ok) {
|
||||
if (wrong < 3) {
|
||||
std::fprintf(stderr, " %s pixel (%u, %u): %d %d %d %d, want %d %d %d %d\n", name, x, y, p[0], p[1], p[2], p[3],
|
||||
want[0], want[1], want[2], want[3]);
|
||||
}
|
||||
++wrong;
|
||||
}
|
||||
}
|
||||
}
|
||||
return wrong;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
char temp[MAX_PATH] = {};
|
||||
char cache[MAX_PATH + 64] = {};
|
||||
GetTempPathA(sizeof(temp), temp);
|
||||
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");
|
||||
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).
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD n = GetModuleFileNameW(nullptr, path, MAX_PATH);
|
||||
wchar_t* slash = n ? wcsrchr(path, L'\\') : nullptr;
|
||||
if (!slash || wcslen(path) + 40 >= MAX_PATH) return 1;
|
||||
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",
|
||||
GetLastError());
|
||||
return 1;
|
||||
}
|
||||
auto fake_copies = reinterpret_cast<FakeCopiesFn>(reinterpret_cast<void*>(GetProcAddress(fake, "FakeXGCopies")));
|
||||
|
||||
const std::string before = read_log();
|
||||
|
||||
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_console_texture_contents: 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;
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
auto serialize = d3d12 ? reinterpret_cast<SerializeRootFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
|
||||
: nullptr;
|
||||
HMODULE dxc = LoadLibraryA("dxcompiler.dll");
|
||||
if (!serialize || !dxc) {
|
||||
std::printf("SKIP: test_d3d12_console_texture_contents: %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;
|
||||
}
|
||||
|
||||
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);
|
||||
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
|
||||
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
|
||||
|
||||
// Root signature: one table of the title's own ranges, a CBV (entry 0) and an SRV (entry 1).
|
||||
D3D12_DESCRIPTOR_RANGE ranges[2] = {};
|
||||
ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
|
||||
ranges[0].NumDescriptors = 1;
|
||||
ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
|
||||
ranges[1].NumDescriptors = 1;
|
||||
ranges[1].OffsetInDescriptorsFromTableStart = 1;
|
||||
D3D12_ROOT_PARAMETER param{};
|
||||
param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
|
||||
param.DescriptorTable = {2, ranges};
|
||||
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
|
||||
root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
root_desc.Desc_1_0.NumParameters = 1;
|
||||
root_desc.Desc_1_0.pParameters = ¶m;
|
||||
root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
|
||||
ID3DBlob* root_blob = nullptr;
|
||||
hr = serialize(&root_desc, &root_blob, nullptr);
|
||||
void* root = nullptr;
|
||||
if (SUCCEEDED(hr) && root_blob) {
|
||||
hr = slot<CreateRootFn>(dev, kDevCreateRootSignature)(dev, 0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(),
|
||||
__uuidof(ID3D12RootSignature), &root);
|
||||
}
|
||||
CHECK(hr == S_OK && root, "CreateRootSignature hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
const std::vector<uint8_t> vs = console_container(kTableVs, sizeof(kTableVs) / 4, 2);
|
||||
const std::vector<uint8_t> ps = console_container(kTexturedPs, sizeof(kTexturedPs) / 4, 1);
|
||||
const D3D12_INPUT_ELEMENT_DESC elements[] = {
|
||||
{"POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
|
||||
};
|
||||
void* pipeline = nullptr;
|
||||
{
|
||||
Stream s;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, static_cast<ID3D12RootSignature*>(root));
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE{vs.data(), vs.size()});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE{ps.data(), ps.size()});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, D3D12_INPUT_LAYOUT_DESC{elements, 1});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
|
||||
D3D12_RT_FORMAT_ARRAY formats{};
|
||||
formats.NumRenderTargets = 1;
|
||||
formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats);
|
||||
D3D12_RASTERIZER_DESC raster{};
|
||||
raster.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
raster.CullMode = D3D12_CULL_MODE_NONE;
|
||||
raster.DepthClipEnable = TRUE;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, raster);
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC{});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC{1, 0});
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC desc{s.bytes.size(), s.bytes.data()};
|
||||
hr = slot<CreateStreamFn>(dev, kDevCreatePipelineState)(dev, &desc, __uuidof(ID3D12PipelineState), &pipeline);
|
||||
}
|
||||
CHECK(hr == S_OK && pipeline, "CreatePipelineState(textured console pair) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// The two textures in title memory: written first, placed after, as a loaded asset would be.
|
||||
void* memory = VirtualAlloc(nullptr, 64 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
CHECK(memory != nullptr, "VirtualAlloc for the title memory");
|
||||
if (!memory) return 1;
|
||||
auto* linear_bytes = static_cast<uint8_t*>(memory); // 16 rows at 256 bytes: 4 KB
|
||||
auto* tiled_bytes = static_cast<uint8_t*>(memory) + 0x2000; // 16 x 16 x 4 = 1 KB
|
||||
for (UINT y = 0; y < kSize; ++y) {
|
||||
for (UINT x = 0; x < kSize; ++x) {
|
||||
texel(x, y, linear_bytes + static_cast<size_t>(y) * kLinearPitch + static_cast<size_t>(x) * 4);
|
||||
texel(x, y, tiled_bytes + (static_cast<size_t>(kSize - 1 - y) * kSize + x) * 4); // the stand-in's layout
|
||||
}
|
||||
}
|
||||
D3D12_RESOURCE_DESC tex_desc{};
|
||||
tex_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
tex_desc.Width = kSize;
|
||||
tex_desc.Height = kSize;
|
||||
tex_desc.DepthOrArraySize = 1;
|
||||
tex_desc.MipLevels = 1;
|
||||
tex_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
tex_desc.SampleDesc.Count = 1;
|
||||
auto placed = slot<CreatePlacedXFn>(dev, kDevCreatePlacedResourceX);
|
||||
void* textures[2] = {};
|
||||
tex_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(kLayoutLinear);
|
||||
hr = placed(dev, reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(linear_bytes), &tex_desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
|
||||
nullptr, __uuidof(ID3D12Resource), &textures[0]);
|
||||
CHECK(hr == S_OK && textures[0], "CreatePlacedResourceX(linear texture) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
tex_desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(kLayoutTiled);
|
||||
hr = placed(dev, reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(tiled_bytes), &tex_desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
|
||||
nullptr, __uuidof(ID3D12Resource), &textures[1]);
|
||||
CHECK(hr == S_OK && textures[1], "CreatePlacedResourceX(tiled texture) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// Render targets, readbacks, vertices and constants.
|
||||
D3D12_HEAP_PROPERTIES default_heap{}, upload_heap{}, readback_heap{};
|
||||
default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC target_desc = tex_desc;
|
||||
target_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
D3D12_RESOURCE_DESC buffer_desc{};
|
||||
buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer_desc.Height = 1;
|
||||
buffer_desc.DepthOrArraySize = 1;
|
||||
buffer_desc.MipLevels = 1;
|
||||
buffer_desc.SampleDesc.Count = 1;
|
||||
buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
|
||||
void* targets[2] = {};
|
||||
void* readbacks[2] = {};
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
hr = committed(dev, &default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
|
||||
__uuidof(ID3D12Resource), &targets[i]);
|
||||
CHECK(hr == S_OK && targets[i], "render target %d hr=0x%08lx", i, static_cast<unsigned long>(hr));
|
||||
buffer_desc.Width = static_cast<UINT64>(kReadPitch) * kSize;
|
||||
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &readbacks[i]);
|
||||
CHECK(hr == S_OK && readbacks[i], "readback buffer %d hr=0x%08lx", i, static_cast<unsigned long>(hr));
|
||||
}
|
||||
void* upload = nullptr;
|
||||
buffer_desc.Width = 64 * 1024;
|
||||
hr = committed(dev, &upload_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), &upload);
|
||||
CHECK(hr == S_OK && upload, "upload buffer hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{};
|
||||
rtv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
rtv_heap_desc.NumDescriptors = 2;
|
||||
void* rtv_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &rtv_heap_desc, __uuidof(ID3D12DescriptorHeap), &rtv_heap);
|
||||
CHECK(hr == S_OK && rtv_heap, "RTV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{};
|
||||
view_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
|
||||
view_heap_desc.NumDescriptors = 8;
|
||||
view_heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
|
||||
void* view_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &view_heap_desc, __uuidof(ID3D12DescriptorHeap), &view_heap);
|
||||
CHECK(hr == S_OK && view_heap, "CBV/SRV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!queue || !allocator || !list || !fence || !root || !pipeline || !textures[0] || !textures[1] || !targets[0] ||
|
||||
!targets[1] || !readbacks[0] || !readbacks[1] || !upload || !rtv_heap || !view_heap) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_console_texture_contents: setup\n");
|
||||
return 1;
|
||||
}
|
||||
// Console descriptor handles are addresses; an RTV descriptor is 112 bytes there.
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2];
|
||||
rtvs[0] = slot<HeapStartFn>(rtv_heap, kHeapGetCpuStart)(rtv_heap);
|
||||
rtvs[1].ptr = rtvs[0].ptr + 112;
|
||||
for (int i = 0; i < 2; ++i) slot<CreateRtvFn>(dev, kDevCreateRenderTargetView)(dev, targets[i], nullptr, rtvs[i]);
|
||||
|
||||
// A full-target quad (x, y, u, v) at offset 0, the constants (1, 1, 0, 0) at offset 4096.
|
||||
const float quad[] = {-1, 1, 0, 0, 1, 1, 1, 0, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 1, 0, 1, -1, 1, 1};
|
||||
void* mapped = nullptr;
|
||||
hr = slot<MapFn>(upload, kResMap)(upload, 0, nullptr, &mapped);
|
||||
CHECK(hr == S_OK && mapped, "upload buffer Map hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!mapped) return 1;
|
||||
std::memcpy(mapped, quad, sizeof(quad));
|
||||
const float scale[4] = {1.0f, 1.0f, 0.0f, 0.0f};
|
||||
std::memset(static_cast<uint8_t*>(mapped) + 4096, 0, 256);
|
||||
std::memcpy(static_cast<uint8_t*>(mapped) + 4096, scale, sizeof(scale));
|
||||
const D3D12_GPU_VIRTUAL_ADDRESS upload_va = slot<GetGpuVaFn>(upload, kResGetGpuVirtualAddress)(upload);
|
||||
const D3D12_VERTEX_BUFFER_VIEW vbv{upload_va, sizeof(quad), 16};
|
||||
|
||||
// Table i (heap slots 2i, 2i+1): the constants, then texture i.
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE view_start = slot<HeapStartFn>(view_heap, kHeapGetCpuStart)(view_heap);
|
||||
const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{upload_va + 4096, 256};
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
|
||||
srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
|
||||
srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
|
||||
srv.Texture2D.MipLevels = 1;
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE tables[2];
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
const SIZE_T base = view_start.ptr + static_cast<SIZE_T>(2 * i) * 32;
|
||||
slot<CreateCbvFn>(dev, kDevCreateConstantBufferView)(dev, &cbv, {base});
|
||||
if (i == 0) {
|
||||
slot<CreateSrvFn>(dev, kDevCreateShaderResourceView)(dev, textures[i], &srv, {base + 32});
|
||||
} else {
|
||||
struct alignas(8) {
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc;
|
||||
uint64_t location;
|
||||
} xbox_srv{srv, reinterpret_cast<uint64_t>(tiled_bytes)};
|
||||
slot<CreatePlacedSrvXFn>(dev, kDevCreatePlacedShaderResourceViewX)(dev, textures[i], &xbox_srv, {base + 32});
|
||||
}
|
||||
tables[i].ptr = base;
|
||||
}
|
||||
|
||||
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(kSize), static_cast<float>(kSize), 0, 1};
|
||||
const D3D12_RECT scissor{0, 0, static_cast<LONG>(kSize), static_cast<LONG>(kSize)};
|
||||
const FLOAT grey[4] = {0.5f, 0.5f, 0.5f, 0.5f};
|
||||
// One round: both textures drawn into their targets, then read back.
|
||||
auto run_round = [&](int round) -> bool {
|
||||
if (round > 1) {
|
||||
slot<ResetAllocatorFn>(allocator, kAllocatorReset)(allocator);
|
||||
slot<ResetListFn>(list, kListReset)(list, allocator, nullptr);
|
||||
}
|
||||
void* heaps[] = {view_heap};
|
||||
slot<SetHeapsFn>(list, kListSetDescriptorHeaps)(list, 1, heaps);
|
||||
slot<SetObjectFn>(list, kListSetGraphicsRootSignature)(list, root);
|
||||
slot<ViewportsFn>(list, kListRSSetViewports)(list, 1, &viewport);
|
||||
slot<ScissorsFn>(list, kListRSSetScissorRects)(list, 1, &scissor);
|
||||
slot<SetVbFn>(list, kListIASetVertexBuffers)(list, 0, 1, &vbv);
|
||||
slot<TopologyFn>(list, kListIASetPrimitiveTopology)(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
slot<SetObjectFn>(list, kListSetPipelineState)(list, pipeline);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (round > 1) { // back from the previous round's copy
|
||||
D3D12_RESOURCE_BARRIER to_rt{};
|
||||
to_rt.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
to_rt.Transition.pResource = static_cast<ID3D12Resource*>(targets[i]);
|
||||
to_rt.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
to_rt.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
to_rt.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &to_rt);
|
||||
}
|
||||
slot<SetTableFn>(list, kListSetGraphicsRootDescriptorTable)(list, 0, tables[i]);
|
||||
slot<SetTargetsFn>(list, kListOMSetRenderTargets)(list, 1, &rtvs[i], FALSE, nullptr);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtvs[i], grey, 0, nullptr);
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 6, 1, 0, 0);
|
||||
}
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
D3D12_RESOURCE_BARRIER to_copy{};
|
||||
to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
to_copy.Transition.pResource = static_cast<ID3D12Resource*>(targets[i]);
|
||||
to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &to_copy);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{};
|
||||
dst.pResource = static_cast<ID3D12Resource*>(readbacks[i]);
|
||||
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kReadPitch};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{};
|
||||
src.pResource = static_cast<ID3D12Resource*>(targets[i]);
|
||||
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
slot<CopyTextureFn>(list, kListCopyTextureRegion)(list, &dst, 0, 0, 0, &src, nullptr);
|
||||
}
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "round %d: list Close", round);
|
||||
void* lists[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
|
||||
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, static_cast<UINT64>(round)) == S_OK, "round %d: queue Signal", round);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, static_cast<UINT64>(round), done) == S_OK, "round %d: fence event",
|
||||
round);
|
||||
const bool ok = WaitForSingleObject(done, 20000) == WAIT_OBJECT_0;
|
||||
CHECK(ok, "round %d: GPU work completes", round);
|
||||
CloseHandle(done);
|
||||
return ok;
|
||||
};
|
||||
// The image of texture i in its target after the last round: 0 when it matches `variant`.
|
||||
auto check = [&](int round, int i, int variant) {
|
||||
static const char* names[2] = {"linear (0x100)", "tiled through XG (0x105)"};
|
||||
void* result = nullptr;
|
||||
hr = slot<MapFn>(readbacks[i], kResMap)(readbacks[i], 0, nullptr, &result);
|
||||
CHECK(hr == S_OK && result, "round %d: readback %d Map hr=0x%08lx", round, i, static_cast<unsigned long>(hr));
|
||||
if (!result) return;
|
||||
const unsigned wrong = wrong_pixels(static_cast<const uint8_t*>(result), names[i], variant);
|
||||
CHECK(wrong == 0, "round %d: the draw of the %s texture in title memory shows its texels (variant %d): %u of %u pixel(s) differ",
|
||||
round, names[i], variant, wrong, kSize * kSize);
|
||||
slot<UnmapFn>(readbacks[i], kResUnmap)(readbacks[i], 0, nullptr);
|
||||
};
|
||||
|
||||
// Round 1: the linear texture's memory cannot be read yet (one 4 KiB page), so its copy fails;
|
||||
// the tiled one is copied.
|
||||
DWORD old_protect = 0;
|
||||
CHECK(VirtualProtect(linear_bytes, 4096, PAGE_NOACCESS, &old_protect), "VirtualProtect(PAGE_NOACCESS)");
|
||||
if (!run_round(1)) return 1;
|
||||
check(1, 1, 0);
|
||||
// Round 2, at once (well within the 250 ms check interval): the memory is readable again and
|
||||
// the failed copy is retried at the next draw.
|
||||
CHECK(VirtualProtect(linear_bytes, 4096, PAGE_READWRITE, &old_protect), "VirtualProtect(PAGE_READWRITE)");
|
||||
if (!run_round(2)) return 1;
|
||||
check(2, 0, 0);
|
||||
check(2, 1, 0);
|
||||
// Round 3: the title rewrites the linear texture; the tiled one is unchanged. After the check
|
||||
// interval a draw copies the changed texture again and not the other one.
|
||||
for (UINT y = 0; y < kSize; ++y) {
|
||||
for (UINT x = 0; x < kSize; ++x) texel(x, y, linear_bytes + static_cast<size_t>(y) * kLinearPitch + static_cast<size_t>(x) * 4, 1);
|
||||
}
|
||||
Sleep(700);
|
||||
if (!run_round(3)) return 1;
|
||||
check(3, 0, 1);
|
||||
check(3, 1, 0);
|
||||
CHECK(fake_copies && fake_copies() == 1, "the tiled texture was untiled through XG's CopyFromSubresource once (%ld)",
|
||||
fake_copies ? fake_copies() : -1L);
|
||||
|
||||
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, "console_descriptor") == 0, "every table entry read was found through its marker");
|
||||
CHECK(count_of(mine, "hr=0x80070005") == 1, "the copy from unreadable memory fails once, logged (%zu)",
|
||||
count_of(mine, "hr=0x80070005"));
|
||||
CHECK(count_of(mine, "subresource(s), hr=0x00000000") == 2,
|
||||
"two first copies succeed: the tiled one, and the linear one on retry (%zu)",
|
||||
count_of(mine, "subresource(s), hr=0x00000000"));
|
||||
CHECK(count_of(mine, "copied again: its title memory changed") == 1, "only the changed texture is copied again (%zu)",
|
||||
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)"));
|
||||
} else {
|
||||
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
|
||||
}
|
||||
|
||||
for (void* object : {view_heap, rtv_heap, upload, readbacks[1], readbacks[0], targets[1], targets[0], textures[1], textures[0],
|
||||
pipeline, root, fence, list, allocator, queue, dev}) {
|
||||
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",
|
||||
g_checks - g_failed, g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# PresentX composes its planes (premultiplied alpha, source and destination rectangles). Needs
|
||||
# D3DMetal and the GDK's PC dxcompiler.dll beside the shims (bx-cli run --gdk-libraries); skips
|
||||
# without them.
|
||||
add_executable(test_d3d12_presentx_planes main.cpp)
|
||||
target_compile_definitions(test_d3d12_presentx_planes PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_presentx_planes PRIVATE d3d12_xs kernel32 user32 uuid)
|
||||
@@ -0,0 +1,320 @@
|
||||
/*
|
||||
* Conformance test: PresentX composes its planes (authorized GDK documentation, "Hardware overlays").
|
||||
*
|
||||
* The documented contract: plane 0 is the background plane and plane 1 the HUD plane in front of
|
||||
* it; content is premultiplied alpha; a plane's source rectangle (pSrcViewRects) is in texels of
|
||||
* its resource and its destination rectangle (pDestPlacementBase, a D3D12XBOX_VIEW_RECT) is
|
||||
* normalized to the output. So a pixel of the output is hud.rgb + background.rgb * (1 - hud.a).
|
||||
*
|
||||
* Two planes of our own, made with clears:
|
||||
* plane 0, 64 x 64: opaque red (1, 0, 0, 1);
|
||||
* plane 1, 128 x 128: left half premultiplied half-transparent green (0, 0.5, 0, 0.5), right half
|
||||
* transparent (0, 0, 0, 0).
|
||||
* Present 1 shows both over the whole output (no rectangles). Expected, from the formula alone:
|
||||
* left half (0 + 1 * 0.5, 0.5 + 0, 0) = (128, 128, 0) in 8 bits (+-3),
|
||||
* right half (1, 0, 0) = (255, 0, 0).
|
||||
* Present 2 shows plane 1's left half (source rectangle 0, 0, 64, 128) in the output's right half
|
||||
* (destination 0.5, 0, 1, 1): left half red, right half (128, 128, 0).
|
||||
*
|
||||
* The output is read from the frame dump (BX_PRESENT_DUMP, every present): a BMP of the composed
|
||||
* frame, downscaled 4x (16 x 16 here), 24-bit, bottom row first. Pixels next to the half-way line
|
||||
* are not checked (bilinear scaling).
|
||||
*
|
||||
* Without composition, plane 0 alone is copied to the window: the frame is red everywhere and the
|
||||
* green halves fail.
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
|
||||
* 14 CreateDescriptorHeap, 20 CreateRenderTargetView, 27 CreateCommittedResource, 36 CreateFence,
|
||||
* 48 CreateCommandQueueX, 73 CreateCommandListX; descriptor heap 9 GetCPUDescriptorHandleForHeapStart;
|
||||
* command list 9 Close, 26 ResourceBarrier, 52 ClearRenderTargetView; queue 10 ExecuteCommandLists,
|
||||
* 16 Signal, 32 PresentX; fence 9 SetEventOnCompletion.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
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, kDevCreateDescriptorHeap = 14, kDevCreateRenderTargetView = 20;
|
||||
constexpr int kDevCreateCommittedResource = 27, kDevCreateFence = 36, kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
|
||||
constexpr int kHeapGetCpuStart = 9;
|
||||
constexpr int kListClose = 9, kListResourceBarrier = 26, kListClearRenderTargetView = 52;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kQueuePresentX = 32, kFenceSetEventOnCompletion = 9;
|
||||
|
||||
constexpr UINT kBackground = 64, kHud = 128, kDump = kBackground / 4;
|
||||
|
||||
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
|
||||
UINT64 Token;
|
||||
UINT ResourceCount;
|
||||
void** ppResources;
|
||||
D3D12_RECT* pSrcViewRects;
|
||||
void* pDestPlacementBase;
|
||||
UINT ColorSpace;
|
||||
UINT ScaleFilter;
|
||||
UINT ExtendedDescCount;
|
||||
void* pExtendedDescs;
|
||||
UINT Flags;
|
||||
};
|
||||
static_assert(sizeof(PlaneParameters) == 72, "D3D12XBOX_PRESENT_PLANE_PARAMETERS");
|
||||
struct ViewRect { // D3D12XBOX_VIEW_RECT
|
||||
float left, top, right, bottom;
|
||||
};
|
||||
struct QueueDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, EngineOrPipeIndex, QueueIndex;
|
||||
};
|
||||
struct ListDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, NodeMask, ResourceBarrierBatchSize;
|
||||
};
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
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 CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
|
||||
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateRtvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_RENDER_TARGET_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using ClearFn = void(STDMETHODCALLTYPE*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
using PresentFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const PlaneParameters*, const void*);
|
||||
|
||||
int g_checks = 0, g_failed = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_presentx_planes:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* The dumped frame `n` as rows of (r, g, b), top row first; empty when it cannot be read. */
|
||||
std::vector<uint8_t> read_dump(const char* folder, unsigned n, UINT* w, UINT* h) {
|
||||
char path[MAX_PATH + 32];
|
||||
std::snprintf(path, sizeof(path), "%s\\frame_%06u.bmp", folder, n);
|
||||
std::vector<uint8_t> file;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
uint8_t buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) file.insert(file.end(), buffer, buffer + got);
|
||||
std::fclose(f);
|
||||
}
|
||||
if (file.size() < 54 || file[0] != 'B' || file[1] != 'M') return {};
|
||||
uint32_t offset = 0;
|
||||
int32_t width = 0, height = 0;
|
||||
std::memcpy(&offset, &file[10], 4);
|
||||
std::memcpy(&width, &file[18], 4);
|
||||
std::memcpy(&height, &file[22], 4);
|
||||
if (width <= 0 || height <= 0 || file[28] != 24) return {};
|
||||
const size_t stride = (static_cast<size_t>(width) * 3 + 3) & ~size_t(3);
|
||||
if (file.size() < offset + stride * static_cast<size_t>(height)) return {};
|
||||
std::vector<uint8_t> rgb(static_cast<size_t>(width) * height * 3);
|
||||
for (int y = 0; y < height; ++y) {
|
||||
const uint8_t* row = &file[offset + stride * static_cast<size_t>(height - 1 - y)];
|
||||
for (int x = 0; x < width; ++x) {
|
||||
uint8_t* out = &rgb[(static_cast<size_t>(y) * width + x) * 3];
|
||||
out[0] = row[x * 3 + 2];
|
||||
out[1] = row[x * 3 + 1];
|
||||
out[2] = row[x * 3 + 0];
|
||||
}
|
||||
}
|
||||
*w = static_cast<UINT>(width);
|
||||
*h = static_cast<UINT>(height);
|
||||
return rgb;
|
||||
}
|
||||
|
||||
/* Pixels of columns [x0, x1) of the dump that differ from (r, g, b) by more than 3. */
|
||||
unsigned wrong(const std::vector<uint8_t>& rgb, UINT w, UINT h, UINT x0, UINT x1, int r, int g, int b, const char* what) {
|
||||
unsigned bad = 0;
|
||||
for (UINT y = 1; y + 1 < h; ++y) {
|
||||
for (UINT x = x0; x < x1; ++x) {
|
||||
const uint8_t* p = &rgb[(static_cast<size_t>(y) * w + x) * 3];
|
||||
if (std::abs(p[0] - r) > 3 || std::abs(p[1] - g) > 3 || std::abs(p[2] - b) > 3) {
|
||||
if (bad++ < 2) std::fprintf(stderr, " %s (%u, %u): %d %d %d, want %d %d %d\n", what, x, y, p[0], p[1], p[2], r, g, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) { return DefWindowProcW(window, message, w, l); }
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
char temp[MAX_PATH] = {};
|
||||
GetTempPathA(sizeof(temp), temp);
|
||||
char folder[MAX_PATH + 64] = {};
|
||||
std::snprintf(folder, sizeof(folder), "%sbx-presentx-planes-%lu-%lu", temp, static_cast<unsigned long>(GetCurrentProcessId()),
|
||||
static_cast<unsigned long>(GetTickCount()));
|
||||
CreateDirectoryA(folder, nullptr);
|
||||
SetEnvironmentVariableA("BX_PRESENT_DUMP", folder);
|
||||
SetEnvironmentVariableA("BX_PRESENT_DUMP_EVERY", "1");
|
||||
|
||||
// PresentX shows frames on the title's visible top-level window.
|
||||
WNDCLASSW wc{};
|
||||
wc.lpfnWndProc = window_proc;
|
||||
wc.hInstance = GetModuleHandleW(nullptr);
|
||||
wc.lpszClassName = L"bx_presentx_planes";
|
||||
RegisterClassW(&wc);
|
||||
HWND window = CreateWindowExW(0, wc.lpszClassName, L"presentx planes", WS_OVERLAPPEDWINDOW, 0, 0, 200, 200, nullptr, nullptr,
|
||||
wc.hInstance, nullptr);
|
||||
CHECK(window != nullptr, "CreateWindowExW");
|
||||
if (!window) return 1;
|
||||
ShowWindow(window, SW_SHOWNOACTIVATE);
|
||||
|
||||
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_presentx_planes: 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;
|
||||
if (!LoadLibraryA("dxcompiler.dll")) {
|
||||
std::printf("SKIP: test_d3d12_presentx_planes: no dxcompiler.dll beside the shims (run with bx-cli run --gdk-libraries)\n");
|
||||
return 77;
|
||||
}
|
||||
|
||||
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);
|
||||
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 heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
void* planes[2] = {};
|
||||
const UINT sizes[2] = {kBackground, kHud};
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
desc.Width = sizes[i];
|
||||
desc.Height = sizes[i];
|
||||
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
|
||||
__uuidof(ID3D12Resource), &planes[i]);
|
||||
CHECK(hr == S_OK && planes[i], "plane %d texture hr=0x%08lx", i, static_cast<unsigned long>(hr));
|
||||
}
|
||||
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
|
||||
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
heap_desc.NumDescriptors = 2;
|
||||
void* rtv_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &rtv_heap);
|
||||
CHECK(hr == S_OK && rtv_heap, "RTV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!queue || !allocator || !list || !fence || !planes[0] || !planes[1] || !rtv_heap) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_presentx_planes: setup\n");
|
||||
return 1;
|
||||
}
|
||||
// Console descriptor handles are addresses; an RTV descriptor is 112 bytes there.
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2];
|
||||
rtvs[0] = slot<HeapStartFn>(rtv_heap, kHeapGetCpuStart)(rtv_heap);
|
||||
rtvs[1].ptr = rtvs[0].ptr + 112;
|
||||
for (int i = 0; i < 2; ++i) slot<CreateRtvFn>(dev, kDevCreateRenderTargetView)(dev, planes[i], nullptr, rtvs[i]);
|
||||
|
||||
const FLOAT red[4] = {1, 0, 0, 1};
|
||||
const FLOAT clear[4] = {0, 0, 0, 0};
|
||||
const FLOAT half_green[4] = {0, 0.5f, 0, 0.5f};
|
||||
const D3D12_RECT hud_left{0, 0, static_cast<LONG>(kHud / 2), static_cast<LONG>(kHud)};
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtvs[0], red, 0, nullptr);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtvs[1], clear, 0, nullptr);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtvs[1], half_green, 1, &hud_left);
|
||||
for (int i = 0; i < 2; ++i) { // presentable (PRESENT, i.e. COMMON) for PresentX
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = static_cast<ID3D12Resource*>(planes[i]);
|
||||
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &b);
|
||||
}
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
|
||||
void* lists[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
|
||||
slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done);
|
||||
CHECK(WaitForSingleObject(done, 20000) == WAIT_OBJECT_0, "the clears complete");
|
||||
CloseHandle(done);
|
||||
|
||||
auto present = slot<PresentFn>(queue, kQueuePresentX);
|
||||
PlaneParameters p[2] = {};
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
p[i].ResourceCount = 1;
|
||||
p[i].ppResources = &planes[i];
|
||||
p[i].ColorSpace = 0; // DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709
|
||||
}
|
||||
// Present 1: both planes over the whole output.
|
||||
hr = present(queue, 2, p, nullptr);
|
||||
CHECK(hr == S_OK, "PresentX(two planes) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
// Present 2: plane 1's left half in the output's right half.
|
||||
D3D12_RECT source{0, 0, static_cast<LONG>(kHud / 2), static_cast<LONG>(kHud)};
|
||||
ViewRect right_half{0.5f, 0.0f, 1.0f, 1.0f};
|
||||
p[1].pSrcViewRects = &source;
|
||||
p[1].pDestPlacementBase = &right_half;
|
||||
hr = present(queue, 2, p, nullptr);
|
||||
CHECK(hr == S_OK, "PresentX(two planes, rectangles) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
UINT w = 0, h = 0;
|
||||
std::vector<uint8_t> first = read_dump(folder, 1, &w, &h);
|
||||
CHECK(!first.empty() && w == kDump && h == kDump, "frame 1 is dumped at %ux%u (got %ux%u)", kDump, kDump, w, h);
|
||||
if (!first.empty() && w == kDump && h == kDump) {
|
||||
CHECK(wrong(first, w, h, 1, kDump / 2 - 1, 128, 128, 0, "frame 1 left") == 0,
|
||||
"frame 1, left half: half-transparent green over red is (128, 128, 0)");
|
||||
CHECK(wrong(first, w, h, kDump / 2 + 1, kDump - 1, 255, 0, 0, "frame 1 right") == 0,
|
||||
"frame 1, right half: the transparent HUD shows the red background");
|
||||
}
|
||||
std::vector<uint8_t> second = read_dump(folder, 2, &w, &h);
|
||||
CHECK(!second.empty() && w == kDump && h == kDump, "frame 2 is dumped at %ux%u (got %ux%u)", kDump, kDump, w, h);
|
||||
if (!second.empty() && w == kDump && h == kDump) {
|
||||
CHECK(wrong(second, w, h, 1, kDump / 2 - 1, 255, 0, 0, "frame 2 left") == 0, "frame 2, left half: no HUD, red");
|
||||
CHECK(wrong(second, w, h, kDump / 2 + 1, kDump - 1, 128, 128, 0, "frame 2 right") == 0,
|
||||
"frame 2, right half: the HUD's left half placed there, (128, 128, 0)");
|
||||
}
|
||||
|
||||
for (void* object : {rtv_heap, planes[1], planes[0], fence, list, allocator, queue, dev}) {
|
||||
slot<ReleaseFn>(object, kRelease)(object);
|
||||
}
|
||||
DestroyWindow(window);
|
||||
std::printf("%s: test_d3d12_presentx_planes (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed,
|
||||
g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
Reference in new issue
Block a user