feat(gpu): GPU compute detile for guest tiled textures (Vulkan + Metal) (#592)

* feat(gpu): GPU compute detile for guest tiled textures (Vulkan + Metal)

Move RDNA2 exact-XOR deswizzle (swizzle modes 5/9/24/27, 4bpp) off the CPU
onto a GPU compute pass. GnmTiling.GetDetileParams resolves the shared
addressing into DetileParams; the CPU fallback and both GPU kernels consume
the same params so they never disagree.

Vulkan (verified bit-exact on NVIDIA): SpirvFixedShaders.CreateDetileCompute
hand-emits the SPIR-V kernel; VulkanDetilePass.RecordDetile records the
dispatch into the async batch command buffer (never a blocking submit on the
render thread) with transients retired via fence; VulkanDetileSelfTest
(SHARPEMU_DETILE_SELFTEST=1) checks both entry points against the CPU detile.

Metal (Mac-untested): detile_compute.msl (detile_cs) + MetalDetilePass mirror
the Vulkan pass. The active Metal path CPU-detiles via the new
GnmTiling.DetileWithParams when a texture arrives packaged (empty RgbaPixels +
TiledSource/Detile), keeping Metal correct under default-on with no regression;
wiring MetalDetilePass live is the remaining on-device step.

Flags: GPU detile is default-on (SHARPEMU_GPU_DETILE=0 disables);
[GPU-DETILE] diagnostics gated behind SHARPEMU_LOG_GPU_DETILE=1.

Tests: 17 detile unit tests pass, incl. DetileWithParams and GetDetileParams
each matching TryDetile bit-for-bit across all supported modes/bpp, plus a
SPIR-V structural-validity test.

* feat(gpu): GPU compute detile for guest tiled textures (Vulkan + Metal)

Move RDNA2 exact-XOR deswizzle (swizzle modes 5/9/24/27, 4bpp) off the CPU
onto a GPU compute pass. GnmTiling.GetDetileParams resolves the shared
addressing into DetileParams that the CPU fallback and both GPU kernels
consume, so they never disagree; everything else keeps the CPU path.

Vulkan (verified bit-exact on NVIDIA): SpirvFixedShaders.CreateDetileCompute
hand-emits the kernel; VulkanDetilePass.RecordDetile records into the async
batch command buffer (never a blocking submit on the render thread) with
transients retired via fence, falling back to CPU detile on failure.
VulkanDetileSelfTest (SHARPEMU_DETILE_SELFTEST=1) checks both entry points.

Metal (Mac-untested): detile_compute.msl + MetalDetilePass mirror the Vulkan
pass; the active Metal path CPU-detiles via GnmTiling.DetileWithParams so it
stays correct under default-on. Wiring MetalDetilePass live is a follow-up.

Flags: default-on (SHARPEMU_GPU_DETILE=0 disables); diagnostics behind
SHARPEMU_LOG_GPU_DETILE=1. Adds 17 passing detile unit tests.

* Fix: added support layered texture support for the GPU-Detiling.

* Fix: Added support for BlockTable (1 / 4 / 8 (Morton/Z-order))

* feat: added support for 8 and 16 bpp (bytes per element)

* Fixed a build failure specific to this branch

---------
This commit is contained in:
shadowbeat070
2026-07-24 19:13:02 +02:00
committed by GitHub
parent 5228335f15
commit a158960c20
13 changed files with 2702 additions and 27 deletions
+160
View File
@@ -271,6 +271,25 @@ public static partial class AgcExports
Environment.GetEnvironmentVariable("SHARPEMU_NO_TEXTURE_SKIP"),
"1",
StringComparison.Ordinal);
// GPU deswizzle: ship raw tiled bytes + params to the backend instead of
// detiling on the CPU. On by default; SHARPEMU_GPU_DETILE=0 forces the CPU
// path. Backend-agnostic here (only inspects DetileParams); the Vulkan/Metal
// backends detile on the GPU, others fall back to the CPU path.
private static readonly bool _gpuDetileEnabled = !string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_GPU_DETILE"),
"0",
StringComparison.Ordinal);
// Diagnostics (SHARPEMU_LOG_GPU_DETILE=1): one line per distinct texture tile
// mode and per-gate decision, so we can see which swizzle modes/formats a
// title uses and whether each takes the GPU or CPU path.
private static readonly bool _gpuDetileLog = string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_LOG_GPU_DETILE"),
"1",
StringComparison.Ordinal);
private static readonly HashSet<uint> _seenTextureTileModes = new();
private static readonly HashSet<uint> _gpuDetileGateDiag = new();
private static long _dcbWriteDataTraceCount;
private static int _tracedVertexRangeCount;
private static long _dcbWaitRegMemTraceCount;
@@ -8235,6 +8254,15 @@ public static partial class AgcExports
/// enabled and the format is understood; returns null to keep the raw
/// bytes (linear surfaces, unknown modes, or non-power-of-two elements).
/// </summary>
// The GPU detile kernel implements these two equation families at 4/8/16 bpp
// (one/two/four 32-bit words per element; 1/2 bpp are sub-word and stay on the
// CPU). Keep in lockstep with VulkanDetilePass.Supports / MetalDetilePass.Supports.
private static bool IsGpuDetileEquation(DetileEquation equation) =>
equation == DetileEquation.ExactXor || equation == DetileEquation.BlockTable;
private static bool IsGpuDetileBytesPerElement(int bytesPerElement) =>
bytesPerElement is 4 or 8 or 16;
private static bool TryGetTextureElementLayout(
TextureDescriptor descriptor,
uint sourceWidth,
@@ -8411,6 +8439,20 @@ public static partial class AgcExports
return true;
}
if (_gpuDetileLog)
{
lock (_seenTextureTileModes)
{
if (_seenTextureTileModes.Add(descriptor.TileMode))
{
Console.Error.WriteLine(
$"[GPU-DETILE] texture tile_mode={descriptor.TileMode} fmt={descriptor.Format} " +
$"{descriptor.Width}x{descriptor.Height} " +
$"(0=linear; GPU covers exact-XOR 5/9/24/27 @ 4bpp).");
}
}
}
var sourceWidth = descriptor.TileMode == 0
? GetLinearTexturePitch(
Math.Max(descriptor.Width, descriptor.Pitch),
@@ -8695,6 +8737,65 @@ public static partial class AgcExports
var arrayLayers = arrayUploadLayers;
var layerBytes = checked((int)sourceSliceByteCount);
var totalBytes = (long)layerBytes * arrayLayers;
// GPU detile for arrayed exact-XOR/4bpp textures: pack the tiled array
// slices contiguously and hand them to the GPU pass (one dispatch-Z
// layer per slice), mirroring the single-layer gate above. The backend
// deswizzles every layer on the GPU; only unsupported cases fall to the
// CPU per-layer detile below. Font/text atlases uploaded as 2D arrays
// take this path.
if (_gpuDetileEnabled && hasElementLayout && !baseMipInTail &&
IsGpuDetileBytesPerElement(bytesPerElement) &&
(long)physicalSourceByteCount * arrayLayers <= int.MaxValue)
{
var gpuArrayParams = GnmTiling.GetDetileParams(
descriptor.TileMode, bytesPerElement, elementsWide, elementsHigh);
if (IsGpuDetileEquation(gpuArrayParams.Equation) &&
(long)elementsWide * elementsHigh * bytesPerElement <= (long)physicalSourceByteCount)
{
var sliceBytes = checked((int)physicalSourceByteCount);
var tiledLayers = new byte[(long)sliceBytes * arrayLayers];
var readAllLayers = true;
for (var layer = 0u; layer < arrayLayers; layer++)
{
if (!ctx.Memory.TryRead(
descriptor.Address + layer * chainSliceBytes + baseMipByteOffset,
tiledLayers.AsSpan(checked((int)(layer * (uint)sliceBytes)), sliceBytes)))
{
readAllLayers = false;
break;
}
}
if (readAllLayers)
{
texture = new GuestDrawTexture(
descriptor.Address,
descriptor.Width,
descriptor.Height,
descriptor.Format,
descriptor.NumberType,
[],
IsFallback: false,
IsStorage: false,
MipLevels: descriptor.MipLevels,
MipLevel: mipLevel,
BaseMipLevel: descriptor.ViewBaseLevel,
ResourceMipLevels: descriptor.ResourceMipLevels,
Pitch: sourceWidth,
TileMode: descriptor.TileMode,
DstSelect: descriptor.DstSelect,
Sampler: sampler,
WriteGeneration: hasWriteGeneration ? writeGeneration : -1,
ArrayedView: true,
ArrayLayers: arrayLayers,
TiledSource: tiledLayers,
Detile: gpuArrayParams);
return true;
}
}
}
if (totalBytes <= int.MaxValue)
{
var layered = new byte[totalBytes];
@@ -8792,6 +8893,65 @@ public static partial class AgcExports
}
DumpTextureSourceIfRequested(descriptor, sourceWidth, source);
if (_gpuDetileLog && descriptor.TileMode != 0)
{
lock (_gpuDetileGateDiag)
{
if (_gpuDetileGateDiag.Add(descriptor.TileMode))
{
var eq = hasElementLayout
? GnmTiling.GetDetileParams(
descriptor.TileMode, bytesPerElement, elementsWide, elementsHigh).Equation
: DetileEquation.None;
Console.Error.WriteLine(
$"[GPU-DETILE] gate mode={descriptor.TileMode} fmt={descriptor.Format} " +
$"bpp={bytesPerElement} hasLayout={hasElementLayout} mipTail={baseMipInTail} " +
$"storage={isStorage} arrayed={isArrayed} eq={eq} -> " +
$"{(hasElementLayout && !baseMipInTail && IsGpuDetileBytesPerElement(bytesPerElement) && IsGpuDetileEquation(eq) ? "GPU" : "CPU")}");
}
}
}
// GPU detile: for the 4/8/16-bytes/element base-mip case the backend can
// deswizzle on the GPU (exact-XOR and block-table equations, including
// block-compressed formats), so ship the raw tiled bytes + params rather
// than paying the CPU detile. Everything else keeps the CPU path below.
//
// Arrayed textures are handled by the arrayed branch above (they package
// every layer's tiled slice); this branch is the single-layer case.
if (_gpuDetileEnabled && hasElementLayout && !baseMipInTail &&
IsGpuDetileBytesPerElement(bytesPerElement) && !isArrayed)
{
var gpuDetileParams = GnmTiling.GetDetileParams(
descriptor.TileMode, bytesPerElement, elementsWide, elementsHigh);
if (IsGpuDetileEquation(gpuDetileParams.Equation) &&
(long)elementsWide * elementsHigh * bytesPerElement <= source.Length)
{
texture = new GuestDrawTexture(
descriptor.Address,
descriptor.Width,
descriptor.Height,
descriptor.Format,
descriptor.NumberType,
[],
IsFallback: false,
IsStorage: isStorage,
MipLevels: descriptor.MipLevels,
MipLevel: mipLevel,
BaseMipLevel: descriptor.ViewBaseLevel,
ResourceMipLevels: descriptor.ResourceMipLevels,
Pitch: sourceWidth,
TileMode: descriptor.TileMode,
DstSelect: descriptor.DstSelect,
Sampler: ToGuestSampler(samplerDescriptor),
WriteGeneration: hasWriteGeneration ? writeGeneration : -1,
ArrayedView: isArrayed,
TiledSource: source,
Detile: gpuDetileParams);
return true;
}
}
var rgba = TryDetileTextureSource(
descriptor,
sourceWidth,