diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index b57999a1cf17..2d238267d917 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -76,6 +76,17 @@ add_custom_command( DEPENDS "${agcTextureDetileShaderSource}" glslang-standalone VERBATIM ) +set(agcTextureDetileChangedShaderSpv ${agcTextureDetileGeneratedDir}/TextureDetileChanged.spv) +set(agcTextureDetileChangedShaderHeader ${agcTextureDetileGeneratedDir}/TextureDetileChanged_spv.h) +add_custom_command( + OUTPUT "${agcTextureDetileChangedShaderHeader}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}" + COMMAND "$" -V --target-env vulkan1.1 -DBYTE_OUTPUT=1 -o "${agcTextureDetileChangedShaderSpv}" "${agcTextureDetileShaderSource}" + COMMAND ${CMAKE_COMMAND} -DINPUT=${agcTextureDetileChangedShaderSpv} -DOUTPUT=${agcTextureDetileChangedShaderHeader} + -DSYMBOL=TEXTURE_DETILE_CHANGED_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake" + DEPENDS "${agcTextureDetileShaderSource}" glslang-standalone + VERBATIM +) set(agcTextureDetileImageShaderSpv ${agcTextureDetileGeneratedDir}/TextureDetileImage.spv) set(agcTextureDetileImageShaderHeader ${agcTextureDetileGeneratedDir}/TextureDetileImage_spv.h) add_custom_command( @@ -494,6 +505,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Sampler.cpp ${agcSampleOrderShaderHeaders} ${agcTextureDetileShaderHeader} + ${agcTextureDetileChangedShaderHeader} ${agcReadbackHeaders} ${agcMultisampleUploadHeader} ${agcMultisampleUploadFragHeader} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index 6a22508c58d3..eac1a3665de5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -27,6 +27,7 @@ namespace AgcDriver::Graphics { class Buffer; +class DeviceBuffer; class ResidentColor; class CommandBatch; class StorageTexture; @@ -315,6 +316,8 @@ class StorageTexture : public std::enable_shared_from_this { VkImageView AttachmentProxyView(); void RecordAttachmentProxyLoad(VkCommandBuffer commands, VkImageLayout attachmentLayout) const; void RecordAttachmentProxyStore(VkCommandBuffer commands, VkImageLayout attachmentLayout) const; + void PrepareLinearDraw(); + void FinishLinearDraw(); void WriteBack(); // Deferred write-back (APS5_EAGER_WRITEBACK=1 stores at once instead). void MarkDirty(); @@ -966,6 +969,7 @@ class StorageTexture : public std::enable_shared_from_this { std::vector layerOriginal; std::map keptAtUnwatch; std::shared_ptr savedBytes; + std::shared_ptr linearDrawOriginal; std::vector savedTicket; std::uint64_t lastSaveTicket = 0; std::vector baselineDue; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index 7f571bfea0a2..0d5213ed94ea 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -50,7 +50,7 @@ namespace AgcDriver::Graphics { // into tiled `destination`; offsets always refer to the respective buffers, and `window` // restricts the move to part of the mip (a partial upload or write-back, StorageTexture), // leaving the other elements of both buffers alone. - void Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, bool thick = false, const DetileWindow& window = {}); + void Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, bool thick = false, const DetileWindow& window = {}, std::uint64_t originalOffset = 0); void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {}); void DispatchRepack(VkCommandBuffer commands, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, std::uint64_t bytes, bool depthToFloat = false); static VkFormat ImageElementFormat(std::uint32_t elementBytes); @@ -64,7 +64,7 @@ namespace AgcDriver::Graphics { private: VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth); VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes); - VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false); + VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, bool changedOnly = false); void release() noexcept; struct DescriptorRing { std::vector pools; @@ -81,6 +81,7 @@ namespace AgcDriver::Graphics { VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkShaderModule module = VK_NULL_HANDLE; + VkShaderModule changedModule = VK_NULL_HANDLE; std::vector> pipelines; std::vector> gcnGeometries; std::uint32_t layerBankXor(TextureTileMode tileMode, std::uint32_t elementBytes, const TileMipLayout& layout, std::uint32_t layer); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp index 6c8e6b6a7821..1ff6ff09b741 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp +++ b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp @@ -1,4 +1,7 @@ #version 450 +#ifdef BYTE_OUTPUT +#extension GL_EXT_shader_8bit_storage : require +#endif #ifdef LINEAR_IMAGE #extension GL_EXT_shader_image_load_formatted : require #endif @@ -33,6 +36,7 @@ layout(constant_id = 22) const uint SPLIT0 = 0u; layout(constant_id = 23) const uint SPLIT1 = 0u; layout(constant_id = 24) const uint SPLIT2 = 0u; layout(constant_id = 25) const uint SPLIT3 = 0u; +layout(constant_id = 26) const uint CHANGED_ONLY = 0u; layout(local_size_x = 8, local_size_y = 8) in; @@ -41,8 +45,13 @@ layout(set = 0, binding = 0, std430) buffer Tiled { uint data[]; } tiledBuffer; layout(set = 0, binding = 1) uniform uimage2D linearImage; #else layout(set = 0, binding = 0, std430) readonly buffer Input { uint data[]; } inputBuffer; +#ifdef BYTE_OUTPUT +layout(set = 0, binding = 1, std430) writeonly buffer Output { uint8_t data[]; } outputBuffer; +#else layout(set = 0, binding = 1, std430) buffer Output { uint data[]; } outputBuffer; #endif +layout(set = 0, binding = 2, std430) readonly buffer Original { uint data[]; } originalBuffer; +#endif layout(push_constant) uniform Push { uint srcBase; @@ -69,6 +78,7 @@ layout(push_constant) uniform Push { uint rowBegin; uint pipeBankXor; uint splitStride; + uint originalBase; } params; uint equationBit(uint mask, uvec2 p) { @@ -193,6 +203,16 @@ void loadElement(uvec2 p, uint dst) { } #else void copyElement(uint src, uint dst) { +#ifdef BYTE_OUTPUT + const uint original = params.originalBase + src - params.srcBase; + for (uint offset = 0u; offset < ELEMENT_BYTES; ++offset) { + const uint currentAddress = src + offset; + const uint originalAddress = original + offset; + const uint current = (inputBuffer.data[currentAddress >> 2] >> ((currentAddress & 3u) * 8u)) & 0xffu; + const uint before = (originalBuffer.data[originalAddress >> 2] >> ((originalAddress & 3u) * 8u)) & 0xffu; + if (current != before) outputBuffer.data[dst + offset] = uint8_t(current); + } +#else if (ELEMENT_BYTES >= 4u) { for (uint i = 0u; i < ELEMENT_BYTES; i += 4u) { outputBuffer.data[(dst + i) >> 2] = inputBuffer.data[(src + i) >> 2]; @@ -204,6 +224,7 @@ void copyElement(uint src, uint dst) { atomicAnd(outputBuffer.data[dst >> 2], ~(mask << shift)); atomicOr(outputBuffer.data[dst >> 2], value << shift); } +#endif } #endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 3cd25e3d4ec0..380210531fdf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2720,7 +2720,7 @@ void keepRecordedDraw(Recorder& recorder, const std::shared_ptr else residents[index]->MarkDirty(); } for (std::size_t index = 0; index < residents.size(); ++index) { - if (storeNow[index]) StorageTexture::FlushPending(residents[index]->Descriptor().baseAddress, static_cast(residents[index]->GuestBytes()), nullptr, "linear target"); + if (storeNow[index]) residents[index]->FinishLinearDraw(); } } @@ -3031,6 +3031,9 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam const bool fenced = state.depth.has_value() || !record.proxies.empty(); resources.RequireGuestBuffers(); if (UsesMeshWindow(shaders)) PrepareMeshWindow(context); + for (const auto& target : record.targets) { + if (target != nullptr) target->PrepareLinearDraw(); + } const auto start = recorder->StartDrawPass(passKey, inputs.indexInputBehindGpuWrite || capture || readsTarget || gpuIndirect || meshIndirect || captured || !record.staged.empty() || PixelFunctionLdsSubgroup(shaders) != 0u, fenced, passAccess); if (record.spaceKeep != nullptr) *record.spaceKeep = reserveSpaceKeep(*recorder, resources); for (const auto& target : record.multisampleTargets) KeepMultisampleTarget_nid_no_patch(target); @@ -4558,6 +4561,11 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D if (recorded && recorder->HasQueuedKeyStores() && (resources->HoldsLease() || recorder->AnyQueuedKeyStore(touches))) recorder->FlushKeyStores(); // A queued label store over such memory likewise (Recorder::RecordStore). if (recorded && recorder->HasQueuedStores() && (resources->HoldsLease() || recorder->AnyQueuedStore(touches))) recorder->FlushStores(); + if (recorded) { + for (const auto& binding : targets) { + if (binding.resident != nullptr) binding.resident->PrepareLinearDraw(); + } + } const auto commands = recorded ? recorder->Commands() : batch->Handle(); if (recorded) prepared.spaceKeep = reserveSpaceKeep(*recorder, *resources); std::optional batchRecording; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index b39d797f18d2..b98c477a37d8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -7695,7 +7695,51 @@ bool StorageTexture::cpuLeftUnchanged(std::uint32_t layer, std::uint64_t from, s return cpu[0] == 0; } +void StorageTexture::PrepareLinearDraw() { + if (descriptor.tileMode != TextureTileMode::kLinear) return; + WriteBack(); + FlushPending(descriptor.baseAddress, static_cast(guestBytes), this, "linear draw baseline"); + linearDrawOriginal.reset(); + uploadReason = "linear draw baseline"; + Refresh(); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr, "a recorded linear target needs an active recorder"); + const auto bytes = sliceLinearBytes * arrayLayers; + Require(bytes <= std::numeric_limits::max() / 2, "a linear target snapshot exceeds addressable memory"); + auto snapshot = std::make_shared(context, static_cast(bytes * 2), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + auto regions = CopyRegions(); + for (auto& region : regions) region.bufferOffset += bytes; + recorder->Keep(snapshot); + recorder->KeepBytes(snapshot.get(), snapshot->Size()); + const auto commands = recorder->Commands(); + VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; + barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, descriptor.mipCount, 0, geometry.imageLayers}; + context.Function("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); + context.Function("vkCmdCopyImageToBuffer")(commands, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, snapshot->Handle(), static_cast(regions.size()), regions.data()); + barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; + context.Function("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); + Recorder::CountBarriers(Recorder::CommandClass::Draw, 2); + linearDrawOriginal = std::move(snapshot); +} + +void StorageTexture::FinishLinearDraw() { + if (descriptor.tileMode != TextureTileMode::kLinear) return; + FlushPending(descriptor.baseAddress, static_cast(guestBytes), nullptr, "linear target"); + if (!anyLayerPending()) linearDrawOriginal.reset(); +} + void StorageTexture::writeBackLayers(const std::vector& layers) { + const auto drawOriginal = linearDrawOriginal; CaptureTrace::Log("writeback image=%llx generation=%llu reason=%s units=%zu", static_cast(descriptor.baseAddress), static_cast(generation), flushReason, static_cast(std::count(layers.begin(), layers.end(), true))); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; PhaseTimer timer; @@ -7746,6 +7790,7 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { for (auto at = layerBegin(layer) & ~(block - 1); at < end; at += block) generations[static_cast((at - spanBegin) / block)] = unitBlockGeneration(layer, at); } const auto drawn = drawnArea(); + const bool rectStore = drawn.rect && drawOriginal == nullptr; std::vector changedBlocks(spanBlocks); std::vector cpuBlocks(drawn.drawn ? spanBlocks : 0); const bool tracked = GuestMemory::ChangedBlocks(firstStored, static_cast(lastStored - firstStored), generations, changedBlocks, cpuBlocks); @@ -7790,8 +7835,15 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { const auto begin = layerBegin(layer); const auto end = begin + layerBytes(layer); const bool layerTracked = unitTracked.empty() ? tracked : unitTracked[layer]; + if (drawOriginal != nullptr) { + for (auto at = begin & ~(block - 1); at < end; at += block) { + if (changedBlocks[static_cast((at - spanBegin) / block)] == GuestMemory::BlockWritten) skippedLayer[layer] = true; + } + keep.emplace_back(begin, end); + continue; + } const bool unknown = layerTracked ? layerGeneration[layer] == 0 : !compared[layer]; - if (unknown && !drawn.rect) { + if (unknown && !rectStore) { if (!layerTracked && !unsavedOutsideWatch) unsavedCause = std::string("storing storage image results pending over memory outside the write watch without the guest bytes saved before them is not implemented (unit ") + std::to_string(layer) + " of " + std::to_string(trackedLayers) + ": " + BaselineMissText(pendingMiss[layer]) + ")"; unsavedOutsideWatch = unsavedOutsideWatch || !layerTracked; keep.emplace_back(begin, end); @@ -7805,14 +7857,14 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { const auto index = static_cast((at - spanBegin) / block); const bool kept = keptAtUnwatchHolds(from, layer); const bool written = kept || unknown || (changedBlocks[index] == GuestMemory::BlockWritten && (compared[layer] || !edge || GuestMemory::StoredOver(from, static_cast(to - from), unitBlockGeneration(layer, at))) && !cpuLeftUnchanged(layer, from, to, edge)); - if (written && (!drawn.rect || (layerTracked && !kept && !unknown && cpuBlocks[index] == 0))) { + if (written && (!rectStore || (layerTracked && !kept && !unknown && cpuBlocks[index] == 0))) { skippedAny = true; skippedLayer[layer] = true; keptBlocks.emplace_back(from, layer); ++skipped; continue; } - if (written && drawn.rect) skippedLayer[layer] = true; + if (written && rectStore) skippedLayer[layer] = true; if (!keep.empty() && keep.back().second == from) keep.back().second = to; else keep.emplace_back(from, to); } @@ -7828,10 +7880,10 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { std::fprintf(stderr, "[flush] image 0x%llx+0x%llx keeps %zu CPU-written 64 KiB blocks (first stored byte at +0x%llx, %zu ranges stored, generation %llu)\n", static_cast(descriptor.baseAddress), static_cast(guestBytes), skipped, static_cast(first - descriptor.baseAddress), keep.size(), static_cast(generation)); } std::vector> spans; - if (drawn.rect) spans = drawnSpans(drawn, keep); - const auto& stores = drawn.rect ? spans : keep; - const auto stampBegin = drawn.rect && !stores.empty() ? stores.front().first : firstStored; - const auto stampEnd = drawn.rect && !stores.empty() ? stores.back().second : lastStored; + if (rectStore) spans = drawnSpans(drawn, keep); + const auto& stores = rectStore ? spans : keep; + const auto stampBegin = rectStore && !stores.empty() ? stores.front().first : firstStored; + const auto stampEnd = rectStore && !stores.empty() ? stores.back().second : lastStored; // Taken before this write-back stamps anything (see advanceAdjacent), with the 64 KiB block span // its stamps cover. const auto firstBlock = stampBegin / block; @@ -7912,7 +7964,7 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { ++Profile().storageDirectWriteBacks; return; } - if (drawn.rect) { + if (rectStore) { PublishShadow(stampBegin, static_cast(stampEnd - stampBegin), PublishScope::PartialUnits, PublishReason::Upload); const auto storedBytes = storeDrawnRect(drawn, segments, stores, saveUnits); countStorageWriteBack(storedBytes, true, true); @@ -7933,11 +7985,11 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { // The whole-layer copies below overwrite the interior units of the span; the edge units // keep a neighbour's shadowed results in the rest of their bytes, which reach the import // first (this write-back's stamps then make those units stale). - PublishShadow(firstStored, static_cast(lastStored - firstStored), PublishScope::PartialUnits, PublishReason::Upload); + PublishShadow(firstStored, static_cast(lastStored - firstStored), drawOriginal != nullptr ? PublishScope::Whole : PublishScope::PartialUnits, PublishReason::Upload); // The surface lives in host-imported memory: the retiler writes into device scratch and the // untouched blocks are copied into the imported bytes in place, recorded behind the work that // produced the image; nothing crosses to the CPU. - auto linear = std::make_shared(context, static_cast(sliceLinearBytes * arrayLayers), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); + auto linear = drawOriginal != nullptr ? drawOriginal : std::make_shared(context, static_cast(sliceLinearBytes * arrayLayers), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); std::vector copied; for (const auto& [from, to] : keep) copied.push_back({from - descriptor.baseAddress, to - descriptor.baseAddress, from - descriptor.baseAddress}); auto padding = paddingSeeds(segments, copied); @@ -7952,7 +8004,7 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { for (const auto& [begin, end] : coveredBytes(runs)) importStores.emplace_back(descriptor.baseAddress + begin, descriptor.baseAddress + end); padding = {}; static const bool importRetile = std::getenv("APS5_NO_LINEAR_IMPORT_RETILE") == nullptr; - if (importRetile && !geometry.levelMajor && elementBytes % 4 == 0 && segments.size() == 1 && segments.front().begin <= firstStored && lastStored <= segments.front().end) { + if (importRetile && drawOriginal == nullptr && !geometry.levelMajor && elementBytes % 4 == 0 && segments.size() == 1 && segments.front().begin <= firstStored && lastStored <= segments.front().end) { std::vector> wholeLayers; for (std::uint32_t layer = 0; layer < trackedLayers; ++layer) { if (!layers[layer]) continue; @@ -7983,7 +8035,10 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { recorder->FlushStoresOverlapping(firstStored, static_cast(lastStored - firstStored)); commands = recorder->Commands(); timing = recorder->BeginGpuTiming(Recorder::CommandClass::StorageWriteBack); - if (linear) recorder->Keep(linear, linear->Size()); + if (linear) { + recorder->Keep(linear, drawOriginal != nullptr ? 0 : linear->Size()); + if (drawOriginal != nullptr) recorder->KeepBytes(linear.get(), linear->Size()); + } if (tiledScratch) recorder->Keep(tiledScratch, tiledScratch->Size()); for (const auto& slab : padding.slabs) recorder->Keep(slab); // The image itself must outlive the recorded retile: the cache may evict it right after. @@ -8031,7 +8086,21 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { if (!geometry.HasLayer(level, layer)) continue; const auto& mip = mips[level]; if (directImport != nullptr) detiler.Dispatch(commands, descriptor.tileMode, elementBytes, linear->Handle(), geometry.LinearLayerOffset(layer) + mip.linearOffset, directImport->buffer, HostImportOffset(*directImport, descriptor.baseAddress + geometry.GuestOffset(layer, mip)), mip, true, layer, geometry.thick, {.pipeBankXor = descriptor.pipeBankXor}); - else detiler.Dispatch(commands, descriptor.tileMode, elementBytes, linear->Handle(), geometry.LinearLayerOffset(layer) + mip.linearOffset, tiledScratch->Handle(), geometry.GuestOffset(layer, mip), mip, true, layer, geometry.thick, {.pipeBankXor = descriptor.pipeBankXor}); + else { + detiler.Dispatch(commands, descriptor.tileMode, elementBytes, linear->Handle(), geometry.LinearLayerOffset(layer) + mip.linearOffset, tiledScratch->Handle(), geometry.GuestOffset(layer, mip), mip, true, layer, geometry.thick, {.pipeBankXor = descriptor.pipeBankXor}); + if (drawOriginal != nullptr) { + const auto address = descriptor.baseAddress + geometry.GuestLayerOffset(layer) + mip.tiledOffset; + const auto offset = geometry.LinearLayerOffset(layer) + mip.linearOffset; + for (const auto& segment : segments) { + const auto begin = std::max(address, segment.begin); + const auto end = std::min(address + mip.tiledSize, segment.end); + if (begin >= end) continue; + Require(end - address <= UINT32_MAX, "a linear target write-back exceeds addressable shader offsets"); + detiler.Dispatch(commands, descriptor.tileMode, elementBytes, linear->Handle(), offset, segment.import->buffer, HostImportOffset(*segment.import, begin), mip, true, layer, false, + {.rangeBegin = static_cast(begin - address), .rangeEnd = static_cast(end - address), .tiledBase = static_cast(begin - address)}, sliceLinearBytes * arrayLayers + offset); + } + } + } } } if (directImport != nullptr) { @@ -8046,7 +8115,7 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { const auto end = std::min(to, segment.end); if (begin < end) copies.push_back({begin - descriptor.baseAddress, HostImportOffset(*segment.import, begin), end - begin}); } - if (!copies.empty()) context.Function("vkCmdCopyBuffer")(commands, tiledScratch->Handle(), segment.import->buffer, static_cast(copies.size()), copies.data()); + if (drawOriginal == nullptr && !copies.empty()) context.Function("vkCmdCopyBuffer")(commands, tiledScratch->Handle(), segment.import->buffer, static_cast(copies.size()), copies.data()); } if (!saveUnits.empty()) { std::vector saves; @@ -8132,7 +8201,7 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { std::vector unsaved = layerOriginal; unsaved.flip(); for (const auto& [begin, end] : unitRuns(unsaved)) { - if (drawn.rect) { + if (rectStore) { GuestMemory::ReadCommitted(descriptor.baseAddress + begin, std::span(original).subspan(static_cast(begin), static_cast(end - begin))); continue; } @@ -8145,6 +8214,8 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { DeviceBuffer linear(context, static_cast(sliceLinearBytes * arrayLayers), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); DeviceBuffer tiled(context, original.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); Buffer host(context, original.size(), VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); + std::unique_ptr drawBefore; + if (drawOriginal != nullptr) drawBefore = std::make_unique(context, static_cast(sliceLinearBytes * arrayLayers), VK_BUFFER_USAGE_TRANSFER_DST_BIT); if (profile) Profile().storageAlloc += timer.lap(); // Start from the uploaded bytes so padding and untouched texels keep their guest values. std::memcpy(host.Bytes().data(), original.data(), original.size()); @@ -8152,6 +8223,10 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { detiler.BeginBatch(); CommandBatch batch(context); const auto commands = batch.Handle(); + if (drawBefore != nullptr) { + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); + CopyBuffer(context, commands, drawOriginal->Handle(), sliceLinearBytes * arrayLayers, drawBefore->Handle(), 0, drawBefore->Bytes().size()); + } RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); CopyBuffer(context, commands, host.Handle(), 0, tiled.Handle(), 0, original.size()); VkImageMemoryBarrier toSource{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; @@ -8199,7 +8274,7 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { APS5_LOG_CHARS_OUT_DEBUG("StorageTexture writeback done"); std::uint64_t storedBytes = 0; for (const auto& [from, to] : stores) storedBytes += to - from; - countStorageWriteBack(drawn.rect ? storedBytes : guestBytes, false, drawn.drawn); + countStorageWriteBack(rectStore ? storedBytes : guestBytes, false, drawn.drawn); if (profile) Profile().storageGpu += timer.lap(); if (dump) { char name[64]; @@ -8213,6 +8288,18 @@ void StorageTexture::writeBackLayers(const std::vector& layers) { } // Store only the kept ranges' blocks that changed, so concurrent CPU writes to untouched texels // survive; `original` follows for the stored layers (the others' guest bytes are unchanged). + if (drawBefore != nullptr) { + const auto before = drawBefore->Bytes(); + for (std::uint32_t layer = 0; layer < arrayLayers; ++layer) { + for (std::uint32_t level = 0; level < mips.size(); ++level) { + if (!geometry.HasLayer(level, layer)) continue; + const auto& mip = mips[level]; + for (const auto& [begin, end] : CoveredMipBytes(TextureTileMode::kLinear, elementBytes, mip)) { + std::memcpy(original.data() + geometry.GuestLayerOffset(layer) + mip.tiledOffset + begin, before.data() + geometry.LinearLayerOffset(layer) + mip.linearOffset + begin, static_cast(end - begin)); + } + } + } + } const auto current = host.Bytes(); for (const auto& [from, to] : stores) { const auto offset = static_cast(from - descriptor.baseAddress); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 0ee6c619587e..7b1be06367f8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Graphics/include/TextureSwizzleEquations.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/TextureDetile_spv.h" +#include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileChanged_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/CmaskClear_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileImage_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/TextureRepack_spv.h" @@ -40,6 +41,7 @@ struct Push { std::uint32_t rowBegin; std::uint32_t pipeBankXor; std::uint32_t splitStride; + std::uint32_t originalBase; }; std::uint32_t BlockBytesFor(TextureTileMode tileMode) { @@ -63,15 +65,15 @@ std::uint32_t BlockBytesFor(TextureTileMode tileMode) { throw std::runtime_error("AGC graphics: TextureDetiler encountered an unknown tile mode"); } -std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image) { - return (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; +std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool changedOnly) { + return (changedOnly ? 1u << 19 : 0u) | (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; } } TextureDetiler::TextureDetiler(const Context& context) : context(context) { try { - std::array bindings{}; + std::array bindings{}; for (std::uint32_t index = 0; index < bindings.size(); ++index) { bindings[index].binding = index; bindings[index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; @@ -94,6 +96,7 @@ TextureDetiler::TextureDetiler(const Context& context) : context(context) { Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &pipelineLayout), "vkCreatePipelineLayout"); module = CreateShaderModule(context, TEXTURE_DETILE_SPV, sizeof(TEXTURE_DETILE_SPV), "vkCreateShaderModule"); bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + layoutInfo.bindingCount = 2; Check(context.Function("vkCreateDescriptorSetLayout")(context.device, &layoutInfo, nullptr, &imageDescriptorLayout), "vkCreateDescriptorSetLayout"); pipelineLayoutInfo.pSetLayouts = &imageDescriptorLayout; Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &imagePipelineLayout), "vkCreatePipelineLayout"); @@ -129,6 +132,7 @@ void TextureDetiler::release() noexcept { if (imagePipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, imagePipelineLayout, nullptr); if (imageDescriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, imageDescriptorLayout, nullptr); for (const auto& entry : pipelines) context.Function("vkDestroyPipeline")(context.device, entry.second, nullptr); + if (changedModule) context.Function("vkDestroyShaderModule")(context.device, changedModule, nullptr); if (module) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); if (pipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr); if (descriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, descriptorLayout, nullptr); @@ -145,16 +149,17 @@ VkFormat TextureDetiler::ImageElementFormat(std::uint32_t elementBytes) { } } -VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image) { +VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool changedOnly) { Require(std::has_single_bit(elementBytes) && elementBytes <= 16u, "unsupported element size for texture detiling"); - const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image); + const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image, changedOnly); for (const auto& entry : pipelines) { if (entry.first == key) return entry.second; } // Constants 0-3 select element size, block size, addressing family and direction; 4-19 carry the // per-bit XOR equation for the equation family (2); 20-21 override the block extent in elements. const bool gcn = IsGcnTiled(tileMode); - std::array values{elementBytes, gcn ? 0u : BlockBytesFor(tileMode), tileMode == TextureTileMode::kLinear ? 0u : 1u, retile ? 1u : 0u}; + std::array values{elementBytes, gcn ? 0u : BlockBytesFor(tileMode), tileMode == TextureTileMode::kLinear ? 0u : 1u, retile ? 1u : 0u}; + values[26] = changedOnly ? 1u : 0u; if (gcn) { Require(!thick || IsGcnThick(tileMode), "PS4 thin tiled surfaces are detiled thin"); const auto geometry = GcnTiling(tileMode, elementBytes); @@ -187,7 +192,13 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem else if (words) shader = CreateShaderModule(context, TEXTURE_DETILE_IMAGE_WORDS_SPV, sizeof(TEXTURE_DETILE_IMAGE_WORDS_SPV), "vkCreateShaderModule detile image words"); else shader = CreateShaderModule(context, TEXTURE_DETILE_IMAGE_SPV, sizeof(TEXTURE_DETILE_IMAGE_SPV), "vkCreateShaderModule"); } - std::array entries{}; + if (changedOnly && changedModule == VK_NULL_HANDLE) { + VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + moduleInfo.codeSize = sizeof(TEXTURE_DETILE_CHANGED_SPV); + moduleInfo.pCode = TEXTURE_DETILE_CHANGED_SPV; + Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &changedModule), "vkCreateShaderModule"); + } + std::array entries{}; for (std::uint32_t index = 0; index < entries.size(); ++index) entries[index] = {index, index * 4u, 4}; VkSpecializationInfo specialization{}; specialization.mapEntryCount = static_cast(entries.size()); @@ -196,7 +207,7 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem specialization.pData = values.data(); VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - stage.module = shader; + stage.module = image || !changedOnly ? shader : changedModule; stage.pName = "main"; stage.pSpecializationInfo = &specialization; VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; @@ -228,13 +239,15 @@ void TextureDetiler::checkWindow(const TileMipLayout& layout, const DetileWindow if (!(window.columnBegin < columnEnd && window.rowBegin < rowEnd)) Require(false, "texture detiling window lies outside the mip: columns " + std::to_string(window.columnBegin) + ".." + std::to_string(columnEnd) + ", rows " + std::to_string(window.rowBegin) + ".." + std::to_string(rowEnd) + " of " + std::to_string(layout.width) + "x" + std::to_string(layout.height)); } -void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile, std::uint32_t slice, bool thick, const DetileWindow& window) { +void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile, std::uint32_t slice, bool thick, const DetileWindow& window, std::uint64_t originalOffset) { Require(commands != VK_NULL_HANDLE, "texture detiling requires an active command buffer"); Require(window.rangeBegin < window.rangeEnd && window.tiledBase <= window.rangeBegin, "texture detiling window is empty"); Require(source != VK_NULL_HANDLE && destination != VK_NULL_HANDLE, "texture detiling requires source and destination buffers"); std::uint32_t columnEnd = 0, rowEnd = 0; checkWindow(layout, window, columnEnd, rowEnd); - const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thick && !(IsGcnThick(tileMode) && layout.gcnMicroTiled)); + const bool changedOnly = originalOffset != 0; + Require(!changedOnly || (retile && tileMode == TextureTileMode::kLinear && !thick), "changed texture write-back requires a linear retile"); + const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thick && !(IsGcnThick(tileMode) && layout.gcnMicroTiled), false, changedOnly); const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto sourceDescriptorOffset = sourceOffset - sourceOffset % alignment; const auto destinationDescriptorOffset = destinationOffset - destinationOffset % alignment; @@ -245,30 +258,39 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode // range can touch (linear). const std::uint64_t tiledBytes = window.rangeEnd == 0xffffffffu ? layout.tiledSize : std::min(layout.tiledSize, window.rangeEnd) - window.tiledBase; const std::uint64_t linearBytes = window.linearBytes != 0 ? window.linearBytes : layout.linearSize - std::min(window.linearBase, layout.linearSize); + const auto originalDescriptorOffset = changedOnly ? originalOffset - originalOffset % alignment : sourceDescriptorOffset; + const auto originalBase = changedOnly ? originalOffset - originalDescriptorOffset : 0; + if (changedOnly) { + Require(originalOffset >= sourceOffset && originalOffset - sourceOffset >= linearBytes, "texture write-back baseline overlaps its current bytes"); + Require(originalBase <= UINT32_MAX && linearBytes <= UINT32_MAX - originalBase, "texture write-back baseline exceeds addressable range"); + Require(linearBytes <= UINT64_MAX - originalOffset, "texture write-back baseline exceeds its buffer address range"); + } const auto sourceRange = (sourceBase + (retile ? linearBytes : tiledBytes) + 3) / 4 * 4; + const auto originalRange = changedOnly ? (originalBase + linearBytes + 3) / 4 * 4 : sourceRange; + Require(originalRange <= context.limits.maxStorageBufferRange && originalRange <= UINT64_MAX - originalDescriptorOffset, "texture write-back baseline buffer range exceeds device limits"); const auto destinationRange = (destinationBase + (retile ? tiledBytes : linearBytes) + 3) / 4 * 4; Require(sourceRange <= context.limits.maxStorageBufferRange && destinationRange <= context.limits.maxStorageBufferRange, "texture detiling buffer range exceeds device limits"); const auto set = allocateSet(); - const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; - const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; - std::array writes{}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = set; - writes[0].dstBinding = 0; - writes[0].descriptorCount = 1; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].pBufferInfo = &sourceInfo; - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = set; - writes[1].dstBinding = 1; - writes[1].descriptorCount = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[1].pBufferInfo = &destinationInfo; + const std::array buffers{{ + {source, sourceDescriptorOffset, sourceRange}, + {destination, destinationDescriptorOffset, destinationRange}, + {source, originalDescriptorOffset, originalRange} + }}; + std::array writes{}; + for (std::uint32_t index = 0; index < writes.size(); ++index) { + writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[index].dstSet = set; + writes[index].dstBinding = index; + writes[index].descriptorCount = 1; + writes[index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[index].pBufferInfo = &buffers[index]; + } context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.BindComputePipeline(commands, target); context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr); Push push{}; push.srcBase = static_cast(sourceBase); + push.originalBase = static_cast(originalBase); push.dstBase = static_cast(destinationBase); push.width = layout.width; push.height = layout.height; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetilerDescriptors.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetilerDescriptors.cpp index 4f6d535f67d4..4e60c45d4493 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetilerDescriptors.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetilerDescriptors.cpp @@ -66,7 +66,7 @@ VkDescriptorSet TextureDetiler::allocateFrom(DescriptorRing& ring, VkDescriptorS VkDescriptorSet TextureDetiler::allocateSet(bool image) { if (image) return allocateFrom(imageDescriptorSets, imageDescriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}}, "vkCreateDescriptorPool texture detiler", "vkAllocateDescriptorSets texture detiler", "vkResetDescriptorPool texture detiler"); - return allocateFrom(descriptorSets, descriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64 * 2}}, "vkCreateDescriptorPool texture detiler", "vkAllocateDescriptorSets texture detiler", "vkResetDescriptorPool texture detiler"); + return allocateFrom(descriptorSets, descriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64 * 3}}, "vkCreateDescriptorPool texture detiler", "vkAllocateDescriptorSets texture detiler", "vkResetDescriptorPool texture detiler"); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 5118e0b0a3db..978481f16969 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -15744,9 +15744,10 @@ int main(int argc, char** argv) { }, [](VkBuffer buffer) -> std::vector& { return mock.memories.at(mock.bufferMemory.at(buffer)); }, [] { - Require(mock.writes.size() >= 2, "expected texture detiling descriptor writes"); - const auto& destinationWrite = mock.writes.back(); - const auto& sourceWrite = mock.writes[mock.writes.size() - 2]; + Require(mock.writes.size() >= 3, "expected texture detiling descriptor writes"); + const auto& originalWrite = mock.writes.back(); + const auto& destinationWrite = mock.writes[mock.writes.size() - 2]; + const auto& sourceWrite = mock.writes[mock.writes.size() - 3]; DetilerCapture capture{}; capture.groupsX = mock.lastDispatchGroups.x; capture.groupsY = mock.lastDispatchGroups.y; @@ -15758,6 +15759,9 @@ int main(int argc, char** argv) { capture.destinationBuffer = destinationWrite.buffers.at(0).buffer; capture.destinationOffset = destinationWrite.buffers.at(0).offset; capture.destinationRange = destinationWrite.buffers.at(0).range; + capture.originalBuffer = originalWrite.buffers.at(0).buffer; + capture.originalOffset = originalWrite.buffers.at(0).offset; + capture.originalRange = originalWrite.buffers.at(0).range; return capture; }, [] { return mock.pipelineCreateCount; }, diff --git a/core/libs/prx/libSceAgcDriver/tests/GraphicsTests.hpp b/core/libs/prx/libSceAgcDriver/tests/GraphicsTests.hpp index 95dcc30770f3..13569080efe6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/GraphicsTests.hpp +++ b/core/libs/prx/libSceAgcDriver/tests/GraphicsTests.hpp @@ -19,6 +19,9 @@ struct DetilerCapture { VkBuffer destinationBuffer; VkDeviceSize destinationOffset; VkDeviceSize destinationRange; + VkBuffer originalBuffer; + VkDeviceSize originalOffset; + VkDeviceSize originalRange; }; struct TextureDetilerTestAccess { diff --git a/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp index 68297257b09e..ab7287f3b8bc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp @@ -31,6 +31,7 @@ struct Push { std::uint32_t rowBegin; std::uint32_t pipeBankXor; std::uint32_t splitStride; + std::uint32_t originalBase; }; Push decodePush(const std::vector& bytes) { @@ -83,11 +84,13 @@ void RunTextureDetilerTests(const Context& context, const TextureDetilerTestAcce Require(push.pitchBytes == 96 && push.blocksPerRow == 5, "push constant row layout changed"); Require(push.tail == 0 && push.tailX == 0 && push.tailY == 0, "push constant tail fields must reflect a non-tail mip"); Require(push.elementBytes == 4, "push constant element size changed"); + Require(push.originalBase == 0, "an ordinary detile must not have a write-back baseline"); Require(push.rangeBegin == 0 && push.rangeEnd == 0xffffffffu && push.tiledBase == 0 && push.linearBase == 0, "a whole-mip dispatch must move every element out of whole buffers"); Require(push.columnBegin == 0 && push.rowBegin == 0, "a whole-mip dispatch starts at the mip's origin"); Require(capture.sourceBuffer == source && capture.destinationBuffer == destination, "dispatch bound the wrong source or destination buffer"); Require(capture.sourceOffset == 16 && capture.sourceRange == 68, "source descriptor offset or range computed incorrectly"); Require(capture.destinationOffset == 32 && capture.destinationRange == 56, "destination descriptor offset or range computed incorrectly"); + Require(capture.originalBuffer == source && capture.originalOffset == capture.sourceOffset && capture.originalRange == capture.sourceRange, "an ordinary detile must bind a valid unused baseline descriptor"); const auto pipelinesAfterFirst = access.pipelineCount(); Require(pipelinesAfterFirst == 1, "the first dispatch must create exactly one compute pipeline"); @@ -175,6 +178,27 @@ void RunTextureDetilerTests(const Context& context, const TextureDetilerTestAcce Require(decodePush(access.lastDispatch().pushConstants).pipeBankXor == 0xa00u, "the window's pipe/bank XOR did not reach the detiling shader"); Require(equationSpecialization[0] == 4 && equationSpecialization[1] == 4096 && equationSpecialization[2] == 2, "SW_4KB_D_X detiling must select the equation family over 4 KiB blocks"); + for (const auto elementBytes : {1u, 2u, 4u, 8u, 16u}) { + const auto pitch = 4u * elementBytes + 7u; + const auto changedLayout = makeLayout(4, 3, pitch, 0, pitch * 3u, pitch * 3u); + detiler.Dispatch(commands, TextureTileMode::kLinear, elementBytes, source, 19, destination, 39, changedLayout, true); + const auto ordinaryPipelines = access.pipelineCount(); + detiler.Dispatch(commands, TextureTileMode::kLinear, elementBytes, source, 19, destination, 39, changedLayout, true, 0, false, {}, 2067); + capture = access.lastDispatch(); + push = decodePush(capture.pushConstants); + Require(push.srcBase == 3 && push.dstBase == 7 && push.originalBase == 3, "changed texture write-back lost a subword offset"); + Require(capture.sourceOffset == 16 && capture.sourceRange == (3u + pitch * 3u + 3u) / 4u * 4u, "changed texture write-back must bind only the current source window"); + Require(capture.originalBuffer == source && capture.originalOffset == 2064 && capture.originalRange == capture.sourceRange, "changed texture write-back must bind its baseline independently of the distance between snapshots"); + Require(capture.destinationOffset == 32 && capture.destinationRange == (7u + pitch * 3u + 3u) / 4u * 4u, "changed texture write-back must bind only the destination window"); + Require(capture.groupsX == 1 && capture.groupsY == 1, "changed texture write-back changed the dispatch extent"); + Require(access.pipelineCount() == ordinaryPipelines + 1, "changed texture write-back needs a separate specialization"); + detiler.Dispatch(commands, TextureTileMode::kLinear, elementBytes, source, 19, destination, 39, changedLayout, true, 0, false, {}, 2590); + Require(access.pipelineCount() == ordinaryPipelines + 1, "changed texture write-back must reuse its pipeline across baseline offsets"); + Require(decodePush(access.lastDispatch().pushConstants).originalBase == 14, "changed texture write-back reused the previous baseline offset"); + detiler.Dispatch(commands, TextureTileMode::kLinear, elementBytes, source, 19, destination, 39, changedLayout, true); + Require(access.pipelineCount() == ordinaryPipelines + 1 && decodePush(access.lastDispatch().pushConstants).originalBase == 0, "ordinary retile reused changed-only state"); + } + { const auto mip = ComputeColorTargetMipLayout(ColorTileMode::RenderTarget, 4, 1024, 1024, 11, 4); Require(mip.width == 64 && mip.height == 64 && mip.tail, "the first packed render-target mip has the wrong extent"); @@ -229,6 +253,14 @@ void RunTextureDetilerTests(const Context& context, const TextureDetilerTestAcce Require(tabledCapture.groupsX == 3 && tabledCapture.groupsY == 2 && tabledCapture.groupsZ == 1, "a detile dispatch through the device's function table recorded the wrong group counts"); } + reject([&] { detiler.Dispatch(commands, TextureTileMode::kStandard4KB, 4, source, 0, destination, 0, layout, true, 0, false, {}, 256); }, "requires a linear retile"); + reject([&] { detiler.Dispatch(commands, TextureTileMode::kLinear, 4, source, 0, destination, 0, layout, false, 0, false, {}, 256); }, "requires a linear retile"); + reject([&] { detiler.Dispatch(commands, TextureTileMode::kLinear, 4, source, 0, destination, 0, layout, true, 0, true, {}, 256); }, "requires a linear retile"); + reject([&] { detiler.Dispatch(commands, TextureTileMode::kLinear, 4, source, 32, destination, 0, layout, true, 0, false, {}, 16); }, "baseline overlaps"); + reject([&] { detiler.Dispatch(commands, TextureTileMode::kLinear, 4, source, 0, destination, 0, layout, true, 0, false, {}, 16); }, "baseline overlaps"); + reject([&] { detiler.Dispatch(commands, TextureTileMode::kLinear, 4, source, 0, destination, 0, layout, true, 0, false, {}, UINT64_MAX); }, "baseline exceeds its buffer address range"); + reject([&] { detiler.Dispatch(commands, TextureTileMode::kLinear, 4, source, 0, destination, 0, makeLayout(8, 8, 32, 0, 32, std::uint64_t{UINT32_MAX} + 1u), true, 0, false, {}, std::uint64_t{UINT32_MAX} + 1u); }, "baseline exceeds addressable range"); + reject([&] { detiler.Dispatch(commands, TextureTileMode::kLinear, 4, source, 0, destination, 0, makeLayout(8, 8, 32, 0, 32, 1024), true, 0, false, {}, 2049); }, "baseline buffer range exceeds device limits"); reject([&] { detiler.Dispatch(VK_NULL_HANDLE, TextureTileMode::kStandard4KB, 4, source, 0, destination, 0, layout, 0); }, "active command buffer"); reject([&] { detiler.Dispatch(commands, TextureTileMode::kStandard4KB, 4, VK_NULL_HANDLE, 0, destination, 0, layout, 0); }, "source and destination buffers"); reject([&] { detiler.Dispatch(commands, TextureTileMode::kStandard4KB, 4, source, 0, VK_NULL_HANDLE, 0, layout, 0); }, "source and destination buffers"); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_preserved_bytes_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_preserved_bytes_tests.cmake new file mode 100644 index 000000000000..ca827ebb4a04 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_preserved_bytes_tests.cmake @@ -0,0 +1,6 @@ +add_test(NAME agc_driver_linear_target_preserved_bytes_seeded COMMAND agc_driver_linear_target_preserved_bytes_tests) +set_tests_properties(agc_driver_linear_target_preserved_bytes_seeded PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_LINEAR_SEED_LEFT=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") +if(WIN32) + set_tests_properties(agc_driver_linear_target_preserved_bytes_seeded PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_publication_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_publication_tests.cmake new file mode 100644 index 000000000000..a3978e92439b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_publication_tests.cmake @@ -0,0 +1,9 @@ +foreach(agcLinearCase IN ITEMS mask geometry reader eviction alias same) + add_test(NAME agc_driver_linear_target_publication_${agcLinearCase} COMMAND agc_driver_linear_target_publication_tests ${agcLinearCase}) + set_tests_properties(agc_driver_linear_target_publication_${agcLinearCase} PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_linear_target_publication_${agcLinearCase} PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endforeach() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_recipe_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_recipe_tests.cmake new file mode 100644 index 000000000000..3c3203bbf959 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_linear_target_recipe_tests.cmake @@ -0,0 +1,6 @@ +add_test(NAME agc_driver_linear_target_recipe COMMAND agc_driver_linear_target_resident_tests --recipe) +set_tests_properties(agc_driver_linear_target_recipe PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") +if(WIN32) + set_tests_properties(agc_driver_linear_target_recipe PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetConcurrentBytes.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetConcurrentBytes.cpp new file mode 100644 index 000000000000..bc6cea774a7e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetConcurrentBytes.cpp @@ -0,0 +1,342 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/State.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +struct VulkanDeviceTestAccess { + static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); } +}; + +} + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 4096; +constexpr std::size_t BlockBytes = 65536; +constexpr std::uint32_t Rgba32FloatInfo = 0x8738u; +constexpr std::uint32_t Rgba8UnormInfo = 0x8028u; +constexpr std::uint32_t LinearAttrib3 = 0x09000000u; +constexpr std::uint32_t Float32AbgrExport = 9; +constexpr std::uint32_t NoInput = 0xffffffffu; + +alignas(256) constexpr std::array VertexCode{ + 0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000, +}; + +constexpr std::array, 3> Triangle{{ + {-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f} +}}; + +alignas(256) std::array, 4> Programs{}; +std::size_t programCount = 0; + +std::array BufferDescriptor(const void* data, std::uint32_t stride, std::uint32_t count) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (stride << 16u), count, 0x01016facu}; +} + +std::span Program(std::uint32_t fixedVgpr, std::uint32_t stippleVgpr, bool blue = false) { + Require(programCount < Programs.size(), "too many test programs"); + auto& code = Programs[programCount++]; + std::size_t at = 0; + code[at++] = 0x36000000u | (20u << 17u) | (fixedVgpr << 9u) | 0xffu; + code[at++] = 0x0000ffffu; + code[at++] = 0x2c000000u | (21u << 17u) | (fixedVgpr << 9u) | 0x90u; + code[at++] = 0x7e000c00u | (20u << 17u) | (256u + 20u); + code[at++] = 0x7e000c00u | (21u << 17u) | (256u + 21u); + code[at++] = stippleVgpr == NoInput ? (blue ? 0x7e0002f2u : 0x7e000280u) | (22u << 17u) : 0x7e000c00u | (22u << 17u) | (256u + stippleVgpr); + code[at++] = 0x7e0002f2u | (23u << 17u); + code[at++] = 0xf800180fu; + code[at++] = 0x17161514u; + code[at++] = 0xbf810000u; + return std::span(code.data(), at); +} + +struct Block { + explicit Block(std::size_t bytes) : bytes(bytes), watched(AgcDriver::GuestMemory::WriteWatched()) { +#ifdef _WIN32 + if (watched) { + data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + } else { + data = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + } +#else + if (watched) { + void* raw = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the color target"); + const auto begin = reinterpret_cast(raw); + const auto aligned = (begin + BlockBytes - 1) & ~(static_cast(BlockBytes) - 1); + if (aligned != begin) munmap(raw, aligned - begin); + if (aligned + bytes != begin + bytes + BlockBytes) munmap(reinterpret_cast(aligned + bytes), begin + BlockBytes - aligned); + data = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + } else { + data = static_cast(std::aligned_alloc(BlockBytes, bytes)); + } +#endif + Require(data != nullptr, "cannot allocate the color target"); + Require(!watched || AgcDriver::GuestMemory::Watched(Address(), bytes), "the color target is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(data, bytes, true, true, true); + } + ~Block() { + AgcDriver::Graphics::StorageTexture::FlushPending(Address(), bytes, nullptr, "test release"); + { + GuestAllocations::Mutation mutation; + mutation.Remove(data); + } +#ifdef _WIN32 + if (watched) { + GuestArena::GuestArenaReset_nid_postfix(data, bytes); + GuestArena::GuestArenaRelease_nid_postfix(data, bytes); + } else { + VirtualFree(data, 0, MEM_RELEASE); + } +#else + if (watched) { + munmap(data, bytes); + GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(data, bytes); + } else { + std::free(data); + } +#endif + } + Block(const Block&) = delete; + Block& operator=(const Block&) = delete; + std::uint64_t Address() const { return reinterpret_cast(data); } + std::size_t bytes; + bool watched; + std::uint8_t* data = nullptr; +}; + +AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t info) { + AgcDriver::Registers cx; + cx[0x318] = static_cast(block.Address() >> 8u); + cx[0x31b] = 0; + cx[0x31c] = info; + cx[0x31d] = 0; + cx[0x323] = 0; + cx[0x324] = 0; + cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u); + cx[0x3b8] = LinearAttrib3; + cx[0x390] = static_cast(block.Address() >> 40u); + auto color = AgcDriver::Graphics::DecodeColorBuffer(cx, 0); + color.exportIndex = 0; + return color; +} + +void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t inputAddr, std::span pixelCode, std::uint32_t scissorWidth = Width, std::uint32_t writeMask = 0xfu) { + const auto target = device.Target(); + constexpr std::uint32_t waveSize = 64; + std::vector vertexUserData(4, 0u); + const auto vertexBuffer = BufferDescriptor(Triangle.data(), 16u, static_cast(Triangle.size())); + std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin()); + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertex{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {waveSize, 0, vertexUserData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, + target, + {0, 0, 0, 64} + }; + vertex.useCache = false; + const auto vertexResult = ShaderRecompiler::Recompile(vertex); + const auto vertexPush = static_cast(vertexResult.pushConstants.size()); + + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.inputAddr = inputAddr; + pixel.targetOutputMode.at(0) = Float32AbgrExport; + pixel.targetExportMapping.fill(0xe4u); + const std::vector pixelUserData(8, 0u); + const std::array pixelMemory{{{reinterpret_cast(pixelCode.data()), std::as_bytes(pixelCode)}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, reinterpret_cast(pixelCode.data()), pixelCode, 0, {}}, + {waveSize, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory}, + target, + PixelPushLayout(vertexPush, target) + }; + fragment.useCache = false; + const auto pixelResult = ShaderRecompiler::Recompile(fragment); + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, target)} + }}; + + VkPipelineColorBlendAttachmentState blend{}; + blend.blendEnable = VK_FALSE; + blend.colorWriteMask = writeMask; + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt}; + state.colors = {color}; + state.color = color; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {scissorWidth, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blends = {blend}; + state.blend = blend; + state.blendConstants = {}; + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; + device.Draw(state, draw, shaders); +} + + +struct Hammer { + std::uint8_t* data; + std::size_t pixels; + std::atomic stop{false}; + std::atomic passes{0}; + std::atomic regressions{0}; + std::atomic alphaCorruptions{0}; + std::atomic lostUpdates{0}; + std::atomic staleValues{0}; + std::atomic passLimit{60000u}; + std::array firstRegressions{}; + std::uint32_t pass = 0; + void Run() { + while (!stop.load(std::memory_order_relaxed) && pass < passLimit.load(std::memory_order_relaxed)) { + ++pass; + const auto expected = static_cast(pass - 1u); + for (std::size_t index = 0; index < pixels; ++index) { + auto* pixel = data + index * 4u; + std::uint16_t seen = 0; + std::memcpy(&seen, pixel, 2u); + if (seen != expected) { + if (static_cast(expected - seen) == 1u) lostUpdates.fetch_add(1, std::memory_order_relaxed); + else staleValues.fetch_add(1, std::memory_order_relaxed); + const auto slot = regressions.fetch_add(1, std::memory_order_relaxed); + if (slot < firstRegressions.size()) firstRegressions[slot] = (static_cast(pass) << 48u) | (static_cast(seen) << 32u) | static_cast(index); + } + if (pixel[3] != 0x77u) alphaCorruptions.fetch_add(1, std::memory_order_relaxed); + const auto value = static_cast(pass); + pixel[0] = static_cast(value & 0xffu); + pixel[1] = static_cast(value >> 8u); + pixel[3] = 0x77u; + } + passes.store(pass, std::memory_order_release); + } + } +}; + +bool Expect(AgcDriver::VulkanDevice& device) { + using ShaderRecompiler::PixelInput; + using ShaderRecompiler::PixelInputBit; + constexpr std::size_t pixels = std::size_t{Width} * Height; + constexpr std::size_t bytes = pixels * 4u; + Block block(bytes); + for (std::size_t index = 0; index < pixels; ++index) { + auto* pixel = block.data + index * 4u; + pixel[0] = 0; + pixel[1] = 0; + pixel[2] = 0x11u; + pixel[3] = 0x77u; + } + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + if (AgcDriver::Graphics::HostImportFor(context, block.Address(), bytes) == nullptr) return false; + const auto color = DecodeTarget(block, Rgba8UnormInfo); + Require(color.tileMode == AgcDriver::Graphics::ColorTileMode::Linear && color.bytes == bytes && color.format == VK_FORMAT_R8G8B8A8_UNORM, "the target is not a linear R8G8B8A8 target"); + const auto input = PixelInputBit(PixelInput::PositionFixedPoint); + const bool synchronousControl = std::getenv("APS5_HAMMER_SYNC") != nullptr; + const bool sequential = std::getenv("APS5_HAMMER_SEQUENTIAL") != nullptr; + Hammer hammer{block.data, pixels}; + if (sequential) hammer.passLimit.store(3u); + std::thread worker([&] { hammer.Run(); }); + while (hammer.passes.load(std::memory_order_acquire) < 2u) std::this_thread::yield(); + if (sequential) worker.join(); + const auto before = std::chrono::steady_clock::now(); + Draw(device, color, input, Program(0u, NoInput, true), Width, 4u); + const auto* recorder = AgcDriver::Graphics::Recorder::Active(); + const bool wasRecorded = recorder != nullptr && !recorder->Idle(); + if (!synchronousControl) Require(wasRecorded, "the blue-only draw into the imported linear target was not recorded"); + const auto recorded = std::chrono::steady_clock::now(); + if (sequential) { + hammer.passLimit.store(5u); + hammer.Run(); + } + device.WaitIdle(); + const auto done = std::chrono::steady_clock::now(); + const auto passesAtDone = hammer.passes.load(std::memory_order_acquire); + if (!sequential) { + while (hammer.passes.load(std::memory_order_acquire) < passesAtDone + 2u) std::this_thread::yield(); + hammer.stop.store(true, std::memory_order_relaxed); + worker.join(); + } + const auto lastPass = static_cast(hammer.passes.load()); + std::size_t wrongBlue = 0, wrongCounter = 0, wrongAlpha = 0; + for (std::size_t index = 0; index < pixels; ++index) { + const auto* pixel = block.data + index * 4u; + std::uint16_t counter = 0; + std::memcpy(&counter, pixel, 2u); + wrongBlue += pixel[2] != 0xffu; + wrongCounter += counter != lastPass; + wrongAlpha += pixel[3] != 0x77u; + } + std::printf("linear target concurrent bytes: pixels=%zu recorded=%d passes=%u (at wait end %u) draw ms=%.2f wait ms=%.2f\n", pixels, wasRecorded, hammer.passes.load(), passesAtDone, std::chrono::duration(recorded - before).count(), std::chrono::duration(done - recorded).count()); + std::printf("linear target concurrent bytes: mode=%s counter regressions seen by the CPU writer=%zu (lost updates by one pass=%zu, other stale values=%zu) alpha corruptions seen=%zu; final wrong blue=%zu wrong counter=%zu wrong alpha=%zu\n", sequential ? "sequential" : "concurrent", hammer.regressions.load(), hammer.lostUpdates.load(), hammer.staleValues.load(), hammer.alphaCorruptions.load(), wrongBlue, wrongCounter, wrongAlpha); + for (std::size_t slot = 0; slot < std::min(hammer.regressions.load(), hammer.firstRegressions.size()); ++slot) { + const auto packed = hammer.firstRegressions[slot]; + std::printf(" regression: pass=%llu saw=%llu at pixel=%llu (expected %llu)\n", static_cast(packed >> 48u), static_cast((packed >> 32u) & 0xffffu), static_cast(packed & 0xffffffffu), static_cast((packed >> 48u) - 1u)); + } + Require(wrongBlue == 0, "the GPU's blue channel did not reach guest memory"); + Require(hammer.regressions.load() == 0 && hammer.alphaCorruptions.load() == 0 && wrongCounter == 0 && wrongAlpha == 0, "CPU byte stores to channels the draw masked out were lost or reverted during publication"); + return true; +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!Expect(*device)) { + std::puts("linear target concurrent bytes skipped: no host import on this device"); + return VulkanTestSkipped; + } + std::puts("linear target concurrent bytes passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPreservedBytes.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPreservedBytes.cpp new file mode 100644 index 000000000000..f772fe52dbaf --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPreservedBytes.cpp @@ -0,0 +1,292 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/State.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +struct VulkanDeviceTestAccess { + static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); } +}; + +} + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 16; +constexpr std::size_t BlockBytes = 65536; +constexpr std::uint32_t Rgba32FloatInfo = 0x8738u; +constexpr std::uint32_t LinearAttrib3 = 0x09000000u; +constexpr std::uint32_t Float32AbgrExport = 9; +constexpr std::uint32_t NoInput = 0xffffffffu; + +alignas(256) constexpr std::array VertexCode{ + 0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000, +}; + +constexpr std::array, 3> Triangle{{ + {-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f} +}}; + +alignas(256) std::array, 4> Programs{}; +std::size_t programCount = 0; + +std::array BufferDescriptor(const void* data, std::uint32_t stride, std::uint32_t count) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (stride << 16u), count, 0x01016facu}; +} + +std::span Program(std::uint32_t fixedVgpr, std::uint32_t stippleVgpr, bool blue = false) { + Require(programCount < Programs.size(), "too many test programs"); + auto& code = Programs[programCount++]; + std::size_t at = 0; + code[at++] = 0x36000000u | (20u << 17u) | (fixedVgpr << 9u) | 0xffu; + code[at++] = 0x0000ffffu; + code[at++] = 0x2c000000u | (21u << 17u) | (fixedVgpr << 9u) | 0x90u; + code[at++] = 0x7e000c00u | (20u << 17u) | (256u + 20u); + code[at++] = 0x7e000c00u | (21u << 17u) | (256u + 21u); + code[at++] = stippleVgpr == NoInput ? (blue ? 0x7e0002f2u : 0x7e000280u) | (22u << 17u) : 0x7e000c00u | (22u << 17u) | (256u + stippleVgpr); + code[at++] = 0x7e0002f2u | (23u << 17u); + code[at++] = 0xf800180fu; + code[at++] = 0x17161514u; + code[at++] = 0xbf810000u; + return std::span(code.data(), at); +} + +struct Block { + explicit Block(std::size_t bytes) : bytes(bytes), watched(AgcDriver::GuestMemory::WriteWatched()) { +#ifdef _WIN32 + if (watched) { + data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + } else { + data = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + } +#else + if (watched) { + void* raw = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the color target"); + const auto begin = reinterpret_cast(raw); + const auto aligned = (begin + BlockBytes - 1) & ~(static_cast(BlockBytes) - 1); + if (aligned != begin) munmap(raw, aligned - begin); + if (aligned + bytes != begin + bytes + BlockBytes) munmap(reinterpret_cast(aligned + bytes), begin + BlockBytes - aligned); + data = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + } else { + data = static_cast(std::aligned_alloc(BlockBytes, bytes)); + } +#endif + Require(data != nullptr, "cannot allocate the color target"); + Require(!watched || AgcDriver::GuestMemory::Watched(Address(), bytes), "the color target is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(data, bytes, true, true, true); + } + ~Block() { + AgcDriver::Graphics::StorageTexture::FlushPending(Address(), bytes, nullptr, "test release"); + { + GuestAllocations::Mutation mutation; + mutation.Remove(data); + } +#ifdef _WIN32 + if (watched) { + GuestArena::GuestArenaReset_nid_postfix(data, bytes); + GuestArena::GuestArenaRelease_nid_postfix(data, bytes); + } else { + VirtualFree(data, 0, MEM_RELEASE); + } +#else + if (watched) { + munmap(data, bytes); + GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(data, bytes); + } else { + std::free(data); + } +#endif + } + Block(const Block&) = delete; + Block& operator=(const Block&) = delete; + std::uint64_t Address() const { return reinterpret_cast(data); } + std::size_t bytes; + bool watched; + std::uint8_t* data = nullptr; +}; + +AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t info) { + AgcDriver::Registers cx; + cx[0x318] = static_cast(block.Address() >> 8u); + cx[0x31b] = 0; + cx[0x31c] = info; + cx[0x31d] = 0; + cx[0x323] = 0; + cx[0x324] = 0; + cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u); + cx[0x3b8] = LinearAttrib3; + cx[0x390] = static_cast(block.Address() >> 40u); + auto color = AgcDriver::Graphics::DecodeColorBuffer(cx, 0); + color.exportIndex = 0; + return color; +} + +void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t inputAddr, std::span pixelCode, std::uint32_t scissorWidth = Width) { + const auto target = device.Target(); + constexpr std::uint32_t waveSize = 64; + std::vector vertexUserData(4, 0u); + const auto vertexBuffer = BufferDescriptor(Triangle.data(), 16u, static_cast(Triangle.size())); + std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin()); + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertex{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {waveSize, 0, vertexUserData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, + target, + {0, 0, 0, 64} + }; + vertex.useCache = false; + const auto vertexResult = ShaderRecompiler::Recompile(vertex); + const auto vertexPush = static_cast(vertexResult.pushConstants.size()); + + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.inputAddr = inputAddr; + pixel.targetOutputMode.at(0) = Float32AbgrExport; + pixel.targetExportMapping.fill(0xe4u); + const std::vector pixelUserData(8, 0u); + const std::array pixelMemory{{{reinterpret_cast(pixelCode.data()), std::as_bytes(pixelCode)}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, reinterpret_cast(pixelCode.data()), pixelCode, 0, {}}, + {waveSize, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory}, + target, + PixelPushLayout(vertexPush, target) + }; + fragment.useCache = false; + const auto pixelResult = ShaderRecompiler::Recompile(fragment); + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, target)} + }}; + + VkPipelineColorBlendAttachmentState blend{}; + blend.blendEnable = VK_FALSE; + blend.colorWriteMask = 0xf; + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt}; + state.colors = {color}; + state.color = color; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {scissorWidth, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blends = {blend}; + state.blend = blend; + state.blendConstants = {}; + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; + device.Draw(state, draw, shaders); +} + + +void Check(const std::vector& stored, const std::string& what) { + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + std::array texel{}; + std::memcpy(texel.data(), stored.data() + (static_cast(y) * Width + x) * 16u, sizeof(texel)); + const std::array expected{static_cast(x), static_cast(y), 0.0f, 1.0f}; + Require(texel == expected, what + ": pixel (" + std::to_string(x) + ", " + std::to_string(y) + ") holds (" + std::to_string(texel[0]) + ", " + std::to_string(texel[1]) + ", " + std::to_string(texel[2]) + ", " + std::to_string(texel[3]) + ")"); + } + } +} + +bool Expect(AgcDriver::VulkanDevice& device) { + using ShaderRecompiler::PixelInput; + using ShaderRecompiler::PixelInputBit; + constexpr std::size_t bytes = std::size_t{Width} * Height * 16u; + Block block(bytes); + std::fill(block.data, block.data + bytes, std::uint8_t{0xff}); + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + if (AgcDriver::Graphics::HostImportFor(context, block.Address(), bytes) == nullptr) return false; + const auto color = DecodeTarget(block, Rgba32FloatInfo); + Require(color.tileMode == AgcDriver::Graphics::ColorTileMode::Linear && color.bytes == bytes, "the target is not a linear R32G32B32A32 target"); + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput)); + const auto* recorder = AgcDriver::Graphics::Recorder::Active(); + if (std::getenv("APS5_NO_RESIDENT_LINEAR") == nullptr) Require(recorder != nullptr && !recorder->Idle(), "the draw into an imported linear target waited for the GPU instead of being recorded"); + device.WaitIdle(); + std::vector stored(bytes); + std::memcpy(stored.data(), block.data, bytes); + Check(stored, "after the recorded draw, raw guest read"); + constexpr std::uint32_t drawn = Width / 2u; + constexpr std::size_t rowBytes = std::size_t{Width} * 16u; + const bool sameOutput = std::getenv("APS5_LINEAR_SAME_OUTPUT") != nullptr; + const bool seeded = std::getenv("APS5_LINEAR_SEED_LEFT") != nullptr; + if (seeded) { + for (std::uint32_t y = 0; y < Height; ++y) std::memset(block.data + y * rowBytes, 0x5a, drawn * 16u); + } + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput, !sameOutput), drawn); + for (std::uint32_t y = 0; y < Height; ++y) std::memset(block.data + y * rowBytes + drawn * 16u, 0x42, rowBytes - drawn * 16u); + device.WaitIdle(); + std::size_t wrongGpu = 0; + std::size_t wrongCpu = 0; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < drawn; ++x) { + std::array texel{}; + std::memcpy(texel.data(), block.data + y * rowBytes + x * 16u, sizeof(texel)); + const std::array expected{static_cast(x), static_cast(y), sameOutput ? 0.0f : 1.0f, 1.0f}; + if (texel != expected) ++wrongGpu; + } + auto* begin = block.data + y * rowBytes + drawn * 16u; + wrongCpu += static_cast(std::count_if(begin, block.data + (y + 1u) * rowBytes, [](std::uint8_t byte) { return byte != 0x42u; })); + } + std::printf("linear target CPU-write check: seeded=%d, wrong GPU pixels=%zu/512, wrong CPU bytes=%zu/8192\n", seeded, wrongGpu, wrongCpu); + Require(wrongGpu == 0 && wrongCpu == 0, "linear target write-back failed to preserve the drawn half and the later CPU-written half together"); + return true; +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!Expect(*device)) { + std::puts("linear target resident test skipped: no host import on this device"); + return VulkanTestSkipped; + } + std::puts("linear target CPU-write tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPublication.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPublication.cpp new file mode 100644 index 000000000000..48149644096c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPublication.cpp @@ -0,0 +1,405 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/State.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include +#include +#include +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +struct VulkanDeviceTestAccess { + static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); } +}; + +} + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 1088; +constexpr std::size_t BlockBytes = 65536; +constexpr std::uint32_t Rgba32FloatInfo = 0x8738u; +constexpr std::uint32_t LinearAttrib3 = 0x09000000u; +constexpr std::uint32_t Float32AbgrExport = 9; +constexpr std::uint32_t NoInput = 0xffffffffu; + +alignas(256) constexpr std::array VertexCode{ + 0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000, +}; + +constexpr std::array, 3> Triangle{{ + {-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f} +}}; + +alignas(256) std::array, 8> Programs{}; +std::size_t programCount = 0; + +std::array BufferDescriptor(const void* data, std::uint32_t stride, std::uint32_t count) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (stride << 16u), count, 0x01016facu}; +} + +std::span Program(std::uint32_t fixedVgpr, std::uint32_t stippleVgpr, bool blue = false) { + Require(programCount < Programs.size(), "too many test programs"); + auto& code = Programs[programCount++]; + std::size_t at = 0; + code[at++] = 0x36000000u | (20u << 17u) | (fixedVgpr << 9u) | 0xffu; + code[at++] = 0x0000ffffu; + code[at++] = 0x2c000000u | (21u << 17u) | (fixedVgpr << 9u) | 0x90u; + code[at++] = 0x7e000c00u | (20u << 17u) | (256u + 20u); + code[at++] = 0x7e000c00u | (21u << 17u) | (256u + 21u); + code[at++] = stippleVgpr == NoInput ? (blue ? 0x7e0002f2u : 0x7e000280u) | (22u << 17u) : 0x7e000c00u | (22u << 17u) | (256u + stippleVgpr); + code[at++] = 0x7e0002f2u | (23u << 17u); + code[at++] = 0xf800180fu; + code[at++] = 0x17161514u; + code[at++] = 0xbf810000u; + return std::span(code.data(), at); +} + +struct Block { + explicit Block(std::size_t bytes) : bytes(bytes), watched(AgcDriver::GuestMemory::WriteWatched()) { +#ifdef _WIN32 + if (watched) { + data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + } else { + data = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + } +#else + if (watched) { + void* raw = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the color target"); + const auto begin = reinterpret_cast(raw); + const auto aligned = (begin + BlockBytes - 1) & ~(static_cast(BlockBytes) - 1); + if (aligned != begin) munmap(raw, aligned - begin); + if (aligned + bytes != begin + bytes + BlockBytes) munmap(reinterpret_cast(aligned + bytes), begin + BlockBytes - aligned); + data = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + } else { + data = static_cast(std::aligned_alloc(BlockBytes, bytes)); + } +#endif + Require(data != nullptr, "cannot allocate the color target"); + Require(!watched || AgcDriver::GuestMemory::Watched(Address(), bytes), "the color target is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(data, bytes, true, true, true); + } + ~Block() { + AgcDriver::Graphics::StorageTexture::FlushPending(Address(), bytes, nullptr, "test release"); + { + GuestAllocations::Mutation mutation; + mutation.Remove(data); + } +#ifdef _WIN32 + if (watched) { + GuestArena::GuestArenaReset_nid_postfix(data, bytes); + GuestArena::GuestArenaRelease_nid_postfix(data, bytes); + } else { + VirtualFree(data, 0, MEM_RELEASE); + } +#else + if (watched) { + munmap(data, bytes); + GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(data, bytes); + } else { + std::free(data); + } +#endif + } + Block(const Block&) = delete; + Block& operator=(const Block&) = delete; + std::uint64_t Address() const { return reinterpret_cast(data); } + std::size_t bytes; + bool watched; + std::uint8_t* data = nullptr; +}; + +AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t info) { + AgcDriver::Registers cx; + cx[0x318] = static_cast(block.Address() >> 8u); + cx[0x31b] = 0; + cx[0x31c] = info; + cx[0x31d] = 0; + cx[0x323] = 0; + cx[0x324] = 0; + cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u); + cx[0x3b8] = LinearAttrib3; + cx[0x390] = static_cast(block.Address() >> 40u); + auto color = AgcDriver::Graphics::DecodeColorBuffer(cx, 0); + color.exportIndex = 0; + return color; +} + +void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t inputAddr, std::span pixelCode, std::uint32_t scissorWidth = Width, std::uint32_t scissorX = 0, std::uint32_t writeMask = 0xf, bool sparse = false) { + const auto target = device.Target(); + constexpr std::uint32_t waveSize = 64; + std::vector vertexUserData(4, 0u); + const std::array, 3> small{{{-1.0f, -1.0f, 0.5f, 1.0f}, {-0.5f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f}}}; + const auto vertexBuffer = BufferDescriptor(sparse ? small.data() : Triangle.data(), 16u, static_cast(Triangle.size())); + std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin()); + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertex{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {waveSize, 0, vertexUserData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, + target, + {0, 0, 0, 64} + }; + vertex.useCache = false; + const auto vertexResult = ShaderRecompiler::Recompile(vertex); + const auto vertexPush = static_cast(vertexResult.pushConstants.size()); + + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.inputAddr = inputAddr; + pixel.targetOutputMode.at(0) = Float32AbgrExport; + pixel.targetExportMapping.fill(0xe4u); + const std::vector pixelUserData(8, 0u); + const std::array pixelMemory{{{reinterpret_cast(pixelCode.data()), std::as_bytes(pixelCode)}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, reinterpret_cast(pixelCode.data()), pixelCode, 0, {}}, + {waveSize, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory}, + target, + PixelPushLayout(vertexPush, target) + }; + fragment.useCache = false; + const auto pixelResult = ShaderRecompiler::Recompile(fragment); + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, target)} + }}; + + VkPipelineColorBlendAttachmentState blend{}; + blend.blendEnable = VK_FALSE; + blend.colorWriteMask = writeMask; + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt}; + state.colors = {color}; + state.color = color; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{static_cast(scissorX), 0}, {scissorWidth, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blends = {blend}; + state.blend = blend; + state.blendConstants = {}; + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; + device.Draw(state, draw, shaders); +} + + +void Check(const std::vector& stored, const std::string& what) { + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + std::array texel{}; + std::memcpy(texel.data(), stored.data() + (static_cast(y) * Width + x) * 16u, sizeof(texel)); + const std::array expected{static_cast(x), static_cast(y), 0.0f, 1.0f}; + Require(texel == expected, what + ": pixel (" + std::to_string(x) + ", " + std::to_string(y) + ") holds (" + std::to_string(texel[0]) + ", " + std::to_string(texel[1]) + ", " + std::to_string(texel[2]) + ", " + std::to_string(texel[3]) + ")"); + } + } +} + +bool Expect(AgcDriver::VulkanDevice& device, const std::string& mode) { + using namespace AgcDriver::Graphics; + constexpr std::size_t bytes = std::size_t{Width} * Height * 16u; + Block block(bytes); + std::memset(block.data, 0xff, bytes); + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + if (HostImportFor(context, block.Address(), bytes) == nullptr) return false; + const auto color = DecodeTarget(block, Rgba32FloatInfo); + const auto input = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionFixedPoint); + Draw(device, color, input, Program(0u, NoInput)); + device.WaitIdle(); + Check(std::vector(block.data, block.data + bytes), "initial publication"); + if (mode == "same") { + auto original = std::make_shared(context, Width / 2u * Height * 16u, VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + for (std::uint32_t y = 0; y < Height; ++y) { + std::memcpy(original->Bytes().data() + std::size_t{y} * Width / 2u * 16u, + block.data + std::size_t{y} * Width * 16u, Width / 2u * 16u); + } + std::shared_ptr live; + { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + live = StorageTexture::FindLive(block.Address(), bytes); + Require(live != nullptr, "the same-value target has no resident image"); + live->Refresh(); + std::memset(block.data, 0x42, bytes); + live->PrepareLinearDraw(); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr, "the same-value draw has no recorder"); + recorder->Keep(original); + recorder->Keep(live); + const auto commands = recorder->Commands(); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, + VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); + VkBufferImageCopy copy{}; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + copy.imageExtent = {Width / 2u, Height, 1}; + context.Function("vkCmdCopyBufferToImage")(commands, original->Handle(), live->Image(), VK_IMAGE_LAYOUT_GENERAL, 1, ©); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + live->MarkDirty(); + live->FinishLinearDraw(); + } + device.WaitIdle(); + for (std::uint32_t y = 0; y < Height; ++y) { + const auto* row = block.data + std::size_t{y} * Width * 16u; + Require(std::memcmp(row, original->Bytes().data() + std::size_t{y} * Width / 2u * 16u, Width / 2u * 16u) == 0, + "a GPU write equal to stale image contents did not replace the newer guest bytes"); + Require(std::all_of(row + Width / 2u * 16u, row + Width * 16u, [](auto byte) { return byte == 0x42u; }), + "a same-value GPU write overwrote CPU bytes outside its region"); + } + std::puts("linear publication same-value write after refresh: passed"); + return true; + } + const bool queued = mode == "queued"; + const bool masked = mode == "mask"; + const bool geometry = mode == "geometry"; + const bool reader = mode == "reader"; + const bool eviction = mode == "eviction"; + const bool alias = mode == "alias"; + Require(queued || masked || geometry || reader || eviction || alias, "unknown linear publication case"); + if (alias) { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + const auto prior = StorageTexture::FindLive(block.Address(), bytes); + Require(prior != nullptr, "the initial target has no resident image"); + auto descriptor = prior->Descriptor(); + descriptor.width /= 2u; + descriptor.height *= 2u; + auto overlapping = CachedStorageSurface(context, descriptor); + Require(overlapping != prior && overlapping->GuestBytes() == bytes, "the reshaped storage alias was not created"); + const std::array zero{0u, 0u, 0u, 0x3f800000u}; + const char* refusal = nullptr; + Require(overlapping->FillClear(zero, 0u, refusal), std::string("the alias clear was refused: ") + (refusal != nullptr ? refusal : "unknown")); + Require(StorageTexture::AnyPending(), "the alias clear has no pending result"); + } + Draw(device, color, input, Program(0u, NoInput, true), queued ? Width / 4u : (masked || geometry ? Width : Width / 2u), 0u, masked ? 4u : 0xfu, geometry); + if (queued) Draw(device, color, input, Program(0u, NoInput), Width / 4u, Width / 2u); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr && !recorder->Idle(), "the tested linear draw did not remain recorded"); + if (eviction) { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + const auto live = StorageTexture::FindLive(block.Address(), bytes); + Require(live != nullptr && live->Cached(), "the target was not cached before eviction"); + live->Flush(); + ClearCachedTextures(device.Device()); + Require(!live->Cached(), "the target survived the cache clear"); + Require(!recorder->Idle(), "cache eviction unexpectedly completed the pending draw"); + } + const auto inside = [&](std::uint32_t x, std::uint32_t y) { + if (geometry) return static_cast(x) + 0.5 < 8.0 + 8.0 * (static_cast(y) + 0.5) / Height; + if (queued) return x < Width / 4u || (x >= Width / 2u && x < 3u * Width / 4u); + return x < Width / 2u; + }; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + auto* pixel = block.data + (std::size_t{y} * Width + x) * 16u; + if (masked) { + std::memset(pixel, 0x42, 8u); + std::memset(pixel + 12u, 0x42, 4u); + } else if (!inside(x, y)) std::memset(pixel, 0x42, 16u); + } + } + const auto check = [&](const std::uint8_t* data) { + std::size_t wrongGpu = 0, wrongCpu = 0; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto* pixel = data + (std::size_t{y} * Width + x) * 16u; + if (masked) { + float blue = 0; + std::memcpy(&blue, pixel + 8u, 4u); + wrongGpu += blue != 1.0f; + for (std::size_t byte = 0; byte < 16u; ++byte) if (byte < 8u || byte >= 12u) wrongCpu += pixel[byte] != 0x42u; + } else if (inside(x, y)) { + std::array texel{}; + std::memcpy(texel.data(), pixel, sizeof(texel)); + wrongGpu += texel != std::array{static_cast(x), static_cast(y), queued && x >= Width / 2u ? 0.0f : 1.0f, 1.0f}; + } else { + for (std::size_t byte = 0; byte < 16u; ++byte) wrongCpu += pixel[byte] != 0x42u; + } + } + } + std::printf("linear publication %s: bytes=%zu, wrong GPU pixels=%zu, wrong CPU bytes=%zu\n", mode.c_str(), bytes, wrongGpu, wrongCpu); + Require(wrongGpu == 0 && wrongCpu == 0, "linear publication lost GPU results or CPU bytes"); + }; + if (reader) { + Block destination(bytes); + Block label(BlockBytes); + std::memset(destination.data, 0xa5, bytes); + std::memset(label.data, 0, BlockBytes); + constexpr std::uint32_t ready = 0x8152u; + { + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + const auto copied = device.CopyBuffer(destination.Address(), block.Address(), bytes, 0, std::numeric_limits::max(), 0, 0, 0, [](std::span, std::uint64_t) {}); + Require(copied.path == 1 || copied.path == 3, "the dependent copy did not use a GPU path"); + Require(device.WriteLabelOnGpu(label.Address(), std::as_bytes(std::span(&ready, 1)), 1, 0, false) == 0, "the completion label was not GPU-visible"); + std::printf("dependent GPU copy path=%d\n", copied.path); + device.SubmitRecorded(false); + } + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + const auto* observed = reinterpret_cast(label.data); + while (*observed != ready) { + Require(std::chrono::steady_clock::now() < deadline, "the GPU completion label did not land"); + std::this_thread::yield(); + } + check(destination.data); + check(block.data); + device.WaitIdle(); + } else { + device.WaitIdle(); + check(block.data); + } + return true; +} + +} + +int main(int argc, char** argv) { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!Expect(*device, argc > 1 ? argv[1] : "queued")) return VulkanTestSkipped; + std::puts("linear target publication tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetResident.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetResident.cpp index 993358e4c789..be0d8e5d9783 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetResident.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetResident.cpp @@ -4,8 +4,10 @@ #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/State.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" #include "prx/libc/include/GuestWriteWatch.hpp" @@ -22,13 +24,17 @@ #include #include #include +#include #include #include #include #include #include +#include +#include #include #include +#include #include namespace AgcDriver { @@ -48,6 +54,7 @@ constexpr std::uint32_t Width = 64; constexpr std::uint32_t Height = 16; constexpr std::size_t BlockBytes = 65536; constexpr std::uint32_t Rgba32FloatInfo = 0x8738u; +constexpr std::uint32_t Rgba8Info = 0x8028u; constexpr std::uint32_t LinearAttrib3 = 0x09000000u; constexpr std::uint32_t Float32AbgrExport = 9; constexpr std::uint32_t NoInput = 0xffffffffu; @@ -60,7 +67,12 @@ constexpr std::array, 3> Triangle{{ {-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f} }}; -alignas(256) std::array, 4> Programs{}; +constexpr std::array, 6> LeftHalf{{ + {-1.0f, -1.0f, 0.5f, 1.0f}, {0.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 1.0f, 0.5f, 1.0f}, + {0.0f, -1.0f, 0.5f, 1.0f}, {0.0f, 1.0f, 0.5f, 1.0f}, {-1.0f, 1.0f, 0.5f, 1.0f} +}}; + +alignas(256) std::array, 15> Programs{}; std::size_t programCount = 0; std::array BufferDescriptor(const void* data, std::uint32_t stride, std::uint32_t count) { @@ -68,7 +80,7 @@ std::array BufferDescriptor(const void* data, std::uint32_t st return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (stride << 16u), count, 0x01016facu}; } -std::span Program(std::uint32_t fixedVgpr, std::uint32_t stippleVgpr) { +std::span Program(std::uint32_t fixedVgpr, std::uint32_t stippleVgpr, std::uint32_t blueConstant = 0x80u) { Require(programCount < Programs.size(), "too many test programs"); auto& code = Programs[programCount++]; std::size_t at = 0; @@ -77,7 +89,7 @@ std::span Program(std::uint32_t fixedVgpr, std::uint32_t st code[at++] = 0x2c000000u | (21u << 17u) | (fixedVgpr << 9u) | 0x90u; code[at++] = 0x7e000c00u | (20u << 17u) | (256u + 20u); code[at++] = 0x7e000c00u | (21u << 17u) | (256u + 21u); - code[at++] = stippleVgpr == NoInput ? 0x7e000280u | (22u << 17u) : 0x7e000c00u | (22u << 17u) | (256u + stippleVgpr); + code[at++] = stippleVgpr == NoInput ? 0x7e000200u | blueConstant | (22u << 17u) : 0x7e000c00u | (22u << 17u) | (256u + stippleVgpr); code[at++] = 0x7e0002f2u | (23u << 17u); code[at++] = 0xf800180fu; code[at++] = 0x17161514u; @@ -159,11 +171,12 @@ AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t return color; } -void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t inputAddr, std::span pixelCode) { +void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t inputAddr, std::span pixelCode, + std::uint32_t scissorWidth = Width, VkColorComponentFlags colorWriteMask = 0xf, std::span> vertices = Triangle, bool halveDestination = false, bool recipe = false) { const auto target = device.Target(); constexpr std::uint32_t waveSize = 64; std::vector vertexUserData(4, 0u); - const auto vertexBuffer = BufferDescriptor(Triangle.data(), 16u, static_cast(Triangle.size())); + const auto vertexBuffer = BufferDescriptor(vertices.data(), 16u, static_cast(vertices.size())); std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin()); const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; ShaderRecompiler::RecompileRequest vertex{ @@ -196,8 +209,14 @@ void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarge }}; VkPipelineColorBlendAttachmentState blend{}; - blend.blendEnable = VK_FALSE; - blend.colorWriteMask = 0xf; + blend.blendEnable = halveDestination ? VK_TRUE : VK_FALSE; + blend.srcColorBlendFactor = VK_BLEND_FACTOR_ZERO; + blend.dstColorBlendFactor = VK_BLEND_FACTOR_CONSTANT_COLOR; + blend.colorBlendOp = VK_BLEND_OP_ADD; + blend.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; + blend.dstAlphaBlendFactor = VK_BLEND_FACTOR_CONSTANT_ALPHA; + blend.alphaBlendOp = VK_BLEND_OP_ADD; + blend.colorWriteMask = colorWriteMask; AgcDriver::Graphics::State state{}; state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt}; state.colors = {color}; @@ -207,14 +226,23 @@ void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarge state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; state.negativeOneToOne = false; - state.scissor = {{0, 0}, {Width, Height}}; + state.scissor = {{0, 0}, {scissorWidth, Height}}; state.cullMode = VK_CULL_MODE_NONE; state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; state.blends = {blend}; state.blend = blend; - state.blendConstants = {}; - const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; - device.Draw(state, draw, shaders); + state.blendConstants = {0.5f, 0.5f, 0.5f, 0.5f}; + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(vertices.size()), 0, 1, 0, false}; + if (!recipe) { + device.Draw(state, draw, shaders); + return; + } + std::shared_ptr captured; + device.Draw(state, draw, shaders, {}, &captured); + Require(captured != nullptr, "the linear draw did not produce a reusable recipe"); + device.WaitIdle(); + Require(device.DrawFromRecipe(state, draw, shaders, {}, captured) == AgcDriver::RecipeOutcome::Recorded, + "the linear draw did not execute its cached recipe"); } @@ -229,11 +257,14 @@ void Check(const std::vector& stored, const std::string& what) { } } -bool Expect(AgcDriver::VulkanDevice& device) { +enum class Coverage { Scissor, BlueOnly, Geometry }; + +constexpr std::size_t TargetBytes = std::size_t{Width} * Height * 16u; + +bool Expect(AgcDriver::VulkanDevice& device, Block& block, Coverage coverage, bool seed = false, bool recipe = false) { using ShaderRecompiler::PixelInput; using ShaderRecompiler::PixelInputBit; - constexpr std::size_t bytes = std::size_t{Width} * Height * 16u; - Block block(bytes); + constexpr std::size_t bytes = TargetBytes; std::fill(block.data, block.data + bytes, std::uint8_t{0xff}); const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); if (AgcDriver::Graphics::HostImportFor(context, block.Address(), bytes) == nullptr) return false; @@ -241,21 +272,314 @@ bool Expect(AgcDriver::VulkanDevice& device) { Require(color.tileMode == AgcDriver::Graphics::ColorTileMode::Linear && color.bytes == bytes, "the target is not a linear R32G32B32A32 target"); Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput)); const auto* recorder = AgcDriver::Graphics::Recorder::Active(); - Require(recorder != nullptr && !recorder->Idle(), "the draw into an imported linear target waited for the GPU instead of being recorded"); + const bool resident = std::getenv("APS5_NO_RESIDENT_LINEAR") == nullptr; + Require(!resident || (recorder != nullptr && !recorder->Idle()), "the draw into an imported linear target waited for the GPU instead of being recorded"); device.WaitIdle(); std::vector stored(bytes); std::memcpy(stored.data(), block.data, bytes); Check(stored, "after the recorded draw, raw guest read"); + constexpr std::uint32_t drawn = Width / 2u; + constexpr std::size_t rowBytes = std::size_t{Width} * 16u; + constexpr std::size_t drawnBytes = std::size_t{drawn} * 16u; + const bool masked = coverage == Coverage::BlueOnly; + const bool geometry = coverage == Coverage::Geometry; + const std::string name = recipe ? "cached recipe" : seed ? "seeded scissor" : masked ? "blue-only mask" : geometry ? "partial geometry" : "unseeded scissor"; + if (seed) { + for (std::uint32_t y = 0; y < Height; ++y) std::memset(block.data + y * rowBytes, 0x5a, drawnBytes); + } + std::unique_ptr recipeVertices; + auto vertices = geometry ? std::span>(LeftHalf) : std::span>(Triangle); + if (recipe) { + recipeVertices = std::make_unique(BlockBytes); + std::memcpy(recipeVertices->data, vertices.data(), vertices.size_bytes()); + Require(AgcDriver::Graphics::HostImportFor(context, recipeVertices->Address(), vertices.size_bytes()) != nullptr, + "the recipe fixture requires host-imported vertex data"); + vertices = {reinterpret_cast*>(recipeVertices->data), vertices.size()}; + } + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput, 0xf4u), + geometry ? Width : drawn, masked ? VK_COLOR_COMPONENT_B_BIT : 0xf, vertices, false, recipe); + recorder = AgcDriver::Graphics::Recorder::Active(); + Require(!resident || (recorder != nullptr && !recorder->Idle()), name + ": the second draw waited for the GPU instead of being recorded"); + for (std::uint32_t y = 0; y < Height; ++y) { + auto* row = block.data + y * rowBytes; + std::memset(row + drawnBytes, 0x42, rowBytes - drawnBytes); + if (masked) { + for (std::uint32_t x = 0; x < drawn; ++x) { + std::memset(row + x * 16u, 0x42, 8u); + std::memset(row + x * 16u + 12u, 0x42, 4u); + } + } + } + device.WaitIdle(); + for (std::uint32_t y = 0; y < Height; ++y) { + const auto* row = block.data + y * rowBytes; + for (std::uint32_t x = 0; x < drawn; ++x) { + std::array texel{}; + std::memcpy(texel.data(), row + x * 16u, sizeof(texel)); + constexpr float cpu = std::bit_cast(0x42424242u); + const std::array expected{masked ? cpu : static_cast(x), masked ? cpu : static_cast(y), 2.0f, masked ? cpu : 1.0f}; + Require(texel == expected, name + ": the second draw or the CPU's masked channels were lost at (" + std::to_string(x) + ", " + std::to_string(y) + ")"); + } + Require(std::all_of(row + drawnBytes, row + rowBytes, [](std::uint8_t byte) { return byte == 0x42u; }), + name + ": write-back overwrote the CPU's untouched right half in row " + std::to_string(y)); + } + return true; +} + +bool ExpectSubwordWrites(AgcDriver::VulkanDevice& device, Block& block) { + using ShaderRecompiler::PixelInput; + using ShaderRecompiler::PixelInputBit; + constexpr std::size_t bytes = std::size_t{Width} * Height * 4u; + constexpr std::uint32_t drawn = Width / 2u; + std::fill(block.data, block.data + bytes, std::uint8_t{0xff}); + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + if (AgcDriver::Graphics::HostImportFor(context, block.Address(), bytes) == nullptr) return false; + const auto color = DecodeTarget(block, Rgba8Info); + Require(color.tileMode == AgcDriver::Graphics::ColorTileMode::Linear && color.format == VK_FORMAT_R8G8B8A8_UNORM && color.bytes == bytes, + "the target is not a linear R8G8B8A8_UNORM target"); + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput)); + device.WaitIdle(); + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto* texel = block.data + (std::size_t{y} * Width + x) * 4u; + Require(texel[0] == (x == 0 ? 0u : 255u) && texel[1] == (y == 0 ? 0u : 255u) && texel[2] == 0u && texel[3] == 255u, + "RGBA8 initial draw did not reach guest memory"); + } + } + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput, 0xf2u), drawn, VK_COLOR_COMPONENT_B_BIT); + const auto* recorder = AgcDriver::Graphics::Recorder::Active(); + const bool resident = std::getenv("APS5_NO_RESIDENT_LINEAR") == nullptr; + Require(!resident || (recorder != nullptr && !recorder->Idle()), "RGBA8 masked draw waited for the GPU instead of being recorded"); + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + auto* texel = block.data + (std::size_t{y} * Width + x) * 4u; + texel[0] = texel[1] = texel[3] = 0x42u; + if (x >= drawn) texel[2] = 0x42u; + } + } + const auto check = [&](std::uint8_t channels, const std::string& name) { + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto* texel = block.data + (std::size_t{y} * Width + x) * 4u; + Require(texel[0] == channels && texel[1] == channels && texel[2] == (x < drawn ? 255u : 0x42u) && texel[3] == channels, + name + ": unexpected pixel at (" + std::to_string(x) + ", " + std::to_string(y) + ")"); + } + } + }; + device.WaitIdle(); + check(0x42u, "RGBA8 GPU and CPU writes sharing a dword"); + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput), Width, + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_A_BIT, Triangle, true); + recorder = AgcDriver::Graphics::Recorder::Active(); + Require(!resident || (recorder != nullptr && !recorder->Idle()), "RGBA8 destination blend waited for the GPU instead of being recorded"); + device.WaitIdle(); + check(0x21u, "RGBA8 destination blend must read the CPU's preserved channels"); + return true; +} + +bool ExpectQueuedDraws(AgcDriver::VulkanDevice& device, Block& block) { + using ShaderRecompiler::PixelInput; + using ShaderRecompiler::PixelInputBit; + std::fill(block.data, block.data + TargetBytes, std::uint8_t{0xff}); + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + if (AgcDriver::Graphics::HostImportFor(context, block.Address(), TargetBytes) == nullptr) return false; + const auto color = DecodeTarget(block, Rgba32FloatInfo); + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput)); + device.WaitIdle(); + Check(std::vector(block.data, block.data + TargetBytes), "queued draw baseline"); + const bool resident = std::getenv("APS5_NO_RESIDENT_LINEAR") == nullptr; + for (const auto [width, blue] : {std::pair{Width / 2u, 0xf4u}, std::pair{Width / 4u, 0xf2u}}) { + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput, blue), width, VK_COLOR_COMPONENT_B_BIT); + const auto* recorder = AgcDriver::Graphics::Recorder::Active(); + Require(!resident || (recorder != nullptr && !recorder->Idle()), "an overlapping linear draw waited for the GPU instead of being recorded"); + } + constexpr float cpu = 64.0f; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + auto* texel = block.data + (std::size_t{y} * Width + x) * 16u; + for (const auto channel : {0u, 1u, 3u}) std::memcpy(texel + channel * sizeof(float), &cpu, sizeof(cpu)); + if (x >= Width / 2u) std::memcpy(texel + 2u * sizeof(float), &cpu, sizeof(cpu)); + } + } + const auto check = [&](float channels, const std::string& name) { + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + std::array texel{}; + std::memcpy(texel.data(), block.data + (std::size_t{y} * Width + x) * 16u, sizeof(texel)); + const std::array expected{channels, channels, x < Width / 4u ? 1.0f : x < Width / 2u ? 2.0f : cpu, channels}; + Require(texel == expected, name + ": unexpected pixel at (" + std::to_string(x) + ", " + std::to_string(y) + ")"); + } + } + }; + device.WaitIdle(); + check(cpu, "queued overlapping draws and untouched CPU bytes"); + Draw(device, color, PixelInputBit(PixelInput::PositionFixedPoint), Program(0u, NoInput), Width, + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_A_BIT, Triangle, true); + device.WaitIdle(); + check(cpu / 2.0f, "queued draw refresh must upload preserved CPU channels"); return true; } +void ExpectCpuSnapshot(AgcDriver::VulkanDevice& device) { + using namespace AgcDriver::Graphics; + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + context.hostImportAlignment = 0; + TextureDetiler detiler(context); + context.detiler = &detiler; + Block block(2 * BlockBytes); + std::memset(block.data, 0x11, block.bytes); + GuestTextureResource resource{}; + resource.baseAddress = block.Address(); + resource.width = 63; + resource.height = 256; + resource.depthOrLastArray = 1; + resource.mipCount = 1; + resource.tileMode = TextureTileMode::kLinear; + resource.dimension = TextureDimension::k2DArray; + resource.format = 56; + resource.dstSelX = 4; + resource.dstSelY = 5; + resource.dstSelZ = 6; + resource.dstSelW = 7; + const auto geometry = DescribeSurface(resource); + const auto& mip = geometry.mips.front(); + Require(geometry.imageLayers == 2 && geometry.layerBytes == BlockBytes && geometry.guestBytes == block.bytes && mip.pitchBytes == 256, + "CPU snapshot fixture does not contain two padded 64 KiB layers"); + Require(HostImportFor(context, block.Address(), block.bytes) == nullptr, "CPU snapshot fixture unexpectedly imported guest memory"); + auto image = StorageTexture::Create(context, detiler, resource, 0); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr, "CPU snapshot fixture has no recorder"); + constexpr std::uint32_t drawn = 31; + auto upload = std::make_shared(context, drawn * resource.height * 4u, VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + std::fill(upload->Bytes().begin(), upload->Bytes().end(), std::byte{0x22}); + image->PrepareLinearDraw(); + recorder->Keep(image); + recorder->Keep(upload); + const auto commands = recorder->Commands(); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); + VkBufferImageCopy write{}; + write.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + write.imageExtent = {drawn, resource.height, 1}; + context.Function("vkCmdCopyBufferToImage")(commands, upload->Handle(), image->Image(), VK_IMAGE_LAYOUT_GENERAL, 1, &write); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT); + for (std::uint32_t row = 0; row < resource.height; ++row) { + auto* pixels = block.data + row * mip.pitchBytes; + std::memset(pixels + drawn * 4u, 0x42, (resource.width - drawn) * 4u); + std::memset(pixels + resource.width * 4u, 0x55, mip.pitchBytes - resource.width * 4u); + } + std::memset(block.data + geometry.layerBytes, 0x66, static_cast(geometry.layerBytes)); + std::vector expected(block.data, block.data + block.bytes); + for (std::uint32_t row = 0; row < resource.height; ++row) std::memset(expected.data() + row * mip.pitchBytes, 0x22, drawn * 4u); + image->MarkSliceDirty(0); + image->FinishLinearDraw(); + recorder->Sync(); + Require(std::equal(expected.begin(), expected.end(), block.data), "CPU snapshot write-back lost GPU bytes, CPU bytes, padding, or the untouched layer"); + image->Refresh(); + const auto rowBytes = resource.width * 4u; + const auto layerBytes = rowBytes * resource.height; + Buffer readback(context, static_cast(layerBytes) * 2u, VK_BUFFER_USAGE_TRANSFER_DST_BIT); + CommandBatch batch(context); + RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); + VkBufferImageCopy read{}; + read.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 2}; + read.imageExtent = {resource.width, resource.height, 1}; + context.Function("vkCmdCopyImageToBuffer")(batch.Handle(), image->Image(), VK_IMAGE_LAYOUT_GENERAL, readback.Handle(), 1, &read); + RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + batch.SubmitAndWait(); + for (std::uint32_t layer = 0; layer < 2; ++layer) { + for (std::uint32_t row = 0; row < resource.height; ++row) { + Require(std::memcmp(readback.Bytes().data() + layer * layerBytes + row * rowBytes, + expected.data() + geometry.GuestLayerOffset(layer) + row * mip.pitchBytes, rowBytes) == 0, + "CPU snapshot refresh did not upload preserved CPU texels"); + } + } + std::puts("linear target CPU snapshot, padded array layers, and refresh: passed"); } -int main() { +void ExpectChangedRetile(AgcDriver::VulkanDevice& device) { + using namespace AgcDriver::Graphics; + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); + TextureDetiler detiler(context); + for (const auto elementBytes : {1u, 2u, 4u, 8u, 16u}) { + for (std::uint32_t shift = 0; shift < 4; ++shift) { + TileMipLayout layout{}; + layout.width = 19; + layout.height = 3; + layout.pitchBytes = layout.width * elementBytes + 7u; + layout.linearSize = layout.tiledSize = layout.pitchBytes * layout.height; + const std::uint32_t currentOffset = 19u + shift, originalOffset = 2046u + shift, destinationOffset = 39u + shift; + Buffer source(context, 4096, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + Buffer destination(context, 2048, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + auto sourceBytes = source.Bytes(); + std::fill(sourceBytes.begin(), sourceBytes.end(), std::byte{0x11}); + std::fill_n(sourceBytes.begin() + currentOffset, static_cast(layout.linearSize), std::byte{0x22}); + std::array expected{}; + expected.fill(std::byte{0x42}); + std::copy(expected.begin(), expected.end(), destination.Bytes().begin()); + const bool windowed = shift % 2u != 0; + DetileWindow window{}; + if (windowed) { + window.rangeBegin = layout.pitchBytes + elementBytes; + window.rangeEnd = layout.pitchBytes + 18u * elementBytes; + window.columnBegin = 1; window.columnEnd = 18; + window.rowBegin = 1; window.rowEnd = 2; + } + for (std::uint32_t y = 0; y < layout.height; ++y) { + for (std::uint32_t x = 0; x < layout.width * elementBytes; ++x) { + const auto offset = y * layout.pitchBytes + x; + const auto before = static_cast((offset * 29u + 11u) & 0xffu); + sourceBytes[originalOffset + offset] = sourceBytes[currentOffset + offset] = before; + if ((x + y) % 3u != 0) continue; + const auto changed = before ^ std::byte{0x80}; + sourceBytes[currentOffset + offset] = changed; + if (!windowed || (y == 1 && x >= elementBytes && x < 18u * elementBytes)) expected[destinationOffset + offset] = changed; + } + } + detiler.BeginBatch(); + CommandBatch batch(context); + RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + detiler.Dispatch(batch.Handle(), TextureTileMode::kLinear, elementBytes, source.Handle(), currentOffset, destination.Handle(), destinationOffset, layout, true, 0, false, window, originalOffset); + RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + batch.SubmitAndWait(); + destination.Invalidate(); + Require(std::equal(expected.begin(), expected.end(), destination.Bytes().begin()), + "changed linear retile corrupted GPU bytes, CPU bytes, or padding for element size " + std::to_string(elementBytes) + " and offset shift " + std::to_string(shift)); + } + } +} + +} + +int main(int argc, char** argv) { try { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - if (!Expect(*device)) { + std::printf("linear target resident device: %s\n", device->DeviceName().c_str()); + if (argc == 2 && std::string(argv[1]) == "--recipe") { + Block recipe(BlockBytes); + Require(Expect(*device, recipe, Coverage::Scissor, false, true), "the recipe fixture requires a host-imported linear target"); + std::puts("linear target cached recipe tests passed"); + return 0; + } + ExpectChangedRetile(*device); + ExpectCpuSnapshot(*device); + Block unseeded(BlockBytes); + Block seeded(BlockBytes); + Block masked(BlockBytes); + Block geometry(BlockBytes); + Block subword(BlockBytes); + Block queued(BlockBytes); + if (!Expect(*device, unseeded, Coverage::Scissor) || !Expect(*device, seeded, Coverage::Scissor, true) || + !Expect(*device, masked, Coverage::BlueOnly) || !Expect(*device, geometry, Coverage::Geometry) || + !ExpectSubwordWrites(*device, subword) || !ExpectQueuedDraws(*device, queued)) { std::puts("linear target resident test skipped: no host import on this device"); return VulkanTestSkipped; } diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 16737015ea38..625ad31643ba 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -224,6 +224,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | | `APS5_HOST_IMPORT_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 0 | budget in MiB for pinned host imports; `0` selects the larger of 6144 MiB and half the physical memory, at most the largest host heap minus the larger of 2 GiB and half that heap (4055 MiB on a 16 GB Windows PC with an RTX 4060) | | `APS5_UPLOAD_CACHE_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 512 | budget in MiB for the read-only guest buffer uploads reused across builds; `0` disables the cache | +| `APS5_HAMMER_SEQUENTIAL` | presence | `core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetConcurrentBytes.cpp` | | runs the CPU byte writer before recording and before waiting, without concurrent publication | +| `APS5_HAMMER_SYNC` | presence | `core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetConcurrentBytes.cpp` | | permits the synchronous control to complete without a recorded draw | | `APS5_IGNORE_DEPTH_TEST` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp` | | renders depth- and stencil-tested draws without a depth target as if the tests always passed | | `APS5_IMAGE_POOL_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp` | | size in MiB of the released image memory the buffer pool keeps for reuse by memory type and size while the device-local heap is under its reported budget, including at most one empty image slab; a quarter of the device tier's budget by default; `0` frees released image memory at once | | `APS5_INDEX_IN_PLACE_BEHIND_WRITER` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | binds the index range of a draw without vertex attributes, mesh stage or primitive restart in place from its host import behind a pending GPU writer, with a barrier before the draw, instead of waiting for the writer and copying the range; APS5_AB can toggle it; with APS5_PROFILE_DRAW it prints one `[index-behind-writer]` line per 10 s summed over every thread, counting each outcome of an attempt (taken, no writer, vertex attributes, index limit, mesh stage, primitive restart, vertex offset, unit shadow, pending storage, label or store, copied writer, no import, refused, off) | @@ -412,6 +414,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_RECORD_COPIED_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | waits for copied-write draws at once instead of listing their write-back for later | | `APS5_NO_RECT_INDIRECT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp` | | sends an indirect rectangle-list draw down the CPU path instead of the GPU-side path | | `APS5_NO_REFRESH_GPU_ORDERED` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | waits on the CPU for the pending writers a storage refresh flushes and compares the guest bytes, instead of re-uploading the layers from the import behind the write-backs | +| `APS5_LINEAR_SAME_OUTPUT` | presence | `core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPreservedBytes.cpp` | | repeats the initial GPU output in the CPU-write regression instead of drawing a different blue value | +| `APS5_LINEAR_SEED_LEFT` | presence | `core/libs/prx/libSceAgcDriver/tests/execution/LinearTargetPreservedBytes.cpp` | | seeds the drawn half before recording the CPU-write regression's second draw | | `APS5_NO_RESIDENT_LINEAR` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | drops the residency of linear color targets, so a target whose address has a host import, or whose import a draw would make, is copied in and out again | | `APS5_NO_RESIDENT_PRESENT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | always presents through guest memory instead of the resident image | | `APS5_NO_RESIDENT_TARGETS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | copies every render target in and out again instead of keeping it resident |