Files
vslam_cpp/libs/vslam_slam/src/voxel_export.cc
trung09122002 0a1b1b13f1 update
2026-09-23 13:36:48 +07:00

247 lines
8.3 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 <opencv2/core.hpp>
#include <algorithm>
#include <cmath>
#include <map>
#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;
out->truncated = acc_.size() > opt_.max_cells;
const size_t n = std::min(acc_.size(), opt_.max_cells);
out->cells.clear();
out->cells.reserve(n);
for (size_t i = 0; i < n; ++i) {
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]);
}
StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
const VoxelExportOptions& opt, 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");
}
VoxelAccumulator acc(opt);
size_t nodes_with_grid = 0;
int channels_seen = 0;
for (const auto& kv : poses) {
if (kv.second.isNull()) continue;
rtabmap::SensorData data = mem->getNodeData(kv.first, false, false, false, true);
// ⚠️ BAT BUOC. Thieu dong nay thi gridObstacleCellsRaw() tra ma tran RONG
// o moi node va ban do 3D im lang rong khong.
data.uncompressData();
if (data.gridCellSize() <= 0.0f) continue;
const cv::Mat& obs = data.gridObstacleCellsRaw();
if (obs.empty()) continue;
if (obs.depth() != CV_32F) {
return StatusResponse::Error(
StatusCode::kInternal,
"o luoi cuc bo khong phai float32 (depth=" +
std::to_string(obs.depth()) + ") -- phien ban RTAB-Map la");
}
const int ch = obs.channels();
if (ch < 2) {
return StatusResponse::Error(
StatusCode::kInternal,
"o luoi cuc bo co " + std::to_string(ch) +
" kenh, cho doi 2 (XY) hoac 3/4 (XYZ[+RGB])");
}
if (channels_seen == 0) channels_seen = ch;
// 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();
const int n = obs.cols * obs.rows;
const float* p = obs.ptr<float>();
for (int i = 0; i < n; ++i) {
const float px = p[0];
const float py = p[1];
// 2 kenh = luoi PHANG (DB quet voi Grid/3D=false). Van ve duoc, chi la
// ra mot lop ngang -- Init() da canh bao truong hop nay.
const float pz = (ch >= 3) ? p[2] : 0.0f;
p += ch;
acc.AddPoint(r00 * px + r01 * py + r02 * pz + tx,
r10 * px + r11 * py + r12 * pz + ty,
r20 * px + r21 * py + r22 * pz + tz);
}
++nodes_with_grid;
}
if (nodes_with_grid == 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"khong node nao co luoi cuc bo -- RGBD/CreateOccupancyGrid tat, hoac "
"DB quet truoc khi bat camera_3d");
}
acc.Finish(out);
// Mot dong, mot lan moi 30 giay: so kenh la thu duy nhat trong ca duong nay
// khong doc duoc tu header RTAB-Map, nen no phai hien ra o log that.
VSLAM_INFO_THROTTLE(30.0, "slam: voxel " << out->cells.size() << " o tu "
<< nodes_with_grid << " node (" << channels_seen
<< " kenh/o" << (out->truncated ? ", DA CAT BOT" : "")
<< ")");
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