SurfaceDataColliderComponent.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 <SurfaceData/Components/SurfaceDataColliderComponent.h>
  9. #include <AzCore/Debug/Profiler.h>
  10. #include <AzCore/RTTI/BehaviorContext.h>
  11. #include <AzCore/Serialization/EditContext.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <AzCore/Math/IntersectSegment.h>
  14. #include <AzFramework/Physics/Common/PhysicsSceneQueries.h>
  15. #include <AzFramework/Physics/Components/SimulatedBodyComponentBus.h>
  16. #include <SurfaceData/SurfaceDataSystemRequestBus.h>
  17. #include <SurfaceData/Utility/SurfaceDataUtility.h>
  18. namespace SurfaceData
  19. {
  20. void SurfaceDataColliderConfig::Reflect(AZ::ReflectContext* context)
  21. {
  22. if (auto serialize = azrtti_cast<AZ::SerializeContext*>(context))
  23. {
  24. serialize->Class<SurfaceDataColliderConfig, AZ::ComponentConfig>()
  25. ->Version(0)
  26. ->Field("ProviderTags", &SurfaceDataColliderConfig::m_providerTags)
  27. ->Field("ModifierTags", &SurfaceDataColliderConfig::m_modifierTags)
  28. ;
  29. if (auto edit = serialize->GetEditContext())
  30. {
  31. edit->Class<SurfaceDataColliderConfig>(
  32. "PhysX Collider Surface Tag Emitter", "")
  33. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  34. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  35. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  36. ->DataElement(0, &SurfaceDataColliderConfig::m_providerTags, "Generated Tags", "Surface tags to add to created points")
  37. ->DataElement(0, &SurfaceDataColliderConfig::m_modifierTags, "Extended Tags", "Surface tags to add to contained points")
  38. ;
  39. }
  40. }
  41. if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  42. {
  43. behaviorContext->Class<SurfaceDataColliderConfig>()
  44. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common)
  45. ->Attribute(AZ::Script::Attributes::Category, "Vegetation")
  46. ->Attribute(AZ::Script::Attributes::Module, "surface_data")
  47. ->Constructor()
  48. ->Property("providerTags", BehaviorValueProperty(&SurfaceDataColliderConfig::m_providerTags))
  49. ->Property("modifierTags", BehaviorValueProperty(&SurfaceDataColliderConfig::m_modifierTags))
  50. ;
  51. }
  52. }
  53. void SurfaceDataColliderComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  54. {
  55. services.push_back(AZ_CRC_CE("SurfaceDataProviderService"));
  56. services.push_back(AZ_CRC_CE("SurfaceDataModifierService"));
  57. }
  58. void SurfaceDataColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  59. {
  60. services.push_back(AZ_CRC_CE("SurfaceDataProviderService"));
  61. services.push_back(AZ_CRC_CE("SurfaceDataModifierService"));
  62. }
  63. void SurfaceDataColliderComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  64. {
  65. services.push_back(AZ_CRC_CE("PhysicsColliderService"));
  66. }
  67. void SurfaceDataColliderComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  68. {
  69. services.push_back(AZ_CRC_CE("PhysicsWorldBodyService"));
  70. }
  71. void SurfaceDataColliderComponent::Reflect(AZ::ReflectContext* context)
  72. {
  73. SurfaceDataColliderConfig::Reflect(context);
  74. if (auto serialize = azrtti_cast<AZ::SerializeContext*>(context))
  75. {
  76. serialize->Class<SurfaceDataColliderComponent, AZ::Component>()
  77. ->Version(0)
  78. ->Field("Configuration", &SurfaceDataColliderComponent::m_configuration)
  79. ;
  80. }
  81. if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  82. {
  83. behaviorContext->Class<SurfaceDataColliderComponent>()
  84. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common)
  85. ->Attribute(AZ::Script::Attributes::Category, "Vegetation")
  86. ->Attribute(AZ::Script::Attributes::Module, "surface_data")
  87. ->Constructor()
  88. ->Property("providerTags",
  89. [](SurfaceDataColliderComponent* component) { return component->m_configuration.m_providerTags; },
  90. [](SurfaceDataColliderComponent* component, SurfaceData::SurfaceTagVector value)
  91. {
  92. component->m_configuration.m_providerTags = value;
  93. component->OnCompositionChanged();
  94. })
  95. ->Property("modifierTags",
  96. [](SurfaceDataColliderComponent* component) { return component->m_configuration.m_modifierTags; },
  97. [](SurfaceDataColliderComponent* component, SurfaceData::SurfaceTagVector value)
  98. {
  99. component->m_configuration.m_modifierTags = value;
  100. component->OnCompositionChanged();
  101. })
  102. ;
  103. }
  104. }
  105. SurfaceDataColliderComponent::SurfaceDataColliderComponent(const SurfaceDataColliderConfig& configuration)
  106. : m_configuration(configuration)
  107. {
  108. }
  109. void SurfaceDataColliderComponent::Activate()
  110. {
  111. m_providerHandle = InvalidSurfaceDataRegistryHandle;
  112. m_modifierHandle = InvalidSurfaceDataRegistryHandle;
  113. m_refresh = false;
  114. AZ::TransformNotificationBus::Handler::BusConnect(GetEntityId());
  115. Physics::ColliderComponentEventBus::Handler::BusConnect(GetEntityId());
  116. // Update the cached collider data and bounds, then register the surface data provider / modifier
  117. m_newPointWeights.AssignSurfaceTagWeights(m_configuration.m_providerTags, 1.0f);
  118. UpdateColliderData();
  119. }
  120. void SurfaceDataColliderComponent::Deactivate()
  121. {
  122. if (m_providerHandle != InvalidSurfaceDataRegistryHandle)
  123. {
  124. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataProvider(m_providerHandle);
  125. m_providerHandle = InvalidSurfaceDataRegistryHandle;
  126. }
  127. if (m_modifierHandle != InvalidSurfaceDataRegistryHandle)
  128. {
  129. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataModifier(m_modifierHandle);
  130. m_modifierHandle = InvalidSurfaceDataRegistryHandle;
  131. }
  132. AZ::TickBus::Handler::BusDisconnect();
  133. AZ::TransformNotificationBus::Handler::BusDisconnect();
  134. Physics::ColliderComponentEventBus::Handler::BusDisconnect();
  135. SurfaceDataProviderRequestBus::Handler::BusDisconnect();
  136. SurfaceDataModifierRequestBus::Handler::BusDisconnect();
  137. m_refresh = false;
  138. // Clear the cached mesh data
  139. {
  140. AZStd::unique_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  141. m_colliderBounds = AZ::Aabb::CreateNull();
  142. }
  143. }
  144. bool SurfaceDataColliderComponent::ReadInConfig(const AZ::ComponentConfig* baseConfig)
  145. {
  146. if (auto config = azrtti_cast<const SurfaceDataColliderConfig*>(baseConfig))
  147. {
  148. m_configuration = *config;
  149. return true;
  150. }
  151. return false;
  152. }
  153. bool SurfaceDataColliderComponent::WriteOutConfig(AZ::ComponentConfig* outBaseConfig) const
  154. {
  155. if (auto config = azrtti_cast<SurfaceDataColliderConfig*>(outBaseConfig))
  156. {
  157. *config = m_configuration;
  158. return true;
  159. }
  160. return false;
  161. }
  162. void SurfaceDataColliderComponent::GetSurfacePoints(const AZ::Vector3& inPosition, SurfacePointList& surfacePointList) const
  163. {
  164. GetSurfacePointsFromList(AZStd::span<const AZ::Vector3>(&inPosition, 1), surfacePointList);
  165. }
  166. void SurfaceDataColliderComponent::GetSurfacePointsFromList(
  167. AZStd::span<const AZ::Vector3> inPositions, SurfacePointList& surfacePointList) const
  168. {
  169. AzPhysics::SimulatedBodyComponentRequestsBus::Event(
  170. GetEntityId(),
  171. [this, inPositions, &surfacePointList](AzPhysics::SimulatedBodyComponentRequestsBus::Events* simBody)
  172. {
  173. AZStd::shared_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  174. AzPhysics::RayCastRequest request;
  175. request.m_direction = -AZ::Vector3::CreateAxisZ();
  176. for (auto& inPosition : inPositions)
  177. {
  178. // test AABB as first pass to claim the point
  179. if (SurfaceData::AabbContains2D(m_colliderBounds, inPosition))
  180. {
  181. // We're casting the ray to look for a collision, so start at the top of the collider and cast downwards
  182. // the full height of the collider.
  183. request.m_start = AZ::Vector3(inPosition.GetX(), inPosition.GetY(), m_colliderBounds.GetMax().GetZ());
  184. request.m_distance = m_colliderBounds.GetExtents().GetZ();
  185. AzPhysics::SceneQueryHit result = simBody->RayCast(request);
  186. if (result)
  187. {
  188. surfacePointList.AddSurfacePoint(
  189. GetEntityId(), inPosition, result.m_position, result.m_normal, m_newPointWeights);
  190. }
  191. }
  192. }
  193. });
  194. }
  195. void SurfaceDataColliderComponent::ModifySurfacePoints(
  196. AZStd::span<const AZ::Vector3> positions,
  197. AZStd::span<const AZ::EntityId> creatorEntityIds,
  198. AZStd::span<SurfaceData::SurfaceTagWeights> weights) const
  199. {
  200. AZ_Assert(
  201. (positions.size() == creatorEntityIds.size()) && (positions.size() == weights.size()),
  202. "Sizes of the passed-in spans don't match");
  203. AZStd::shared_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  204. // If we don't have a valid volume or don't have any modifier tags, there's nothing to do.
  205. if (!m_colliderBounds.IsValid() || m_configuration.m_modifierTags.empty())
  206. {
  207. return;
  208. }
  209. AzPhysics::SimulatedBodyComponentRequestsBus::Event(
  210. GetEntityId(),
  211. [this, positions, creatorEntityIds, &weights](AzPhysics::SimulatedBodyComponentRequestsBus::Events* simBody)
  212. {
  213. // We're checking to see if each point is inside the body, so we can initialize direction and distance for every check.
  214. // The direction shouldn't matter and the distance needs to be 0.
  215. AzPhysics::RayCastRequest request;
  216. request.m_direction = AZ::Vector3::CreateAxisZ();
  217. request.m_distance = 0.0f;
  218. AzPhysics::SceneQueryHit result;
  219. for (size_t index = 0; index < positions.size(); index++)
  220. {
  221. // Only modify points that weren't created by this entity.
  222. if (creatorEntityIds[index] != GetEntityId())
  223. {
  224. // Do a quick bounds check before performing the more expensive raycast.
  225. if (m_colliderBounds.Contains(positions[index]))
  226. {
  227. // We're in bounds, so if the raycast succeeds too, then we're inside the volume.
  228. request.m_start = positions[index];
  229. result = simBody->RayCast(request);
  230. if (result)
  231. {
  232. // If the query point collides with the volume, add all our modifier tags with a weight of 1.0f.
  233. weights[index].AddSurfaceTagWeights(m_configuration.m_modifierTags, 1.0f);
  234. }
  235. }
  236. }
  237. }
  238. });
  239. }
  240. void SurfaceDataColliderComponent::OnCompositionChanged()
  241. {
  242. if (!m_refresh)
  243. {
  244. m_refresh = true;
  245. AZ::TickBus::Handler::BusConnect();
  246. }
  247. }
  248. void SurfaceDataColliderComponent::OnColliderChanged()
  249. {
  250. OnCompositionChanged();
  251. }
  252. void SurfaceDataColliderComponent::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, [[maybe_unused]] const AZ::Transform& world)
  253. {
  254. OnCompositionChanged();
  255. }
  256. void SurfaceDataColliderComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  257. {
  258. if (m_refresh)
  259. {
  260. UpdateColliderData();
  261. m_refresh = false;
  262. }
  263. AZ::TickBus::Handler::BusDisconnect();
  264. }
  265. void SurfaceDataColliderComponent::UpdateColliderData()
  266. {
  267. AZ_PROFILE_FUNCTION(SurfaceData);
  268. bool colliderValidBeforeUpdate = false;
  269. bool colliderValidAfterUpdate = false;
  270. {
  271. AZStd::unique_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  272. colliderValidBeforeUpdate = m_colliderBounds.IsValid();
  273. m_colliderBounds = AZ::Aabb::CreateNull();
  274. AzPhysics::SimulatedBodyComponentRequestsBus::EventResult(m_colliderBounds, GetEntityId(), &AzPhysics::SimulatedBodyComponentRequestsBus::Events::GetAabb);
  275. colliderValidAfterUpdate = m_colliderBounds.IsValid();
  276. }
  277. SurfaceDataRegistryEntry providerRegistryEntry;
  278. providerRegistryEntry.m_entityId = GetEntityId();
  279. providerRegistryEntry.m_bounds = m_colliderBounds;
  280. providerRegistryEntry.m_tags = m_configuration.m_providerTags;
  281. providerRegistryEntry.m_maxPointsCreatedPerInput = 1;
  282. SurfaceDataRegistryEntry modifierRegistryEntry(providerRegistryEntry);
  283. modifierRegistryEntry.m_tags = m_configuration.m_modifierTags;
  284. modifierRegistryEntry.m_maxPointsCreatedPerInput = 0;
  285. if (!colliderValidBeforeUpdate && !colliderValidAfterUpdate)
  286. {
  287. // We didn't have a valid collider before or after running this, so do nothing.
  288. }
  289. else if (!colliderValidBeforeUpdate && colliderValidAfterUpdate)
  290. {
  291. // Our collider has become valid, so register as a provider and save off the provider handle
  292. AZ_Assert((m_providerHandle == InvalidSurfaceDataRegistryHandle), "Surface data handle is initialized before our collider became valid");
  293. AZ_Assert((m_modifierHandle == InvalidSurfaceDataRegistryHandle), "Surface Modifier data handle is initialized before our collider became valid");
  294. AZ_Assert(m_colliderBounds.IsValid(), "Collider Geometry isn't correctly initialized.");
  295. m_providerHandle = AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->RegisterSurfaceDataProvider(providerRegistryEntry);
  296. m_modifierHandle = AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->RegisterSurfaceDataModifier(modifierRegistryEntry);
  297. // Start listening for surface data events
  298. AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  299. AZ_Assert((m_modifierHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  300. SurfaceDataProviderRequestBus::Handler::BusConnect(m_providerHandle);
  301. SurfaceDataModifierRequestBus::Handler::BusConnect(m_modifierHandle);
  302. }
  303. else if (colliderValidBeforeUpdate && !colliderValidAfterUpdate)
  304. {
  305. // Our collider has stopped being valid, so unregister and stop listening for surface data events
  306. AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  307. AZ_Assert((m_modifierHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  308. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataProvider(m_providerHandle);
  309. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataModifier(m_modifierHandle);
  310. m_providerHandle = InvalidSurfaceDataRegistryHandle;
  311. m_modifierHandle = InvalidSurfaceDataRegistryHandle;
  312. SurfaceDataProviderRequestBus::Handler::BusDisconnect();
  313. SurfaceDataModifierRequestBus::Handler::BusDisconnect();
  314. }
  315. else if (colliderValidBeforeUpdate && colliderValidAfterUpdate)
  316. {
  317. // Our collider was valid before and after, it just changed in some way, so update our registry entry.
  318. AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  319. AZ_Assert((m_modifierHandle != InvalidSurfaceDataRegistryHandle), "Invalid modifier data handle");
  320. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UpdateSurfaceDataProvider(m_providerHandle, providerRegistryEntry);
  321. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UpdateSurfaceDataModifier(m_modifierHandle, modifierRegistryEntry);
  322. }
  323. }
  324. }