3
0

AttachmentReadback.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Atom/RPI.Public/Buffer/BufferSystemInterface.h>
  9. #include <Atom/RPI.Public/Buffer/Buffer.h>
  10. #include <Atom/RPI.Public/Image/AttachmentImage.h>
  11. #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
  12. #include <Atom/RPI.Public/Pass/AttachmentReadback.h>
  13. #include <Atom/RPI.Public/RPIUtils.h>
  14. #include <Atom/RPI.Reflect/Buffer/BufferAssetCreator.h>
  15. #include <Atom/RHI/CommandList.h>
  16. #include <Atom/RHI/Factory.h>
  17. #include <Atom/RHI/MultiDeviceFence.h>
  18. #include <Atom/RHI/FrameGraphExecuteContext.h>
  19. #include <Atom/RHI/FrameScheduler.h>
  20. #include <Atom/RHI/RHISystemInterface.h>
  21. #include <Atom/RHI/RHIUtils.h>
  22. #include <Atom/RHI/ScopeProducerFunction.h>
  23. #include <AzCore/Serialization/Json/JsonUtils.h>
  24. #include <AzCore/std/smart_ptr/make_shared.h>
  25. namespace AZ
  26. {
  27. namespace RPI
  28. {
  29. AttachmentReadback::AttachmentReadback(const RHI::ScopeId& scopeId) : m_dispatchItem(RHI::MultiDevice::AllDevices)
  30. {
  31. for(uint32_t i = 0; i < RHI::Limits::Device::FrameCountMax; i++)
  32. {
  33. m_isReadbackComplete.push_back(false);
  34. }
  35. // Create fence
  36. m_fence = aznew RHI::MultiDeviceFence;
  37. AZ_Assert(m_fence != nullptr, "AttachmentReadback failed to create a fence");
  38. [[maybe_unused]] RHI::ResultCode result = m_fence->Init(RHI::MultiDevice::AllDevices, RHI::FenceState::Reset);
  39. AZ_Assert(result == RHI::ResultCode::Success, "AttachmentReadback failed to init fence");
  40. // Load shader and srg
  41. constexpr const char* ShaderPath = "shaders/decomposemsimage.azshader";
  42. m_decomposeShader = LoadCriticalShader(ShaderPath);
  43. if (m_decomposeShader == nullptr)
  44. {
  45. AZ_Error("PassSystem", false, "[AttachmentReadback]: Failed to load shader '%s'!", ShaderPath);
  46. return;
  47. }
  48. // Load SRG
  49. const auto srgLayout = m_decomposeShader->FindShaderResourceGroupLayout(SrgBindingSlot::Object);
  50. if (srgLayout)
  51. {
  52. m_decomposeSrg = ShaderResourceGroup::Create(m_decomposeShader->GetAsset(), m_decomposeShader->GetSupervariantIndex(), srgLayout->GetName());
  53. if (!m_decomposeSrg)
  54. {
  55. AZ_Error("PassSystem", false, "Failed to create SRG from shader asset '%s'", ShaderPath);
  56. return;
  57. }
  58. }
  59. RHI::PipelineStateDescriptorForDispatch pipelineStateDescriptor;
  60. const auto& shaderVariant = m_decomposeShader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId);
  61. shaderVariant.ConfigurePipelineState(pipelineStateDescriptor);
  62. m_dispatchItem.SetPipelineState(m_decomposeShader->AcquirePipelineState(pipelineStateDescriptor));
  63. AZStd::array<const RHI::MultiDeviceShaderResourceGroup*, 1> srgs{m_decomposeSrg->GetRHIShaderResourceGroup()};
  64. m_dispatchItem.SetShaderResourceGroups(srgs);
  65. // find srg input indexes
  66. m_decomposeInputImageIndex = m_decomposeSrg->FindShaderInputImageIndex(Name("m_msImage"));
  67. m_decomposeOutputImageIndex = m_decomposeSrg->FindShaderInputImageIndex(Name("m_outputImage"));
  68. // build scope producer for copying
  69. m_copyScopeProducer = AZStd::make_shared<RHI::ScopeProducerFunctionNoData>(
  70. scopeId,
  71. AZStd::bind(&AttachmentReadback::CopyPrepare, this, AZStd::placeholders::_1),
  72. AZStd::bind(&AttachmentReadback::CopyCompile, this, AZStd::placeholders::_1),
  73. AZStd::bind(&AttachmentReadback::CopyExecute, this, AZStd::placeholders::_1));
  74. m_state = ReadbackState::Idle;
  75. }
  76. AttachmentReadback::~AttachmentReadback()
  77. {
  78. Reset();
  79. m_fence = nullptr;
  80. }
  81. bool AttachmentReadback::ReadPassAttachment(const PassAttachment* attachment, const AZ::Name& readbackName, const RHI::ImageSubresourceRange* mipsRange)
  82. {
  83. if (AZ::RHI::IsNullRHI())
  84. {
  85. return false;
  86. }
  87. if (!IsReady())
  88. {
  89. AZ_Assert(false, "AttachmentsReadbackGroup is not ready to readback attachments.");
  90. return false;
  91. }
  92. Reset();
  93. if (!attachment || (attachment->GetAttachmentType() != RHI::AttachmentType::Buffer && attachment->GetAttachmentType() != RHI::AttachmentType::Image))
  94. {
  95. AZ_Assert(false, "ReadPassAttachment: attachment is not a buffer or an image");
  96. return false;
  97. }
  98. m_state = ReadbackState::AttachmentSet;
  99. m_attachmentId = attachment->GetAttachmentId();
  100. m_attachmentType = attachment->GetAttachmentType();
  101. m_readbackName = readbackName;
  102. if (m_readbackName.IsEmpty())
  103. {
  104. m_readbackName = AZStd::string::format("%s_RB", m_attachmentId.GetCStr());
  105. }
  106. m_copyAttachmentId = m_attachmentId;
  107. // Get some attachment information
  108. if (m_attachmentType == RHI::AttachmentType::Buffer)
  109. {
  110. if (attachment->m_importedResource)
  111. {
  112. Buffer* buffer = static_cast<Buffer*>(attachment->m_importedResource.get());
  113. m_bufferAttachmentByteSize = buffer->GetBufferSize();
  114. }
  115. else
  116. {
  117. m_bufferAttachmentByteSize = attachment->m_descriptor.m_buffer.m_byteCount;
  118. }
  119. m_readbackItems.push_back({});
  120. auto& item = m_readbackItems.back();
  121. item.m_readbackBufferArray.resize(RHI::Limits::Device::FrameCountMax, nullptr);
  122. }
  123. else
  124. {
  125. if (attachment->m_importedResource)
  126. {
  127. AttachmentImage* attImage = static_cast<AttachmentImage*>(attachment->m_importedResource.get());
  128. m_imageDescriptor = attImage->GetRHIImage()->GetDescriptor();
  129. }
  130. else
  131. {
  132. m_imageDescriptor = attachment->m_descriptor.m_image;
  133. }
  134. m_imageMipsRange = (mipsRange != nullptr)
  135. ? *mipsRange
  136. : RHI::ImageSubresourceRange(0, 0, 0, 0);
  137. for (uint32_t mipIndex = m_imageMipsRange.m_mipSliceMin; mipIndex <= m_imageMipsRange.m_mipSliceMax; mipIndex++)
  138. {
  139. m_readbackItems.push_back({});
  140. auto& mipItem = m_readbackItems.back();
  141. mipItem.m_readbackBufferArray.resize(RHI::Limits::Device::FrameCountMax, nullptr);
  142. }
  143. // Add decompose scope to convert multi-sampled images to image array
  144. if (m_imageDescriptor.m_multisampleState.m_samples > 1)
  145. {
  146. m_copyAttachmentId = RHI::AttachmentId(AZStd::string::format("%s_Decomposed", m_attachmentId.GetCStr()));
  147. m_decomposeScopeProducer = AZStd::make_shared<RHI::ScopeProducerFunctionNoData>(
  148. m_copyAttachmentId,
  149. AZStd::bind(&AttachmentReadback::DecomposePrepare, this, AZStd::placeholders::_1),
  150. AZStd::bind(&AttachmentReadback::DecomposeCompile, this, AZStd::placeholders::_1),
  151. AZStd::bind(&AttachmentReadback::DecomposeExecute, this, AZStd::placeholders::_1));
  152. }
  153. }
  154. return true;
  155. }
  156. void AttachmentReadback::DecomposePrepare(RHI::FrameGraphInterface frameGraph)
  157. {
  158. RHI::ImageScopeAttachmentDescriptor inputDesc{ m_attachmentId };
  159. inputDesc.m_imageViewDescriptor.m_aspectFlags = RHI::CheckBitsAny(RHI::GetImageAspectFlags(m_imageDescriptor.m_format), RHI::ImageAspectFlags::Depth)?
  160. RHI::ImageAspectFlags::Depth:RHI::ImageAspectFlags::Color;
  161. frameGraph.UseAttachment(inputDesc, RHI::ScopeAttachmentAccess::Read, RHI::ScopeAttachmentUsage::Shader);
  162. RHI::ImageScopeAttachmentDescriptor outputDesc{ m_copyAttachmentId };
  163. frameGraph.UseAttachment(outputDesc, RHI::ScopeAttachmentAccess::Write, RHI::ScopeAttachmentUsage::Shader);
  164. }
  165. void AttachmentReadback::DecomposeCompile(const RHI::FrameGraphCompileContext& context)
  166. {
  167. // prepare compute shader which to convert multi-sample texture to texture array
  168. RHI::DispatchDirect dispatchArgs;
  169. dispatchArgs.m_totalNumberOfThreadsX = m_imageDescriptor.m_size.m_width;
  170. dispatchArgs.m_totalNumberOfThreadsY = m_imageDescriptor.m_size.m_height;
  171. dispatchArgs.m_totalNumberOfThreadsZ = m_imageDescriptor.m_arraySize;
  172. dispatchArgs.m_threadsPerGroupX = 16; // these numbers are matching numthreads in shader file
  173. dispatchArgs.m_threadsPerGroupY = 16;
  174. dispatchArgs.m_threadsPerGroupZ = 1;
  175. m_dispatchItem.SetArguments(dispatchArgs);
  176. const RHI::MultiDeviceImageView* imageView = context.GetImageView(m_attachmentId);
  177. m_decomposeSrg->SetImageView(m_decomposeInputImageIndex, imageView);
  178. imageView = context.GetImageView(m_copyAttachmentId);
  179. m_decomposeSrg->SetImageView(m_decomposeOutputImageIndex, imageView);
  180. m_decomposeSrg->Compile();
  181. }
  182. void AttachmentReadback::DecomposeExecute(const RHI::FrameGraphExecuteContext& context)
  183. {
  184. context.GetCommandList()->Submit(m_dispatchItem.GetDeviceDispatchItem(context.GetDeviceIndex()));
  185. }
  186. void AttachmentReadback::CopyPrepare(RHI::FrameGraphInterface frameGraph)
  187. {
  188. if (m_attachmentType == RHI::AttachmentType::Buffer)
  189. {
  190. RHI::BufferScopeAttachmentDescriptor descriptor{ m_copyAttachmentId };
  191. descriptor.m_bufferViewDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, aznumeric_cast<uint32_t>(m_bufferAttachmentByteSize));
  192. frameGraph.UseCopyAttachment(descriptor, RHI::ScopeAttachmentAccess::Read);
  193. }
  194. else if (m_attachmentType == RHI::AttachmentType::Image)
  195. {
  196. RHI::ImageScopeAttachmentDescriptor descriptor{ m_copyAttachmentId };
  197. frameGraph.UseCopyAttachment(descriptor, RHI::ScopeAttachmentAccess::Read);
  198. }
  199. frameGraph.SetEstimatedItemCount(static_cast<uint32_t>(m_readbackItems.size()));
  200. frameGraph.SignalFence(*m_fence);
  201. // CPU has already consumed the GPU buffer. We can clear it now.
  202. // We don't do this in the Async callback as the callback can get signaled by the GPU at anytime.
  203. // We were seeing an issue where during the buffer cleanup there was a chance to hit the assert
  204. // related to disconnecting a bus during a dispatch on a lockless Bus.
  205. // The fix is to clear the buffer outside of the callback.
  206. for (int32_t i = 0; i < RHI::Limits::Device::FrameCountMax; i++)
  207. {
  208. if (m_isReadbackComplete[i])
  209. {
  210. m_isReadbackComplete[i] = false;
  211. for (auto& readbackItem : m_readbackItems)
  212. {
  213. readbackItem.m_readbackBufferArray[i] = nullptr;
  214. }
  215. }
  216. }
  217. // Loop the triple buffer index and cache the current index to the callback.
  218. m_readbackBufferCurrentIndex = (m_readbackBufferCurrentIndex + 1) % RHI::Limits::Device::FrameCountMax;
  219. }
  220. void AttachmentReadback::CopyCompile(const RHI::FrameGraphCompileContext& context)
  221. {
  222. if (m_attachmentType == RHI::AttachmentType::Buffer)
  223. {
  224. const AZ::RHI::MultiDeviceBuffer* buffer = context.GetBuffer(m_copyAttachmentId);
  225. RPI::CommonBufferDescriptor desc;
  226. desc.m_poolType = RPI::CommonBufferPoolType::ReadBack;
  227. desc.m_bufferName = m_readbackName.GetStringView();
  228. desc.m_byteCount = buffer->GetDescriptor().m_byteCount;
  229. m_readbackItems[0].m_readbackBufferArray[m_readbackBufferCurrentIndex] = BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc);
  230. // copy buffer
  231. RHI::MultiDeviceCopyBufferDescriptor copyBuffer;
  232. copyBuffer.m_mdSourceBuffer = buffer;
  233. copyBuffer.m_mdDestinationBuffer = m_readbackItems[0].m_readbackBufferArray[m_readbackBufferCurrentIndex]->GetRHIBuffer();
  234. copyBuffer.m_size = aznumeric_cast<uint32_t>(desc.m_byteCount);
  235. m_readbackItems[0].m_copyItem = copyBuffer;
  236. }
  237. else if (m_attachmentType == RHI::AttachmentType::Image)
  238. {
  239. // copy image to read back buffer since only buffer can be accessed by host
  240. const AZ::RHI::MultiDeviceImage* image = context.GetImage(m_copyAttachmentId);
  241. if (!image)
  242. {
  243. AZ_Warning("AttachmentReadback", false, "Failed to find attachment image %s for copy to buffer", m_copyAttachmentId.GetCStr());
  244. return;
  245. }
  246. for (uint16_t itemIdx = 0; itemIdx < static_cast<uint16_t>(m_readbackItems.size()); itemIdx++)
  247. {
  248. auto& readbackItem = m_readbackItems[itemIdx];
  249. // copy descriptor for copying image to buffer
  250. RHI::MultiDeviceCopyImageToBufferDescriptor copyImageToBuffer;
  251. copyImageToBuffer.m_mdSourceImage = image;
  252. readbackItem.m_copyItem = copyImageToBuffer;
  253. }
  254. }
  255. }
  256. void AttachmentReadback::CopyExecute(const RHI::FrameGraphExecuteContext& context)
  257. {
  258. uint32_t readbackBufferCurrentIndex = m_readbackBufferCurrentIndex;
  259. auto deviceIndex = context.GetDeviceIndex();
  260. m_fence->GetDeviceFence(deviceIndex)
  261. ->WaitOnCpuAsync(
  262. [this, readbackBufferCurrentIndex, deviceIndex]()
  263. {
  264. if (m_state == ReadbackState::Reading)
  265. {
  266. if (CopyBufferData(readbackBufferCurrentIndex, deviceIndex))
  267. {
  268. m_state = ReadbackState::Success;
  269. }
  270. else
  271. {
  272. m_state = ReadbackState::Failed;
  273. }
  274. }
  275. if (m_callback)
  276. {
  277. m_callback(GetReadbackResult());
  278. }
  279. Reset();
  280. });
  281. for (uint16_t itemIdx = 0; itemIdx < static_cast<uint16_t>(m_readbackItems.size()); itemIdx++)
  282. {
  283. auto& readbackItem = m_readbackItems[itemIdx];
  284. if (m_attachmentType == RHI::AttachmentType::Image)
  285. {
  286. // copy image to read back buffer since only buffer can be accessed by host
  287. const auto image = readbackItem.m_copyItem.m_mdImage.m_mdSourceImage;
  288. if (!image)
  289. {
  290. AZ_Warning(
  291. "AttachmentReadback",
  292. false,
  293. "Failed to find attachment image %s for copy to buffer",
  294. m_copyAttachmentId.GetCStr());
  295. return;
  296. }
  297. m_imageDescriptor = image->GetDescriptor();
  298. // [GFX TODO] [ATOM-14140] [Pass Tree] Add the ability to output all the array subresources and planars
  299. // only array 0, and one aspect (planar) at this moment.
  300. // Note: Mip Levels and Texture3D images are supported.
  301. const uint16_t mipSlice = m_imageMipsRange.m_mipSliceMin + itemIdx;
  302. RHI::ImageSubresourceRange range(mipSlice, mipSlice, 0, 0);
  303. range.m_aspectFlags = RHI::ImageAspectFlags::Color;
  304. // setup aspect
  305. RHI::ImageAspect imageAspect = RHI::ImageAspect::Color;
  306. RHI::ImageAspectFlags imageAspectFlags = RHI::GetImageAspectFlags(m_imageDescriptor.m_format);
  307. if (RHI::CheckBitsAll(imageAspectFlags, RHI::ImageAspectFlags::Depth))
  308. {
  309. imageAspect = RHI::ImageAspect::Depth;
  310. range.m_aspectFlags = RHI::ImageAspectFlags::Depth;
  311. }
  312. AZStd::vector<RHI::SingleDeviceImageSubresourceLayout> imageSubresourceLayouts;
  313. imageSubresourceLayouts.resize_no_construct(m_imageDescriptor.m_mipLevels);
  314. size_t totalSizeInBytes = 0;
  315. image->GetDeviceImage(context.GetDeviceIndex())->GetSubresourceLayouts(range, imageSubresourceLayouts.data(), &totalSizeInBytes);
  316. AZ::u64 byteCount = totalSizeInBytes;
  317. RPI::CommonBufferDescriptor desc;
  318. desc.m_poolType = RPI::CommonBufferPoolType::ReadBack;
  319. desc.m_bufferName = m_readbackName.GetStringView();
  320. desc.m_byteCount = byteCount;
  321. readbackItem.m_readbackBufferArray[m_readbackBufferCurrentIndex] =
  322. BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc);
  323. // Use the aspect format as output format, this format is also used as copy destination's format
  324. m_imageDescriptor.m_format = FindFormatForAspect(m_imageDescriptor.m_format, imageAspect);
  325. // copy descriptor for copying image to buffer
  326. RHI::MultiDeviceCopyImageToBufferDescriptor copyImageToBuffer;
  327. copyImageToBuffer.m_mdSourceImage = image;
  328. copyImageToBuffer.m_sourceSize = imageSubresourceLayouts[mipSlice].m_size;
  329. copyImageToBuffer.m_sourceSubresource = RHI::ImageSubresource(mipSlice, 0 /*arraySlice*/, imageAspect);
  330. copyImageToBuffer.m_destinationOffset = 0;
  331. copyImageToBuffer.m_destinationBytesPerRow = imageSubresourceLayouts[mipSlice].m_bytesPerRow;
  332. copyImageToBuffer.m_destinationBytesPerImage = imageSubresourceLayouts[mipSlice].m_bytesPerImage;
  333. copyImageToBuffer.m_mdDestinationBuffer = readbackItem.m_readbackBufferArray[m_readbackBufferCurrentIndex]->GetRHIBuffer();
  334. copyImageToBuffer.m_destinationFormat = m_imageDescriptor.m_format;
  335. readbackItem.m_mipInfo.m_slice = mipSlice;
  336. readbackItem.m_mipInfo.m_size = imageSubresourceLayouts[mipSlice].m_size;
  337. readbackItem.m_copyItem = copyImageToBuffer;
  338. }
  339. if (readbackItem.m_readbackBufferArray[m_readbackBufferCurrentIndex])
  340. {
  341. context.GetCommandList()->Submit(readbackItem.m_copyItem.GetDeviceCopyItem(context.GetDeviceIndex()));
  342. }
  343. }
  344. }
  345. void AttachmentReadback::Reset()
  346. {
  347. m_attachmentId = RHI::AttachmentId{};
  348. m_readbackItems.clear();
  349. m_state = ReadbackState::Idle;
  350. m_readbackName = AZ::Name{};
  351. m_copyAttachmentId = RHI::AttachmentId{};
  352. m_decomposeScopeProducer = nullptr;
  353. if (m_decomposeSrg)
  354. {
  355. m_decomposeSrg->SetImageView(m_decomposeInputImageIndex, nullptr);
  356. m_decomposeSrg->SetImageView(m_decomposeOutputImageIndex, nullptr);
  357. }
  358. if (m_fence)
  359. {
  360. m_fence->Reset();
  361. }
  362. }
  363. AttachmentReadback::ReadbackState AttachmentReadback::GetReadbackState()
  364. {
  365. return m_state;
  366. }
  367. void AttachmentReadback::SetCallback(CallbackFunction callback)
  368. {
  369. m_callback = callback;
  370. }
  371. void AttachmentReadback::SetUserIdentifier(uint32_t userIdentifier)
  372. {
  373. m_userIdentifier = userIdentifier;
  374. }
  375. void AttachmentReadback::FrameBegin(Pass::FramePrepareParams params)
  376. {
  377. if (m_state == AttachmentReadback::ReadbackState::AttachmentSet)
  378. {
  379. // Need decompose
  380. if (m_decomposeScopeProducer)
  381. {
  382. // Create transient image array to save decompose result
  383. RHI::TransientImageDescriptor descriptor;
  384. descriptor.m_attachmentId = m_copyAttachmentId;
  385. auto format = m_imageDescriptor.m_format;
  386. // We can only use one planar for none render target shader output. Set to output Depth aspect only
  387. if (RHI::GetImageAspectFlags(format) == RHI::ImageAspectFlags::DepthStencil)
  388. {
  389. format = FindFormatForAspect(format, RHI::ImageAspect::Depth);
  390. }
  391. descriptor.m_imageDescriptor = RHI::ImageDescriptor::Create2DArray(RHI::ImageBindFlags::ShaderReadWrite,
  392. m_imageDescriptor.m_size.m_width, m_imageDescriptor.m_size.m_height,
  393. m_imageDescriptor.m_multisampleState.m_samples, // Use sample count as array size
  394. format);
  395. params.m_frameGraphBuilder->GetAttachmentDatabase().CreateTransientImage(descriptor);
  396. params.m_frameGraphBuilder->ImportScopeProducer(*m_decomposeScopeProducer.get());
  397. }
  398. // Import copy producer
  399. params.m_frameGraphBuilder->ImportScopeProducer(*m_copyScopeProducer.get());
  400. m_state = AttachmentReadback::ReadbackState::Reading;
  401. }
  402. }
  403. bool AttachmentReadback::IsFinished() const
  404. {
  405. return m_state == ReadbackState::Success || m_state == ReadbackState::Failed;
  406. }
  407. bool AttachmentReadback::IsReady() const
  408. {
  409. return !(m_state == ReadbackState::Reading || m_state == ReadbackState::Uninitialized);
  410. }
  411. AttachmentReadback::ReadbackResult AttachmentReadback::GetReadbackResult() const
  412. {
  413. ReadbackResult result;
  414. result.m_state = m_state;
  415. result.m_attachmentType = m_attachmentType;
  416. result.m_dataBuffer = m_readbackItems[0].m_dataBuffer;
  417. result.m_name = m_readbackName;
  418. result.m_userIdentifier = m_userIdentifier;
  419. result.m_imageDescriptor = m_imageDescriptor;
  420. result.m_imageDescriptor.m_arraySize = 1;
  421. if (m_attachmentType == RHI::AttachmentType::Image)
  422. {
  423. result.m_mipDataBuffers.reserve(m_readbackItems.size());
  424. for (const auto& readbackItem : m_readbackItems)
  425. {
  426. result.m_mipDataBuffers.push_back({});
  427. auto& mipDataBuffer = result.m_mipDataBuffers.back();
  428. mipDataBuffer.m_mipBuffer = readbackItem.m_dataBuffer;
  429. mipDataBuffer.m_mipInfo = readbackItem.m_mipInfo;
  430. }
  431. }
  432. return result;
  433. }
  434. bool AttachmentReadback::CopyBufferData(uint32_t readbackBufferIndex, int deviceIndex)
  435. {
  436. for (auto& readbackItem : m_readbackItems)
  437. {
  438. Data::Instance<Buffer> readbackBufferCurrent = readbackItem.m_readbackBufferArray[readbackBufferIndex];
  439. if (!readbackBufferCurrent)
  440. {
  441. return false;
  442. }
  443. auto bufferSize = readbackBufferCurrent->GetBufferSize();
  444. readbackItem.m_dataBuffer = AZStd::make_shared<AZStd::vector<uint8_t>>();
  445. void* buf = readbackBufferCurrent->Map(bufferSize, 0)[deviceIndex];
  446. if (buf)
  447. {
  448. if (m_attachmentType == RHI::AttachmentType::Buffer)
  449. {
  450. readbackItem.m_dataBuffer->resize_no_construct(bufferSize);
  451. memcpy(readbackItem.m_dataBuffer->data(), buf, bufferSize);
  452. }
  453. else if (m_attachmentType == RHI::AttachmentType::Image)
  454. {
  455. RHI::Size mipSize = readbackItem.m_mipInfo.m_size;
  456. RHI::SingleDeviceImageSubresourceLayout imageLayout = RHI::GetImageSubresourceLayout(mipSize,
  457. m_imageDescriptor.m_format);
  458. auto rowCount = imageLayout.m_rowCount;
  459. auto byteCount = imageLayout.m_bytesPerImage;
  460. if (m_imageDescriptor.m_dimension == AZ::RHI::ImageDimension::Image3D)
  461. {
  462. byteCount *= mipSize.m_depth;
  463. rowCount *= mipSize.m_depth;
  464. }
  465. readbackItem.m_dataBuffer->resize_no_construct(byteCount);
  466. const uint8_t* const sourceBegin = static_cast<uint8_t*>(buf);
  467. uint8_t* const destBegin = readbackItem.m_dataBuffer->data();
  468. // The source image WAS the destination when the copy item transferred data from GPU to CPU
  469. // this explains why the name srcBytesPerRow for these memcpy operations.
  470. const auto srcBytesPerRow = readbackItem.m_copyItem.m_mdImageToBuffer.m_destinationBytesPerRow;
  471. for (uint32_t row = 0; row < rowCount; ++row)
  472. {
  473. void* dest = destBegin + row * imageLayout.m_bytesPerRow;
  474. const void* source = sourceBegin + row * srcBytesPerRow;
  475. memcpy(dest, source, imageLayout.m_bytesPerRow);
  476. }
  477. }
  478. readbackBufferCurrent->Unmap();
  479. m_isReadbackComplete[readbackBufferIndex] = true;
  480. }
  481. else
  482. {
  483. return false;
  484. }
  485. }
  486. return true;
  487. }
  488. } // namespace RPI
  489. } // namespace AZ