Files
vslam_cpp/libs/vslam_slam/src/voxel_export.cc
trung09122002 d6f1afac31 update
2026-09-24 16:30:03 +07:00

289 lines
10 KiB
C++

#include "vslam/voxel_export.h"
#include <rtabmap/core/Memory.h>
#include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/Transform.h>
#include <rtabmap/core/util3d.h>
#include <opencv2/core.hpp>
#include <algorithm>
#include <cmath>
#include <iterator>
#include <map>
#include <string>
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Goi chi so co dau vao 63 bit: 21 bit moi truc, lech +2^20 de so am van sap
// xep dung thu tu khi so sanh uint64.
//
// Vi sao vector<uint64> da sort chu khong phai hash set hay octree: tap nay
// duoc dung LAI TU DAU moi lan xuat (pose toi uu dich cho, cau truc tang dan
// vo nghia), va nguoi tieu thu can dau ra DA SAP XEP de lam phep tru tap hop
// O(n). Mot vector phang sort cache tot hon han hash 2 trieu phan tu.
constexpr int32_t kIdxBias = 1 << 20;
constexpr int32_t kIdxMin = -kIdxBias;
constexpr int32_t kIdxMax = kIdxBias - 1;
inline uint64_t PackKey(int32_t x, int32_t y, int32_t z) {
const uint64_t ux = static_cast<uint64_t>(static_cast<uint32_t>(x + kIdxBias)) & 0x1FFFFFULL;
const uint64_t uy = static_cast<uint64_t>(static_cast<uint32_t>(y + kIdxBias)) & 0x1FFFFFULL;
const uint64_t uz = static_cast<uint64_t>(static_cast<uint32_t>(z + kIdxBias)) & 0x1FFFFFULL;
return (ux << 42) | (uy << 21) | uz;
}
inline void UnpackKey(uint64_t k, int32_t* x, int32_t* y, int32_t* z) {
*x = static_cast<int32_t>((k >> 42) & 0x1FFFFFULL) - kIdxBias;
*y = static_cast<int32_t>((k >> 21) & 0x1FFFFFULL) - kIdxBias;
*z = static_cast<int32_t>(k & 0x1FFFFFULL) - kIdxBias;
}
inline bool FitsInt16(int32_t v) {
return v >= -32768 && v <= 32767;
}
inline uint64_t KeyOf(const VoxelIndex& k) {
return PackKey(k.x, k.y, k.z);
}
} // namespace
VoxelAccumulator::VoxelAccumulator(const VoxelExportOptions& opt) : opt_(opt) {
if (opt_.emit_size_m <= 0.0) opt_.emit_size_m = 0.10;
inv_size_ = 1.0 / opt_.emit_size_m;
scratch_.reserve(1 << 16);
}
void VoxelAccumulator::AddPoint(double x, double y, double z) {
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z)) return;
if (z < opt_.z_min || z > opt_.z_max) {
++z_rejected_;
return;
}
const double fx = std::floor(x * inv_size_);
const double fy = std::floor(y * inv_size_);
const double fz = std::floor(z * inv_size_);
// Kiem TRUOC khi ep kieu: ep mot double khong lot int32 la hanh vi khong
// xac dinh, va o day no den tu du lieu cam bien chu khong tu hang so.
if (fx < kIdxMin || fx > kIdxMax || fy < kIdxMin || fy > kIdxMax ||
fz < kIdxMin || fz > kIdxMax) {
++clamped_;
return;
}
const int32_t ix = static_cast<int32_t>(fx);
const int32_t iy = static_cast<int32_t>(fy);
const int32_t iz = static_cast<int32_t>(fz);
// Dang truyen la int16 -> chi so ngoai dai do la bo, khong phai kep: kep se
// dan mot buc tuong gia o ria ban do.
if (!FitsInt16(ix) || !FitsInt16(iy) || !FitsInt16(iz)) {
++clamped_;
return;
}
scratch_.push_back(PackKey(ix, iy, iz));
if (scratch_.size() >= opt_.flush_every) Flush();
}
void VoxelAccumulator::Flush() {
if (scratch_.empty()) return;
std::sort(scratch_.begin(), scratch_.end());
scratch_.erase(std::unique(scratch_.begin(), scratch_.end()), scratch_.end());
if (acc_.empty()) {
acc_.swap(scratch_);
} else {
std::vector<uint64_t> merged;
merged.reserve(acc_.size() + scratch_.size());
std::set_union(acc_.begin(), acc_.end(), scratch_.begin(), scratch_.end(),
std::back_inserter(merged));
acc_.swap(merged);
}
scratch_.clear();
}
void VoxelAccumulator::Finish(VoxelGrid* out) {
Flush();
out->resolution = static_cast<float>(opt_.emit_size_m);
out->origin_x = 0.0;
out->origin_y = 0.0;
out->origin_z = 0.0;
out->header.frame_id = kMapFrame;
// ⚠️ Cham tran thi GIAM MAU DEU, tuyet doi khong cat cut danh sach.
//
// `acc_` sort theo khoa goi, ma khoa goi sort theo x truoc -- nen lay
// `max_cells` phan tu DAU la chat mot lat khong gian: nguyen mot canh cua
// toa nha bien mat khoi ban do trong khi phan con lai van day du. Da mac
// dung loi nay: nguoi dung bao "goc tren ben trai quet roi ma gio mat".
//
// Giam mau deu thi ban do GIU NGUYEN hinh dang, chi thua di. Cung khuon mau
// ma EncodeCloud dung cho `cloud_max_points` (binary_codec.cc) -- buoc deu,
// khong cat duoi.
const size_t total = acc_.size();
stride_ = 1;
if (opt_.max_cells > 0 && total > opt_.max_cells) {
stride_ = (total + opt_.max_cells - 1) / opt_.max_cells;
}
out->truncated = stride_ > 1;
out->cells.clear();
out->cells.reserve(total / stride_ + 1);
for (size_t i = 0; i < total; i += stride_) {
int32_t x = 0, y = 0, z = 0;
UnpackKey(acc_[i], &x, &y, &z);
VoxelIndex k;
k.x = static_cast<int16_t>(x);
k.y = static_cast<int16_t>(y);
k.z = static_cast<int16_t>(z);
out->cells.push_back(k);
}
// `acc_` da sort theo khoa goi, va khoa goi giu dung thu tu tu nhien cua
// (x, y, z) nho phep lech +2^20 -- nen out->cells cung da sap xep.
}
void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
const std::vector<VoxelIndex>& now,
std::vector<VoxelIndex>* added,
std::vector<VoxelIndex>* removed) {
added->clear();
removed->clear();
size_t i = 0, j = 0;
while (i < prev.size() && j < now.size()) {
const uint64_t a = KeyOf(prev[i]);
const uint64_t b = KeyOf(now[j]);
if (a == b) {
++i;
++j;
} else if (a < b) {
removed->push_back(prev[i++]);
} else {
added->push_back(now[j++]);
}
}
for (; i < prev.size(); ++i) removed->push_back(prev[i]);
for (; j < now.size(); ++j) added->push_back(now[j]);
}
void NodeCloudFromSensorData(const rtabmap::SensorData& data,
const VoxelExportOptions& opt,
std::vector<float>* out) {
out->clear();
if (data.depthOrRightRaw().empty() || data.cameraModels().empty()) return;
// cloudFromSensorData ap localTransform cua camera (base <- optical), nen
// diem ra o frame base cua node -- cung frame voi pose cua no.
const auto cloud = rtabmap::util3d::cloudFromSensorData(
data, opt.depth_decimation, static_cast<float>(opt.depth_max_m),
static_cast<float>(opt.depth_min_m));
if (!cloud) return;
VoxelAccumulator acc(opt);
for (const auto& p : cloud->points) acc.AddPoint(p.x, p.y, p.z);
VoxelGrid vg;
acc.Finish(&vg);
const double s = opt.emit_size_m;
out->reserve(vg.cells.size() * 3);
for (const VoxelIndex& k : vg.cells) {
out->push_back(static_cast<float>((k.x + 0.5) * s));
out->push_back(static_cast<float>((k.y + 0.5) * s));
out->push_back(static_cast<float>((k.z + 0.5) * s));
}
}
StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
const VoxelExportOptions& opt,
VoxelNodeCache* cache, VoxelGrid* out) {
const std::map<int, rtabmap::Transform>& poses = slam.getLocalOptimizedPoses();
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"khong co pose nao de dung ban do voxel");
}
const rtabmap::Memory* mem = slam.getMemory();
if (mem == nullptr) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"rtabmap chua co Memory");
}
// Bo node khong con trong do thi (bi gop/xoa) -- khong thi cache phinh mai.
for (auto it = cache->nodes.begin(); it != cache->nodes.end();) {
it = poses.count(it->first) ? std::next(it) : cache->nodes.erase(it);
}
VoxelAccumulator acc(opt);
size_t nodes_used = 0, fetched = 0, pending = 0, no_points = 0;
for (const auto& kv : poses) {
if (kv.second.isNull()) continue;
auto it = cache->nodes.find(kv.first);
if (it == cache->nodes.end()) {
if (fetched >= opt.max_new_nodes) {
++pending;
continue;
}
++fetched;
// images=true, con lai false: chi can depth + camera model.
rtabmap::SensorData data = mem->getNodeData(kv.first, true, false, false, false);
// ⚠️ BAT BUOC. Thieu dong nay thi depthOrRightRaw() tra ma tran RONG o
// moi node va ban do 3D im lang rong khong.
data.uncompressData();
std::vector<float> pts;
NodeCloudFromSensorData(data, opt, &pts);
it = cache->nodes.emplace(kv.first, std::move(pts)).first;
}
const std::vector<float>& pts = it->second;
if (pts.empty()) {
++no_points;
continue;
}
// Pose da toi uu: node -> map. Dung ma tran 3x4 dung san, 12 phep nhan
// cho moi diem, thay vi dung mot rtabmap::Transform cho tung diem.
const rtabmap::Transform& T = kv.second;
const float r00 = T.r11(), r01 = T.r12(), r02 = T.r13(), tx = T.x();
const float r10 = T.r21(), r11 = T.r22(), r12 = T.r23(), ty = T.y();
const float r20 = T.r31(), r21 = T.r32(), r22 = T.r33(), tz = T.z();
for (size_t i = 0; i + 2 < pts.size(); i += 3) {
const float px = pts[i], py = pts[i + 1], pz = pts[i + 2];
acc.AddPoint(r00 * px + r01 * py + r02 * pz + tx,
r10 * px + r11 * py + r12 * pz + ty,
r20 * px + r21 * py + r22 * pz + tz);
}
++nodes_used;
}
if (nodes_used == 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
pending > 0 ? "dang nap depth cua node"
: "khong node nao co depth -- DB quet voi camera_3d=false, "
"hoac khong co camera");
}
acc.Finish(out);
// Mot dong, mot lan moi 30 giay. `khong co diem` cao bat thuong nghia la
// getNodeData khong tra depth -- thu dau tien can nhin khi ban do 3D rong.
VSLAM_INFO_THROTTLE(30.0, "slam: voxel " << out->cells.size() << " o tu "
<< nodes_used << " node (dang nap " << pending << ", "
<< no_points << " node khong co diem"
<< (out->truncated
? ", GIAM MAU 1/" + std::to_string(acc.stride()) +
" -- cham tran max_cells"
: std::string())
<< ")");
if (acc.clamped() > 0) {
VSLAM_WARN_THROTTLE(30.0, "slam: " << acc.clamped()
<< " diem ngoai dai chi so voxel -- bo qua");
}
return StatusResponse::Ok();
}
} // namespace vslam