CommonSampleComponentBase.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 <CommonSampleComponentBase.h>
  13. #include <SampleComponentManager.h>
  14. #include <SampleComponentConfig.h>
  15. #include <Automation/ScriptableImGui.h>
  16. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  17. #include <Atom/RPI.Public/Image/StreamingImage.h>
  18. #include <RHI/BasicRHIComponent.h>
  19. #include <EntityUtilityFunctions.h>
  20. namespace AtomSampleViewer
  21. {
  22. using namespace AZ;
  23. using namespace RPI;
  24. bool CommonSampleComponentBase::ReadInConfig(const ComponentConfig* baseConfig)
  25. {
  26. auto config = azrtti_cast<const SampleComponentConfig*>(baseConfig);
  27. if (config && config->IsValid())
  28. {
  29. m_cameraEntityId = config->m_cameraEntityId;
  30. m_entityContextId = config->m_entityContextId;
  31. return true;
  32. }
  33. else
  34. {
  35. AZ_Assert(false, "SampleComponentConfig required for sample component configuration.");
  36. return false;
  37. }
  38. }
  39. AzFramework::EntityContextId CommonSampleComponentBase::GetEntityContextId() const
  40. {
  41. return m_entityContextId;
  42. }
  43. AZ::EntityId CommonSampleComponentBase::GetCameraEntityId() const
  44. {
  45. return m_cameraEntityId;
  46. }
  47. AZ::Render::MeshFeatureProcessorInterface* CommonSampleComponentBase::GetMeshFeatureProcessor() const
  48. {
  49. if (!m_meshFeatureProcessor)
  50. {
  51. m_meshFeatureProcessor = Scene::GetFeatureProcessorForEntityContextId<Render::MeshFeatureProcessorInterface>(m_entityContextId);
  52. AZ_Assert(m_meshFeatureProcessor, "MeshFeatureProcessor not available.");
  53. }
  54. return m_meshFeatureProcessor;
  55. }
  56. void CommonSampleComponentBase::InitLightingPresets(bool loadDefaultLightingPresets)
  57. {
  58. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(GetEntityContextId());
  59. AZ_Assert(skyboxFeatureProcessor, "Unable to find SkyBoxFeatureProcessorInterface.");
  60. skyboxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  61. skyboxFeatureProcessor->Enable(true);
  62. // We don't necessarily need an entity but PostProcessFeatureProcessorInterface needs an ID to retrieve ExposureControlSettingsInterface.
  63. AzFramework::EntityContextRequestBus::EventResult(m_postProcessEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "postProcessEntity");
  64. AZ_Assert(m_postProcessEntity != nullptr, "Failed to create post process entity.");
  65. m_postProcessEntity->Activate();
  66. if (loadDefaultLightingPresets)
  67. {
  68. AZStd::list<AZ::Data::AssetInfo> lightingAssetInfoList;
  69. AZ::Data::AssetCatalogRequests::AssetEnumerationCB enumerateCB = [&lightingAssetInfoList]([[maybe_unused]] const AZ::Data::AssetId id, const AZ::Data::AssetInfo& info)
  70. {
  71. if (AzFramework::StringFunc::EndsWith(info.m_relativePath.c_str(), ".lightingpreset.azasset"))
  72. {
  73. lightingAssetInfoList.push_front(info);
  74. }
  75. };
  76. AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::EnumerateAssets, nullptr, enumerateCB, nullptr);
  77. for (const auto& info : lightingAssetInfoList)
  78. {
  79. AppendLightingPresetsFromAsset(info.m_relativePath);
  80. }
  81. }
  82. AZ::TransformNotificationBus::MultiHandler::BusConnect(m_cameraEntityId);
  83. AZ::EntityBus::MultiHandler::BusConnect(m_postProcessEntity->GetId());
  84. }
  85. void CommonSampleComponentBase::ShutdownLightingPresets()
  86. {
  87. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  88. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  89. for (AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  90. {
  91. directionalLightFeatureProcessor->ReleaseLight(handle);
  92. }
  93. m_lightHandles.clear();
  94. ClearLightingPresets();
  95. if (m_postProcessEntity)
  96. {
  97. DestroyEntity(m_postProcessEntity, GetEntityContextId());
  98. }
  99. skyboxFeatureProcessor->Enable(false);
  100. AZ::TransformNotificationBus::MultiHandler::BusDisconnect();
  101. AZ::EntityBus::MultiHandler::BusDisconnect();
  102. }
  103. void CommonSampleComponentBase::LoadLightingPresetsFromAsset(const AZStd::string& assetPath)
  104. {
  105. ClearLightingPresets();
  106. AppendLightingPresetsFromAsset(assetPath);
  107. }
  108. void CommonSampleComponentBase::AppendLightingPresetsFromAsset(const AZStd::string& assetPath)
  109. {
  110. Data::Asset<AnyAsset> asset = AssetUtils::LoadAssetByProductPath<AnyAsset>(assetPath.c_str(), AssetUtils::TraceLevel::Error);
  111. if (asset)
  112. {
  113. const AZ::Render::LightingPreset* preset = asset->GetDataAs<AZ::Render::LightingPreset>();
  114. if (preset)
  115. {
  116. m_lightingPresets.push_back(*preset);
  117. }
  118. m_lightingPresetsDirty = true;
  119. if (!m_lightingPresets.empty() && m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  120. {
  121. m_currentLightingPresetIndex = 0;
  122. OnLightingPresetSelected(m_lightingPresets[0], m_useAlternateSkybox);
  123. }
  124. }
  125. else
  126. {
  127. AZ_Error("Lighting Preset", false, "Lighting preset file failed to load from path: %s.", assetPath.c_str());
  128. }
  129. }
  130. void CommonSampleComponentBase::ClearLightingPresets()
  131. {
  132. m_currentLightingPresetIndex = InvalidLightingPresetIndex;
  133. m_useAlternateSkybox = false;
  134. m_lightingPresets.clear();
  135. m_lightingPresetsDirty = true;
  136. }
  137. void CommonSampleComponentBase::ImGuiLightingPreset()
  138. {
  139. AZ_Assert((m_currentLightingPresetIndex == InvalidLightingPresetIndex) == m_lightingPresets.empty(),
  140. "m_currentLightingPresetIndex should be invalid if and only if no lighting presets are loaded.");
  141. if (m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  142. {
  143. AZ_Warning("Lighting Preset", false, "Lighting presets must be loaded before calling ImGui.");
  144. return;
  145. }
  146. AZStd::string selectedPresetLabel = m_lightingPresets[m_currentLightingPresetIndex].m_displayName;
  147. if (m_useAlternateSkybox)
  148. {
  149. selectedPresetLabel += " (Alt)";
  150. }
  151. // Note that before we were using ScriptableImGui::Combo but there were issues (at least on some systems) when the number of items
  152. // exceeded the max visible item count (which defaults to 8 in ImGui). In this case you'd expect to see a scroll bar in the combo box,
  153. // but the combo box just never popped up. This only happened in profile, not debug builds. It seems to be a bug in ImGui. So by using
  154. // BeginCombo with ImGuiComboFlags_HeightLargest, we just make sure the combo box is always big enough for all the items.
  155. if (ScriptableImGui::BeginCombo("Lighting Preset##SampleBase", selectedPresetLabel.c_str(), ImGuiComboFlags_HeightLargest))
  156. {
  157. for (uint32_t i = 0; i < m_lightingPresets.size(); ++i)
  158. {
  159. AZStd::string& name = m_lightingPresets[i].m_displayName;
  160. AZStd::string nameForAlternateSkybox = name + " (Alt)";
  161. // Each LightingPreset can have an alternate skybox (usually a blurred version of the primary skybox), so we expose both here as separate items in the UI.
  162. bool useThisPresetWithNormalSkybox = (i == m_currentLightingPresetIndex) && !m_useAlternateSkybox;
  163. bool useThisPresetWithAlternateSkybox = (i == m_currentLightingPresetIndex) && m_useAlternateSkybox;
  164. useThisPresetWithNormalSkybox = ScriptableImGui::Selectable(name.c_str(), useThisPresetWithNormalSkybox);
  165. useThisPresetWithAlternateSkybox = ScriptableImGui::Selectable(nameForAlternateSkybox.c_str(), useThisPresetWithAlternateSkybox);
  166. if (useThisPresetWithNormalSkybox || useThisPresetWithAlternateSkybox)
  167. {
  168. m_currentLightingPresetIndex = i;
  169. m_useAlternateSkybox = useThisPresetWithAlternateSkybox;
  170. OnLightingPresetSelected(m_lightingPresets[i], m_useAlternateSkybox);
  171. }
  172. }
  173. ScriptableImGui::EndCombo();
  174. }
  175. }
  176. void CommonSampleComponentBase::OnLightingPresetSelected(const AZ::Render::LightingPreset& preset, bool useAlternateSkybox)
  177. {
  178. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  179. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::PostProcessFeatureProcessorInterface>(m_entityContextId);
  180. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::ImageBasedLightFeatureProcessorInterface>(m_entityContextId);
  181. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  182. AZ::Render::ExposureControlSettingsInterface* exposureControlSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(m_postProcessEntity->GetId())->GetOrCreateExposureControlSettingsInterface();
  183. Camera::Configuration cameraConfig;
  184. Camera::CameraRequestBus::EventResult(cameraConfig, m_cameraEntityId, &Camera::CameraRequestBus::Events::GetCameraConfiguration);
  185. preset.ApplyLightingPreset(
  186. iblFeatureProcessor,
  187. skyboxFeatureProcessor,
  188. exposureControlSettingInterface,
  189. directionalLightFeatureProcessor,
  190. cameraConfig,
  191. m_lightHandles,
  192. nullptr,
  193. AZ::RPI::MaterialPropertyIndex{},
  194. useAlternateSkybox);
  195. }
  196. void CommonSampleComponentBase::OnTransformChanged(const AZ::Transform&, const AZ::Transform&)
  197. {
  198. const AZ::EntityId* currentBusId = AZ::TransformNotificationBus::GetCurrentBusId();
  199. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  200. if (currentBusId && *currentBusId == m_cameraEntityId && directionalLightFeatureProcessor)
  201. {
  202. auto transform = AZ::Transform::CreateIdentity();
  203. AZ::TransformBus::EventResult(
  204. transform,
  205. m_cameraEntityId,
  206. &AZ::TransformBus::Events::GetWorldTM);
  207. for (const AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  208. {
  209. directionalLightFeatureProcessor->SetCameraTransform(handle, transform);
  210. }
  211. }
  212. }
  213. void CommonSampleComponentBase::OnLightingPresetEntityShutdown(const AZ::EntityId& entityId)
  214. {
  215. if (m_postProcessEntity && m_postProcessEntity->GetId() == entityId)
  216. {
  217. m_postProcessEntity = nullptr;
  218. }
  219. }
  220. void CommonSampleComponentBase::PreloadAssets(const AZStd::vector<AssetCollectionAsyncLoader::AssetToLoadInfo>& assetList)
  221. {
  222. m_isAllAssetsReady = false;
  223. // Configure the imgui progress list widget.
  224. auto onUserCancelledAction = [&]()
  225. {
  226. AZ_TracePrintf(m_sampleName.c_str() , "Cancelled by user.\n");
  227. m_assetLoadManager.Cancel();
  228. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  229. };
  230. m_imguiProgressList.OpenPopup("Waiting For Assets...", "Assets pending for processing:", {}, onUserCancelledAction, true /*automaticallyCloseOnAction*/, "Cancel");
  231. AZStd::for_each(assetList.begin(), assetList.end(),
  232. [&](const AssetCollectionAsyncLoader::AssetToLoadInfo& item) { m_imguiProgressList.AddItem(item.m_assetPath); });
  233. m_assetLoadManager.LoadAssetsAsync(assetList, [&](AZStd::string_view assetName, [[maybe_unused]] bool success, size_t pendingAssetCount)
  234. {
  235. AZ_Error(m_sampleName.c_str(), success, "Error loading asset %s, a crash will occur when OnAllAssetsReadyActivate() is called!", assetName.data());
  236. AZ_TracePrintf(m_sampleName.c_str(), "Asset %s loaded %s. Wait for %zu more assets before full activation\n", assetName.data(), success ? "successfully" : "UNSUCCESSFULLY", pendingAssetCount);
  237. m_imguiProgressList.RemoveItem(assetName);
  238. if (!pendingAssetCount && !m_isAllAssetsReady)
  239. {
  240. m_isAllAssetsReady = true;
  241. OnAllAssetsReadyActivate();
  242. }
  243. });
  244. }
  245. } // namespace AtomSampleViewer