SkyAtmospherePass.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 <SkyAtmosphere/SkyAtmospherePass.h>
  9. #include <SkyAtmosphere/SkyAtmosphereParentPass.h>
  10. #include <Atom/RPI.Public/Image/AttachmentImagePool.h>
  11. #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
  12. #include <Atom/RPI.Reflect/Pass/PassName.h>
  13. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  14. #include <Atom/RPI.Public/RPIUtils.h>
  15. #include <Atom/RPI.Public/Pass/FullscreenTrianglePass.h>
  16. #include <Atom/RPI.Public/Pass/ComputePass.h>
  17. namespace AZ::Render
  18. {
  19. SkyAtmospherePass::SkyAtmospherePass(const RPI::PassDescriptor& descriptor, SkyAtmosphereFeatureProcessorInterface::AtmosphereId id)
  20. : RPI::ParentPass(descriptor)
  21. , m_atmosphereId(id)
  22. {
  23. }
  24. RPI::Ptr<SkyAtmospherePass> SkyAtmospherePass::CreateWithPassRequest(SkyAtmosphereFeatureProcessorInterface::AtmosphereId id)
  25. {
  26. // Create a pass request for the descriptor so we can connect it to the parent class input connections
  27. RPI::PassRequest childRequest;
  28. childRequest.m_templateName = Name{ "SkyAtmosphereTemplate" };
  29. childRequest.m_passName = Name( AZStd::string::format("SkyAtmospherePass.%hu", id.GetIndex()) );
  30. RPI::PassConnection passConnection;
  31. passConnection.m_localSlot = Name{ "SpecularInputOutput" };
  32. passConnection.m_attachmentRef.m_pass = Name{ "Parent" };
  33. passConnection.m_attachmentRef.m_attachment = Name{ "SpecularInputOutput" };
  34. childRequest.m_connections.emplace_back(passConnection);
  35. passConnection.m_localSlot = Name{ "ReflectionInputOutput" };
  36. passConnection.m_attachmentRef.m_attachment = Name{ "ReflectionInputOutput" };
  37. childRequest.m_connections.emplace_back(passConnection);
  38. passConnection.m_localSlot = Name{ "SkyBoxDepth" };
  39. passConnection.m_attachmentRef.m_attachment = Name{ "SkyBoxDepth" };
  40. childRequest.m_connections.emplace_back(passConnection);
  41. passConnection.m_localSlot = Name{ "DirectionalShadowmap" };
  42. passConnection.m_attachmentRef.m_attachment = Name{ "DirectionalShadowmap" };
  43. childRequest.m_connections.emplace_back(passConnection);
  44. passConnection.m_localSlot = Name{ "DirectionalESM" };
  45. passConnection.m_attachmentRef.m_attachment = Name{ "DirectionalESM" };
  46. childRequest.m_connections.emplace_back(passConnection);
  47. const AZStd::shared_ptr<const RPI::PassTemplate> childTemplate =
  48. RPI::PassSystemInterface::Get()->GetPassTemplate(childRequest.m_templateName);
  49. AZ_Assert(
  50. childTemplate,
  51. "SkyAtmospherePass::CreateWithPassRequest - attempting to create a pass before the template has been created.");
  52. RPI::PassDescriptor descriptor{ childRequest.m_passName, childTemplate, &childRequest };
  53. return aznew SkyAtmospherePass(descriptor, id);
  54. }
  55. void SkyAtmospherePass::CreateImage(const Name& slotName, const RHI::ImageDescriptor& desc, ImageInstance& image)
  56. {
  57. // we need a unique name because there may be multiple sky parent passes
  58. AZStd::string imageName = RPI::ConcatPassString(GetPathName(), slotName);
  59. RHI::ClearValue clearValue = RHI::ClearValue::CreateVector4Float(0, 0, 0, 0);
  60. Data::Instance<AZ::RPI::AttachmentImagePool> pool = RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool();
  61. image = AZ::RPI::AttachmentImage::Create(*pool.get(), desc, Name(imageName), &clearValue, nullptr);
  62. }
  63. void SkyAtmospherePass::BindLUTs()
  64. {
  65. auto bindImageToSlot = [&](const ImageInstance& image, const AZ::Name& slotName, const AZ::Name& passName)
  66. {
  67. auto pass = FindChildPass(passName);
  68. if (!pass)
  69. {
  70. AZ_Warning("SkyAtmospherePass", false, "Failed to find pass %s", passName.GetCStr());
  71. return;
  72. }
  73. auto binding = pass->FindAttachmentBinding(slotName);
  74. if (!binding)
  75. {
  76. AZ_Warning("SkyAtmospherePass", false, "Failed to find binding for slot %s", slotName.GetCStr());
  77. return;
  78. }
  79. if (!binding->GetAttachment())
  80. {
  81. pass->AttachImageToSlot(slotName, image);
  82. }
  83. };
  84. {
  85. // create and bind transmittance LUT
  86. constexpr AZ::u32 width = 256;
  87. constexpr AZ::u32 height = 64;
  88. RHI::ImageDescriptor imageDesc = RHI::ImageDescriptor::Create2D(
  89. RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite, width, height,
  90. RHI::Format::R16G16B16A16_FLOAT);
  91. if (!m_transmittanceLUTImage)
  92. {
  93. CreateImage(Name("TransmittanceLUTImageAttachment"), imageDesc, m_transmittanceLUTImage);
  94. }
  95. bindImageToSlot(m_transmittanceLUTImage, Name("SkyTransmittanceLUTOutput"), Name("SkyTransmittanceLUTPass"));
  96. bindImageToSlot(m_transmittanceLUTImage, Name("SkyTransmittanceLUTInput"), Name("SkyViewLUTPass"));
  97. bindImageToSlot(m_transmittanceLUTImage, Name("SkyTransmittanceLUTInput"), Name("SkyVolumeLUTPass"));
  98. bindImageToSlot(m_transmittanceLUTImage, Name("SkyTransmittanceLUTInput"), Name("SkyRayMarchingPass"));
  99. }
  100. {
  101. // create and bind sky view LUT
  102. constexpr AZ::u32 width = 192;
  103. constexpr AZ::u32 height = 108;
  104. RHI::ImageDescriptor imageDesc = RHI::ImageDescriptor::Create2D(
  105. RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite, width, height, RHI::Format::R11G11B10_FLOAT);
  106. if (!m_skyViewLUTImage)
  107. {
  108. CreateImage(Name("SkyViewLUTImageAttachment"), imageDesc, m_skyViewLUTImage);
  109. }
  110. bindImageToSlot(m_skyViewLUTImage, Name("SkyViewLUTOutput"), Name("SkyViewLUTPass"));
  111. bindImageToSlot(m_skyViewLUTImage, Name("SkyViewLUTInput"), Name("SkyRayMarchingPass"));
  112. }
  113. {
  114. // create and bind sky volume LUT
  115. constexpr AZ::u32 width = 32;
  116. constexpr AZ::u32 height = 32;
  117. constexpr AZ::u32 depth = 32;
  118. RHI::ImageDescriptor imageDesc = RHI::ImageDescriptor::Create3D(
  119. RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite, width, height, depth, RHI::Format::R16G16B16A16_FLOAT);
  120. if (!m_skyVolumeLUTImage)
  121. {
  122. CreateImage(Name("SkyVolumeLUTImageAttachment"), imageDesc, m_skyVolumeLUTImage);
  123. }
  124. bindImageToSlot(m_skyVolumeLUTImage, Name("SkyVolumeLUTOutput"), Name("SkyVolumeLUTPass"));
  125. bindImageToSlot(m_skyVolumeLUTImage, Name("SkyVolumeLUTInput"), Name("SkyRayMarchingPass"));
  126. }
  127. }
  128. void SkyAtmospherePass::BuildShaderData()
  129. {
  130. m_atmospherePassData.clear();
  131. for (auto child : m_children)
  132. {
  133. if (RPI::RenderPass* renderPass = azrtti_cast<RPI::RenderPass*>(child.get()))
  134. {
  135. auto srg = renderPass->GetShaderResourceGroup();
  136. if (!srg)
  137. {
  138. continue;
  139. }
  140. auto index = srg->FindShaderInputConstantIndex(Name("m_constants"));
  141. if(!index.IsValid())
  142. {
  143. continue;
  144. }
  145. Data::Instance<RPI::Shader> shader;
  146. if (auto fullscreenPass = azrtti_cast<RPI::FullscreenTrianglePass*>(renderPass); fullscreenPass != nullptr)
  147. {
  148. shader = fullscreenPass->GetShader();
  149. }
  150. else if (auto computePass = azrtti_cast<RPI::ComputePass*>(renderPass); computePass != nullptr)
  151. {
  152. shader = computePass->GetShader();
  153. }
  154. if (!shader)
  155. {
  156. continue;
  157. }
  158. RPI::ShaderOptionGroup shaderOptionGroup = shader->CreateShaderOptionGroup();
  159. m_atmospherePassData.push_back({ index, srg, AZStd::move(shaderOptionGroup) });
  160. }
  161. }
  162. m_updateConstants = true;
  163. }
  164. void SkyAtmospherePass::BuildInternal()
  165. {
  166. Base::BuildInternal();
  167. BuildShaderData();
  168. m_skyTransmittanceLUTPass = FindChildPass(Name("SkyTransmittanceLUTPass"));
  169. m_skyViewLUTPass = FindChildPass(Name("SkyViewLUTPass"));
  170. m_skyVolumeLUTPass = FindChildPass(Name("SkyVolumeLUTPass"));
  171. BindLUTs();
  172. m_enableSkyTransmittanceLUTPass = true;
  173. }
  174. void SkyAtmospherePass::UpdatePassData()
  175. {
  176. uint32_t childIndex = 0;
  177. for (auto passData : m_atmospherePassData)
  178. {
  179. passData.m_srg->SetConstant(passData.m_index, m_constants);
  180. passData.m_shaderOptionGroup.SetValue(AZ::Name("o_enableShadows"), AZ::RPI::ShaderOptionValue{ m_enableShadows });
  181. passData.m_shaderOptionGroup.SetValue(AZ::Name("o_enableFastSky"), AZ::RPI::ShaderOptionValue{ m_enableFastSky });
  182. passData.m_shaderOptionGroup.SetValue(AZ::Name("o_enableSun"), AZ::RPI::ShaderOptionValue{ m_enableSun });
  183. passData.m_shaderOptionGroup.SetValue(AZ::Name("o_enableFastAerialPerspective"), AZ::RPI::ShaderOptionValue{ m_fastAerialPerspectiveEnabled });
  184. passData.m_shaderOptionGroup.SetValue(AZ::Name("o_enableAerialPerspective"), AZ::RPI::ShaderOptionValue{ m_aerialPerspectiveEnabled });
  185. const auto& pass = m_children[childIndex];
  186. if (auto fullscreenPass = azrtti_cast<RPI::FullscreenTrianglePass*>(pass); fullscreenPass != nullptr)
  187. {
  188. fullscreenPass->UpdateShaderOptions(passData.m_shaderOptionGroup.GetShaderVariantId());
  189. }
  190. else if (auto computePass = azrtti_cast<RPI::ComputePass*>(pass); computePass != nullptr)
  191. {
  192. computePass->UpdateShaderOptions(passData.m_shaderOptionGroup.GetShaderVariantId());
  193. }
  194. childIndex++;
  195. }
  196. }
  197. bool SkyAtmospherePass::NeedsShaderDataRebuild() const
  198. {
  199. if (m_children.empty())
  200. {
  201. return false;
  202. }
  203. else if (m_children.size() != m_atmospherePassData.size())
  204. {
  205. return true;
  206. }
  207. // SRG may change due to a shader reload
  208. for (int i = 0; i < m_atmospherePassData.size(); ++i)
  209. {
  210. if (RPI::RenderPass* renderPass = azrtti_cast<RPI::RenderPass*>(m_children[i].get()))
  211. {
  212. auto srg = renderPass->GetShaderResourceGroup();
  213. if (m_atmospherePassData[i].m_srg != srg)
  214. {
  215. return true;
  216. }
  217. }
  218. }
  219. return false;
  220. }
  221. void SkyAtmospherePass::FrameBeginInternal(AZ::RPI::Pass::FramePrepareParams params)
  222. {
  223. if (NeedsShaderDataRebuild())
  224. {
  225. BuildShaderData();
  226. }
  227. if (m_updateConstants && !m_atmospherePassData.empty())
  228. {
  229. m_updateConstants = false;
  230. UpdatePassData();
  231. }
  232. if (m_skyTransmittanceLUTPass)
  233. {
  234. if (m_enableSkyTransmittanceLUTPass)
  235. {
  236. m_skyTransmittanceLUTPass->SetEnabled(true);
  237. // we automatically disable the pass after updating until LUT params change again
  238. m_enableSkyTransmittanceLUTPass = false;
  239. }
  240. else if (m_skyTransmittanceLUTPass->IsEnabled())
  241. {
  242. m_skyTransmittanceLUTPass->SetEnabled(false);
  243. }
  244. }
  245. if (m_skyViewLUTPass)
  246. {
  247. if (m_enableFastSky != m_skyViewLUTPass->IsEnabled())
  248. {
  249. m_skyViewLUTPass->SetEnabled(m_enableFastSky);
  250. }
  251. }
  252. if (m_skyVolumeLUTPass)
  253. {
  254. bool enableVolumePass = m_fastAerialPerspectiveEnabled && m_aerialPerspectiveEnabled;
  255. if (enableVolumePass != m_skyVolumeLUTPass->IsEnabled())
  256. {
  257. m_skyVolumeLUTPass->SetEnabled(enableVolumePass);
  258. }
  259. }
  260. Base::FrameBeginInternal(params);
  261. }
  262. bool SkyAtmospherePass::LutParamsEqual(const SkyAtmosphereParams& lhs, const SkyAtmosphereParams& rhs) const
  263. {
  264. return lhs.m_rayleighExpDistribution == rhs.m_rayleighExpDistribution &&
  265. lhs.m_mieExpDistribution == rhs.m_mieExpDistribution &&
  266. lhs.m_planetRadius == rhs.m_planetRadius &&
  267. lhs.m_atmosphereRadius == rhs.m_atmosphereRadius &&
  268. lhs.m_luminanceFactor.IsClose(rhs.m_luminanceFactor) &&
  269. lhs.m_rayleighScattering.IsClose(rhs.m_rayleighScattering) &&
  270. lhs.m_mieScattering.IsClose(rhs.m_mieScattering) &&
  271. lhs.m_mieAbsorption.IsClose(rhs.m_mieAbsorption) &&
  272. lhs.m_absorption.IsClose(rhs.m_absorption) &&
  273. lhs.m_groundAlbedo.IsClose(rhs.m_groundAlbedo);
  274. }
  275. void SkyAtmospherePass::UpdateRenderPassSRG(const SkyAtmosphereParams& params)
  276. {
  277. m_constants.m_bottomRadius = params.m_planetRadius;
  278. m_constants.m_topRadius = params.m_atmosphereRadius;
  279. m_constants.m_sunRadiusFactor = params.m_sunRadiusFactor;
  280. m_constants.m_sunFalloffFactor = params.m_sunFalloffFactor;
  281. params.m_sunColor.GetAsVector3().StoreToFloat3(m_constants.m_sunColor);
  282. params.m_sunLimbColor.GetAsVector3().StoreToFloat3(m_constants.m_sunLimbColor);
  283. params.m_sunDirection.GetNormalized().StoreToFloat3(m_constants.m_sunDirection);
  284. params.m_planetOrigin.StoreToFloat3(m_constants.m_planetOrigin);
  285. m_constants.m_sunShadowFarClip = params.m_sunShadowsFarClip * 0.001f; // scale to km
  286. m_constants.m_nearClip = params.m_nearClip;
  287. m_constants.m_nearFadeDistance = params.m_nearFadeDistance;
  288. m_constants.m_aerialDepthFactor = params.m_aerialDepthFactor;
  289. // avoid oversampling (too many loops) causing device removal
  290. constexpr uint32_t maxSamples{ 64 };
  291. if (params.m_minSamples > maxSamples)
  292. {
  293. AZ_WarningOnce("SkyAtmosphere", false, "Clamping min samples to %ul to avoid device removal", maxSamples);
  294. m_constants.m_rayMarchMin = maxSamples;
  295. }
  296. else
  297. {
  298. m_constants.m_rayMarchMin = aznumeric_cast<float>(params.m_minSamples);
  299. }
  300. if (params.m_maxSamples > maxSamples)
  301. {
  302. AZ_WarningOnce("SkyAtmosphere", false, "Clamping max samples to %ul to avoid device removal", maxSamples);
  303. m_constants.m_rayMarchMax = maxSamples;
  304. }
  305. else
  306. {
  307. m_constants.m_rayMarchMax = aznumeric_cast<float>(params.m_maxSamples);
  308. }
  309. // update LUT params the first time or when they change
  310. if (m_lutUpdateRequired || !LutParamsEqual(m_atmosphereParams, params))
  311. {
  312. m_lutUpdateRequired = false;
  313. params.m_luminanceFactor.StoreToFloat3(m_constants.m_luminanceFactor);
  314. params.m_rayleighScattering.StoreToFloat3(m_constants.m_rayleighScattering);
  315. params.m_mieScattering.StoreToFloat3(m_constants.m_mieScattering);
  316. params.m_mieAbsorption.StoreToFloat3(m_constants.m_mieAbsorption);
  317. (params.m_mieScattering + params.m_mieAbsorption).StoreToFloat3(m_constants.m_mieExtinction);
  318. params.m_absorption.StoreToFloat3(m_constants.m_absorption);
  319. params.m_groundAlbedo.StoreToFloat3(m_constants.m_groundAlbedo);
  320. const float atmosphereHeight = params.m_atmosphereRadius - params.m_planetRadius;
  321. if (atmosphereHeight > 0 && params.m_rayleighExpDistribution > 0 && params.m_mieExpDistribution > 0)
  322. {
  323. // prevent rayleigh and mie distributions being larger than the atmosphere size
  324. m_constants.m_rayleighDensityExpScale = -1.f / static_cast<float>(AZStd::min(params.m_rayleighExpDistribution, atmosphereHeight));
  325. m_constants.m_mieDensityExpScale = -1.f / static_cast<float>(AZStd::min(params.m_mieExpDistribution, atmosphereHeight));
  326. }
  327. // absorption density layer uses a tent distribution
  328. // for now we'll base this distribution on earth settings for ozone
  329. m_constants.m_absorptionDensity0LayerWidth = atmosphereHeight * 0.25f; // altitude at which absorption reaches its maximum value
  330. m_constants.m_absorptionDensity0LinearTerm = 1.f / 15.f;
  331. m_constants.m_absorptionDensity0ConstantTerm = -2.f / 3.f;
  332. m_constants.m_absorptionDensity1LinearTerm = -1.f / 15.f;
  333. m_constants.m_absorptionDensity1ConstantTerm = 8.f / 3.f;
  334. m_enableSkyTransmittanceLUTPass = true;
  335. }
  336. m_atmosphereParams = params;
  337. m_enableShadows = params.m_shadowsEnabled;
  338. m_enableFastSky = params.m_fastSkyEnabled;
  339. m_fastAerialPerspectiveEnabled = params.m_fastAerialPerspectiveEnabled;
  340. m_aerialPerspectiveEnabled = params.m_aerialPerspectiveEnabled;
  341. m_enableSun = params.m_sunEnabled;
  342. // UpdateRenderPassSRG can be called before the child passes are ready
  343. // so we store the constants and set them in FrameBeginInternal
  344. m_updateConstants = true;
  345. }
  346. void SkyAtmospherePass::ResetInternal()
  347. {
  348. m_transmittanceLUTImage.reset();
  349. m_skyViewLUTImage.reset();
  350. m_skyVolumeLUTImage.reset();
  351. m_atmospherePassData.clear();
  352. Base::ResetInternal();
  353. }
  354. SkyAtmosphereFeatureProcessorInterface::AtmosphereId SkyAtmospherePass::GetAtmosphereId() const
  355. {
  356. return m_atmosphereId;
  357. }
  358. } // namespace AZ::Render