diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 34422cc0a9..06f4b7279e 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -165,13 +165,19 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s The game executable imports two functions from `xg_xs.dll`, the console's texture layout library: `XGSuggestSwizzleMode` (2 call sites, in the helper that fills a texture description) and `XGCreateTextureComputer` -(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). The runtime has no model of the console -resource layout, so `runtime/shims/xg_xs.cpp` computes none: both return `E_NOTIMPL` and write no layout. Two of the -four `XGCreateTextureComputer` callers ignore the HRESULT and call through the object at once, so the shim still stores -a static object in the out pointer; its slot 1 (read as `Release`) does nothing, and every other slot up to 31 logs its -index and caller once and returns `E_NOTIMPL` without writing its arguments. The call shapes and the reasoning are at -the top of the file; `xg_xs_test` covers them. Textures whose layout the game asks for are therefore not laid out yet. -The table above was measured before this shim and still lists these two as unimplemented; they are served now. +(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). `runtime/shims/xg_xs.cpp` answers them +from a model of the console's texture layouts, `runtime/src/console_texture_layout.h` (AMD addrlib's GFX10 rules for +the linear, 256 B, 4 KiB and 64 KiB modes: block shapes, mip tails, the micro tile patterns, a separate stencil plane), +ported with the computer's method table and layout structure from Marvisak/VIctory (GPL-3.0, `xg.rs` and `texture.rs` +at `d2a4bae1f`). `XGSuggestSwizzleMode` writes `0x100 | mode` (linear for 1D, `64KB_Z_X` for depth, `64KB_R_X` for +render targets, else `4KB_S`); the computer fills the layout (slot 2), gives an element's offset (slot 6), copies a +subresource into (slot 8) and out of (slot 9) tiled memory, and reports the 64 KiB tiling (slot 10). Not modelled: +compression metadata planes, and addressing or copies for the pipe/bank XOR modes and MSAA (`E_NOTIMPL`). A description +it cannot lay out still gets a computer in the out pointer with `E_INVALIDARG`, because two of the four callers ignore +the HRESULT and call through the object at once; that object answers every slot with `E_NOTIMPL` and writes nothing. +`xg_xs_test` covers the model (hand-checked addresses, mip tails, a bijection and round trip over every element) and the +shim's slots. The table above was measured before this shim and still lists these two as unimplemented; they are served +now. Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.dll`), and they are not complete: they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`, diff --git a/runtime/shims/console_texture_size.h b/runtime/shims/console_texture_size.h new file mode 100644 index 0000000000..a72205e9dd --- /dev/null +++ b/runtime/shims/console_texture_size.h @@ -0,0 +1,13 @@ +#pragma once + +// The console's size for a texture (xg_xs.cpp), for the D3D12 device proxy's GetResourceAllocationInfo. A pointer, so +// that the proxy does not link the xg_xs shim; null in a process without it. +#include + +namespace rt::xg { + +// `desc`: the title's 56-byte D3D12_RESOURCE_DESC. 0 when the shim cannot lay it out; else its bytes, and `alignment`. +using TextureSizeFn = std::uint64_t (*)(const void* desc, std::uint64_t& alignment); +inline TextureSizeFn texture_size_fn = nullptr; + +} // namespace rt::xg diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index f0fefd5351..5d57169dd3 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #include "d3d12_xs_device.h" +#include "console_texture_size.h" #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" @@ -2693,11 +2694,41 @@ void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12 if (console.SizeInBytes >= info.SizeInBytes) info = console; } +// The console's answer for textures it lays out itself: those whose layout is a swizzle mode (0x100 | mode) or left to +// the runtime (0, the mode XGSuggestSwizzleMode gives). The retail title sizes its streamed textures with slot 25 and +// computes offsets and lengths inside its texture archives from the answers, so a PC GPU's sizes send it to the wrong +// bytes (it asserted at game_scarlett_master.exe+0x4ffd879, 1.0.2.1). Every description must be such a texture, else +// `info` is left alone: render targets, depth, buffers and shapes xg_xs cannot lay out keep the PC answer. +bool console_texture_sizes(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info) { + if (!descs || !count || !rt::xg::texture_size_fn) return false; + UINT64 end = 0, alignment = 1; + for (UINT i = 0; i < count; ++i) { + const D3D12_RESOURCE_DESC& d = descs[i]; + const UINT layout = static_cast(d.Layout); + if (d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || (layout != 0 && (layout & ~0xffu) != 0x100) || + (d.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) + return false; + std::uint64_t own = 0; + const std::uint64_t size = rt::xg::texture_size_fn(&d, own); + if (!size || !own) return false; + end = (end + own - 1) / own * own + size; + alignment = (std::max)(alignment, own); + } + info.SizeInBytes = (end + alignment - 1) / alignment * alignment; + info.Alignment = alignment; + return true; +} + void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, std::uint64_t count, const D3D12_RESOURCE_DESC* descs) { note_slot(25); const StructReturnCall call = struct_return_call(a0, a1); ID3D12Device* const real = call.self->real; + // Streamed textures (console_texture_sizes) get the console's own sizes, in the console form only, as the render + // targets below: a PC-form caller compares with the PC device. + if (call.console_abi && + console_texture_sizes(descs, static_cast(count), *static_cast(call.ret))) + return call.ret; // Normalize console descriptors in a copy. PC calls can also pass the Xbox tiled layout explicitly. Otherwise // their flags and layout reach the host unchanged so the host can validate them. const UINT desc_count = static_cast(count); diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index b45fbf689a..2ddf08f797 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -1,4 +1,6 @@ -// xg_xs.dll: the console's texture layout library. The game executable (1.0.2.1) imports two functions from it. +// xg_xs.dll: the console's texture layout library. Titles ask it which swizzle mode a texture should use, how large it +// is, where each mip and slice lies, and to copy linear data into tiled memory and back. The game executable +// (1.0.2.1) imports two functions from it. // // Measured from the call sites in the executable, read statically (shapes and checks only): // HRESULT XGSuggestSwizzleMode(const desc*, 0, uint32_t* mode) @@ -7,86 +9,510 @@ // known, writes itself as 0x100 | mode. The HRESULT is only passed back up; no caller branches on it. // HRESULT XGCreateTextureComputer(const desc*, computer** out) // 4 call sites. Two test the HRESULT and take their failure path when it is negative; two ignore it and call -// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites, read as -// Release; no site calls slot 0, read as AddRef, nor QueryInterface), slot 2 with one out pointer to a large -// stack structure (2 sites), slot 8 with six arguments in a loop over subresources (1 site) and slot 10 with -// seven arguments (1 site). No site reads the return value of slots 2, 8 or 10. +// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites), slot 2 with +// one out pointer to a large stack structure (2 sites), slot 8 with six arguments in a loop over subresources +// (1 site) and slot 10 with seven arguments (1 site). // -// The runtime has no model of the console's resource layout (runtime/src/gfx10_tiling.h covers two swizzle modes of -// one 2D level, without mips or the layout structure slot 2 fills), so nothing here computes a layout: -// - XGSuggestSwizzleMode returns E_NOTIMPL and writes nothing, so the field keeps the 0 the caller put there. -// - XGCreateTextureComputer returns E_NOTIMPL, but still stores a computer in *out. The two checking callers then -// fail cleanly; the two that do not check would otherwise call through a null pointer. COM says *out is null on -// failure; this breaks that on purpose, because the measured callers need it. -// - Slot 0 and slot 1 count nothing (the computer is one static object). Every other slot, up to kSlots, prints its -// index and caller once and returns E_NOTIMPL without writing its arguments, so a caller's own zero-filled outputs -// stay zero and a stack structure the caller did not fill stays as it was. -// Hypothesis, not measured: slots 0 and 1 being AddRef and Release; the meaning of slots 2, 8 and 10; that callers -// reach no slot above kSlots - 1 (the computer is also stored in an object at one site and may be called later). +// The computer's methods, their arguments and the layout structure slot 2 fills are taken from Marvisak/VIctory +// (GPL-3.0), crates/victory-hle/src/modules/xg.rs at commit d2a4bae1f, which serves the same title: 0 AddRef, +// 1 Release, 2 the layout, 6 an element's byte offset, 8 a copy into and 9 a copy out of a subresource, 10 the 64 KiB +// tiling. They match the slots measured above. The layouts come from runtime/src/console_texture_layout.h, ported +// from the same project. +// +// Kept from the measured callers: a description this shim cannot lay out still gets a computer in *out (with a +// negative HRESULT), because two callers use *out without checking the HRESULT. That computer answers every slot +// with E_NOTIMPL and writes nothing. COM says *out is null on failure; this breaks that on purpose. +// +// Not modelled: compression metadata planes (HTILE, CMASK, FMASK, DCC), addressing and copies for the pipe/bank XOR +// modes (_X, _T) and MSAA (they need the GPU's pipe configuration; the host renders those targets), and the slots no +// caller reaches (size, alignment, mip offset, element coordinate, view descriptor), which log once and return +// E_NOTIMPL. #include #include +#include #include #include +#include #include #include +#include +#include +#include +#include #include +#include "../src/console_texture_layout.h" +#include "console_texture_size.h" #include "shims.h" namespace { +namespace ct = leonida::console_texture; + constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +constexpr HRESULT kInvalidArg = static_cast(0x80070057u); +constexpr HRESULT kFail = static_cast(0x80004005u); constexpr size_t kSlots = 32; -// Prints once per entry point; `slot` is the vtable index for a computer method, or -1 for an export. -void warn_once(std::atomic& warned, const char* what, int slot, const void* caller) { +// D3D12_RESOURCE_DESC, whose layout field carries 0x100 | swizzle mode on the console (1 row major, 0 "pick one"). +struct ResourceDesc { + uint32_t dimension; + uint64_t alignment; + uint64_t width; + uint32_t height; + uint16_t depth_or_array; + uint16_t mips; + uint32_t format; + uint32_t samples; + uint32_t quality; + uint32_t layout; + uint32_t flags; +}; +static_assert(sizeof(ResourceDesc) == 0x38); + +constexpr uint32_t kSwizzled = 0x100; +constexpr uint32_t kRowMajor = 1; +constexpr uint32_t kAllowRenderTarget = 1; +constexpr uint32_t kAllowDepthStencil = 2; +constexpr uint32_t kTexture1d = 2, kTexture2d = 3, kTexture3d = 4; + +// The layout structure slot 2 fills. Offsets 0x00, 0x08, 0x10 and 0x1c of a mip are the ones the title reads; the +// rest follow the library's older public shape (VIctory's reading). +constexpr size_t kMips = 15; +struct MipOut { + uint64_t size; + uint64_t offset; + uint64_t slice_size; + uint32_t pitch_texels; + uint32_t pitch_bytes; + uint32_t alignment; + uint32_t padded[3]; // width, height in elements, depth or array size + uint32_t elements[2]; + uint32_t texels[2]; + uint32_t depth_or_array; + uint32_t samples; + uint32_t swizzle; + uint64_t bank_rotation[2]; + uint32_t slice_depth; + uint32_t in_tail; + uint32_t tail_position; // where a tail mip starts in elements: x bits 0-10, y 11-21 +}; +struct PlaneOut { + uint32_t usage; // 1 data, 7 depth, 8 stencil (metadata planes are not made) + uint64_t size; + uint64_t slice_size; + uint64_t offset; + uint64_t alignment; + uint32_t element_bytes; + uint32_t standard_mips; + uint32_t tail_mips; + MipOut mips[kMips]; +}; +struct LayoutOut { + uint64_t size; + uint64_t alignment; + uint32_t mips; + uint32_t planes; + PlaneOut plane[4]; + uint32_t dimension; +}; +static_assert(sizeof(MipOut) == 0x70); +static_assert(sizeof(PlaneOut) == 0x6c8); +static_assert(sizeof(LayoutOut) == 0x1b40); + +struct PackedMips { + uint8_t standard; + uint8_t packed; + uint32_t tiles; + uint32_t start; +}; +struct SubresourceTiling { + uint32_t width; + uint16_t height; + uint16_t depth; + uint32_t start; +}; +constexpr uint64_t kTile = 64u << 10; + +// Prints once per call site kind; `slot` is the vtable index for a computer method, or -1 for an export. +void warn_once(std::atomic& warned, const char* what, int slot, const void* caller, const char* why) { if (warned.exchange(true, std::memory_order_relaxed)) return; char name[64]; if (slot < 0) std::snprintf(name, sizeof(name), "%s", what); else std::snprintf(name, sizeof(name), "%s%d", what, slot); - std::fprintf(stderr, "[rt] xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", - name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); + std::fprintf(stderr, "[rt] xg_xs: %s: %s (caller %s, logged once)\n", name, why, + rt::shims::module_offset(reinterpret_cast(caller)).c_str()); +} + +// The mode the console's library picks for a description: linear for 1D, the XOR render and depth modes for targets, +// else 4 KiB standard. VIctory's reading of the library's older optimal-mode function (any size, 2D, 3D and cubes +// alike); revisit if streamed textures come out scrambled. +uint32_t suggested(const ResourceDesc& d) { + if (d.dimension == kTexture1d) return ct::kLinear; + if (d.flags & kAllowDepthStencil) return ct::kSw64kbZX; + if (d.flags & kAllowRenderTarget) return ct::kSw64kbRX; + return ct::kSw4kbS; +} + +std::optional texture_of(const ResourceDesc& d) { + ct::TextureDesc t; + switch (d.dimension) { + case kTexture1d: t.dimension = ct::Dimension::tex1d; break; + case kTexture2d: t.dimension = ct::Dimension::tex2d; break; + case kTexture3d: t.dimension = ct::Dimension::tex3d; break; + default: return std::nullopt; + } + if (d.layout == 0) t.swizzle = suggested(d); + else if (d.layout == kRowMajor) t.swizzle = ct::kLinear; + else if ((d.layout & ~0xffu) == kSwizzled) t.swizzle = d.layout & 0xffu; + else return std::nullopt; + if (d.width > std::numeric_limits::max()) return std::nullopt; + t.width = static_cast(d.width); + t.height = d.height; + t.depth_or_array = d.depth_or_array; + t.mips = d.mips; + t.format = d.format; + t.samples = d.samples ? d.samples : 1; + auto texture = ct::Texture::make(t); + // The layout structure has room for 15 mips. + if (!texture || texture->planes[0].layout.mips.size() > kMips) return std::nullopt; + return texture; } -ULONG __stdcall computer_add_ref(void*) { return 1; } -ULONG __stdcall computer_release(void*) { return 1; } +// ---- The computer that cannot lay its description out: every slot E_NOTIMPL, nothing written. ---- + +ULONG __stdcall stub_add_ref(void*) { return 1; } +ULONG __stdcall stub_release(void*) { return 1; } template -HRESULT __stdcall computer_slot(void*) { +HRESULT __stdcall stub_slot(void*) { static std::atomic warned{false}; - warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "no layout for this description; E_NOTIMPL"); return kNotImpl; } template -constexpr auto make_vtable(std::index_sequence) { +constexpr auto make_stub_vtable(std::index_sequence) { return std::array{ - (Slot == 0 ? reinterpret_cast(&computer_add_ref) - : Slot == 1 ? reinterpret_cast(&computer_release) - : reinterpret_cast(&computer_slot))...}; + (Slot == 0 ? reinterpret_cast(&stub_add_ref) + : Slot == 1 ? reinterpret_cast(&stub_release) + : reinterpret_cast(&stub_slot))...}; } +const auto kStubVtable = make_stub_vtable(std::make_index_sequence{}); +struct StubComputer { + const void* const* vtable; +}; +StubComputer g_stub{kStubVtable.data()}; + +// ---- The computer with a layout. ---- -const auto kVtable = make_vtable(std::make_index_sequence{}); struct Computer { const void* const* vtable; + std::atomic refs{1}; + ResourceDesc desc{}; + uint32_t mips = 0; + ct::Texture texture; }; -Computer g_computer{kVtable.data()}; -HRESULT __stdcall XGCreateTextureComputer(const void* /*desc*/, void** out) { - static std::atomic warned{false}; - warn_once(warned, "XGCreateTextureComputer", -1, _ReturnAddress()); - if (!out) return E_POINTER; - *out = &g_computer; // see the top of the file: two measured callers use *out without checking the HRESULT - return kNotImpl; +ULONG __stdcall add_ref(Computer* c) { return c->refs.fetch_add(1, std::memory_order_relaxed) + 1; } + +ULONG __stdcall release(Computer* c) { + const ULONG left = c->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (left == 0) delete c; + return left; +} + +// The mode a tail mip is reported in: the 256-byte one of its kind (3 for the render kind, which GFX10 lacks), the +// depth mode itself. +uint32_t tail_swizzle(uint32_t s) { + switch (s) { + case 2: case 6: case 10: case 18: case 22: case 26: return ct::kSw256bD; + case 23: case 27: return 3; + case 24: return s; + default: return ct::kSw256bS; + } +} + +MipOut mip_out(const ResourceDesc& desc, const ct::Layout& l, size_t i) { + const ct::Mip& m = l.mips[i]; + const uint64_t bpe = l.desc.element_bytes; + const uint32_t block = l.desc.block; + const bool three_d = desc.dimension == kTexture3d; + const uint32_t array = desc.depth_or_array ? desc.depth_or_array : 1u; + MipOut out{}; + out.pitch_texels = m.pitch * block; + out.pitch_bytes = m.pitch * l.desc.element_bytes; + out.padded[0] = m.pitch; + out.padded[1] = m.rows; + out.padded[2] = three_d ? m.depth_pitch : array; + out.elements[0] = m.width; + out.elements[1] = m.height; + const uint64_t w = desc.width >> i; + out.texels[0] = w ? static_cast(w) : 1u; + out.texels[1] = (desc.height >> i) ? (desc.height >> i) : 1u; + out.depth_or_array = three_d ? m.depth : array; + out.samples = l.desc.samples; + out.slice_depth = l.block[2]; + const uint64_t slice = uint64_t{m.pitch} * m.rows * bpe; + const uint64_t depth = three_d ? m.depth_pitch : 1u; + if (!m.tail) { + out.offset = m.offset; + out.slice_size = slice * l.desc.samples; + out.size = out.slice_size * depth; + out.alignment = static_cast(l.alignment); + out.swizzle = l.desc.swizzle; + } else { + out.in_tail = 1; + out.alignment = 256; + out.swizzle = tail_swizzle(l.desc.swizzle); + if (l.thick) { // a 3D tail mip is placed by position, not by offset + out.slice_size = l.alignment / l.block[2]; + out.tail_position = m.tail->x | (m.tail->y << 11); + } else { + out.offset = m.tail->offset; + out.slice_size = slice; + } + out.size = out.slice_size * depth; + } + return out; } -HRESULT __stdcall XGSuggestSwizzleMode(const void* /*desc*/, uint32_t /*flags*/, uint32_t* /*mode*/) { +HRESULT __stdcall layout(Computer* c, LayoutOut* out) { + if (!out) return kInvalidArg; + std::memset(out, 0, sizeof(*out)); + out->size = c->texture.size; + out->alignment = c->texture.alignment; + out->mips = c->mips; + out->planes = static_cast(c->texture.planes.size()); + out->dimension = c->desc.dimension; + // The library calls a depth plane "depth" only beside stencil or without mips. + const bool depth = (c->desc.flags & kAllowDepthStencil) && (c->texture.planes.size() > 1 || c->mips == 1); + for (size_t p = 0; p < c->texture.planes.size() && p < 4; ++p) { + const ct::Plane& src = c->texture.planes[p]; + const ct::Layout& l = src.layout; + PlaneOut& plane = out->plane[p]; + plane.usage = src.stencil ? 8u : depth ? 7u : 1u; + plane.size = l.size; + plane.slice_size = l.slice_size; + plane.offset = src.offset; + plane.alignment = l.alignment; + plane.element_bytes = l.desc.element_bytes; + plane.standard_mips = l.first_tail_mip; + plane.tail_mips = c->mips - l.first_tail_mip; + for (size_t i = 0; i < l.mips.size() && i < kMips; ++i) plane.mips[i] = mip_out(c->desc, l, i); + } + return S_OK; +} + +// The plane, its mip and array slice for a subresource index, and the tiled bytes and the linear bytes a copy touches. +struct CopyArgs { + const ct::Plane* plane; + uint32_t mip, slice; + size_t tiled, linear; +}; + +std::optional copy_args(const Computer* c, uint32_t plane, uint32_t subresource, uint32_t row, + uint32_t depth) { + if (plane >= c->texture.planes.size() || c->mips == 0) return std::nullopt; + const ct::Plane& p = c->texture.planes[plane]; + const ct::Layout& l = p.layout; + const uint32_t mip = subresource % c->mips, slice = subresource / c->mips; + if (mip >= l.mips.size()) return std::nullopt; + const ct::Mip& m = l.mips[mip]; + const uint64_t bytes = uint64_t{m.width} * l.desc.element_bytes; + const uint64_t depths = l.subresource_depth(mip); + // Every factor is at most 2^32, so each product fits in 64 bits; the sum is checked against size_t below. + const uint64_t linear = (depths - 1) * depth + uint64_t{m.height - 1} * row + bytes; + const uint64_t tiled = p.offset + l.size; + if (linear > std::numeric_limits::max() || tiled > std::numeric_limits::max()) + return std::nullopt; + return CopyArgs{&p, mip, slice, static_cast(tiled), static_cast(linear)}; +} + +HRESULT result(ct::Error e) { + switch (e) { + case ct::Error::ok: return S_OK; + case ct::Error::unsupported: return kNotImpl; + default: return kInvalidArg; + } +} + +void warn_copy(const Computer* c, const char* what, uint32_t subresource, ct::Error e) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) >= 8) return; + std::fprintf(stderr, + "[rt] xg_xs: %s subresource %u failed (%s): dim=%u %llux%u depth/array=%u mips=%u format=%u " + "layout=0x%x\n", + what, subresource, + e == ct::Error::unsupported ? "addressing not modelled" : e == ct::Error::too_small ? "too small" + : "invalid", + c->desc.dimension, static_cast(c->desc.width), c->desc.height, + c->desc.depth_or_array, c->desc.mips, c->desc.format, c->desc.layout); +} + +// (tiled base, plane, subresource, linear, row pitch, depth pitch). +HRESULT __stdcall copy_into(Computer* c, uint8_t* tiled, uint32_t plane, uint32_t subresource, const uint8_t* linear, + uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.tile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy into", subresource, e); + return result(e); +} + +// (linear, plane, subresource, sample, tiled base, row pitch, depth pitch). +HRESULT __stdcall copy_from(Computer* c, uint8_t* linear, uint32_t plane, uint32_t subresource, uint32_t /*sample*/, + const uint8_t* tiled, uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.detile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy out of", subresource, e); + return result(e); +} + +// (total tiles, packed mips, tile shape in texels, in: room / out: count, first, subresource tilings), in 64 KiB +// tiles of plane 0, for 2D 64 KiB modes only (others fail, as on the console). The mip tail is the packed part, tile 0 +// of each slice; tilings list the standard mips of every slice in turn. With a tail the console's library lists two +// slices at most and zeroes all but the first (VIctory's reading; the title reads slice 0 only). +HRESULT __stdcall tiling(Computer* c, uint32_t* tiles, PackedMips* packed, uint32_t* shape, uint32_t* count, + uint32_t first, SubresourceTiling* out) { + const ct::Layout& l = c->texture.planes[0].layout; + if (l.alignment != kTile) return kFail; + if (l.thick) return kNotImpl; + const uint32_t standard = l.first_tail_mip; + const bool tail = standard < c->mips; + const uint64_t tail_tiles = standard == 0 ? l.slice_size / kTile + : tail ? l.mips[standard - 1].offset / kTile + : 0; + const uint32_t block = l.desc.block; + if (tiles) *tiles = static_cast(l.size / kTile); + if (packed) { + packed->standard = static_cast(standard); + packed->packed = static_cast(c->mips - standard); + packed->tiles = static_cast(tail_tiles); + packed->start = 0; + } + if (shape) { + shape[0] = l.block[0] * block; + shape[1] = l.block[1] * block; + shape[2] = l.block[2]; + } + if (count) { + const uint32_t slices = tail ? std::min(l.slices, 2u) : l.slices; + const uint64_t total = uint64_t{standard} * slices; + const uint32_t wanted = + static_cast(std::min(total > first ? total - first : 0, *count)); + for (uint32_t i = 0; i < wanted && out; ++i) { + const uint32_t slice = (first + i) / standard, mip = (first + i) % standard; + const ct::Mip& m = l.mips[mip]; + SubresourceTiling entry{}; + if (!(tail && slice > 0)) { + entry.width = m.pitch / l.block[0]; + entry.height = static_cast(m.rows / l.block[1]); + entry.depth = 1; + entry.start = static_cast((uint64_t{slice} * l.slice_size + m.offset) / kTile); + } + out[i] = entry; + } + *count = out ? wanted : 0; + } + return S_OK; +} + +// (plane, mip, x, y, z or slice, sample, bit position): an element's byte offset from the texture's start, 0 if +// outside. VIctory measured the title reading texels of a 128x4 4KB_S texture on the CPU through it. +uint64_t __stdcall element_offset(Computer* c, uint32_t plane, uint32_t mip, uint64_t x, uint32_t y, uint32_t z, + uint32_t /*sample*/, uint32_t* bit) { + if (bit) *bit = 0; + if (plane >= c->texture.planes.size()) return 0; + const ct::Plane& p = c->texture.planes[plane]; + const uint32_t x32 = x > std::numeric_limits::max() ? std::numeric_limits::max() + : static_cast(x); + uint64_t at = 0; + if (p.layout.offset(mip, x32, y, z, at) != ct::Error::ok) return 0; + return p.offset + at; +} + +template +HRESULT __stdcall unused_slot(Computer*) { static std::atomic warned{false}; - warn_once(warned, "XGSuggestSwizzleMode", -1, _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "method not implemented; E_NOTIMPL"); return kNotImpl; } +template +constexpr auto make_vtable(std::index_sequence) { + return std::array{ + (Slot == 0 ? reinterpret_cast(&add_ref) + : Slot == 1 ? reinterpret_cast(&release) + : Slot == 2 ? reinterpret_cast(&layout) + : Slot == 6 ? reinterpret_cast(&element_offset) + : Slot == 8 ? reinterpret_cast(©_into) + : Slot == 9 ? reinterpret_cast(©_from) + : Slot == 10 ? reinterpret_cast(&tiling) + : reinterpret_cast(&unused_slot))...}; +} +const auto kVtable = make_vtable(std::make_index_sequence{}); + +HRESULT __stdcall XGCreateTextureComputer(const ResourceDesc* desc, void** out) { + if (!out) return E_POINTER; + std::optional texture; + if (desc) texture = texture_of(*desc); + if (!texture) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) < 8) { + if (desc) + std::fprintf(stderr, + "[rt] xg_xs: XGCreateTextureComputer: no layout for dim=%u %llux%u depth/array=%u " + "mips=%u format=%u samples=%u layout=0x%x flags=0x%x (caller %s)\n", + desc->dimension, static_cast(desc->width), desc->height, + desc->depth_or_array, desc->mips, desc->format, desc->samples, desc->layout, + desc->flags, + rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); + else + std::fprintf(stderr, "[rt] xg_xs: XGCreateTextureComputer: null description\n"); + } + *out = &g_stub; // see the top of the file: two measured callers use *out without checking the HRESULT + return kInvalidArg; + } + auto* c = new (std::nothrow) Computer; + if (!c) { + *out = &g_stub; + return E_OUTOFMEMORY; + } + c->vtable = kVtable.data(); + c->desc = *desc; + c->mips = static_cast(texture->planes[0].layout.mips.size()); + c->texture = std::move(*texture); + *out = c; + return S_OK; +} + +// (desc, flags, out layout); the title passes flags 0 and puts the result in the description's layout field. +HRESULT __stdcall XGSuggestSwizzleMode(const ResourceDesc* desc, uint32_t /*flags*/, uint32_t* mode) { + if (!desc || !mode) return kInvalidArg; + *mode = kSwizzled | suggested(*desc); + return S_OK; +} + +uint64_t texture_size(const void* desc, uint64_t& alignment) { + ResourceDesc d; + static_assert(sizeof(d) == 56); + std::memcpy(&d, desc, sizeof(d)); + const auto texture = texture_of(d); + if (!texture) return 0; + alignment = texture->alignment; + return texture->size; +} +const bool g_texture_size_set = (rt::xg::texture_size_fn = &texture_size, true); + } // namespace SHIM_TABLE(xg_xs, diff --git a/runtime/src/console_texture_layout.h b/runtime/src/console_texture_layout.h new file mode 100644 index 0000000000..782d8584ad --- /dev/null +++ b/runtime/src/console_texture_layout.h @@ -0,0 +1,610 @@ +// Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and alignment, where each mip and array slice +// starts, the address of each element, and copies between tiled memory and linear rows. Used by the xg_xs.dll shim +// (runtime/shims/xg_xs.cpp), whose texture computer answers the title's layout and copy calls from it. +// +// Ported from Marvisak/VIctory (GPL-3.0), crates/victory-formats/src/texture.rs at commit d2a4bae1f, which follows +// AMD's address library (addrlib) as shipped in Mesa under src/amd/addrlib: block dimensions, mip placement and mip +// tails from gfx10addrlib.cpp and addrlib2.cpp (ComputeSurfaceInfoMacroTiled, ComputeThinBlockDimension, +// GetMipTailDim, GetMaxNumMipsInTail, HwlComputeSurfaceInfoLinear, ComputeSurfaceAddrFromCoordMacroTiled), and the +// 256-byte micro tile patterns in kMicro from gfx10SwizzlePattern.h (the RB+ tables, as on RDNA2). addrlib carries +// this notice: +// +// Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and +// to permit persons to whom the Software is furnished to do so, subject to the following conditions: the above +// copyright notice and this permission notice shall be included in all copies or substantial portions of the +// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. +// +// Units: an element is a texel, or a 4x4 block of a block-compressed format. Mips of one array slice (or one depth +// slab of a thick 3D texture) are stored together, smallest first: the mip tail (the small mips sharing one block) +// at offset 0, mip 0 last. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::console_texture { + +// A swizzle mode, by its hardware number (addrlib's ADDR_SW_* order). +enum : uint32_t { + kLinear = 0, + kSw256bS = 1, + kSw256bD = 2, + kSw4kbS = 5, + kSw4kbD = 6, + kSw64kbS = 9, + kSw64kbD = 10, + kSw64kbST = 17, + kSw64kbDT = 18, + kSw4kbSX = 21, + kSw4kbDX = 22, + kSw4kbRX = 23, + kSw64kbZX = 24, + kSw64kbSX = 25, + kSw64kbDX = 26, + kSw64kbRX = 27, +}; + +// log2 of the block size in bytes (0 for linear); nullopt for modes GFX10 does not have. +inline std::optional block_log2(uint32_t swizzle) { + switch (swizzle) { + case 0: return 0; + case 1: case 2: return 8; + case 5: case 6: case 21: case 22: case 23: return 12; + case 9: case 10: case 17: case 18: case 24: case 25: case 26: case 27: return 16; + default: return std::nullopt; + } +} +inline bool is_standard(uint32_t s) { return s == 1 || s == 5 || s == 9 || s == 17 || s == 21 || s == 25; } +inline bool is_display(uint32_t s) { return s == 2 || s == 6 || s == 10 || s == 18 || s == 22 || s == 26; } +inline bool is_z_order(uint32_t s) { return s == 24; } +// Pipe and bank XOR modes (_T, _X): their addresses depend on the GPU's pipe configuration. +inline bool is_xor(uint32_t s) { return s >= 16; } + +enum class Dimension { tex1d, tex2d, tex3d }; + +enum class Error { + ok, + invalid, // the description makes no texture, or a coordinate or subresource lies outside it + unsupported, // a valid layout whose addressing is not implemented here + too_small, // a buffer is smaller than the layout or the rows need +}; + +// One plane of a texture. +struct Desc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; + uint32_t element_bytes = 4; // 1, 2, 4, 8 or 16 + uint32_t block = 1; // texels per element side: 1, or 4 for block compression + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Tail { + uint32_t offset = 0; // byte offset inside the tail block + uint32_t x = 0, y = 0; // element position the mip starts at +}; + +// Where one mip lives inside a slice. +struct Mip { + uint32_t width = 0, height = 0, depth = 0; // size in elements (depth 1 unless the texture is 3D) + uint32_t pitch = 0, rows = 0, depth_pitch = 0; // padded size in elements: whole blocks, or the tail's share + uint64_t offset = 0; // byte offset of its first block in the slice (0 in the tail) + std::optional tail; +}; + +namespace detail { + +constexpr uint32_t div_ceil(uint32_t a, uint32_t b) { return (a + b - 1) / b; } +constexpr uint32_t round_up(uint32_t a, uint32_t b) { return div_ceil(a, b) * b; } + +// Elements along one side of mip `mip`, as data and copies see it: texels halve rounding down (to at least 1), then +// round up to whole elements. +constexpr uint32_t dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(std::max(texels >> mip, 1u), block); +} +// Elements along one side of mip `mip` for placement (padding, tail, offsets): addrlib halves mip 0's elements +// rounding up, which can be one more than dim() for odd sizes. +constexpr uint32_t padded_dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(div_ceil(std::max(texels, 1u), block), 1u << mip); +} + +// Micro tile (256 bytes) patterns by log2 of the element size: for each address bit, the element coordinate bit it +// takes (x0, y1, z0...), "--" for the bits inside an element. Thin S, thin D, thick S (also the D 3D modes). From +// addrlib's GFX10_SW_256_S_RBPLUS, GFX10_SW_256_D_RBPLUS and GFX10_SW_4K_S3_RBPLUS patterns; the larger blocks add +// bits Y, X (thin) or Y, X, Z (thick) in turn. +inline constexpr const char* kMicro[3][5] = { + {"x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"}, + {"x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1x2y2", "------x0y0x1x2y1", "--------x0y0x1y1"}, + {"x0x1z0y0z1y1x2z2", "--x0z0y0z1y1x1z2", "----x0y0z0y1x1z1", "------x0z0y0x1z1", "--------z0y0x0z1"}, +}; + +// For each axis, the address bit each coordinate bit lands on. +inline std::array, 3> pattern(int kind, uint32_t element_log2, uint32_t block_log2) { + std::array, 3> axes; + const char* micro = kMicro[kind][element_log2]; + for (uint32_t bit = 0; bit < 8; ++bit) { + const char a = micro[2 * bit]; + const int axis = a == 'x' ? 0 : a == 'y' ? 1 : a == 'z' ? 2 : -1; + if (axis < 0) continue; + const size_t index = static_cast(micro[2 * bit + 1] - '0'); + auto& to = axes[static_cast(axis)]; + if (to.size() <= index) to.resize(index + 1, 0); + to[index] = bit; + } + static constexpr int kThin[2] = {1, 0}; + static constexpr int kThick[3] = {1, 0, 2}; + const int* order = kind == 2 ? kThick : kThin; + const uint32_t n = kind == 2 ? 3u : 2u; + for (uint32_t bit = 8, i = 0; bit < block_log2; ++bit, ++i) axes[static_cast(order[i % n])].push_back(bit); + return axes; +} + +// Byte offsets inside a block for coordinates 0..2^bits of one axis. +inline std::vector spread(const std::vector& bits) { + std::vector out(size_t{1} << bits.size()); + for (uint32_t c = 0; c < out.size(); ++c) { + uint32_t v = 0; + for (size_t i = 0; i < bits.size(); ++i) v |= ((c >> i) & 1u) << bits[i]; + out[c] = v; + } + return out; +} + +} // namespace detail + +constexpr uint32_t kMaxMips = 16; +// The largest width, height and depth (or array size) accepted, in texels. GFX10's image descriptors hold at most +// 16384 texels per side, so no texture the GPU can use is refused. The bound also keeps every size computed below +// within uint64_t (and its uint32_t steps), which unchecked values from a title would otherwise overflow. +constexpr uint32_t kMaxExtent = 1u << 14; + +// 256-byte micro tile dimensions by log2 element size, 2D and 3D. +inline constexpr uint32_t kBlock256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; +inline constexpr uint32_t kBlock256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; +inline constexpr uint32_t kBlock1k_3d[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; + +class Layout { +public: + Desc desc; + std::array block{}; // block dimensions in elements (linear: the pitch alignment, 1, 1) + bool thick = false; // 3D blocks span block[2] depth slices (GFX10 3D S and D modes) + // Array slices, depth slabs of block[2] slices (thick), or depth slices (thin and linear 3D). + uint32_t slices = 0; + uint64_t slice_size = 0; // bytes of one slice: its whole mip chain + uint64_t size = 0; + uint64_t alignment = 0; + uint32_t first_tail_mip = 0; // the first mip in the tail; mips.size() without one + std::vector mips; + + static std::optional make(const Desc& d) { + const auto log2 = block_log2(d.swizzle); + if (!log2) return std::nullopt; + const auto in = [](uint32_t v, uint32_t lo, uint32_t hi) { return v >= lo && v <= hi; }; + const bool valid = + in(d.width, 1, kMaxExtent) && in(d.height, 1, kMaxExtent) && in(d.depth, 1, kMaxExtent) && + in(d.mips, 1, kMaxMips) && std::has_single_bit(d.element_bytes) && d.element_bytes <= 16 && + (d.block == 1 || d.block == 4) && std::has_single_bit(d.samples) && d.samples <= 8 && + (d.samples == 1 || (d.dimension == Dimension::tex2d && d.mips == 1)) && + (d.dimension != Dimension::tex1d || d.height == 1) && + (d.dimension != Dimension::tex3d || d.swizzle == 0 || d.swizzle == 5 || d.swizzle == 9 || + d.swizzle == 17 || d.swizzle == 21 || (d.swizzle >= 24 && d.swizzle <= 27)); + if (!valid) return std::nullopt; + return *log2 == 0 ? linear(d) : tiled(d, *log2); + } + + // Whether offset() and the copies work for this layout: linear and the modes without pipe or bank XOR, + // single-sampled. The XOR modes (_X, _T) and MSAA need the GPU's pipe and bank configuration (Series X and S + // differ); titles use them for render targets and depth, which the host renders. + bool addressable() const { return desc.swizzle == kLinear || !pattern_[0].empty(); } + + // Depth slices a subresource of mip `mip` covers: the mip's depth for 3D textures, else 1 (one array slice). + uint32_t subresource_depth(uint32_t mip) const { return mip < mips.size() ? mips[mip].depth : 0; } + + // Byte offset of element (x, y) of mip `mip` in array slice or depth slice `z`. Coordinates must lie inside. + Error offset(uint32_t mip, uint32_t x, uint32_t y, uint32_t z, uint64_t& out) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = desc.dimension == Dimension::tex3d ? m.depth : slices; + const bool inside = x < m.width && y < m.height && z < depth; + if (!inside) return Error::invalid; + if (!addressable()) return Error::unsupported; + const auto [slice, inner] = split(z); + const uint64_t base = uint64_t{slice} * slice_size + m.offset; + if (desc.swizzle == kLinear) { + out = base + (uint64_t{y} * m.pitch + x) * desc.element_bytes; + return Error::ok; + } + out = base + row(m, y, inner) + column(m, x); + return Error::ok; + } + + // Copies one subresource out of tiled memory (the whole texture, `size` bytes) into linear rows: mip `mip` of + // array slice `slice` (3D: every depth slice of the mip, slice 0). Rows are row_pitch bytes apart, depth slices + // depth_pitch. + Error detile(const uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(linear + l, tiled + t, n); + }); + } + // The reverse of detile(): linear rows into tiled memory. + Error tile(uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, const uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(tiled + t, linear + l, n); + }); + } + + // Byte offsets inside a block of each element coordinate bit, per axis; empty for linear and XOR/MSAA modes. + const std::array, 3>& pattern() const { return pattern_; } + +private: + std::array, 3> pattern_; + + // HwlComputeSurfaceInfoLinear: rows aligned to 256 bytes, mips packed smallest first, a 3D texture's depth slices + // each hold the chain. + static Layout linear(const Desc& d) { + using namespace detail; + Layout l; + l.desc = d; + const uint64_t bpe = d.element_bytes; + const uint32_t align = 256 / d.element_bytes; + const bool three_d = d.dimension == Dimension::tex3d; + uint64_t offset = 0; + for (uint32_t i = d.mips; i-- > 0;) { + const uint32_t h = padded_dim(d.height, i, d.block); + const uint32_t pitch = round_up(padded_dim(d.width, i, d.block), align); + Mip m; + m.width = dim(d.width, i, d.block); + m.height = dim(d.height, i, d.block); + m.depth = three_d ? dim(d.depth, i, 1) : 1; + m.pitch = pitch; + m.rows = h; + m.depth_pitch = three_d ? d.depth : 1; + m.offset = offset; + l.mips.push_back(m); + offset += uint64_t{pitch} * h * bpe; + } + std::reverse(l.mips.begin(), l.mips.end()); + l.block = {align, 1, 1}; + l.slices = d.depth; + l.slice_size = offset; + l.size = offset * d.depth; + l.alignment = 256; + l.first_tail_mip = d.mips; + return l; + } + + static Layout tiled(const Desc& d, uint32_t block_log2) { + using namespace detail; + Layout l; + l.desc = d; + const uint32_t element_log2 = static_cast(std::countr_zero(d.element_bytes)); + const uint64_t bpe = d.element_bytes; + const uint64_t block_bytes = uint64_t{1} << block_log2; + const bool thick = d.dimension == Dimension::tex3d && (is_standard(d.swizzle) || is_display(d.swizzle)); + std::array block{}; + if (thick) { // ComputeThickBlockDimension + const uint32_t amp = (block_log2 - 10) / 3, rest = (block_log2 - 10) % 3; + const auto* b = kBlock1k_3d[element_log2]; + block = {b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + (rest != 0 ? 1u : 0u))}; + } else { // ComputeThinBlockDimension + const uint32_t samples_log2 = static_cast(std::countr_zero(d.samples)); + const uint32_t elements_log2 = block_log2 - element_log2 - samples_log2; + const bool wide = (samples_log2 & 1) == 0 || (block_log2 & 1) != 0; + const uint32_t w = (elements_log2 + (wide ? 1u : 0u)) / 2; + block = {1u << w, 1u << (elements_log2 - w), 1}; + } + uint32_t slices = round_up(d.depth, block[2]); + const bool three_d = d.dimension == Dimension::tex3d; + // Mip depths placed by a thick layout (thin ones store depth as slices). + const auto mip_depth = [&](uint32_t i) { return thick ? padded_dim(d.depth, i, 1) : 1u; }; + const auto depth_of = [&](uint32_t i) { return three_d ? dim(d.depth, i, 1) : 1u; }; + const auto width = [&](uint32_t i) { return dim(d.width, i, d.block); }; + const auto height = [&](uint32_t i) { return dim(d.height, i, d.block); }; + uint32_t first_tail_mip = d.mips; + uint64_t slice_size = 0; + if (d.mips == 1) { + Mip m; + m.width = width(0); + m.height = height(0); + m.depth = depth_of(0); + m.pitch = round_up(width(0), block[0]); + m.rows = round_up(height(0), block[1]); + m.depth_pitch = three_d ? slices : 1; + l.mips.push_back(m); + slice_size = uint64_t{m.pitch} * m.rows * bpe * d.samples; + } else { + // GetMipTailDim: the largest mip the tail takes. + std::array tail_max = block; + if (thick) { + switch (block_log2 % 3) { + case 0: tail_max[1] >>= 1; break; + case 1: tail_max[0] >>= 1; break; + default: tail_max[2] >>= 1; break; + } + } else { + tail_max[0] >>= 1; + } + // GetMaxNumMipsInTail; 256-byte blocks have no tail (ComputeSurfaceInfoMicroTiled). + const uint32_t effective = thick ? block_log2 - (block_log2 - 8) / 3 : block_log2; + const uint32_t max_in_tail = effective == 8 ? 0 + : (effective >= 9 && effective <= 11) ? 1 + (1u << (effective - 9)) + : effective - 4; + // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. + std::array fixed = tail_max; + if (is_z_order(d.swizzle) && element_log2 <= 1) { + const auto* b = kBlock256_2d[element_log2]; + fixed[0] /= b[0] / kBlock256_2d[2][0]; + fixed[1] /= b[1] / kBlock256_2d[2][1]; + } + std::vector sizes; + for (uint32_t i = 0; i < d.mips; ++i) { + const uint32_t w = padded_dim(d.width, i, d.block), h = padded_dim(d.height, i, d.block); + if (w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail) { + first_tail_mip = i; + slice_size += block_bytes / block[2]; + break; + } + const uint32_t pitch = round_up(w, block[0]), rows = round_up(h, block[1]); + const uint32_t depth = round_up(mip_depth(i), block[2]); + const uint64_t one = uint64_t{pitch} * rows * bpe; + slice_size += one; + sizes.push_back(one * block[2]); + Mip m; + m.width = width(i); + m.height = height(i); + m.depth = depth_of(i); + m.pitch = pitch; + m.rows = rows; + m.depth_pitch = three_d ? depth : 1; + l.mips.push_back(m); + } + // Standard mips from the smallest up, after the tail block. + uint64_t offset = first_tail_mip < d.mips ? block_bytes : 0; + for (uint32_t i = first_tail_mip; i-- > 0;) { + l.mips[i].offset = offset; + offset += sizes[i]; + } + uint32_t micro[2]; + if (thick) { + micro[0] = kBlock256_3d[element_log2][0]; + micro[1] = kBlock256_3d[element_log2][1]; + } else { + micro[0] = kBlock256_2d[element_log2][0]; + micro[1] = kBlock256_2d[element_log2][1]; + } + uint32_t pitch = tail_max[0], rows = tail_max[1]; + for (uint32_t i = first_tail_mip; i < d.mips; ++i) { + const uint32_t m = max_in_tail - 1 - (i - first_tail_mip); + const uint32_t offset_in_tail = m > 6 ? 16u << m : m << 8; + // Address bits 8.. of the offset, odd ones x, even ones y. + const auto bits = [&](uint32_t from) { + uint32_t v = 0; + for (uint32_t b = 0; b < 6; ++b) v |= ((offset_in_tail >> (from + 2 * b)) & 1u) << b; + return v; + }; + uint32_t x = bits(9), y = bits(8); + if ((block_log2 & 1) != 0) { + std::swap(x, y); + if ((element_log2 & 1) != 0) { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + Mip t; + t.width = width(i); + t.height = height(i); + t.depth = depth_of(i); + t.pitch = pitch; + t.rows = rows; + t.depth_pitch = thick ? round_up(mip_depth(i), kBlock256_3d[element_log2][2]) : 1; + t.offset = 0; + t.tail = Tail{offset_in_tail, x * micro[0], y * micro[1]}; + l.mips.push_back(t); + pitch = std::max(pitch >> 1, micro[0]); + rows = std::max(rows >> 1, micro[1]); + } + } + // Thick layouts store each depth slab's chain together. + const uint64_t slab = thick ? block[2] : 1; + slice_size *= slab; + slices /= block[2]; + if (!is_xor(d.swizzle) && d.samples == 1) { + const int kind = thick ? 2 : (is_display(d.swizzle) ? 1 : 0); + const auto bits = detail::pattern(kind, element_log2, block_log2); + for (size_t a = 0; a < 3; ++a) l.pattern_[a] = detail::spread(bits[a]); + } + l.block = block; + l.thick = thick; + l.slices = slices; + l.slice_size = slice_size; + l.size = slice_size * slices; + l.alignment = block_bytes; + l.first_tail_mip = first_tail_mip; + return l; + } + + // The slice and the depth inside it for z (an array slice or a 3D depth slice). + std::pair split(uint32_t z) const { + return thick ? std::pair{z / block[2], z % block[2]} : std::pair{z, 0u}; + } + + // The part of an address that depends on the row (and depth in a thick block). + uint64_t row(const Mip& m, uint32_t y, uint32_t z) const { + const uint32_t bw = block[0], bh = block[1]; + const int log2 = std::countr_zero(alignment); + // In the tail the pattern of the shifted position gives the mip's offset inside the tail block. + y += m.tail ? m.tail->y : 0; + const uint64_t blocks = uint64_t{y / bh} * (m.pitch / bw); + return (blocks << log2) + (pattern_[1][y % bh] | pattern_[2][z]); + } + + // The part of an address that depends on the column. + uint64_t column(const Mip& m, uint32_t x) const { + const uint32_t bw = block[0]; + x += m.tail ? m.tail->x : 0; + return (uint64_t{x / bw} << std::countr_zero(alignment)) + pattern_[0][x % bw]; + } + + // Visits contiguous runs as (tiled byte offset, linear byte offset, length). + template + Error walk(size_t tiled_len, uint32_t mip, uint32_t slice, size_t linear_len, size_t row_pitch, + size_t depth_pitch, Copy&& copy) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = m.depth; + uint32_t first = slice; + if (desc.dimension == Dimension::tex3d) { + if (slice != 0) return Error::invalid; + first = 0; + } + if (first >= slices) return Error::invalid; + if (!addressable()) return Error::unsupported; + const size_t n = desc.element_bytes; + const size_t bytes = size_t{m.width} * n; + // need = (depth - 1) * depth_pitch + (height - 1) * row_pitch + bytes, refused on overflow. + const size_t dz = depth - 1u, dy = m.height - 1u; + if ((dz && depth_pitch > SIZE_MAX / dz) || (dy && row_pitch > SIZE_MAX / dy)) return Error::too_small; + const size_t depth_offset = dz * depth_pitch, row_offset = dy * row_pitch; + if (depth_offset > SIZE_MAX - row_offset || depth_offset + row_offset > SIZE_MAX - bytes) + return Error::too_small; + const size_t need = depth_offset + row_offset + bytes; + if (tiled_len < size || linear_len < need || row_pitch < bytes) return Error::too_small; + const bool is_linear = desc.swizzle == kLinear; + // The row and depth contribute one common base to every column, so the same contiguous runs repeat on + // every row, including mip tails. + struct Run { + size_t tiled, linear, len; + }; + std::vector runs; + if (!is_linear) { + size_t first_linear = 0, first_tiled = static_cast(column(m, 0)); + for (uint32_t x = 1; x < m.width; ++x) { + const size_t off = static_cast(column(m, x)); + const size_t at = x * n; + if (off != first_tiled + (at - first_linear)) { + runs.push_back({first_tiled, first_linear, at - first_linear}); + first_tiled = off; + first_linear = at; + } + } + runs.push_back({first_tiled, first_linear, bytes - first_linear}); + } + for (uint32_t z = 0; z < depth; ++z) { + const auto [s, inner] = split(first + z); + const uint64_t base = uint64_t{s} * slice_size + m.offset; + for (uint32_t y = 0; y < m.height; ++y) { + const size_t linear_row = z * depth_pitch + y * row_pitch; + if (is_linear) { + copy(static_cast(base + uint64_t{y} * m.pitch * n), linear_row, bytes); + } else { + const size_t tiled_row = static_cast(base + row(m, y, inner)); + for (const Run& r : runs) copy(tiled_row + r.tiled, linear_row + r.linear, r.len); + } + } + } + return Error::ok; + } +}; + +// What a DXGI format stores per element: bytes, texels per element side (4 for block compression), and whether its +// stencil is a second plane (the GPU keeps depth and stencil apart). nullopt for 96-bit, 1-bit, packed 4:2:2 and +// video formats, which have no layout here. +struct Format { + uint32_t bytes, block; + bool stencil; +}; +inline std::optional format(uint32_t dxgi) { + const auto in = [&](uint32_t lo, uint32_t hi) { return dxgi >= lo && dxgi <= hi; }; + if (in(1, 4)) return Format{16, 1, false}; + if (in(9, 18)) return Format{8, 1, false}; + if (in(19, 22) || in(44, 47)) return Format{4, 1, true}; + if (in(23, 43) || dxgi == 67 || in(87, 93) || dxgi == 116 || dxgi == 117) return Format{4, 1, false}; + if (in(48, 59) || dxgi == 85 || dxgi == 86 || dxgi == 115) return Format{2, 1, false}; + if (in(118, 120)) return Format{2, 1, true}; + if (in(60, 65)) return Format{1, 1, false}; + if (in(70, 72) || in(79, 81)) return Format{8, 4, false}; + if (in(73, 78) || in(82, 84) || in(94, 99)) return Format{16, 4, false}; + return std::nullopt; +} + +// A texture as the console allocates it: a D3D12-style description with a swizzle mode. +struct TextureDesc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth_or_array = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; // 0: the full chain + uint32_t format = 0; // DXGI format number + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Plane { + uint64_t offset = 0; // from the start of the texture + bool stencil = false; + Layout layout; +}; + +// Every data plane of a texture (depth, then stencil), placed one after the other. No compression metadata planes +// (HTILE, CMASK, FMASK, DCC): the console adds them to render targets and depth buffers unless the description +// denies them, so those are smaller here than on the console; the host GPU renders them, so nothing reads that +// memory. +struct Texture { + std::vector planes; + uint64_t size = 0; + uint64_t alignment = 0; + + static std::optional make(const TextureDesc& desc) { + const auto f = format(desc.format); + if (!f) return std::nullopt; + const uint32_t depth3d = desc.dimension == Dimension::tex3d ? desc.depth_or_array : 1; + const uint32_t mips = + desc.mips ? desc.mips + : 32u - static_cast(std::countl_zero( + std::max({desc.width, desc.height, depth3d, 1u}))); + const auto plane = [&](uint32_t bytes) { + Desc d; + d.dimension = desc.dimension; + d.width = desc.width; + d.height = desc.height; + d.depth = desc.depth_or_array; + d.mips = mips; + d.element_bytes = bytes; + d.block = f->block; + d.samples = std::max(desc.samples, 1u); + d.swizzle = desc.swizzle; + return d; + }; + Texture t; + auto main = Layout::make(plane(f->bytes)); + if (!main) return std::nullopt; + t.planes.push_back({0, false, std::move(*main)}); + if (f->stencil) { + auto s = Layout::make(plane(1)); + if (!s) return std::nullopt; + const uint64_t a = s->alignment; + const uint64_t offset = (t.planes[0].layout.size + a - 1) / a * a; + t.planes.push_back({offset, true, std::move(*s)}); + } + const Plane& last = t.planes.back(); + t.size = last.offset + last.layout.size; + for (const Plane& p : t.planes) t.alignment = std::max(t.alignment, p.layout.alignment); + return t; + } +}; + +} // namespace leonida::console_texture diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 7db9b60962..9446f2a0fe 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -1,34 +1,46 @@ -// Checks the registered xg_xs.dll shim against the call shapes measured in the game executable (runtime/shims/xg_xs.cpp). +// Checks the registered xg_xs.dll shim (runtime/shims/xg_xs.cpp) and the console texture layout model behind it +// (runtime/src/console_texture_layout.h). Synthetic textures only; no game files. // -// Both exports are resolved through rt::shims::find, so this is the table the runtime installs. The checks: both -// return E_NOTIMPL, XGSuggestSwizzleMode leaves the caller's field alone, XGCreateTextureComputer still hands out a -// computer (two measured callers use it without checking the HRESULT), and the computer's slots called at the -// measured sites (1, 2, 8, 10) return without writing what their arguments point to. +// Both exports are resolved through rt::shims::find, so this is the table the runtime installs. The layout cases and +// their expected numbers are those of the project the model is ported from (Marvisak/VIctory, GPL-3.0, +// crates/victory-formats/src/texture.rs and crates/victory-hle/src/modules/xg.rs tests at d2a4bae1f): hand-checked +// addresses, mip tail placement, a two-plane depth-stencil, and a bijection plus round trip over every element. #include #include #include #include +#include +#include "../src/console_texture_layout.h" +#include "console_texture_size.h" #include "shims.h" namespace { +namespace ct = leonida::console_texture; + using CreateFn = HRESULT(__stdcall*)(const void*, void**); using SuggestFn = HRESULT(__stdcall*)(const void*, uint32_t, uint32_t*); using ReleaseFn = ULONG(__stdcall*)(void*); -using Slot2Fn = HRESULT(__stdcall*)(void*, void*); -using Slot8Fn = HRESULT(__stdcall*)(void*, void*, uint32_t, uint32_t, const void*, uint32_t, uint32_t); -using Slot10Fn = HRESULT(__stdcall*)(void*, uint32_t*, void*, void*, uint32_t*, uint32_t, void*); +using LayoutFn = HRESULT(__stdcall*)(void*, void*); +using OffsetFn = uint64_t(__stdcall*)(void*, uint32_t, uint32_t, uint64_t, uint32_t, uint32_t, uint32_t, uint32_t*); +using IntoFn = HRESULT(__stdcall*)(void*, uint8_t*, uint32_t, uint32_t, const uint8_t*, uint32_t, uint32_t); +using FromFn = HRESULT(__stdcall*)(void*, uint8_t*, uint32_t, uint32_t, uint32_t, const uint8_t*, uint32_t, uint32_t); +using TilingFn = HRESULT(__stdcall*)(void*, uint32_t*, void*, uint32_t*, uint32_t*, uint32_t, void*); constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +constexpr HRESULT kInvalidArg = static_cast(0x80070057u); +constexpr HRESULT kFail = static_cast(0x80004005u); int g_checks = 0; int g_failures = 0; void check(bool condition, const char* what) { ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; + if (!condition) { + std::printf("FAIL %s\n", what); + ++g_failures; + } } bool all_bytes(const uint8_t* p, size_t n, uint8_t value) { @@ -37,6 +49,337 @@ bool all_bytes(const uint8_t* p, size_t n, uint8_t value) { return true; } +ct::Desc desc2d(uint32_t w, uint32_t h, uint32_t mips, uint32_t bpe, uint32_t swizzle) { + ct::Desc d; + d.width = w; + d.height = h; + d.mips = mips; + d.element_bytes = bpe; + d.swizzle = swizzle; + return d; +} + +uint64_t offset_of(const ct::Layout& l, uint32_t mip, uint32_t x, uint32_t y, uint32_t z) { + uint64_t at = ~uint64_t{0}; + return l.offset(mip, x, y, z, at) == ct::Error::ok ? at : ~uint64_t{0}; +} + +// The D3D12-style description the title passes (0x38 bytes). +struct ResourceDesc { + uint32_t dimension; + uint64_t alignment; + uint64_t width; + uint32_t height; + uint16_t depth_or_array; + uint16_t mips; + uint32_t format; + uint32_t samples; + uint32_t quality; + uint32_t layout; + uint32_t flags; +}; +static_assert(sizeof(ResourceDesc) == 0x38); + +ResourceDesc rdesc(uint64_t w, uint32_t h, uint16_t mips, uint32_t format, uint32_t layout) { + ResourceDesc d{}; + d.dimension = 3; + d.width = w; + d.height = h; + d.depth_or_array = 1; + d.mips = mips; + d.format = format; + d.samples = 1; + d.layout = layout; + return d; +} + +void test_layout_model() { + // Sizes past the hardware's 16384 texels per side are refused instead of overflowing. + for (uint32_t s : {ct::kLinear, ct::kSw64kbDX}) { + const auto largest = ct::Layout::make(desc2d(ct::kMaxExtent, ct::kMaxExtent, 15, 16, s)); + check(largest && largest->size >= uint64_t{ct::kMaxExtent} * ct::kMaxExtent * 16, "largest texture lays out"); + check(!ct::Layout::make(desc2d(ct::kMaxExtent + 1, 1, 1, 16, s)), "width past 16384 is refused"); + check(!ct::Layout::make(desc2d(1, 0xffffffffu, 1, 16, s)), "height past 16384 is refused"); + auto deep = desc2d(1, 1, 1, 16, s); + deep.depth = 0xffffffffu; + check(!ct::Layout::make(deep), "depth past 16384 is refused"); + } + // Blocks hold their size in elements, and the pattern covers exactly the block's coordinates. + for (uint32_t log2 : {8u, 12u, 16u}) { + const uint32_t s = log2 == 8 ? ct::kSw256bS : log2 == 12 ? ct::kSw4kbS : ct::kSw64kbD; + for (uint32_t e = 0; e < 5; ++e) { + const auto l = ct::Layout::make(desc2d(1, 1, 1, 1u << e, s)); + check(l && (uint64_t{l->block[0]} * l->block[1] * l->block[2] << e) == (uint64_t{1} << log2), + "block holds its size in elements"); + check(l && l->pattern()[0].size() == l->block[0] && l->pattern()[1].size() == l->block[1], + "pattern covers the block"); + } + } + { + const auto l = ct::Layout::make(desc2d(64, 64, 1, 16, ct::kSw64kbD)); + check(l && l->block[0] == 64 && l->block[1] == 64 && l->block[2] == 1, "64 KiB, 16-byte elements: 64x64"); + check(l && l->size == 65536 && l->alignment == 65536, "64 KiB, 16-byte elements: one block"); + } + // Hand-checked: in a 64 KiB D block of 4-byte elements, x bits go to address bits 2, 3, 6, 9, 11, 13, 15 and y + // bits to 4, 5, 7, 8, 10, 12, 14; a 4 KiB S block of 16-byte elements is 16x16 with y first. + { + const auto l = ct::Layout::make(desc2d(128, 128, 1, 4, ct::kSw64kbD)); + check(l && offset_of(*l, 0, 1, 0, 0) == (1u << 2), "64KB_D x=1"); + check(l && offset_of(*l, 0, 4, 0, 0) == (1u << 6), "64KB_D x=4"); + check(l && offset_of(*l, 0, 0, 4, 0) == (1u << 7), "64KB_D y=4"); + check(l && offset_of(*l, 0, 0, 8, 0) == (1u << 8), "64KB_D y=8"); + check(l && offset_of(*l, 0, 64, 64, 0) == ((1u << 15) | (1u << 14)), "64KB_D (64,64)"); + const auto s = ct::Layout::make(desc2d(32, 32, 1, 16, ct::kSw4kbS)); + check(s && s->block[0] == 16 && s->block[1] == 16, "4KB_S 16-byte block is 16x16"); + check(s && offset_of(*s, 0, 0, 1, 0) == (1u << 4), "4KB_S y=1"); + check(s && offset_of(*s, 0, 1, 0, 0) == (1u << 6), "4KB_S x=1"); + check(s && offset_of(*s, 0, 16, 0, 0) == 4096, "4KB_S second block"); + check(s && offset_of(*s, 0, 0, 16, 0) == 8192, "4KB_S third block"); + } + // A 256x256 BC7 chain in 64 KiB D: one tail block holding mips 1-8, then mip 0; mip 1 sits at x = 32 elements, + // 32 KiB into the tail. 4 KiB blocks hold fewer tail mips. + { + const auto l = ct::Layout::make(desc2d(64, 64, 9, 16, ct::kSw64kbD)); + check(l && l->first_tail_mip == 1 && l->size == 2 * 65536 && l->mips[0].offset == 65536, "tail comes first"); + check(l && l->mips[1].tail && l->mips[1].tail->offset == 32768 && l->mips[1].tail->x == 32 && + l->mips[1].tail->y == 0, + "mip 1 tail position"); + check(l && offset_of(*l, 1, 0, 0, 0) == 32768, "mip 1 element 0 address"); + const auto s = ct::Layout::make(desc2d(64, 64, 9, 16, ct::kSw4kbS)); + check(s && s->first_tail_mip == 3 && s->mips[2].offset == 4096 && s->mips[1].offset == 8192 && + s->mips[0].offset == 8192 + 16384, + "4 KiB tail holds fewer mips"); + } + // Depth-stencil is two planes: 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks. + { + ct::TextureDesc t; + t.width = 1920; + t.height = 1080; + t.format = 20; + t.swizzle = ct::kSw64kbZX; + const auto tex = ct::Texture::make(t); + check(tex && tex->planes.size() == 2, "D32_FLOAT_S8X24 has two planes"); + check(tex && tex->planes[0].layout.size == 1920ull * 1152 * 4, "depth plane size"); + check(tex && tex->planes[1].offset == tex->planes[0].layout.size, "stencil follows depth"); + check(tex && tex->planes[1].layout.size == 2048ull * 1280, "stencil plane size"); + check(tex && !tex->planes[0].layout.addressable(), "XOR modes are not addressed"); + } + // Bad descriptions and buffers are refused. + { + check(!ct::Layout::make(desc2d(0, 4, 1, 4, ct::kSw4kbS)), "zero width is refused"); + check(!ct::Layout::make(desc2d(4, 4, 1, 12, ct::kSw4kbS)), "12-byte elements are refused"); + check(!ct::Layout::make(desc2d(4, 4, 1, 4, 3)), "mode 3 is refused"); + const auto l = ct::Layout::make(desc2d(64, 64, 1, 4, ct::kSw4kbS)); + std::vector out(64 * 64 * 4), small(100); + check(l && l->detile(small.data(), small.size(), 0, 0, out.data(), out.size(), 256, 0) == ct::Error::too_small, + "a short tiled buffer is too small"); + uint64_t at = 0; + check(l && l->offset(0, 64, 0, 0, at) == ct::Error::invalid, "an element outside is invalid"); + const auto lin = ct::Layout::make(desc2d(4, 2, 1, 4, ct::kLinear)); + std::vector tiled(lin ? lin->size : 0), linear(32); + check(lin && lin->detile(tiled.data(), tiled.size(), 0, 0, linear.data(), linear.size(), SIZE_MAX, 0) == + ct::Error::too_small, + "an overflowing row pitch is refused"); + auto vol = desc2d(4, 2, 1, 4, ct::kLinear); + vol.dimension = ct::Dimension::tex3d; + vol.depth = 3; + const auto v = ct::Layout::make(vol); + std::vector vt(v ? v->size : 0), vl(96); + check(v && v->detile(vt.data(), vt.size(), 0, 0, vl.data(), vl.size(), 16, SIZE_MAX) == ct::Error::too_small, + "an overflowing depth pitch is refused"); + } +} + +// Every element of every mip and slice lands on its own address inside the texture, and tiling then detiling gives +// the rows back without touching the padding around them. +void test_bijection_and_round_trip() { + std::vector cases = { + desc2d(64, 64, 7, 16, ct::kSw64kbD), desc2d(100, 60, 7, 4, ct::kSw64kbD), desc2d(250, 175, 8, 8, ct::kSw4kbS), + desc2d(33, 17, 6, 1, ct::kSw4kbD), desc2d(40, 9, 3, 2, ct::kSw64kbS), desc2d(30, 20, 5, 4, ct::kLinear), + desc2d(83, 31, 6, 1, ct::kSw256bS), + }; + auto bc = desc2d(109, 71, 6, 16, ct::kSw256bD); + bc.block = 4; + cases.push_back(bc); + auto array = desc2d(70, 70, 4, 16, ct::kSw4kbS); + array.depth = 3; + cases.push_back(array); + auto volume = desc2d(64, 32, 7, 4, ct::kSw4kbS); + volume.dimension = ct::Dimension::tex3d; + volume.depth = 16; + cases.push_back(volume); + for (const ct::Desc& d : cases) { + const auto l = ct::Layout::make(d); + if (!l) { + check(false, "round-trip case lays out"); + continue; + } + std::vector seen(static_cast(l->size)); + std::vector tiled(static_cast(l->size)); + const size_t n = d.element_bytes; + const uint32_t slices = d.dimension == ct::Dimension::tex3d ? 1 : d.depth; + bool ok = true; + for (uint32_t slice = 0; slice < slices; ++slice) { + for (uint32_t mip = 0; mip < d.mips; ++mip) { + const ct::Mip& m = l->mips[mip]; + const size_t active = size_t{m.width} * n, row = active + 13, plane = row * m.height + 11; + std::vector linear(plane * m.depth); + for (size_t i = 0; i < linear.size(); ++i) linear[i] = static_cast(i * 7 + mip * 13 + slice); + ok &= l->tile(tiled.data(), tiled.size(), mip, slice, linear.data(), linear.size(), row, plane) == + ct::Error::ok; + std::vector back(linear.size(), 0xcc); + ok &= l->detile(tiled.data(), tiled.size(), mip, slice, back.data(), back.size(), row, plane) == + ct::Error::ok; + for (uint32_t z = 0; z < m.depth; ++z) { + const size_t base = z * plane; + for (uint32_t y = 0; y < m.height; ++y) { + const size_t start = base + y * row; + ok &= std::memcmp(&back[start], &linear[start], active) == 0; + ok &= all_bytes(&back[start + active], row - active, 0xcc); + for (uint32_t x = 0; x < m.width; ++x) { + uint64_t at64 = 0; + if (l->offset(mip, x, y, slice + z, at64) != ct::Error::ok) { + ok = false; + continue; + } + const size_t at = static_cast(at64); + const size_t source = start + x * n; + if (at + n > seen.size() || at % n != 0 || seen[at]) { + ok = false; + continue; + } + ok &= std::memcmp(&tiled[at], &linear[source], n) == 0; + seen[at] = true; + } + } + ok &= all_bytes(&back[base + plane - 11], 11, 0xcc); + } + } + } + char what[96]; + std::snprintf(what, sizeof(what), "bijection and round trip: %ux%ux%u mips %u bpe %u mode %u", d.width, + d.height, d.depth, d.mips, d.element_bytes, d.swizzle); + check(ok, what); + } +} + +void test_shim(CreateFn create, SuggestFn suggest) { + // XGSuggestSwizzleMode follows the use: 4KB_S, then the XOR render and depth modes. + uint32_t mode = 0; + ResourceDesc d = rdesc(256, 256, 1, 98, 0); + check(suggest(&d, 0, &mode) == S_OK && mode == 0x105, "suggest: a sampled texture gets 4KB_S"); + d.flags = 1; + check(suggest(&d, 0, &mode) == S_OK && mode == 0x11b, "suggest: a render target gets 64KB_R_X"); + d.flags = 2; + check(suggest(&d, 0, &mode) == S_OK && mode == 0x118, "suggest: a depth target gets 64KB_Z_X"); + check(suggest(nullptr, 0, &mode) == kInvalidArg, "suggest: a null description is E_INVALIDARG"); + + // The size the device proxy answers GetResourceAllocationInfo with: 4 KiB tiles where the layout is left open. + uint64_t alignment = 0; + check(rt::xg::texture_size_fn != nullptr, "the shim offers its sizes"); + d = rdesc(128, 4, 1, 11, 0); + check(rt::xg::texture_size_fn(&d, alignment) == 0x4000 && alignment == 0x1000, "128x4 R16G16B16A16 is four 4 KiB tiles"); + d = rdesc(128, 128, 6, 71, 0); + check(rt::xg::texture_size_fn(&d, alignment) == 0x3000 && alignment == 0x1000, "128x128 BC1 with 6 mips is three"); + d = rdesc(128, 128, 6, 71, 0x109); + check(rt::xg::texture_size_fn(&d, alignment) == 0x10000 && alignment == 0x10000, "in a 64 KiB mode it is one of those"); + d = rdesc(256, 256, 1, 0, 0); + check(rt::xg::texture_size_fn(&d, alignment) == 0, "an unknown format has no size"); + + check(create(&d, nullptr) == E_POINTER, "XGCreateTextureComputer(desc, nullptr) is E_POINTER"); + + // A description with no layout still hands out a computer (two measured callers use *out without checking). + void* stub = nullptr; + const ResourceDesc bad = rdesc(256, 256, 1, 0, 0x10a); + check(create(&bad, &stub) == kInvalidArg, "an unknown format is E_INVALIDARG"); + check(stub != nullptr, "and still stores a computer for the callers that do not check"); + if (stub) { + void* const* vt = *static_cast(stub); + std::vector out(0x1b40, 0xcd); + check(reinterpret_cast(vt[2])(stub, out.data()) == kNotImpl && + all_bytes(out.data(), out.size(), 0xcd), + "that computer's slot 2 is E_NOTIMPL and writes nothing"); + reinterpret_cast(vt[1])(stub); + reinterpret_cast(vt[1])(stub); + check(reinterpret_cast(vt[2])(stub, out.data()) == kNotImpl, + "that computer stays usable after more Releases than it was handed out"); + } + + // Element offsets (slot 6): linear rows of 1 KiB (128 8-byte elements), 0 outside. + { + void* c = nullptr; + const ResourceDesc lin = rdesc(128, 4, 1, 11, 0x100); + check(create(&lin, &c) == S_OK && c, "a 128x4 R16G16B16A16 linear texture gets a computer"); + if (c) { + void* const* vt = *static_cast(c); + uint32_t bit = 7; + check(reinterpret_cast(vt[6])(c, 0, 0, 3, 1, 0, 0, &bit) == (128 + 3) * 8 && bit == 0, + "slot 6: element (3, 1) of linear rows"); + check(reinterpret_cast(vt[6])(c, 0, 0, 128, 0, 0, 0, nullptr) == 0, "slot 6: 0 outside"); + check(reinterpret_cast(vt[1])(c) == 0, "Release frees the computer"); + } + } + + // The title's calls: the layout, then a copy in and out of each mip. 256x256 BC7, full chain, 64 KiB display. + void* c = nullptr; + const ResourceDesc bc7 = rdesc(256, 256, 0, 98, 0x10a); + check(create(&bc7, &c) == S_OK && c, "a 256x256 BC7 chain gets a computer"); + if (!c) return; + void* const* vt = *static_cast(c); + std::vector buf(0x1b40); + check(reinterpret_cast(vt[2])(c, buf.data()) == S_OK, "slot 2 fills the layout"); + const auto u64 = [&](size_t at) { uint64_t v; std::memcpy(&v, &buf[at], 8); return v; }; + const auto u32 = [&](size_t at) { uint32_t v; std::memcpy(&v, &buf[at], 4); return v; }; + // LayoutOut: size 0x00, alignment 0x08, mips 0x10, planes 0x14, plane[0] at 0x18 (PlaneOut: element_bytes 0x28, + // standard 0x2c, tail 0x30, mips at 0x38, MipOut 0x70 bytes: offset 0x08, pitch_bytes 0x1c, elements 0x30, in_tail + // 0x64). + check(u64(0x00) == 131072 && u64(0x08) == 65536 && u32(0x10) == 9 && u32(0x14) == 1, "layout totals"); + const size_t plane = 0x18; + check(u32(plane + 0x2c) == 1 && u32(plane + 0x30) == 8 && u32(plane + 0x28) == 16, "plane 0 mips and elements"); + const size_t mip0 = plane + 0x38, mip1 = mip0 + 0x70; + check(u64(mip0 + 0x08) == 65536 && u32(mip0 + 0x1c) == 1024, "mip 0 offset and pitch"); + check(u64(mip1 + 0x08) == 32768 && u32(mip1 + 0x64) == 1, "mip 1 sits in the tail"); + + std::vector tiled(131072); + bool copies = true; + for (uint32_t mip = 0; mip < 9; ++mip) { + const size_t m = mip0 + mip * 0x70; + const uint32_t w = u32(m + 0x30), h = u32(m + 0x34), row = w * 16; + std::vector rows(size_t{row} * h); + for (size_t i = 0; i < rows.size(); ++i) rows[i] = static_cast(i ^ mip); + copies &= reinterpret_cast(vt[8])(c, tiled.data(), 0, mip, rows.data(), row, 0) == S_OK; + std::vector back(rows.size()); + copies &= reinterpret_cast(vt[9])(c, back.data(), 0, mip, 0, tiled.data(), row, 0) == S_OK; + copies &= back == rows; + } + check(copies, "slots 8 and 9 copy every mip in and out"); + + // Slot 10: one tile for the tail, one for mip 0. + uint32_t tiles = 0, shape[3] = {}, count = 4; + uint8_t packed[12] = {}; + uint8_t subs[4 * 12] = {}; + check(reinterpret_cast(vt[10])(c, &tiles, packed, shape, &count, 0, subs) == S_OK, "slot 10 succeeds"); + uint32_t packed_tiles = 0, first_start = 0; + std::memcpy(&packed_tiles, packed + 4, 4); + std::memcpy(&first_start, subs + 8, 4); + check(tiles == 2 && packed[0] == 1 && packed[1] == 8 && packed_tiles == 1, "slot 10 tiles and packed mips"); + check(shape[0] == 256 && shape[1] == 256 && shape[2] == 1 && count == 1 && first_start == 1, + "slot 10 shape and mip 0's tiling"); + check(reinterpret_cast(vt[1])(c) == 0, "Release frees the BC7 computer"); + + // 4 KiB modes have no 64 KiB tiling. + void* c4 = nullptr; + const ResourceDesc four = rdesc(256, 256, 0, 98, 0x105); + check(create(&four, &c4) == S_OK && c4, "a 4KB_S chain gets a computer"); + if (c4) { + void* const* v4 = *static_cast(c4); + check(reinterpret_cast(v4[10])(c4, &tiles, nullptr, nullptr, nullptr, 0, nullptr) == kFail, + "slot 10 of a 4 KiB mode is E_FAIL"); + check(reinterpret_cast(v4[31])(c4, buf.data()) == kNotImpl, "the last slot (31) is E_NOTIMPL"); + reinterpret_cast(v4[1])(c4); + } +} + } // namespace int main() { @@ -47,44 +390,9 @@ int main() { check(rt::shims::owns_dll("xg_xs.dll"), "the registry owns xg_xs.dll"); if (!create || !suggest) return 1; - uint8_t desc[0x38] = {}; - uint32_t mode = 0x1234; - check(suggest(desc, 0, &mode) == kNotImpl, "XGSuggestSwizzleMode returns E_NOTIMPL"); - check(mode == 0x1234, "XGSuggestSwizzleMode leaves the mode field as the caller set it"); - - check(create(desc, nullptr) == E_POINTER, "XGCreateTextureComputer(desc, nullptr) is E_POINTER"); - void* computer = nullptr; - check(create(desc, &computer) == kNotImpl, "XGCreateTextureComputer returns E_NOTIMPL"); - check(computer != nullptr, "XGCreateTextureComputer still stores a computer for the callers that do not check"); - if (!computer) return 1; - - void* const* vtable = *static_cast(computer); - uint8_t layout[0x800]; - std::memset(layout, 0xcd, sizeof(layout)); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, "slot 2 returns E_NOTIMPL"); - check(all_bytes(layout, sizeof(layout), 0xcd), "slot 2 writes nothing to its output"); - - uint8_t dst[64]; - std::memset(dst, 0xcd, sizeof(dst)); - const uint8_t src[64] = {}; - check(reinterpret_cast(vtable[8])(computer, dst, 0, 0, src, 16, 64) == kNotImpl, - "slot 8 returns E_NOTIMPL"); - check(all_bytes(dst, sizeof(dst), 0xcd), "slot 8 writes nothing to its destination"); - - uint32_t count = 0, inout = 0x10; - uint8_t a[12] = {}, b[12] = {}, list[0xc0] = {}; - check(reinterpret_cast(vtable[10])(computer, &count, a, b, &inout, 0, list) == kNotImpl, - "slot 10 returns E_NOTIMPL"); - check(count == 0 && inout == 0x10 && all_bytes(a, 12, 0) && all_bytes(b, 12, 0) && - all_bytes(list, sizeof(list), 0), - "slot 10 leaves the caller's zero-filled outputs as they were"); - check(reinterpret_cast(vtable[31])(computer, layout) == kNotImpl, "the last slot (31) is traced too"); - - auto release = reinterpret_cast(vtable[1]); - release(computer); - release(computer); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, - "the computer stays usable after more Releases than it was handed out"); + test_layout_model(); + test_bijection_and_round_trip(); + test_shim(create, suggest); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 3c2ce853ba..e430032a81 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -11,6 +11,7 @@ // - --fail-virtualalloc / --fail-virtualprotect / --fail-veh: the guard region's setup failing, injected by // patching this executable's own import table before the first proxy table is built (one process each). // Every device, queue, fence and resource here is a mock that records the calls it gets. No game data, no Xbox DLLs. +#include "../shims/console_texture_size.h" #include "../shims/d3d12_xs_device.h" #include @@ -1367,6 +1368,45 @@ int check_resource_allocation_info() { EXPECT(mock->calls[25] == 2 && mock->args[25][2] == 1); EXPECT(pc.SizeInBytes == 65536 && pc.Alignment == 65536); + // With the xg_xs shim in the process, textures it lays out get their console size, each at its own alignment: here + // 0x3000 at 0x1000, then 0x10000 at 0x10000. The PC device is not asked. That is for a call in the console form + // (the return buffer first), as the console sizes of render targets are; a PC-form caller keeps the PC answer. + const auto console = [&](UINT count, const D3D12_RESOURCE_DESC* list) { + return reinterpret_cast(vtable[25])(&pc, device, 1, count, word(list)); + }; + rt::xg::texture_size_fn = [](const void* desc, std::uint64_t& alignment) -> std::uint64_t { + const UINT64 width = static_cast(desc)->Width; + alignment = width == 128 ? 0x1000 : 0x10000; + return width == 128 ? 0x3000 : width == 256 ? 0x10000 : 0; + }; + D3D12_RESOURCE_DESC textures[2] = {}; + textures[0].Dimension = textures[1].Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + textures[0].Width = 128; + textures[1].Width = 256; + textures[0].Height = textures[1].Height = 1; + textures[0].DepthOrArraySize = textures[1].DepthOrArraySize = 1; + textures[1].Layout = static_cast(0x109); + EXPECT(console(1, textures) == word(&pc)); + EXPECT(mock->calls[25] == 2 && pc.SizeInBytes == 0x3000 && pc.Alignment == 0x1000); + console(2, textures); + EXPECT(mock->calls[25] == 2 && pc.SizeInBytes == 0x20000 && pc.Alignment == 0x10000); + raw(device, 25, word(&pc), 1, 1, word(textures)); // the PC form: the PC device's answer (one 64 KiB unit) + EXPECT(mock->calls[25] == 3 && pc.SizeInBytes == 65536 && pc.Alignment == 65536); + // Anything else is the PC device's to answer for the whole list (and main's console sizes of render targets after + // it): a target, depth, a buffer, another layout, a texture xg_xs cannot lay out. + for (int k = 0; k < 5; ++k) { + D3D12_RESOURCE_DESC other[2] = {textures[0], textures[1]}; + if (k == 0) other[1].Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + if (k == 1) other[1].Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + if (k == 2) other[1].Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + if (k == 3) other[1].Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (k == 4) other[1].Width = 64; + const auto asked = mock->calls[25]; + console(2, other); + EXPECT(mock->calls[25] > asked); + } + rt::xg::texture_size_fn = nullptr; + EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: device slot 25 with the buffer in RCX and the device in RDX reaches the PC method and writes " "only the struct; the PC form reaches it too\n", g_label);