SurfaceDataShapeComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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/SurfaceDataShapeComponent.h>
  9. #include <AzCore/Component/TransformBus.h>
  10. #include <AzCore/Debug/Profiler.h>
  11. #include <AzCore/Serialization/EditContext.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <SurfaceData/SurfaceDataSystemRequestBus.h>
  14. #include <SurfaceData/Utility/SurfaceDataUtility.h>
  15. #include <SurfaceDataProfiler.h>
  16. namespace SurfaceData
  17. {
  18. void SurfaceDataShapeConfig::Reflect(AZ::ReflectContext* context)
  19. {
  20. AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
  21. if (serialize)
  22. {
  23. serialize->Class<SurfaceDataShapeConfig, AZ::ComponentConfig>()
  24. ->Version(0)
  25. ->Field("ProviderTags", &SurfaceDataShapeConfig::m_providerTags)
  26. ->Field("ModifierTags", &SurfaceDataShapeConfig::m_modifierTags)
  27. ;
  28. AZ::EditContext* edit = serialize->GetEditContext();
  29. if (edit)
  30. {
  31. edit->Class<SurfaceDataShapeConfig>(
  32. "Shape 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, &SurfaceDataShapeConfig::m_providerTags, "Generated Tags", "Surface tags to add to created points")
  37. ->DataElement(0, &SurfaceDataShapeConfig::m_modifierTags, "Extended Tags", "Surface tags to add to contained points")
  38. ;
  39. }
  40. }
  41. }
  42. void SurfaceDataShapeComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  43. {
  44. services.push_back(AZ_CRC_CE("SurfaceDataProviderService"));
  45. services.push_back(AZ_CRC_CE("SurfaceDataModifierService"));
  46. }
  47. void SurfaceDataShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  48. {
  49. services.push_back(AZ_CRC_CE("SurfaceDataProviderService"));
  50. services.push_back(AZ_CRC_CE("SurfaceDataModifierService"));
  51. }
  52. void SurfaceDataShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  53. {
  54. services.push_back(AZ_CRC_CE("ShapeService"));
  55. }
  56. void SurfaceDataShapeComponent::Reflect(AZ::ReflectContext* context)
  57. {
  58. SurfaceDataShapeConfig::Reflect(context);
  59. AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
  60. if (serialize)
  61. {
  62. serialize->Class<SurfaceDataShapeComponent, AZ::Component>()
  63. ->Version(0)
  64. ->Field("Configuration", &SurfaceDataShapeComponent::m_configuration)
  65. ;
  66. }
  67. }
  68. SurfaceDataShapeComponent::SurfaceDataShapeComponent(const SurfaceDataShapeConfig& configuration)
  69. : m_configuration(configuration)
  70. {
  71. }
  72. void SurfaceDataShapeComponent::Activate()
  73. {
  74. m_providerHandle = InvalidSurfaceDataRegistryHandle;
  75. m_modifierHandle = InvalidSurfaceDataRegistryHandle;
  76. m_refresh = false;
  77. AZ::TransformNotificationBus::Handler::BusConnect(GetEntityId());
  78. LmbrCentral::ShapeComponentNotificationsBus::Handler::BusConnect(GetEntityId());
  79. // Update the cached shape data and bounds, then register the surface data provider / modifier
  80. m_newPointWeights.AssignSurfaceTagWeights(m_configuration.m_providerTags, 1.0f);
  81. UpdateShapeData();
  82. }
  83. void SurfaceDataShapeComponent::Deactivate()
  84. {
  85. if (m_providerHandle != InvalidSurfaceDataRegistryHandle)
  86. {
  87. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataProvider(m_providerHandle);
  88. m_providerHandle = InvalidSurfaceDataRegistryHandle;
  89. }
  90. if (m_modifierHandle != InvalidSurfaceDataRegistryHandle)
  91. {
  92. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataModifier(m_modifierHandle);
  93. m_modifierHandle = InvalidSurfaceDataRegistryHandle;
  94. }
  95. m_refresh = false;
  96. AZ::TickBus::Handler::BusDisconnect();
  97. AZ::TransformNotificationBus::Handler::BusDisconnect();
  98. LmbrCentral::ShapeComponentNotificationsBus::Handler::BusDisconnect();
  99. SurfaceDataProviderRequestBus::Handler::BusDisconnect();
  100. SurfaceDataModifierRequestBus::Handler::BusDisconnect();
  101. // Clear the cached shape data
  102. {
  103. AZStd::unique_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  104. m_shapeBounds = AZ::Aabb::CreateNull();
  105. m_shapeBoundsIsValid = false;
  106. }
  107. }
  108. bool SurfaceDataShapeComponent::ReadInConfig(const AZ::ComponentConfig* baseConfig)
  109. {
  110. if (auto config = azrtti_cast<const SurfaceDataShapeConfig*>(baseConfig))
  111. {
  112. m_configuration = *config;
  113. return true;
  114. }
  115. return false;
  116. }
  117. bool SurfaceDataShapeComponent::WriteOutConfig(AZ::ComponentConfig* outBaseConfig) const
  118. {
  119. if (auto config = azrtti_cast<SurfaceDataShapeConfig*>(outBaseConfig))
  120. {
  121. *config = m_configuration;
  122. return true;
  123. }
  124. return false;
  125. }
  126. void SurfaceDataShapeComponent::GetSurfacePoints(const AZ::Vector3& inPosition, SurfacePointList& surfacePointList) const
  127. {
  128. GetSurfacePointsFromList(AZStd::span<const AZ::Vector3>(&inPosition, 1), surfacePointList);
  129. }
  130. void SurfaceDataShapeComponent::GetSurfacePointsFromList(
  131. AZStd::span<const AZ::Vector3> inPositions, SurfacePointList& surfacePointList) const
  132. {
  133. SURFACE_DATA_PROFILE_FUNCTION_VERBOSE
  134. AZStd::shared_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  135. if (!m_shapeBoundsIsValid)
  136. {
  137. return;
  138. }
  139. LmbrCentral::ShapeComponentRequestsBus::Event(
  140. GetEntityId(),
  141. [this, inPositions, &surfacePointList](LmbrCentral::ShapeComponentRequestsBus::Events* shape)
  142. {
  143. const AZ::Vector3 rayDirection = -AZ::Vector3::CreateAxisZ();
  144. // Shapes don't currently have a way to query normals at a point intersection, so we'll just return a Z-up normal
  145. // until they get support for it.
  146. const AZ::Vector3 surfacePointNormal = AZ::Vector3::CreateAxisZ();
  147. for (auto& inPosition : inPositions)
  148. {
  149. if (SurfaceData::AabbContains2D(m_shapeBounds, inPosition))
  150. {
  151. const AZ::Vector3 rayOrigin = AZ::Vector3(inPosition.GetX(), inPosition.GetY(), m_shapeBounds.GetMax().GetZ());
  152. float intersectionDistance = 0.0f;
  153. bool hitShape = shape->IntersectRay(rayOrigin, rayDirection, intersectionDistance);
  154. if (hitShape)
  155. {
  156. AZ::Vector3 position = rayOrigin + intersectionDistance * rayDirection;
  157. surfacePointList.AddSurfacePoint(GetEntityId(), inPosition, position, surfacePointNormal, m_newPointWeights);
  158. }
  159. }
  160. }
  161. });
  162. }
  163. void SurfaceDataShapeComponent::ModifySurfacePoints(
  164. AZStd::span<const AZ::Vector3> positions,
  165. AZStd::span<const AZ::EntityId> creatorEntityIds,
  166. AZStd::span<SurfaceData::SurfaceTagWeights> weights) const
  167. {
  168. SURFACE_DATA_PROFILE_FUNCTION_VERBOSE
  169. AZ_Assert(
  170. (positions.size() == creatorEntityIds.size()) && (positions.size() == weights.size()),
  171. "Sizes of the passed-in spans don't match");
  172. AZStd::shared_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  173. if (m_shapeBoundsIsValid && !m_configuration.m_modifierTags.empty())
  174. {
  175. const AZ::EntityId entityId = GetEntityId();
  176. LmbrCentral::ShapeComponentRequestsBus::Event(
  177. entityId,
  178. [entityId, this, positions, creatorEntityIds, &weights](LmbrCentral::ShapeComponentRequestsBus::Events* shape)
  179. {
  180. for (size_t index = 0; index < positions.size(); index++)
  181. {
  182. // Don't bother modifying points that this component created.
  183. if (creatorEntityIds[index] == entityId)
  184. {
  185. continue;
  186. }
  187. if (m_shapeBounds.Contains(positions[index]) && shape->IsPointInside(positions[index]))
  188. {
  189. // If the point is inside our shape, add all our modifier tags with a weight of 1.0f.
  190. weights[index].AddSurfaceTagWeights(m_configuration.m_modifierTags, 1.0f);
  191. }
  192. }
  193. });
  194. }
  195. }
  196. void SurfaceDataShapeComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& /*world*/)
  197. {
  198. OnCompositionChanged();
  199. }
  200. void SurfaceDataShapeComponent::OnShapeChanged([[maybe_unused]] ShapeChangeReasons changeReason)
  201. {
  202. OnCompositionChanged();
  203. }
  204. void SurfaceDataShapeComponent::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/)
  205. {
  206. if (m_refresh)
  207. {
  208. UpdateShapeData();
  209. m_refresh = false;
  210. }
  211. AZ::TickBus::Handler::BusDisconnect();
  212. }
  213. void SurfaceDataShapeComponent::OnCompositionChanged()
  214. {
  215. if (!m_refresh)
  216. {
  217. m_refresh = true;
  218. AZ::TickBus::Handler::BusConnect();
  219. }
  220. }
  221. void SurfaceDataShapeComponent::UpdateShapeData()
  222. {
  223. AZ_PROFILE_FUNCTION(SurfaceData);
  224. bool shapeValidBeforeUpdate = false;
  225. bool shapeValidAfterUpdate = false;
  226. {
  227. AZStd::unique_lock<decltype(m_cacheMutex)> lock(m_cacheMutex);
  228. shapeValidBeforeUpdate = m_shapeBoundsIsValid;
  229. m_shapeBounds = AZ::Aabb::CreateNull();
  230. LmbrCentral::ShapeComponentRequestsBus::EventResult(m_shapeBounds, GetEntityId(), &LmbrCentral::ShapeComponentRequestsBus::Events::GetEncompassingAabb);
  231. m_shapeBoundsIsValid = m_shapeBounds.IsValid();
  232. shapeValidAfterUpdate = m_shapeBoundsIsValid;
  233. }
  234. SurfaceDataRegistryEntry providerRegistryEntry;
  235. providerRegistryEntry.m_entityId = GetEntityId();
  236. providerRegistryEntry.m_bounds = m_shapeBounds;
  237. providerRegistryEntry.m_tags = m_configuration.m_providerTags;
  238. providerRegistryEntry.m_maxPointsCreatedPerInput = 1;
  239. SurfaceDataRegistryEntry modifierRegistryEntry(providerRegistryEntry);
  240. modifierRegistryEntry.m_tags = m_configuration.m_modifierTags;
  241. modifierRegistryEntry.m_maxPointsCreatedPerInput = 0;
  242. if (shapeValidBeforeUpdate && shapeValidAfterUpdate)
  243. {
  244. // Our shape was valid before and after, it just changed in some way, so update our registry entries
  245. AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  246. AZ_Assert((m_modifierHandle != InvalidSurfaceDataRegistryHandle), "Invalid modifier data handle");
  247. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UpdateSurfaceDataProvider(m_providerHandle, providerRegistryEntry);
  248. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UpdateSurfaceDataModifier(m_modifierHandle, modifierRegistryEntry);
  249. }
  250. else if (!shapeValidBeforeUpdate && shapeValidAfterUpdate)
  251. {
  252. // Our shape has become valid, so register as a provider and save off the registry handles
  253. AZ_Assert((m_providerHandle == InvalidSurfaceDataRegistryHandle), "Surface Provider data handle is initialized before our shape became valid");
  254. AZ_Assert((m_modifierHandle == InvalidSurfaceDataRegistryHandle), "Surface Modifier data handle is initialized before our shape became valid");
  255. m_providerHandle = AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->RegisterSurfaceDataProvider(providerRegistryEntry);
  256. m_modifierHandle = AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->RegisterSurfaceDataModifier(modifierRegistryEntry);
  257. // Start listening for surface data events
  258. AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  259. AZ_Assert((m_modifierHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  260. SurfaceDataProviderRequestBus::Handler::BusConnect(m_providerHandle);
  261. SurfaceDataModifierRequestBus::Handler::BusConnect(m_modifierHandle);
  262. }
  263. else if (shapeValidBeforeUpdate && !shapeValidAfterUpdate)
  264. {
  265. // Our shape has stopped being valid, so unregister and stop listening for surface data events
  266. AZ_Assert((m_providerHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  267. AZ_Assert((m_modifierHandle != InvalidSurfaceDataRegistryHandle), "Invalid surface data handle");
  268. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataProvider(m_providerHandle);
  269. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataModifier(m_modifierHandle);
  270. m_providerHandle = InvalidSurfaceDataRegistryHandle;
  271. m_modifierHandle = InvalidSurfaceDataRegistryHandle;
  272. SurfaceDataProviderRequestBus::Handler::BusDisconnect();
  273. SurfaceDataModifierRequestBus::Handler::BusDisconnect();
  274. }
  275. else
  276. {
  277. // We didn't have a valid shape before or after running this, so do nothing.
  278. }
  279. }
  280. const float SurfaceDataShapeComponent::s_rayAABBHeightPadding = 0.1f;
  281. }