2
0

ROS2FrameComponent.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 "ROS2FrameSystemComponent.h"
  9. #include <AzCore/Component/Entity.h>
  10. #include <AzCore/Component/EntityUtils.h>
  11. #include <AzCore/RTTI/ReflectContext.h>
  12. #include <AzCore/Serialization/EditContext.h>
  13. #include <AzCore/Serialization/EditContextConstants.inl>
  14. #include <AzCore/Serialization/Json/JsonSerialization.h>
  15. #include <AzCore/Serialization/Json/JsonSerializationResult.h>
  16. #include <AzCore/Serialization/Json/RegistrationContext.h>
  17. #include <AzCore/Serialization/SerializeContext.h>
  18. #include <ROS2/Frame/ROS2FrameComponent.h>
  19. #include <ROS2/Frame/ROS2FrameConfiguration.h>
  20. #include <ROS2/ROS2Bus.h>
  21. #include <ROS2/Utilities/ROS2Names.h>
  22. #include <rapidjson/document.h>
  23. #include <rapidjson/stringbuffer.h>
  24. namespace ROS2
  25. {
  26. namespace Internal
  27. {
  28. bool HasComponentOfType(const AZ::Entity* entity, const AZ::Uuid typeId)
  29. {
  30. auto components = AZ::EntityUtils::FindDerivedComponents(entity, typeId);
  31. return !components.empty();
  32. }
  33. AZ::TransformInterface* GetEntityTransformInterface(const AZ::Entity* entity)
  34. {
  35. if (!entity)
  36. {
  37. AZ_Error("GetEntityTransformInterface", false, "Invalid entity!");
  38. return nullptr;
  39. }
  40. auto* interface = entity->FindComponent<AzFramework::TransformComponent>();
  41. return interface;
  42. }
  43. const ROS2FrameComponent* GetFirstROS2FrameAncestor(const AZ::Entity* entity)
  44. {
  45. auto* entityTransformInterface = GetEntityTransformInterface(entity);
  46. if (!entityTransformInterface)
  47. {
  48. AZ_Error("GetFirstROS2FrameAncestor", false, "Invalid transform interface!");
  49. return nullptr;
  50. }
  51. AZ::EntityId parentEntityId = entityTransformInterface->GetParentId();
  52. if (!parentEntityId.IsValid())
  53. { // We have reached the top level, there is no parent entity so there can be no parent ROS2Frame
  54. return nullptr;
  55. }
  56. AZ::Entity* parentEntity = nullptr;
  57. AZ::ComponentApplicationBus::BroadcastResult(parentEntity, &AZ::ComponentApplicationRequests::FindEntity, parentEntityId);
  58. AZ_Assert(parentEntity, "No parent entity id : %s", parentEntityId.ToString().c_str());
  59. auto* component = parentEntity->FindComponent<ROS2FrameComponent>();
  60. if (component == nullptr)
  61. { // Parent entity has no ROS2Frame, but there can still be a ROS2Frame in its ancestors
  62. return GetFirstROS2FrameAncestor(parentEntity);
  63. }
  64. // Found the component!
  65. return component;
  66. }
  67. } // namespace Internal
  68. AZ::JsonSerializationResult::Result JsonFrameComponentConfigSerializer::Load(
  69. void* outputValue, const AZ::Uuid& outputValueTypeId, const rapidjson::Value& inputValue, AZ::JsonDeserializerContext& context)
  70. {
  71. AZ_Error(
  72. "ROS2FrameComponent",
  73. false,
  74. "An old version of the ROS2FrameComponent is being loaded. Manual conversion is required. The conversion script is "
  75. "located in: "
  76. "o3de-extras/Gems/ROS2/Code/Source/Frame/Conversions/FrameConversion.py");
  77. namespace JSR = AZ::JsonSerializationResult;
  78. auto configInstance = reinterpret_cast<ROS2FrameComponent*>(outputValue);
  79. AZ_Assert(configInstance, "Output value for JsonFrameComponentConfigSerializer can't be null.");
  80. JSR::ResultCode result(JSR::Tasks::ReadField);
  81. {
  82. JSR::ResultCode componentIdLoadResult = ContinueLoadingFromJsonObjectField(
  83. &configInstance->m_jointName, azrtti_typeid<decltype(configInstance->m_jointName)>(), inputValue, "Joint Name", context);
  84. result.Combine(componentIdLoadResult);
  85. }
  86. {
  87. JSR::ResultCode componentIdLoadResult = ContinueLoadingFromJsonObjectField(
  88. &configInstance->m_frameName, azrtti_typeid<decltype(configInstance->m_frameName)>(), inputValue, "Frame Name", context);
  89. result.Combine(componentIdLoadResult);
  90. }
  91. {
  92. JSR::ResultCode componentIdLoadResult = ContinueLoadingFromJsonObjectField(
  93. &configInstance->m_publishTransform,
  94. azrtti_typeid<decltype(configInstance->m_publishTransform)>(),
  95. inputValue,
  96. "Publish Transform",
  97. context);
  98. result.Combine(componentIdLoadResult);
  99. }
  100. {
  101. JSR::ResultCode componentIdLoadResult = ContinueLoadingFromJsonObjectField(
  102. &configInstance->m_namespaceConfiguration,
  103. azrtti_typeid<decltype(configInstance->m_namespaceConfiguration)>(),
  104. inputValue,
  105. "Namespace Configuration",
  106. context);
  107. result.Combine(componentIdLoadResult);
  108. }
  109. return context.Report(
  110. result,
  111. result.GetProcessing() != JSR::Processing::Halted ? "Successfully loaded ROS2FrameComponent information."
  112. : "Failed to load ROS2FrameComponent information.");
  113. }
  114. AZ_CLASS_ALLOCATOR_IMPL(JsonFrameComponentConfigSerializer, AZ::SystemAllocator);
  115. void ROS2FrameComponent::Init()
  116. {
  117. m_namespaceConfiguration.Init();
  118. }
  119. void ROS2FrameComponent::Activate()
  120. {
  121. m_namespaceConfiguration.PopulateNamespace(IsTopLevel(), GetEntity()->GetName());
  122. if (m_publishTransform)
  123. {
  124. AZ_TracePrintf("ROS2FrameComponent", "Setting up %s", GetFrameID().data());
  125. // The frame will always be dynamic if it's a top entity.
  126. if (IsTopLevel())
  127. {
  128. m_isDynamic = true;
  129. }
  130. // Otherwise it'll be dynamic when it has joints and it's not a fixed joint.
  131. else
  132. {
  133. // Quickfix: Use hard-coded uuids to avoid linking to PhysX.
  134. const bool hasJoints =
  135. Internal::HasComponentOfType(m_entity, AZ::Uuid("{B01FD1D2-1D91-438D-874A-BF5EB7E919A8}")); // PhysX::JointComponent;
  136. const bool hasFixedJoints = Internal::HasComponentOfType(
  137. m_entity, AZ::Uuid("{02E6C633-8F44-4CEE-AE94-DCB06DE36422}")); // PhysX::FixedJointComponent
  138. const bool hasArticulations = Internal::HasComponentOfType(
  139. m_entity, AZ::Uuid("{48751E98-B35F-4A2F-A908-D9CDD5230264}")); // PhysX::ArticulationComponent
  140. m_isDynamic = (hasJoints && !hasFixedJoints) || hasArticulations;
  141. }
  142. AZ_TracePrintf(
  143. "ROS2FrameComponent",
  144. "Setting up %s transform between parent %s and child %s to be published %s\n",
  145. IsDynamic() ? "dynamic" : "static",
  146. GetParentFrameID().data(),
  147. GetFrameID().data(),
  148. IsDynamic() ? "continuously to /tf" : "once to /tf_static");
  149. m_ros2Transform = AZStd::make_unique<ROS2Transform>(GetParentFrameID(), GetFrameID(), IsDynamic());
  150. if (IsDynamic())
  151. {
  152. AZ::TickBus::Handler::BusConnect();
  153. }
  154. else
  155. {
  156. m_ros2Transform->Publish(GetFrameTransform());
  157. }
  158. }
  159. }
  160. void ROS2FrameComponent::Deactivate()
  161. {
  162. if (m_publishTransform)
  163. {
  164. if (IsDynamic())
  165. {
  166. AZ::TickBus::Handler::BusDisconnect();
  167. }
  168. m_ros2Transform.reset();
  169. }
  170. }
  171. void ROS2FrameComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  172. {
  173. m_ros2Transform->Publish(GetFrameTransform());
  174. }
  175. AZStd::string ROS2FrameComponent::GetGlobalFrameName() const
  176. {
  177. return ROS2Names::GetNamespacedName(GetNamespace(), AZStd::string("odom"));
  178. }
  179. void ROS2FrameComponent::UpdateNamespaceConfiguration(
  180. const AZStd::string& ros2Namespace, NamespaceConfiguration::NamespaceStrategy strategy)
  181. {
  182. m_namespaceConfiguration.SetNamespace(ros2Namespace, strategy);
  183. }
  184. bool ROS2FrameComponent::IsTopLevel() const
  185. {
  186. return GetGlobalFrameName() == GetParentFrameID();
  187. }
  188. bool ROS2FrameComponent::IsDynamic() const
  189. {
  190. return m_isDynamic;
  191. }
  192. const ROS2FrameComponent* ROS2FrameComponent::GetParentROS2FrameComponent() const
  193. {
  194. return Internal::GetFirstROS2FrameAncestor(GetEntity());
  195. }
  196. AZ::Transform ROS2FrameComponent::GetFrameTransform() const
  197. {
  198. auto* transformInterface = Internal::GetEntityTransformInterface(GetEntity());
  199. if (const auto* parentFrame = GetParentROS2FrameComponent(); parentFrame != nullptr)
  200. {
  201. auto* ancestorTransformInterface = Internal::GetEntityTransformInterface(parentFrame->GetEntity());
  202. AZ_Assert(ancestorTransformInterface, "No transform interface for an entity with a ROS2Frame component, which requires it!");
  203. const auto worldFromAncestor = ancestorTransformInterface->GetWorldTM();
  204. const auto worldFromThis = transformInterface->GetWorldTM();
  205. const auto ancestorFromWorld = worldFromAncestor.GetInverse();
  206. return ancestorFromWorld * worldFromThis;
  207. }
  208. return transformInterface->GetWorldTM();
  209. }
  210. AZStd::string ROS2FrameComponent::GetParentFrameID() const
  211. {
  212. if (auto parentFrame = GetParentROS2FrameComponent(); parentFrame != nullptr)
  213. {
  214. return parentFrame->GetFrameID();
  215. }
  216. // If parent entity does not exist or does not have a ROS2FrameComponent, return ROS2 default global frame.
  217. return GetGlobalFrameName();
  218. }
  219. AZStd::string ROS2FrameComponent::GetFrameID() const
  220. {
  221. return ROS2Names::GetNamespacedName(GetNamespace(), m_frameName);
  222. }
  223. void ROS2FrameComponent::SetFrameID(const AZStd::string& frameId)
  224. {
  225. m_frameName = frameId;
  226. }
  227. AZStd::string ROS2FrameComponent::GetNamespace() const
  228. {
  229. auto parentFrame = GetParentROS2FrameComponent();
  230. AZStd::string parentNamespace;
  231. if (parentFrame != nullptr)
  232. {
  233. parentNamespace = parentFrame->GetNamespace();
  234. }
  235. return m_namespaceConfiguration.GetNamespace(parentNamespace);
  236. }
  237. AZ::Name ROS2FrameComponent::GetJointName() const
  238. {
  239. return AZ::Name(ROS2Names::GetNamespacedName(GetNamespace(), m_jointName).c_str());
  240. }
  241. void ROS2FrameComponent::SetJointName(const AZStd::string& jointName)
  242. {
  243. m_jointName = jointName;
  244. }
  245. void ROS2FrameComponent::Reflect(AZ::ReflectContext* context)
  246. {
  247. if (auto jsonContext = azrtti_cast<AZ::JsonRegistrationContext*>(context))
  248. {
  249. jsonContext->Serializer<JsonFrameComponentConfigSerializer>()->HandlesType<ROS2FrameComponent>();
  250. }
  251. ROS2FrameConfiguration::Reflect(context);
  252. if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
  253. {
  254. serialize->Class<ROS2FrameComponent, AZ::Component>()
  255. ->Version(1)
  256. ->Field("Frame Name", &ROS2FrameComponent::m_frameName)
  257. ->Field("Joint Name", &ROS2FrameComponent::m_jointName)
  258. ->Field("Publish Transform", &ROS2FrameComponent::m_publishTransform)
  259. ->Field("Namespace Configuration", &ROS2FrameComponent::m_namespaceConfiguration);
  260. if (AZ::EditContext* ec = serialize->GetEditContext())
  261. {
  262. ec->Class<ROS2FrameComponent>(
  263. "ROS2 Frame Game Component (outdated)",
  264. "This is a game version of the ROS2 Frame component. This is outdated and was updated to the new "
  265. "ROS2FrameEditorComponent. If you see this component a manual conversion is required.")
  266. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  267. ->Attribute(AZ::Edit::Attributes::Category, "ROS2")
  268. ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/ROS2Frame.svg")
  269. ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/ROS2Frame.svg")
  270. ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/ros2-frame/")
  271. ->UIElement(
  272. AZ::Edit::UIHandlers::Label,
  273. "This component is no longer supported. Manual conversion to the ROS2FrameEditorComponent is required.")
  274. ->DataElement(AZ::Edit::UIHandlers::Default, &ROS2FrameComponent::m_frameName, "Frame Name", "Name of the frame.")
  275. ->DataElement(AZ::Edit::UIHandlers::Default, &ROS2FrameComponent::m_jointName, "Joint Name", "Name of the joint.")
  276. ->DataElement(
  277. AZ::Edit::UIHandlers::Default,
  278. &ROS2FrameComponent::m_publishTransform,
  279. "Publish Transform",
  280. "Publish the transform of this frame.")
  281. ->DataElement(
  282. AZ::Edit::UIHandlers::Default,
  283. &ROS2FrameComponent::m_namespaceConfiguration,
  284. "Namespace Configuration",
  285. "Configuration of the namespace for this frame.");
  286. }
  287. }
  288. }
  289. void ROS2FrameComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  290. {
  291. provided.push_back(AZ_CRC_CE("ROS2Frame"));
  292. }
  293. void ROS2FrameComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  294. {
  295. incompatible.push_back(AZ_CRC_CE("ROS2Frame"));
  296. }
  297. void ROS2FrameComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  298. {
  299. required.push_back(AZ_CRC_CE("TransformService"));
  300. }
  301. ROS2FrameComponent::ROS2FrameComponent(){};
  302. ROS2FrameComponent::ROS2FrameComponent(const ROS2FrameConfiguration& configuration)
  303. : m_namespaceConfiguration(configuration.m_namespaceConfiguration)
  304. , m_frameName(configuration.m_frameName)
  305. , m_jointName(configuration.m_jointName)
  306. , m_publishTransform(configuration.m_publishTransform)
  307. , m_isDynamic(configuration.m_isDynamic){};
  308. ROS2FrameConfiguration ROS2FrameComponent::GetConfiguration() const
  309. {
  310. ROS2FrameConfiguration configuration;
  311. configuration.m_namespaceConfiguration = m_namespaceConfiguration;
  312. configuration.m_frameName = m_frameName;
  313. configuration.m_jointName = m_jointName;
  314. configuration.m_publishTransform = m_publishTransform;
  315. configuration.m_isDynamic = m_isDynamic;
  316. return configuration;
  317. }
  318. } // namespace ROS2