perf(agc): replay draws to native multisample color targets (#27849)

This commit is contained in:
RavenCurseBurg authored and GitHub committed 2026-12-04 13:14:44 +13:00
1 parent 5de13f086f
commit c48c201900
6 files changed
+170 -33

No files matched your search

@@ -70,12 +70,17 @@ enum class RecipeOutcome { Recorded, Rebuild };
// pipeline stages. Built at the end of a recorded, cacheable, reusable, non-indirect draw and
// attached to the draw entry's matched stage variants; immutable.
struct DrawRecipe {
struct MultisampleAttachment {
std::weak_ptr<void> owner;
VkImage image;
};
VkDevice device = VK_NULL_HANDLE;
std::weak_ptr<Graphics::ShaderResources> templateRef;
Graphics::ResourceCache::Key key;
std::weak_ptr<Graphics::Pipeline> pipeline;
std::weak_ptr<Graphics::Framebuffer> framebuffer;
std::vector<std::weak_ptr<Graphics::StorageTexture>> targets;
std::vector<MultisampleAttachment> multisampleAttachments;
std::vector<VkImageView> targetViews;
std::uint64_t passKey = 0;
Graphics::VertexInputLayout vertexInput;
@@ -114,6 +114,7 @@ void PublishMultisampleTargetColor_nid_no_patch(const Context& context, const Co
void SynchronizeMultisampleTargetRead_nid_no_patch(std::uint64_t address, std::size_t bytes);
VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, VkImage* image = nullptr);
VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, std::shared_ptr<void>& owner, VkImage* image = nullptr);
bool RepeatMultisampleTargetView(const Context& context, const ColorTarget& target, const std::shared_ptr<void>& owner, VkImage image, VkImageView view);
void PrepareMultisampleTargetForDraw_nid_no_patch(const Context& context, const ColorTarget& target);
void KeepMultisampleTarget_nid_no_patch(const std::shared_ptr<void>& owner);
void MaterializeMultisampleTargetClear(const Context& context, const ColorTarget& target);
@@ -4890,14 +4890,19 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D
// only a template the resource cache serves under this content key (reusable: no lease,
// no copied writes, every direct region import- or mirror-served) of a direct draw, so a
// hit's proof is the template's ProveCurrent and nothing needs completion work.
if (recipeOut != nullptr && DrawRecipes() && cacheable && contentKey != nullptr && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && !multisampled && !pipeline->ReordersSamples()) {
if (recipeOut != nullptr && DrawRecipes() && cacheable && contentKey != nullptr && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && !pipeline->ReordersSamples() &&
(!multisampled || std::ranges::all_of(targets, &TargetBinding::multisampled))) {
auto recipe = std::make_shared<DrawRecipe>();
recipe->device = context.device;
recipe->templateRef = resources;
recipe->key = *contentKey;
recipe->pipeline = pipeline;
recipe->framebuffer = framebuffer;
for (const auto& owner : owners) recipe->targets.emplace_back(owner);
if (multisampled) {
for (const auto& binding : targets) recipe->multisampleAttachments.push_back({binding.multisampleOwner, binding.multisampleImage});
} else {
for (const auto& owner : owners) recipe->targets.emplace_back(owner);
}
recipe->targetViews = targetViews;
recipe->passKey = DrawRenderPassKey(context, state, targetViews);
recipe->vertexInput = inputs.VertexLayout();
@@ -5438,7 +5443,9 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
if (recipe.hasDepth != state.depth.has_value()) return miss(DrawRecipeMiss::TargetGone);
if (!ZeroVertexLayoutMatches(recipe.vertexInput, shaders.front().program->vertexAttributes)) return miss(DrawRecipeMiss::Proof);
const std::size_t expectedViews = state.colors.size() + (recipe.hasDepth ? 1u : 0u);
Require(recipe.targets.size() == state.colors.size() && recipe.targetViews.size() == expectedViews, "draw recipe targets do not match the state");
const bool multisampled = !recipe.multisampleAttachments.empty();
const auto colorCount = multisampled ? recipe.multisampleAttachments.size() : recipe.targets.size();
Require(colorCount == state.colors.size() && recipe.targetViews.size() == expectedViews, "draw recipe targets do not match the state");
const auto plan = planDraw(context, state, draw, shaders, &recipe, outcome, timer);
DrawInputs inputs;
if (plan.nothing) inputs.nothing = true;
@@ -5457,20 +5464,37 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
if (ownsTargetMemo(memo) && (memo.colors.valid || memo.depth.valid)) noteTargetMemo(TargetMemoEvent::RecipeInvalidated);
memo.Invalidate();
const bool passAttachments = PassAttachmentMemoEnabled();
const bool verifyAttachments = passAttachments && VerifyPassAttachments() && [&] {
std::vector<std::shared_ptr<void>> multisampleOwners;
std::vector<VkImage> multisampleImages;
if (multisampled) {
multisampleOwners.reserve(state.colors.size());
multisampleImages.reserve(state.colors.size());
}
const bool verifyAttachments = passAttachments && !multisampled && VerifyPassAttachments() && [&] {
InlineList<std::shared_ptr<StorageTexture>, 8> ignored;
return matchAttachmentMemo(context, state, ignored, recipe.targetViews);
}();
InlineList<std::shared_ptr<StorageTexture>, 8> targets;
const bool attachmentsFromMemo = passAttachments && !VerifyPassAttachments() && matchAttachmentMemo(context, state, targets, recipe.targetViews);
const bool attachmentsFromMemo = passAttachments && !multisampled && !VerifyPassAttachments() && matchAttachmentMemo(context, state, targets, recipe.targetViews);
if (attachmentsFromMemo) {
noteAttachments(AttachmentEvent::Hit);
for (std::size_t index = 0; index < state.colors.size(); ++index) {
if (state.colors[index].fmaskAddress != 0) GuardOneFragmentFmask(context, state.colors[index]);
}
} else {
for (std::size_t index = 0; index < recipe.targets.size(); ++index) {
for (std::size_t index = 0; index < colorCount; ++index) {
timer.phase(PhaseSetup);
if (multisampled) {
const auto& color = state.colors[index];
const auto& attachment = recipe.multisampleAttachments[index];
auto owner = attachment.owner.lock();
if (!RepeatMultisampleTargetView(context, color, owner, attachment.image, recipe.targetViews[index])) return miss(DrawRecipeMiss::TargetGone);
multisampleOwners.push_back(std::move(owner));
multisampleImages.push_back(attachment.image);
targets.EmplaceBack(nullptr);
timer.phase(PhaseReadTarget);
continue;
}
if (state.colors[index].fmaskAddress != 0) GuardOneFragmentFmask(context, state.colors[index]);
auto stored = recipe.targets[index].lock();
if (stored == nullptr || !StorageImageCached(context, stored.get()) || !StorageImageServesKeys(*stored, SurfaceForTarget(state.colors[index]).dccAddress)) return miss(DrawRecipeMiss::TargetGone);
@@ -5517,6 +5541,13 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
}
const auto moved = resources->MovedReadOnlyBuffers(shaders, *recorder, &state.color);
if (!moved.has_value()) return miss(DrawRecipeMiss::Buffers);
if (multisampled) {
const auto& sources = resources->MultisampleSources();
for (const auto& color : state.colors) {
if (std::ranges::find(sources, color.surfaceAddress) != sources.end()) return miss(DrawRecipeMiss::Proof);
}
if (state.depth) RequireNoNativeDepthFeedback_nid_no_patch(context, *state.depth, resources->SampledTextures());
}
CheckBufferAliases(shaders, state.color, draw.indexAddress, inputs.indexBytes);
if (recipe.hasDepth && writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth);
SharedResourceCache().Touch(recipe.key);
@@ -5533,7 +5564,7 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
auto framebuffer = recipe.framebuffer.lock();
if (framebuffer == nullptr) {
const auto stored = targets.Span();
const std::vector<std::shared_ptr<void>> framebufferOwners(stored.begin(), stored.end());
const auto framebufferOwners = multisampled ? multisampleOwners : std::vector<std::shared_ptr<void>>(stored.begin(), stored.end());
framebuffer = pipeline->AcquireFramebuffer(recipe.targetViews, framebufferOwners, state.renderExtent, state.renderLayers);
}
timer.phase(PhasePipeline);
@@ -5545,6 +5576,8 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
record.moved = *moved;
record.targetViews = recipe.targetViews;
record.targets = targets.Span();
record.multisampleTargets = std::move(multisampleOwners);
record.multisampleImages = std::move(multisampleImages);
InlineList<std::pair<std::uint32_t, std::uint32_t>, 8> slices;
for (const auto& color : state.colors) slices.EmplaceBack(color.arraySlice, color.arrayLastSlice != 0 ? color.layers : 1u);
record.targetSlices = slices.Span();
@@ -1612,7 +1612,7 @@ void requireNoTextureHost(const Context& context, const ColorTarget& target) {
}
}
MultisampleTarget& acquire(const Context& context, const ColorTarget& requested, std::optional<VkClearColorValue> initialClear = std::nullopt, std::shared_ptr<Buffer> initialUpload = {}, std::vector<std::byte> initialBaseline = {}) {
MultisampleTarget* acquireExisting(const Context& context, const ColorTarget& requested, const MultisampleTarget* expected = nullptr, VkImage expectedImage = VK_NULL_HANDLE) {
discardRetiredTargets();
for (const auto& target : targets()) {
if (!target->active->load(std::memory_order_acquire)) continue;
@@ -1620,8 +1620,10 @@ MultisampleTarget& acquire(const Context& context, const ColorTarget& requested,
auto use = requested;
use.format = target->target.format;
const bool takesRegisterState = target->TakesRegisterState(use);
if (takesRegisterState) target->CheckTextureImport();
if (takesRegisterState || recreated(target->target, use)) {
const bool recreate = takesRegisterState || recreated(target->target, use);
if (expected != nullptr && (target.get() != expected || target->image != expectedImage || recreate)) return nullptr;
if (recreate) {
if (takesRegisterState) target->CheckTextureImport();
{
std::unique_lock lock(guardedMutex());
if (!target->active->load(std::memory_order_acquire)) continue;
@@ -1632,7 +1634,7 @@ MultisampleTarget& acquire(const Context& context, const ColorTarget& requested,
target->use->hostOnly.store(true, std::memory_order_release);
guard(context, use, target->active, target->metadataValid, target->use, target);
target->ApplyFastClear(use);
return *target;
return target.get();
}
{
std::unique_lock lock(guardedMutex());
@@ -1659,8 +1661,13 @@ MultisampleTarget& acquire(const Context& context, const ColorTarget& requested,
target->ApplyFastClear(use);
collectFmaskWrites(target->target);
stampUse(*target->use, target->target.address, guardedColorBytes(target->target));
return *target;
return target.get();
}
return nullptr;
}
MultisampleTarget& acquire(const Context& context, const ColorTarget& requested, std::optional<VkClearColorValue> initialClear = std::nullopt, std::shared_ptr<Buffer> initialUpload = {}, std::vector<std::byte> initialBaseline = {}) {
if (auto* existing = acquireExisting(context, requested)) return *existing;
const auto& use = requested;
requireNoTextureHost(context, use);
auto target = std::make_shared<MultisampleTarget>(context, use, false, initialClear, std::move(initialUpload), std::move(initialBaseline));
@@ -2118,6 +2125,18 @@ VkImageView MultisampleTargetView(const Context& context, const ColorTarget& tar
return acquired.View(target.format);
}
bool RepeatMultisampleTargetView(const Context& context, const ColorTarget& target, const std::shared_ptr<void>& owner, VkImage image, VkImageView view) {
if (owner == nullptr || target.samples <= 1 || target.staged) return false;
storeEarlierStorageResults(target);
const DccPublication publication(target);
TargetsLock lock;
auto* existing = acquireExisting(context, target, static_cast<const MultisampleTarget*>(owner.get()), image);
if (existing == nullptr || existing->View(target.format) != view) return false;
existing->drawn = true;
++existing->contents;
return true;
}
void KeepMultisampleTarget_nid_no_patch(const std::shared_ptr<void>& owner) {
std::static_pointer_cast<MultisampleTarget>(owner)->Keep();
}
@@ -175,21 +175,27 @@ State drawState(const ColorTarget& color, const DrawOptions& options) {
return state;
}
void draw(AgcDriver::VulkanDevice& device, const ColorTarget& color, const DrawOptions& options = {}) {
struct CoverShaders {
ShaderRecompiler::RecompileResult vertex;
vertex.spirv = std::vector<std::uint32_t>(std::begin(COVER_VERT_SPV), std::end(COVER_VERT_SPV));
vertex.variantId = 1;
ShaderRecompiler::RecompileResult fragment;
fragment.spirv = std::vector<std::uint32_t>(std::begin(COVER_FRAG_SPV), std::end(COVER_FRAG_SPV));
fragment.variantId = 2;
const std::array<CompiledShader, 2> shaders{{
const std::array<CompiledShader, 2> stages{{
{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0},
{ShaderRecompiler::ShaderStage::Fragment, &fragment, 0}
}};
CoverShaders() {
vertex.spirv = std::vector<std::uint32_t>(std::begin(COVER_VERT_SPV), std::end(COVER_VERT_SPV));
vertex.variantId = 1;
fragment.spirv = std::vector<std::uint32_t>(std::begin(COVER_FRAG_SPV), std::end(COVER_FRAG_SPV));
fragment.variantId = 2;
}
};
void draw(AgcDriver::VulkanDevice& device, const ColorTarget& color, const DrawOptions& options = {}) {
const CoverShaders cover;
const auto state = drawState(color, options);
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
if (options.prepareOnly) SetDrawStopAfterResolveForTest(DrawStopForTest::ReturnAfterResolve);
device.Draw(state, {0, 3, 0, 1, 0, false}, shaders);
device.Draw(state, {0, 3, 0, 1, 0, false}, cover.stages);
}
bool memoSwitchedOff() {
@@ -1629,16 +1635,8 @@ void recipeViews(AgcDriver::VulkanDevice& device) {
colorB.surfaceAddress = colorB.address;
reset(device, colorA);
reset(device, colorB);
ShaderRecompiler::RecompileResult vertex;
vertex.spirv = std::vector<std::uint32_t>(std::begin(COVER_VERT_SPV), std::end(COVER_VERT_SPV));
vertex.variantId = 1;
ShaderRecompiler::RecompileResult fragment;
fragment.spirv = std::vector<std::uint32_t>(std::begin(COVER_FRAG_SPV), std::end(COVER_FRAG_SPV));
fragment.variantId = 2;
const std::array<CompiledShader, 2> shaders{{
{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0},
{ShaderRecompiler::ShaderStage::Fragment, &fragment, 0}
}};
const CoverShaders cover;
const auto& shaders = cover.stages;
const auto stateA = drawState(colorA, {});
const auto stateB = drawState(colorB, {});
const AgcDriver::Pm4::DrawParameters params{0, 3, 0, 1, 0, false};
@@ -1680,8 +1678,86 @@ void recipeViews(AgcDriver::VulkanDevice& device) {
expect(device, colorA, [](std::uint32_t x) { return leftOver(x, Old); }, "recipe draw after view change");
}
const std::array<std::pair<const char*, void (*)(AgcDriver::VulkanDevice&)>, 18> R3Scenarios{{
void multisampleRecipe(AgcDriver::VulkanDevice& device) {
auto color = colorTarget();
color.address = address(MultisampleStorage.data());
color.surfaceAddress = color.address;
color.samples = color.coverageSamples = 4;
const auto bytes = MultisampledColorBytes(color);
Require(bytes <= MultisampleStorage.size(), "multisample recipe storage is too small");
AgcDriver::GuestMemory::Write(color.address, std::vector<std::byte>(bytes));
AgcDriver::GuestMemory::BumpCollectEpoch();
auto state = drawState(color, {});
state.blend.blendEnable = VK_TRUE;
state.blend.srcColorBlendFactor = VK_BLEND_FACTOR_CONSTANT_COLOR;
state.blend.dstColorBlendFactor = VK_BLEND_FACTOR_ONE;
state.blend.srcAlphaBlendFactor = VK_BLEND_FACTOR_CONSTANT_ALPHA;
state.blend.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
state.blends = {state.blend};
state.blendConstants.fill(32.0f / 255.0f);
state.quadSampleMask.fill(0x5u);
const CoverShaders cover;
const AgcDriver::Pm4::DrawParameters draw{0, 3, 0, 1, 0, false};
std::shared_ptr<const AgcDriver::DrawRecipe> recipe;
unsigned draws = 0;
{
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
while (recipe == nullptr && draws < 3) {
device.Draw(state, draw, cover.stages, {}, &recipe);
++draws;
}
Require(recipe != nullptr, "the native multisample color draw did not build a recipe");
Require(device.DrawFromRecipe(state, draw, cover.stages, {}, recipe) == AgcDriver::RecipeOutcome::Recorded,
"the native multisample color draw did not replay");
++draws;
device.WaitIdle();
}
const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device);
const auto samples = ReadMultisampleTargetSamples_nid_no_patch(context, color);
Require(samples.size() == Width * Height * color.samples * 4u, "multisample recipe readback size");
for (unsigned pixel = 0; pixel < Width * Height; ++pixel) {
for (unsigned sample = 0; sample < color.samples; ++sample) {
std::uint32_t value;
std::memcpy(&value, samples.data() + (pixel * color.samples + sample) * sizeof(value), sizeof(value));
const auto expected = pixel % Width < LeftWidth && (sample == 0 || sample == 2) ? 32u * draws * 0x01010101u : 0u;
Require(value == expected, "multisample recipe changed sample " + std::to_string(sample) + " at pixel " + std::to_string(pixel));
}
}
const auto destination = colorTarget();
reset(device, destination);
ColorMetadataPass resolve{};
resolve.mode = ColorMetadataPass::Mode::Resolve;
resolve.source = color;
resolve.targets = {destination};
device.ColorMetadataPass(resolve);
expect(device, destination, [&](unsigned x) { return x < LeftWidth ? 16u * draws * 0x01010101u : 0u; }, "multisample recipe resolve");
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
device.WaitIdle();
const auto alias = MultisampleColorTargetOver(color.address, static_cast<std::size_t>(bytes));
Require(alias.has_value(), "the multisample test target has no live owner");
RetireMultisampleColorTarget(alias->active);
Require(device.DrawFromRecipe(state, draw, cover.stages, {}, recipe) == AgcDriver::RecipeOutcome::Rebuild,
"a recipe replayed a retired multisample attachment");
std::shared_ptr<const AgcDriver::DrawRecipe> replacement;
device.Draw(state, draw, cover.stages, {}, &replacement);
Require(replacement != nullptr, "the new multisample owner did not produce a replacement recipe");
Require(device.DrawFromRecipe(state, draw, cover.stages, {}, recipe) == AgcDriver::RecipeOutcome::Rebuild,
"a recipe replayed a replacement owner at the same guest address");
Require(device.DrawFromRecipe(state, draw, cover.stages, {}, replacement) == AgcDriver::RecipeOutcome::Recorded,
"the replacement owner's recipe did not record");
device.WaitIdle();
std::shared_ptr<void> heldOwner;
MultisampleTargetView(context, color, heldOwner);
ClearMultisampleTargets(context.device);
Require(device.DrawFromRecipe(state, draw, cover.stages, {}, replacement) == AgcDriver::RecipeOutcome::Rebuild,
"a live framebuffer owner remained replayable after the target list was cleared");
}
const std::array<std::pair<const char*, void (*)(AgcDriver::VulkanDevice&)>, 19> R3Scenarios{{
{"memo-order", memoOrder},
{"multisample-recipe", multisampleRecipe},
{"recipe-views", recipeViews},
{"untracked-dcc", untrackedDccClear},
{"untracked-cmask", untrackedCmaskClear},
@@ -83,13 +83,16 @@ if(BUILD_TESTING)
endif()
endforeach()
add_test(NAME agc_driver_target_memo_recipe_views COMMAND agc_driver_target_memo_tests --r3 recipe-views)
set_tests_properties(agc_driver_target_memo_recipe_views PROPERTIES
add_test(NAME agc_driver_multisample_color_recipe COMMAND agc_driver_target_memo_tests --r3 multisample-recipe)
set_tests_properties(agc_driver_multisample_color_recipe agc_driver_target_memo_recipe_views PROPERTIES
TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PROFILE_DRAW=1"
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1")
set_property(TEST agc_driver_target_memo_recipe_views APPEND PROPERTY ENVIRONMENT APS5_PROFILE_DRAW=1)
set_tests_properties(agc_driver_target_memo_recipe_views PROPERTIES
PASS_REGULAR_EXPRESSION "recipe views: pass attachment memo on.*target state memo tests passed"
FAIL_REGULAR_EXPRESSION "differ from the full lookup")
if(WIN32)
set_tests_properties(agc_driver_target_memo_recipe_views PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
set_tests_properties(agc_driver_multisample_color_recipe agc_driver_target_memo_recipe_views PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
if(NOT WIN32)
add_test(NAME agc_driver_target_memo_watched_imports COMMAND agc_driver_target_memo_tests)