MeshExampleComponent.cpp 20 KB

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