MeshExampleComponent.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  3. *
  4. * SPDX-License-Identifier: Apache-2.0 OR MIT
  5. *
  6. */
  7. #include <MeshExampleComponent.h>
  8. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  9. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  10. #include <Atom/RHI/Device.h>
  11. #include <Atom/RHI/Factory.h>
  12. #include <Atom/RPI.Public/View.h>
  13. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  14. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  15. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  16. #include <AzCore/Asset/AssetManagerBus.h>
  17. #include <AzCore/Component/Entity.h>
  18. #include <AzCore/IO/IOUtils.h>
  19. #include <AzCore/Serialization/SerializeContext.h>
  20. #include <AzCore/std/smart_ptr/make_shared.h>
  21. #include <AzCore/std/sort.h>
  22. #include <AzFramework/Components/TransformComponent.h>
  23. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  24. #include <SampleComponentManager.h>
  25. #include <SampleComponentConfig.h>
  26. #include <EntityUtilityFunctions.h>
  27. #include <Automation/ScriptableImGui.h>
  28. #include <Automation/ScriptRunnerBus.h>
  29. #include <RHI/BasicRHIComponent.h>
  30. namespace AtomSampleViewer
  31. {
  32. const char* MeshExampleComponent::CameraControllerNameTable[CameraControllerCount] =
  33. {
  34. "ArcBall",
  35. "NoClip"
  36. };
  37. void MeshExampleComponent::Reflect(AZ::ReflectContext* context)
  38. {
  39. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  40. {
  41. serializeContext->Class<MeshExampleComponent, AZ::Component>()
  42. ->Version(0)
  43. ;
  44. }
  45. }
  46. MeshExampleComponent::MeshExampleComponent()
  47. : m_materialBrowser("@user@/MeshExampleComponent/material_browser.xml")
  48. , m_modelBrowser("@user@/MeshExampleComponent/model_browser.xml")
  49. , m_imguiSidebar("@user@/MeshExampleComponent/sidebar.xml")
  50. {
  51. m_changedHandler = AZ::Render::MeshFeatureProcessorInterface::ModelChangedEvent::Handler
  52. {
  53. [&](AZ::Data::Instance<AZ::RPI::Model> model)
  54. {
  55. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  56. // This handler will be connected to the feature processor so that when the model is updated, the camera
  57. // controller will reset. This ensures the camera is a reasonable distance from the model when it resizes.
  58. ResetCameraController();
  59. UpdateGroundPlane();
  60. }
  61. };
  62. }
  63. void MeshExampleComponent::DefaultWindowCreated()
  64. {
  65. AZ::Render::Bootstrap::DefaultWindowBus::BroadcastResult(m_windowContext, &AZ::Render::Bootstrap::DefaultWindowBus::Events::GetDefaultWindowContext);
  66. }
  67. void MeshExampleComponent::CreateLowEndPipeline()
  68. {
  69. AZ::RPI::RenderPipelineDescriptor pipelineDesc;
  70. pipelineDesc.m_mainViewTagName = "MainCamera";
  71. pipelineDesc.m_name = "LowEndPipeline";
  72. pipelineDesc.m_rootPassTemplate = "LowEndPipelineTemplate";
  73. pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4;
  74. m_lowEndPipeline = AZ::RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext);
  75. }
  76. void MeshExampleComponent::DestroyLowEndPipeline()
  77. {
  78. m_lowEndPipeline = nullptr;
  79. }
  80. void MeshExampleComponent::ActivateLowEndPipeline()
  81. {
  82. AZ::RPI::ScenePtr defaultScene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene();
  83. m_originalPipeline = defaultScene->GetDefaultRenderPipeline();
  84. defaultScene->AddRenderPipeline(m_lowEndPipeline);
  85. m_lowEndPipeline->SetDefaultView(m_originalPipeline->GetDefaultView());
  86. defaultScene->RemoveRenderPipeline(m_originalPipeline->GetId());
  87. m_imguiScope = AZ::Render::ImGuiActiveContextScope::FromPass(AZ::RPI::PassHierarchyFilter({ m_lowEndPipeline->GetId().GetCStr(), "ImGuiPass" }));
  88. }
  89. void MeshExampleComponent::DeactivateLowEndPipeline()
  90. {
  91. m_imguiScope = {}; // restores previous ImGui context.
  92. AZ::RPI::ScenePtr defaultScene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene();
  93. defaultScene->AddRenderPipeline(m_originalPipeline);
  94. defaultScene->RemoveRenderPipeline(m_lowEndPipeline->GetId());
  95. }
  96. void MeshExampleComponent::Activate()
  97. {
  98. UseArcBallCameraController();
  99. m_materialBrowser.SetFilter([this](const AZ::Data::AssetInfo& assetInfo)
  100. {
  101. if (!AzFramework::StringFunc::Path::IsExtension(assetInfo.m_relativePath.c_str(), "azmaterial"))
  102. {
  103. return false;
  104. }
  105. if (m_showModelMaterials)
  106. {
  107. return true;
  108. }
  109. // Return true only if the azmaterial was generated from a ".material" file.
  110. // Materials with subid == 0, are 99.99% guaranteed to be generated from a ".material" file.
  111. // Without this assurance We would need to call AzToolsFramework::AssetSystem::AssetSystemRequest::GetSourceInfoBySourceUUID()
  112. // to figure out what's the source of this azmaterial. But, Atom can not include AzToolsFramework.
  113. return assetInfo.m_assetId.m_subId == 0;
  114. });
  115. m_modelBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  116. {
  117. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::ModelAsset>();
  118. });
  119. m_materialBrowser.Activate();
  120. m_modelBrowser.Activate();
  121. m_imguiSidebar.Activate();
  122. InitLightingPresets(true);
  123. AZ::Data::Asset<AZ::RPI::MaterialAsset> groundPlaneMaterialAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::MaterialAsset>(DefaultPbrMaterialPath, AZ::RPI::AssetUtils::TraceLevel::Error);
  124. m_groundPlaneMaterial = AZ::RPI::Material::FindOrCreate(groundPlaneMaterialAsset);
  125. m_groundPlaneModelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>("objects/plane.azmodel", AZ::RPI::AssetUtils::TraceLevel::Assert);
  126. AZ::TickBus::Handler::BusConnect();
  127. AZ::Render::Bootstrap::DefaultWindowNotificationBus::Handler::BusConnect();
  128. CreateLowEndPipeline();
  129. }
  130. void MeshExampleComponent::Deactivate()
  131. {
  132. if (m_useLowEndPipeline)
  133. {
  134. DeactivateLowEndPipeline();
  135. }
  136. DestroyLowEndPipeline();
  137. AZ::Render::Bootstrap::DefaultWindowNotificationBus::Handler::BusDisconnect();
  138. AZ::TickBus::Handler::BusDisconnect();
  139. m_imguiSidebar.Deactivate();
  140. m_materialBrowser.Deactivate();
  141. m_modelBrowser.Deactivate();
  142. RemoveController();
  143. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  144. GetMeshFeatureProcessor()->ReleaseMesh(m_groundPlandMeshHandle);
  145. m_modelAsset = {};
  146. m_groundPlaneModelAsset = {};
  147. m_materialOverrideInstance = nullptr;
  148. ShutdownLightingPresets();
  149. }
  150. void MeshExampleComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  151. {
  152. bool modelNeedsUpdate = false;
  153. // Switch pipeline before any imGui actions (switching pipelines switches imGui scope)
  154. if (m_switchPipeline)
  155. {
  156. if (m_useLowEndPipeline)
  157. {
  158. ActivateLowEndPipeline();
  159. }
  160. else
  161. {
  162. DeactivateLowEndPipeline();
  163. }
  164. m_switchPipeline = false;
  165. }
  166. if (m_imguiSidebar.Begin())
  167. {
  168. ImGuiLightingPreset();
  169. ImGuiAssetBrowser::WidgetSettings assetBrowserSettings;
  170. m_switchPipeline = ScriptableImGui::Checkbox("Use Low End Pipeline", &m_useLowEndPipeline) || m_switchPipeline;
  171. modelNeedsUpdate |= ScriptableImGui::Checkbox("Enable Material Override", &m_enableMaterialOverride);
  172. if (ScriptableImGui::Checkbox("Show Ground Plane", &m_showGroundPlane))
  173. {
  174. if (m_showGroundPlane)
  175. {
  176. CreateGroundPlane();
  177. UpdateGroundPlane();
  178. }
  179. else
  180. {
  181. RemoveGroundPlane();
  182. }
  183. }
  184. if (ScriptableImGui::Checkbox("Show Model Materials", &m_showModelMaterials))
  185. {
  186. modelNeedsUpdate = true;
  187. m_materialBrowser.SetNeedsRefresh();
  188. }
  189. assetBrowserSettings.m_labels.m_root = "Materials";
  190. modelNeedsUpdate |= m_materialBrowser.Tick(assetBrowserSettings);
  191. ImGui::Spacing();
  192. ImGui::Separator();
  193. ImGui::Spacing();
  194. assetBrowserSettings.m_labels.m_root = "Models";
  195. bool modelChanged = m_modelBrowser.Tick(assetBrowserSettings);
  196. modelNeedsUpdate |= modelChanged;
  197. if (modelChanged)
  198. {
  199. // Reset LOD override when the model changes.
  200. m_lodOverride = AZ::RPI::Cullable::NoLodOverride;
  201. }
  202. AZ::Data::Instance<AZ::RPI::Model> model = GetMeshFeatureProcessor()->GetModel(m_meshHandle);
  203. if (model)
  204. {
  205. const char* NoLodOverrideText = "No LOD Override";
  206. const char* LodFormatString = "LOD %i";
  207. AZStd::string previewText = m_lodOverride == AZ::RPI::Cullable::NoLodOverride ? NoLodOverrideText : AZStd::string::format(LodFormatString, m_lodOverride);
  208. if (ScriptableImGui::BeginCombo("", previewText.c_str()))
  209. {
  210. if (ScriptableImGui::Selectable(NoLodOverrideText, m_lodOverride == AZ::RPI::Cullable::NoLodOverride))
  211. {
  212. m_lodOverride = AZ::RPI::Cullable::NoLodOverride;
  213. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  214. }
  215. for (uint32_t i = 0; i < model->GetLodCount(); ++i)
  216. {
  217. AZStd::string name = AZStd::string::format(LodFormatString, i);
  218. if (ScriptableImGui::Selectable(name.c_str(), m_lodOverride == i))
  219. {
  220. m_lodOverride = i;
  221. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  222. }
  223. }
  224. ScriptableImGui::EndCombo();
  225. }
  226. }
  227. ImGui::Spacing();
  228. ImGui::Separator();
  229. ImGui::Spacing();
  230. // Camera controls
  231. {
  232. int32_t* currentControllerTypeIndex = reinterpret_cast<int32_t*>(&m_currentCameraControllerType);
  233. ImGui::LabelText("##CameraControllerLabel", "Camera Controller:");
  234. if (ScriptableImGui::Combo("##CameraController", currentControllerTypeIndex, CameraControllerNameTable, CameraControllerCount))
  235. {
  236. ResetCameraController();
  237. }
  238. }
  239. ImGui::Spacing();
  240. ImGui::Separator();
  241. ImGui::Spacing();
  242. if (m_materialOverrideInstance && ImGui::Button("Material Details..."))
  243. {
  244. m_imguiMaterialDetails.SetMaterial(m_materialOverrideInstance);
  245. m_imguiMaterialDetails.OpenDialog();
  246. }
  247. m_imguiSidebar.End();
  248. }
  249. m_imguiMaterialDetails.Tick();
  250. if (modelNeedsUpdate)
  251. {
  252. ModelChange();
  253. }
  254. }
  255. void MeshExampleComponent::ModelChange()
  256. {
  257. if (!m_modelBrowser.GetSelectedAssetId().IsValid())
  258. {
  259. m_modelAsset = {};
  260. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  261. return;
  262. }
  263. // If a material hasn't been selected, just choose the first one
  264. // If for some reason no materials are available log an error
  265. AZ::Data::AssetId selectedMaterialAssetId = m_materialBrowser.GetSelectedAssetId();
  266. if (!selectedMaterialAssetId.IsValid())
  267. {
  268. selectedMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultPbrMaterialPath, AZ::RPI::AssetUtils::TraceLevel::Error);
  269. if (!selectedMaterialAssetId.IsValid())
  270. {
  271. AZ_Error("MeshExampleComponent", false, "Failed to select model, no material available to render with.");
  272. return;
  273. }
  274. }
  275. if (m_enableMaterialOverride && selectedMaterialAssetId.IsValid())
  276. {
  277. AZ::Data::Asset<AZ::RPI::MaterialAsset> materialAsset;
  278. materialAsset.Create(selectedMaterialAssetId);
  279. m_materialOverrideInstance = AZ::RPI::Material::FindOrCreate(materialAsset);
  280. }
  281. else
  282. {
  283. m_materialOverrideInstance = nullptr;
  284. }
  285. if (m_modelAsset.GetId() != m_modelBrowser.GetSelectedAssetId())
  286. {
  287. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  288. m_modelAsset.Create(m_modelBrowser.GetSelectedAssetId());
  289. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  290. m_meshHandle = GetMeshFeatureProcessor()->AcquireMesh(AZ::Render::MeshHandleDescriptor{ m_modelAsset }, m_materialOverrideInstance);
  291. GetMeshFeatureProcessor()->SetTransform(m_meshHandle, AZ::Transform::CreateIdentity());
  292. GetMeshFeatureProcessor()->ConnectModelChangeEventHandler(m_meshHandle, m_changedHandler);
  293. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  294. }
  295. else
  296. {
  297. GetMeshFeatureProcessor()->SetMaterialAssignmentMap(m_meshHandle, m_materialOverrideInstance);
  298. }
  299. }
  300. void MeshExampleComponent::CreateGroundPlane()
  301. {
  302. m_groundPlandMeshHandle = GetMeshFeatureProcessor()->AcquireMesh(AZ::Render::MeshHandleDescriptor{ m_groundPlaneModelAsset }, m_groundPlaneMaterial);
  303. }
  304. void MeshExampleComponent::UpdateGroundPlane()
  305. {
  306. if (m_groundPlandMeshHandle.IsValid())
  307. {
  308. AZ::Transform groundPlaneTransform = AZ::Transform::CreateIdentity();
  309. AZ::Vector3 modelCenter;
  310. float modelRadius;
  311. m_modelAsset->GetAabb().GetAsSphere(modelCenter, modelRadius);
  312. static const float GroundPlaneRelativeScale = 4.0f;
  313. static const float GroundPlaneOffset = 0.01f;
  314. groundPlaneTransform.SetUniformScale(GroundPlaneRelativeScale * modelRadius);
  315. groundPlaneTransform.SetTranslation(AZ::Vector3(0.0f, 0.0f, m_modelAsset->GetAabb().GetMin().GetZ() - GroundPlaneOffset));
  316. GetMeshFeatureProcessor()->SetTransform(m_groundPlandMeshHandle, groundPlaneTransform);
  317. }
  318. }
  319. void MeshExampleComponent::RemoveGroundPlane()
  320. {
  321. GetMeshFeatureProcessor()->ReleaseMesh(m_groundPlandMeshHandle);
  322. }
  323. void MeshExampleComponent::OnEntityDestruction(const AZ::EntityId& entityId)
  324. {
  325. OnLightingPresetEntityShutdown(entityId);
  326. AZ::EntityBus::MultiHandler::BusDisconnect(entityId);
  327. }
  328. void MeshExampleComponent::UseArcBallCameraController()
  329. {
  330. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  331. azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  332. }
  333. void MeshExampleComponent::UseNoClipCameraController()
  334. {
  335. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  336. azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  337. }
  338. void MeshExampleComponent::RemoveController()
  339. {
  340. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  341. }
  342. void MeshExampleComponent::SetArcBallControllerParams()
  343. {
  344. if (!m_modelBrowser.GetSelectedAssetId().IsValid() || !m_modelAsset.IsReady())
  345. {
  346. return;
  347. }
  348. // Adjust the arc-ball controller so that it has bounds that make sense for the current model
  349. AZ::Vector3 center;
  350. float radius;
  351. m_modelAsset->GetAabb().GetAsSphere(center, radius);
  352. const float startingDistance = radius * ArcballRadiusDefaultModifier;
  353. const float minDistance = radius * ArcballRadiusMinModifier;
  354. const float maxDistance = radius * ArcballRadiusMaxModifier;
  355. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, center);
  356. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, startingDistance);
  357. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMinDistance, minDistance);
  358. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMaxDistance, maxDistance);
  359. }
  360. void MeshExampleComponent::ResetCameraController()
  361. {
  362. RemoveController();
  363. if (m_currentCameraControllerType == CameraControllerType::ArcBall)
  364. {
  365. UseArcBallCameraController();
  366. SetArcBallControllerParams();
  367. }
  368. else if (m_currentCameraControllerType == CameraControllerType::NoClip)
  369. {
  370. UseNoClipCameraController();
  371. }
  372. }
  373. } // namespace AtomSampleViewer