VLink  2.3.0
A high-performance communication middleware
point_cloud.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file point_cloud.h
26  * @brief Zero-copy, schema-aware 3-D point cloud container with per-field type protocol.
27  *
28  * @details
29  * @c PointCloud carries a contiguous array of fixed-size point records together
30  * with a compact, self-describing schema (the embedded @c Protocol). Schemas
31  * are encoded as two @c uint64_t nibble-packed integers plus a comma-separated
32  * 152-byte name string, so a receiver can introspect every field without
33  * sharing an external IDL. The 40-byte @c Header prefix carries sequencing
34  * and dual-timestamp metadata.
35  *
36  * @par Point format diagram
37  * @code
38  * Per-point layout (tightly packed, no padding):
39  *
40  * XYZ float : [ x: float32 | y: float32 | z: float32 ] (12 B)
41  * XYZI float : [ x | y | z | intensity: float32 ] (16 B)
42  * XYZRGB : [ x | y | z | r: u8 | g: u8 | b: u8 | pad: u8 ] (16 B)
43  * XYZ + features : [ x | y | z | t: u32 | label: u8 | conf: f32 | ... ] (variable)
44  * XYZ double : [ x: float64 | y: float64 | z: float64 ] (24 B)
45  *
46  * Schema is encoded into two uint64_t integers, one nibble per field
47  * (high nibble = first field):
48  *
49  * size_num: 0x0408... (each nibble is the field byte-size)
50  * type_num: 0x0A0B... (each nibble is a PointCloud::Type enum value)
51  * names: "x,y,z,intensity,label" (stored in 152 bytes)
52  * @endcode
53  *
54  * @par Supported field types
55  * | Enum | C++ type | Bytes |
56  * | ------------------ | ----------- | ----- |
57  * | @c kBoolType | @c bool | 1 |
58  * | @c kInt8Type | @c int8_t | 1 |
59  * | @c kUint8Type | @c uint8_t | 1 |
60  * | @c kInt16Type | @c int16_t | 2 |
61  * | @c kUint16Type | @c uint16_t | 2 |
62  * | @c kInt32Type | @c int32_t | 4 |
63  * | @c kUint32Type | @c uint32_t | 4 |
64  * | @c kInt64Type | @c int64_t | 8 |
65  * | @c kUint64Type | @c uint64_t | 8 |
66  * | @c kFloatType | @c float | 4 |
67  * | @c kDoubleType | @c double | 8 |
68  *
69  * @par Protocol nested struct
70  * | Member | Type | Purpose |
71  * | --------------- | -------------- | ---------------------------------------------- |
72  * | @c size_num | @c uint64_t | Per-field byte sizes packed in nibbles |
73  * | @c type_num | @c uint64_t | Per-field @c Type tags packed in nibbles |
74  * | @c names[152] | @c char[] | Comma-separated field names (3..16 fields) |
75  *
76  * @par Wire format
77  * @c PointCloud is POD; @c memcpy of the struct snapshot plus the packed point
78  * buffer forms the wire payload. The @c sizeof value is locked by
79  * @c static_assert and forms a permanent contract: @c vlink::zerocopy::*
80  * containers offer NO forward and NO backward binary compatibility -- every
81  * field, including reserved bytes and the @c Protocol descriptor, is part of
82  * the wire contract.
83  * @code
84  * static_assert(sizeof(PointCloud) == 256, "Sizeof must be 256 bytes.");
85  * @endcode
86  *
87  * @par Memory layout
88  * @code
89  * Offset Size Field
90  * ------ ---- ----------------------------------------------------------------
91  * 0 40 Header header
92  * 40 168 Protocol protocol_ (size_num + type_num + names[152])
93  * 208 8 uint8_t* data_
94  * 216 8 size_t capacity_
95  * 224 8 size_t size_
96  * 232 4 uint32_t reserved_buf_
97  * 236 4 uint32_t reserved_buf2_
98  * 240 2 uint16_t pack_size_
99  * 242 2 uint16_t extent_
100  * 244 1 uint8_t downsample_
101  * 245 1 uint8_t reserved_buf3_
102  * 246 1 bool vertical_
103  * 247 1 bool is_owner_
104  * 248 8 uint64_t index_
105  * ------ ---- ----------------------------------------------------------------
106  * Total 256 bytes (alignas 8)
107  *
108  * Wire envelope:
109  * [ magic_begin (4) | version (4) | PointCloud (256) | point data (size_ * pack_size_) | magic_end (4) ]
110  * @endcode
111  *
112  * @par Reserved bytes
113  * @c reserved_buf_ (offset 232), @c reserved_buf2_ (offset 236) and @c reserved_buf3_
114  * (offset 245) are wire-locked padding bytes. They travel through the wire format
115  * unchanged but MUST NOT be repurposed by application code because future library
116  * revisions may bind them to real fields. The @c uint8_t @c downsample_ at
117  * offset 244 records the voxel-grid downsampling level applied to the payload (see
118  * @c downsample()): @c 0 disables downsampling, @c 255 is the most aggressive.
119  *
120  * @par Optional storage compression
121  * The @c extent and @c vertical create options trade fidelity for footprint along
122  * two independent axes. When @c extent_ > 0 the three leading XYZ
123  * coordinates are linearly quantised with @c Quantize::encode<int16_t>(extent, value)
124  * and restored with @c Quantize::decode<float/double>(extent, stored), halving
125  * (or better) their in-memory footprint; the
126  * embedded schema is rewritten so the XYZ fields advertise @c kInt16Type and
127  * @c get_value_v3f() / @c get_value_v3d() transparently dequantise back to floating
128  * point. The generic @c get_value<int16_t>() returns the raw @c int16_t storage,
129  * whereas @c get_value<float>() / @c get_value<double>() also dequantise (matching
130  * @c v3f / @c v3d). Points whose XYZ fall outside @c (-extent, +extent) cannot be represented and are
131  * discarded on insert rather than saturated. When @c vertical_ is @c true the serialised wire
132  * payload is emitted in structure-of-arrays order (@c xx..x @c yy..y @c zz..z, one field column after
133  * another) which packs better under a downstream entropy coder; the in-memory
134  * buffer stays interleaved (row-major) and @c operator<< restores that layout, so
135  * the field accessors are unaffected.
136  *
137  * @par Optional voxel-grid downsampling
138  * @c downsample() collapses spatially-close points by mapping each point's quantised
139  * XYZ onto a voxel grid and keeping the first point seen in each voxel, compacting the
140  * survivors to the front of the buffer and shrinking @c size(). It applies only to
141  * quantised clouds (@c extent_ > 0) and records the requested level into the
142  * @c downsample_ marker, which @c get_downsample() reports. The marker is
143  * producer-set, not an automatically maintained invariant: freshly created clouds
144  * record @c 0, and @c clear() resets it to @c 0; it is NOT recomputed when points are
145  * subsequently added or modified.
146  *
147  * @par Example -- typical fill and publish
148  * @code
149  * vlink::zerocopy::PointCloud pc;
150  * pc.create_v3f<float>(1000, {"intensity"}); // schema: x, y, z, intensity (all f32)
151  *
152  * pc.push_value_v3f(1.0F, 2.0F, 3.0F, 0.8F);
153  * pc.push_value_v3f(4.0F, 5.0F, 6.0F, 0.5F);
154  *
155  * auto key_map = pc.get_key_map();
156  * float intensity = pc.get_value<float>(0, key_map, "intensity");
157  *
158  * vlink::Bytes wire;
159  * pc >> wire;
160  *
161  * vlink::zerocopy::PointCloud rx;
162  * rx << wire;
163  * @endcode
164  */
165 
166 #pragma once
167 
168 #include <cstdint>
169 #include <iostream>
170 #include <limits>
171 #include <string>
172 #include <string_view>
173 #include <type_traits>
174 #include <unordered_map>
175 #include <vector>
176 
177 #include "../base/bytes.h"
178 #include "../base/quantize.h"
179 #include "./header.h"
180 
181 namespace vlink {
182 
183 namespace zerocopy {
184 
185 /**
186  * @struct PointCloud
187  * @brief 256-byte POD container holding a schema-described array of N-field point records.
188  *
189  * @details
190  * The struct size is locked at 256 bytes on 64-bit targets via
191  * @c static_assert. Points are stored in tightly packed row-major order; one
192  * row equals @c pack_size() bytes. Schemas are inspected by calling
193  * @c get_key_map() / @c get_key_list() and field values read through the
194  * @c get_value family of templates.
195  */
196 struct VLINK_EXPORT_AND_ALIGNED(8) PointCloud final {
197  /**
198  * @brief Fundamental field type tag used by the embedded @c Protocol.
199  */
200  enum Type : uint8_t {
201  kUnknownType = 0, ///< Uninitialised / unsupported type.
202  kBoolType = 1, ///< @c bool (1 byte).
203  kInt8Type = 2, ///< @c int8_t (1 byte).
204  kUint8Type = 3, ///< @c uint8_t (1 byte).
205  kInt16Type = 4, ///< @c int16_t (2 bytes).
206  kUint16Type = 5, ///< @c uint16_t (2 bytes).
207  kInt32Type = 6, ///< @c int32_t (4 bytes).
208  kUint32Type = 7, ///< @c uint32_t (4 bytes).
209  kInt64Type = 8, ///< @c int64_t (8 bytes).
210  kUint64Type = 9, ///< @c uint64_t (8 bytes).
211  kFloatType = 10, ///< @c float (4 bytes).
212  kDoubleType = 11, ///< @c double (8 bytes).
213  };
214 
215  /**
216  * @struct Key
217  * @brief Descriptor for one named field within a packed point record.
218  */
219  struct Key final {
220  std::string name; ///< Field name (e.g. @c "x", @c "intensity").
221  uint8_t type{kUnknownType}; ///< @c Type tag for the field.
222  uint8_t size{0}; ///< Field byte size derived from @c type.
223  };
224 
225  /**
226  * @brief Maps a field name to its byte offset inside one packed point record.
227  */
228  using KeyMap = std::unordered_map<std::string, uint16_t>;
229 
230  /**
231  * @brief Ordered list of field descriptors for one packed point record.
232  */
233  using KeyList = std::vector<Key>;
234 
235  /**
236  * @struct Vector3f
237  * @brief Compact single-precision XYZ vector (12 bytes, 4-byte aligned).
238  */
239  struct VLINK_EXPORT_AND_ALIGNED(4) Vector3f final {
240  float x{0}; ///< X component.
241  float y{0}; ///< Y component.
242  float z{0}; ///< Z component.
243 
244  /**
245  * @brief Default-constructs a zeroed vector and asserts the 12-byte contract.
246  */
247  Vector3f() noexcept;
248 
249  /**
250  * @brief Value constructor.
251  *
252  * @param _x X component.
253  * @param _y Y component.
254  * @param _z Z component.
255  */
256  explicit Vector3f(float _x, float _y, float _z) noexcept;
257 
258  /**
259  * @brief Formats the vector as @c "(x, y, z)" on @p ostream.
260  *
261  * @param ostream Output stream.
262  * @param v3f Vector to format.
263  * @return Reference to @p ostream.
264  */
265  friend std::ostream& operator<<(std::ostream& ostream, const Vector3f& v3f) noexcept;
266  };
267 
268  /**
269  * @struct Vector3d
270  * @brief Compact double-precision XYZ vector (24 bytes, 8-byte aligned).
271  */
272  struct VLINK_EXPORT_AND_ALIGNED(8) Vector3d final {
273  double x{0}; ///< X component.
274  double y{0}; ///< Y component.
275  double z{0}; ///< Z component.
276 
277  /**
278  * @brief Default-constructs a zeroed vector and asserts the 24-byte contract.
279  */
280  Vector3d() noexcept;
281 
282  /**
283  * @brief Value constructor.
284  *
285  * @param _x X component.
286  * @param _y Y component.
287  * @param _z Z component.
288  */
289  explicit Vector3d(double _x, double _y, double _z) noexcept;
290 
291  /**
292  * @brief Formats the vector as @c "(x, y, z)" on @p ostream.
293  *
294  * @param ostream Output stream.
295  * @param v3d Vector to format.
296  * @return Reference to @p ostream.
297  */
298  friend std::ostream& operator<<(std::ostream& ostream, const Vector3d& v3d) noexcept;
299  };
300 
301  /**
302  * @brief Default-constructs an empty cloud and asserts the 256-byte contract.
303  */
304  PointCloud() noexcept;
305 
306  /**
307  * @brief Frees the owned point buffer when @c is_owner() is @c true.
308  */
309  ~PointCloud() noexcept;
310 
311  /**
312  * @brief Deep-copies @p target into a freshly allocated cloud.
313  *
314  * @param target Source cloud to clone.
315  */
316  PointCloud(const PointCloud& target) noexcept;
317 
318  /**
319  * @brief Steals @p target's allocation and metadata; @p target ends empty.
320  *
321  * @param target Source cloud moved from.
322  */
323  PointCloud(PointCloud&& target) noexcept;
324 
325  /**
326  * @brief Deep-copy-assigns @p target; self-assignment is a no-op.
327  *
328  * @param target Source cloud to clone.
329  * @return Reference to @c *this.
330  */
331  PointCloud& operator=(const PointCloud& target) noexcept;
332 
333  /**
334  * @brief Move-assigns @p target; self-assignment is a no-op.
335  *
336  * @param target Source cloud moved from.
337  * @return Reference to @c *this.
338  */
339  PointCloud& operator=(PointCloud&& target) noexcept;
340 
341  /**
342  * @brief Deserialises a @c PointCloud from @p bytes with zero-copy borrowing semantics.
343  *
344  * @param bytes Wire buffer produced by @c operator>>.
345  * @return @c true on success; @c false on magic mismatch or size mismatch.
346  */
347  bool operator<<(const Bytes& bytes) noexcept;
348 
349  /**
350  * @brief Serialises the struct snapshot plus point bytes into @p bytes.
351  *
352  * @param bytes Output buffer; resized automatically when its size differs from the serialized size.
353  * @return @c true on success; @c false when output allocation fails or vertical
354  * serialization would overwrite or release the source payload. Unsafe
355  * output reuse is rejected before modifying @p bytes.
356  */
357  bool operator>>(Bytes& bytes) const noexcept;
358 
359  /**
360  * @brief Validates that @p bytes carries a well-formed @c PointCloud envelope.
361  *
362  * @param bytes Wire buffer to inspect.
363  * @return @c true when both magic sentinels match and the minimum size holds.
364  */
365  [[nodiscard]] static bool check_valid(const Bytes& bytes) noexcept;
366 
367  /**
368  * @brief Whether the data pointer is non-null and both @c size() and @c pack_size() are positive.
369  *
370  * @return @c true when the cloud holds usable points.
371  */
372  [[nodiscard]] bool is_valid() const noexcept;
373 
374  /**
375  * @brief Borrows @p target's point buffer and protocol without copying.
376  *
377  * @param target Source cloud whose buffer must outlive @c *this.
378  * @return @c false on self-borrow or owned-buffer aliasing, otherwise @c true.
379  */
380  bool shallow_copy(const PointCloud& target) noexcept;
381 
382  /**
383  * @brief Allocates (or reuses) an owned buffer and copies @p target's protocol and point bytes.
384  *
385  * @param target Source cloud to clone.
386  * @return @c false on self-copy, owned-buffer aliasing, size overflow, or allocation failure.
387  */
388  bool deep_copy(const PointCloud& target) noexcept;
389 
390  /**
391  * @brief Transfers ownership from @p target; @p target ends empty.
392  *
393  * @param target Source cloud moved from.
394  * @return @c false on self-move, otherwise @c true.
395  */
396  bool move_copy(PointCloud& target) noexcept;
397 
398  /**
399  * @brief Total bytes that @c operator>> would write for this cloud.
400  *
401  * @return @c sizeof(magic_begin) + @c sizeof(version) + @c sizeof(PointCloud) + @c size() * @c pack_size() + @c
402  * sizeof(magic_end).
403  */
404  [[nodiscard]] size_t get_serialized_size() const noexcept;
405 
406  /**
407  * @brief Builds a @c KeyMap (and optional @c KeyList) from the embedded protocol descriptor.
408  *
409  * @param key_list Optional output; filled with ordered field descriptors when non-null.
410  * @return Map from field name to byte offset within one packed point.
411  */
412  [[nodiscard]] KeyMap get_key_map(KeyList* key_list = nullptr) const noexcept;
413 
414  /**
415  * @brief Returns the ordered field descriptors from the embedded protocol.
416  *
417  * @return Field descriptors in packed byte order.
418  */
419  [[nodiscard]] KeyList get_key_list() const noexcept;
420 
421  /**
422  * @brief Number of points currently stored.
423  *
424  * @return Point count, or 0 when empty.
425  */
426  [[nodiscard]] size_t size() const noexcept;
427 
428  /**
429  * @brief Byte size of one packed point record (sum of field byte sizes).
430  *
431  * @return Stride in bytes, or 0 when no schema has been set.
432  */
433  [[nodiscard]] size_t pack_size() const noexcept;
434 
435  /**
436  * @brief Whether this cloud owns its point buffer.
437  *
438  * @return @c true when the destructor would free the buffer.
439  */
440  [[nodiscard]] bool is_owner() const noexcept;
441 
442  /**
443  * @brief Quantisation extent currently configured for XYZ (maximum absolute coordinate).
444  *
445  * @return Extent value; @c 0 when quantisation is disabled.
446  */
447  [[nodiscard]] uint16_t get_extent() const noexcept;
448 
449  /**
450  * @brief Whether serialisation emits the payload in vertical (structure-of-arrays) column order.
451  *
452  * @return @c true when vertical layout is enabled.
453  */
454  [[nodiscard]] bool get_vertical() const noexcept;
455 
456  /**
457  * @brief Sets whether serialisation emits the payload in vertical (structure-of-arrays) column order.
458  *
459  * @details
460  * This toggles only the wire payload layout used by @c operator>>. The owned or borrowed
461  * in-memory point buffer remains in row-major order, and the schema, extent, downsample marker,
462  * logical size, and point data are left unchanged.
463  *
464  * @param vertical @c true to serialise field columns contiguously; @c false for row-major payloads.
465  */
466  void set_vertical(bool vertical) noexcept;
467 
468  /**
469  * @brief Voxel-grid downsampling level recorded for this cloud (producer-set marker; see @c downsample()).
470  *
471  * @return Level value in @c [0, 255]; @c 0 when downsampling is disabled.
472  */
473  [[nodiscard]] uint8_t get_downsample() const noexcept;
474 
475  /**
476  * @brief Voxel-grid downsamples a quantised owned cloud in place.
477  *
478  * @details
479  * Keeps the first point per occupied voxel, compacts survivors to the front, and shrinks @c size().
480  * @p level controls voxel size in @c [0,255]; @c 0 is a no-op that clears the marker. Successful
481  * positive calls record @p level in @c downsample_, while rejected positive calls leave the marker
482  * unchanged. Only clouds created with @c extent > 0 and owned storage can be downsampled.
483  *
484  * @param level Downsampling aggressiveness in @c [0,255]; @c 0 disables downsampling.
485  * @return @c true on success or level-@c 0 no-op; @c false when downsampling is not applicable.
486  */
487  bool downsample(uint8_t level) noexcept;
488 
489  /**
490  * @brief Raw @c Protocol::size_num integer (nibbles = per-field byte sizes).
491  *
492  * @return Stored value.
493  */
494  [[nodiscard]] uint64_t get_protocol_size_num() const noexcept;
495 
496  /**
497  * @brief Raw @c Protocol::type_num integer (nibbles = per-field @c Type tags).
498  *
499  * @return Stored value.
500  */
501  [[nodiscard]] uint64_t get_protocol_type_num() const noexcept;
502 
503  /**
504  * @brief Comma-separated field sizes for diagnostic output (e.g. @c "4,4,4,1").
505  *
506  * @return Printable size string.
507  */
508  [[nodiscard]] std::string get_protocol_size_str() const noexcept;
509 
510  /**
511  * @brief Raw comma-separated field name string (e.g. @c "x,y,z,intensity").
512  *
513  * @return Copy of the embedded name string. Keep the encoded string below
514  * 152 bytes if string-returning helpers must round-trip.
515  */
516  [[nodiscard]] std::string get_protocol_name_str() const noexcept;
517 
518  /**
519  * @brief Comma-separated field types for diagnostic output (e.g. @c "float,float,float,uint8").
520  *
521  * @return Printable type string.
522  */
523  [[nodiscard]] std::string get_protocol_type_str() const noexcept;
524 
525  /**
526  * @brief Read-only pointer to the packed point buffer (one row per point).
527  *
528  * @return Pointer to the first point.
529  */
530  [[nodiscard]] const uint8_t* get_internal_data() const noexcept;
531 
532  /**
533  * @brief Pre-allocated point capacity (@c capacity_ / @c pack_size_).
534  *
535  * @return Reserved point count; 0 for borrowed / deserialised buffers.
536  */
537  [[nodiscard]] size_t get_reserved_size() const noexcept;
538 
539  /**
540  * @brief Reads the first three @c float fields of point @p loop_index as XYZ.
541  *
542  * @param x Output X value.
543  * @param y Output Y value.
544  * @param z Output Z value.
545  * @param loop_index Zero-based point index.
546  * @return @c false on out-of-range.
547  */
548  bool get_value_v3f(float& x, float& y, float& z, size_t loop_index) const noexcept;
549 
550  /**
551  * @brief Reads the first three @c float fields of point @p loop_index into a @c Vector3f.
552  *
553  * @param v3f Output vector.
554  * @param loop_index Zero-based point index.
555  * @return @c false on out-of-range.
556  */
557  bool get_value_v3f(Vector3f& v3f, size_t loop_index) const noexcept;
558 
559  /**
560  * @brief Returns the first three @c float fields of point @p loop_index as a @c Vector3f.
561  *
562  * @param loop_index Zero-based point index.
563  * @return Vector; zero-initialised on out-of-range.
564  */
565  [[nodiscard]] Vector3f get_value_v3f(size_t loop_index) const noexcept;
566 
567  /**
568  * @brief Reads the first three @c double fields of point @p loop_index as XYZ.
569  *
570  * @param x Output X value.
571  * @param y Output Y value.
572  * @param z Output Z value.
573  * @param loop_index Zero-based point index.
574  * @return @c false on out-of-range.
575  */
576  bool get_value_v3d(double& x, double& y, double& z, size_t loop_index) const noexcept;
577 
578  /**
579  * @brief Reads the first three @c double fields of point @p loop_index into a @c Vector3d.
580  *
581  * @param v3d Output vector.
582  * @param loop_index Zero-based point index.
583  * @return @c false on out-of-range.
584  */
585  bool get_value_v3d(Vector3d& v3d, size_t loop_index) const noexcept;
586 
587  /**
588  * @brief Returns the first three @c double fields of point @p loop_index as a @c Vector3d.
589  *
590  * @param loop_index Zero-based point index.
591  * @return Vector; zero-initialised on out-of-range.
592  */
593  [[nodiscard]] Vector3d get_value_v3d(size_t loop_index) const noexcept;
594 
595  /**
596  * @brief Reads a field at byte @p offset within point @p loop_index into @p t.
597  *
598  * @tparam T Field type; must be fundamental.
599  * @param t Output value.
600  * @param loop_index Zero-based point index.
601  * @param offset Byte offset within one packed record.
602  * @return @c false (and zeroes @p t) on out-of-bounds access.
603  */
604  template <typename T>
605  bool get_value(T& t, size_t loop_index, uint16_t offset) const noexcept;
606 
607  /**
608  * @brief Returns a field at byte @p offset within point @p loop_index by value.
609  *
610  * @tparam T Field type; must be fundamental.
611  * @param loop_index Zero-based point index.
612  * @param offset Byte offset within one packed record.
613  * @return Field value; zero-initialised on out-of-bounds access.
614  */
615  template <typename T>
616  [[nodiscard]] T get_value(size_t loop_index, uint16_t offset) const noexcept;
617 
618  /**
619  * @brief Reads a named field from point @p loop_index using a cached @c KeyMap.
620  *
621  * @tparam T Field type; must be fundamental.
622  * @param t Output value.
623  * @param loop_index Zero-based point index.
624  * @param key_map Map obtained from @c get_key_map().
625  * @param key Full field name to look up.
626  * @return @c false (and zeroes @p t) on unknown key or out-of-bounds access.
627  */
628  template <typename T>
629  bool get_value(T& t, size_t loop_index, KeyMap& key_map, std::string_view key) const noexcept;
630 
631  /**
632  * @brief Returns a named field from point @p loop_index using a cached @c KeyMap.
633  *
634  * @tparam T Field type; must be fundamental.
635  * @param loop_index Zero-based point index.
636  * @param key_map Map obtained from @c get_key_map().
637  * @param key Full field name.
638  * @return Field value; zero-initialised on unknown key or out-of-bounds access.
639  */
640  template <typename T>
641  [[nodiscard]] T get_value(size_t loop_index, KeyMap& key_map, std::string_view key) const noexcept;
642 
643  /**
644  * @brief Returns a field value cast to @c double, dispatched on the runtime @c Type tag.
645  *
646  * @param loop_index Zero-based point index.
647  * @param offset Byte offset within one packed record.
648  * @param type @c Type tag for this field.
649  * @return Field value as @c double, or 0 on unknown type.
650  */
651  [[nodiscard]] double get_value_for_double_float(size_t loop_index, uint16_t offset, uint8_t type) const noexcept;
652 
653  /**
654  * @brief Returns a named field value cast to @c double using a cached @c KeyMap.
655  *
656  * @param loop_index Zero-based point index.
657  * @param key_map Map obtained from @c get_key_map().
658  * @param key Full field name.
659  * @param type @c Type tag for this field.
660  * @return Field value as @c double, or 0 on unknown key / type.
661  */
662  [[nodiscard]] double get_value_for_double_float(size_t loop_index, KeyMap& key_map, std::string_view key,
663  uint8_t type) const noexcept;
664 
665  /**
666  * @brief Returns a field value formatted as a printable string.
667  *
668  * @param loop_index Zero-based point index.
669  * @param offset Byte offset within one packed record.
670  * @param type @c Type tag.
671  * @return Stringified value, or empty on unknown type.
672  */
673  [[nodiscard]] std::string get_value_for_print(size_t loop_index, uint16_t offset, uint8_t type) const noexcept;
674 
675  /**
676  * @brief Returns a named field value formatted as a printable string.
677  *
678  * @param loop_index Zero-based point index.
679  * @param key_map Map obtained from @c get_key_map().
680  * @param key Full field name.
681  * @param type @c Type tag.
682  * @return Stringified value; empty for unknown @p type.
683  */
684  [[nodiscard]] std::string get_value_for_print(size_t loop_index, KeyMap& key_map, std::string_view key,
685  uint8_t type) const noexcept;
686 
687  /**
688  * @brief Creates a cloud from pre-built protocol integers and a name string.
689  *
690  * @details
691  * Low-level entry point used when @p size_num and @p type_num are already
692  * known (e.g. reconstructed from a wire buffer). Prefer the type-safe
693  * @c create<T...>() template for new producers.
694  *
695  * @param size Maximum number of points to pre-allocate.
696  * @param size_num Protocol size encoding.
697  * @param type_num Protocol type encoding.
698  * @param key_str Comma-separated field names (3..16 fields, up to 152 bytes).
699  * @param extent Optional XYZ quantisation extent; @c 0 disables quantisation.
700  * @param vertical When @c true the serialised payload uses structure-of-arrays column order.
701  * @return @c false on protocol validation failure, size overflow, or allocation failure (including XYZ that is not
702  * @c float / @c double / @c int16_t when @p extent is non-zero).
703  */
704  bool create(size_t size, uint64_t size_num, uint64_t type_num, std::string_view key_str, uint16_t extent = 0,
705  bool vertical = false) noexcept;
706 
707  /**
708  * @brief Creates a cloud with a type-safe variadic field schema.
709  *
710  * @tparam T Fixed-width field types supported by @c PointCloud::Type. 3..16 types required.
711  * @param _size Maximum number of points.
712  * @param keys Field names in the same order as @c T... .
713  * @param extent Optional XYZ quantisation extent; @c 0 disables quantisation.
714  * @param vertical When @c true the serialised payload uses structure-of-arrays column order.
715  * @return @c false when key count is wrong, schema packing fails, size overflows, or allocation fails.
716  */
717  template <typename... T>
718  bool create(size_t _size, const std::vector<std::string>& keys = {}, uint16_t extent = 0,
719  bool vertical = false) noexcept;
720 
721  /**
722  * @brief Creates a cloud with @c float XYZ followed by additional variadic fields.
723  *
724  * @tparam T Types for additional fields beyond XYZ.
725  * @param _size Maximum number of points.
726  * @param keys Names for the additional fields (excluding x, y, z).
727  * @param extent Optional XYZ quantisation extent; @c 0 disables quantisation.
728  * @param vertical When @c true the serialised payload uses structure-of-arrays column order.
729  * @return @c false on schema packing failure, size overflow, or allocation failure.
730  */
731  template <typename... T>
732  bool create_v3f(size_t _size, const std::vector<std::string>& keys = {}, uint16_t extent = 0,
733  bool vertical = false) noexcept;
734 
735  /**
736  * @brief Creates a cloud with @c double XYZ followed by additional variadic fields.
737  *
738  * @tparam T Types for additional fields beyond XYZ.
739  * @param _size Maximum number of points.
740  * @param keys Names for the additional fields (excluding x, y, z).
741  * @param extent Optional XYZ quantisation extent; @c 0 disables quantisation.
742  * @param vertical When @c true the serialised payload uses structure-of-arrays column order.
743  * @return @c false on schema packing failure, size overflow, or allocation failure.
744  */
745  template <typename... T>
746  bool create_v3d(size_t _size, const std::vector<std::string>& keys = {}, uint16_t extent = 0,
747  bool vertical = false) noexcept;
748 
749  /**
750  * @brief Bulk-fills the cloud from a pre-packed external buffer.
751  *
752  * @param src_data Source buffer in packed row order; must be non-null.
753  * @param _size Number of points to copy; must be non-zero.
754  * @return @c false on invalid arguments or capacity overflow.
755  */
756  bool fill_packed_data(const uint8_t* src_data, size_t _size) noexcept;
757 
758  /**
759  * @brief Appends one point with the given field values (must match schema).
760  *
761  * @tparam T Field value types; must all be fundamental. 3..16 required.
762  * @param args Field values in schema order.
763  * @return @c false on capacity exhaustion or pack-size mismatch.
764  */
765  template <typename... T>
766  bool push_value(T... args) noexcept;
767 
768  /**
769  * @brief Appends one point with @c float XYZ followed by additional fields.
770  *
771  * @tparam T Types for additional fields beyond XYZ.
772  * @param x X coordinate.
773  * @param y Y coordinate.
774  * @param z Z coordinate.
775  * @param args Additional field values.
776  * @return @c false on capacity exhaustion, pack-size mismatch, or any XYZ coordinate outside
777  * @c (-extent, +extent) on a quantised cloud (the out-of-range point is discarded).
778  */
779  template <typename... T>
780  bool push_value_v3f(float x, float y, float z, T... args) noexcept;
781 
782  /**
783  * @brief Appends one point from a @c Vector3f plus additional fields.
784  *
785  * @tparam T Types for additional fields beyond XYZ.
786  * @param v3f XYZ coordinates.
787  * @param args Additional field values.
788  * @return @c false on capacity exhaustion, pack-size mismatch, or any XYZ coordinate outside
789  * @c (-extent, +extent) on a quantised cloud (the out-of-range point is discarded).
790  */
791  template <typename... T>
792  bool push_value_v3f(Vector3f v3f, T... args) noexcept;
793 
794  /**
795  * @brief Appends one point with @c double XYZ followed by additional fields.
796  *
797  * @tparam T Types for additional fields beyond XYZ.
798  * @param x X coordinate.
799  * @param y Y coordinate.
800  * @param z Z coordinate.
801  * @param args Additional field values.
802  * @return @c false on capacity exhaustion, pack-size mismatch, or any XYZ coordinate outside
803  * @c (-extent, +extent) on a quantised cloud (the out-of-range point is discarded).
804  */
805  template <typename... T>
806  bool push_value_v3d(double x, double y, double z, T... args) noexcept;
807 
808  /**
809  * @brief Appends one point from a @c Vector3d plus additional fields.
810  *
811  * @tparam T Types for additional fields beyond XYZ.
812  * @param v3d XYZ coordinates.
813  * @param args Additional field values.
814  * @return @c false on capacity exhaustion, pack-size mismatch, or any XYZ coordinate outside
815  * @c (-extent, +extent) on a quantised cloud (the out-of-range point is discarded).
816  */
817  template <typename... T>
818  bool push_value_v3d(Vector3d v3d, T... args) noexcept;
819 
820  /**
821  * @brief Sets the logical point count without reallocating.
822  *
823  * @details
824  * Updates the internal write cursor to @c size * @c pack_size_. Required
825  * before random overwrites via @c set_value().
826  *
827  * @param size New logical point count; must not exceed allocated capacity.
828  * @return @c false on capacity overflow or invalid state.
829  */
830  bool resize(size_t size) noexcept;
831 
832  /**
833  * @brief Overwrites the record at @p loop_index with new field values.
834  *
835  * @details
836  * Requires the logical size and internal write cursor to be consistent;
837  * call @c resize() (or finish a full @c push_value() sequence) first.
838  *
839  * @tparam T Field value types; must all be fundamental. 3..16 required.
840  * @param loop_index Zero-based point index to overwrite.
841  * @param args Field values in schema order.
842  * @return @c false on out-of-range, cursor inconsistency, or pack-size mismatch.
843  */
844  template <typename... T>
845  bool set_value(size_t loop_index, T... args) noexcept;
846 
847  /**
848  * @brief Overwrites point @p loop_index with @c float XYZ plus additional fields.
849  *
850  * @tparam T Types for additional fields beyond XYZ.
851  * @param loop_index Zero-based point index.
852  * @param x X coordinate.
853  * @param y Y coordinate.
854  * @param z Z coordinate.
855  * @param args Additional field values.
856  * @return @c false on failure, or when any XYZ coordinate is outside @c (-extent, +extent) on a
857  * quantised cloud (the out-of-range point is discarded).
858  */
859  template <typename... T>
860  bool set_value_v3f(size_t loop_index, float x, float y, float z, T... args) noexcept;
861 
862  /**
863  * @brief Overwrites point @p loop_index from a @c Vector3f plus additional fields.
864  *
865  * @tparam T Types for additional fields beyond XYZ.
866  * @param loop_index Zero-based point index.
867  * @param v3f XYZ coordinates.
868  * @param args Additional field values.
869  * @return @c false on failure, or when any XYZ coordinate is outside @c (-extent, +extent) on a
870  * quantised cloud (the out-of-range point is discarded).
871  */
872  template <typename... T>
873  bool set_value_v3f(size_t loop_index, Vector3f v3f, T... args) noexcept;
874 
875  /**
876  * @brief Overwrites point @p loop_index with @c double XYZ plus additional fields.
877  *
878  * @tparam T Types for additional fields beyond XYZ.
879  * @param loop_index Zero-based point index.
880  * @param x X coordinate.
881  * @param y Y coordinate.
882  * @param z Z coordinate.
883  * @param args Additional field values.
884  * @return @c false on failure, or when any XYZ coordinate is outside @c (-extent, +extent) on a
885  * quantised cloud (the out-of-range point is discarded).
886  */
887  template <typename... T>
888  bool set_value_v3d(size_t loop_index, double x, double y, double z, T... args) noexcept;
889 
890  /**
891  * @brief Overwrites point @p loop_index from a @c Vector3d plus additional fields.
892  *
893  * @tparam T Types for additional fields beyond XYZ.
894  * @param loop_index Zero-based point index.
895  * @param v3d XYZ coordinates.
896  * @param args Additional field values.
897  * @return @c false on failure, or when any XYZ coordinate is outside @c (-extent, +extent) on a
898  * quantised cloud (the out-of-range point is discarded).
899  */
900  template <typename... T>
901  bool set_value_v3d(size_t loop_index, Vector3d v3d, T... args) noexcept;
902 
903  /**
904  * @brief Resets the logical count, optionally releasing every resource.
905  *
906  * @details
907  * With @p force == @c false (default) only the write cursor and logical
908  * count are zeroed so the buffer can be refilled in place. With
909  * @p force == @c true the owned buffer is freed and every protocol /
910  * header field is cleared.
911  *
912  * @param force When @c true, free the buffer and reset all state.
913  */
914  void clear(bool force = false) noexcept;
915 
916  /**
917  * @brief Mutable reference to the first wire-locked reserved field (@c uint32_t at offset 232).
918  *
919  * @details
920  * Lets application code stash a small flag or minor sub-type id that travels through the
921  * wire format unchanged. It is part of the binary contract and MUST NOT be repurposed once
922  * a future library revision binds it to a real field.
923  *
924  * @return Reference to @c reserved_buf_.
925  */
926  uint32_t& get_reserved() noexcept { return reserved_buf_; }
927 
928  /**
929  * @brief Mutable reference to the second wire-locked reserved field (@c uint32_t at offset 236).
930  *
931  * @details
932  * Lets application code stash a small flag or minor sub-type id that travels through the
933  * wire format unchanged. It is part of the binary contract and MUST NOT be repurposed once
934  * a future library revision binds it to a real field.
935  *
936  * @return Reference to @c reserved_buf2_.
937  */
938  uint32_t& get_reserved2() noexcept { return reserved_buf2_; }
939 
940  /**
941  * @brief Mutable reference to the third wire-locked reserved field (@c uint8_t at offset 245).
942  *
943  * @details
944  * Lets application code stash a small flag or minor sub-type id that travels through the
945  * wire format unchanged. It is part of the binary contract and MUST NOT be repurposed once
946  * a future library revision binds it to a real field.
947  *
948  * @return Reference to @c reserved_buf3_.
949  */
950  uint8_t& get_reserved3() noexcept { return reserved_buf3_; }
951 
952  Header header; ///< Sequencing and timestamp metadata prefix.
953 
954  static constexpr bool kZerocopyTypes{true}; ///< Marker probed by the VLink type-trait machinery.
955 
956  private:
957  struct VLINK_EXPORT_AND_ALIGNED(8) Protocol final {
958  uint64_t size_num{0};
959  uint64_t type_num{0};
960  char names[152]{0};
961 
962  Protocol() noexcept = default;
963 
964  template <typename... T>
965  static uint64_t get_size_num() noexcept;
966 
967  template <typename... T>
968  static uint64_t get_type_num() noexcept;
969 
970  template <typename T>
971  static constexpr uint8_t get_type() noexcept;
972 
973  constexpr uint64_t get_pack_size() const noexcept;
974 
975  static bool check_valid(uint64_t _size_num, std::string_view _names) noexcept;
976 
977  static std::string get_names(const std::vector<std::string>& keys) noexcept;
978 
979  KeyList get_key_list() const noexcept;
980 
981  std::string get_size_for_print() const noexcept;
982 
983  std::string get_type_for_print() const noexcept;
984  };
985 
986  template <typename T>
987  static bool xyz_in_extent(T x, T y, T z, uint16_t extent) noexcept;
988 
989  bool compress_protocol_xyz() noexcept;
990 
991  Protocol protocol_;
992  uint8_t* data_{nullptr};
993  size_t capacity_{0};
994  size_t size_{0};
995  uint32_t reserved_buf_{0};
996  uint32_t reserved_buf2_{0};
997  uint16_t pack_size_{0};
998  uint16_t extent_{0};
999  uint8_t downsample_{0};
1000  uint8_t reserved_buf3_{0};
1001  bool vertical_{false};
1002  bool is_owner_{false};
1003  uint64_t index_{0};
1004 
1005  static constexpr uint32_t kMagicNumberBegin{0x98B7F16A};
1006  static constexpr uint32_t kMagicNumberEnd{0x98B7F16F};
1007 };
1008 
1009 ////////////////////////////////////////////////////////////////
1010 /// Details
1011 ////////////////////////////////////////////////////////////////
1012 
1013 template <typename T>
1014 inline bool PointCloud::get_value(T& t, size_t loop_index, uint16_t offset) const noexcept {
1015  static_assert(std::is_fundamental_v<T>, "T must be fundamental.");
1016 
1017  if VUNLIKELY (!data_ || loop_index >= size_ || offset > pack_size_) {
1018  std::memset(&t, 0, sizeof(T));
1019  return false;
1020  }
1021 
1022  if (extent_ != 0 && offset < sizeof(int16_t) * 3) {
1023  if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double>) {
1024  int16_t value = 0;
1025 
1026  if VUNLIKELY (sizeof(value) > static_cast<size_t>(pack_size_ - offset)) {
1027  t = 0;
1028  return false;
1029  }
1030 
1031  const size_t p = (loop_index * pack_size_) + offset;
1032  std::memcpy(&value, data_ + p, sizeof(value));
1033  t = Quantize::decode<T>(extent_, value);
1034 
1035  return true;
1036  }
1037  }
1038 
1039  if VUNLIKELY (sizeof(T) > static_cast<size_t>(pack_size_ - offset)) {
1040  std::memset(&t, 0, sizeof(T));
1041  return false;
1042  }
1043 
1044  const size_t p = (loop_index * pack_size_) + offset;
1045  std::memcpy(&t, data_ + p, sizeof(T));
1046 
1047  return true;
1048 }
1049 
1050 template <typename T>
1051 inline T PointCloud::get_value(size_t loop_index, uint16_t offset) const noexcept {
1052  static_assert(std::is_fundamental_v<T>, "T must be fundamental.");
1053 
1054  T t;
1055 
1056  get_value(t, loop_index, offset);
1057 
1058  return t;
1059 }
1060 
1061 template <typename T>
1062 inline bool PointCloud::get_value(T& t, size_t loop_index, KeyMap& key_map, std::string_view key) const noexcept {
1063  static_assert(std::is_fundamental_v<T>, "T must be fundamental.");
1064 
1065  const std::string lookup(key);
1066  auto iter = key_map.find(lookup);
1067 
1068  if VUNLIKELY (iter == key_map.end()) {
1069  std::memset(&t, 0, sizeof(T));
1070  return false;
1071  }
1072 
1073  return get_value<T>(t, loop_index, iter->second);
1074 }
1075 
1076 template <typename T>
1077 inline T PointCloud::get_value(size_t loop_index, KeyMap& key_map, std::string_view key) const noexcept {
1078  static_assert(std::is_fundamental_v<T>, "T must be fundamental.");
1079 
1080  T t;
1081 
1082  get_value(t, loop_index, key_map, key);
1083 
1084  return t;
1085 }
1086 
1087 template <typename... T>
1088 inline bool PointCloud::create(size_t size, const std::vector<std::string>& keys, uint16_t extent,
1089  bool vertical) noexcept {
1090  static_assert((std::is_fundamental_v<T> && ...), "All types must be fundamental.");
1091 
1092  static_assert(sizeof...(T) >= 3 && sizeof...(T) <= 16, "The number of keys ranges is [3 ~ 16].");
1093 
1094  static_assert(((Protocol::get_type<T>() != kUnknownType) && ...),
1095  "All field types must map to a supported PointCloud::Type.");
1096 
1097  if VUNLIKELY (sizeof...(T) != keys.size()) {
1098  return false;
1099  }
1100 
1101  uint64_t size_num = Protocol::get_size_num<T...>();
1102 
1103  if VUNLIKELY (size_num == 0) {
1104  return false;
1105  }
1106 
1107  std::string key_str = Protocol::get_names(keys);
1108 
1109  if VUNLIKELY (key_str.empty()) {
1110  return false;
1111  }
1112 
1113  uint64_t type_num = Protocol::get_type_num<T...>();
1114 
1115  Protocol new_protocol{};
1116  new_protocol.size_num = size_num;
1117  std::memset(new_protocol.names, 0, sizeof(new_protocol.names));
1118  std::memcpy(new_protocol.names, key_str.c_str(), key_str.size());
1119  new_protocol.type_num = type_num;
1120 
1121  if (extent != 0) {
1122  PointCloud protocol_probe;
1123  protocol_probe.protocol_ = new_protocol;
1124 
1125  if VUNLIKELY (!protocol_probe.compress_protocol_xyz()) {
1126  return false;
1127  }
1128 
1129  new_protocol = protocol_probe.protocol_;
1130  }
1131 
1132  const size_t new_pack_size = new_protocol.get_pack_size();
1133 
1134  if VUNLIKELY (new_pack_size != 0 && size > std::numeric_limits<size_t>::max() / new_pack_size) {
1135  return false;
1136  }
1137 
1138  if (is_owner_ && data_ && capacity_ != 0) {
1139  Bytes::bytes_free(data_, capacity_);
1140  }
1141 
1142  data_ = nullptr;
1143  is_owner_ = false;
1144  capacity_ = 0;
1145  size_ = 0;
1146  index_ = 0;
1147 
1148  protocol_ = new_protocol;
1149  extent_ = extent;
1150  vertical_ = vertical;
1151  downsample_ = 0;
1152 
1153  pack_size_ = new_pack_size;
1154  capacity_ = size * pack_size_;
1155 
1156  if VLIKELY (capacity_ != 0) {
1157  data_ = Bytes::bytes_malloc(capacity_);
1158 
1159  if VUNLIKELY (!data_) {
1160  capacity_ = 0;
1161  return false;
1162  }
1163 
1164  is_owner_ = true;
1165  }
1166 
1167  return true;
1168 }
1169 
1170 template <typename... T>
1171 inline bool PointCloud::create_v3f(size_t _size, const std::vector<std::string>& keys, uint16_t extent,
1172  bool vertical) noexcept {
1173  std::vector<std::string> target_keys{"x", "y", "z"};
1174 
1175  target_keys.insert(target_keys.end(), keys.begin(), keys.end());
1176 
1177  return create<float, float, float, T...>(_size, target_keys, extent, vertical);
1178 }
1179 
1180 template <typename... T>
1181 inline bool PointCloud::create_v3d(size_t _size, const std::vector<std::string>& keys, uint16_t extent,
1182  bool vertical) noexcept {
1183  std::vector<std::string> target_keys{"x", "y", "z"};
1184 
1185  target_keys.insert(target_keys.end(), keys.begin(), keys.end());
1186 
1187  return create<double, double, double, T...>(_size, target_keys, extent, vertical);
1188 }
1189 
1190 inline bool PointCloud::fill_packed_data(const uint8_t* src_data, size_t _size) noexcept {
1191  bool is_fill_success = false;
1192 
1193  if VUNLIKELY (_size == 0 || !src_data) {
1194  is_fill_success = false;
1195  } else if VUNLIKELY (!is_owner_ || !data_ || pack_size_ == 0 || capacity_ == 0) {
1196  is_fill_success = false;
1197  } else if VUNLIKELY (_size > std::numeric_limits<size_t>::max() / pack_size_ || _size * pack_size_ > capacity_) {
1198  is_fill_success = false;
1199  } else {
1200  std::memcpy(data_, src_data, _size * pack_size_);
1201  size_ = _size;
1202  index_ = _size * pack_size_;
1203  is_fill_success = true;
1204  }
1205 
1206  return is_fill_success;
1207 }
1208 
1209 template <typename... T>
1210 inline bool PointCloud::push_value(T... args) noexcept {
1211  static_assert((std::is_fundamental_v<T> && ...), "All types must be fundamental.");
1212 
1213  static_assert(sizeof...(T) >= 3 && sizeof...(T) <= 16, "The number of keys ranges is [3 ~ 16].");
1214 
1215  if VUNLIKELY (!is_owner_ || !data_ || pack_size_ == 0 || capacity_ == 0) {
1216  return false;
1217  }
1218 
1219  if VUNLIKELY (size_ * pack_size_ >= capacity_) {
1220  return false;
1221  }
1222 
1223  constexpr size_t kTargetPackSize = (sizeof(T) + ...);
1224 
1225  if VUNLIKELY (kTargetPackSize != pack_size_) {
1226  return false;
1227  }
1228 
1229  auto* target_ptr = data_ + index_;
1230 
1231  (
1232  [&]() {
1233  std::memcpy(target_ptr, &args, sizeof(args));
1234  target_ptr += sizeof(args);
1235  }(),
1236  ...);
1237 
1238  index_ += pack_size_;
1239  ++size_;
1240 
1241  return true;
1242 }
1243 
1244 template <typename... T>
1245 inline bool PointCloud::push_value_v3f(float x, float y, float z, T... args) noexcept {
1246  if (extent_ != 0) {
1247  if VUNLIKELY (!xyz_in_extent(x, y, z, extent_)) {
1248  return false;
1249  }
1250 
1251  auto qx = Quantize::encode<int16_t>(extent_, x);
1252  auto qy = Quantize::encode<int16_t>(extent_, y);
1253  auto qz = Quantize::encode<int16_t>(extent_, z);
1254 
1255  return push_value(qx, qy, qz, args...);
1256  }
1257 
1258  return push_value(x, y, z, args...);
1259 }
1260 
1261 template <typename... T>
1262 inline bool PointCloud::push_value_v3f(Vector3f v3f, T... args) noexcept {
1263  return push_value_v3f(v3f.x, v3f.y, v3f.z, args...);
1264 }
1265 
1266 template <typename... T>
1267 inline bool PointCloud::push_value_v3d(double x, double y, double z, T... args) noexcept {
1268  if (extent_ != 0) {
1269  if VUNLIKELY (!xyz_in_extent(x, y, z, extent_)) {
1270  return false;
1271  }
1272 
1273  auto qx = Quantize::encode<int16_t>(extent_, x);
1274  auto qy = Quantize::encode<int16_t>(extent_, y);
1275  auto qz = Quantize::encode<int16_t>(extent_, z);
1276 
1277  return push_value(qx, qy, qz, args...);
1278  }
1279 
1280  return push_value(x, y, z, args...);
1281 }
1282 
1283 template <typename... T>
1284 inline bool PointCloud::push_value_v3d(Vector3d v3d, T... args) noexcept {
1285  return push_value_v3d(v3d.x, v3d.y, v3d.z, args...);
1286 }
1287 
1288 inline bool PointCloud::resize(size_t size) noexcept {
1289  if VUNLIKELY (!is_owner_ || !data_ || pack_size_ == 0 || capacity_ == 0) {
1290  return false;
1291  }
1292 
1293  if VUNLIKELY (size > std::numeric_limits<size_t>::max() / pack_size_) {
1294  return false;
1295  }
1296 
1297  if VUNLIKELY (size * pack_size_ > capacity_) {
1298  return false;
1299  }
1300 
1301  size_ = size;
1302  index_ = size_ * pack_size_;
1303 
1304  return true;
1305 }
1306 
1307 template <typename... T>
1308 bool PointCloud::set_value(size_t loop_index, T... args) noexcept {
1309  static_assert((std::is_fundamental_v<T> && ...), "All types must be fundamental.");
1310 
1311  static_assert(sizeof...(T) >= 3 && sizeof...(T) <= 16, "The number of keys ranges is [3 ~ 16].");
1312 
1313  if VUNLIKELY (!is_owner_ || !data_ || pack_size_ == 0 || capacity_ == 0) {
1314  return false;
1315  }
1316 
1317  if VUNLIKELY (loop_index >= size_ || size_ * pack_size_ > capacity_) {
1318  return false;
1319  }
1320 
1321  if VUNLIKELY (index_ != size_ * pack_size_) {
1322  std::cerr << "[PointCloud::set_value] Invalid buffer state: "
1323  << "The current buffer size does not match the capacity. "
1324  << "Please call resize(size) before using set_value()." << std::endl;
1325  return false;
1326  }
1327 
1328  constexpr size_t kTargetPackSize = (sizeof(T) + ...);
1329 
1330  if VUNLIKELY (kTargetPackSize != pack_size_) {
1331  return false;
1332  }
1333 
1334  auto* target_ptr = data_ + (loop_index * pack_size_);
1335 
1336  (
1337  [&]() {
1338  std::memcpy(target_ptr, &args, sizeof(args));
1339  target_ptr += sizeof(args);
1340  }(),
1341  ...);
1342 
1343  return true;
1344 }
1345 
1346 template <typename... T>
1347 inline bool PointCloud::set_value_v3f(size_t loop_index, float x, float y, float z, T... args) noexcept {
1348  if (extent_ != 0) {
1349  if VUNLIKELY (!xyz_in_extent(x, y, z, extent_)) {
1350  return false;
1351  }
1352 
1353  auto qx = Quantize::encode<int16_t>(extent_, x);
1354  auto qy = Quantize::encode<int16_t>(extent_, y);
1355  auto qz = Quantize::encode<int16_t>(extent_, z);
1356 
1357  return set_value(loop_index, qx, qy, qz, args...);
1358  }
1359 
1360  return set_value(loop_index, x, y, z, args...);
1361 }
1362 
1363 template <typename... T>
1364 inline bool PointCloud::set_value_v3f(size_t loop_index, Vector3f v3f, T... args) noexcept {
1365  return set_value_v3f(loop_index, v3f.x, v3f.y, v3f.z, args...);
1366 }
1367 
1368 template <typename... T>
1369 inline bool PointCloud::set_value_v3d(size_t loop_index, double x, double y, double z, T... args) noexcept {
1370  if (extent_ != 0) {
1371  if VUNLIKELY (!xyz_in_extent(x, y, z, extent_)) {
1372  return false;
1373  }
1374 
1375  auto qx = Quantize::encode<int16_t>(extent_, x);
1376  auto qy = Quantize::encode<int16_t>(extent_, y);
1377  auto qz = Quantize::encode<int16_t>(extent_, z);
1378 
1379  return set_value(loop_index, qx, qy, qz, args...);
1380  }
1381 
1382  return set_value(loop_index, x, y, z, args...);
1383 }
1384 
1385 template <typename... T>
1386 inline bool PointCloud::set_value_v3d(size_t loop_index, Vector3d v3d, T... args) noexcept {
1387  return set_value_v3d(loop_index, v3d.x, v3d.y, v3d.z, args...);
1388 }
1389 
1390 template <typename... T>
1391 inline uint64_t PointCloud::Protocol::get_size_num() noexcept {
1392  uint64_t target_num = 0;
1393 
1394  uint64_t key_shift = sizeof...(T) * 4;
1395 
1396  (
1397  [&](auto type) {
1398  key_shift -= 4;
1399  target_num |= (static_cast<uint64_t>(sizeof(type)) & 0xF) << key_shift;
1400  }(T{}),
1401  ...);
1402 
1403  return target_num;
1404 }
1405 
1406 template <typename... T>
1407 inline uint64_t PointCloud::Protocol::get_type_num() noexcept {
1408  uint64_t target_num = 0;
1409 
1410  uint64_t key_shift = sizeof...(T) * 4;
1411 
1412  (
1413  [&](auto type) {
1414  key_shift -= 4;
1415  target_num |= (static_cast<uint64_t>(get_type<decltype(type)>()) & 0xF) << key_shift;
1416  }(T{}),
1417  ...);
1418 
1419  return target_num;
1420 }
1421 
1422 template <typename T>
1423 inline constexpr uint8_t PointCloud::Protocol::get_type() noexcept {
1424  if constexpr (std::is_same_v<T, bool>) {
1425  return kBoolType;
1426  } else if constexpr (std::is_same_v<T, int8_t>) {
1427  return kInt8Type;
1428  } else if constexpr (std::is_same_v<T, uint8_t>) {
1429  return kUint8Type;
1430  } else if constexpr (std::is_same_v<T, int16_t>) {
1431  return kInt16Type;
1432  } else if constexpr (std::is_same_v<T, uint16_t>) {
1433  return kUint16Type;
1434  } else if constexpr (std::is_same_v<T, int32_t>) {
1435  return kInt32Type;
1436  } else if constexpr (std::is_same_v<T, uint32_t>) {
1437  return kUint32Type;
1438  } else if constexpr (std::is_same_v<T, int64_t>) {
1439  return kInt64Type;
1440  } else if constexpr (std::is_same_v<T, uint64_t>) {
1441  return kUint64Type;
1442  } else if constexpr (std::is_same_v<T, float>) {
1443  return kFloatType;
1444  } else if constexpr (std::is_same_v<T, double>) {
1445  return kDoubleType;
1446  } else {
1447  return kUnknownType;
1448  }
1449 }
1450 
1451 inline constexpr uint64_t PointCloud::Protocol::get_pack_size() const noexcept {
1452  int sum = 0;
1453 
1454  auto target_num = size_num;
1455 
1456  while (target_num > 0) {
1457  sum += target_num & 0xF;
1458  target_num >>= 4;
1459  }
1460 
1461  return sum;
1462 }
1463 
1464 template <typename T>
1465 inline bool PointCloud::xyz_in_extent(T x, T y, T z, uint16_t extent) noexcept {
1466  return x > -extent && x < extent && y > -extent && y < extent && z > -extent && z < extent;
1467 }
1468 
1469 } // namespace zerocopy
1470 
1471 } // namespace vlink
Fixed-size timestamp and sequencing prefix embedded by every VLink zero-copy container.
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284
40-byte timestamp / sequencing metadata prefix shared by all zero-copy containers.
Definition: point_cloud.h:196
256-byte POD container holding a schema-described array of N-field point records.