CommonSampleComponentBase.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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]);
  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_lightingPresets.clear();
  134. m_lightingPresetsDirty = true;
  135. }
  136. void CommonSampleComponentBase::ImGuiLightingPreset()
  137. {
  138. AZ_Assert((m_currentLightingPresetIndex == InvalidLightingPresetIndex) == m_lightingPresets.empty(),
  139. "m_currentLightingPresetIndex should be invalid if and only if no lighting presets are loaded.");
  140. if (m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  141. {
  142. AZ_Warning("Lighting Preset", false, "Lighting presets must be loaded before calling ImGui.");
  143. return;
  144. }
  145. AZStd::vector<const char*> items;
  146. for (const auto& lightingPreset : m_lightingPresets)
  147. {
  148. items.push_back(lightingPreset.m_displayName.c_str());
  149. }
  150. if (ScriptableImGui::Combo("Lighting Preset##SampleBase", &m_currentLightingPresetIndex, items.begin(), aznumeric_cast<int>(items.size())))
  151. {
  152. OnLightingPresetSelected(m_lightingPresets[m_currentLightingPresetIndex]);
  153. }
  154. }
  155. void CommonSampleComponentBase::OnLightingPresetSelected(const AZ::Render::LightingPreset& preset)
  156. {
  157. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  158. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::PostProcessFeatureProcessorInterface>(m_entityContextId);
  159. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::ImageBasedLightFeatureProcessorInterface>(m_entityContextId);
  160. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  161. AZ::Render::ExposureControlSettingsInterface* exposureControlSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(m_postProcessEntity->GetId())->GetOrCreateExposureControlSettingsInterface();
  162. Camera::Configuration cameraConfig;
  163. Camera::CameraRequestBus::EventResult(cameraConfig, m_cameraEntityId, &Camera::CameraRequestBus::Events::GetCameraConfiguration);
  164. preset.ApplyLightingPreset(
  165. iblFeatureProcessor,
  166. skyboxFeatureProcessor,
  167. exposureControlSettingInterface,
  168. directionalLightFeatureProcessor,
  169. cameraConfig,
  170. m_lightHandles);
  171. }
  172. void CommonSampleComponentBase::OnTransformChanged(const AZ::Transform&, const AZ::Transform&)
  173. {
  174. const AZ::EntityId* currentBusId = AZ::TransformNotificationBus::GetCurrentBusId();
  175. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  176. if (currentBusId && *currentBusId == m_cameraEntityId && directionalLightFeatureProcessor)
  177. {
  178. auto transform = AZ::Transform::CreateIdentity();
  179. AZ::TransformBus::EventResult(
  180. transform,
  181. m_cameraEntityId,
  182. &AZ::TransformBus::Events::GetWorldTM);
  183. for (const AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  184. {
  185. directionalLightFeatureProcessor->SetCameraTransform(handle, transform);
  186. }
  187. }
  188. }
  189. void CommonSampleComponentBase::OnLightingPresetEntityShutdown(const AZ::EntityId& entityId)
  190. {
  191. if (m_postProcessEntity && m_postProcessEntity->GetId() == entityId)
  192. {
  193. m_postProcessEntity = nullptr;
  194. }
  195. }
  196. void CommonSampleComponentBase::PreloadAssets(const AZStd::vector<AssetCollectionAsyncLoader::AssetToLoadInfo>& assetList)
  197. {
  198. m_isAllAssetsReady = false;
  199. // Configure the imgui progress list widget.
  200. auto onUserCancelledAction = [&]()
  201. {
  202. AZ_TracePrintf(m_sampleName.c_str() , "Cancelled by user.\n");
  203. m_assetLoadManager.Cancel();
  204. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  205. };
  206. m_imguiProgressList.OpenPopup("Waiting For Assets...", "Assets pending for processing:", {}, onUserCancelledAction, true /*automaticallyCloseOnAction*/, "Cancel");
  207. AZStd::for_each(assetList.begin(), assetList.end(),
  208. [&](const AssetCollectionAsyncLoader::AssetToLoadInfo& item) { m_imguiProgressList.AddItem(item.m_assetPath); });
  209. m_assetLoadManager.LoadAssetsAsync(assetList, [&](AZStd::string_view assetName, [[maybe_unused]] bool success, size_t pendingAssetCount)
  210. {
  211. AZ_Error(m_sampleName.c_str(), success, "Error loading asset %s, a crash will occur when OnAllAssetsReadyActivate() is called!", assetName.data());
  212. 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);
  213. m_imguiProgressList.RemoveItem(assetName);
  214. if (!pendingAssetCount && !m_isAllAssetsReady)
  215. {
  216. m_isAllAssetsReady = true;
  217. OnAllAssetsReadyActivate();
  218. }
  219. });
  220. }
  221. } // namespace AtomSampleViewer