This commit is contained in:
trung09122002
2026-09-23 13:36:48 +07:00
parent dbcbf84dc3
commit 0a1b1b13f1
38 changed files with 2331 additions and 138 deletions

View File

@@ -106,6 +106,12 @@ DbFacts InspectDatabase(const std::string& path) {
auto it = db_params.find(rtabmap::Parameters::kOptimizerStrategy());
if (it != db_params.end()) f.optimizer_strategy = it->second;
// Cung co che: doc lai tham so DB da luu. "true"/"1" deu tinh la bat.
auto it3d = db_params.find(rtabmap::Parameters::kGrid3D());
if (it3d != db_params.end()) {
f.grid_3d = (it3d->second == "true" || it3d->second == "1");
}
driver->closeConnection(false);
return f;
}

View File

@@ -116,6 +116,42 @@ std::map<std::string, std::string> BuildRtabmapParams(
// Kp/MaxFeatures: -1 = tat han tui tu. >0 = so dac trung moi anh.
out["Kp/MaxFeatures"] = cfg.visual_loop ? "400" : "-1";
// --- camera_3d: luoi cuc bo 3D de dung ban do voxel cho web ---
//
// Nam o muc 3 chu khong o `project_defaults`: slam.yaml dat THANG
// `Grid/Sensor: "0"` va `Grid/3D: "false"`, ma muc 2 (YAML) ghi de len muc
// 1. De o day thi ba key nay la HE QUA cua co, dung nhu Mem/IncrementalMemory
// la he qua cua mode.
if (cfg.camera_3d) {
// 0=scan 1=depth 2=ca hai. Can "2": LiDAR van la trong tai cho ICP, con
// depth la thu duy nhat co chieu cao.
out["Grid/Sensor"] = "2";
out["Grid/3D"] = "true";
// Tach san/vat can bang NGUONG CHIEU CAO, khong bang phap tuyen.
// NormalsSegmentation mac dinh true va la duong DAT: no uoc luong phap
// tuyen (Grid/NormalK = 20 lang gieng) cho moi diem, moi khung. Robot nay
// la 2.5D (Reg/Force3DoF), san phang, nen mot nguong chieu cao la du.
// RTAB-Map cung noi thang: MaxGroundHeight "should be set if
// NormalsSegmentation is false".
out["Grid/NormalsSegmentation"] = "false";
out["Grid/MaxGroundHeight"] = "0.10"; // duoi nguong = san
out["Grid/MaxObstacleHeight"] = "2.0"; // tren nguong = tran, vut di
// ⚠️ Grid/RayTracing GIU NGUYEN "true" (mac dinh cua du an), khong tat.
//
// Tat no re hon that -- voi Grid/3D=true, ray tracing dien o KHONG GIAN
// chu khong phai mat phang, va ban do voxel chi doc o BI CHIEM nen o
// trong la chi phi thuan. Nhung no cung chinh la thu sinh ra o "trong"
// cua luoi 2D: do tren robot that 2026-09-23, mot phien 3.5 phut cho
// 84961 o trong / 5049 o bi chiem. Tat di thi khung ban do tren web gan
// nhu chi con mau "chua biet".
//
// Muon danh doi nguoc lai thi dat `Grid/RayTracing: "false"` trong khoi
// `rtabmap:` cua slam.yaml -- do la viec cua nguoi van hanh, khong phai
// mot he qua am tham cua camera_3d.
}
// Optimizer: dat TUONG MINH, luon luon.
//
// DB hien co (`map_house.db`) luu Optimizer/Strategy=2 (GTSAM). Tren Jetson

View File

@@ -12,6 +12,7 @@
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
#include "vslam/occupancy_export.h"
#include "vslam/sensor_data_builder.h"
@@ -69,6 +70,10 @@ void RtabmapSlam::SetExtrinsics(const Transform& laser_to_base,
SlamMode RtabmapSlam::mode() const { return impl_->cfg.mode; }
const SlamStats& RtabmapSlam::stats() const { return impl_->stats; }
const std::string& RtabmapSlam::database_path() const {
return impl_->cfg.database_path;
}
Pose2D RtabmapSlam::map_correction() const {
std::lock_guard<std::mutex> lk(impl_->out_mu);
return impl_->map_correction;
@@ -88,6 +93,27 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
}
impl_->cfg = cfg;
// --- Giai duong dan DB: tuong doi -> MapDir(), no {stamp} ---
//
// Lam o DAY chu khong o app_config: duong `--check` khong dung toi
// RtabmapSlam, nen cau hinh van kiem duoc tren may khong co quyen ghi vao
// /var/lib -- bon test badconfig chay dung kieu do.
impl_->cfg.database_path = ResolveMapPath(cfg.database_path);
const std::string& db_path = impl_->cfg.database_path;
if (db_path != cfg.database_path) {
VSLAM_INFO("slam: database_path \"" << cfg.database_path << "\" -> " << db_path);
}
// {stamp} o che do localization la mot loi logic, khong phai tuy chon: ten
// sinh moi lan chay thi khong bao gio khop ban do da quet.
if (cfg.mode == SlamMode::kLocalization &&
cfg.database_path.find("{stamp}") != std::string::npos) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"localization voi {stamp} trong database_path: ten sinh moi lan chay "
"thi khong bao gio tim thay ban do da quet.");
}
// ULogger cua RTAB-Map mac dinh in thang ra stdout va rat on. Day ve ERROR;
// thong tin can thiet da co trong SlamOutput va stats.
ULogger::setType(ULogger::kTypeNoLog);
@@ -113,14 +139,14 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
return StatusResponse::Error(StatusCode::kInvalidArgument, msg);
}
const DbFacts facts = InspectDatabase(cfg.database_path);
const DbFacts facts = InspectDatabase(db_path);
if (cfg.mode == SlamMode::kLocalization) {
// Localization can mot ban do DA CO. Khong co thi no chay im lang ma
// khong bao gio dinh vi duoc vao dau -- da do: process_ms 0.3-2.4 ms va
// map->odom luon bang 0, trong nhu "SLAM dang chay tot".
//
// Duong dan rong = DB trong RAM = chac chan khong co ban do.
if (cfg.database_path.empty()) {
if (db_path.empty()) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"che do localization nhung database_path de rong (DB trong RAM). "
@@ -129,7 +155,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
if (!facts.exists || facts.nodes == 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"che do localization nhung DB khong co node nao: " + cfg.database_path);
"che do localization nhung DB khong co node nao: " + db_path);
}
}
if (cfg.visual_loop && facts.exists && facts.words == 0) {
@@ -141,6 +167,11 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
"visual_loop=true nhung DB khong co tu vung (Word = 0). Ban do nay "
"duoc quet voi visual_loop=false; hai co phai khop nhau.");
}
if (cfg.camera_3d && facts.exists && !facts.grid_3d) {
VSLAM_WARN("slam: camera_3d=true nhung DB nay duoc quet voi Grid/3D=false "
"-- ban do voxel se chi co MOT lop ngang o cao do LiDAR. Quet "
"lai vao DB moi neu can ban do 3D that.");
}
if (facts.exists && facts.optimizer_strategy != cfg.optimizer_strategy) {
VSLAM_WARN("slam: DB luu Optimizer/Strategy=" << facts.optimizer_strategy
<< ", dang ep ve " << cfg.optimizer_strategy
@@ -169,10 +200,19 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
" node: RTAB-Map 0.21.13 nem 'UNIQUE constraint failed: "
"Statistics.id' o MOI khung va khong dung duoc ban do nao.\n"
" - Quet lai tu dau : --slam-db <duong dan MOI>\n"
" - Dat ten tu dong : --slam-db \"map_{stamp}.db\"\n"
" - Dung ban do nay : --slam-mode localization "
"--slam-init-pose x,y,yaw");
}
// rtabmap.init() tao FILE, khong tao THU MUC -- thieu thu muc cha thi no
// nem tu trong ruot sqlite. Chi can o mapping; localization thi DB bat buoc
// da ton tai va da qua phep kiem ben tren.
if (cfg.mode == SlamMode::kMapping && !db_path.empty()) {
const StatusResponse mk = EnsureParentDir(db_path);
if (!mk.ok()) return mk;
}
rtabmap::ParametersMap pm(params.begin(), params.end());
try {
// loadDatabaseParameters = FALSE, luon luon.
@@ -180,7 +220,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
// map_house.db luu Optimizer/Strategy=2 (GTSAM). Neu de RTAB-Map doc lai
// tham so tu DB thi tren Jetson build -DWITH_GTSAM=OFF no se chon GTSAM
// va crash thieu symbol.
impl_->rtabmap.init(pm, cfg.database_path, /*loadDatabaseParameters=*/false);
impl_->rtabmap.init(pm, db_path, /*loadDatabaseParameters=*/false);
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInternal,
std::string("rtabmap init: ") + e.what());
@@ -205,7 +245,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
impl_->map_version = 1;
}
VSLAM_INFO("slam: " << SlamModeName(cfg.mode) << ", DB "
<< (cfg.database_path.empty() ? "(RAM)" : cfg.database_path)
<< (db_path.empty() ? "(RAM)" : db_path)
<< " (" << facts.nodes << " node, " << facts.words
<< " tu vung), optimizer " << cfg.optimizer_strategy);
return StatusResponse::Ok();
@@ -307,6 +347,14 @@ StatusResponse RtabmapSlam::ExportMap(OccupancyGrid* out) {
return ExportOccupancyGrid(impl_->rtabmap, out);
}
StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt,
VoxelGrid* out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
return ExportVoxelGrid(impl_->rtabmap, opt, out);
}
StatusResponse RtabmapSlam::Close(bool save_database) {
if (!impl_->inited) return StatusResponse::Ok();
impl_->inited = false;

View File

@@ -0,0 +1,246 @@
#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