Subpass_RPI_ExampleComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 <Subpass_RPI_ExampleComponent.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 <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
  26. #include <SampleComponentManager.h>
  27. #include <SampleComponentConfig.h>
  28. #include <EntityUtilityFunctions.h>
  29. #include <Automation/ScriptableImGui.h>
  30. #include <Automation/ScriptRunnerBus.h>
  31. #include <RHI/BasicRHIComponent.h>
  32. namespace AtomSampleViewer
  33. {
  34. const char* Subpass_RPI_ExampleComponent::CameraControllerNameTable[CameraControllerCount] =
  35. {
  36. "ArcBall",
  37. "NoClip"
  38. };
  39. void Subpass_RPI_ExampleComponent::Reflect(AZ::ReflectContext* context)
  40. {
  41. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  42. {
  43. serializeContext->Class<Subpass_RPI_ExampleComponent, AZ::Component>()
  44. ->Version(0)
  45. ;
  46. }
  47. }
  48. Subpass_RPI_ExampleComponent::Subpass_RPI_ExampleComponent()
  49. {
  50. }
  51. void Subpass_RPI_ExampleComponent::DefaultWindowCreated()
  52. {
  53. AZ::Render::Bootstrap::DefaultWindowBus::BroadcastResult(m_windowContext, &AZ::Render::Bootstrap::DefaultWindowBus::Events::GetDefaultWindowContext);
  54. }
  55. void Subpass_RPI_ExampleComponent::ChangeActivePipeline(AvailablePipelines pipelineOption)
  56. {
  57. if ((pipelineOption == m_activePipelineOption) && (m_activePipeline != nullptr))
  58. {
  59. return;
  60. }
  61. // remove currently running sample pipeline, if any
  62. bool removeOriginalPipeline = true;
  63. if (m_activePipeline)
  64. {
  65. m_scene->RemoveRenderPipeline(m_activePipeline->GetId());
  66. m_activePipeline = nullptr;
  67. removeOriginalPipeline = false;
  68. }
  69. // Create the pipeline.
  70. const auto pipelineOptionIdx = static_cast<size_t>(pipelineOption);
  71. AZ::RPI::RenderPipelineDescriptor pipelineDesc;
  72. pipelineDesc.m_mainViewTagName = "MainCamera";
  73. pipelineDesc.m_materialPipelineTag = "MultiViewPipeline";
  74. pipelineDesc.m_name = PipelineOptions[pipelineOptionIdx].m_pipelineName;
  75. pipelineDesc.m_rootPassTemplate = PipelineOptions[pipelineOptionIdx].m_rootPassTemplate;
  76. pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 1;
  77. m_activePipeline = AZ::RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext);
  78. AZ_Assert(m_activePipeline != nullptr, "Failed to create render pipeline with name='%s' and template='%s'.",
  79. PipelineOptions[pipelineOptionIdx].m_pipelineName, PipelineOptions[pipelineOptionIdx].m_rootPassTemplate);
  80. // Activate the pipeline
  81. m_activePipeline->GetRootPass()->SetEnabled(true); // PassSystem::RemoveRenderPipeline was calling SetEnabled(false)
  82. m_scene->AddRenderPipeline(m_activePipeline);
  83. m_activePipeline->SetDefaultView(m_originalPipeline->GetDefaultView());
  84. if (removeOriginalPipeline)
  85. {
  86. m_scene->RemoveRenderPipeline(m_originalPipeline->GetId());
  87. }
  88. m_activePipelineOption = pipelineOption;
  89. AZ_TracePrintf(LogName, "New active pipeline is '%s' from template '%s'",
  90. PipelineOptions[pipelineOptionIdx].m_pipelineName, PipelineOptions[pipelineOptionIdx].m_rootPassTemplate);
  91. }
  92. void Subpass_RPI_ExampleComponent::RestoreOriginalPipeline()
  93. {
  94. if (m_activePipeline)
  95. {
  96. m_scene->RemoveRenderPipeline(m_activePipeline->GetId());
  97. m_activePipeline = nullptr;
  98. }
  99. m_originalPipeline->GetRootPass()->SetEnabled(true); // PassSystem::RemoveRenderPipeline was calling SetEnabled(false)
  100. m_scene->AddRenderPipeline(m_originalPipeline);
  101. }
  102. void Subpass_RPI_ExampleComponent::Activate()
  103. {
  104. UseArcBallCameraController();
  105. InitLightingPresets(true);
  106. ActivateGroundPlane();
  107. ActivateModel();
  108. // Need to connect to this EBus before creating the pipeline because
  109. // we need the window context.
  110. AZ::Render::Bootstrap::DefaultWindowNotificationBus::Handler::BusConnect();
  111. AzFramework::InputChannelEventListener::BusConnect();
  112. // Save a pointer to the original default pipeline.
  113. m_originalPipeline = m_scene->GetDefaultRenderPipeline();
  114. // Start with our default pipeline
  115. ChangeActivePipeline(m_activePipelineOption);
  116. }
  117. void Subpass_RPI_ExampleComponent::ActivateGroundPlane()
  118. {
  119. // Load the material asset first.
  120. const auto traceLevel = AZ::RPI::AssetUtils::TraceLevel::Assert;
  121. auto groundPlaneMaterialAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::MaterialAsset>(DefaultPbrMaterialPath, traceLevel);
  122. AZ_Assert(groundPlaneMaterialAsset.GetId().IsValid(), "Invalid material asset from path='%s'", DefaultPbrMaterialPath);
  123. m_groundPlaneModelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(DefaultGroundPlaneModelPath, traceLevel);
  124. AZ_Assert(m_groundPlaneModelAsset.GetId().IsValid(), "Invalid ground plane model asset from path='%s'", DefaultGroundPlaneModelPath);
  125. auto meshHandleDescriptor = AZ::Render::MeshHandleDescriptor(m_groundPlaneModelAsset, AZ::RPI::Material::FindOrCreate(groundPlaneMaterialAsset));
  126. m_groundPlandMeshHandle = GetMeshFeatureProcessor()->AcquireMesh(meshHandleDescriptor);
  127. GetMeshFeatureProcessor()->SetTransform(m_groundPlandMeshHandle, AZ::Transform::CreateIdentity());
  128. }
  129. void Subpass_RPI_ExampleComponent::ActivateModel()
  130. {
  131. // Load the material asset first.
  132. const auto traceLevel = AZ::RPI::AssetUtils::TraceLevel::Assert;
  133. auto materialAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::MaterialAsset>(DefaultMaterialPath, traceLevel);
  134. AZ_Assert(materialAsset.GetId().IsValid(), "Invalid material asset from path='%s'", DefaultMaterialPath);
  135. m_modelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(DefaultModelPath, traceLevel);
  136. AZ_Assert(m_modelAsset.GetId().IsValid(), "Invalid model asset from path='%s'", DefaultModelPath);
  137. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  138. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  139. AZ::Render::MeshHandleDescriptor descriptor(m_modelAsset, AZ::RPI::Material::FindOrCreate(materialAsset));
  140. descriptor.m_modelChangedEventHandler = AZ::Render::MeshHandleDescriptor::ModelChangedEvent::Handler{
  141. [this](const AZ::Data::Instance<AZ::RPI::Model>& /*model*/)
  142. {
  143. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  144. // This handler will be connected to the feature processor so that when the model is updated, the camera
  145. // controller will reset. This ensures the camera is a reasonable distance from the model when it resizes.
  146. ResetCameraController();
  147. UpdateGroundPlane();
  148. }
  149. };
  150. m_meshHandle = GetMeshFeatureProcessor()->AcquireMesh(descriptor);
  151. GetMeshFeatureProcessor()->SetTransform(m_meshHandle, AZ::Transform::CreateIdentity());
  152. }
  153. void Subpass_RPI_ExampleComponent::Deactivate()
  154. {
  155. AZ::Render::Bootstrap::DefaultWindowNotificationBus::Handler::BusDisconnect();
  156. AzFramework::InputChannelEventListener::BusDisconnect();
  157. GetMeshFeatureProcessor()->ReleaseMesh(m_groundPlandMeshHandle);
  158. m_groundPlandMeshHandle = {};
  159. GetMeshFeatureProcessor()->ReleaseMesh(m_meshHandle);
  160. m_modelAsset = {};
  161. RestoreOriginalPipeline();
  162. RemoveController();
  163. ShutdownLightingPresets();
  164. }
  165. void Subpass_RPI_ExampleComponent::UpdateGroundPlane()
  166. {
  167. if (m_groundPlandMeshHandle.IsValid())
  168. {
  169. AZ::Transform groundPlaneTransform = AZ::Transform::CreateIdentity();
  170. if (m_modelAsset)
  171. {
  172. AZ::Vector3 modelCenter;
  173. float modelRadius;
  174. m_modelAsset->GetAabb().GetAsSphere(modelCenter, modelRadius);
  175. static const float GroundPlaneRelativeScale = 4.0f;
  176. static const float GroundPlaneOffset = 0.01f;
  177. groundPlaneTransform.SetUniformScale(GroundPlaneRelativeScale * modelRadius);
  178. groundPlaneTransform.SetTranslation(AZ::Vector3(0.0f, 0.0f, m_modelAsset->GetAabb().GetMin().GetZ() - GroundPlaneOffset));
  179. }
  180. GetMeshFeatureProcessor()->SetTransform(m_groundPlandMeshHandle, groundPlaneTransform);
  181. }
  182. }
  183. void Subpass_RPI_ExampleComponent::OnEntityDestruction(const AZ::EntityId& entityId)
  184. {
  185. AZ::EntityBus::MultiHandler::BusDisconnect(entityId);
  186. }
  187. // AzFramework::InputChannelEventListener
  188. bool Subpass_RPI_ExampleComponent::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel)
  189. {
  190. const auto& inputDevice = inputChannel.GetInputDevice();
  191. if (!AzFramework::InputDeviceKeyboard::IsKeyboardDevice(inputDevice.GetInputDeviceId()))
  192. {
  193. return false;
  194. }
  195. const AzFramework::InputChannelId& inputChannelId = inputChannel.GetInputChannelId();
  196. switch (inputChannel.GetState())
  197. {
  198. case AzFramework::InputChannel::State::Ended:
  199. {
  200. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Alphanumeric1)
  201. {
  202. ChangeActivePipeline(AvailablePipelines::TwoSubpassesPipeline);
  203. }
  204. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Alphanumeric2)
  205. {
  206. ChangeActivePipeline(AvailablePipelines::TwoPassesPipeline);
  207. }
  208. else
  209. {
  210. AZ_TracePrintf(LogName, "Invalid Key=%s. Only '1' or '2' are supported\n", inputChannelId.GetName());
  211. }
  212. break;
  213. }
  214. default:
  215. {
  216. break;
  217. }
  218. }
  219. return false;
  220. }
  221. void Subpass_RPI_ExampleComponent::UseArcBallCameraController()
  222. {
  223. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  224. azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  225. }
  226. void Subpass_RPI_ExampleComponent::UseNoClipCameraController()
  227. {
  228. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  229. azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  230. }
  231. void Subpass_RPI_ExampleComponent::RemoveController()
  232. {
  233. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  234. }
  235. void Subpass_RPI_ExampleComponent::SetArcBallControllerParams()
  236. {
  237. if (!m_modelAsset.IsReady())
  238. {
  239. return;
  240. }
  241. // Adjust the arc-ball controller so that it has bounds that make sense for the current model
  242. AZ::Vector3 center;
  243. float radius;
  244. m_modelAsset->GetAabb().GetAsSphere(center, radius);
  245. const float startingDistance = radius * ArcballRadiusDefaultModifier;
  246. const float minDistance = radius * ArcballRadiusMinModifier;
  247. const float maxDistance = radius * ArcballRadiusMaxModifier;
  248. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, center);
  249. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, startingDistance);
  250. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMinDistance, minDistance);
  251. AZ::Debug::ArcBallControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetMaxDistance, maxDistance);
  252. }
  253. void Subpass_RPI_ExampleComponent::ResetCameraController()
  254. {
  255. RemoveController();
  256. if (m_currentCameraControllerType == CameraControllerType::ArcBall)
  257. {
  258. UseArcBallCameraController();
  259. SetArcBallControllerParams();
  260. }
  261. else if (m_currentCameraControllerType == CameraControllerType::NoClip)
  262. {
  263. UseNoClipCameraController();
  264. }
  265. }
  266. } // namespace AtomSampleViewer