ROS2LidarSensorComponent.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 <Atom/RPI.Public/AuxGeom/AuxGeomFeatureProcessorInterface.h>
  9. #include <Atom/RPI.Public/Scene.h>
  10. #include <Lidar/LidarRegistrarSystemComponent.h>
  11. #include <Lidar/PointCloudMessageBuilder.h>
  12. #include <Lidar/ROS2LidarSensorComponent.h>
  13. #include <ROS2/Frame/ROS2FrameComponent.h>
  14. #include <ROS2/Utilities/ROS2Names.h>
  15. #include <ROS2Sensors/Lidar/ClassSegmentationBus.h>
  16. #include <sensor_msgs/point_cloud2_iterator.hpp>
  17. namespace ROS2Sensors
  18. {
  19. namespace
  20. {
  21. const char* PointCloudType = "sensor_msgs::msg::PointCloud2";
  22. }
  23. void ROS2LidarSensorComponent::Reflect(AZ::ReflectContext* context)
  24. {
  25. if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  26. {
  27. serializeContext->Class<ROS2LidarSensorComponent, SensorBaseType>()->Version(3)->Field(
  28. "lidarCore", &ROS2LidarSensorComponent::m_lidarCore);
  29. if (auto* editContext = serializeContext->GetEditContext())
  30. {
  31. editContext->Class<ROS2LidarSensorComponent>("ROS2 Lidar Sensor", "Lidar sensor component")
  32. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  33. ->Attribute(AZ::Edit::Attributes::Category, "ROS2")
  34. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game"))
  35. ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/ROS2LidarSensor.svg")
  36. ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/ROS2LidarSensor.svg")
  37. ->DataElement(
  38. AZ::Edit::UIHandlers::ComboBox,
  39. &ROS2LidarSensorComponent::m_lidarCore,
  40. "Lidar configuration",
  41. "Lidar configuration")
  42. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly);
  43. }
  44. }
  45. }
  46. void ROS2LidarSensorComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  47. {
  48. required.push_back(AZ_CRC_CE("ROS2Frame"));
  49. }
  50. ROS2LidarSensorComponent::ROS2LidarSensorComponent()
  51. : m_lidarCore(LidarTemplateUtils::Get3DModels())
  52. {
  53. ROS2::TopicConfiguration pc;
  54. AZStd::string type = PointCloudType;
  55. pc.m_type = type;
  56. pc.m_topic = "pc";
  57. m_sensorConfiguration.m_frequency = 10.f;
  58. m_sensorConfiguration.m_publishersConfigurations.insert(AZStd::make_pair(type, pc));
  59. }
  60. ROS2LidarSensorComponent::ROS2LidarSensorComponent(
  61. const ROS2::SensorConfiguration& sensorConfiguration, const LidarSensorConfiguration& lidarConfiguration)
  62. : m_lidarCore(lidarConfiguration)
  63. {
  64. m_sensorConfiguration = sensorConfiguration;
  65. }
  66. void ROS2LidarSensorComponent::Activate()
  67. {
  68. ROS2SensorComponentBase::Activate();
  69. m_lidarCore.Init(GetEntityId());
  70. m_lidarRaycasterId = m_lidarCore.GetLidarRaycasterId();
  71. m_canRaycasterPublish = false;
  72. if (m_lidarCore.m_lidarConfiguration.m_lidarSystemFeatures & LidarSystemFeatures::PointcloudPublishing)
  73. {
  74. LidarRaycasterRequestBus::EventResult(
  75. m_canRaycasterPublish, m_lidarRaycasterId, &LidarRaycasterRequestBus::Events::CanHandlePublishing);
  76. }
  77. if (m_canRaycasterPublish)
  78. {
  79. const ROS2::TopicConfiguration& publisherConfig = m_sensorConfiguration.m_publishersConfigurations[PointCloudType];
  80. auto* ros2Frame = GetEntity()->FindComponent<ROS2::ROS2FrameComponent>();
  81. LidarRaycasterRequestBus::Event(
  82. m_lidarRaycasterId,
  83. &LidarRaycasterRequestBus::Events::ConfigurePointCloudPublisher,
  84. ROS2::ROS2Names::GetNamespacedName(GetNamespace(), publisherConfig.m_topic),
  85. ros2Frame->GetNamespacedFrameID().data(),
  86. publisherConfig.GetQoS());
  87. }
  88. else
  89. {
  90. auto ros2Node = ROS2::ROS2Interface::Get()->GetNode();
  91. AZ_Assert(m_sensorConfiguration.m_publishersConfigurations.size() == 1, "Invalid configuration of publishers for lidar sensor");
  92. const ROS2::TopicConfiguration& publisherConfig = m_sensorConfiguration.m_publishersConfigurations[PointCloudType];
  93. AZStd::string fullTopic = ROS2::ROS2Names::GetNamespacedName(GetNamespace(), publisherConfig.m_topic);
  94. m_pointCloudPublisher = ros2Node->create_publisher<sensor_msgs::msg::PointCloud2>(fullTopic.data(), publisherConfig.GetQoS());
  95. const auto resultFlags = m_lidarCore.GetResultFlags();
  96. if (IsFlagEnabled(RaycastResultFlags::SegmentationData, resultFlags))
  97. {
  98. m_segmentationClassesPublisher = ros2Node->create_publisher<vision_msgs::msg::LabelInfo>(
  99. ROS2::ROS2Names::GetNamespacedName(GetNamespace(), "segmentation_classes").data(), publisherConfig.GetQoS());
  100. }
  101. }
  102. StartSensor(
  103. m_sensorConfiguration.m_frequency,
  104. [this]([[maybe_unused]] auto&&... args)
  105. {
  106. FrequencyTick();
  107. },
  108. [this]([[maybe_unused]] auto&&... args)
  109. {
  110. if (!m_sensorConfiguration.m_visualize)
  111. {
  112. return;
  113. }
  114. m_lidarCore.VisualizeResults();
  115. });
  116. LidarConfigurationRequestBus::Handler::BusConnect(GetEntityId());
  117. }
  118. void ROS2LidarSensorComponent::Deactivate()
  119. {
  120. LidarConfigurationRequestBus::Handler::BusDisconnect(GetEntityId());
  121. StopSensor();
  122. m_pointCloudPublisher.reset();
  123. m_lidarCore.Deinit();
  124. ROS2SensorComponentBase::Deactivate();
  125. }
  126. void ROS2LidarSensorComponent::FrequencyTick()
  127. {
  128. if (m_canRaycasterPublish && m_sensorConfiguration.m_publishingEnabled)
  129. {
  130. const builtin_interfaces::msg::Time timestamp = ROS2::ROS2Interface::Get()->GetROSTimestamp();
  131. LidarRaycasterRequestBus::Event(
  132. m_lidarRaycasterId,
  133. &LidarRaycasterRequestBus::Events::UpdatePublisherTimestamp,
  134. aznumeric_cast<AZ::u64>(timestamp.sec) * aznumeric_cast<AZ::u64>(1.0e9f) + timestamp.nanosec);
  135. }
  136. AZStd::optional<RaycastResults> lastScanResults = m_lidarCore.PerformRaycast();
  137. if (!lastScanResults.has_value() || m_canRaycasterPublish || !m_sensorConfiguration.m_publishingEnabled)
  138. {
  139. return;
  140. }
  141. PublishRaycastResults(lastScanResults.value());
  142. }
  143. template<typename T>
  144. using Pc2MsgIt = sensor_msgs::PointCloud2Iterator<T>;
  145. void ROS2LidarSensorComponent::PublishRaycastResults(const RaycastResults& results)
  146. {
  147. auto builder = PointCloud2MessageBuilder(
  148. GetEntity()->FindComponent<ROS2::ROS2FrameComponent>()->GetNamespacedFrameID(),
  149. ROS2::ROS2Interface::Get()->GetROSTimestamp(),
  150. results.GetCount());
  151. builder.AddField("x", sensor_msgs::msg::PointField::FLOAT32)
  152. .AddField("y", sensor_msgs::msg::PointField::FLOAT32)
  153. .AddField("z", sensor_msgs::msg::PointField::FLOAT32);
  154. if (results.IsFieldPresent<RaycastResultFlags::Intensity>())
  155. {
  156. builder.AddField("intensity", sensor_msgs::msg::PointField::FLOAT32);
  157. }
  158. if (results.IsFieldPresent<RaycastResultFlags::SegmentationData>())
  159. {
  160. builder.AddField("entity_id", sensor_msgs::msg::PointField::INT32);
  161. builder.AddField("class_id", sensor_msgs::msg::PointField::UINT8);
  162. builder.AddField("rgba", sensor_msgs::msg::PointField::UINT32);
  163. }
  164. sensor_msgs::msg::PointCloud2 message = builder.Get();
  165. Pc2MsgIt<float> messageXIt(message, "x");
  166. Pc2MsgIt<float> messageYIt(message, "y");
  167. Pc2MsgIt<float> messageZIt(message, "z");
  168. const auto positionField = results.GetConstFieldSpan<RaycastResultFlags::Point>().value();
  169. auto positionIt = positionField.begin();
  170. AZStd::optional<Pc2MsgIt<float>> messageIntensityIt;
  171. AZStd::optional<RaycastResults::FieldSpan<RaycastResultFlags::Intensity>::const_iterator> intensityIt;
  172. if (results.IsFieldPresent<RaycastResultFlags::Intensity>())
  173. {
  174. messageIntensityIt = Pc2MsgIt<float>(message, "intensity");
  175. intensityIt = results.GetConstFieldSpan<RaycastResultFlags::Intensity>().value().begin();
  176. }
  177. struct MessageSegmentationIterators
  178. {
  179. Pc2MsgIt<int32_t> m_entityIdIt;
  180. Pc2MsgIt<uint8_t> m_classIdIt;
  181. Pc2MsgIt<uint32_t> m_rgbaIt;
  182. };
  183. AZStd::optional<MessageSegmentationIterators> messageSegDataIts;
  184. AZStd::optional<RaycastResults::FieldSpan<RaycastResultFlags::SegmentationData>::const_iterator> segDataIt;
  185. if (results.IsFieldPresent<RaycastResultFlags::SegmentationData>())
  186. {
  187. messageSegDataIts = MessageSegmentationIterators{
  188. Pc2MsgIt<int32_t>(message, "entity_id"),
  189. Pc2MsgIt<uint8_t>(message, "class_id"),
  190. Pc2MsgIt<uint32_t>(message, "rgba"),
  191. };
  192. segDataIt = results.GetConstFieldSpan<RaycastResultFlags::SegmentationData>().value().begin();
  193. }
  194. const auto entityTransform = GetEntity()->FindComponent<AzFramework::TransformComponent>();
  195. const auto inverseLidarTM = entityTransform->GetWorldTM().GetInverse();
  196. auto* classSegmentationInterface = ClassSegmentationInterface::Get();
  197. AZ_Warning(
  198. __func__,
  199. !results.IsFieldPresent<RaycastResultFlags::SegmentationData>() || classSegmentationInterface,
  200. "Segmentation data was requested but the Class Segmentation interface was unavailable. Unable to fetch segmentation class "
  201. "data. Please make sure to add the Class Segmentation Configuration Component to the Level Entity for this feature to work "
  202. "properly.");
  203. for (size_t i = 0; i < results.GetCount(); ++i)
  204. {
  205. AZ::Vector3 point = *positionIt;
  206. const AZ::Vector3 globalPoint = inverseLidarTM.TransformPoint(point);
  207. *messageXIt = globalPoint.GetX();
  208. *messageYIt = globalPoint.GetY();
  209. *messageZIt = globalPoint.GetZ();
  210. if (messageIntensityIt.has_value() && intensityIt.has_value())
  211. {
  212. *messageIntensityIt.value() = *intensityIt.value();
  213. ++intensityIt.value();
  214. ++messageIntensityIt.value();
  215. }
  216. if (messageSegDataIts.has_value() && segDataIt.has_value() && classSegmentationInterface)
  217. {
  218. const ResultTraits<RaycastResultFlags::SegmentationData>::Type segmentationData = *segDataIt.value();
  219. *messageSegDataIts->m_entityIdIt = segmentationData.m_entityId;
  220. *messageSegDataIts->m_classIdIt = segmentationData.m_classId;
  221. AZ::Color color = classSegmentationInterface->GetClassColor(segmentationData.m_classId);
  222. AZ::u32 rvizColorFormat = color.GetA8() << 24 | color.GetR8() << 16 | color.GetG8() << 8 | color.GetB8();
  223. *messageSegDataIts->m_rgbaIt = rvizColorFormat;
  224. ++segDataIt.value();
  225. ++messageSegDataIts->m_entityIdIt;
  226. ++messageSegDataIts->m_classIdIt;
  227. ++messageSegDataIts->m_rgbaIt;
  228. }
  229. ++positionIt;
  230. ++messageXIt;
  231. ++messageYIt;
  232. ++messageZIt;
  233. }
  234. m_pointCloudPublisher->publish(message);
  235. if (m_segmentationClassesPublisher && classSegmentationInterface)
  236. {
  237. const auto& segmentationClassConfigList = classSegmentationInterface->GetClassConfigList();
  238. vision_msgs::msg::LabelInfo segmentationClasses;
  239. for (const auto& segmentationClass : segmentationClassConfigList)
  240. {
  241. vision_msgs::msg::VisionClass visionClass;
  242. visionClass.class_id = segmentationClass.m_classId;
  243. visionClass.class_name = segmentationClass.m_className.c_str();
  244. segmentationClasses.class_map.push_back(visionClass);
  245. }
  246. m_segmentationClassesPublisher->publish(segmentationClasses);
  247. }
  248. }
  249. void ROS2LidarSensorComponent::SetConfiguration(const LidarSensorConfiguration& configuration)
  250. {
  251. m_lidarCore.Deinit();
  252. m_lidarCore.m_lidarConfiguration = configuration;
  253. m_lidarCore.Init(GetEntityId());
  254. }
  255. const LidarSensorConfiguration ROS2LidarSensorComponent::GetConfiguration()
  256. {
  257. return m_lidarCore.m_lidarConfiguration;
  258. }
  259. AZStd::string ROS2LidarSensorComponent::GetModelName()
  260. {
  261. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_name;
  262. }
  263. void ROS2LidarSensorComponent::SetModelName(const AZStd::string& name)
  264. {
  265. m_lidarCore.Deinit();
  266. m_lidarCore.m_lidarConfiguration.m_lidarModelName = name;
  267. m_lidarCore.m_lidarConfiguration.FetchLidarModelConfiguration();
  268. // Unknown lidar models are set to custom lidar model with a given name
  269. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_name = name;
  270. m_lidarCore.Init(GetEntityId());
  271. }
  272. bool ROS2LidarSensorComponent::IsSegmentationEnabled()
  273. {
  274. return m_lidarCore.m_lidarConfiguration.m_isSegmentationEnabled;
  275. }
  276. void ROS2LidarSensorComponent::SetSegmentationEnabled(bool enabled)
  277. {
  278. m_lidarCore.Deinit();
  279. m_lidarCore.m_lidarConfiguration.m_isSegmentationEnabled = enabled;
  280. m_lidarCore.Init(GetEntityId());
  281. }
  282. bool ROS2LidarSensorComponent::IsAddPointsAtMaxEnabled()
  283. {
  284. return m_lidarCore.m_lidarConfiguration.m_addPointsAtMax;
  285. }
  286. void ROS2LidarSensorComponent::SetAddPointsAtMaxEnabled(bool addPoints)
  287. {
  288. m_lidarCore.Deinit();
  289. m_lidarCore.m_lidarConfiguration.m_addPointsAtMax = addPoints;
  290. m_lidarCore.Init(GetEntityId());
  291. }
  292. bool ROS2LidarSensorComponent::Is2D()
  293. {
  294. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_is2D;
  295. }
  296. float ROS2LidarSensorComponent::GetMinHAngle()
  297. {
  298. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_minHAngle;
  299. }
  300. void ROS2LidarSensorComponent::SetMinHAngle(float angle)
  301. {
  302. if (angle < -180.0f || angle > 180.0f)
  303. {
  304. AZ_Error("ROS2LidarSensorComponent", false, "Min horizontal angle must be between -180 and 180 degrees.");
  305. return;
  306. }
  307. m_lidarCore.Deinit();
  308. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_minHAngle = angle;
  309. m_lidarCore.Init(GetEntityId());
  310. }
  311. float ROS2LidarSensorComponent::GetMaxHAngle()
  312. {
  313. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_maxHAngle;
  314. }
  315. void ROS2LidarSensorComponent::SetMaxHAngle(float angle)
  316. {
  317. if (angle < -180.0f || angle > 180.0f)
  318. {
  319. AZ_Error("ROS2LidarSensorComponent", false, "Max horizontal angle must be between -180 and 180 degrees.");
  320. return;
  321. }
  322. m_lidarCore.Deinit();
  323. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_maxHAngle = angle;
  324. m_lidarCore.Init(GetEntityId());
  325. }
  326. float ROS2LidarSensorComponent::GetMinVAngle()
  327. {
  328. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_minVAngle;
  329. }
  330. void ROS2LidarSensorComponent::SetMinVAngle(float angle)
  331. {
  332. if (angle < -90.0f || angle > 90.0f)
  333. {
  334. AZ_Error("ROS2LidarSensorComponent", false, "Min vertical angle must be between -90 and 90 degrees.");
  335. return;
  336. }
  337. m_lidarCore.Deinit();
  338. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_minVAngle = angle;
  339. m_lidarCore.Init(GetEntityId());
  340. }
  341. float ROS2LidarSensorComponent::GetMaxVAngle()
  342. {
  343. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_maxVAngle;
  344. }
  345. void ROS2LidarSensorComponent::SetMaxVAngle(float angle)
  346. {
  347. if (angle < -90.0f || angle > 90.0f)
  348. {
  349. AZ_Error("ROS2LidarSensorComponent", false, "Max vertical angle must be between -90 and 90 degrees.");
  350. return;
  351. }
  352. m_lidarCore.Deinit();
  353. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_maxVAngle = angle;
  354. m_lidarCore.Init(GetEntityId());
  355. }
  356. unsigned int ROS2LidarSensorComponent::GetLayers()
  357. {
  358. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_layers;
  359. }
  360. void ROS2LidarSensorComponent::SetLayers(unsigned int layers)
  361. {
  362. m_lidarCore.Deinit();
  363. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_layers = layers;
  364. m_lidarCore.Init(GetEntityId());
  365. }
  366. unsigned int ROS2LidarSensorComponent::GetNumberOfIncrements()
  367. {
  368. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_numberOfIncrements;
  369. }
  370. void ROS2LidarSensorComponent::SetNumberOfIncrements(unsigned int increments)
  371. {
  372. m_lidarCore.Deinit();
  373. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_numberOfIncrements = increments;
  374. m_lidarCore.Init(GetEntityId());
  375. }
  376. float ROS2LidarSensorComponent::GetMinRange()
  377. {
  378. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_minRange;
  379. }
  380. void ROS2LidarSensorComponent::SetMinRange(float range)
  381. {
  382. const float maxRange = m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_maxRange;
  383. if (range < 0.0f || range > maxRange)
  384. {
  385. AZ_Error("ROS2LidarSensorComponent", false, "Min range cannot be less than 0 or greater than max range (%f).", maxRange);
  386. return;
  387. }
  388. m_lidarCore.Deinit();
  389. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_minRange = range;
  390. m_lidarCore.Init(GetEntityId());
  391. }
  392. float ROS2LidarSensorComponent::GetMaxRange()
  393. {
  394. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_maxRange;
  395. }
  396. void ROS2LidarSensorComponent::SetMaxRange(float range)
  397. {
  398. const float minRange = m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_minRange;
  399. if (range < minRange)
  400. {
  401. AZ_Error("ROS2LidarSensorComponent", false, "Max range cannot be less than min range (%f).", minRange);
  402. return;
  403. }
  404. m_lidarCore.Deinit();
  405. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_maxRange = range;
  406. m_lidarCore.Init(GetEntityId());
  407. }
  408. const LidarTemplate::NoiseParameters& ROS2LidarSensorComponent::GetNoiseParameters()
  409. {
  410. return m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_noiseParameters;
  411. }
  412. void ROS2LidarSensorComponent::SetNoiseParameters(const LidarTemplate::NoiseParameters& params)
  413. {
  414. if (params.m_angularNoiseStdDev < 0.0f || params.m_angularNoiseStdDev > 180.0f || params.m_distanceNoiseStdDevBase < 0.0f ||
  415. params.m_distanceNoiseStdDevRisePerMeter < 0.0f)
  416. {
  417. AZ_Error("ROS2LidarSensorComponent", false, "Invalid noise parameters provided.");
  418. return;
  419. }
  420. m_lidarCore.Deinit();
  421. m_lidarCore.m_lidarConfiguration.m_lidarParameters.m_noiseParameters = params;
  422. m_lidarCore.Init(GetEntityId());
  423. }
  424. } // namespace ROS2Sensors