ShadowExampleComponent.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. /*
  2. * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
  3. * its licensors.
  4. *
  5. * For complete copyright and license terms please see the LICENSE at the root of this
  6. * distribution (the "License"). All use of this software is governed by the License,
  7. * or, if provided, by the license below or the license accompanying this file. Do not
  8. * remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. *
  11. */
  12. #include <ShadowExampleComponent.h>
  13. #include <Automation/ScriptableImGui.h>
  14. #include <Automation/ScriptRunnerBus.h>
  15. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  16. #include <Atom/RPI.Public/RPISystemInterface.h>
  17. #include <Atom/RPI.Public/Scene.h>
  18. #include <Atom/RPI.Public/Model/Model.h>
  19. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  20. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  21. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  22. #include <AzCore/Component/Entity.h>
  23. #include <AzFramework/Components/CameraBus.h>
  24. #include <SampleComponentManager.h>
  25. #include <SampleComponentConfig.h>
  26. #include <RHI/BasicRHIComponent.h>
  27. #include <Atom/RPI.Public/ColorManagement/TransformColor.h>
  28. namespace AtomSampleViewer
  29. {
  30. namespace
  31. {
  32. const char* BunnyModelFilePath = "objects/bunny.azmodel";
  33. const char* CubeModelFilePath = "testdata/objects/cube/cube.azmodel";
  34. };
  35. const AZ::Color ShadowExampleComponent::DirectionalLightColor = AZ::Color::CreateOne();
  36. AZ::Color ShadowExampleComponent::s_positionalLightColors[] = {
  37. // they will be initialized in the constructor.
  38. AZ::Color::CreateZero(),
  39. AZ::Color::CreateZero(),
  40. AZ::Color::CreateZero()
  41. };
  42. const AZ::Render::ShadowmapSize ShadowExampleComponent::s_shadowmapImageSizes[] =
  43. {
  44. AZ::Render::ShadowmapSize::Size256,
  45. AZ::Render::ShadowmapSize::Size512,
  46. AZ::Render::ShadowmapSize::Size1024,
  47. AZ::Render::ShadowmapSize::Size2048
  48. };
  49. const char* ShadowExampleComponent::s_shadowmapImageSizeLabels[] =
  50. {
  51. "256",
  52. "512",
  53. "1024",
  54. "2048"
  55. };
  56. const AZ::Render::ShadowFilterMethod ShadowExampleComponent::s_shadowFilterMethods[] =
  57. {
  58. AZ::Render::ShadowFilterMethod::None,
  59. AZ::Render::ShadowFilterMethod::Pcf,
  60. AZ::Render::ShadowFilterMethod::Esm,
  61. AZ::Render::ShadowFilterMethod::EsmPcf
  62. };
  63. const char* ShadowExampleComponent::s_shadowFilterMethodLabels[] =
  64. {
  65. "None",
  66. "PCF",
  67. "ESM",
  68. "ESM+PCF"
  69. };
  70. ShadowExampleComponent::ShadowExampleComponent()
  71. : m_imguiSidebar("@user@/ShadowExampleComponent/sidebar.xml")
  72. {
  73. s_positionalLightColors[0] = AZ::Colors::Red;
  74. s_positionalLightColors[1] = AZ::Colors::Green;
  75. s_positionalLightColors[2] = AZ::Colors::Blue;
  76. }
  77. void ShadowExampleComponent::Reflect(AZ::ReflectContext* context)
  78. {
  79. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  80. {
  81. serializeContext->Class<ShadowExampleComponent, AZ::Component>()
  82. ->Version(0)
  83. ;
  84. }
  85. }
  86. void ShadowExampleComponent::Activate()
  87. {
  88. using namespace AZ;
  89. m_sampleName = "ShadowExampleComponent";
  90. // Don't continue the script until assets are ready and scene is setup
  91. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScriptWithTimeout, 120.0f);
  92. // preload assets
  93. AZStd::vector<AssetCollectionAsyncLoader::AssetToLoadInfo> assetList = {
  94. {DefaultPbrMaterialPath, azrtti_typeid<RPI::MaterialAsset>()},
  95. {BunnyModelFilePath, azrtti_typeid<RPI::ModelAsset>()},
  96. {CubeModelFilePath, azrtti_typeid<RPI::ModelAsset>()}
  97. };
  98. PreloadAssets(assetList);
  99. }
  100. void ShadowExampleComponent::OnAllAssetsReadyActivate()
  101. {
  102. using namespace AZ;
  103. // Load the assets
  104. m_bunnyModelAsset = RPI::AssetUtils::GetAssetByProductPath<RPI::ModelAsset>(BunnyModelFilePath, RPI::AssetUtils::TraceLevel::Assert);
  105. m_floorModelAsset = RPI::AssetUtils::GetAssetByProductPath<RPI::ModelAsset>(CubeModelFilePath, RPI::AssetUtils::TraceLevel::Assert);
  106. m_materialAsset = RPI::AssetUtils::GetAssetByProductPath<RPI::MaterialAsset>(DefaultPbrMaterialPath, RPI::AssetUtils::TraceLevel::Assert);
  107. m_bunnyMeshIsReady = false;
  108. m_floorMeshIsReady = false;
  109. m_directionalLightImageSizeIndex = 2; // image size is 1024.
  110. for (uint32_t index = 0; index < PositionalLightCount; ++index)
  111. {
  112. m_positionalLightImageSizeIndices[index] = 2; // image size is 1024.
  113. }
  114. m_cascadeCount = 2;
  115. m_ratioLogarithmUniform = 0.5f;
  116. UseArcBallCameraController();
  117. RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get();
  118. m_directionalLightFeatureProcessor = scene->GetFeatureProcessor<Render::DirectionalLightFeatureProcessorInterface>();
  119. m_diskLightFeatureProcessor = scene->GetFeatureProcessor<Render::DiskLightFeatureProcessorInterface>();
  120. m_pointLightFeatureProcessor = scene->GetFeatureProcessor<Render::PointLightFeatureProcessorInterface>();
  121. CreateMeshes();
  122. CreateDirectionalLight();
  123. CreateDiskLights();
  124. m_elapsedTime = 0.f;
  125. m_imguiSidebar.Activate();
  126. AZ::TickBus::Handler::BusConnect();
  127. }
  128. void ShadowExampleComponent::Deactivate()
  129. {
  130. AZ::TickBus::Handler::BusDisconnect();
  131. RestoreCameraConfiguration();
  132. RemoveController();
  133. GetMeshFeatureProcessor()->ReleaseMesh(m_floorMeshHandle);
  134. GetMeshFeatureProcessor()->ReleaseMesh(m_bunnyMeshHandle);
  135. DestroyDiskLights();
  136. DestroyPointLights();
  137. m_directionalLightFeatureProcessor->ReleaseLight(m_directionalLightHandle);
  138. m_imguiSidebar.Deactivate();
  139. }
  140. void ShadowExampleComponent::OnTick(float deltaTime, AZ::ScriptTimePoint)
  141. {
  142. using namespace AZ;
  143. constexpr float directionalLightPeriodTime = 5.f; // 5 seconds for a rotation of directional light position.
  144. constexpr float lightPeriodTime = 7.f; // 7 seconds for a rotation of light positions.
  145. if (m_elapsedTime == 0.f)
  146. {
  147. SaveCameraConfiguration();
  148. SetInitialArcBallControllerParams();
  149. SetInitialShadowParams();
  150. }
  151. m_elapsedTime += deltaTime;
  152. if (m_isDirectionalLightAutoRotate)
  153. {
  154. m_directionalLightRotationAngle = fmodf(m_directionalLightRotationAngle + deltaTime * Constants::TwoPi / directionalLightPeriodTime, Constants::TwoPi);
  155. }
  156. if (m_isPositionalLightAutoRotate)
  157. {
  158. m_positionalLightRotationAngle = fmodf(m_positionalLightRotationAngle - deltaTime * Constants::TwoPi / lightPeriodTime + Constants::TwoPi, Constants::TwoPi);
  159. }
  160. UpdateDirectionalLight();
  161. for (uint32_t index = 0; index < PositionalLightCount; ++index)
  162. {
  163. const auto transform = GetTransformForLight(index);
  164. if (m_diskLightHandles[index].IsValid())
  165. {
  166. m_diskLightFeatureProcessor->SetPosition(m_diskLightHandles[index], transform.GetTranslation());
  167. m_diskLightFeatureProcessor->SetDirection(m_diskLightHandles[index], transform.GetBasis(1));
  168. }
  169. if (m_pointLightHandles[index].IsValid())
  170. {
  171. m_pointLightFeatureProcessor->SetPosition(m_pointLightHandles[index], transform.GetTranslation());
  172. }
  173. }
  174. Camera::CameraRequestBus::Event(
  175. GetCameraEntityId(),
  176. &Camera::CameraRequestBus::Events::SetFovRadians,
  177. m_cameraFovY);
  178. DrawSidebar();
  179. }
  180. AZ::Transform ShadowExampleComponent::GetTransformForLight(const uint32_t index) const
  181. {
  182. constexpr float diskLightDist = 5.f;
  183. using namespace AZ;
  184. const float angle = m_positionalLightRotationAngle + index * Constants::TwoPi / 3;
  185. const auto location = Vector3(diskLightDist * sinf(angle), diskLightDist * cosf(angle), m_positionalLightHeights[index]);
  186. const auto transform = Transform::CreateLookAt(location, Vector3::CreateZero());
  187. return transform;
  188. }
  189. float ShadowExampleComponent::GetAttenuationForLight(const uint32_t index) const
  190. {
  191. return sqrtf(m_lightIntensities[index] / CutoffIntensity);
  192. }
  193. AZ::Render::PhotometricColor<AZ::Render::PhotometricUnit::Candela> ShadowExampleComponent::GetRgbIntensityForLight(
  194. const uint32_t index) const
  195. {
  196. AZ::Render::PhotometricColor<AZ::Render::PhotometricUnit::Candela> lightRgbIntensity(
  197. s_positionalLightColors[index] * m_lightIntensities[index]);
  198. return lightRgbIntensity;
  199. }
  200. AZStd::pair<float, float> ShadowExampleComponent::GetConeAnglesForLight(const uint32_t index) const
  201. {
  202. const float innerConeAngle = AZ::DegToRad(m_outerConeAngles[index]) * ConeAngleInnerRatio;
  203. const float outerConeAngle = AZ::DegToRad(m_outerConeAngles[index]);
  204. return AZStd::make_pair(innerConeAngle, outerConeAngle);
  205. }
  206. void ShadowExampleComponent::UpdateDirectionalLight()
  207. {
  208. using namespace AZ;
  209. constexpr float directionalLightDist = 10.f;
  210. // Directional Light Transform
  211. {
  212. const auto lightLocation = Vector3(
  213. directionalLightDist * sinf(m_directionalLightRotationAngle), directionalLightDist * cosf(m_directionalLightRotationAngle),
  214. m_directionalLightHeight);
  215. const auto lightTransform = Transform::CreateLookAt(lightLocation, Vector3::CreateZero());
  216. m_directionalLightFeatureProcessor->SetDirection(m_directionalLightHandle, lightTransform.GetBasis(1));
  217. }
  218. // Camera Configuration
  219. {
  220. Camera::Configuration config;
  221. Camera::CameraRequestBus::EventResult(config, GetCameraEntityId(), &Camera::CameraRequestBus::Events::GetCameraConfiguration);
  222. m_directionalLightFeatureProcessor->SetCameraConfiguration(m_directionalLightHandle, config);
  223. }
  224. // Camera Transform
  225. {
  226. Transform transform = Transform::CreateIdentity();
  227. TransformBus::EventResult(transform, GetCameraEntityId(), &TransformBus::Events::GetWorldTM);
  228. m_directionalLightFeatureProcessor->SetCameraTransform(m_directionalLightHandle, transform);
  229. }
  230. }
  231. void ShadowExampleComponent::SaveCameraConfiguration()
  232. {
  233. Camera::CameraRequestBus::EventResult(
  234. m_originalFarClipDistance,
  235. GetCameraEntityId(),
  236. &Camera::CameraRequestBus::Events::GetFarClipDistance);
  237. Camera::CameraRequestBus::EventResult(
  238. m_originalCameraFovRadians,
  239. GetCameraEntityId(),
  240. &Camera::CameraRequestBus::Events::GetFovRadians);
  241. }
  242. void ShadowExampleComponent::RestoreCameraConfiguration()
  243. {
  244. Camera::CameraRequestBus::Event(
  245. GetCameraEntityId(),
  246. &Camera::CameraRequestBus::Events::SetFarClipDistance,
  247. m_originalFarClipDistance);
  248. Camera::CameraRequestBus::Event(
  249. GetCameraEntityId(),
  250. &Camera::CameraRequestBus::Events::SetFovRadians,
  251. m_originalCameraFovRadians);
  252. }
  253. void ShadowExampleComponent::UseArcBallCameraController()
  254. {
  255. using namespace AZ;
  256. Debug::CameraControllerRequestBus::Event(
  257. GetCameraEntityId(),
  258. &Debug::CameraControllerRequestBus::Events::Enable,
  259. azrtti_typeid<Debug::ArcBallControllerComponent>());
  260. }
  261. void ShadowExampleComponent::SetInitialArcBallControllerParams()
  262. {
  263. using namespace AZ;
  264. const auto cameraLocation = Vector3(0.f, -2.f, 2.f);
  265. Debug::ArcBallControllerRequestBus::Event(
  266. GetCameraEntityId(),
  267. &Debug::ArcBallControllerRequestBus::Events::SetCenter,
  268. cameraLocation);
  269. Debug::ArcBallControllerRequestBus::Event(
  270. GetCameraEntityId(),
  271. &Debug::ArcBallControllerRequestBus::Events::SetPitch,
  272. -Constants::QuarterPi);
  273. Debug::ArcBallControllerRequestBus::Event(
  274. GetCameraEntityId(),
  275. &Debug::ArcBallControllerRequestBus::Events::SetDistance,
  276. 50.f);
  277. }
  278. void ShadowExampleComponent::SetInitialShadowParams()
  279. {
  280. Camera::CameraRequestBus::Event(
  281. GetCameraEntityId(),
  282. &Camera::CameraRequestBus::Events::SetFovRadians,
  283. AZ::Constants::QuarterPi);
  284. }
  285. void ShadowExampleComponent::RemoveController()
  286. {
  287. AZ::Debug::CameraControllerRequestBus::Event(
  288. GetCameraEntityId(),
  289. &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  290. }
  291. void ShadowExampleComponent::CreateMeshes()
  292. {
  293. using namespace AZ;
  294. m_materialInstance = RPI::Material::FindOrCreate(m_materialAsset);
  295. m_floorMeshHandle = GetMeshFeatureProcessor()->AcquireMesh(m_floorModelAsset, m_materialInstance);
  296. m_bunnyMeshHandle = GetMeshFeatureProcessor()->AcquireMesh(m_bunnyModelAsset, m_materialInstance);
  297. auto updateFloorTransform = [&](Data::Instance<RPI::Model> model)
  298. {
  299. const AZ::Aabb& aabb = model->GetAabb();
  300. const float maxZ = aabb.GetMax().GetZ();
  301. const AZ::Vector3 scale{ 12.f, 12.f, 0.1f };
  302. const AZ::Vector3 translation{ 0.f, 0.f, -maxZ * scale.GetZ() };
  303. const auto transform = AZ::Transform::CreateTranslation(translation) *
  304. AZ::Transform::CreateScale(scale);
  305. GetMeshFeatureProcessor()->SetTransform(m_floorMeshHandle, transform);
  306. m_floorMeshIsReady = true;
  307. if (m_bunnyMeshIsReady)
  308. {
  309. // Now that the models are initialized, we can allow the script to continue.
  310. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  311. }
  312. };
  313. auto updateBunnyTransform = [&](Data::Instance<RPI::Model> model)
  314. {
  315. const AZ::Aabb& aabb = model->GetAabb();
  316. const float minZ = aabb.GetMin().GetZ();
  317. const AZ::Vector3 translation{ 0.f, 0.f, -minZ };
  318. const auto transform = AZ::Transform::CreateTranslation(translation);
  319. GetMeshFeatureProcessor()->SetTransform(m_bunnyMeshHandle, transform);
  320. m_bunnyMeshIsReady = true;
  321. if (m_floorMeshIsReady)
  322. {
  323. // Now that the models are initialized, we can allow the script to continue.
  324. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  325. }
  326. };
  327. m_floorReadyHandle = ModelChangedHandler(updateFloorTransform);
  328. m_bunnyReadyHandle = ModelChangedHandler(updateBunnyTransform);
  329. GetMeshFeatureProcessor()->ConnectModelChangeEventHandler(m_floorMeshHandle, m_floorReadyHandle);
  330. GetMeshFeatureProcessor()->ConnectModelChangeEventHandler(m_bunnyMeshHandle, m_bunnyReadyHandle);
  331. // Currently there's no way for the mesh feature procesor to announce change on connect if the model is ready already.
  332. // This can go away when AZ::Event::Handler's callback can be called publicly.
  333. Data::Instance<RPI::Model> floorModel = GetMeshFeatureProcessor()->GetModel(m_floorMeshHandle);
  334. if (floorModel)
  335. {
  336. updateFloorTransform(floorModel);
  337. }
  338. Data::Instance<RPI::Model> bunnyModel = GetMeshFeatureProcessor()->GetModel(m_bunnyMeshHandle);
  339. if (bunnyModel)
  340. {
  341. updateBunnyTransform(bunnyModel);
  342. }
  343. }
  344. void ShadowExampleComponent::CreateDirectionalLight()
  345. {
  346. using namespace AZ;
  347. Render::DirectionalLightFeatureProcessorInterface* const featureProcessor = m_directionalLightFeatureProcessor;
  348. const DirectionalLightHandle handle = featureProcessor->AcquireLight();
  349. AZ::Render::PhotometricColor<AZ::Render::PhotometricUnit::Lux> lightColor(DirectionalLightColor * m_directionalLightIntensity);
  350. featureProcessor->SetRgbIntensity(handle, lightColor);
  351. featureProcessor->SetShadowmapSize(handle, s_shadowmapImageSizes[m_directionalLightImageSizeIndex]);
  352. featureProcessor->SetShadowFarClipDistance(handle, FarClipDistance);
  353. featureProcessor->SetCascadeCount(handle, m_cascadeCount);
  354. featureProcessor->SetShadowmapFrustumSplitSchemeRatio(handle, m_ratioLogarithmUniform);
  355. featureProcessor->SetViewFrustumCorrectionEnabled(handle, m_isCascadeCorrectionEnabled);
  356. featureProcessor->SetShadowFilterMethod(handle, s_shadowFilterMethods[m_shadowFilterMethodIndexDirectional]);
  357. featureProcessor->SetShadowBoundaryWidth(handle, m_boundaryWidthDirectional);
  358. featureProcessor->SetPredictionSampleCount(handle, m_predictionSampleCountDirectional);
  359. featureProcessor->SetFilteringSampleCount(handle, m_filteringSampleCountDirectional);
  360. featureProcessor->SetGroundHeight(handle, 0.f);
  361. m_directionalLightHandle = handle;
  362. SetupDebugFlags();
  363. }
  364. void ShadowExampleComponent::CreateDiskLights()
  365. {
  366. DestroyDiskLights();
  367. using namespace AZ;
  368. Render::DiskLightFeatureProcessorInterface* const featureProcessor = m_diskLightFeatureProcessor;
  369. for (uint32_t index = 0; index < PositionalLightCount; ++index)
  370. {
  371. const DiskLightHandle handle = featureProcessor->AcquireLight();
  372. AZ_Assert(m_diskLightHandles[index].IsNull(), "Unreleased light");
  373. m_diskLightHandles[index] = handle;
  374. }
  375. ApplyDiskLightSettings();
  376. }
  377. void ShadowExampleComponent::CreatePointLights()
  378. {
  379. DestroyPointLights();
  380. using namespace AZ;
  381. Render::PointLightFeatureProcessorInterface* const featureProcessor = m_pointLightFeatureProcessor;
  382. for (uint32_t index = 0; index < PositionalLightCount; ++index)
  383. {
  384. const PointLightHandle handle = featureProcessor->AcquireLight();
  385. AZ_Assert(m_pointLightHandles[index].IsNull(), "Unreleased light");
  386. m_pointLightHandles[index] = handle;
  387. }
  388. ApplyPointLightSettings();
  389. }
  390. void ShadowExampleComponent::DrawSidebar()
  391. {
  392. using namespace AZ::Render;
  393. if (m_imguiSidebar.Begin())
  394. {
  395. ImGui::Spacing();
  396. DrawSidebarDirectionalLight();
  397. ImGui::Separator();
  398. if (DrawSidebarPositionalLights())
  399. {
  400. ApplyDiskLightSettings();
  401. ApplyPointLightSettings();
  402. }
  403. ImGui::Separator();
  404. DrawSidebarCamera();
  405. ImGui::Separator();
  406. if (ScriptableImGui::Button("Material Details..."))
  407. {
  408. m_imguiMaterialDetails.SetMaterial(m_materialInstance);
  409. m_imguiMaterialDetails.OpenDialog();
  410. }
  411. m_imguiSidebar.End();
  412. }
  413. m_imguiMaterialDetails.Tick();
  414. }
  415. void ShadowExampleComponent::DrawSidebarDirectionalLight()
  416. {
  417. ImGui::Indent();
  418. if (ImGui::CollapsingHeader("Directional Light", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed))
  419. {
  420. ScriptableImGui::SliderFloat("Height##Directional", &m_directionalLightHeight, 1.f, 30.f, "%.1f", ImGuiSliderFlags_Logarithmic);
  421. ScriptableImGui::Checkbox("Auto Rotation##Directional", &m_isDirectionalLightAutoRotate);
  422. ScriptableImGui::SliderAngle("Direction##Directional", &m_directionalLightRotationAngle, 0, 360);
  423. if (ScriptableImGui::SliderFloat(
  424. "Intensity##Directional", &m_directionalLightIntensity, 0.f, 20.f, "%.1f", ImGuiSliderFlags_Logarithmic))
  425. {
  426. AZ::Render::PhotometricColor<AZ::Render::PhotometricUnit::Lux> lightColor(
  427. DirectionalLightColor * m_directionalLightIntensity);
  428. m_directionalLightFeatureProcessor->SetRgbIntensity(m_directionalLightHandle, lightColor);
  429. }
  430. ImGui::Text("Shadowmap Size");
  431. if (ScriptableImGui::Combo(
  432. "Size##Directional", &m_directionalLightImageSizeIndex, s_shadowmapImageSizeLabels,
  433. AZ_ARRAY_SIZE(s_shadowmapImageSizeLabels)))
  434. {
  435. m_directionalLightFeatureProcessor->SetShadowmapSize(
  436. m_directionalLightHandle, s_shadowmapImageSizes[m_directionalLightImageSizeIndex]);
  437. }
  438. ImGui::Text("Number of cascades");
  439. bool cascadesChanged = false;
  440. cascadesChanged = cascadesChanged || ScriptableImGui::RadioButton("1", &m_cascadeCount, 1);
  441. ImGui::SameLine();
  442. cascadesChanged = cascadesChanged || ScriptableImGui::RadioButton("2", &m_cascadeCount, 2);
  443. ImGui::SameLine();
  444. cascadesChanged = cascadesChanged || ScriptableImGui::RadioButton("3", &m_cascadeCount, 3);
  445. ImGui::SameLine();
  446. cascadesChanged = cascadesChanged || ScriptableImGui::RadioButton("4", &m_cascadeCount, 4);
  447. if (cascadesChanged)
  448. {
  449. m_directionalLightFeatureProcessor->SetCascadeCount(m_directionalLightHandle, m_cascadeCount);
  450. }
  451. ImGui::Spacing();
  452. bool cascadeDepthIsChanged = ScriptableImGui::Checkbox("Automatic Cascade Split", &m_shadowmapFrustumSplitIsAutomatic);
  453. if (m_shadowmapFrustumSplitIsAutomatic)
  454. {
  455. ImGui::Text("Cascade partition scheme");
  456. ImGui::Text(" (uniform <--> logarithm)");
  457. cascadeDepthIsChanged =
  458. cascadeDepthIsChanged || ScriptableImGui::SliderFloat("Ratio", &m_ratioLogarithmUniform, 0.f, 1.f, "%0.3f");
  459. if (cascadeDepthIsChanged)
  460. {
  461. m_directionalLightFeatureProcessor->SetShadowmapFrustumSplitSchemeRatio(
  462. m_directionalLightHandle, m_ratioLogarithmUniform);
  463. }
  464. }
  465. else
  466. {
  467. for (int cascadeIndex = 0; cascadeIndex < m_cascadeCount; ++cascadeIndex)
  468. {
  469. const AZStd::string label = AZStd::string::format("FarDepth %d", cascadeIndex);
  470. cascadeDepthIsChanged =
  471. cascadeDepthIsChanged || ScriptableImGui::SliderFloat(label.c_str(), &m_cascadeFarDepth[cascadeIndex], 0.01f, 20.f);
  472. }
  473. if (cascadeDepthIsChanged)
  474. {
  475. for (int cascadeIndex = 0; cascadeIndex < m_cascadeCount; ++cascadeIndex)
  476. {
  477. m_directionalLightFeatureProcessor->SetCascadeFarDepth(
  478. m_directionalLightHandle, aznumeric_cast<uint16_t>(cascadeIndex), m_cascadeFarDepth[cascadeIndex]);
  479. }
  480. }
  481. }
  482. ImGui::Spacing();
  483. ImGui::Text("Filtering");
  484. if (ScriptableImGui::Combo(
  485. "Filter Method##Directional", &m_shadowFilterMethodIndexDirectional, s_shadowFilterMethodLabels,
  486. AZ_ARRAY_SIZE(s_shadowFilterMethodLabels)))
  487. {
  488. m_directionalLightFeatureProcessor->SetShadowFilterMethod(
  489. m_directionalLightHandle, s_shadowFilterMethods[m_shadowFilterMethodIndexDirectional]);
  490. }
  491. if (m_shadowFilterMethodIndexDirectional != aznumeric_cast<int>(AZ::Render::ShadowFilterMethod::None))
  492. {
  493. ImGui::Text("Boundary Width in meter");
  494. if (ScriptableImGui::SliderFloat("Width##Directional", &m_boundaryWidthDirectional, 0.f, 0.1f, "%.3f"))
  495. {
  496. m_directionalLightFeatureProcessor->SetShadowBoundaryWidth(m_directionalLightHandle, m_boundaryWidthDirectional);
  497. }
  498. }
  499. if (m_shadowFilterMethodIndexDirectional == aznumeric_cast<int>(AZ::Render::ShadowFilterMethod::Pcf) ||
  500. m_shadowFilterMethodIndexDirectional == aznumeric_cast<int>(AZ::Render::ShadowFilterMethod::EsmPcf))
  501. {
  502. ImGui::Spacing();
  503. ImGui::Text("Filtering (PCF specific)");
  504. if (ScriptableImGui::SliderInt("Prediction # ##Directional", &m_predictionSampleCountDirectional, 4, 16))
  505. {
  506. m_directionalLightFeatureProcessor->SetPredictionSampleCount(
  507. m_directionalLightHandle, m_predictionSampleCountDirectional);
  508. }
  509. if (ScriptableImGui::SliderInt("Filtering # ##Directional", &m_filteringSampleCountDirectional, 4, 64))
  510. {
  511. m_directionalLightFeatureProcessor->SetFilteringSampleCount(
  512. m_directionalLightHandle, m_filteringSampleCountDirectional);
  513. }
  514. }
  515. ImGui::Spacing();
  516. bool debugFlagsChanged = false;
  517. debugFlagsChanged = ScriptableImGui::Checkbox("Debug Coloring", &m_isDebugColoringEnabled) || debugFlagsChanged;
  518. debugFlagsChanged = ScriptableImGui::Checkbox("Debug Bounding Box", &m_isDebugBoundingBoxEnabled) || debugFlagsChanged;
  519. if (debugFlagsChanged)
  520. {
  521. SetupDebugFlags();
  522. }
  523. if (ScriptableImGui::Checkbox("Cascade Position Correction", &m_isCascadeCorrectionEnabled))
  524. {
  525. m_directionalLightFeatureProcessor->SetViewFrustumCorrectionEnabled(m_directionalLightHandle, m_isCascadeCorrectionEnabled);
  526. }
  527. }
  528. ImGui::Unindent();
  529. }
  530. bool ShadowExampleComponent::DrawSidebarPositionalLights()
  531. {
  532. using namespace AZ::Render;
  533. bool settingsChanged = false;
  534. ImGui::Indent();
  535. if (ImGui::CollapsingHeader("Positional Lights", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed))
  536. {
  537. ImGui::Text("Light Type");
  538. if (ScriptableImGui::RadioButton("Disk", &m_positionalLightTypeActive, 0))
  539. {
  540. DestroyPointLights();
  541. CreateDiskLights();
  542. settingsChanged = true;
  543. }
  544. if (ScriptableImGui::RadioButton("Point", &m_positionalLightTypeActive, 1))
  545. {
  546. DestroyDiskLights();
  547. CreatePointLights();
  548. settingsChanged = true;
  549. }
  550. ScriptableImGui::Checkbox("Auto Rotation##Positional", &m_isPositionalLightAutoRotate);
  551. ScriptableImGui::SliderAngle("Base Direction##Positional", &m_positionalLightRotationAngle, 0, 360);
  552. ImGui::Spacing();
  553. ImGui::Text("Control Target");
  554. ScriptableImGui::RadioButton("Red", &m_controlTargetPositionalLightIndex, 0);
  555. ImGui::SameLine();
  556. ScriptableImGui::RadioButton("Green", &m_controlTargetPositionalLightIndex, 1);
  557. ImGui::SameLine();
  558. ScriptableImGui::RadioButton("Blue", &m_controlTargetPositionalLightIndex, 2);
  559. const int index = m_controlTargetPositionalLightIndex;
  560. ScriptableImGui::SliderFloat(
  561. "Height##Positional", &m_positionalLightHeights[index], 1.f, 30.f, "%.1f", ImGuiSliderFlags_Logarithmic);
  562. if (ScriptableImGui::SliderFloat("Cone Angle", &m_outerConeAngles[index], 0.f, 120.f))
  563. {
  564. settingsChanged = true;
  565. }
  566. if (ScriptableImGui::SliderFloat(
  567. "Intensity##Positional", &m_lightIntensities[index], 0.f, 20000.f, "%.1f", ImGuiSliderFlags_Logarithmic))
  568. {
  569. settingsChanged = true;
  570. }
  571. bool shadowmapSizeChanged = ScriptableImGui::Checkbox("Enable Shadow", &m_positionalLightShadowEnabled[index]);
  572. ImGui::Text("Shadowmap Size");
  573. shadowmapSizeChanged = shadowmapSizeChanged ||
  574. ScriptableImGui::Combo("Size##Positional", &m_positionalLightImageSizeIndices[index], s_shadowmapImageSizeLabels,
  575. AZ_ARRAY_SIZE(s_shadowmapImageSizeLabels));
  576. if (shadowmapSizeChanged)
  577. {
  578. // Reset shadow parameters when shadow is disabled.
  579. if (!m_positionalLightShadowEnabled[index])
  580. {
  581. m_shadowFilterMethodIndicesPositional[index] = 0;
  582. m_boundaryWidthsPositional[index] = 0.f;
  583. m_predictionSampleCountsPositional[index] = 0;
  584. m_filteringSampleCountsPositional[index] = 0;
  585. }
  586. settingsChanged = true;
  587. }
  588. ImGui::Spacing();
  589. ImGui::Text("Filtering");
  590. if (ScriptableImGui::Combo(
  591. "Filter Method##Positional", &m_shadowFilterMethodIndicesPositional[index], s_shadowFilterMethodLabels,
  592. AZ_ARRAY_SIZE(s_shadowFilterMethodLabels)))
  593. {
  594. settingsChanged = true;
  595. }
  596. if (m_shadowFilterMethodIndicesPositional[index] != aznumeric_cast<int>(ShadowFilterMethod::None))
  597. {
  598. ImGui::Text("Boundary Width in degrees");
  599. if (ScriptableImGui::SliderFloat("Width##Positional", &m_boundaryWidthsPositional[index], 0.f, 1.0f, "%.3f"))
  600. {
  601. settingsChanged = true;
  602. }
  603. }
  604. if (m_shadowFilterMethodIndicesPositional[index] == aznumeric_cast<int>(ShadowFilterMethod::Pcf) ||
  605. m_shadowFilterMethodIndicesPositional[index] == aznumeric_cast<int>(ShadowFilterMethod::EsmPcf))
  606. {
  607. ImGui::Spacing();
  608. ImGui::Text("Filtering (PCF specific)");
  609. if (m_pcfMethod[index] == PcfMethod::BoundarySearch &&
  610. ScriptableImGui::SliderInt("Prediction # ##Positional", &m_predictionSampleCountsPositional[index], 4, 16))
  611. {
  612. settingsChanged = true;
  613. }
  614. if (ScriptableImGui::SliderInt("Filtering # ##Positional", &m_filteringSampleCountsPositional[index], 4, 64))
  615. {
  616. settingsChanged = true;
  617. }
  618. int pcfMethodAsInteger = aznumeric_cast<int>(m_pcfMethod[index]);
  619. if (ScriptableImGui::RadioButton(
  620. "Boundary Search filtering", &pcfMethodAsInteger, static_cast<int>(PcfMethod::BoundarySearch)))
  621. {
  622. m_pcfMethod[index] = PcfMethod::BoundarySearch;
  623. settingsChanged = true;
  624. }
  625. if (ScriptableImGui::RadioButton("Bicubic filtering", &pcfMethodAsInteger, static_cast<int>(PcfMethod::Bicubic)))
  626. {
  627. m_pcfMethod[index] = PcfMethod::Bicubic;
  628. settingsChanged = true;
  629. }
  630. }
  631. }
  632. ImGui::Unindent();
  633. return settingsChanged;
  634. }
  635. void ShadowExampleComponent::DrawSidebarCamera()
  636. {
  637. ImGui::Indent();
  638. if (ImGui::CollapsingHeader("Camera", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed))
  639. {
  640. using namespace AZ;
  641. ScriptableImGui::SliderAngle("FoVY", &m_cameraFovY, 1.f, 120.f);
  642. ImGui::Spacing();
  643. Transform cameraTransform;
  644. TransformBus::EventResult(cameraTransform, GetCameraEntityId(), &TransformBus::Events::GetWorldTM);
  645. const Vector3 eularDegrees = cameraTransform.GetEulerDegrees();
  646. float cameraPitch = eularDegrees.GetElement(0);
  647. const float cameraYaw = eularDegrees.GetElement(1);
  648. if (cameraPitch > 180.f)
  649. {
  650. cameraPitch -= 360.f;
  651. }
  652. ImGui::Text("Pitch: %f", cameraPitch);
  653. ImGui::Text("Yaw: %f", cameraYaw);
  654. }
  655. ImGui::Unindent();
  656. }
  657. void ShadowExampleComponent::SetupDebugFlags()
  658. {
  659. int flags = AZ::Render::DirectionalLightFeatureProcessorInterface::DebugDrawFlags::DebugDrawNone;
  660. if (m_isDebugColoringEnabled)
  661. {
  662. flags |= AZ::Render::DirectionalLightFeatureProcessorInterface::DebugDrawFlags::DebugDrawColoring;
  663. }
  664. if (m_isDebugBoundingBoxEnabled)
  665. {
  666. flags |= AZ::Render::DirectionalLightFeatureProcessorInterface::DebugDrawFlags::DebugDrawBoundingBoxes;
  667. }
  668. m_directionalLightFeatureProcessor->SetDebugFlags(m_directionalLightHandle,
  669. static_cast<AZ::Render::DirectionalLightFeatureProcessorInterface::DebugDrawFlags>(flags));
  670. }
  671. void ShadowExampleComponent::DestroyDiskLights()
  672. {
  673. for (DiskLightHandle& handle : m_diskLightHandles)
  674. {
  675. m_diskLightFeatureProcessor->ReleaseLight(handle);
  676. }
  677. }
  678. void ShadowExampleComponent::DestroyPointLights()
  679. {
  680. for (PointLightHandle& handle : m_pointLightHandles)
  681. {
  682. m_pointLightFeatureProcessor->ReleaseLight(handle);
  683. }
  684. }
  685. void ShadowExampleComponent::ApplyDiskLightSettings()
  686. {
  687. for (uint32_t index = 0; index < PositionalLightCount; ++index)
  688. {
  689. auto lightHandle = m_diskLightHandles[index];
  690. if (lightHandle.IsValid())
  691. {
  692. auto [innerConeAngle, outerConeAngle] = GetConeAnglesForLight(index);
  693. m_diskLightFeatureProcessor->SetConeAngles(lightHandle, innerConeAngle, outerConeAngle);
  694. m_diskLightFeatureProcessor->SetPosition(lightHandle, GetTransformForLight(index).GetTranslation());
  695. m_diskLightFeatureProcessor->SetDirection(lightHandle, GetTransformForLight(index).GetBasis(1));
  696. m_diskLightFeatureProcessor->SetAttenuationRadius(lightHandle, GetAttenuationForLight(index));
  697. m_diskLightFeatureProcessor->SetRgbIntensity(lightHandle, GetRgbIntensityForLight(index));
  698. const bool shadowEnabled = m_positionalLightShadowEnabled[index];
  699. m_diskLightFeatureProcessor->SetShadowsEnabled(lightHandle, shadowEnabled);
  700. if (shadowEnabled)
  701. {
  702. m_diskLightFeatureProcessor->SetShadowmapMaxResolution(
  703. lightHandle, s_shadowmapImageSizes[m_positionalLightImageSizeIndices[index]]);
  704. m_diskLightFeatureProcessor->SetShadowFilterMethod(
  705. lightHandle, s_shadowFilterMethods[m_shadowFilterMethodIndicesPositional[index]]);
  706. m_diskLightFeatureProcessor->SetSofteningBoundaryWidthAngle(lightHandle, AZ::DegToRad(m_boundaryWidthsPositional[index]));
  707. m_diskLightFeatureProcessor->SetFilteringSampleCount(lightHandle, m_filteringSampleCountsPositional[index]);
  708. m_diskLightFeatureProcessor->SetPredictionSampleCount(lightHandle, m_predictionSampleCountsPositional[index]);
  709. m_diskLightFeatureProcessor->SetPcfMethod(lightHandle, m_pcfMethod[index]);
  710. }
  711. }
  712. }
  713. }
  714. void ShadowExampleComponent::ApplyPointLightSettings()
  715. {
  716. for (uint32_t index = 0; index < PositionalLightCount; ++index)
  717. {
  718. auto lightHandle = m_pointLightHandles[index];
  719. if (lightHandle.IsValid())
  720. {
  721. m_pointLightFeatureProcessor->SetPosition(lightHandle, GetTransformForLight(index).GetTranslation());
  722. m_pointLightFeatureProcessor->SetBulbRadius(lightHandle, 0.0f);
  723. m_pointLightFeatureProcessor->SetAttenuationRadius(lightHandle, GetAttenuationForLight(index));
  724. m_pointLightFeatureProcessor->SetRgbIntensity(lightHandle, GetRgbIntensityForLight(index));
  725. const bool shadowEnabled = m_positionalLightShadowEnabled[index];
  726. m_pointLightFeatureProcessor->SetShadowsEnabled(lightHandle, shadowEnabled);
  727. if (shadowEnabled)
  728. {
  729. m_pointLightFeatureProcessor->SetShadowmapMaxResolution(
  730. lightHandle, s_shadowmapImageSizes[m_positionalLightImageSizeIndices[index]]);
  731. m_pointLightFeatureProcessor->SetShadowFilterMethod(
  732. lightHandle, s_shadowFilterMethods[m_shadowFilterMethodIndicesPositional[index]]);
  733. m_pointLightFeatureProcessor->SetPcfMethod(lightHandle, m_pcfMethod[index]);
  734. m_pointLightFeatureProcessor->SetFilteringSampleCount(lightHandle, m_filteringSampleCountsPositional[index]);
  735. m_pointLightFeatureProcessor->SetPredictionSampleCount(lightHandle, m_predictionSampleCountsPositional[index]);
  736. m_pointLightFeatureProcessor->SetSofteningBoundaryWidthAngle(lightHandle, AZ::DegToRad(m_boundaryWidthsPositional[index]));
  737. }
  738. }
  739. }
  740. }
  741. } // namespace AtomSampleViewer