| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823 |
- /*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
- #include <AzCore/RTTI/RTTI.h>
- #include <AzCore/std/string/conversions.h>
- #include <AtomCore/Instance/InstanceDatabase.h>
- #include <AtomCore/std/containers/vector_set.h>
- #include <Atom/RHI/FrameGraphAttachmentInterface.h>
- #include <Atom/RHI/FrameGraphBuilder.h>
- #include <Atom/RHI/RHIUtils.h>
- #include <Atom/RHI.Reflect/Base.h>
- #include <Atom/RPI.Public/Buffer/Buffer.h>
- #include <Atom/RPI.Public/Image/AttachmentImage.h>
- #include <Atom/RPI.Reflect/Image/Image.h>
- #include <Atom/RPI.Public/Pass/AttachmentReadback.h>
- #include <Atom/RPI.Public/Pass/ParentPass.h>
- #include <Atom/RPI.Public/Pass/Pass.h>
- #include <Atom/RPI.Public/Pass/PassLibrary.h>
- #include <Atom/RPI.Public/Pass/PassDefines.h>
- #include <Atom/RPI.Public/Pass/PassSystemInterface.h>
- #include <Atom/RPI.Public/Pass/PassUtils.h>
- #include <Atom/RPI.Public/Pass/Specific/ImageAttachmentPreviewPass.h>
- #include <Atom/RPI.Public/RenderPipeline.h>
- #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
- #include <Atom/RPI.Public/Image/AttachmentImagePool.h>
- #include <Atom/RPI.Reflect/Image/AttachmentImageAsset.h>
- #include <Atom/RPI.Reflect/Pass/PassRequest.h>
- #include <Atom/RPI.Reflect/Pass/PassTemplate.h>
- #include <Atom/RPI.Reflect/Pass/PassName.h>
- #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
- namespace AZ
- {
- namespace RPI
- {
- // --- Constructors ---
- Pass::Pass(const PassDescriptor& descriptor)
- : m_name(descriptor.m_passName)
- , m_path(descriptor.m_passName)
- {
- AZ_RPI_PASS_ASSERT((descriptor.m_passRequest == nullptr) || (descriptor.m_passTemplate != nullptr),
- "Pass::Pass - request is valid but template is nullptr. This is not allowed. Passing a valid passRequest also requires a valid passTemplate.");
- m_passData = PassUtils::GetPassDataPtr(descriptor);
- if (m_passData)
- {
- PassUtils::ExtractPipelineGlobalConnections(m_passData, m_pipelineGlobalConnections);
- m_viewTag = m_passData->m_pipelineViewTag;
- }
- m_flags.m_enabled = true;
- m_flags.m_timestampQueryEnabled = false;
- m_flags.m_pipelineStatisticsQueryEnabled = false;
- m_template = descriptor.m_passTemplate;
- if (descriptor.m_passRequest != nullptr)
- {
- // Assert m_template is the same as the one in the pass request
- if (PassValidation::IsEnabled())
- {
- const AZStd::shared_ptr<const PassTemplate> passTemplate = PassSystemInterface::Get()->GetPassTemplate(descriptor.m_passRequest->m_templateName);
- AZ_RPI_PASS_ASSERT(m_template == passTemplate, "Error: template in PassDescriptor doesn't match template from PassRequest!");
- }
- m_request = *descriptor.m_passRequest;
- m_flags.m_createdByPassRequest = true;
- m_flags.m_enabled = m_request.m_passEnabled;
- }
- PassSystemInterface::Get()->RegisterPass(this);
- QueueForBuildAndInitialization();
- // Skip reset since the pass just got created
- m_state = PassState::Reset;
- }
- Pass::~Pass()
- {
- AZ_RPI_BREAK_ON_TARGET_PASS;
- PassSystemInterface::Get()->UnregisterPass(this);
- }
- PassDescriptor Pass::GetPassDescriptor() const
- {
- PassDescriptor desc;
- desc.m_passName = m_name;
- desc.m_passTemplate = m_template ? PassSystemInterface::Get()->GetPassTemplate(m_template->m_name) : nullptr;
- if (m_flags.m_createdByPassRequest)
- {
- desc.m_passRequest = AZStd::make_shared<PassRequest>(m_request);
- }
- else
- {
- desc.m_passRequest.reset();
- }
-
- desc.m_passData = m_passData;
- return desc;
- }
- void Pass::SetEnabled(bool enabled)
- {
- m_flags.m_enabled = enabled;
- OnHierarchyChange();
- }
- // --- Error Logging ---
- void Pass::LogError(AZStd::string&& message)
- {
- #if AZ_RPI_ENABLE_PASS_DEBUGGING
- AZ::Debug::Trace::Instance().Break();
- #endif
- if (PassValidation::IsEnabled())
- {
- ++m_errors;
- if (m_errorMessages.size() < MessageLogLimit)
- {
- m_errorMessages.push_back(AZStd::move(message));
- }
- }
- }
- void Pass::LogWarning(AZStd::string&& message)
- {
- if (PassValidation::IsEnabled())
- {
- ++m_warnings;
- if (m_warningMessages.size() < MessageLogLimit)
- {
- m_warningMessages.push_back(AZStd::move(message));
- }
- }
- }
- // --- Hierarchy functions ---
- void Pass::OnHierarchyChange()
- {
- if (m_parent != nullptr)
- {
- // Set new tree depth and path
- m_flags.m_parentEnabled = m_parent->m_flags.m_enabled && (m_parent->m_flags.m_parentEnabled || m_parent->m_parent == nullptr);
- m_treeDepth = m_parent->m_treeDepth + 1;
- m_path = ConcatPassName(m_parent->m_path, m_name);
- m_flags.m_partOfHierarchy = m_parent->m_flags.m_partOfHierarchy;
- if (m_state == PassState::Orphaned)
- {
- QueueForBuildAndInitialization();
- }
- }
- AZ_RPI_BREAK_ON_TARGET_PASS;
- }
- void Pass::RemoveFromParent()
- {
- AZ_RPI_BREAK_ON_TARGET_PASS;
- AZ_RPI_PASS_ASSERT(m_parent != nullptr, "Trying to remove pass from parent but pointer to the parent pass is null.");
- m_parent->RemoveChild(Ptr<Pass>(this));
- m_queueState = PassQueueState::NoQueue;
- m_state = PassState::Orphaned;
- }
- void Pass::OnOrphan()
- {
- AZ_RPI_BREAK_ON_TARGET_PASS;
- if (m_flags.m_containsGlobalReference && m_pipeline != nullptr)
- {
- m_pipeline->RemovePipelineGlobalConnectionsFromPass(this);
- }
- m_parent = nullptr;
- m_flags.m_partOfHierarchy = false;
- m_treeDepth = 0;
- m_parentChildIndex = 0;
- m_queueState = PassQueueState::NoQueue;
- m_state = PassState::Orphaned;
- }
- ParentPass* Pass::AsParent()
- {
- return azrtti_cast<ParentPass*>(this);
- }
- const ParentPass* Pass::AsParent() const
- {
- return azrtti_cast<const ParentPass*>(this);
- }
- // --- Bindings ---
- PassAttachmentBinding& Pass::GetInputBinding(uint32_t index)
- {
- uint32_t bindingIndex = m_inputBindingIndices[index];
- return m_attachmentBindings[bindingIndex];
- }
- PassAttachmentBinding& Pass::GetInputOutputBinding(uint32_t index)
- {
- uint32_t bindingIndex = m_inputOutputBindingIndices[index];
- return m_attachmentBindings[bindingIndex];
- }
- PassAttachmentBinding& Pass::GetOutputBinding(uint32_t index)
- {
- uint32_t bindingIndex = m_outputBindingIndices[index];
- return m_attachmentBindings[bindingIndex];
- }
- void Pass::AddAttachmentBinding(PassAttachmentBinding attachmentBinding)
- {
- auto index = static_cast<uint8_t>(m_attachmentBindings.size());
- // Add the binding. This will assert if the fixed size array is full.
- m_attachmentBindings.push_back(attachmentBinding);
- // Add the index of the binding to the input, output or input/output list based on the slot type
- switch (attachmentBinding.m_slotType)
- {
- case PassSlotType::Input:
- m_inputBindingIndices.push_back(index);
- break;
- case PassSlotType::InputOutput:
- m_inputOutputBindingIndices.push_back(index);
- break;
- case PassSlotType::Output:
- m_outputBindingIndices.push_back(index);
- break;
- default:
- break;
- }
- }
- // --- Finders ---
- Ptr<Pass> Pass::FindAdjacentPass(const Name& passName)
- {
- // 1. Check This
- if (passName == PassNameThis)
- {
- return Ptr<Pass>(this);
- }
- // 2. Check Parent
- if (m_parent == nullptr)
- {
- return nullptr;
- }
- if (passName == PassNameParent || passName == m_parent->GetName())
- {
- return Ptr<Pass>(m_parent);
- }
- // 3. Check Siblings
- Ptr<Pass> foundPass = m_parent->FindChildPass(passName);
- // 4. Check Children
- if (!foundPass && AsParent())
- {
- foundPass = AsParent()->FindChildPass(passName);
- }
- // Finished search, return
- return foundPass;
- }
- PassAttachmentBinding* Pass::FindAttachmentBinding(const Name& slotName)
- {
- for (PassAttachmentBinding& binding : m_attachmentBindings)
- {
- if (slotName == binding.m_name)
- {
- return &binding;
- }
- }
- return nullptr;
- }
- const PassAttachmentBinding* Pass::FindAttachmentBinding(const Name& slotName) const
- {
- for (const PassAttachmentBinding& binding : m_attachmentBindings)
- {
- if (slotName == binding.m_name)
- {
- return &binding;
- }
- }
- return nullptr;
- }
- Ptr<PassAttachment> Pass::FindOwnedAttachment(const Name& attachmentName) const
- {
- for (const Ptr<PassAttachment>& attachment : m_ownedAttachments)
- {
- if (attachment->m_name == attachmentName)
- {
- return attachment;
- }
- }
- return nullptr;
- }
- Ptr<PassAttachment> Pass::FindAttachment(const Name& slotName) const
- {
- if (const PassAttachmentBinding* binding = FindAttachmentBinding(slotName))
- {
- return binding->GetAttachment();
- }
- return FindOwnedAttachment(slotName);
- }
- const PassAttachmentBinding* Pass::FindAdjacentBinding(const PassAttachmentRef& attachmentRef, [[maybe_unused]] const char* attachmentSourceTypeDebugName)
- {
- const PassAttachmentBinding* result = nullptr;
- if (attachmentRef.m_pass.IsEmpty() && attachmentRef.m_attachment.IsEmpty())
- {
- // The data isn't actually referencing anything, so this is not an error, just return null.
- return result;
- }
- if (attachmentRef.m_pass.IsEmpty() != attachmentRef.m_attachment.IsEmpty())
- {
- AZ_Error("Pass", false,
- "Invalid attachment reference (Pass [%s], Attachment [%s]). Both Pass and Attachment must be set.",
- attachmentRef.m_pass.GetCStr(), attachmentRef.m_attachment.GetCStr());
- return result;
- }
- // Find pass
- if (Ptr<Pass> pass = FindAdjacentPass(attachmentRef.m_pass))
- {
- // Find attachment within pass
- result = pass->FindAttachmentBinding(attachmentRef.m_attachment);
- }
- AZ_Error("Pass", result, "Pass [%s] could not find %s (Pass [%s], Attachment [%s])",
- m_path.GetCStr(), attachmentSourceTypeDebugName, attachmentRef.m_pass.GetCStr(), attachmentRef.m_attachment.GetCStr());
- return result;
- }
- // --- PassTemplate related functions ---
- void Pass::CreateBindingsFromTemplate()
- {
- if (m_template)
- {
- for (const PassSlot& slot : m_template->m_slots)
- {
- PassAttachmentBinding binding(slot);
- AddAttachmentBinding(binding);
- }
- }
- }
- void Pass::AttachBufferToSlot(AZStd::string_view slot, Data::Instance<Buffer> buffer)
- {
- AttachBufferToSlot(Name(slot), buffer);
- }
- void Pass::AttachBufferToSlot(const Name& slot, Data::Instance<Buffer> buffer)
- {
- if (!buffer)
- {
- return;
- }
- PassAttachmentBinding* localBinding = FindAttachmentBinding(slot);
- if (!localBinding)
- {
- AZ_RPI_PASS_ERROR(false, "Pass::AttachBufferToSlot - Pass [%s] failed to find slot [%s].",
- m_path.GetCStr(), slot.GetCStr());
- return;
- }
- // We can't handle the case that there is already an attachment attached yet.
- // We could consider to add it later if there are needs. It may require remove from the owned attachment list and
- // handle the connected bindings
- if (localBinding->GetAttachment())
- {
- AZ_RPI_PASS_ERROR(false, "Pass::AttachBufferToSlot - Slot [%s] already has attachment [%s].",
- slot.GetCStr(), localBinding->GetAttachment()->m_name.GetCStr());
- return;
- }
- PassBufferAttachmentDesc desc;
- desc.m_bufferDescriptor = buffer->GetRHIBuffer()->GetDescriptor();
- desc.m_lifetime = RHI::AttachmentLifetimeType::Imported;
- desc.m_name = buffer->GetAttachmentId();
- Ptr<PassAttachment> attachment = CreateAttachmentFromDesc(desc);
- attachment->m_importedResource = buffer;
- m_ownedAttachments.push_back(attachment);
- localBinding->SetOriginalAttachment(attachment);
- }
-
- void Pass::AttachImageToSlot(const Name& slot, Data::Instance<AttachmentImage> image)
- {
- PassAttachmentBinding* localBinding = FindAttachmentBinding(slot);
- if (!localBinding)
- {
- AZ_RPI_PASS_ERROR(false, "Pass::AttachImageToSlot - Pass [%s] failed to find slot [%s].",
- m_path.GetCStr(), slot.GetCStr());
- return;
- }
- // We can't handle the case that there is already an attachment attached yet.
- // We could consider to add it later if there are needs. It may require remove from the owned attachment list and
- // handle the connected bindings
- if (localBinding->GetAttachment())
- {
- AZ_RPI_PASS_ERROR(false, "Pass::AttachImageToSlot - Slot [%s] already has attachment [%s].",
- slot.GetCStr(), localBinding->GetAttachment()->m_name.GetCStr());
- return;
- }
- PassImageAttachmentDesc desc;
- desc.m_imageDescriptor = image->GetRHIImage()->GetDescriptor();
- desc.m_lifetime = RHI::AttachmentLifetimeType::Imported;
- desc.m_name = image->GetAttachmentId();
- Ptr<PassAttachment> attachment = CreateAttachmentFromDesc(desc);
- attachment->m_importedResource = image;
- m_ownedAttachments.push_back(attachment);
- localBinding->SetOriginalAttachment(attachment);
- }
- void Pass::ProcessConnection(const PassConnection& connection, uint32_t slotTypeMask)
- {
- [[maybe_unused]] auto prefix = [&]() -> AZStd::string
- {
- return AZStd::string::format(
- "Pass::ProcessConnection %s:%s -> %s:%s",
- m_path.GetCStr(),
- connection.m_localSlot.GetCStr(),
- connection.m_attachmentRef.m_pass.GetCStr(),
- connection.m_attachmentRef.m_attachment.GetCStr());
- };
- // -- Find Local Binding --
- // Get the input from this pass that forms one end of the connection
- PassAttachmentBinding* localBinding = FindAttachmentBinding(connection.m_localSlot);
- if (!localBinding)
- {
- AZ_RPI_PASS_ERROR(false, "%s: failed to find Local Slot.", prefix().c_str());
- return;
- }
- // Slot type mask used to skip connections at various stages of initialization
- uint32_t bindingMask = (1 << uint32_t(localBinding->m_slotType));
- if (!(bindingMask & slotTypeMask))
- {
- return;
- }
- // -- Local Variables --
- Name connectedPassName = connection.m_attachmentRef.m_pass;
- Name connectedSlotName = connection.m_attachmentRef.m_attachment;
- Ptr<PassAttachment> attachment = nullptr;
- PassAttachmentBinding* connectedBinding = nullptr;
- bool foundPass = false;
- bool slotTypeMismatch = false;
- // -- Search This Pass --
- if (connectedPassName == PassNameThis)
- {
- foundPass = true;
- attachment = FindOwnedAttachment(connectedSlotName);
- AZ_RPI_PASS_ERROR(
- attachment, "%s: Current Pass doesn't own an attachment named [%s].", prefix().c_str(), connectedSlotName.GetCStr());
- }
- // -- Search Pipeline --
- else if (connectedPassName == PipelineGlobalKeyword)
- {
- AZ_RPI_PASS_ERROR(m_pipeline != nullptr, "%s: Pass doesn't have a valid pipeline pointer.", prefix().c_str());
- foundPass = true; // Using the "Pipeline" keyword, no need to continue searching for passes
- if (m_pipeline)
- {
- const PipelineGlobalBinding* globalBinding = m_pipeline->GetPipelineGlobalConnection(connectedSlotName);
- if (globalBinding)
- {
- connectedBinding = globalBinding->m_binding;
- }
- AZ_RPI_PASS_ERROR(connectedBinding, "%s: Cannot find pipeline global connection.", prefix().c_str());
- }
- }
- // -- Search Parent & Siblings --
- // The (connectedPassName != m_name) avoids edge case where parent pass has child pass of same name.
- // In this case, parent pass would ask it's parent pass for a sibling with the given name and get a pointer to itself.
- // It would then try to connect to itself, which is obviously not the intention of the user
- if (!foundPass && m_parent && connectedPassName != m_name)
- {
- if (connectedPassName == PassNameParent)
- {
- foundPass = true;
- connectedBinding = m_parent->FindAttachmentBinding(connectedSlotName);
- if (!connectedBinding)
- {
- attachment = m_parent->FindOwnedAttachment(connectedSlotName);
- }
- else
- {
- slotTypeMismatch = connectedBinding->m_slotType != localBinding->m_slotType &&
- connectedBinding->m_slotType != PassSlotType::InputOutput &&
- localBinding->m_slotType != PassSlotType::InputOutput;
- }
- }
- else
- {
- // Use the connection Name to find a sibling pass
- Ptr<Pass> siblingPass = m_parent->FindChildPass(connectedPassName);
- if (siblingPass)
- {
- foundPass = true;
- connectedBinding = siblingPass->FindAttachmentBinding(connectedSlotName);
- slotTypeMismatch = connectedBinding != nullptr &&
- connectedBinding->m_slotType == localBinding->m_slotType &&
- connectedBinding->m_slotType != PassSlotType::InputOutput;
- }
- }
- }
- // -- Search Children --
- ParentPass* asParent = AsParent();
- if (!foundPass && asParent)
- {
- Ptr<Pass> childPass = asParent->FindChildPass(connectedPassName);
- if (childPass)
- {
- foundPass = true;
- connectedBinding = childPass->FindAttachmentBinding(connectedSlotName);
- slotTypeMismatch = connectedBinding != nullptr &&
- connectedBinding->m_slotType != localBinding->m_slotType &&
- connectedBinding->m_slotType != PassSlotType::InputOutput &&
- localBinding->m_slotType != PassSlotType::InputOutput;
- }
- }
- // -- Finalize & Report Errors --
- if (slotTypeMismatch)
- {
- AZ_RPI_PASS_ERROR(
- false,
- "%s: Slot Type Mismatch - When connecting to a child slot, both slots must be of the same type, or one must be "
- "InputOutput.",
- prefix().c_str());
- connectedBinding = nullptr;
- }
- if (connectedBinding)
- {
- localBinding->m_connectedBinding = connectedBinding;
- UpdateConnectedBinding(*localBinding);
- }
- else if (attachment)
- {
- localBinding->SetOriginalAttachment(attachment);
- }
- else
- {
- if (!m_flags.m_partOfHierarchy)
- {
- // [GFX TODO][ATOM-13693]: REMOVE POST R1 - passes not in hierarchy should no longer have this function called
- // When view is changing, removal of the passes can occur (cascade shadow passes for example)
- // resulting in temporary orphan passes that will be removed over the next frame.
- AZ_RPI_PASS_WARNING(false, "%s: Pass is no longer part of the hierarchy and about to be removed.", prefix().c_str());
- }
- else if (foundPass)
- {
- AZ_RPI_PASS_ERROR(false, "%s: Could not find binding on target.", prefix().c_str());
- }
- else
- {
- AZ_RPI_PASS_ERROR(false, "%s: Could not find target pass.", prefix().c_str());
- }
- }
- }
- void Pass::ProcessFallbackConnection(const PassFallbackConnection& connection)
- {
- PassAttachmentBinding* inputBinding = FindAttachmentBinding(connection.m_inputSlotName);
- PassAttachmentBinding* outputBinding = FindAttachmentBinding(connection.m_outputSlotName);
- [[maybe_unused]] auto prefix = [&]() -> AZStd::string
- {
- return AZStd::string::format(
- "Pass::ProcessFallbackConnection: %s, %s -> %s",
- m_path.GetCStr(),
- connection.m_inputSlotName.GetCStr(),
- connection.m_outputSlotName.GetCStr());
- };
- if (!outputBinding || !inputBinding)
- {
- AZ_RPI_PASS_ERROR(inputBinding, "%s: failed to find input slot.", prefix().c_str());
- AZ_RPI_PASS_ERROR(outputBinding, "%s: failed to find output slot.", prefix().c_str());
- return;
- }
- bool typesAreValid = inputBinding->m_slotType == PassSlotType::Input && outputBinding->m_slotType == PassSlotType::Output;
- if (!typesAreValid)
- {
- AZ_RPI_PASS_ERROR(
- inputBinding->m_slotType == PassSlotType::Input, "%s: Input doesn't have SlotType::Input.", prefix().c_str());
- AZ_RPI_PASS_ERROR(
- outputBinding->m_slotType == PassSlotType::Output, "%s: Output doesn't have SlotType::Output.", prefix().c_str());
- return;
- }
- outputBinding->m_fallbackBinding = inputBinding;
- UpdateConnectedBinding(*outputBinding);
- }
- template<typename AttachmentDescType>
- Ptr<PassAttachment> Pass::CreateAttachmentFromDesc(const AttachmentDescType& desc)
- {
- Ptr<PassAttachment> attachment = aznew PassAttachment(desc);
- // If the attachment is imported, we will create the resource (buffer or image) of this attachment
- // from asset referenced in m_assetRef
- // The resource instance will be saved in m_importedResource and the attachment id is acquired from resource instance
- if (desc.m_lifetime == RHI::AttachmentLifetimeType::Imported)
- {
- attachment->m_path = desc.m_name;
- if (attachment->m_descriptor.m_type == RHI::AttachmentType::Buffer)
- {
- Data::Asset<BufferAsset> bufferAsset = AssetUtils::LoadAssetById<BufferAsset>(desc.m_assetRef.m_assetId, AssetUtils::TraceLevel::None);
- if (bufferAsset.IsReady())
- {
- Data::Instance<Buffer> buffer = Buffer::FindOrCreate(bufferAsset);
- if (buffer)
- {
- attachment->m_path = buffer->GetAttachmentId();
- attachment->m_importedResource = buffer;
- attachment->m_descriptor = buffer->GetRHIBuffer()->GetDescriptor();
- }
- }
- }
- else if (attachment->m_descriptor.m_type == RHI::AttachmentType::Image)
- {
- Data::Asset<AttachmentImageAsset> imageAsset = AssetUtils::LoadAssetById<AttachmentImageAsset>(desc.m_assetRef.m_assetId, AssetUtils::TraceLevel::None);
- if (imageAsset.IsReady())
- {
- Data::Instance<AttachmentImage> image = AttachmentImage::FindOrCreate(imageAsset);
- if (image)
- {
- attachment->m_path = image->GetAttachmentId();
- attachment->m_importedResource = image;
- attachment->m_descriptor = image->GetDescriptor();
- }
- }
- }
- else
- {
- AZ_RPI_PASS_ASSERT(false, "Unsupported imported attachment type");
- }
- }
- else
- {
- // Only apply path name to transient attachment. Keep the original name for imported attachment
- attachment->ComputePathName(m_path);
- }
- // Setup attachment sources...
- if (desc.m_sizeSource.m_source.m_pass == PipelineKeyword) // if source is pipeline
- {
- attachment->m_renderPipelineSource = m_pipeline;
- attachment->m_getSizeFromPipeline = true;
- attachment->m_sizeMultipliers = desc.m_sizeSource.m_multipliers;
- }
- else if (const PassAttachmentBinding* source = FindAdjacentBinding(desc.m_sizeSource.m_source, "SizeSource"))
- {
- attachment->m_sizeSource = source;
- attachment->m_sizeMultipliers = desc.m_sizeSource.m_multipliers;
- }
- if (desc.m_formatSource.m_pass == PipelineKeyword) // if source is pipeline
- {
- attachment->m_renderPipelineSource = m_pipeline;
- attachment->m_getFormatFromPipeline = true;
- }
- else if (const PassAttachmentBinding* source = FindAdjacentBinding(desc.m_formatSource, "FormatSource"))
- {
- attachment->m_formatSource = source;
- }
- if (desc.m_multisampleSource.m_pass == PipelineKeyword) // if source is pipeline
- {
- attachment->m_renderPipelineSource = m_pipeline;
- attachment->m_getMultisampleStateFromPipeline = true;
- }
- else if (const PassAttachmentBinding* source = FindAdjacentBinding(desc.m_multisampleSource, "MultisampleSource"))
- {
- attachment->m_multisampleSource = source;
- }
- if (const PassAttachmentBinding* source = FindAdjacentBinding(desc.m_arraySizeSource, "ArraySizeSource"))
- {
- attachment->m_arraySizeSource = source;
- }
- attachment->m_ownerPass = this;
- return attachment;
- }
- template<typename AttachmentDescType>
- void Pass::OverrideOrAddAttachment(const AttachmentDescType& desc)
- {
- bool overrideAttachment = false;
- // Search existing attachments
- for (size_t i = 0; i < m_ownedAttachments.size(); ++i)
- {
- // If we find one with the same name
- if (m_ownedAttachments[i]->m_name == desc.m_name)
- {
- // Override it
- m_ownedAttachments[i] = CreateAttachmentFromDesc(desc);
- overrideAttachment = true;
- break;
- }
- }
- // If we didn't override any attachments
- if (!overrideAttachment)
- {
- // Create a new one
- m_ownedAttachments.emplace_back(CreateAttachmentFromDesc(desc));
- }
- }
- void Pass::SetupInputsFromRequest()
- {
- if (m_flags.m_createdByPassRequest)
- {
- const uint32_t slotTypeMask = (1 << uint32_t(PassSlotType::Input)) | (1 << uint32_t(PassSlotType::InputOutput));
- for (const PassConnection& connection : m_request.m_connections)
- {
- ProcessConnection(connection, slotTypeMask);
- }
- }
- }
- void Pass::SetupOutputsFromRequest()
- {
- if (m_flags.m_createdByPassRequest)
- {
- const uint32_t slotTypeMask = (1 << uint32_t(PassSlotType::Output));
- for (const PassConnection& connection : m_request.m_connections)
- {
- ProcessConnection(connection, slotTypeMask);
- }
- }
- }
- void Pass::SetupPassDependencies()
- {
- // Get dependencies declared in the PassRequest
- if (m_flags.m_createdByPassRequest)
- {
- for (const Name& passName : m_request.m_executeAfterPasses)
- {
- Ptr<Pass> executeAfterPass = FindAdjacentPass(passName);
- if (executeAfterPass != nullptr)
- {
- m_executeAfterPasses.push_back(executeAfterPass.get());
- }
- }
- for (const Name& passName : m_request.m_executeBeforePasses)
- {
- Ptr<Pass> executeBeforePass = FindAdjacentPass(passName);
- if (executeBeforePass != nullptr)
- {
- m_executeBeforePasses.push_back(executeBeforePass.get());
- }
- }
- }
- // Inherit dependencies from ParentPass
- if (m_parent)
- {
- for (Pass* pass : m_parent->m_executeAfterPasses)
- {
- m_executeAfterPasses.push_back(pass);
- }
- for (Pass* pass : m_parent->m_executeBeforePasses)
- {
- m_executeBeforePasses.push_back(pass);
- }
- }
- }
- void Pass::SetupInputsFromTemplate()
- {
- if (m_template)
- {
- const uint32_t slotTypeMask = (1 << uint32_t(PassSlotType::Input)) | (1 << uint32_t(PassSlotType::InputOutput));
- for (const PassConnection& outputConnection : m_template->m_connections)
- {
- ProcessConnection(outputConnection, slotTypeMask);
- }
- }
- }
- void Pass::SetupOutputsFromTemplate()
- {
- if (m_template)
- {
- const uint32_t slotTypeMask = (1 << uint32_t(PassSlotType::Output));
- for (const PassConnection& outputConnection : m_template->m_connections)
- {
- ProcessConnection(outputConnection, slotTypeMask);
- }
- for (const PassFallbackConnection& fallbackConnection : m_template->m_fallbackConnections)
- {
- ProcessFallbackConnection(fallbackConnection);
- }
- }
- }
- void Pass::CreateAttachmentsFromTemplate()
- {
- if (m_template)
- {
- // Create image attachments
- for (const PassImageAttachmentDesc& desc : m_template->m_imageAttachments)
- {
- m_ownedAttachments.emplace_back(CreateAttachmentFromDesc(desc));
- }
- // Create buffer attachments
- for (const PassBufferAttachmentDesc& desc : m_template->m_bufferAttachments)
- {
- m_ownedAttachments.emplace_back(CreateAttachmentFromDesc(desc));
- }
- }
- }
- void Pass::CreateAttachmentsFromRequest()
- {
- if (m_flags.m_createdByPassRequest)
- {
- // Create image attachments
- for (const PassImageAttachmentDesc& desc : m_request.m_imageAttachmentOverrides)
- {
- OverrideOrAddAttachment(desc);
- }
- // Create buffer attachments
- for (const PassBufferAttachmentDesc& desc : m_request.m_bufferAttachmentOverrides)
- {
- OverrideOrAddAttachment(desc);
- }
- }
- }
- // --- Attachment and Binding related functions ---
- void Pass::StoreImportedAttachmentReferences()
- {
- m_importedAttachmentStore.clear();
- for (const Ptr<PassAttachment>& attachment : m_ownedAttachments)
- {
- if (attachment->m_lifetime == RHI::AttachmentLifetimeType::Imported)
- {
- m_importedAttachmentStore.push_back(attachment);
- }
- }
- }
- void Pass::CreateTransientAttachments(RHI::FrameGraphAttachmentInterface attachmentDatabase)
- {
- for (const Ptr<PassAttachment>& attachment : m_ownedAttachments)
- {
- if (attachment->m_lifetime == RHI::AttachmentLifetimeType::Transient)
- {
- switch (attachment->m_descriptor.m_type)
- {
- case RHI::AttachmentType::Image:
- attachmentDatabase.CreateTransientImage(attachment->GetTransientImageDescriptor());
- break;
- case RHI::AttachmentType::Buffer:
- attachmentDatabase.CreateTransientBuffer(attachment->GetTransientBufferDescriptor());
- break;
- default:
- AZ_RPI_PASS_ASSERT(false, "Error, transient attachment is neither an image nor a buffer!");
- break;
- }
- }
- }
- }
- void Pass::ImportAttachments(RHI::FrameGraphAttachmentInterface attachmentDatabase)
- {
- for (const Ptr<PassAttachment>& attachment : m_ownedAttachments)
- {
- if (attachment->m_lifetime == RHI::AttachmentLifetimeType::Imported)
- {
- // make sure to only import the resource one time
- RHI::AttachmentId attachmentId = attachment->GetAttachmentId();
- const RHI::FrameAttachment* currentAttachment = attachmentDatabase.FindAttachment(attachmentId);
- if (azrtti_istypeof<Image>(attachment->m_importedResource.get()))
- {
- Image* image = static_cast<Image*>(attachment->m_importedResource.get());
- if (currentAttachment == nullptr)
- {
- attachmentDatabase.ImportImage(attachmentId, image->GetRHIImage());
- }
- else
- {
- AZ_Assert(currentAttachment->GetResource() == image->GetRHIImage(),
- "Importing image attachment named \"%s\" but a different attachment with the "
- "same name already exists in the database.\n", attachmentId.GetCStr());
- }
- }
- else if (azrtti_istypeof<Buffer>(attachment->m_importedResource.get()))
- {
- Buffer* buffer = static_cast<Buffer*>(attachment->m_importedResource.get());
- if (currentAttachment == nullptr)
- {
- attachmentDatabase.ImportBuffer(attachmentId, buffer->GetRHIBuffer());
- }
- else
- {
- AZ_Assert(currentAttachment->GetResource() == buffer->GetRHIBuffer(),
- "Importing buffer attachment named \"%s\" but a different attachment with the "
- "same name already exists in the database.\n", attachmentId.GetCStr());
- }
- }
- else
- {
- AZ_RPI_PASS_ERROR(false, "Can't import unknown resource type");
- }
- }
- }
- }
- void Pass::UpdateAttachmentUsageIndices()
- {
- // We want to find attachments that are used more than once by the same pass
- // An example of this could be reading from and writing to different mips of the same texture
- // Loop over all attachments bound to this pass
- size_t size = m_attachmentBindings.size();
- for (size_t i = 0; i < size; ++i)
- {
- PassAttachmentBinding& binding01 = m_attachmentBindings[i];
- // For the outer loop, only consider bindings which are the
- // first occurrence of their given attachment in the pass
- if (binding01.m_attachmentUsageIndex != 0)
- {
- continue;
- }
- // Loop over all subsequent bindings in the pass
- uint8_t duplicateCount = 0;
- for (size_t j = i + 1; j < size; ++j)
- {
- PassAttachmentBinding& binding02 = m_attachmentBindings[j];
- // Bindings are considered having the same attachment if they are connected to the same binding...
- bool haveSameConnection = binding01.m_connectedBinding == binding02.m_connectedBinding;
- haveSameConnection = haveSameConnection && binding01.m_connectedBinding != nullptr;
- // ... Or if they point to the same attachment
- bool isSameAttachment = binding01.GetAttachment() == binding02.GetAttachment();
- isSameAttachment = isSameAttachment && binding01.GetAttachment() != nullptr;
- // If binding 01 and binding 02 have the same attachment, update the attachment usage index on binding 02
- if (haveSameConnection || isSameAttachment)
- {
- binding02.m_attachmentUsageIndex = ++duplicateCount;
- }
- }
- }
- }
- void Pass::UpdateOwnedAttachments()
- {
- // Update the output attachments to coincide with their source attachments (if specified)
- // This involves getting the format and calculating the size from the source attachment
- for (Ptr<PassAttachment>& attachment: m_ownedAttachments)
- {
- attachment->Update();
- }
- }
- void Pass::UpdateConnectedBinding(PassAttachmentBinding& binding)
- {
- bool useFallback = (m_state != PassState::Building && !IsEnabled());
- binding.UpdateConnection(useFallback);
- }
- void Pass::UpdateConnectedBindings()
- {
- // Depending on whether a pass is enabled or not, it may switch it's bindings to become a pass-through
- // For this reason we update connecting bindings on a per-frame basis
- for (PassAttachmentBinding& binding : m_attachmentBindings)
- {
- UpdateConnectedBinding(binding);
- }
- }
- void Pass::RegisterPipelineGlobalConnections()
- {
- if (!m_pipeline)
- {
- AZ_RPI_PASS_ERROR(m_pipelineGlobalConnections.size() == 0,
- "Pass::RegisterPipelineGlobalConnections() - PipelineGlobal connections specified but no pipeline set on pass [%s]",
- m_path.GetCStr());
- }
- for (const PipelineGlobalConnection& connection : m_pipelineGlobalConnections)
- {
- PassAttachmentBinding* binding = FindAttachmentBinding(connection.m_localBinding);
- AZ_RPI_PASS_ERROR(binding != nullptr, "Pass::RegisterPipelineGlobalConnections() - Could not find local binding [%s]",
- connection.m_localBinding.GetCStr());
- if (binding)
- {
- m_pipeline->AddPipelineGlobalConnection(connection.m_globalName, binding, this);
- }
- }
- m_flags.m_containsGlobalReference = (m_pipelineGlobalConnections.size() > 0);
- }
- // --- Queuing functions with PassSystem ---
- void Pass::QueueForBuildAndInitialization()
- {
- // Don't queue if we're currently building. Don't queue if we're already queued for Build or Removal
- if (m_state != PassState::Building &&
- m_queueState != PassQueueState::QueuedForBuildAndInitialization &&
- m_queueState != PassQueueState::QueuedForRemoval)
- {
- // NOTE: We only queue for Build here, the queue for Initialization happens at the end of Pass::Build
- // (doing it this way is an optimization to minimize the number of passes queued for initialization,
- // as many passes will be initialized by their parent passes and thus don't need to be queued)
- PassSystemInterface::Get()->QueueForBuild(this);
- m_queueState = PassQueueState::QueuedForBuildAndInitialization;
- // Transition state
- // If we are Rendering, the state will transition [Rendering -> Queued] in Pass::FrameEnd
- // TODO: the PassState::Reset check is a quick fix until the pass concurrency with multiple scenes issue is fixed
- if (m_state != PassState::Rendering && m_state != PassState::Reset)
- {
- m_state = PassState::Queued;
- }
- }
- }
- void Pass::QueueForInitialization()
- {
- // Only queue if the pass is not in any queue. Don't queue if we're currently initializing.
- if (m_queueState == PassQueueState::NoQueue && m_state != PassState::Initializing)
- {
- PassSystemInterface::Get()->QueueForInitialization(this);
- m_queueState = PassQueueState::QueuedForInitialization;
- // Transition state
- // If we are Rendering, the state will transition [Rendering -> Queued] in Pass::FrameEnd
- // If the state is Built, preserve the state since [Built -> Initializing] is a valid transition
- // Preserving PassState::Built lets the pass ignore subsequent build calls in the same frame
- if (m_state != PassState::Rendering && m_state != PassState::Built)
- {
- m_state = PassState::Queued;
- }
- }
- }
- void Pass::QueueForRemoval()
- {
- // Skip only if we're already queued for removal, otherwise proceed.
- // QueuedForRemoval overrides QueuedForBuildAndInitialization and QueuedForInitialization.
- if (m_queueState != PassQueueState::QueuedForRemoval)
- {
- PassSystemInterface::Get()->QueueForRemoval(this);
- m_queueState = PassQueueState::QueuedForRemoval;
- // Transition state
- // If we are Rendering, the state will transition [Rendering -> Queued] in Pass::FrameEnd
- if (m_state != PassState::Rendering)
- {
- m_state = PassState::Queued;
- }
- }
- }
- // --- Pass behavior functions ---
- void Pass::Reset()
- {
- AZ_RPI_BREAK_ON_TARGET_PASS;
- // Ensure we're in a valid state to reset. This ensures the pass won't be reset multiple times in the same frame.
- bool execute = (m_state == PassState::Idle);
- execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForBuildAndInitialization);
- execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization);
- if (!execute)
- {
- return;
- }
- m_state = PassState::Resetting;
- if (m_flags.m_isPipelineRoot)
- {
- m_pipeline->ClearGlobalBindings();
- }
- // Store references to imported attachments to underlying images and buffers aren't deleted during attachment building
- StoreImportedAttachmentReferences();
- // Clear lists
- m_inputBindingIndices.clear();
- m_inputOutputBindingIndices.clear();
- m_outputBindingIndices.clear();
- m_attachmentBindings.clear();
- m_ownedAttachments.clear();
- m_executeAfterPasses.clear();
- m_executeBeforePasses.clear();
- ResetInternal();
- m_state = PassState::Reset;
- }
- void Pass::Build(bool calledFromPassSystem)
- {
- AZ_RPI_BREAK_ON_TARGET_PASS;
- // Ensure we're in a valid state to build. This ensures the pass won't be built multiple times in the same frame.
- bool execute = (m_state == PassState::Reset);
- if (!execute)
- {
- return;
- }
- m_state = PassState::Building;
- // Bindings, inputs and attachments
- CreateBindingsFromTemplate();
- RegisterPipelineGlobalConnections();
- SetupPassDependencies();
- CreateAttachmentsFromTemplate();
- CreateAttachmentsFromRequest();
- SetupInputsFromTemplate();
- SetupInputsFromRequest();
- // Custom pass behavior
- BuildInternal();
- // Outputs
- SetupOutputsFromTemplate();
- SetupOutputsFromRequest();
- // Update
- UpdateConnectedBindings();
- UpdateOwnedAttachments();
- UpdateAttachmentUsageIndices();
- m_state = PassState::Built;
- m_queueState = PassQueueState::NoQueue;
- // If this pass's Build() wasn't called from the Pass System, then it was called by it's parent pass
- // In which case we don't need to queue for initialization because the parent will already be queued
- if (calledFromPassSystem)
- {
- // Queue for Initialization
- QueueForInitialization();
- }
- }
- void Pass::Initialize()
- {
- AZ_RPI_BREAK_ON_TARGET_PASS;
- // Ensure we're in a valid state to initialize. This ensures the pass won't be initialized multiple times in the same frame.
- bool execute = (m_state == PassState::Idle || m_state == PassState::Built);
- execute = execute || (m_state == PassState::Queued && m_queueState == PassQueueState::QueuedForInitialization);
- if (!execute)
- {
- return;
- }
- m_state = PassState::Initializing;
- m_queueState = PassQueueState::NoQueue;
- InitializeInternal();
-
- // Need to recreate the dest attachment because the source attachment might be changed
- if (!m_attachmentCopy.expired())
- {
- m_attachmentCopy.lock()->InvalidateDestImage();
- }
- m_state = PassState::Initialized;
- }
- void Pass::OnInitializationFinished()
- {
- m_flags.m_alreadyCreatedChildren = false;
- m_importedAttachmentStore.clear();
- OnInitializationFinishedInternal();
- m_state = PassState::Idle;
- }
- void Pass::Validate(PassValidationResults& validationResults)
- {
- if (PassValidation::IsEnabled())
- {
- // Log passes with missing input
- for (uint8_t idx : m_inputBindingIndices)
- {
- if (!m_attachmentBindings[idx].GetAttachment())
- {
- validationResults.m_passesWithMissingInputs.push_back(this);
- break;
- }
- }
- // Log passes with missing input/output
- for (uint8_t idx : m_inputOutputBindingIndices)
- {
- if (!m_attachmentBindings[idx].GetAttachment())
- {
- validationResults.m_passesWithMissingInputOutputs.push_back(this);
- break;
- }
- }
- // Log passes with missing output (note that missing output connections are not considered an error)
- for (uint8_t idx : m_outputBindingIndices)
- {
- if (!m_attachmentBindings[idx].GetAttachment())
- {
- validationResults.m_passesWithMissingOutputs.push_back(this);
- break;
- }
- }
- if (m_errorMessages.size() > 0)
- {
- validationResults.m_passesWithErrors.push_back(this);
- }
- if (m_warningMessages.size() > 0)
- {
- validationResults.m_passesWithWarnings.push_back(this);
- }
- }
- }
- void Pass::FrameBegin(FramePrepareParams params)
- {
- AZ_RPI_BREAK_ON_TARGET_PASS;
- bool earlyOut = !IsEnabled();
- // Skip if this pass is the root of the pipeline and the pipeline is set to not render
- if (m_flags.m_isPipelineRoot)
- {
- AZ_RPI_PASS_ASSERT(m_pipeline != nullptr, "Pass is flagged as a pipeline root but it's pipeline pointer is invalid while trying to render");
- earlyOut = earlyOut || m_pipeline == nullptr || m_pipeline->GetRenderMode() == RenderPipeline::RenderMode::NoRender;
- }
- if (earlyOut)
- {
- return;
- }
- AZ_Error("PassSystem", m_state == PassState::Idle,
- "Pass::FrameBegin - Pass [%s] is attempting to render, and should be in the 'Idle' or 'Queued' state, but is in the '%s' state.",
- m_path.GetCStr(), ToString(m_state).data());
- m_state = PassState::Rendering;
- UpdateOwnedAttachments();
- CreateTransientAttachments(params.m_frameGraphBuilder->GetAttachmentDatabase());
- ImportAttachments(params.m_frameGraphBuilder->GetAttachmentDatabase());
- // readback attachment with input state
- UpdateReadbackAttachment(params, true);
- // FrameBeginInternal needs to be the last function be called in FrameBegin because its implementation expects
- // all the attachments are imported to database (for example, ImageAttachmentPreview)
- FrameBeginInternal(params);
-
- // readback attachment with output state
- UpdateReadbackAttachment(params, false);
- // update attachment copy for preview
- UpdateAttachmentCopy(params);
- }
- void Pass::FrameEnd()
- {
- if (m_state == PassState::Rendering)
- {
- FrameEndInternal();
- m_state = (m_queueState == PassQueueState::NoQueue) ? PassState::Idle : PassState::Queued;
- }
- }
- // --- RenderPipeline, PipelineViewTag and DrawListTag ---
-
- RHI::DrawListTag Pass::GetDrawListTag() const
- {
- static RHI::DrawListTag invalidTag;
- return invalidTag;
- }
- const PipelineViewTag& Pass::GetPipelineViewTag() const
- {
- if (m_viewTag.IsEmpty())
- {
- if (m_flags.m_isPipelineRoot && m_pipeline)
- {
- return m_pipeline->GetMainViewTag();
- }
- else if (m_parent)
- {
- return m_parent->GetPipelineViewTag();
- }
- }
- return m_viewTag;
- }
- void Pass::SetRenderPipeline(RenderPipeline* pipeline)
- {
- AZ_Assert(!m_pipeline || !pipeline || m_pipeline == pipeline,
- "Switching passes between pipelines is not supported and may result in undefined behavior");
- if (m_pipeline != pipeline)
- {
- m_pipeline = pipeline;
- // Re-queue for new pipeline.
- if (m_pipeline != nullptr)
- {
- PassState currentState = m_state;
- m_queueState = PassQueueState::NoQueue;
- QueueForBuildAndInitialization();
- if (currentState == PassState::Reset)
- {
- m_state = PassState::Reset;
- }
- }
- }
- }
-
- void Pass::ManualPipelineBuildAndInitialize()
- {
- Build();
- Initialize();
- OnInitializationFinished();
- }
- Scene* Pass::GetScene() const
- {
- if (m_pipeline)
- {
- return m_pipeline->GetScene();
- }
- return nullptr;
- }
- PassTree* Pass::GetPassTree() const
- {
- return m_pipeline ? &(m_pipeline->m_passTree) : nullptr;
- }
- void Pass::GetViewDrawListInfo(RHI::DrawListMask& outDrawListMask, PassesByDrawList& outPassesByDrawList, const PipelineViewTag& viewTag) const
- {
- // NOTE: we always collect the draw list mask regardless if the pass enabled or not. The reason is we want to keep the view information
- // even when pass is disabled so it can continue work correctly when re-enable it.
- // Only get the DrawListTag if this pass has a DrawListTag and it's PipelineViewId matches
- if (BindViewSrg() && HasDrawListTag() && GetPipelineViewTag() == viewTag)
- {
- RHI::DrawListTag drawListTag = GetDrawListTag();
- if (drawListTag.IsValid() && outPassesByDrawList.find(drawListTag) == outPassesByDrawList.end())
- {
- outPassesByDrawList[drawListTag] = this;
- outDrawListMask.set(drawListTag.GetIndex());
- }
- }
- }
- void Pass::GetPipelineViewTags(PipelineViewTags& outTags) const
- {
- if (BindViewSrg())
- {
- outTags.insert(GetPipelineViewTag());
- }
- }
- void Pass::SortDrawList(RHI::DrawList& drawList) const
- {
- if (!drawList.empty())
- {
- RHI::SortDrawList(drawList, m_drawListSortType);
- }
- }
- // --- Debug & Validation functions ---
- bool PassValidationResults::IsValid()
- {
- if (PassValidation::IsEnabled())
- {
- // Pass validation fail if there are any passes with build errors or missing inputs (or input/outputs)
- return (m_passesWithErrors.size() == 0) && (m_passesWithMissingInputs.size() == 0) && (m_passesWithMissingInputOutputs.size() == 0);
- }
- else
- {
- return true;
- }
- }
- TimestampResult Pass::GetLatestTimestampResult() const
- {
- return GetTimestampResultInternal();
- }
- PipelineStatisticsResult Pass::GetLatestPipelineStatisticsResult() const
- {
- return GetPipelineStatisticsResultInternal();
- }
- bool Pass::ReadbackAttachment(AZStd::shared_ptr<AttachmentReadback> readback, uint32_t readbackIndex, const Name& slotName
- , PassAttachmentReadbackOption option, const RHI::ImageSubresourceRange* mipsRange)
- {
- // Return false if it's already readback
- if (m_attachmentReadback)
- {
- AZ_Warning("Pass", false, "ReadbackAttachment: skip readback pass [%s] slot [%s] because there is an another active readback", m_path.GetCStr(), slotName.GetCStr());
- return false;
- }
- uint32_t bindingIndex = 0;
- for (auto& binding : m_attachmentBindings)
- {
- if (slotName == binding.m_name)
- {
- RHI::AttachmentType type = binding.GetAttachment()->GetAttachmentType();
- if (type == RHI::AttachmentType::Buffer || type == RHI::AttachmentType::Image)
- {
- RHI::AttachmentId attachmentId = binding.GetAttachment()->GetAttachmentId();
- // Append slot index and pass name so the read back's name won't be same as the attachment used in other passes.
- AZStd::string readbackName = AZStd::string::format("%s_%d_%d_%s", attachmentId.GetCStr(),
- readbackIndex, bindingIndex, GetName().GetCStr());
- if (readback->ReadPassAttachment(binding.GetAttachment().get(), AZ::Name(readbackName), mipsRange))
- {
- m_readbackOption = PassAttachmentReadbackOption::Output;
- // The m_readbackOption is only meaningful if the attachment is used for InputOutput.
- if (binding.m_slotType == PassSlotType::InputOutput)
- {
- m_readbackOption = option;
- }
- m_attachmentReadback = readback;
- return true;
- }
- return false;
- }
- }
- bindingIndex++;
- }
- AZ_Warning("Pass", false, "ReadbackAttachment: failed to find slot [%s] from pass [%s]", slotName.GetCStr(), m_path.GetCStr());
- return false;
- }
- void Pass::UpdateReadbackAttachment(FramePrepareParams params, bool beforeAddScopes)
- {
- if (beforeAddScopes == (m_readbackOption == PassAttachmentReadbackOption::Input) && m_attachmentReadback)
- {
- // Read the attachment for one frame. The reference can be released afterwards
- m_attachmentReadback->FrameBegin(params);
- m_attachmentReadback = nullptr;
- }
- }
- void Pass::UpdateAttachmentCopy(FramePrepareParams params)
- {
- if (!m_attachmentCopy.expired())
- {
- m_attachmentCopy.lock()->FrameBegin(params);
- }
- }
- bool Pass::UpdateImportedAttachmentImage(Ptr<PassAttachment>& attachment, RHI::ImageBindFlags bindFlags, RHI::ImageAspectFlags aspectFlags)
- {
- if (!attachment)
- {
- return false;
- }
- // update the image attachment descriptor to sync up size and format
- attachment->Update(true);
- RHI::ImageDescriptor& imageDesc = attachment->m_descriptor.m_image;
- // The Format Source had no valid attachment
- if (imageDesc.m_format == RHI::Format::Unknown)
- {
- return false;
- }
- RPI::AttachmentImage* currentImage = azrtti_cast<RPI::AttachmentImage*>(attachment->m_importedResource.get());
- if (attachment->m_importedResource && imageDesc.m_size == currentImage->GetDescriptor().m_size)
- {
- // If there's a resource already and the size didn't change, just keep using the old AttachmentImage.
- return true;
- }
-
- Data::Instance<RPI::AttachmentImagePool> pool = RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool();
- // set the bind flags
- imageDesc.m_bindFlags |= bindFlags;
-
- // The ImageViewDescriptor must be specified to make sure the frame graph compiler doesn't treat this as a transient image.
- RHI::ImageViewDescriptor viewDesc = RHI::ImageViewDescriptor::Create(imageDesc.m_format, 0, 0);
- viewDesc.m_aspectFlags = aspectFlags;
- // The full path name is needed for the attachment image so it's not deduplicated from accumulation images in different pipelines.
- AZStd::string imageName = RPI::ConcatPassString(GetPathName(), attachment->m_path);
- auto attachmentImage = RPI::AttachmentImage::Create(*pool.get(), imageDesc, Name(imageName), nullptr, &viewDesc);
- if (attachmentImage)
- {
- attachment->m_path = attachmentImage->GetAttachmentId();
- attachment->m_importedResource = attachmentImage;
- return true;
- }else
- {
- AZ_Error("Pass", false, "UpdateImportedAttachmentImage failed because it is unable to create an attachment image.");
- }
- return false;
- }
- void Pass::PrintIndent(AZStd::string& stringOutput, uint32_t indent) const
- {
- if (PassValidation::IsEnabled())
- {
- for (uint32_t i = 0; i < indent; ++i)
- {
- stringOutput += " ";
- }
- }
- }
- void Pass::PrintPassName(AZStd::string& stringOutput, uint32_t indent) const
- {
- if (PassValidation::IsEnabled())
- {
- stringOutput += "\n";
- PrintIndent(stringOutput, indent);
- stringOutput += "- ";
- //stringOutput += m_name.GetStringView();
- //stringOutput += "- ";
- stringOutput += m_path.GetStringView();
- stringOutput += "\n";
- }
- }
- void Pass::PrintErrors() const
- {
- if (PassValidation::IsEnabled())
- {
- PrintMessages(m_errorMessages);
- }
- }
- void Pass::PrintWarnings() const
- {
- if (PassValidation::IsEnabled())
- {
- PrintMessages(m_warningMessages);
- }
- }
- void Pass::PrintMessages(const AZStd::vector<AZStd::string>& messages) const
- {
- if (PassValidation::IsEnabled())
- {
- AZStd::string stringOutput;
- PrintPassName(stringOutput);
- for (const AZStd::string& message : messages)
- {
- PrintIndent(stringOutput, 1);
- stringOutput += message;
- stringOutput += "\n";
- }
- AZ_Printf("PassSystem", stringOutput.c_str());
- }
- }
- void Pass::PrintBindingsWithoutAttachments(uint32_t slotTypeMask) const
- {
- if (PassValidation::IsEnabled())
- {
- AZStd::string stringOutput;
- PrintPassName(stringOutput);
- for (const PassAttachmentBinding& binding : m_attachmentBindings)
- {
- uint32_t bindingMask = (1 << uint32_t(binding.m_slotType));
- if ((bindingMask & slotTypeMask) && (binding.GetAttachment() == nullptr))
- {
- // Print the name of the slot
- PrintIndent(stringOutput, 1);
- stringOutput += binding.m_name.GetStringView();
- stringOutput += " has no valid attachment\n";
- }
- }
- AZ_Printf("PassSystem", stringOutput.c_str());
- }
- }
- void Pass::DebugPrintBinding(AZStd::string& stringOutput, const PassAttachmentBinding& binding) const
- {
- if (PassValidation::IsEnabled())
- {
- // Print the name of the slot
- stringOutput += binding.m_name.GetStringView();
- // Print the attachment type and size, for example:
- // (Image, 1920, 1080) or (Buffer, 4096 bytes)
- if (binding.GetAttachment() != nullptr)
- {
- stringOutput += " (";
- // Images will have the format: AttachmentName (Image, 1920, 1080)
- if (binding.GetAttachment()->m_descriptor.m_type == RHI::AttachmentType::Image)
- {
- stringOutput += "Image";
- RHI::ImageDescriptor& desc = binding.GetAttachment()->m_descriptor.m_image;
- uint32_t dimensions = static_cast<uint32_t>(desc.m_dimension);
- for (uint32_t i = 0; i < dimensions; ++i)
- {
- stringOutput += ", ";
- stringOutput += AZStd::to_string(desc.m_size[i]);
- }
- if (desc.m_multisampleState.m_samples > 1)
- {
- if (desc.m_multisampleState.m_customPositionsCount > 0)
- {
- stringOutput += ", Custom_MSAA_";
- }
- else
- {
- stringOutput += ", MSAA_";
- }
- stringOutput += AZStd::to_string(desc.m_multisampleState.m_samples);
- stringOutput += "x";
- }
- }
- // Buffers will have the format: AttachmentName (Buffer, 4092 bytes)
- else if (binding.GetAttachment()->m_descriptor.m_type == RHI::AttachmentType::Buffer)
- {
- stringOutput += "Buffer, ";
- stringOutput += AZStd::to_string(binding.GetAttachment()->m_descriptor.m_buffer.m_byteCount);
- stringOutput += " bytes";
- }
- stringOutput += ")";
- }
- }
- }
- void Pass::DebugPrintBindingAndConnection(AZStd::string& stringOutput, uint8_t bindingIndex) const
- {
- if (PassValidation::IsEnabled())
- {
- PrintIndent(stringOutput, m_treeDepth + 2);
- // Print the Attachment
- const PassAttachmentBinding& binding = m_attachmentBindings[bindingIndex];
- DebugPrintBinding(stringOutput, binding);
- // Print the Attachment it's connected to
- if (binding.m_connectedBinding != nullptr)
- {
- stringOutput += " connected to ";
- DebugPrintBinding(stringOutput, *binding.m_connectedBinding);
- }
- stringOutput += "\n";
- }
- }
- void Pass::DebugPrint() const
- {
- if (PassValidation::IsEnabled())
- {
- AZStd::string stringOutput;
- PrintPassName(stringOutput, m_treeDepth);
- // Print inputs
- if (m_inputBindingIndices.size() > 0)
- {
- PrintIndent(stringOutput, m_treeDepth + 1);
- stringOutput += "Inputs:\n";
- for (uint8_t inputIndex : m_inputBindingIndices)
- {
- DebugPrintBindingAndConnection(stringOutput, inputIndex);
- }
- }
- // Print input/outputs
- if (m_inputOutputBindingIndices.size() > 0)
- {
- PrintIndent(stringOutput, m_treeDepth + 1);
- stringOutput += "Input/Outputs:\n";
- for (uint8_t inputIndex : m_inputOutputBindingIndices)
- {
- DebugPrintBindingAndConnection(stringOutput, inputIndex);
- }
- }
- // Print outputs
- if (m_outputBindingIndices.size() > 0)
- {
- PrintIndent(stringOutput, m_treeDepth + 1);
- stringOutput += "Outputs:\n";
- for (uint8_t inputIndex : m_outputBindingIndices)
- {
- DebugPrintBindingAndConnection(stringOutput, inputIndex);
- }
- }
- AZ_Printf("PassSystem", stringOutput.c_str());
- }
- }
- void PassValidationResults::PrintValidationIfError()
- {
- if (PassValidation::IsEnabled())
- {
- if (!IsValid())
- {
- AZ_Printf("PassSystem", "\n--- PASS VALIDATION FAILURE ---"
- "\n--Critical Errors--\n");
- AZ_Printf("PassSystem", "\nThere are %d passes with errors:\n", m_passesWithErrors.size());
- for (Pass* pass : m_passesWithErrors)
- {
- pass->PrintErrors();
- }
- AZ_Printf("PassSystem", "\nThere are %d passes with missing Inputs:\n", m_passesWithMissingInputs.size());
- for (Pass* pass : m_passesWithMissingInputs)
- {
- pass->PrintBindingsWithoutAttachments(uint32_t(PassSlotMask::Input));
- }
- AZ_Printf("PassSystem", "\nThere are %d passes with missing Inputs/Outputs:\n", m_passesWithMissingInputOutputs.size());
- for (Pass* pass : m_passesWithMissingInputOutputs)
- {
- pass->PrintBindingsWithoutAttachments(uint32_t(PassSlotMask::InputOutput));
- }
- AZ_Printf("PassSystem", "\n--Non-Critical Errors/Warnings--\n");
- AZ_Printf("PassSystem", "\nThere are %d passes with warnings:\n", m_passesWithWarnings.size());
- for (Pass* pass : m_passesWithWarnings)
- {
- pass->PrintWarnings();
- }
- }
- }
- }
- } // namespace RPI
- } // namespace AZ
|