MeshExampleComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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_materialOverrideInstance = nullptr;
  105. ShutdownLightingPresets();
  106. }
  107. void MeshExampleComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  108. {
  109. bool modelNeedsUpdate = false;
  110. if (m_imguiSidebar.Begin())
  111. {
  112. ImGuiLightingPreset();
  113. ImGuiAssetBrowser::WidgetSettings assetBrowserSettings;
  114. modelNeedsUpdate |= ScriptableImGui::Checkbox("Enable Material Override", &m_enableMaterialOverride);
  115. if (ScriptableImGui::Checkbox("Show Model Materials", &m_showModelMaterials))
  116. {
  117. modelNeedsUpdate = true;
  118. m_materialBrowser.SetNeedsRefresh();
  119. }
  120. assetBrowserSettings.m_labels.m_root = "Materials";
  121. modelNeedsUpdate |= m_materialBrowser.Tick(assetBrowserSettings);
  122. ImGui::Spacing();
  123. ImGui::Separator();
  124. ImGui::Spacing();
  125. assetBrowserSettings.m_labels.m_root = "Models";
  126. bool modelChanged = m_modelBrowser.Tick(assetBrowserSettings);
  127. modelNeedsUpdate |= modelChanged;
  128. if (modelChanged)
  129. {
  130. // Reset LOD override when the model changes.
  131. m_lodOverride = AZ::RPI::Cullable::NoLodOverride;
  132. }
  133. AZ::Data::Instance<AZ::RPI::Model> model = GetMeshFeatureProcessor()->GetModel(m_meshHandle);
  134. if (model)
  135. {
  136. const char* NoLodOverrideText = "No LOD Override";
  137. const char* LodFormatString = "LOD %i";
  138. AZStd::string previewText = m_lodOverride == AZ::RPI::Cullable::NoLodOverride ? NoLodOverrideText : AZStd::string::format(LodFormatString, m_lodOverride);
  139. if (ScriptableImGui::BeginCombo("", previewText.c_str()))
  140. {
  141. if (ScriptableImGui::Selectable(NoLodOverrideText, m_lodOverride == AZ::RPI::Cullable::NoLodOverride))
  142. {
  143. m_lodOverride = AZ::RPI::Cullable::NoLodOverride;
  144. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  145. }
  146. for (uint32_t i = 0; i < model->GetLodCount(); ++i)
  147. {
  148. AZStd::string name = AZStd::string::format(LodFormatString, i);
  149. if (ScriptableImGui::Selectable(name.c_str(), m_lodOverride == i))
  150. {
  151. m_lodOverride = i;
  152. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  153. }
  154. }
  155. ScriptableImGui::EndCombo();
  156. }
  157. }
  158. ImGui::Spacing();
  159. ImGui::Separator();
  160. ImGui::Spacing();
  161. // Camera controls
  162. {
  163. int32_t* currentControllerTypeIndex = reinterpret_cast<int32_t*>(&m_currentCameraControllerType);
  164. ImGui::LabelText("##CameraControllerLabel", "Camera Controller:");
  165. if (ScriptableImGui::Combo("##CameraController", currentControllerTypeIndex, CameraControllerNameTable, CameraControllerCount))
  166. {
  167. ResetCameraController();
  168. }
  169. }
  170. ImGui::Spacing();
  171. ImGui::Separator();
  172. ImGui::Spacing();
  173. if (m_materialOverrideInstance && ImGui::Button("Material Details..."))
  174. {
  175. m_imguiMaterialDetails.SetMaterial(m_materialOverrideInstance);
  176. m_imguiMaterialDetails.OpenDialog();
  177. }
  178. m_imguiSidebar.End();
  179. }
  180. m_imguiMaterialDetails.Tick();
  181. if (modelNeedsUpdate)
  182. {
  183. ModelChange();
  184. }
  185. }
  186. void MeshExampleComponent::ModelChange()
  187. {
  188. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  189. if (!m_modelBrowser.GetSelectedAssetId().IsValid())
  190. {
  191. return;
  192. }
  193. // If a material hasn't been selected, just choose the first one
  194. // If for some reason no materials are available log an error
  195. AZ::Data::AssetId selectedMaterialAssetId = m_materialBrowser.GetSelectedAssetId();
  196. if (!selectedMaterialAssetId.IsValid())
  197. {
  198. selectedMaterialAssetId = AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultPbrMaterialPath, AZ::RPI::AssetUtils::TraceLevel::Error);
  199. if (!selectedMaterialAssetId.IsValid())
  200. {
  201. AZ_Error("MeshExampleComponent", false, "Failed to select model, no material available to render with.");
  202. return;
  203. }
  204. }
  205. AZ::Render::MaterialAssignmentMap materialMap;
  206. if (m_enableMaterialOverride && selectedMaterialAssetId.IsValid())
  207. {
  208. AZ::Data::Asset<AZ::RPI::MaterialAsset> materialAsset;
  209. materialAsset.Create(selectedMaterialAssetId);
  210. m_materialOverrideInstance = AZ::RPI::Material::FindOrCreate(materialAsset);
  211. materialMap[AZ::Render::DefaultMaterialAssignmentId].m_materialAsset = materialAsset;
  212. materialMap[AZ::Render::DefaultMaterialAssignmentId].m_materialInstance = m_materialOverrideInstance;
  213. }
  214. else
  215. {
  216. m_materialOverrideInstance = nullptr;
  217. }
  218. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  219. AZ::Data::Asset<AZ::RPI::ModelAsset> modelAsset;
  220. modelAsset.Create(m_modelBrowser.GetSelectedAssetId());
  221. m_meshHandle = GetMeshFeatureProcessor()->AcquireMesh(modelAsset, materialMap);
  222. GetMeshFeatureProcessor()->SetTransform(m_meshHandle, AZ::Transform::CreateIdentity());
  223. GetMeshFeatureProcessor()->ConnectModelChangeEventHandler(m_meshHandle, m_changedHandler);
  224. GetMeshFeatureProcessor()->SetLodOverride(m_meshHandle, m_lodOverride);
  225. }
  226. void MeshExampleComponent::OnEntityDestruction(const AZ::EntityId& entityId)
  227. {
  228. OnLightingPresetEntityShutdown(entityId);
  229. AZ::EntityBus::MultiHandler::BusDisconnect(entityId);
  230. }
  231. void MeshExampleComponent::UseArcBallCameraController()
  232. {
  233. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  234. azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  235. }
  236. void MeshExampleComponent::UseNoClipCameraController()
  237. {
  238. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  239. azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  240. }
  241. void MeshExampleComponent::RemoveController()
  242. {
  243. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  244. }
  245. void MeshExampleComponent::SetArcBallControllerParams()
  246. {
  247. if (!m_modelBrowser.GetSelectedAssetId().IsValid())
  248. {
  249. return;
  250. }
  251. // Adjust the arc-ball controller so that it has bounds that make sense for the current model
  252. AZ::Data::Asset<AZ::RPI::ModelAsset> asset = AZ::Data::AssetManager::Instance().GetAsset(m_modelBrowser.GetSelectedAssetId(), azrtti_typeid<AZ::RPI::ModelAsset>(),
  253. AZ::Data::AssetLoadBehavior::PreLoad);
  254. asset.BlockUntilLoadComplete();
  255. AZ::RPI::ModelAsset* modelAsset = asset.Get();
  256. const AZ::Aabb& aabb = modelAsset->GetAabb();
  257. AZ::Vector3 center;
  258. float radius;
  259. aabb.GetAsSphere(center, radius);
  260. const float startingDistance = radius;
  261. const float minDistance = radius * ArcballRadiusMinModifier;
  262. const float maxDistance = radius * ArcballRadiusMaxModifier;
  263. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, center);
  264. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, startingDistance);
  265. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMinDistance, minDistance);
  266. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMaxDistance, maxDistance);
  267. }
  268. void MeshExampleComponent::ResetCameraController()
  269. {
  270. RemoveController();
  271. if (m_currentCameraControllerType == CameraControllerType::ArcBall)
  272. {
  273. UseArcBallCameraController();
  274. SetArcBallControllerParams();
  275. }
  276. else if (m_currentCameraControllerType == CameraControllerType::NoClip)
  277. {
  278. UseNoClipCameraController();
  279. }
  280. }
  281. } // namespace AtomSampleViewer