CommonSampleComponentBase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 <CommonSampleComponentBase.h>
  9. #include <SampleComponentManager.h>
  10. #include <SampleComponentConfig.h>
  11. #include <Automation/ScriptableImGui.h>
  12. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  13. #include <Atom/RPI.Public/Image/StreamingImage.h>
  14. #include <RHI/BasicRHIComponent.h>
  15. #include <EntityUtilityFunctions.h>
  16. namespace AtomSampleViewer
  17. {
  18. using namespace AZ;
  19. using namespace RPI;
  20. void CommonSampleComponentBase::Reflect(ReflectContext* context)
  21. {
  22. if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context))
  23. {
  24. serializeContext->Class<CommonSampleComponentBase, Component>()
  25. ->Version(0)
  26. ;
  27. }
  28. }
  29. bool CommonSampleComponentBase::ReadInConfig(const ComponentConfig* baseConfig)
  30. {
  31. m_scene = RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("RPI"));
  32. auto config = azrtti_cast<const SampleComponentConfig*>(baseConfig);
  33. if (config && config->IsValid())
  34. {
  35. m_cameraEntityId = config->m_cameraEntityId;
  36. m_entityContextId = config->m_entityContextId;
  37. return true;
  38. }
  39. else
  40. {
  41. AZ_Assert(false, "SampleComponentConfig required for sample component configuration.");
  42. return false;
  43. }
  44. }
  45. AzFramework::EntityContextId CommonSampleComponentBase::GetEntityContextId() const
  46. {
  47. return m_entityContextId;
  48. }
  49. AZ::EntityId CommonSampleComponentBase::GetCameraEntityId() const
  50. {
  51. return m_cameraEntityId;
  52. }
  53. AZ::Render::MeshFeatureProcessorInterface* CommonSampleComponentBase::GetMeshFeatureProcessor() const
  54. {
  55. if (!m_meshFeatureProcessor)
  56. {
  57. m_meshFeatureProcessor = Scene::GetFeatureProcessorForEntityContextId<Render::MeshFeatureProcessorInterface>(m_entityContextId);
  58. AZ_Assert(m_meshFeatureProcessor, "MeshFeatureProcessor not available.");
  59. }
  60. return m_meshFeatureProcessor;
  61. }
  62. void CommonSampleComponentBase::InitLightingPresets(bool loadDefaultLightingPresets)
  63. {
  64. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(GetEntityContextId());
  65. AZ_Assert(skyboxFeatureProcessor, "Unable to find SkyBoxFeatureProcessorInterface.");
  66. skyboxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  67. skyboxFeatureProcessor->Enable(true);
  68. if (loadDefaultLightingPresets)
  69. {
  70. AZStd::list<AZ::Data::AssetInfo> lightingAssetInfoList;
  71. AZ::Data::AssetCatalogRequests::AssetEnumerationCB enumerateCB = [&lightingAssetInfoList]([[maybe_unused]] const AZ::Data::AssetId id, const AZ::Data::AssetInfo& info)
  72. {
  73. if (AzFramework::StringFunc::EndsWith(info.m_relativePath.c_str(), ".lightingpreset.azasset"))
  74. {
  75. lightingAssetInfoList.push_front(info);
  76. }
  77. };
  78. AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::EnumerateAssets, nullptr, enumerateCB, nullptr);
  79. for (const auto& info : lightingAssetInfoList)
  80. {
  81. AppendLightingPresetsFromAsset(info.m_relativePath);
  82. }
  83. }
  84. // set the initial lighting preset
  85. static const char* InitialLightingPresetName = "Palermo Sidewalk";
  86. for (uint32_t index = 0; index < m_lightingPresets.size(); ++index)
  87. {
  88. if (AZ::StringFunc::Contains(m_lightingPresets[index].m_displayName, InitialLightingPresetName))
  89. {
  90. m_currentLightingPresetIndex = index;
  91. OnLightingPresetSelected(m_lightingPresets[m_currentLightingPresetIndex].m_preset, m_useAlternateSkybox);
  92. break;
  93. }
  94. }
  95. AZ::TransformNotificationBus::MultiHandler::BusConnect(m_cameraEntityId);
  96. }
  97. void CommonSampleComponentBase::ShutdownLightingPresets()
  98. {
  99. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  100. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  101. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::ImageBasedLightFeatureProcessorInterface>(m_entityContextId);
  102. for (AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  103. {
  104. directionalLightFeatureProcessor->ReleaseLight(handle);
  105. }
  106. m_lightHandles.clear();
  107. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::PostProcessFeatureProcessorInterface>(m_entityContextId);
  108. postProcessFeatureProcessor->RemoveSettingsInterface(GetEntityId());
  109. ClearLightingPresets();
  110. skyboxFeatureProcessor->Enable(false);
  111. iblFeatureProcessor->Reset();
  112. AZ::TransformNotificationBus::MultiHandler::BusDisconnect();
  113. AZ::EntityBus::MultiHandler::BusDisconnect();
  114. }
  115. void CommonSampleComponentBase::LoadLightingPresetsFromAsset(const AZStd::string& assetPath)
  116. {
  117. ClearLightingPresets();
  118. AppendLightingPresetsFromAsset(assetPath);
  119. }
  120. void CommonSampleComponentBase::AppendLightingPresetsFromAsset(const AZStd::string& assetPath)
  121. {
  122. Data::Asset<AnyAsset> asset = AssetUtils::LoadAssetByProductPath<AnyAsset>(assetPath.c_str(), AssetUtils::TraceLevel::Error);
  123. if (asset)
  124. {
  125. const AZ::Render::LightingPreset* preset = asset->GetDataAs<AZ::Render::LightingPreset>();
  126. if (preset)
  127. {
  128. AZStd::string displayName;
  129. AZ::StringFunc::Path::GetFullFileName(assetPath.c_str(), displayName);
  130. AZ::StringFunc::Replace(displayName, ".lightingpreset.azasset", "");
  131. AZStd::vector<AZStd::string> displayNameParts;
  132. AZ::StringFunc::Tokenize(displayName, displayNameParts, "\\/, ()_-");
  133. for (auto& displayNamePart : displayNameParts)
  134. {
  135. displayNamePart[0] = aznumeric_cast<char>(toupper(displayNamePart[0]));
  136. }
  137. displayName.clear();
  138. AZ::StringFunc::Join(displayName, displayNameParts, ' ');
  139. m_lightingPresets.push_back({ displayName, *preset });
  140. }
  141. m_lightingPresetsDirty = true;
  142. if (!m_lightingPresets.empty() && m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  143. {
  144. m_currentLightingPresetIndex = 0;
  145. OnLightingPresetSelected(m_lightingPresets[0].m_preset, m_useAlternateSkybox);
  146. }
  147. }
  148. else
  149. {
  150. AZ_Error("Lighting Preset", false, "Lighting preset file failed to load from path: %s.", assetPath.c_str());
  151. }
  152. }
  153. void CommonSampleComponentBase::ClearLightingPresets()
  154. {
  155. m_currentLightingPresetIndex = InvalidLightingPresetIndex;
  156. m_useAlternateSkybox = false;
  157. m_lightingPresets.clear();
  158. m_lightingPresetsDirty = true;
  159. }
  160. void CommonSampleComponentBase::ImGuiLightingPreset()
  161. {
  162. AZ_Assert((m_currentLightingPresetIndex == InvalidLightingPresetIndex) == m_lightingPresets.empty(),
  163. "m_currentLightingPresetIndex should be invalid if and only if no lighting presets are loaded.");
  164. if (m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  165. {
  166. AZ_Warning("Lighting Preset", false, "Lighting presets must be loaded before calling ImGui.");
  167. return;
  168. }
  169. AZStd::string selectedPresetLabel = m_lightingPresets[m_currentLightingPresetIndex].m_displayName;
  170. if (m_useAlternateSkybox)
  171. {
  172. selectedPresetLabel += " (Alt)";
  173. }
  174. // Note that before we were using ScriptableImGui::Combo but there were issues (at least on some systems) when the number of items
  175. // 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,
  176. // 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
  177. // BeginCombo with ImGuiComboFlags_HeightLargest, we just make sure the combo box is always big enough for all the items.
  178. if (ScriptableImGui::BeginCombo("Lighting Preset##SampleBase", selectedPresetLabel.c_str(), ImGuiComboFlags_HeightLargest))
  179. {
  180. for (uint32_t i = 0; i < m_lightingPresets.size(); ++i)
  181. {
  182. AZStd::string& name = m_lightingPresets[i].m_displayName;
  183. AZStd::string nameForAlternateSkybox = name + " (Alt)";
  184. // 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.
  185. bool useThisPresetWithNormalSkybox = (static_cast<int32_t>(i) == m_currentLightingPresetIndex) && !m_useAlternateSkybox;
  186. bool useThisPresetWithAlternateSkybox = (static_cast<int32_t>(i) == m_currentLightingPresetIndex) && m_useAlternateSkybox;
  187. useThisPresetWithNormalSkybox = ScriptableImGui::Selectable(name.c_str(), useThisPresetWithNormalSkybox);
  188. useThisPresetWithAlternateSkybox = ScriptableImGui::Selectable(nameForAlternateSkybox.c_str(), useThisPresetWithAlternateSkybox);
  189. if (useThisPresetWithNormalSkybox || useThisPresetWithAlternateSkybox)
  190. {
  191. m_currentLightingPresetIndex = i;
  192. m_useAlternateSkybox = useThisPresetWithAlternateSkybox;
  193. OnLightingPresetSelected(m_lightingPresets[i].m_preset, m_useAlternateSkybox);
  194. }
  195. }
  196. ScriptableImGui::EndCombo();
  197. }
  198. }
  199. void CommonSampleComponentBase::IterateToNextLightingPreset()
  200. {
  201. m_currentLightingPresetIndex = (m_currentLightingPresetIndex + 1) % m_lightingPresets.size();
  202. OnLightingPresetSelected(m_lightingPresets[m_currentLightingPresetIndex].m_preset, m_useAlternateSkybox);
  203. }
  204. void CommonSampleComponentBase::OnLightingPresetSelected(const AZ::Render::LightingPreset& preset, bool useAlternateSkybox)
  205. {
  206. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  207. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::PostProcessFeatureProcessorInterface>(m_entityContextId);
  208. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::ImageBasedLightFeatureProcessorInterface>(m_entityContextId);
  209. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  210. AZ::Render::ExposureControlSettingsInterface* exposureControlSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(GetEntityId())->GetOrCreateExposureControlSettingsInterface();
  211. Camera::Configuration cameraConfig;
  212. Camera::CameraRequestBus::EventResult(cameraConfig, m_cameraEntityId, &Camera::CameraRequestBus::Events::GetCameraConfiguration);
  213. preset.ApplyLightingPreset(
  214. iblFeatureProcessor,
  215. skyboxFeatureProcessor,
  216. exposureControlSettingInterface,
  217. directionalLightFeatureProcessor,
  218. cameraConfig,
  219. m_lightHandles,
  220. useAlternateSkybox);
  221. }
  222. void CommonSampleComponentBase::OnTransformChanged(const AZ::Transform&, const AZ::Transform&)
  223. {
  224. const AZ::EntityId* currentBusId = AZ::TransformNotificationBus::GetCurrentBusId();
  225. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  226. if (currentBusId && *currentBusId == m_cameraEntityId && directionalLightFeatureProcessor)
  227. {
  228. auto transform = AZ::Transform::CreateIdentity();
  229. AZ::TransformBus::EventResult(
  230. transform,
  231. m_cameraEntityId,
  232. &AZ::TransformBus::Events::GetWorldTM);
  233. for (const AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  234. {
  235. directionalLightFeatureProcessor->SetCameraTransform(handle, transform);
  236. }
  237. }
  238. }
  239. void CommonSampleComponentBase::PreloadAssets(const AZStd::vector<AssetCollectionAsyncLoader::AssetToLoadInfo>& assetList)
  240. {
  241. m_isAllAssetsReady = false;
  242. // Configure the imgui progress list widget.
  243. auto onUserCancelledAction = [&]()
  244. {
  245. AZ_TracePrintf(m_sampleName.c_str() , "Cancelled by user.\n");
  246. m_assetLoadManager.Cancel();
  247. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  248. };
  249. m_imguiProgressList.OpenPopup("Waiting For Assets...", "Assets pending for processing:", {}, onUserCancelledAction, true /*automaticallyCloseOnAction*/, "Cancel");
  250. AZStd::for_each(assetList.begin(), assetList.end(),
  251. [&](const AssetCollectionAsyncLoader::AssetToLoadInfo& item) { m_imguiProgressList.AddItem(item.m_assetPath); });
  252. m_assetLoadManager.LoadAssetsAsync(assetList, [&](AZStd::string_view assetName, [[maybe_unused]] bool success, size_t pendingAssetCount)
  253. {
  254. AZ_Error(m_sampleName.c_str(), success, "Error loading asset %s, a crash will occur when OnAllAssetsReadyActivate() is called!", assetName.data());
  255. 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);
  256. m_imguiProgressList.RemoveItem(assetName);
  257. if (!pendingAssetCount && !m_isAllAssetsReady)
  258. {
  259. m_isAllAssetsReady = true;
  260. OnAllAssetsReadyActivate();
  261. }
  262. });
  263. }
  264. void CommonSampleComponentBase::ResetScene()
  265. {
  266. m_meshFeatureProcessor = nullptr;
  267. m_scene = RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("RPI"));
  268. }
  269. } // namespace AtomSampleViewer