point_cloud_fusion v1.6.0
Loading...
Searching...
No Matches
point_cloud_layout.hpp
Go to the documentation of this file.
1// Copyright Institute for Automotive Engineering (ika), RWTH Aachen University
2// SPDX-License-Identifier: Apache-2.0
3
4#pragma once
5
6#include <algorithm>
7#include <cmath>
8#include <cstddef>
9#include <cstdint>
10#include <cstring>
11#include <iterator>
12#include <limits>
13#include <optional>
14#include <stdexcept>
15#include <string>
16#include <type_traits>
17#include <unordered_map>
18#include <unordered_set>
19#include <vector>
20
21#include <sensor_msgs/msg/point_cloud2.hpp>
22
24
31inline std::size_t fieldDatatypeSize(uint8_t datatype) {
32 using sensor_msgs::msg::PointField;
33 switch (datatype) {
34 case PointField::INT8:
35 case PointField::UINT8:
36 return 1;
37 case PointField::INT16:
38 case PointField::UINT16:
39 return 2;
40 case PointField::INT32:
41 case PointField::UINT32:
42 case PointField::FLOAT32:
43 return 4;
44 case PointField::FLOAT64:
45 return 8;
46 default:
47 return 0;
48 }
49}
50
51struct FieldCopy {
52 uint32_t source_offset{0};
53 uint32_t destination_offset{0};
54 std::size_t byte_length{0};
55};
56
57struct FieldFill {
58 uint32_t destination_offset{0};
59 std::vector<uint8_t> bytes;
60};
61
63 uint32_t source_offset{0};
64 uint32_t destination_offset{0};
65 uint8_t source_datatype{0};
67};
68
70 bool valid{false};
71 uint32_t x_offset{0};
72 uint32_t y_offset{0};
73 uint32_t z_offset{0};
74 int time_offset{-1};
75 bool whole_point_copy{false};
76 std::vector<FieldCopy> copies;
77 std::vector<FieldConversion> conversions;
78 std::vector<FieldFill> field_fills;
79 std::vector<std::string> zero_filled_fields;
80 std::string rejection_reason;
81};
82
84 std::vector<sensor_msgs::msg::PointField> fields;
85 uint32_t point_step{0};
86 uint32_t x_offset{0};
87 uint32_t y_offset{0};
88 uint32_t z_offset{0};
90 bool is_bigendian{false};
91 bool is_dense{true};
92 std::string fill_error;
93 std::vector<std::string> unused_fill_fields;
94 std::vector<InputLayout> inputs;
95 std::vector<std::string> conflicting_fields;
96};
97
98using MissingFieldFillValues = std::unordered_map<std::string, double>;
99
101inline MissingFieldFillValues parseMissingFieldFillValues(const std::vector<std::string>& entries) {
102 const auto trim = [](const std::string& value) {
103 const auto first = value.find_first_not_of(" \t\r\n");
104 return first == std::string::npos ? std::string{} : value.substr(first, value.find_last_not_of(" \t\r\n") - first + 1);
105 };
107 for (const auto& entry : entries) {
108 const auto separator = entry.find('=');
109 if (separator == std::string::npos) {
110 throw std::invalid_argument("Expected field=value in missing_field_fill_values: " + entry);
111 }
112 const auto name = trim(entry.substr(0, separator));
113 const auto text = trim(entry.substr(separator + 1));
114 if (name.empty() || text.empty()) throw std::invalid_argument("Empty field or value in missing_field_fill_values: " + entry);
115 double value{};
116 try {
117 std::size_t consumed = 0;
118 value = std::stod(text, &consumed);
119 if (consumed != text.size() || std::isinf(value)) throw std::invalid_argument("invalid value");
120 } catch (const std::exception&) {
121 throw std::invalid_argument("Fill value for '" + name + "' must be a finite number or nan");
122 }
123 if (!result.emplace(name, value).second) {
124 throw std::invalid_argument("Duplicate missing-field fill policy for '" + name + "'");
125 }
126 }
127 return result;
128}
129
131template <typename T>
132inline void encodeFillValue(double value, uint8_t* destination) {
133 T typed{};
134 if constexpr (std::is_integral_v<T>) {
135 if (!std::isfinite(value) || std::trunc(value) != value || value < static_cast<double>(std::numeric_limits<T>::lowest()) ||
136 value > static_cast<double>(std::numeric_limits<T>::max())) {
137 throw std::invalid_argument("fill must be an in-range integer (NaN is only supported for FLOAT32/FLOAT64)");
138 }
139 typed = static_cast<T>(value);
140 } else {
141 if (std::isinf(value) || (std::isfinite(value) && std::abs(value) > std::numeric_limits<T>::max())) {
142 throw std::invalid_argument("fill exceeds the floating-point datatype range");
143 }
144 typed = std::isnan(value) ? std::numeric_limits<T>::quiet_NaN() : static_cast<T>(value);
145 }
146 std::memcpy(destination, &typed, sizeof(typed));
147}
148
150inline FieldFill makeFieldFill(const sensor_msgs::msg::PointField& field, double value, bool is_bigendian) {
151 FieldFill fill;
152 fill.destination_offset = field.offset;
153 const auto element_size = fieldDatatypeSize(field.datatype);
154 if (element_size == 0 || field.count == 0) throw std::invalid_argument("invalid fill datatype or element count");
155 fill.bytes.resize(element_size * field.count);
156 using F = sensor_msgs::msg::PointField;
157 switch (field.datatype) {
158 case F::INT8:
159 encodeFillValue<int8_t>(value, fill.bytes.data());
160 break;
161 case F::UINT8:
162 encodeFillValue<uint8_t>(value, fill.bytes.data());
163 break;
164 case F::INT16:
165 encodeFillValue<int16_t>(value, fill.bytes.data());
166 break;
167 case F::UINT16:
168 encodeFillValue<uint16_t>(value, fill.bytes.data());
169 break;
170 case F::INT32:
171 encodeFillValue<int32_t>(value, fill.bytes.data());
172 break;
173 case F::UINT32:
174 encodeFillValue<uint32_t>(value, fill.bytes.data());
175 break;
176 case F::FLOAT32:
177 encodeFillValue<float>(value, fill.bytes.data());
178 break;
179 case F::FLOAT64:
180 encodeFillValue<double>(value, fill.bytes.data());
181 break;
182 default:
183 throw std::invalid_argument("unsupported fill datatype");
184 }
185 const uint16_t endian_check = 1;
186 uint8_t first_byte{};
187 std::memcpy(&first_byte, &endian_check, sizeof(first_byte));
188 const bool host_bigendian = first_byte == 0;
189 if (is_bigendian != host_bigendian) {
190 std::reverse(fill.bytes.begin(), std::next(fill.bytes.begin(), static_cast<std::ptrdiff_t>(element_size)));
191 }
192 for (uint32_t element = 1; element < field.count; ++element) {
193 std::copy_n(fill.bytes.cbegin(), element_size,
194 std::next(fill.bytes.begin(), static_cast<std::ptrdiff_t>(element * element_size)));
195 }
196 return fill;
197}
198
200inline void fillMissingFields(uint8_t* destination, const InputLayout& input) {
201 for (const auto& fill : input.field_fills) {
202 std::copy(fill.bytes.begin(), fill.bytes.end(), std::next(destination, fill.destination_offset));
203 }
204}
205
213inline bool sameType(const sensor_msgs::msg::PointField& lhs, const sensor_msgs::msg::PointField& rhs) {
214 return lhs.name == rhs.name && lhs.datatype == rhs.datatype && lhs.count == rhs.count;
215}
216
225inline bool validField(const sensor_msgs::msg::PointField& field, uint32_t point_step) {
226 const auto size = fieldDatatypeSize(field.datatype);
227 return size > 0 && field.count > 0 && static_cast<std::size_t>(field.offset) + size * field.count <= point_step;
228}
229
237inline const sensor_msgs::msg::PointField* findField(const sensor_msgs::msg::PointCloud2& cloud, const std::string& name) {
238 const auto it =
239 std::find_if(cloud.fields.begin(), cloud.fields.end(), [&name](const auto& field) { return field.name == name; });
240 return it == cloud.fields.end() ? nullptr : &*it;
241}
242
244inline bool fieldIsPublished(const std::vector<std::string>& requested_fields, const std::string& name) {
245 return requested_fields.empty() || std::find(requested_fields.begin(), requested_fields.end(), name) != requested_fields.end();
246}
247
254inline std::vector<std::string> processingFields(const std::vector<std::string>& requested_fields,
255 const std::string& time_field_name,
256 bool motion_compensation) {
257 if (requested_fields.empty() || !motion_compensation || fieldIsPublished(requested_fields, time_field_name)) {
258 return requested_fields;
259 }
260 auto result = requested_fields;
261 result.push_back(time_field_name);
262 return result;
263}
264
272inline bool validXyzField(const sensor_msgs::msg::PointField* field, uint32_t point_step) {
273 return field != nullptr && field->datatype == sensor_msgs::msg::PointField::FLOAT32 && field->count == 1 &&
274 validField(*field, point_step);
275}
276
292inline BatchLayout buildBatchLayout(const std::vector<sensor_msgs::msg::PointCloud2::ConstSharedPtr>& clouds,
293 const std::vector<std::string>& requested_fields,
294 const std::string& time_field_name,
295 const MissingFieldFillValues& fill_values = {},
296 const sensor_msgs::msg::PointField* calibration_field = nullptr) {
297 BatchLayout result;
298 result.inputs.resize(clouds.size());
299
300 std::vector<std::size_t> valid_indices;
301 for (std::size_t index = 0; index < clouds.size(); ++index) {
302 const auto& cloud = clouds[index];
303 auto& input = result.inputs[index];
304 if (!cloud) {
305 input.rejection_reason = "null cloud";
306 continue;
307 }
308 const auto* x = findField(*cloud, "x");
309 const auto* y = findField(*cloud, "y");
310 const auto* z = findField(*cloud, "z");
311 if (!validXyzField(x, cloud->point_step) || !validXyzField(y, cloud->point_step) || !validXyzField(z, cloud->point_step)) {
312 input.rejection_reason = "missing or invalid FLOAT32 x/y/z field";
313 continue;
314 }
315 input.valid = true;
316 result.is_dense = result.is_dense && cloud->is_dense;
317 input.x_offset = x->offset;
318 input.y_offset = y->offset;
319 input.z_offset = z->offset;
320 if (const auto* time = findField(*cloud, time_field_name); time != nullptr &&
321 time->datatype == sensor_msgs::msg::PointField::UINT32 &&
322 time->count == 1 && validField(*time, cloud->point_step)) {
323 input.time_offset = static_cast<int>(time->offset);
324 }
325 valid_indices.push_back(index);
326 }
327 if (valid_indices.empty()) return result;
328
329 const auto& first = *clouds[valid_indices.front()];
330 result.is_bigendian = first.is_bigendian;
331 result.homogeneous_fast_path = std::all_of(valid_indices.begin(), valid_indices.end(), [&](std::size_t index) {
332 const auto& cloud = *clouds[index];
333 return cloud.point_step == first.point_step && cloud.fields == first.fields && cloud.is_bigendian == first.is_bigendian;
334 });
335
336 std::vector<sensor_msgs::msg::PointField> selected;
337 if (!requested_fields.empty()) {
338 std::unordered_set<std::string> emitted;
339 for (const auto& name : requested_fields) {
340 if (!emitted.insert(name).second) continue;
341 const sensor_msgs::msg::PointField* descriptor = nullptr;
342 for (const auto index : valid_indices) {
343 const auto* candidate = findField(*clouds[index], name);
344 if (candidate != nullptr && validField(*candidate, clouds[index]->point_step)) {
345 descriptor = candidate;
346 break;
347 }
348 }
349 if (descriptor != nullptr) {
350 selected.push_back(calibration_field != nullptr && name == calibration_field->name ? *calibration_field : *descriptor);
351 }
352 }
353 } else if (result.homogeneous_fast_path) {
354 selected = first.fields;
355 } else {
356 std::unordered_map<std::string, sensor_msgs::msg::PointField> descriptors;
357 std::unordered_set<std::string> conflicts;
358 std::vector<std::string> order;
359 for (const auto index : valid_indices) {
360 for (const auto& field : clouds[index]->fields) {
361 if (!validField(field, clouds[index]->point_step)) continue;
362 const auto [it, inserted] = descriptors.emplace(field.name, field);
363 if (inserted) {
364 order.push_back(field.name);
365 } else if (!sameType(it->second, field)) {
366 conflicts.insert(field.name);
367 }
368 }
369 }
370 for (const auto& name : order) {
371 if (calibration_field != nullptr && name == calibration_field->name) {
372 selected.push_back(*calibration_field);
373 } else if (conflicts.count(name) != 0U) {
374 result.conflicting_fields.push_back(name);
375 } else {
376 selected.push_back(descriptors.at(name));
377 }
378 }
379 }
380
381 // XYZ is part of every valid output even if a configured optional-field list
382 // omitted it. This keeps the PointCloud2 usable and guarantees transformed
383 // XYZ.
384 for (const char* name : {"x", "y", "z"}) {
385 if (std::none_of(selected.begin(), selected.end(), [name](const auto& field) { return field.name == name; })) {
386 selected.push_back(*findField(first, name));
387 }
388 }
389
390 if (requested_fields.empty() && result.homogeneous_fast_path) {
391 result.fields = selected;
392 result.point_step = first.point_step;
393 } else {
394 for (auto field : selected) {
395 field.offset = result.point_step;
396 result.point_step += static_cast<uint32_t>(fieldDatatypeSize(field.datatype) * field.count);
397 result.fields.push_back(std::move(field));
398 }
399 }
400 for (const auto& field : result.fields) {
401 if (field.name == "x") result.x_offset = field.offset;
402 if (field.name == "y") result.y_offset = field.offset;
403 if (field.name == "z") result.z_offset = field.offset;
404 }
405
406 std::unordered_set<std::string> used_fill_fields;
407 for (const auto index : valid_indices) {
408 const auto& cloud = *clouds[index];
409 auto& input = result.inputs[index];
410 input.whole_point_copy = requested_fields.empty() && result.homogeneous_fast_path;
411 if (input.whole_point_copy) continue;
412 for (const auto& destination : result.fields) {
413 const auto* source = findField(cloud, destination.name);
414 if (source != nullptr && sameType(*source, destination) && validField(*source, cloud.point_step)) {
415 input.copies.push_back({source->offset, destination.offset, fieldDatatypeSize(source->datatype) * source->count});
416 } else if (calibration_field != nullptr && destination.name == calibration_field->name && source != nullptr &&
417 source->count == 1 && validField(*source, cloud.point_step)) {
418 input.conversions.push_back({source->offset, destination.offset, source->datatype, destination.datatype});
419 } else if (const auto fill = fill_values.find(destination.name);
420 fill != fill_values.end() || destination.datatype == sensor_msgs::msg::PointField::FLOAT32 ||
421 destination.datatype == sensor_msgs::msg::PointField::FLOAT64) {
422 const double value = fill != fill_values.end() ? fill->second : std::numeric_limits<double>::quiet_NaN();
423 try {
424 input.field_fills.push_back(makeFieldFill(destination, value, result.is_bigendian));
425 } catch (const std::invalid_argument& error) {
426 result.fill_error = "Cannot fill missing field '" + destination.name + "': " + error.what();
427 return result;
428 }
429 if (fill != fill_values.end()) used_fill_fields.insert(destination.name);
430 if (std::isnan(value)) result.is_dense = false;
431 } else {
432 input.zero_filled_fields.push_back(destination.name);
433 }
434 }
435 }
436 for (const auto& fill : fill_values) {
437 if (used_fill_fields.count(fill.first) == 0U) result.unused_fill_fields.push_back(fill.first);
438 }
439 std::sort(result.unused_fill_fields.begin(), result.unused_fill_fields.end());
440 return result;
441}
442
443} // namespace point_cloud_fusion::detail
bool fieldIsPublished(const std::vector< std::string > &requested_fields, const std::string &name)
bool validXyzField(const sensor_msgs::msg::PointField *field, uint32_t point_step)
Check whether a field is a valid scalar FLOAT32 XYZ component.
MissingFieldFillValues parseMissingFieldFillValues(const std::vector< std::string > &entries)
bool sameType(const sensor_msgs::msg::PointField &lhs, const sensor_msgs::msg::PointField &rhs)
Check whether two fields have the same name and element type.
std::size_t fieldDatatypeSize(uint8_t datatype)
Return the size in bytes of one PointField datatype element.
void fillMissingFields(uint8_t *destination, const InputLayout &input)
std::vector< std::string > processingFields(const std::vector< std::string > &requested_fields, const std::string &time_field_name, bool motion_compensation)
BatchLayout buildBatchLayout(const std::vector< sensor_msgs::msg::PointCloud2::ConstSharedPtr > &clouds, const std::vector< std::string > &requested_fields, const std::string &time_field_name, const MissingFieldFillValues &fill_values={}, const sensor_msgs::msg::PointField *calibration_field=nullptr)
Build a common output layout and per-input copy plan for a cloud batch.
FieldFill makeFieldFill(const sensor_msgs::msg::PointField &field, double value, bool is_bigendian)
bool validField(const sensor_msgs::msg::PointField &field, uint32_t point_step)
Check whether a field descriptor fits within a point record.
std::unordered_map< std::string, double > MissingFieldFillValues
void encodeFillValue(double value, uint8_t *destination)
const sensor_msgs::msg::PointField * findField(const sensor_msgs::msg::PointCloud2 &cloud, const std::string &name)
Find a field descriptor by name in a point cloud.
std::vector< std::string > conflicting_fields
std::vector< std::string > unused_fill_fields
std::vector< sensor_msgs::msg::PointField > fields
std::vector< FieldConversion > conversions
std::vector< std::string > zero_filled_fields
std::vector< int > fields
std::size_t point_step