3
0

AnimViewportRenderer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 <AzFramework/Entity/GameEntityContextBus.h>
  9. #include <AzFramework/Components/TransformComponent.h>
  10. #include <Integration/ActorComponentBus.h>
  11. #include <Integration/Components/ActorComponent.h>
  12. #include <Atom/RPI.Public/Scene.h>
  13. #include <Atom/RPI.Public/RenderPipeline.h>
  14. #include <Atom/RPI.Public/RPIUtils.h>
  15. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  16. #include <Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h>
  17. #include <Atom/Feature/DisplayMapper/DisplayMapperFeatureProcessorInterface.h>
  18. #include <Atom/Feature/PostProcess/PostProcessFeatureProcessorInterface.h>
  19. #include <Atom/Feature/ImageBasedLights/ImageBasedLightFeatureProcessorInterface.h>
  20. #include <Atom/Feature/Mesh/MeshFeatureProcessorInterface.h>
  21. #include <Atom/Component/DebugCamera/CameraComponent.h>
  22. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  23. #include <AtomLyIntegration/CommonFeatures/Material/MaterialComponentConstants.h>
  24. #include <AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h>
  25. #include <AtomLyIntegration/CommonFeatures/Mesh/MeshComponentConstants.h>
  26. #include <AtomLyIntegration/CommonFeatures/Mesh/MeshComponentBus.h>
  27. #include <AtomLyIntegration/CommonFeatures/PostProcess/PostFxLayerComponentConstants.h>
  28. #include <AtomLyIntegration/CommonFeatures/PostProcess/ExposureControl/ExposureControlComponentConstants.h>
  29. #include <AtomLyIntegration/CommonFeatures/ImageBasedLights/ImageBasedLightComponentConstants.h>
  30. #include <EMStudio/AnimViewportRenderer.h>
  31. #include <EMotionFX/Source/EMotionFXManager.h>
  32. #include <EMotionFX/Source/ActorManager.h>
  33. #include <EMotionFX/CommandSystem/Source/CommandManager.h>
  34. #include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h>
  35. #include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.h>
  36. namespace EMStudio
  37. {
  38. AnimViewportRenderer::AnimViewportRenderer(AZ::RPI::ViewportContextPtr viewportContext, const RenderOptions* renderOptions)
  39. : m_windowContext(viewportContext->GetWindowContext())
  40. , m_renderOptions(renderOptions)
  41. {
  42. // Create a new entity context
  43. m_entityContext = AZStd::make_unique<AzFramework::EntityContext>();
  44. m_entityContext->InitContext();
  45. // Create the scene
  46. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  47. AZ_Assert(sceneSystem, "Unable to retrieve scene system.");
  48. AZ::Outcome<AZStd::shared_ptr<AzFramework::Scene>, AZStd::string> createSceneOutcome = sceneSystem->CreateScene("AnimViewport");
  49. AZ_Assert(createSceneOutcome, "%s", createSceneOutcome.GetError().data());
  50. m_frameworkScene = createSceneOutcome.TakeValue();
  51. m_frameworkScene->SetSubsystem<AzFramework::EntityContext::SceneStorageType>(m_entityContext.get());
  52. // Create and register a scene with feature processors defined in the viewport settings
  53. AZ::RPI::SceneDescriptor sceneDesc;
  54. sceneDesc.m_nameId = AZ::Name("AnimViewport");
  55. auto settingsRegistry = AZ::SettingsRegistry::Get();
  56. const char* viewportSettingPath = "/O3DE/Editor/Viewport/Animation/Scene";
  57. bool sceneDescLoaded = settingsRegistry->GetObject(sceneDesc, viewportSettingPath);
  58. m_scene = AZ::RPI::Scene::CreateScene(sceneDesc);
  59. if (!sceneDescLoaded)
  60. {
  61. AZ_Warning("AnimViewportRenderer", false, "Settings registry is missing the scene settings for this viewport, so all feature processors will be enabled. "
  62. "To enable only a minimal set, add the specific list of feature processors with a registry path of '%s'.", viewportSettingPath);
  63. m_scene->EnableAllFeatureProcessors();
  64. }
  65. // Link our RPI::Scene to the AzFramework::Scene
  66. m_frameworkScene->SetSubsystem(m_scene);
  67. AZStd::string pipelineAssetPath = "passes/MainRenderPipeline.azasset";
  68. AZ::RPI::XRRenderingInterface* xrSystem = AZ::RPI::RPISystemInterface::Get()->GetXRSystem();
  69. if (xrSystem)
  70. {
  71. // OpenXr uses low end render pipeline
  72. pipelineAssetPath = "passes/LowEndRenderPipeline.azasset";
  73. }
  74. AZStd::optional<AZ::RPI::RenderPipelineDescriptor> renderPipelineDesc =
  75. AZ::RPI::GetRenderPipelineDescriptorFromAsset(pipelineAssetPath.c_str(), AZStd::string::format("_%i", viewportContext->GetId()));
  76. AZ_Assert(renderPipelineDesc.has_value(), "Invalid render pipeline descriptor from asset %s", pipelineAssetPath.c_str());
  77. const AZ::RHI::MultisampleState multiSampleState = AZ::RPI::RPISystemInterface::Get()->GetApplicationMultisampleState();
  78. renderPipelineDesc.value().m_renderSettings.m_multisampleState = multiSampleState;
  79. AZ_Printf("AnimViewportRenderer", "Animation viewport renderer starting with multi sample %d", multiSampleState.m_samples);
  80. m_renderPipeline = AZ::RPI::RenderPipeline::CreateRenderPipelineForWindow(renderPipelineDesc.value(), *m_windowContext.get());
  81. m_scene->AddRenderPipeline(m_renderPipeline);
  82. m_renderPipeline->SetDefaultView(viewportContext->GetDefaultView());
  83. // Currently the scene has to be activated after render pipeline was added so some feature processors (i.e. imgui) can be
  84. // initialized properly with pipeline's pass information.
  85. m_scene->Activate();
  86. AZ::RPI::RPISystemInterface::Get()->RegisterScene(m_scene);
  87. AzFramework::EntityContextId entityContextId = m_entityContext->GetContextId();
  88. // Get the FeatureProcessors
  89. m_meshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::MeshFeatureProcessorInterface>();
  90. // Configure tone mapper
  91. AzFramework::EntityContextRequestBus::EventResult(
  92. m_postProcessEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "postProcessEntity");
  93. AZ_Assert(m_postProcessEntity != nullptr, "Failed to create post process entity.");
  94. m_postProcessEntity->CreateComponent(AZ::Render::PostFxLayerComponentTypeId);
  95. m_postProcessEntity->CreateComponent(AZ::Render::ExposureControlComponentTypeId);
  96. m_postProcessEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  97. m_postProcessEntity->Init();
  98. m_postProcessEntity->Activate();
  99. // Init directional light processor
  100. m_directionalLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::DirectionalLightFeatureProcessorInterface>();
  101. // Init display mapper processor
  102. m_displayMapperFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::DisplayMapperFeatureProcessorInterface>();
  103. // Init Skybox
  104. m_skyboxFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::SkyBoxFeatureProcessorInterface>();
  105. m_skyboxFeatureProcessor->Enable(true);
  106. m_skyboxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  107. // Create IBL
  108. AzFramework::EntityContextRequestBus::EventResult(
  109. m_iblEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "IblEntity");
  110. AZ_Assert(m_iblEntity != nullptr, "Failed to create ibl entity.");
  111. m_iblEntity->CreateComponent(AZ::Render::ImageBasedLightComponentTypeId);
  112. m_iblEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  113. m_iblEntity->Init();
  114. m_iblEntity->Activate();
  115. // Load light preset
  116. AZ::Data::Asset<AZ::RPI::AnyAsset> lightingPresetAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::AnyAsset>(
  117. "lightingpresets/default.lightingpreset.azasset", AZ::RPI::AssetUtils::TraceLevel::Warning);
  118. const AZ::Render::LightingPreset* preset = lightingPresetAsset->GetDataAs<AZ::Render::LightingPreset>();
  119. SetLightingPreset(preset);
  120. // Create the ground plane
  121. AzFramework::EntityContextRequestBus::EventResult(
  122. m_groundEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ViewportModel");
  123. AZ_Assert(m_groundEntity != nullptr, "Failed to create model entity.");
  124. m_groundEntity->CreateComponent(AZ::Render::MeshComponentTypeId);
  125. m_groundEntity->CreateComponent(AZ::Render::MaterialComponentTypeId);
  126. m_groundEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  127. m_groundEntity->Init();
  128. m_groundEntity->Activate();
  129. Reinit();
  130. }
  131. AnimViewportRenderer::~AnimViewportRenderer()
  132. {
  133. // Destroy all the entity we created.
  134. m_entityContext->DestroyEntity(m_iblEntity);
  135. m_entityContext->DestroyEntity(m_postProcessEntity);
  136. m_entityContext->DestroyEntity(m_groundEntity);
  137. for (AZ::Entity* entity : m_actorEntities)
  138. {
  139. m_entityContext->DestroyEntity(entity);
  140. }
  141. m_actorEntities.clear();
  142. m_entityContext->DestroyContext();
  143. for (AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  144. {
  145. m_directionalLightFeatureProcessor->ReleaseLight(handle);
  146. }
  147. m_lightHandles.clear();
  148. m_frameworkScene->UnsetSubsystem(m_scene);
  149. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  150. AZ_Assert(sceneSystem, "AtomViewportRenderer was unable to get the scene system during destruction.");
  151. bool removeSuccess = sceneSystem->RemoveScene("AnimViewport");
  152. if (!removeSuccess)
  153. {
  154. AZ_Assert(false, "AtomViewportRenderer should be removed.");
  155. }
  156. AZ::RPI::RPISystemInterface::Get()->UnregisterScene(m_scene);
  157. m_scene = nullptr;
  158. }
  159. void AnimViewportRenderer::Reinit()
  160. {
  161. ReinitActorEntities();
  162. ResetEnvironment();
  163. }
  164. void AnimViewportRenderer::MoveActorEntitiesToOrigin()
  165. {
  166. for (AZ::Entity* entity : m_actorEntities)
  167. {
  168. AZ::TransformBus::Event(entity->GetId(), &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateIdentity());
  169. }
  170. }
  171. AZ::Vector3 AnimViewportRenderer::GetCharacterCenter() const
  172. {
  173. AZ::Vector3 result = AZ::Vector3::CreateZero();
  174. if (!m_actorEntities.empty())
  175. {
  176. // Find the actor instance and calculate the center from aabb.
  177. EMotionFX::Integration::ActorComponent* actorComponent =
  178. m_actorEntities[0]->FindComponent<EMotionFX::Integration::ActorComponent>();
  179. EMotionFX::ActorInstance* actorInstance = actorComponent->GetActorInstance();
  180. if (actorInstance)
  181. {
  182. result = actorInstance->GetAabb().GetCenter();
  183. }
  184. }
  185. return result;
  186. }
  187. void AnimViewportRenderer::UpdateActorRenderFlag(EMotionFX::ActorRenderFlags renderFlags)
  188. {
  189. for (AZ::Entity* entity : m_actorEntities)
  190. {
  191. EMotionFX::Integration::ActorComponent* actorComponent = entity->FindComponent<EMotionFX::Integration::ActorComponent>();
  192. if (!actorComponent)
  193. {
  194. AZ_Assert(false, "Found entity without actor component in the actor entity list.");
  195. continue;
  196. }
  197. actorComponent->SetRenderFlag(renderFlags);
  198. }
  199. }
  200. AZStd::shared_ptr<AzFramework::Scene> AnimViewportRenderer::GetFrameworkScene() const
  201. {
  202. return m_frameworkScene;
  203. }
  204. AZ::EntityId AnimViewportRenderer::GetEntityId() const
  205. {
  206. if (m_actorEntities.empty())
  207. {
  208. return AZ::EntityId();
  209. }
  210. return m_actorEntities[0]->GetId();
  211. }
  212. AzFramework::EntityContextId AnimViewportRenderer::GetEntityContextId() const
  213. {
  214. return m_entityContext->GetContextId();
  215. }
  216. void AnimViewportRenderer::UpdateGroundplane()
  217. {
  218. AZ::Vector3 groundPos;
  219. AZ::TransformBus::EventResult(groundPos, m_groundEntity->GetId(), &AZ::TransformBus::Events::GetWorldTranslation);
  220. const AZ::Vector3 characterPos = GetCharacterCenter();
  221. const float tileOffsetX = AZStd::fmod(characterPos.GetX(), TileSize);
  222. const float tileOffsetY = AZStd::fmod(characterPos.GetY(), TileSize);
  223. const AZ::Vector3 newGroundPos(characterPos.GetX() - tileOffsetX, characterPos.GetY() - tileOffsetY, groundPos.GetZ());
  224. AZ::TransformBus::Event(m_groundEntity->GetId(), &AZ::TransformBus::Events::SetWorldTranslation, newGroundPos);
  225. }
  226. void AnimViewportRenderer::ResetEnvironment()
  227. {
  228. // Reset environment
  229. AZ::Transform iblTransform = AZ::Transform::CreateIdentity();
  230. AZ::TransformBus::Event(m_iblEntity->GetId(), &AZ::TransformBus::Events::SetLocalTM, iblTransform);
  231. const AZ::Matrix4x4 rotationMatrix = AZ::Matrix4x4::CreateIdentity();
  232. auto skyBoxFeatureProcessorInterface = m_scene->GetFeatureProcessor<AZ::Render::SkyBoxFeatureProcessorInterface>();
  233. skyBoxFeatureProcessorInterface->SetCubemapRotationMatrix(rotationMatrix);
  234. // Reset ground entity
  235. AZ::Transform identityTransform = AZ::Transform::CreateIdentity();
  236. AZ::TransformBus::Event(m_groundEntity->GetId(), &AZ::TransformBus::Events::SetLocalTM, identityTransform);
  237. auto modelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(
  238. "objects/groudplane/groundplane_512x512m.fbx.azmodel", AZ::RPI::AssetUtils::TraceLevel::Assert);
  239. AZ::Render::MeshComponentRequestBus::Event(
  240. m_groundEntity->GetId(), &AZ::Render::MeshComponentRequestBus::Events::SetModelAsset, modelAsset);
  241. // Reset actor position
  242. for (AZ::Entity* entity : m_actorEntities)
  243. {
  244. AZ::TransformBus::Event(entity->GetId(), &AZ::TransformBus::Events::SetLocalTM, identityTransform);
  245. }
  246. }
  247. void AnimViewportRenderer::ReinitActorEntities()
  248. {
  249. // 1. Destroy all the entities that do not point to any actorAsset anymore.
  250. AZStd::set<AZ::Data::AssetId> assetLookup;
  251. AzFramework::EntityContext* entityContext = m_entityContext.get();
  252. const size_t numActors = EMotionFX::GetActorManager().GetNumActors();
  253. for (size_t i = 0; i < numActors; ++i)
  254. {
  255. assetLookup.emplace(EMotionFX::GetActorManager().GetActorAsset(i).GetId());
  256. }
  257. m_actorEntities.erase(
  258. AZStd::remove_if(
  259. m_actorEntities.begin(), m_actorEntities.end(),
  260. [&assetLookup, entityContext](AZ::Entity* entity)
  261. {
  262. EMotionFX::Integration::ActorComponent* actorComponent =
  263. entity->FindComponent<EMotionFX::Integration::ActorComponent>();
  264. if (assetLookup.find(actorComponent->GetActorAsset().GetId()) == assetLookup.end())
  265. {
  266. entityContext->DestroyEntity(entity);
  267. return true;
  268. }
  269. return false;
  270. }),
  271. m_actorEntities.end());
  272. // 2. Create an entity for every actorAsset stored in actor manager.
  273. for (size_t i = 0; i < numActors; ++i)
  274. {
  275. AZ::Data::Asset<EMotionFX::Integration::ActorAsset> actorAsset = EMotionFX::GetActorManager().GetActorAsset(i);
  276. if (!actorAsset->IsReady())
  277. {
  278. continue;
  279. }
  280. AZ::Entity* entity = FindActorEntity(actorAsset);
  281. if (!entity)
  282. {
  283. m_actorEntities.emplace_back(CreateActorEntity(actorAsset));
  284. }
  285. }
  286. }
  287. AZ::Entity* AnimViewportRenderer::FindActorEntity(AZ::Data::Asset<EMotionFX::Integration::ActorAsset> actorAsset) const
  288. {
  289. const auto foundEntity = AZStd::find_if(
  290. begin(m_actorEntities), end(m_actorEntities),
  291. [match = actorAsset](const AZ::Entity* entity)
  292. {
  293. EMotionFX::Integration::ActorComponent* actorComponent = entity->FindComponent<EMotionFX::Integration::ActorComponent>();
  294. return actorComponent->GetActorAsset() == match;
  295. });
  296. return foundEntity != end(m_actorEntities) ? (*foundEntity) : nullptr;
  297. }
  298. AZ::Entity* AnimViewportRenderer::CreateActorEntity(AZ::Data::Asset<EMotionFX::Integration::ActorAsset> actorAsset)
  299. {
  300. AZ::Entity* actorEntity = m_entityContext->CreateEntity(actorAsset->GetActor()->GetName());
  301. actorEntity->CreateComponent(azrtti_typeid<EMotionFX::Integration::ActorComponent>());
  302. actorEntity->CreateComponent(AZ::Render::MaterialComponentTypeId);
  303. actorEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  304. actorEntity->Init();
  305. actorEntity->Activate();
  306. EMotionFX::Integration::ActorComponent* actorComponent = actorEntity->FindComponent<EMotionFX::Integration::ActorComponent>();
  307. actorComponent->SetActorAsset(actorAsset);
  308. // Since this entity belongs to the animation editor, we need to set the isOwnByRuntime flag to false.
  309. actorComponent->GetActorInstance()->SetIsOwnedByRuntime(false);
  310. // Selet the actor instance in the command manager after it has been created.
  311. AZStd::string outResult;
  312. EMStudioManager::GetInstance()->GetCommandManager()->ExecuteCommandInsideCommand(
  313. AZStd::string::format("Select -actorInstanceID %i", actorComponent->GetActorInstance()->GetID()).c_str(), outResult);
  314. return actorEntity;
  315. }
  316. void AnimViewportRenderer::SetLightingPreset(const AZ::Render::LightingPreset* preset)
  317. {
  318. if (!preset)
  319. {
  320. AZ_Warning("AnimViewportRenderer", false, "Attempting to set invalid lighting preset.");
  321. return;
  322. }
  323. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor =
  324. m_scene->GetFeatureProcessor<AZ::Render::ImageBasedLightFeatureProcessorInterface>();
  325. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor =
  326. m_scene->GetFeatureProcessor<AZ::Render::PostProcessFeatureProcessorInterface>();
  327. AZ::Render::ExposureControlSettingsInterface* exposureControlSettingInterface =
  328. postProcessFeatureProcessor->GetOrCreateSettingsInterface(m_postProcessEntity->GetId())
  329. ->GetOrCreateExposureControlSettingsInterface();
  330. Camera::Configuration cameraConfig;
  331. cameraConfig.m_fovRadians = AZ::DegToRad(m_renderOptions->GetFOV());
  332. cameraConfig.m_nearClipDistance = m_renderOptions->GetNearClipPlaneDistance();
  333. cameraConfig.m_farClipDistance = m_renderOptions->GetFarClipPlaneDistance();
  334. cameraConfig.m_frustumWidth = DefaultFrustumDimension;
  335. cameraConfig.m_frustumHeight = DefaultFrustumDimension;
  336. preset->ApplyLightingPreset(
  337. iblFeatureProcessor, m_skyboxFeatureProcessor, exposureControlSettingInterface, m_directionalLightFeatureProcessor,
  338. cameraConfig, m_lightHandles, false);
  339. }
  340. AZ::RPI::SceneId AnimViewportRenderer::GetRenderSceneId() const
  341. {
  342. return m_scene->GetId();
  343. }
  344. const AZStd::vector<AZ::Entity*>& AnimViewportRenderer::GetActorEntities() const
  345. {
  346. return m_actorEntities;
  347. }
  348. } // namespace EMStudio