feat(shader): implement image_store_pck and image_store_mip_pck

Write the raw texel bits: dmask bit i selects texel dword i, taken from the
next data register, and every other dword of the texel is written as 0; the
descriptor swizzle is ignored (measured on RDNA2 hardware). Only formats whose
bits go through the storage view unchanged are accepted (unsigned integer
components, raw 32-bit signed integer and 32-bit float); normalized, 16-bit
float, narrow signed and 96-bit formats throw.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Adrià Franch
2026-10-04 22:46:58 +02:00
parent e2ac1a6690
commit ef84d7bfa7
8 changed files with 319 additions and 11 deletions
@@ -0,0 +1,250 @@
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <span>
#include <string>
#include <vector>
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::uint32_t Threads = 32;
constexpr std::uint32_t Width = 32;
constexpr std::uint32_t Height = 8;
constexpr std::uint32_t Type2D = 9;
constexpr std::uint32_t IdentitySwizzle = 0xfacu;
constexpr std::uint32_t ReversedSwizzle = 0x977u;
constexpr std::size_t TexelBytes = 8192;
constexpr std::size_t BlockBytes = 65536;
alignas(256) constexpr std::array<std::uint32_t, 24> StoreCode{
0x4a500081, 0xd5690014, 0x0201ff28, 0x9e3779b1, 0x4a2a28ff, 0x7f4a7c15, 0x4a2c28ff, 0xfe94f82a,
0x4a2e28ff, 0x7ddf743f, 0x7e3c0300, 0x7e3e0280, 0xf0281f08, 0x0001141e, 0x7e3e0281, 0xf0281508,
0x0001141e, 0x7e3e0282, 0xf0281a08, 0x0001141e, 0x7e3e0283, 0xf0281808, 0x0001141e, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 17> MipCode{
0x4a500081, 0xd5690014, 0x0201ff28, 0x9e3779b1, 0x4a2a28ff, 0x7f4a7c15, 0x4a2c28ff, 0xfe94f82a,
0x4a2e28ff, 0x7ddf743f, 0x2c3c0081, 0x36400081, 0x34424081, 0x4c3e4284, 0xf02c1b08, 0x0001141e,
0xbf810000,
};
class GuestBlock {
public:
GuestBlock() {
#ifdef _WIN32
block = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
#else
block = static_cast<std::uint8_t*>(std::aligned_alloc(BlockBytes, BlockBytes));
#endif
Require(block != nullptr, "image store packed: cannot allocate the guest block");
GuestAllocations::Mutation().Add(block, BlockBytes, true, true);
}
~GuestBlock() {
GuestAllocations::Mutation().Remove(block);
#ifdef _WIN32
VirtualFree(block, 0, MEM_RELEASE);
#else
std::free(block);
#endif
}
GuestBlock(const GuestBlock&) = delete;
GuestBlock& operator=(const GuestBlock&) = delete;
std::uint8_t* Data() { return block; }
private:
std::uint8_t* block = nullptr;
};
struct Format {
const char* name;
std::uint32_t format;
std::uint32_t bytes;
};
constexpr std::array<Format, 10> Formats{{
{"8_UINT", 5u, 1u},
{"16_UINT", 11u, 2u},
{"8_8_UINT", 18u, 2u},
{"32_SINT", 21u, 4u},
{"32_FLOAT", 22u, 4u},
{"16_16_UINT", 27u, 4u},
{"8_8_8_8_UINT", 60u, 4u},
{"32_32_UINT", 62u, 8u},
{"16_16_16_16_UINT", 69u, 8u},
{"32_32_32_32_FLOAT", 77u, 16u},
}};
std::uint32_t Levels(bool mip) {
return mip ? 2u : 1u;
}
std::vector<AgcDriver::Graphics::TileMipLayout> Mips(const Format& format, bool mip) {
return AgcDriver::Graphics::ComputeMipLayout(AgcDriver::Graphics::TextureTileMode::kLinear, format.format, Width, Height, Levels(mip));
}
std::uint64_t TexelOffset(const AgcDriver::Graphics::TileMipLayout& mip, const Format& format, std::uint32_t x, std::uint32_t y) {
return mip.tiledOffset + static_cast<std::uint64_t>(y) * mip.pitchBytes + static_cast<std::uint64_t>(x) * format.bytes;
}
std::vector<std::uint8_t> Initial() {
std::vector<std::uint8_t> bytes(TexelBytes);
for (std::size_t index = 0; index < bytes.size(); ++index) {
bytes[index] = static_cast<std::uint8_t>(0x80u + 37u * index + 11u * (index >> 4u));
}
return bytes;
}
std::uint32_t Data(std::uint32_t tid, std::uint32_t index) {
return (tid + 1u) * 0x9e3779b1u + index * 0x7f4a7c15u;
}
void Store(std::vector<std::uint8_t>& bytes, const AgcDriver::Graphics::TileMipLayout& mip, const Format& format, std::uint32_t x, std::uint32_t y, std::uint32_t dmask, std::uint32_t tid) {
std::array<std::uint32_t, 4> words{};
std::uint32_t next = 0;
for (std::uint32_t word = 0; word < 4u; ++word) {
if (((dmask >> word) & 1u) != 0u) {
words[word] = Data(tid, next++);
}
}
std::memcpy(bytes.data() + TexelOffset(mip, format, x, y), words.data(), format.bytes);
}
std::vector<std::uint8_t> Expected(const Format& format, bool mip) {
const auto mips = Mips(format, mip);
auto bytes = Initial();
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
if (mip) {
const auto level = tid & 1u;
Store(bytes, mips[level], format, tid >> 1u, 4u - 2u * level, 0xbu, tid);
continue;
}
constexpr std::array<std::uint32_t, 4> Dmasks{0xfu, 0x5u, 0xau, 0x8u};
for (std::uint32_t row = 0; row < Dmasks.size(); ++row) {
Store(bytes, mips[0], format, tid, row, Dmasks[row], tid);
}
}
return bytes;
}
std::array<std::uint32_t, 8> TextureDescriptor(const void* data, std::uint32_t format, std::uint32_t swizzle, std::uint32_t levels) {
const auto address = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(data));
return {
static_cast<std::uint32_t>(address >> 8u),
static_cast<std::uint32_t>((address >> 40u) & 0xffu) | (format << 20u) | (((Width - 1u) & 3u) << 30u),
((Width - 1u) >> 2u) | ((Height - 1u) << 14u),
swizzle | ((levels - 1u) << 16u) | (Type2D << 28u),
0u,
(levels - 1u) << 4u,
0u,
0u,
};
}
void Run(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span<const std::uint32_t> code, const Format& format, std::uint32_t swizzle, bool mip) {
const auto mips = Mips(format, mip);
Require(AgcDriver::Graphics::ComputeSurfaceSize(mips, 1) <= TexelBytes, std::string("image store packed: the mip chain of ") + format.name + " does not fit the texel storage");
const auto initial = Initial();
std::copy(initial.begin(), initial.end(), texels);
std::vector<std::uint32_t> userData(16, 0u);
const auto texture = TextureDescriptor(texels, format.format, swizzle, Levels(mip));
std::copy(texture.begin(), texture.end(), userData.begin() + 4);
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1};
ShaderRecompiler::RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
device.Target(),
{0, 0, 0, 128}
};
request.useCache = false;
const auto result = ShaderRecompiler::Recompile(request);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
device.WaitIdle();
AgcDriver::Graphics::StorageTexture::FlushPending(reinterpret_cast<std::uintptr_t>(texels), TexelBytes, nullptr, "test");
device.WaitIdle();
}
void Check(const std::uint8_t* texels, const Format& format, bool mip, const std::string& what) {
const auto expected = Expected(format, mip);
const auto mips = Mips(format, mip);
for (std::uint32_t level = 0; level < mips.size(); ++level) {
for (std::uint32_t y = 0; y < mips[level].height; ++y) {
for (std::uint32_t x = 0; x < mips[level].width; ++x) {
const auto offset = TexelOffset(mips[level], format, x, y);
const auto chunk = std::min<std::uint32_t>(format.bytes, 4u);
for (std::uint32_t word = 0; word < format.bytes / chunk; ++word) {
std::uint32_t actual = 0;
std::uint32_t wanted = 0;
std::memcpy(&actual, texels + offset + word * chunk, chunk);
std::memcpy(&wanted, expected.data() + offset + word * chunk, chunk);
if (actual != wanted) {
char message[200];
std::snprintf(message, sizeof(message), "%s %s: level %u texel (%u, %u) dword %u is 0x%08x, expected 0x%08x", what.c_str(), format.name, level, x, y, word, actual, wanted);
Require(false, message);
}
}
}
}
}
}
void RequireRefused(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Format& format, const std::string& reason) {
std::string refusal;
try {
Run(device, texels, StoreCode, format, IdentitySwizzle, false);
} catch (const std::exception& error) {
refusal = error.what();
}
Require(refusal.find(reason) != std::string::npos, std::string("image_store_pck of ") + format.name + " was not refused: " + refusal);
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
GuestBlock block;
auto* texels = block.Data();
for (const auto& format : Formats) {
Run(*device, texels, StoreCode, format, IdentitySwizzle, false);
Check(texels, format, false, "image_store_pck");
}
Run(*device, texels, StoreCode, Formats[6], ReversedSwizzle, false);
Check(texels, Formats[6], false, "image_store_pck with a swizzled descriptor");
for (const auto& format : {Formats[6], Formats[9]}) {
Run(*device, texels, MipCode, format, IdentitySwizzle, true);
Check(texels, format, true, "image_store_mip_pck");
}
RequireRefused(*device, texels, {"8_8_8_8_UNORM", 56u, 4u}, "not reproducible");
RequireRefused(*device, texels, {"32_32_32_FLOAT", 74u, 12u}, "does not write");
std::puts("image store packed tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -160,8 +160,8 @@ DecodedImage decodeImageDescriptor(const DescriptorValue& descriptor, const Imag
throw std::runtime_error("FMASK requires a direct sampled image load");
}
if (base.packed) {
if (storage || base.indirectRoot != ImageResource::NoIndirectImage || descriptorImageSwizzle(descriptor) != ShaderImageIdentitySwizzle) {
throw std::runtime_error("packed image load requires a direct sampled image with identity swizzle");
if (base.indirectRoot != ImageResource::NoIndirectImage || (!storage && descriptorImageSwizzle(descriptor) != ShaderImageIdentitySwizzle)) {
throw std::runtime_error("packed image access requires a direct image, with identity swizzle when sampled");
}
decoded.packedFormat = format;
}
@@ -827,6 +827,8 @@ enum class RdnaOpcode : std::uint16_t {
ImageLoadMipPck,
ImageLoadMipPckSgn,
ImageStoreMip,
ImageStorePck,
ImageStoreMipPck,
ImageAtomicSwap,
ImageAtomicAdd,
ImageAtomicUmin,
@@ -103,6 +103,8 @@ constexpr ImageOpcodeInfo imageOpcodes[] = {
{0x05u, RdnaOpcode::ImageLoadMipPckSgn, nullptr, 0, false, false, false},
{0x08u, RdnaOpcode::ImageStore, nullptr, 0, false, false, false},
{0x09u, RdnaOpcode::ImageStoreMip, nullptr, 0, false, false, false},
{0x0au, RdnaOpcode::ImageStorePck, nullptr, 0, false, false, false},
{0x0bu, RdnaOpcode::ImageStoreMipPck, nullptr, 0, false, false, false},
{0x0eu, RdnaOpcode::ImageGetResinfo, nullptr, 0, false, false, false},
{0x60u, RdnaOpcode::ImageGetLod, nullptr, 0, false, false, false},
{0xe6u, RdnaOpcode::ImageBvhIntersectRay, "image_bvh_intersect_ray", 0, false, false, false},
@@ -286,7 +288,7 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span<const std
validateFlags(flags);
const auto dimension = decodeDimension((word0 >> 3u) & 7u);
const bool multisampled = dimension == RdnaImageDimension::Dim2DMsaa || dimension == RdnaImageDimension::Dim2DMsaaArray;
if (multisampled && (info.sample || info.gather || opcode == 0x60u || (opcode >= 1u && opcode <= 5u) || opcode == 9u)) {
if (multisampled && (info.sample || info.gather || opcode == 0x60u || (opcode >= 1u && opcode <= 5u) || opcode == 9u || opcode == 0x0bu)) {
throw std::runtime_error("unsupported multisampled MIMG operation");
}
const auto dmask = (word0 >> 8u) & 15u;
@@ -299,7 +301,7 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span<const std
}
const bool rayQuery = info.opcode == RdnaOpcode::ImageBvhIntersectRay;
std::uint32_t components = rayQuery ? (a16 ? 8u : 11u) : opcode == 0x0Eu ? 1u : coordinateCount(dimension);
if (opcode == 1u || opcode == 4u || opcode == 5u || opcode == 9u) {
if (opcode == 1u || opcode == 4u || opcode == 5u || opcode == 9u || opcode == 0x0bu) {
++components;
}
if (info.sample || info.gather) {
@@ -763,6 +763,8 @@ bool IsImageOpcode(RdnaOpcode opcode) {
case RdnaOpcode::ImageLoadMipPck:
case RdnaOpcode::ImageLoadMipPckSgn:
case RdnaOpcode::ImageStoreMip:
case RdnaOpcode::ImageStorePck:
case RdnaOpcode::ImageStoreMipPck:
case RdnaOpcode::ImageAtomicSwap:
case RdnaOpcode::ImageAtomicAdd:
case RdnaOpcode::ImageAtomicUmin:
@@ -448,18 +448,26 @@ std::uint32_t UnpackImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess
return result;
}
std::uint32_t PackedImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t texel) {
auto& state = ctx.state;
SpirvBufferFormatInfo PackedTexelFormat(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) {
const auto format = access.image.packedFormat;
if (format == IrBufferFormat::Invalid || access.table.mapped != 0 || access.image.depthBits || access.image.conversionFormat != IrBufferFormat::Invalid) {
ctx.Fail(access.inst, "reads packed texels from an image without a packed format");
ctx.Fail(access.inst, "accesses packed texels of an image without a packed format");
}
const auto info = GetFormatInfo(format);
if (info.packedBitfield) {
ctx.Fail(access.inst, "accesses packed texels of a bitfield format");
}
return info;
}
std::uint32_t PackedImageTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t texel) {
auto& state = ctx.state;
const auto info = PackedTexelFormat(ctx, access);
std::uint32_t texelBits = 0;
for (std::uint32_t component = 0; component < info.componentCount; component++) {
const auto bits = info.componentBits[component];
const bool exact = info.type == SpirvFormatComponentType::Uint || info.type == SpirvFormatComponentType::Sint || (info.type == SpirvFormatComponentType::Unorm && bits <= 16u) || (info.type == SpirvFormatComponentType::Float && bits == 32u);
if (info.packedBitfield || !exact) {
if (!exact) {
ctx.Fail(access.inst, "reads packed texels of a format whose bits are not recoverable from the view");
}
texelBits += bits;
@@ -599,6 +607,48 @@ std::uint32_t StoreTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& acce
return PackImageTexel(ctx, access, texel);
}
std::uint32_t PackedStoreTexel(SpirvValueEmitContext& ctx, const ImageEmitAccess& access, std::uint32_t data) {
auto& state = ctx.state;
const auto info = PackedTexelFormat(ctx, access);
const auto numericClass = access.image.numericClass;
if (info.byteSize == 12u) {
ctx.Fail(access.inst, "stores packed texels of a format the hardware does not write");
}
std::uint32_t words[4] = {};
for (std::uint32_t word = 0; word < 4u; word++) {
if (((access.mem.dmask >> word) & 1u) == 0u) {
words[word] = ConstantU32(state, 0u);
continue;
}
words[word] = state.module.AllocateId();
state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), words[word], data, DmaskComponentIndex(access.mem.dmask, word));
}
std::uint32_t values[4] = {};
for (std::uint32_t component = 0; component < 4u; component++) {
if (component >= info.componentCount) {
values[component] = numericClass == IrTextureNumericClass::Float ? ZeroF32(state) : ConstantU32(state, 0u);
continue;
}
const auto bits = info.componentBits[component];
const auto offset = info.componentBitOffset[component];
const bool exact = (info.type == SpirvFormatComponentType::Uint && numericClass == IrTextureNumericClass::Uint) || (bits == 32u && ((info.type == SpirvFormatComponentType::Sint && numericClass == IrTextureNumericClass::Uint) || (info.type == SpirvFormatComponentType::Float && numericClass == IrTextureNumericClass::Float)));
if (!exact || offset % 32u + bits > 32u) {
ctx.Fail(access.inst, "stores packed texels of a format whose bits are not reproducible through the view");
}
auto value = words[offset / 32u];
if (offset % 32u != 0u) {
value = Binary(state, spv::OpShiftRightLogical, TypeU32(state), value, ConstantU32(state, offset % 32u));
}
if (bits < 32u) {
value = Binary(state, spv::OpBitwiseAnd, TypeU32(state), value, ConstantU32(state, (1u << bits) - 1u));
}
values[component] = numericClass == IrTextureNumericClass::Float ? Unary(state, spv::OpBitcast, TypeF32(state), value) : value;
}
const auto texel = state.module.AllocateId();
state.module.AddFunction(spv::OpCompositeConstruct, numericClass == IrTextureNumericClass::Float ? TypeF32Vector(state, 4) : TypeU32Vector(state, 4), texel, values[0], values[1], values[2], values[3]);
return texel;
}
std::uint32_t ImageAtomicOpcode(IrOpcode opcode) {
switch (opcode) {
case IrOpcode::ImageAtomicSwap32:
@@ -686,7 +736,7 @@ void EmitWriteOp(SpirvValueEmitContext& ctx, const ImageEmitAccess& access) {
EmitIfCondition(state, ctx.Arg(access.inst, 3), [&]() {
const auto mipLod = access.image.mipMode == ImageMipMode::DynamicStorage ? LodU32(ctx, access) : 0u;
const auto coord = CoordU32(ctx, access);
const auto texel = StoreTexel(ctx, access, ctx.Arg(access.inst, 2), uintImage);
const auto texel = access.mem.imagePacked ? PackedStoreTexel(ctx, access, ctx.Arg(access.inst, 2)) : StoreTexel(ctx, access, ctx.Arg(access.inst, 2), uintImage);
EmitStorageImageWrite(state, access.mem.resource, mipLod, coord, texel);
});
}
@@ -34,8 +34,8 @@ MemoryInfo imageMemoryInfoFromInstruction(const RdnaInstruction& inst) {
memory.imageSampleFlags = inst.imageSampleFlags;
memory.imageDimension = inst.imageDimension;
memory.imageAddressComponents = inst.imageAddressComponents;
memory.imageHasMip = inst.op == RdnaOpcode::ImageLoadMip || inst.op == RdnaOpcode::ImageStoreMip || inst.op == RdnaOpcode::ImageLoadMipPck || inst.op == RdnaOpcode::ImageLoadMipPckSgn;
memory.imagePacked = inst.op == RdnaOpcode::ImageLoadPck || inst.op == RdnaOpcode::ImageLoadPckSgn || inst.op == RdnaOpcode::ImageLoadMipPck || inst.op == RdnaOpcode::ImageLoadMipPckSgn;
memory.imageHasMip = inst.op == RdnaOpcode::ImageLoadMip || inst.op == RdnaOpcode::ImageStoreMip || inst.op == RdnaOpcode::ImageLoadMipPck || inst.op == RdnaOpcode::ImageLoadMipPckSgn || inst.op == RdnaOpcode::ImageStoreMipPck;
memory.imagePacked = inst.op == RdnaOpcode::ImageLoadPck || inst.op == RdnaOpcode::ImageLoadPckSgn || inst.op == RdnaOpcode::ImageLoadMipPck || inst.op == RdnaOpcode::ImageLoadMipPckSgn || inst.op == RdnaOpcode::ImageStorePck || inst.op == RdnaOpcode::ImageStoreMipPck;
memory.dataSigned = inst.op == RdnaOpcode::ImageLoadPckSgn || inst.op == RdnaOpcode::ImageLoadMipPckSgn;
memory.imageR128 = inst.imageR128;
return memory;
@@ -382,6 +382,8 @@ bool TranslationContext::emitMemory(const RdnaInstruction& inst) {
return imageLoad(inst);
case RdnaOpcode::ImageStore:
case RdnaOpcode::ImageStoreMip:
case RdnaOpcode::ImageStorePck:
case RdnaOpcode::ImageStoreMipPck:
return imageStore(inst);
case RdnaOpcode::ImageGetResinfo:
return imageGetResinfo(inst);