3
0

SimpleLODComponent.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 <AzCore/PlatformDef.h>
  9. #include <AzCore/Component/ComponentApplicationBus.h>
  10. #include <AzCore/Component/Entity.h>
  11. #include <AzCore/Serialization/SerializeContext.h>
  12. #include <AzCore/Serialization/EditContext.h>
  13. #include <AzCore/RTTI/BehaviorContext.h>
  14. #include <Integration/Components/SimpleLODComponent.h>
  15. #include <MCore/Source/AttributeString.h>
  16. #include <EMotionFX/Source/ActorInstance.h>
  17. #include <MathConversion.h>
  18. #include <IRenderAuxGeom.h>
  19. #include <Atom/RPI.Public/ViewportContext.h>
  20. #include <Atom/RPI.Public/ViewportContextBus.h>
  21. namespace EMotionFX
  22. {
  23. namespace Integration
  24. {
  25. void SimpleLODComponent::Configuration::Reflect(AZ::ReflectContext *context)
  26. {
  27. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  28. if (serializeContext)
  29. {
  30. serializeContext->Class<Configuration>()
  31. ->Version(2)
  32. ->Field("LODDistances", &Configuration::m_lodDistances)
  33. ->Field("EnableLODSampling", &Configuration::m_enableLodSampling)
  34. ->Field("LODSampleRates", &Configuration::m_lodSampleRates)
  35. ;
  36. AZ::EditContext* editContext = serializeContext->GetEditContext();
  37. if (editContext)
  38. {
  39. editContext->Class<SimpleLODComponent::Configuration>("Configuration", "The LOD Configuration.")
  40. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  41. ->Attribute(AZ::Edit::Attributes::AutoExpand, "")
  42. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  43. ->DataElement(0, &SimpleLODComponent::Configuration::m_lodDistances,
  44. "LOD distance (Max)", "The maximum camera distance of this LOD.")
  45. ->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, false)
  46. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  47. ->ElementAttribute(AZ::Edit::Attributes::Step, 0.01f)
  48. ->ElementAttribute(AZ::Edit::Attributes::Suffix, " m")
  49. ->ElementAttribute(AZ::Edit::Attributes::Min, 0.00f)
  50. ->DataElement(0, &SimpleLODComponent::Configuration::m_enableLodSampling,
  51. "Enable LOD anim graph sampling", "AnimGraph sample rate will adjust based on LOD level.")
  52. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree)
  53. ->DataElement(0, &SimpleLODComponent::Configuration::m_lodSampleRates,
  54. "Anim graph sample rates", "The sample rate of anim graph based on LOD. Setting it to O means the maximum sample rate.")
  55. ->Attribute(AZ::Edit::Attributes::Visibility, &SimpleLODComponent::Configuration::GetEnableLodSampling)
  56. ->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, false)
  57. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  58. ->ElementAttribute(AZ::Edit::Attributes::Step, 1.0f)
  59. ->ElementAttribute(AZ::Edit::Attributes::Min, 0.0f);
  60. }
  61. }
  62. }
  63. void SimpleLODComponent::Configuration::Reset()
  64. {
  65. m_lodDistances.clear();
  66. }
  67. void SimpleLODComponent::Configuration::GenerateDefaultValue(size_t numLODs)
  68. {
  69. if (numLODs != m_lodDistances.size())
  70. {
  71. // Generate the default LOD (max) distance to 10, 20, 30....
  72. m_lodDistances.resize(numLODs);
  73. for (size_t i = 0; i < numLODs; ++i)
  74. {
  75. m_lodDistances[i] = i * 10.0f + 10.0f;
  76. }
  77. }
  78. if (numLODs != m_lodSampleRates.size())
  79. {
  80. // Generate the default LOD Sample Rate to 140, 60, 45, 25, 15, 10, 10, 10, ...
  81. constexpr AZStd::array defaultSampleRate {140.0f, 60.0f, 45.0f, 25.0f, 15.0f, 10.0f};
  82. m_lodSampleRates.resize(numLODs, 10.0f);
  83. // Do not copy more than what fits in defaultSampleRates or numLODs.
  84. size_t copyCount = std::min(defaultSampleRate.size(), numLODs);
  85. AZStd::copy(begin(defaultSampleRate), begin(defaultSampleRate) + copyCount, begin(m_lodSampleRates));
  86. }
  87. }
  88. bool SimpleLODComponent::Configuration::GetEnableLodSampling()
  89. {
  90. return m_enableLodSampling;
  91. }
  92. void SimpleLODComponent::Reflect(AZ::ReflectContext* context)
  93. {
  94. Configuration::Reflect(context);
  95. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  96. if (serializeContext)
  97. {
  98. serializeContext->Class<SimpleLODComponent, AZ::Component>()
  99. ->Version(1)
  100. ->Field("Configuration", &SimpleLODComponent::m_configuration)
  101. ;
  102. AZ::EditContext* editContext = serializeContext->GetEditContext();
  103. if (editContext)
  104. {
  105. editContext->Class<SimpleLODComponent>(
  106. "Simple LOD distance", "The Simple LOD distance component alters the actor LOD level based on distance to camera")
  107. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  108. ;
  109. }
  110. }
  111. }
  112. SimpleLODComponent::SimpleLODComponent(const Configuration* config)
  113. : m_actorInstance(nullptr)
  114. {
  115. if (config)
  116. {
  117. m_configuration = *config;
  118. }
  119. }
  120. SimpleLODComponent::~SimpleLODComponent()
  121. {
  122. }
  123. void SimpleLODComponent::Init()
  124. {
  125. }
  126. void SimpleLODComponent::Activate()
  127. {
  128. AZ::ApplicationTypeQuery appType;
  129. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  130. if (appType.IsHeadless())
  131. {
  132. return;
  133. }
  134. ActorComponentNotificationBus::Handler::BusConnect(GetEntityId());
  135. AZ::TickBus::Handler::BusConnect();
  136. // Remember the lod type and level so that we can set it back to the previous one on deactivation of the component.
  137. AZ::Render::MeshComponentRequestBus::EventResult(m_previousLodType,
  138. GetEntityId(),
  139. &AZ::Render::MeshComponentRequestBus::Events::GetLodType);
  140. if (m_actorInstance)
  141. {
  142. m_previousLodLevel = m_actorInstance->GetLODLevel();
  143. }
  144. }
  145. void SimpleLODComponent::Deactivate()
  146. {
  147. AZ::ApplicationTypeQuery appType;
  148. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  149. if (appType.IsHeadless())
  150. {
  151. return;
  152. }
  153. AZ::TickBus::Handler::BusDisconnect();
  154. ActorComponentNotificationBus::Handler::BusDisconnect();
  155. AZ::Render::MeshComponentRequestBus::Event(GetEntityId(),
  156. &AZ::Render::MeshComponentRequestBus::Events::SetLodType,
  157. m_previousLodType);
  158. if (m_actorInstance)
  159. {
  160. m_actorInstance->SetLODLevel(m_previousLodLevel);
  161. }
  162. }
  163. void SimpleLODComponent::OnActorInstanceCreated(EMotionFX::ActorInstance* actorInstance)
  164. {
  165. m_actorInstance = actorInstance;
  166. }
  167. void SimpleLODComponent::OnActorInstanceDestroyed(EMotionFX::ActorInstance* actorInstance)
  168. {
  169. AZ_UNUSED(actorInstance);
  170. m_actorInstance = nullptr;
  171. }
  172. void SimpleLODComponent::OnTick(float deltaTime, AZ::ScriptTimePoint time)
  173. {
  174. AZ_UNUSED(deltaTime);
  175. AZ_UNUSED(time);
  176. UpdateLodLevelByDistance(m_actorInstance, m_configuration, GetEntityId());
  177. }
  178. size_t SimpleLODComponent::GetLodByDistance(const AZStd::vector<float>& distances, float distance)
  179. {
  180. const size_t max = distances.size();
  181. for (size_t i = 0; i < max; ++i)
  182. {
  183. const float rDistance = distances[i];
  184. if (distance < rDistance)
  185. {
  186. return i;
  187. }
  188. }
  189. return max - 1;
  190. }
  191. void SimpleLODComponent::UpdateLodLevelByDistance(EMotionFX::ActorInstance* actorInstance, const Configuration& configuration, AZ::EntityId entityId)
  192. {
  193. if (actorInstance)
  194. {
  195. // Compute the distance between the camera and the entity
  196. AZ::Transform worldTransform;
  197. AZ::TransformBus::EventResult(worldTransform, entityId, &AZ::TransformBus::Events::GetWorldTM);
  198. const AZ::Vector3& worldPos = worldTransform.GetTranslation();
  199. auto viewportContextManager = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get();
  200. if (!viewportContextManager)
  201. {
  202. return;
  203. }
  204. AZ::RPI::ViewportContextPtr defaultViewportContext =
  205. viewportContextManager->GetViewportContextByName(viewportContextManager->GetDefaultViewportContextName());
  206. if (!defaultViewportContext)
  207. {
  208. return;
  209. }
  210. const float distance = worldPos.GetDistance(defaultViewportContext->GetCameraTransform().GetTranslation());
  211. const size_t requestedLod = GetLodByDistance(configuration.m_lodDistances, distance);
  212. actorInstance->SetLODLevel(requestedLod);
  213. if (configuration.m_enableLodSampling)
  214. {
  215. const float animGraphSampleRate = configuration.m_lodSampleRates[requestedLod];
  216. const float updateRateInSeconds = animGraphSampleRate > 0.0f ? 1.0f / animGraphSampleRate : 0.0f;
  217. actorInstance->SetMotionSamplingRate(updateRateInSeconds);
  218. }
  219. else if (actorInstance->GetMotionSamplingRate() != 0)
  220. {
  221. actorInstance->SetMotionSamplingRate(0);
  222. }
  223. // Disable the automatic mesh LOD level adjustment based on screen space in case a simple LOD component is present.
  224. // The simple LOD component overrides the mesh LOD level and syncs the skeleton with the mesh LOD level.
  225. AZ::Render::MeshComponentRequestBus::Event(entityId,
  226. &AZ::Render::MeshComponentRequestBus::Events::SetLodType,
  227. AZ::RPI::Cullable::LodType::SpecificLod);
  228. // When setting the actor instance LOD level, a change is just requested and with the next update it will get applied.
  229. // This means that the current LOD level might differ from the requested one. We need to sync the Atom LOD level with the
  230. // current LOD level of the actor instance to avoid skinning artifacts. The requested LOD level will be present and applied
  231. // the following frame.
  232. const size_t currentLod = actorInstance->GetLODLevel();
  233. AZ::Render::MeshComponentRequestBus::Event(entityId,
  234. &AZ::Render::MeshComponentRequestBus::Events::SetLodOverride,
  235. static_cast<AZ::RPI::Cullable::LodOverride>(currentLod));
  236. }
  237. }
  238. } // namespace integration
  239. } // namespace EMotionFX