MeshExampleComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 <MeshExampleComponent.h>
  13. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  14. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  15. #include <Atom/RHI/Device.h>
  16. #include <Atom/RHI/Factory.h>
  17. #include <Atom/RPI.Public/View.h>
  18. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  19. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  20. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  21. #include <AzCore/Asset/AssetManagerBus.h>
  22. #include <AzCore/Component/Entity.h>
  23. #include <AzCore/IO/IOUtils.h>
  24. #include <AzCore/Serialization/SerializeContext.h>
  25. #include <AzCore/std/smart_ptr/make_shared.h>
  26. #include <AzCore/std/sort.h>
  27. #include <AzFramework/Components/TransformComponent.h>
  28. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  29. #include <SampleComponentManager.h>
  30. #include <SampleComponentConfig.h>
  31. #include <EntityUtilityFunctions.h>
  32. #include <Automation/ScriptableImGui.h>
  33. #include <Automation/ScriptRunnerBus.h>
  34. #include <RHI/BasicRHIComponent.h>
  35. namespace AtomSampleViewer
  36. {
  37. const char* MeshExampleComponent::CameraControllerNameTable[CameraControllerCount] =
  38. {
  39. "ArcBall",
  40. "NoClip"
  41. };
  42. void MeshExampleComponent::Reflect(AZ::ReflectContext* context)
  43. {
  44. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  45. {
  46. serializeContext->Class<MeshExampleComponent, AZ::Component>()
  47. ->Version(0)
  48. ;
  49. }
  50. }
  51. MeshExampleComponent::MeshExampleComponent()
  52. : m_materialBrowser("@user@/MeshExampleComponent/material_browser.xml")
  53. , m_modelBrowser("@user@/MeshExampleComponent/model_browser.xml")
  54. , m_imguiSidebar("@user@/MeshExampleComponent/sidebar.xml")
  55. {
  56. m_changedHandler = AZ::Render::MeshFeatureProcessorInterface::ModelChangedEvent::Handler
  57. {
  58. [&](AZ::Data::Instance<AZ::RPI::Model> model)
  59. {
  60. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  61. // This handler will be connected to the feature processor so that when the model is updated, the camera
  62. // controller will reset. This ensures the camera is a reasonable distance from the model when it resizes.
  63. ResetCameraController();
  64. }
  65. };
  66. }
  67. void MeshExampleComponent::Activate()
  68. {
  69. UseArcBallCameraController();
  70. m_materialBrowser.SetFilter([this](const AZ::Data::AssetInfo& assetInfo)
  71. {
  72. if (!AzFramework::StringFunc::Path::IsExtension(assetInfo.m_relativePath.c_str(), "azmaterial"))
  73. {
  74. return false;
  75. }
  76. if (m_showModelMaterials)
  77. {
  78. return true;
  79. }
  80. // Return true only if the azmaterial was generated from a ".material" file.
  81. // Materials with subid == 0, are 99.99% guaranteed to be generated from a ".material" file.
  82. // Without this assurance We would need to call AzToolsFramework::AssetSystem::AssetSystemRequest::GetSourceInfoBySourceUUID()
  83. // to figure out what's the source of this azmaterial. But, Atom can not include AzToolsFramework.
  84. return assetInfo.m_assetId.m_subId == 0;
  85. });
  86. m_modelBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  87. {
  88. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::ModelAsset>();
  89. });
  90. m_materialBrowser.Activate();
  91. m_modelBrowser.Activate();
  92. m_imguiSidebar.Activate();
  93. InitLightingPresets(true);
  94. AZ::TickBus::Handler::BusConnect();
  95. }
  96. void MeshExampleComponent::Deactivate()
  97. {
  98. AZ::TickBus::Handler::BusDisconnect();
  99. m_imguiSidebar.Deactivate();
  100. m_materialBrowser.Deactivate();
  101. m_modelBrowser.Deactivate();
  102. RemoveController();
  103. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  104. m_modelAsset = {};
  105. m_materialOverrideInstance = nullptr;
  106. ShutdownLightingPresets();
  107. }
  108. void MeshExampleComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  109. {
  110. bool modelNeedsUpdate = false;
  111. if (m_imguiSidebar.Begin())
  112. {
  113. ImGuiLightingPreset();
  114. ImGuiAssetBrowser::WidgetSettings assetBrowserSettings;
  115. modelNeedsUpdate |= ScriptableImGui::Checkbox("Enable Material Override", &m_enableMaterialOverride);
  116. if (ScriptableImGui::Checkbox("Show Model Materials", &m_showModelMaterials))
  117. {
  118. modelNeedsUpdate = true;
  119. m_materialBrowser.SetNeedsRefresh();
  120. }
  121. assetBrowserSettings.m_labels.m_root = "Materials";
  122. modelNeedsUpdate |= m_materialBrowser.Tick(assetBrowserSettings);
  123. ImGui::Spacing();
  124. ImGui::Separator();
  125. ImGui::Spacing();
  126. assetBrowserSettings.m_labels.m_root = "Models";
  127. bool modelChanged = m_modelBrowser.Tick(assetBrowserSettings);
  128. modelNeedsUpdate |= modelChanged;
  129. if (modelChanged)
  130. {
  131. // Reset LOD override when the model changes.
  132. m_lodOverride = AZ::RPI::Cullable::NoLodOverride;
  133. }
  134. AZ::Data::Instance<AZ::RPI::Model> model = GetMeshFeatureProcessor()->GetModel(m_meshHandle);
  135. if (model)
  136. {
  137. const char* NoLodOverrideText = "No LOD Override";
  138. const char* LodFormatString = "LOD %i";
  139. AZStd::string previewText = m_lodOverride == AZ::RPI::Cullable::NoLodOverride ? NoLodOverrideText : AZStd::string::format(LodFormatString, m_lodOverride);
  140. if (ScriptableImGui::BeginCombo("", previewText.c_str()))
  141. {
  142. if (ScriptableImGui::Selectable(NoLodOverrideText, m_lodOverride == AZ::RPI::Cullable::NoLodOverride))
  143. {
  144. m_lodOverride = AZ::RPI::Cullable::NoLodOverride;
  145. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  146. }
  147. for (uint32_t i = 0; i < model->GetLodCount(); ++i)
  148. {
  149. AZStd::string name = AZStd::string::format(LodFormatString, i);
  150. if (ScriptableImGui::Selectable(name.c_str(), m_lodOverride == i))
  151. {
  152. m_lodOverride = i;
  153. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  154. }
  155. }
  156. ScriptableImGui::EndCombo();
  157. }
  158. }
  159. ImGui::Spacing();
  160. ImGui::Separator();
  161. ImGui::Spacing();
  162. // Camera controls
  163. {
  164. int32_t* currentControllerTypeIndex = reinterpret_cast<int32_t*>(&m_currentCameraControllerType);
  165. ImGui::LabelText("##CameraControllerLabel", "Camera Controller:");
  166. if (ScriptableImGui::Combo("##CameraController", currentControllerTypeIndex, CameraControllerNameTable, CameraControllerCount))
  167. {
  168. ResetCameraController();
  169. }
  170. }
  171. ImGui::Spacing();
  172. ImGui::Separator();
  173. ImGui::Spacing();
  174. if (m_materialOverrideInstance && ImGui::Button("Material Details..."))
  175. {
  176. m_imguiMaterialDetails.SetMaterial(m_materialOverrideInstance);
  177. m_imguiMaterialDetails.OpenDialog();
  178. }
  179. m_imguiSidebar.End();
  180. }
  181. m_imguiMaterialDetails.Tick();
  182. if (modelNeedsUpdate)
  183. {
  184. ModelChange();
  185. }
  186. }
  187. void MeshExampleComponent::ModelChange()
  188. {
  189. if (!m_modelBrowser.GetSelectedAssetId().IsValid())
  190. {
  191. m_modelAsset = {};
  192. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  193. return;
  194. }
  195. // If a material hasn't been selected, just choose the first one
  196. // If for some reason no materials are available log an error
  197. AZ::Data::AssetId selectedMaterialAssetId = m_materialBrowser.GetSelectedAssetId();
  198. if (!selectedMaterialAssetId.IsValid())
  199. {
  200. selectedMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultPbrMaterialPath, AZ::RPI::AssetUtils::TraceLevel::Error);
  201. if (!selectedMaterialAssetId.IsValid())
  202. {
  203. AZ_Error("MeshExampleComponent", false, "Failed to select model, no material available to render with.");
  204. return;
  205. }
  206. }
  207. if (m_enableMaterialOverride && selectedMaterialAssetId.IsValid())
  208. {
  209. AZ::Data::Asset<AZ::RPI::MaterialAsset> materialAsset;
  210. materialAsset.Create(selectedMaterialAssetId);
  211. m_materialOverrideInstance = AZ::RPI::Material::FindOrCreate(materialAsset);
  212. }
  213. else
  214. {
  215. m_materialOverrideInstance = nullptr;
  216. }
  217. if (m_modelAsset.GetId() != m_modelBrowser.GetSelectedAssetId())
  218. {
  219. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  220. m_modelAsset.Create(m_modelBrowser.GetSelectedAssetId());
  221. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  222. m_meshHandle = GetMeshFeatureProcessor()->AcquireMesh(m_modelAsset, m_materialOverrideInstance);
  223. GetMeshFeatureProcessor()->SetTransform(m_meshHandle, AZ::Transform::CreateIdentity());
  224. GetMeshFeatureProcessor()->ConnectModelChangeEventHandler(m_meshHandle, m_changedHandler);
  225. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  226. }
  227. else
  228. {
  229. GetMeshFeatureProcessor()->SetMaterialAssignmentMap(m_meshHandle, m_materialOverrideInstance);
  230. }
  231. }
  232. void MeshExampleComponent::OnEntityDestruction(const AZ::EntityId& entityId)
  233. {
  234. OnLightingPresetEntityShutdown(entityId);
  235. AZ::EntityBus::MultiHandler::BusDisconnect(entityId);
  236. }
  237. void MeshExampleComponent::UseArcBallCameraController()
  238. {
  239. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  240. azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  241. }
  242. void MeshExampleComponent::UseNoClipCameraController()
  243. {
  244. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  245. azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  246. }
  247. void MeshExampleComponent::RemoveController()
  248. {
  249. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  250. }
  251. void MeshExampleComponent::SetArcBallControllerParams()
  252. {
  253. if (!m_modelBrowser.GetSelectedAssetId().IsValid() || !m_modelAsset.IsReady())
  254. {
  255. return;
  256. }
  257. // Adjust the arc-ball controller so that it has bounds that make sense for the current model
  258. AZ::Vector3 center;
  259. float radius;
  260. m_modelAsset->GetAabb().GetAsSphere(center, radius);
  261. const float startingDistance = radius * ArcballRadiusDefaultModifier;
  262. const float minDistance = radius * ArcballRadiusMinModifier;
  263. const float maxDistance = radius * ArcballRadiusMaxModifier;
  264. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, center);
  265. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, startingDistance);
  266. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMinDistance, minDistance);
  267. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMaxDistance, maxDistance);
  268. }
  269. void MeshExampleComponent::ResetCameraController()
  270. {
  271. RemoveController();
  272. if (m_currentCameraControllerType == CameraControllerType::ArcBall)
  273. {
  274. UseArcBallCameraController();
  275. SetArcBallControllerParams();
  276. }
  277. else if (m_currentCameraControllerType == CameraControllerType::NoClip)
  278. {
  279. UseNoClipCameraController();
  280. }
  281. }
  282. } // namespace AtomSampleViewer