ROS2FrameComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 "NamespaceComputation.h"
  9. #include "ROS2FrameSystemBus.h"
  10. #include <AzCore/RTTI/BehaviorContext.h>
  11. #include <AzCore/Component/Entity.h>
  12. #include <AzCore/Component/EntityUtils.h>
  13. #include <AzCore/Serialization/EditContext.h>
  14. #include <AzCore/Serialization/EditContextConstants.inl>
  15. #include <AzCore/Serialization/Json/RegistrationContext.h>
  16. #include <AzCore/Serialization/SerializeContext.h>
  17. #include <AzCore/Settings/SettingsRegistry.h>
  18. #include <ROS2/Frame/ROS2FrameComponent.h>
  19. #include <ROS2/Frame/ROS2FrameComponentBus.h>
  20. #include <ROS2/Frame/ROS2FrameConfiguration.h>
  21. #include <rapidjson/stringbuffer.h>
  22. namespace ROS2
  23. {
  24. namespace Internal
  25. {
  26. bool HasComponentOfType(const AZ::Entity* entity, const AZ::Uuid typeId)
  27. {
  28. auto components = AZ::EntityUtils::FindDerivedComponents(entity, typeId);
  29. return !components.empty();
  30. }
  31. AZ::TransformInterface* GetEntityTransformInterface(const AZ::Entity* entity)
  32. {
  33. if (!entity)
  34. {
  35. AZ_Error("GetEntityTransformInterface", false, "Invalid entity!");
  36. return nullptr;
  37. }
  38. auto* interface = entity->FindComponent<AzFramework::TransformComponent>();
  39. return interface;
  40. }
  41. const ROS2FrameComponent* GetFirstROS2FrameAncestor(const AZ::Entity* entity)
  42. {
  43. auto* entityTransformInterface = GetEntityTransformInterface(entity);
  44. if (!entityTransformInterface)
  45. {
  46. AZ_Error("GetFirstROS2FrameAncestor", false, "Invalid transform interface!");
  47. return nullptr;
  48. }
  49. AZ::EntityId parentEntityId = entityTransformInterface->GetParentId();
  50. if (!parentEntityId.IsValid())
  51. { // We have reached the top level, there is no parent entity so there can be no parent ROS2Frame
  52. return nullptr;
  53. }
  54. AZ::Entity* parentEntity = nullptr;
  55. AZ::ComponentApplicationBus::BroadcastResult(parentEntity, &AZ::ComponentApplicationRequests::FindEntity, parentEntityId);
  56. AZ_Assert(parentEntity, "No parent entity id : %s", parentEntityId.ToString().c_str());
  57. auto* component = parentEntity->FindComponent<ROS2FrameComponent>();
  58. if (component == nullptr)
  59. { // Parent entity has no ROS2Frame, but there can still be a ROS2Frame in its ancestors
  60. return GetFirstROS2FrameAncestor(parentEntity);
  61. }
  62. // Found the component!
  63. return component;
  64. }
  65. bool IsDynamicHeuristic(bool isTopLevel, const AZ::Entity* entity)
  66. {
  67. if (isTopLevel)
  68. {
  69. return true;
  70. }
  71. const bool hasJoints =
  72. Internal::HasComponentOfType(entity, AZ::Uuid("{B01FD1D2-1D91-438D-874A-BF5EB7E919A8}")); // PhysX::JointComponent;
  73. const bool hasFixedJoints =
  74. Internal::HasComponentOfType(entity, AZ::Uuid("{02E6C633-8F44-4CEE-AE94-DCB06DE36422}")); // PhysX::FixedJointComponent
  75. const bool hasArticulations =
  76. Internal::HasComponentOfType(entity, AZ::Uuid("{48751E98-B35F-4A2F-A908-D9CDD5230264}")); // PhysX::ArticulationComponent
  77. return (hasJoints && !hasFixedJoints) || hasArticulations;
  78. }
  79. } // namespace Internal
  80. void ROS2FrameComponent::Init()
  81. {
  82. }
  83. void ROS2FrameComponent::Activate()
  84. {
  85. // reset cache
  86. m_parentFrame.reset();
  87. m_sourceFrame.reset();
  88. ComputeNamespaceAndFrameName();
  89. if (!m_disabled)
  90. {
  91. AZ::TickBus::Handler::BusConnect();
  92. }
  93. ROS2FrameComponentBus::Handler::BusConnect(GetEntityId());
  94. if (auto* frameSystemInterface = ROS2FrameSystemInterface::Get())
  95. {
  96. frameSystemInterface->RegisterFrame(GetEntityId());
  97. }
  98. }
  99. void ROS2FrameComponent::Deactivate()
  100. {
  101. if (auto* frameSystemInterface = ROS2FrameSystemInterface::Get())
  102. {
  103. frameSystemInterface->UnregisterFrame(GetEntityId());
  104. }
  105. ROS2FrameComponentBus::Handler::BusDisconnect(GetEntityId());
  106. AZ::TickBus::Handler::BusDisconnect();
  107. m_parentFrame.reset();
  108. m_sourceFrame.reset();
  109. m_ros2Transform.reset();
  110. }
  111. void ROS2FrameComponent::ComputeNamespaceAndFrameName()
  112. {
  113. m_computedNamespace = ComputeNamespace(GetEntityId());
  114. m_computedFrameName = GetNamespacedName(m_computedNamespace, m_configuration.m_frameName);
  115. m_computedJointName = GetNamespacedName(m_computedNamespace, m_configuration.m_jointName);
  116. }
  117. void ROS2FrameComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  118. {
  119. if (m_sourceFrame == AZStd::nullopt)
  120. {
  121. // cache parent frame
  122. const auto* ros2FrameComponent = Internal::GetFirstROS2FrameAncestor(GetEntity());
  123. if (ros2FrameComponent != nullptr)
  124. {
  125. m_parentFrame = ros2FrameComponent->GetEntityId();
  126. m_sourceFrame = ros2FrameComponent->GetNamespacedFrameID();
  127. }
  128. else
  129. {
  130. m_parentFrame = AZStd::nullopt;
  131. AZStd::string odometryFrame = GetGlobalFrameID();
  132. if (!odometryFrame.empty())
  133. {
  134. m_sourceFrame = odometryFrame;
  135. }
  136. }
  137. }
  138. // if we don't have to send transforms stop handler
  139. if (!m_configuration.m_publishTransform)
  140. {
  141. AZ::TickBus::Handler::BusDisconnect();
  142. return;
  143. }
  144. if (m_ros2Transform == nullptr && m_sourceFrame.has_value())
  145. {
  146. const bool isTopLevel = !m_parentFrame.has_value();
  147. const bool dynamic = m_configuration.m_forceDynamic || Internal::IsDynamicHeuristic(isTopLevel, GetEntity());
  148. AZ_Printf(
  149. "ROS2FrameComponent",
  150. "Publishing transform from %s to %s, type %s",
  151. m_sourceFrame->c_str(),
  152. GetNamespacedFrameID().c_str(),
  153. dynamic ? "dynamic" : "static");
  154. m_ros2Transform = AZStd::make_unique<ROS2Transform>(*m_sourceFrame, GetNamespacedFrameID(), dynamic);
  155. m_ros2Transform->Publish(GetFrameTransform());
  156. if (!dynamic)
  157. {
  158. // static transform published, no need to keep ticking
  159. AZ::TickBus::Handler::BusDisconnect();
  160. return;
  161. }
  162. }
  163. if (m_ros2Transform)
  164. {
  165. m_ros2Transform->Publish(GetFrameTransform());
  166. }
  167. }
  168. const ROS2FrameComponent* ROS2FrameComponent::GetParentROS2FrameComponent() const
  169. {
  170. if (m_parentFrame.has_value())
  171. {
  172. AZ::Entity* parentEntity = nullptr;
  173. AZ::ComponentApplicationBus::BroadcastResult(parentEntity, &AZ::ComponentApplicationRequests::FindEntity, *m_parentFrame);
  174. AZ_Assert(parentEntity, "No parent entity id : %s", m_parentFrame->ToString().c_str());
  175. return parentEntity->FindComponent<ROS2FrameComponent>();
  176. }
  177. return nullptr;
  178. }
  179. AZ::Transform ROS2FrameComponent::GetFrameTransform() const
  180. {
  181. auto* transformInterface = Internal::GetEntityTransformInterface(GetEntity());
  182. if (const auto* parentFrame = GetParentROS2FrameComponent(); parentFrame != nullptr)
  183. {
  184. auto* ancestorTransformInterface = Internal::GetEntityTransformInterface(parentFrame->GetEntity());
  185. AZ_Assert(ancestorTransformInterface, "No transform interface for an entity with a ROS2Frame component, which requires it!");
  186. const auto worldFromAncestor = ancestorTransformInterface->GetWorldTM();
  187. const auto worldFromThis = transformInterface->GetWorldTM();
  188. const auto ancestorFromWorld = worldFromAncestor.GetInverse();
  189. return ancestorFromWorld * worldFromThis;
  190. }
  191. return transformInterface->GetWorldTM();
  192. }
  193. void ROS2FrameComponent::Reflect(AZ::ReflectContext* context)
  194. {
  195. ROS2FrameConfiguration::Reflect(context);
  196. if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
  197. {
  198. serialize->Class<ROS2FrameComponent, AZ::Component>()->Version(1)->Field(
  199. "ROS2FrameConfiguration", &ROS2FrameComponent::m_configuration);
  200. if (AZ::EditContext* ec = serialize->GetEditContext())
  201. {
  202. ec->Class<ROS2FrameComponent>(
  203. "ROS2 Frame Game Component (outdated)",
  204. "This is a game version of the ROS2 Frame component. This is outdated and was updated to the new "
  205. "ROS2FrameEditorComponent. If you see this component a manual conversion is required.")
  206. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  207. ->Attribute(AZ::Edit::Attributes::Category, "ROS2")
  208. ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/ROS2Frame.svg")
  209. ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/ROS2Frame.svg")
  210. ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/ros2-frame/");
  211. }
  212. }
  213. if (auto bh = azrtti_cast<AZ::BehaviorContext*>(context))
  214. {
  215. bh->EBus<ROS2FrameComponentBus>("ROS2FrameComponentBus")
  216. ->Event("GetNamespace", &ROS2FrameComponentBus::Events::GetNamespace)
  217. ->Event("GetNamespacedFrameID", &ROS2FrameComponentBus::Events::GetNamespacedFrameID)
  218. ->Event("GetNamespacedJointName", &ROS2FrameComponentBus::Events::GetNamespacedJointName)
  219. ->Event("GetJointName", &ROS2FrameComponentBus::Events::GetJointName)
  220. ->Event("GetFrameName", &ROS2FrameComponentBus::Events::GetFrameName)
  221. ->Event("GetGlobalFrameID", &ROS2FrameComponentBus::Events::GetGlobalFrameID);
  222. }
  223. }
  224. void ROS2FrameComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  225. {
  226. provided.push_back(AZ_CRC_CE("ROS2Frame"));
  227. }
  228. void ROS2FrameComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  229. {
  230. incompatible.push_back(AZ_CRC_CE("ROS2Frame"));
  231. }
  232. void ROS2FrameComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  233. {
  234. required.push_back(AZ_CRC_CE("TransformService"));
  235. }
  236. ROS2FrameComponent::ROS2FrameComponent(){};
  237. ROS2FrameComponent::ROS2FrameComponent(const ROS2FrameConfiguration& ros2FrameConfiguration)
  238. : m_configuration(ros2FrameConfiguration)
  239. {
  240. }
  241. //! Disable publishing the transform. It allows to tinker with the transform without spamming /tf_static
  242. //! you can disable it inactive state, and then enable it again.
  243. void ROS2FrameComponent::DisablePublishingTransform()
  244. {
  245. m_disabled = true;
  246. m_parentFrame.reset();
  247. m_ros2Transform.reset();
  248. m_sourceFrame.reset();
  249. AZ::TickBus::Handler::BusDisconnect();
  250. }
  251. //! Enable publishing the transform. It will compute the namespace and frame name again.
  252. //! Note that other won't be notified of the change.
  253. void ROS2FrameComponent::EnablePublishingTransform()
  254. {
  255. ComputeNamespaceAndFrameName();
  256. m_disabled = false;
  257. AZ::TickBus::Handler::BusConnect();
  258. }
  259. AZStd::string ROS2FrameComponent::GetNamespace() const
  260. {
  261. return m_computedNamespace;
  262. }
  263. AZStd::string ROS2FrameComponent::GetNamespacedFrameID() const
  264. {
  265. return m_computedFrameName;
  266. }
  267. AZStd::string ROS2FrameComponent::GetNamespacedJointName() const
  268. {
  269. return m_computedJointName;
  270. }
  271. AZStd::string ROS2FrameComponent::GetJointName() const
  272. {
  273. return m_configuration.m_jointName;
  274. }
  275. AZStd::string ROS2FrameComponent::GetFrameName() const
  276. {
  277. return m_configuration.m_frameName;
  278. }
  279. ROS2FrameConfiguration ROS2FrameComponent::GetConfiguration() const
  280. {
  281. return m_configuration;
  282. }
  283. void ROS2FrameComponent::SetConfiguration(const ROS2FrameConfiguration& config)
  284. {
  285. if (m_entity)
  286. {
  287. AZ_Assert(GetEntity()->GetState() != AZ::Entity::State::Active, "API can be called only for disabled components");
  288. }
  289. if (!config.m_namespaceConfiguration.m_customNamespace.empty())
  290. {
  291. AZ_Warning(
  292. "ROS2FrameComponent",
  293. config.m_namespaceConfiguration.m_namespaceStrategy == NamespaceConfiguration::NamespaceStrategy::Custom,
  294. "Custom namespace is set but the namespace strategy is not set to Custom. The custom namespace will be ignored.");
  295. }
  296. m_configuration = config;
  297. }
  298. AZStd::string ROS2FrameComponent::GetGlobalFrameID() const
  299. {
  300. const AZStd::string odometryFrame = GetGlobalFrameIDFromRegistry();
  301. if (odometryFrame.empty())
  302. {
  303. return "";
  304. }
  305. return GetNamespacedName(m_computedNamespace, odometryFrame);
  306. }
  307. } // namespace ROS2