map,lidar,web: ban do theo lan nhin MOI NHAT + scan dung gio. Luoi 2D: GridGlobal/* (3 lan nhin xuyen qua -> trong, truoc ~9; truoc 07/10 khong truyen vao bo ghep luoi); lop camera + 3D: xoa voxel ma >= 2 node sau nhin xuyen qua (VoxelCarver) -- nguoi dung roi di thi quay lai quet la mat. LiDAR: stamp_offset -55 ms + chinh meo theo chieu quet (do tren ban do that 28/09 + 01/10); web: robot troi muot

This commit is contained in:
trung09122002
2026-10-07 16:04:28 +07:00
parent 61c3a75fb1
commit 31f84eb082
20 changed files with 855 additions and 50 deletions

View File

@@ -115,9 +115,14 @@ struct LidarConfig {
bool inverted = true;
LidarStampMode stamp_mode = LidarStampMode::kFirstPacket;
// Bu do tre da do duoc, cong vao stamp. Chua do -> 0.
// Bu do tre da do duoc, cong vao stamp. Chua do -> 0. sensors.yaml
// `lidar.stamp_offset_sec` (07/10: -0.055, do tren ban do that).
double stamp_offset_sec = 0.0;
// Chinh meo scan trong vong quet (runtime lam, khong phai driver -- driver
// khong biet robot dang chuyen dong the nao). sensors.yaml `lidar.deskew`.
bool deskew = true;
// Canh bao neu do dai sweep lech qua nhieu so voi scan_time du kien. Day la
// bo phat hien mat goi UDP mien phi ma driver goc khong co.
double sweep_duration_tolerance_sec = 0.005;

View File

@@ -65,6 +65,31 @@ void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
const ElevationMap* em, const ScanLevelerConfig& cfg, LaserScan* out,
ScanLevelStats* stats);
// ================== CHINH MEO SCAN (deskew) ==================
// LiDAR QUAY chup tung tia o mot thoi diem khac nhau trong vong quet, con
// stamp la MOT thoi diem (luc het vong). Robot dang quay w thi tia chup truoc
// stamp `lag` giay da lech w * lag -- 0.8 rad/s, vong 40 ms: tia dau va tia
// cuoi lech 1.8 do, o 5 m la 16 cm.
//
// Vong quet bat dau o goc `start_rad` (khung laser) va di theo chieu `dir`
// (+1: goc TANG theo thoi gian, -1: goc GIAM), het mot vong trong `period_s`.
// LakiBeam: theta = (flip ? -a : a) + angle_offset, azimuth a tang tu 0 ->
// start = angle_offset, dir = flip ? -1 : +1. Chieu nay DO tren ban do that
// 28/09 + 01/10: dir -1 lam scan khop tot hon, +1 te hon.
struct SweepTiming {
double start_rad = 0.0;
int dir = -1;
double period_s = 0.04;
};
// Dua moi tia ve khung robot LUC STAMP: robot da quay them w * lag va tien
// v * lag (w rad/s, v m/s theo truc x than) sau khi tia duoc chup. Xep lai vao
// o goc gan nhat, giu tia gan nhat moi o; o khong con tia nao -> NaN. Tia khong
// huu han va sentinel cua sector mask (> range_max) giu nguyen o cu, nhu
// LevelScan.
void DeskewScan(const LaserScan& in, const Transform& laser_to_base, const SweepTiming& tm,
double w, double v, LaserScan* out);
} // namespace vslam
#endif // VSLAM_SCAN_LEVELER_H

View File

@@ -105,4 +105,56 @@ void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
}
}
void DeskewScan(const LaserScan& in, const Transform& laser_to_base, const SweepTiming& tm,
double w, double v, LaserScan* out) {
*out = in;
const size_t n = in.ranges.size();
if (n == 0 || in.angle_increment == 0.0f || !(tm.period_s > 0.0)) return;
const float nan = std::numeric_limits<float>::quiet_NaN();
out->ranges.assign(n, nan);
if (!out->intensities.empty()) out->intensities.assign(n, 0.0f);
// Tia KHONG huu han va sentinel cua sector mask giu nguyen o cu (nhu LevelScan).
std::vector<char> masked(n, 0);
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (std::isnan(r)) continue;
if (std::isinf(r)) {
out->ranges[i] = r;
} else if (r > in.range_max) {
out->ranges[i] = r;
masked[i] = 1;
}
}
const Transform laser_from_base = TransformInverse(laser_to_base);
const double two_pi = 2.0 * M_PI;
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (!std::isfinite(r) || r > in.range_max) continue;
const double a = in.angle_min + static_cast<double>(i) * in.angle_increment;
// Phan vong DA quet truoc tia nay -> tia chup truoc stamp `lag` giay.
double f = std::fmod(tm.dir > 0 ? a - tm.start_rad : tm.start_rad - a, two_pi);
if (f < 0.0) f += two_pi;
const double lag = tm.period_s * (1.0 - f / two_pi);
const double dth = w * lag, dx = v * lag;
// Diem trong khung base LUC CHUP -> khung base LUC STAMP: robot da tien dx
// roi quay dth, nen diem tinh lui dx va xoay -dth.
const Point pb = TransformPoint(laser_to_base, Point{r * std::cos(a), r * std::sin(a), 0.0});
const double c = std::cos(dth), s = std::sin(dth);
const double qx = pb.x - dx, qy = pb.y;
const Point pl = TransformPoint(laser_from_base, Point{c * qx + s * qy, -s * qx + c * qy, pb.z});
const long j = RayIndex(std::atan2(pl.y, pl.x), in.angle_min, in.angle_increment, n);
if (j < 0 || masked[static_cast<size_t>(j)]) continue;
const double rr = std::hypot(pl.x, pl.y);
float& slot = out->ranges[static_cast<size_t>(j)];
if (!std::isfinite(slot) || rr < slot) {
slot = static_cast<float>(rr);
if (!out->intensities.empty() && i < in.intensities.size()) {
out->intensities[static_cast<size_t>(j)] = in.intensities[i];
}
}
}
}
} // namespace vslam

View File

@@ -9,6 +9,7 @@
// canh bao -- cho toi khi goi `uncompressDataConst()`. Do dung la ly do
// `tools/probe_rtabmap` lan dau chay ra "1990 node, 0 o".
#include <map>
#include <set>
#include <string>
@@ -44,10 +45,13 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out);
// `only_ids`: chi dung cac node co id trong tap nay (nullptr = moi node). De
// do relocalization CONG BANG tren mot phien: ban do tu nua dau, hoi bang nua
// sau -- scan dung de hoi khong duoc gop vao ban do.
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max,
OccupancyGrid* out,
const std::set<int>* only_ids = nullptr);
//
// `grid_params`: tham so RTAB-Map dang chay -- lay GridGlobal/* (cach cap nhat
// o) tu day. nullptr = theo tham so DB da luu luc quet.
StatusResponse ExportOccupancyGridFromDb(
const std::string& db_path, double cell_size, double range_max, OccupancyGrid* out,
const std::set<int>* only_ids = nullptr,
const std::map<std::string, std::string>* grid_params = nullptr);
} // namespace vslam

View File

@@ -19,6 +19,7 @@
// `init(params, db, loadDatabaseParameters=false)` VA assert sau do.
#include <memory>
#include <map>
#include <string>
#include <vector>
@@ -138,6 +139,11 @@ class RtabmapSlam {
// Rong = DB trong RAM. Chi co nghia sau Init().
const std::string& database_path() const;
// Tham so RTAB-Map DANG CHAY (slam.yaml + mac dinh). Dung lai GridGlobal/*
// khi dung luoi tu DB (ExportOccupancyGridFromDb) cho cung cach cap nhat o
// voi ban do dang hien.
std::map<std::string, std::string> rtabmap_parameters() const;
private:
std::unique_ptr<RtabmapSlamImpl> impl_;
};

View File

@@ -79,6 +79,15 @@ struct VoxelExportOptions {
// ClearLidarOnSeenRamps. Null = khong thu.
std::vector<uint64_t>* floor_cells = nullptr;
double floor_band = 0.05;
// "Lan nhin MOI NHAT quyet dinh" (07/10): voxel ma >= clear_after_views node
// SAU lan thay cuoi nhin XUYEN qua no (depth xa hon voxel + sai so depth),
// va khong node nao trong so do con thay -> XOA. Nguoi dung tren duong luc
// quet roi di -> quay lai quet la mat. 0 = tat: chi them, khong bao gio xoa
// (hanh vi truoc 07/10). Can min_node_hits >= 1 bat ky -- tu bat dem node.
size_t clear_after_views = 0;
// Chi hoi node co camera trong ban kinh nay (m): xa hon depth nhieu.
double clear_range_m = 3.5;
};
// Khoa o 2D (ix, iy) cua floor_cells.
@@ -89,10 +98,70 @@ inline uint64_t PackFloorCell(int32_t ix, int32_t iy) {
// Diem cua tung node, o frame CUA NODE, da gom voxel. Tinh MOT lan roi giu:
// depth cua node khong doi, chi pose cua no doi sau moi lan toi uu.
// CHI luong slam cham vao.
//
// Anh depth NHO cua mot node + camera cua no, de hoi "node nay co nhin XUYEN
// qua diem X khong" (VoxelCarver). Moi o lay depth NHO NHAT cua khoi pixel:
// than trong -- mot chan nguoi chiem vai pixel van lam o do "thay vat", khong
// thanh "xuyen qua".
struct NodeDepthView {
int w = 0, h = 0;
float fx = 0.0f, fy = 0.0f, cx = 0.0f, cy = 0.0f; // theo anh NHO
float cam[12] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}; // base <- optical, 3x4 theo hang
std::vector<uint16_t> depth_mm; // 0 = khong do duoc
bool empty() const { return depth_mm.empty(); }
};
struct VoxelNodeCache {
std::unordered_map<int, std::vector<float>> nodes; // id -> x,y,z,x,y,z...
struct Node {
std::vector<float> pts; // x,y,z,x,y,z... frame node, da gom voxel
NodeDepthView view; // chi khi clear_after_views > 0
};
std::unordered_map<int, Node> nodes;
// Diem node da cat theo dai z RONG (che do doc). Doi che do thi xoa cache.
bool wide = false;
// Cache co anh depth nho cua node chua. Doi tuy chon thi xoa cache.
bool views = false;
};
// Anh depth nho cua node tu SensorData (depth + camera model dau tien).
// `block`: canh khoi pixel. Khong co depth -> `out` rong.
void NodeDepthViewFromSensorData(const rtabmap::SensorData& data, int block,
NodeDepthView* out);
// "Nhin xuyen qua" (07/10): hoi cac node SAU lan cuoi mot voxel duoc thay xem
// vat do CON khong. Xet node MOI NHAT truoc -- lan nhin moi nhat quyet dinh:
// depth tai cho voxel ~ khoang cach toi voxel -> van con, GIU;
// depth XA hon voxel + sai so -> nhin xuyen qua;
// depth GAN hon -> bi che, khong biet, bo qua.
// Khong chua kieu RTAB-Map -- test duoc nhu VoxelAccumulator.
class VoxelCarver {
public:
VoxelCarver(double range_m, size_t need_views);
// `order` TANG dan theo thoi gian. base_to_map: pose node da toi uu, 3x4 theo
// hang (z da cong z node neu co). `view` phai song toi khi xong Gone().
void AddView(int order, const float base_to_map[12], const NodeDepthView* view);
// true = vat da roi di: >= need lan xuyen qua tu cac node sau `last_order`
// truoc khi gap mot node con thay no.
bool Gone(double x, double y, double z, int last_order);
size_t views() const { return views_.size(); }
private:
struct View {
int order;
float r[9]; // map <- optical, theo hang
float t[3];
const NodeDepthView* v;
};
const std::vector<int>& Near(int32_t cx, int32_t cy);
double range_;
size_t need_;
std::vector<View> views_;
std::unordered_map<uint64_t, std::vector<int>> cells_; // o 1 m -> chi so view
std::unordered_map<uint64_t, std::vector<int>> near_; // cache Near()
};
// Gom diem -> tap voxel. KHONG chua kieu nao cua RTAB-Map, nen test duoc ma
@@ -136,26 +205,37 @@ class VoxelHitCounter {
public:
explicit VoxelHitCounter(const VoxelExportOptions& opt);
void BeginNode();
// `order`: thu tu thoi gian cua node (tang dan) -- VoxelCarver hoi cac node
// SAU lan cuoi voxel duoc thay. Am = tu dem.
void BeginNode(int order = -1);
// Toa do trong frame MAP, met. Cung luat cat z / dai chi so voi
// VoxelAccumulator::AddPoint.
void AddPoint(double x, double y, double z);
void EndNode();
// Voxel co >= min_node_hits node -> dua qua VoxelAccumulator: giu nguyen
// luat giam mau khi cham tran, dau ra da sort.
void Finish(VoxelGrid* out);
// luat giam mau khi cham tran, dau ra da sort. `carver` khac null: bo them
// voxel ma cac node sau lan thay cuoi nhin xuyen qua.
void Finish(VoxelGrid* out, VoxelCarver* carver = nullptr);
size_t clamped() const { return clamped_; }
size_t stride() const { return stride_; }
size_t carved() const { return carved_; }
private:
struct Hit {
uint64_t key;
int32_t order;
bool operator<(const Hit& o) const { return key != o.key ? key < o.key : order < o.order; }
};
VoxelExportOptions opt_;
double inv_size_ = 10.0;
int order_ = -1;
std::vector<uint64_t> node_; // khoa cua node dang gom
std::vector<uint64_t> all_; // khoa DA khu trung theo node, cua moi node
std::vector<Hit> all_; // khoa DA khu trung theo node, cua moi node
size_t clamped_ = 0;
size_t stride_ = 1;
size_t carved_ = 0;
};
// Quet toan bo pose da toi uu va dung lai tap voxel tu dau.

View File

@@ -39,17 +39,23 @@ void CopyGrid(const cv::Mat& m, OccupancyGrid* out) {
StatusResponse BuildFromCache(rtabmap::LocalGridCache& cache,
const std::map<int, rtabmap::Transform>& poses,
double cell_size, double range_max,
const rtabmap::ParametersMap& slam_params,
OccupancyGrid* out) {
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"khong co pose nao de dung grid");
}
rtabmap::ParametersMap params;
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridCellSize(),
std::to_string(cell_size)));
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGrid3D(), "false"));
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridRangeMax(),
std::to_string(range_max)));
// Cach cap nhat o (GridGlobal/*: xac suat trung / truot / kep) THEO RTAB-Map
// dang chay (slam.yaml). Truoc 07/10 khong truyen -> luon mac dinh RTAB-Map:
// o da chac chiem can ~9 lan nhin xuyen qua moi xoa, nen nguoi dung lai roi
// di van nam tren ban do sau khi quay lai quet.
for (const auto& kv : slam_params) {
if (kv.first.rfind("GridGlobal/", 0) == 0) params.insert(kv);
}
params[rtabmap::Parameters::kGridCellSize()] = std::to_string(cell_size);
params[rtabmap::Parameters::kGrid3D()] = "false";
params[rtabmap::Parameters::kGridRangeMax()] = std::to_string(range_max);
rtabmap::OccupancyGrid grid(&cache, params);
grid.update(poses);
@@ -135,13 +141,14 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out) {
cache.add(kv.first, data.gridGroundCellsRaw(), data.gridObstacleCellsRaw(),
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
}
return BuildFromCache(cache, poses, 0.05, 12.0, out);
return BuildFromCache(cache, poses, 0.05, 12.0, slam.getParameters(), out);
}
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max,
OccupancyGrid* out,
const std::set<int>* only_ids) {
const std::set<int>* only_ids,
const std::map<std::string, std::string>* grid_params) {
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
bool opened = false;
try {
@@ -175,6 +182,10 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
with_grid++;
}
// Cach cap nhat o: theo nguoi goi (tham so dang chay), khong thi theo tham
// so DB da luu luc quet.
const rtabmap::ParametersMap slam_params =
grid_params != nullptr ? *grid_params : driver->getLastParameters();
driver->closeConnection(false);
if (with_grid == 0) {
@@ -182,7 +193,7 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
StatusCode::kFailedPrecondition,
"khong node nao co local grid -- ban do quet voi Grid/FromDepth sai?");
}
return BuildFromCache(cache, poses, cell_size, range_max, out);
return BuildFromCache(cache, poses, cell_size, range_max, slam_params, out);
}
} // namespace vslam

View File

@@ -90,6 +90,10 @@ const std::string& RtabmapSlam::database_path() const {
return impl_->cfg.database_path;
}
std::map<std::string, std::string> RtabmapSlam::rtabmap_parameters() const {
return impl_->rtabmap.getParameters();
}
Pose2D RtabmapSlam::map_correction() const {
std::lock_guard<std::mutex> lk(impl_->out_mu);
return impl_->map_correction;

View File

@@ -1,5 +1,6 @@
#include "vslam/voxel_export.h"
#include <rtabmap/core/CameraModel.h>
#include <rtabmap/core/Memory.h>
#include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/SensorData.h>
@@ -9,6 +10,7 @@
#include <opencv2/core.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iterator>
#include <map>
@@ -163,7 +165,10 @@ VoxelHitCounter::VoxelHitCounter(const VoxelExportOptions& opt) : opt_(opt) {
inv_size_ = 1.0 / opt_.emit_size_m;
}
void VoxelHitCounter::BeginNode() { node_.clear(); }
void VoxelHitCounter::BeginNode(int order) {
node_.clear();
order_ = order >= 0 ? order : order_ + 1;
}
void VoxelHitCounter::AddPoint(double x, double y, double z) {
uint64_t key = 0;
@@ -177,11 +182,13 @@ void VoxelHitCounter::EndNode() {
// la mot lan "thay".
std::sort(node_.begin(), node_.end());
node_.erase(std::unique(node_.begin(), node_.end()), node_.end());
all_.insert(all_.end(), node_.begin(), node_.end());
for (const uint64_t k : node_) all_.push_back(Hit{k, order_});
node_.clear();
}
void VoxelHitCounter::Finish(VoxelGrid* out) {
void VoxelHitCounter::Finish(VoxelGrid* out, VoxelCarver* carver) {
// Sort theo (khoa, order): moi khoa mot doan, phan tu CUOI doan la node
// cuoi cung thay voxel do.
std::sort(all_.begin(), all_.end());
// Cat z da lam o AddPoint. Tat no o day: tam voxel co the roi ra ngoai
// [z_min, z_max] khi z_min khong trung bien voxel, va voxel se mat oan.
@@ -191,14 +198,20 @@ void VoxelHitCounter::Finish(VoxelGrid* out) {
VoxelAccumulator acc(o);
const size_t need = std::max<size_t>(opt_.min_node_hits, 1);
const double s = opt_.emit_size_m;
carved_ = 0;
for (size_t i = 0; i < all_.size();) {
size_t j = i + 1;
while (j < all_.size() && all_[j] == all_[i]) ++j;
while (j < all_.size() && all_[j].key == all_[i].key) ++j;
if (j - i >= need) {
int32_t x = 0, y = 0, z = 0;
UnpackKey(all_[i], &x, &y, &z);
UnpackKey(all_[i].key, &x, &y, &z);
// Tam voxel -> luong tu hoa lai ra DUNG chi so do.
acc.AddPoint((x + 0.5) * s, (y + 0.5) * s, (z + 0.5) * s);
const double cx = (x + 0.5) * s, cy = (y + 0.5) * s, cz = (z + 0.5) * s;
if (carver != nullptr && carver->Gone(cx, cy, cz, all_[j - 1].order)) {
++carved_;
} else {
acc.AddPoint(cx, cy, cz);
}
}
i = j;
}
@@ -206,6 +219,143 @@ void VoxelHitCounter::Finish(VoxelGrid* out) {
stride_ = acc.stride();
}
// ---------------- Nhin xuyen qua ----------------
namespace {
// Khoa o 1 m cho chi so node theo vi tri camera.
inline uint64_t CellKey(int32_t cx, int32_t cy) {
return (static_cast<uint64_t>(static_cast<uint32_t>(cx)) << 32) | static_cast<uint32_t>(cy);
}
} // namespace
VoxelCarver::VoxelCarver(double range_m, size_t need_views)
: range_(range_m > 0.0 ? range_m : 3.5), need_(std::max<size_t>(need_views, 1)) {}
void VoxelCarver::AddView(int order, const float b[12], const NodeDepthView* view) {
if (view == nullptr || view->empty()) return;
// map <- optical = (map <- base) * (base <- optical).
const float* c = view->cam;
View w;
w.order = order;
w.v = view;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
w.r[i * 3 + j] = b[i * 4 + 0] * c[0 * 4 + j] + b[i * 4 + 1] * c[1 * 4 + j] +
b[i * 4 + 2] * c[2 * 4 + j];
}
w.t[i] = b[i * 4 + 0] * c[3] + b[i * 4 + 1] * c[7] + b[i * 4 + 2] * c[11] + b[i * 4 + 3];
}
const int idx = static_cast<int>(views_.size());
views_.push_back(w);
cells_[CellKey(static_cast<int32_t>(std::floor(w.t[0])),
static_cast<int32_t>(std::floor(w.t[1])))].push_back(idx);
near_.clear();
}
const std::vector<int>& VoxelCarver::Near(int32_t cx, int32_t cy) {
const uint64_t key = CellKey(cx, cy);
auto it = near_.find(key);
if (it != near_.end()) return it->second;
std::vector<int> v;
const int32_t r = static_cast<int32_t>(std::ceil(range_));
for (int32_t dx = -r; dx <= r; ++dx) {
for (int32_t dy = -r; dy <= r; ++dy) {
auto c = cells_.find(CellKey(cx + dx, cy + dy));
if (c != cells_.end()) v.insert(v.end(), c->second.begin(), c->second.end());
}
}
// Chi so view tang cung order (AddView theo thu tu thoi gian).
std::sort(v.begin(), v.end());
return near_.emplace(key, std::move(v)).first->second;
}
bool VoxelCarver::Gone(double x, double y, double z, int last_order) {
const std::vector<int>& cand =
Near(static_cast<int32_t>(std::floor(x)), static_cast<int32_t>(std::floor(y)));
size_t through = 0;
// MOI NHAT truoc; dung khi toi lan voxel duoc thay cuoi.
for (auto it = cand.rbegin(); it != cand.rend(); ++it) {
const View& w = views_[static_cast<size_t>(*it)];
if (w.order <= last_order) break;
const float qx = static_cast<float>(x) - w.t[0];
const float qy = static_cast<float>(y) - w.t[1];
const float qz = static_cast<float>(z) - w.t[2];
// optical = R^T * q
const float zc = w.r[2] * qx + w.r[5] * qy + w.r[8] * qz;
if (zc < 0.25f || zc > range_) continue;
const float xc = w.r[0] * qx + w.r[3] * qy + w.r[6] * qz;
const float yc = w.r[1] * qx + w.r[4] * qy + w.r[7] * qz;
const NodeDepthView& v = *w.v;
const float u = v.fx * xc / zc + v.cx;
const float vv = v.fy * yc / zc + v.cy;
if (!(u >= 0.0f) || !(vv >= 0.0f) || u >= static_cast<float>(v.w) ||
vv >= static_cast<float>(v.h)) {
continue; // ngoai khung nhin
}
const uint16_t dmm = v.depth_mm[static_cast<size_t>(vv) * static_cast<size_t>(v.w) +
static_cast<size_t>(u)];
if (dmm == 0) continue;
const float d = static_cast<float>(dmm) * 0.001f;
// Sai so depth stereo tang theo z^2 (D410: ~2 cm o 2 m, ~9 cm o 4 m) +
// nua voxel + sai pose.
const float margin = 0.10f + 0.03f * zc * zc;
if (d > zc + margin) {
if (++through >= need_) return true; // nhin xuyen qua: vat da di
} else if (d >= zc - margin) {
return false; // van thay: GIU
}
// Gan hon: bi vat khac che, khong biet.
}
return false;
}
void NodeDepthViewFromSensorData(const rtabmap::SensorData& data, int block,
NodeDepthView* out) {
out->depth_mm.clear();
const cv::Mat& d = data.depthOrRightRaw();
if (d.empty() || data.cameraModels().empty() || block < 1) return;
if (d.type() != CV_16UC1 && d.type() != CV_32FC1) return;
const rtabmap::CameraModel& m = data.cameraModels()[0];
if (m.fx() <= 0.0 || m.fy() <= 0.0) return;
// Mo hinh camera co the theo anh khac co (depth da giam mau): quy ve co depth.
const double sx = m.imageWidth() > 0 ? static_cast<double>(d.cols) / m.imageWidth() : 1.0;
const double sy = m.imageHeight() > 0 ? static_cast<double>(d.rows) / m.imageHeight() : 1.0;
out->w = d.cols / block;
out->h = d.rows / block;
if (out->w <= 0 || out->h <= 0) return;
out->fx = static_cast<float>(m.fx() * sx / block);
out->fy = static_cast<float>(m.fy() * sy / block);
out->cx = static_cast<float>((m.cx() * sx + 0.5) / block - 0.5);
out->cy = static_cast<float>((m.cy() * sy + 0.5) / block - 0.5);
const rtabmap::Transform& L = m.localTransform(); // base <- optical
const float c[12] = {L.r11(), L.r12(), L.r13(), L.x(), L.r21(), L.r22(), L.r23(), L.y(),
L.r31(), L.r32(), L.r33(), L.z()};
std::copy(c, c + 12, out->cam);
out->depth_mm.assign(static_cast<size_t>(out->w) * out->h, 0);
for (int by = 0; by < out->h; ++by) {
for (int bx = 0; bx < out->w; ++bx) {
// NHO NHAT cua khoi: than trong cho viec xoa.
uint32_t best = 0;
for (int y = by * block; y < (by + 1) * block; ++y) {
for (int x = bx * block; x < (bx + 1) * block; ++x) {
uint32_t mm = 0;
if (d.type() == CV_16UC1) {
mm = d.at<uint16_t>(y, x);
} else {
const float f = d.at<float>(y, x);
if (std::isfinite(f) && f > 0.0f) mm = static_cast<uint32_t>(f * 1000.0f + 0.5f);
}
if (mm > 0 && (best == 0 || mm < best)) best = mm;
}
}
out->depth_mm[static_cast<size_t>(by) * out->w + bx] =
static_cast<uint16_t>(std::min<uint32_t>(best, 65535u));
}
}
}
void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
const std::vector<VoxelIndex>& now,
std::vector<VoxelIndex>* added,
@@ -348,17 +498,22 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
node_opt.z_min = opt.z_min - 3.0;
node_opt.z_max = opt.z_max + 3.0;
}
if (cache->wide != use_floor) {
const bool carve = opt.clear_after_views > 0;
if (cache->wide != use_floor || cache->views != carve) {
cache->nodes.clear();
cache->wide = use_floor;
cache->views = carve;
}
// min_node_hits > 1: dem so node thay moi voxel (loc diem bay, nguoi di
// ngang). = 1: duong cu, re hon.
const bool count_hits = opt.min_node_hits > 1;
// ngang). Xoa vat da roi di cung can dem (biet node CUOI thay voxel). Con
// lai: duong cu, re hon.
const bool count_hits = opt.min_node_hits > 1 || carve;
VoxelAccumulator acc(acc_opt);
VoxelHitCounter hits(acc_opt);
VoxelCarver carver(opt.clear_range_m, opt.clear_after_views);
size_t nodes_used = 0, fetched = 0, pending = 0, no_points = 0;
int order = 0; // thu tu thoi gian: id node RTAB-Map tang theo thoi gian
for (const auto& kv : poses) {
if (kv.second.isNull()) continue;
@@ -374,11 +529,15 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
// ⚠️ 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, node_opt, &pts);
it = cache->nodes.emplace(kv.first, std::move(pts)).first;
VoxelNodeCache::Node n;
NodeCloudFromSensorData(data, node_opt, &n.pts);
// Khoi 4x4 tren depth 320x240 -> 80x60 (~10 KB/node): ~0.9 do moi o,
// 4.5 cm o 3 m -- co voxel 5 cm.
if (carve) NodeDepthViewFromSensorData(data, 4, &n.view);
it = cache->nodes.emplace(kv.first, std::move(n)).first;
}
const std::vector<float>& pts = it->second;
const std::vector<float>& pts = it->second.pts;
const int node_order = order++;
if (pts.empty()) {
++no_points;
continue;
@@ -397,7 +556,14 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
if (zi != opt.node_z->end()) z_off = zi->second;
}
if (count_hits) hits.BeginNode();
if (carve) {
// Camera cua node nay de hoi "nhin xuyen qua" -- cung pose (va z node)
// voi diem cua no.
const float b[12] = {r00, r01, r02, tx, r10, r11, r12, ty,
r20, r21, r22, static_cast<float>(tz + z_off)};
carver.AddView(node_order, b, &it->second.view);
}
if (count_hits) hits.BeginNode(node_order);
for (size_t i = 0; i + 2 < pts.size(); i += 3) {
const float px = pts[i], py = pts[i + 1], pz = pts[i + 2];
const double wx = r00 * px + r01 * py + r02 * pz + tx;
@@ -431,10 +597,20 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
"hoac khong co camera");
}
if (count_hits) hits.Finish(out);
const auto t_fin = std::chrono::steady_clock::now();
if (count_hits) hits.Finish(out, carve ? &carver : nullptr);
else acc.Finish(out);
const size_t stride = count_hits ? hits.stride() : acc.stride();
const size_t clamped = count_hits ? hits.clamped() : acc.clamped();
if (carve) {
const double ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t_fin)
.count();
VSLAM_INFO_THROTTLE(30.0, "slam: xoa " << hits.carved()
<< " voxel vat da roi di (>= " << opt.clear_after_views
<< " node sau nhin xuyen qua, " << carver.views() << " node co depth, "
<< ms << " ms)");
}
// 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.

View File

@@ -12,7 +12,7 @@ const MAGIC = 0x314C5356; // 'VSL1' little-endian
// Phien ban ma nguon giao dien. TANG khi doi app.js / app3d.js / style.css.
// Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con
// cache ban cu".
const UI_VERSION = '2026-10-06a';
const UI_VERSION = '2026-10-07a';
// ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau.
//
@@ -393,6 +393,7 @@ function rasterize(map, pal) {
function onState(s) {
state.pose = s.pose;
noteStatePose(s);
// Khong co truong nay = server khong bu duoc do tre scan. Dat null chu
// khong dat {0,0,0}: mot delta 0 gia mao la "da bu", con null thi lop ve
// biet la chua co gi va dung pose hien tai nhu truoc.
@@ -615,6 +616,61 @@ function composePose(a, d) {
};
}
// --- Pose HIEN THI: robot troi muot giua cac khung state ---------------------
//
// Server gui pose 10 Hz (system.yaml status_rate_hz) con trang ve ~60 Hz. Dat
// thang pose moi nhat thi robot NHAY tung buoc 100 ms -- 5 cm / 4.6 do o
// 0.5 m/s, 0.8 rad/s -- va nhay them moi lan SLAM chinh map_correction. O day:
// du doan theo van toc odom toi da DISP_LEAD_MAX giay, roi TRUOT ve dich voi
// hang so DISP_TAU. Xa hon DISP_SNAP (vua chot dinh vi lai) thi dat thang.
//
// CHI la hien thi: so lieu (px/py/pyaw, gap voi ground truth) van doc
// `state.pose` THAT.
const DISP_TAU = 0.08; // s
const DISP_LEAD_MAX = 0.15; // s
const DISP_SNAP_M = 1.0, DISP_SNAP_RAD = 0.8;
const disp = { pose: null, t: 0, rx: 0, vx: 0, vyaw: 0 };
function wrapPi(a) { return Math.atan2(Math.sin(a), Math.cos(a)); }
// Giay, don dieu. `performance` co o moi trinh duyet, nhung KHONG co trong
// sandbox vm cua test/www -- lui ve Date.now().
function nowSec() {
return (typeof performance !== 'undefined' ? performance.now() : Date.now()) / 1000;
}
// Goi moi khung state: luc toi + van toc odom (he than robot).
function noteStatePose(s) {
disp.rx = nowSec();
const o = s.odom || {};
disp.vx = Math.max(-1.5, Math.min(1.5, Number(o.vx) || 0));
disp.vyaw = Math.max(-2.0, Math.min(2.0, Number(o.vyaw) || 0));
}
// Goi MOT lan moi khung ve (draw()).
function displayPose() {
const p = state.pose;
if (!p) return null;
const now = nowSec();
const lead = Math.min(Math.max(now - disp.rx, 0), DISP_LEAD_MAX);
const yaw = p.yaw + disp.vyaw * lead;
const mid = p.yaw + 0.5 * disp.vyaw * lead;
const tx = p.x + disp.vx * lead * Math.cos(mid);
const ty = p.y + disp.vx * lead * Math.sin(mid);
const d = disp.pose;
if (!d || Math.hypot(tx - d.x, ty - d.y) > DISP_SNAP_M ||
Math.abs(wrapPi(yaw - d.yaw)) > DISP_SNAP_RAD) {
disp.pose = { x: tx, y: ty, yaw: wrapPi(yaw) };
} else {
const a = 1 - Math.exp(-Math.max(now - disp.t, 0) / DISP_TAU);
d.x += a * (tx - d.x);
d.y += a * (ty - d.y);
d.yaw = wrapPi(d.yaw + a * wrapPi(yaw - d.yaw));
}
disp.t = now;
// z / nghieng / sigma: theo pose that, chi x-y-yaw duoc lam muot.
return { ...p, x: disp.pose.x, y: disp.pose.y, yaw: disp.pose.yaw };
}
// Pose de ve MOT LOP DU LIEU, khong phai pose robot.
//
// Moi lop toi theo nhip rieng (cloud 2 Hz, scan 10 Hz) con trang ve lai moi
@@ -751,7 +807,7 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
// Dang DINH VI LAI (--slam-reloc): robot TAM o goc map (odom tu 0) -> ve MO.
// Chot xong moi nhay ve cho that. Dong chu trang thai nam o #relocBanner.
const faded = state.relocPending && robotPose === state.pose;
const faded = state.relocPending && robotPose === state.dispPose;
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, pal.robot, faded ? 0.35 : 1.0, pal);
}
}
@@ -792,6 +848,9 @@ function updateSlamLabel() {
}
function draw() {
// Pose HIEN THI cho MOI khung ve duoi day -- tinh MOT lan moi khung hinh, vi
// displayPose() truot theo thoi gian giua hai lan goi.
state.dispPose = displayPose();
// Goi o DAY chu khong trong draw3d(): o so sanh uoc luong voi ground truth
// phai chay ca khi dang xem khung 2D.
updateGapChip();
@@ -807,7 +866,7 @@ function draw() {
// Khung phai VAN phai chay khi dang chia doi.
if (split) {
updateSlamLabel();
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap',
drawScene(cvR, ctxR, state.map, state.mapImage, state.dispPose, true, 'lyMap',
PALETTE.slam);
} else if (split3d) {
// Khong co canvas thu hai o che do nay: draw3d() da ve ca hai nua. Chi
@@ -821,10 +880,10 @@ function draw() {
updateSlamLabel();
// TRAI = THE GIOI: ban do that + pose THAT. Day la khung de LAI.
drawScene(cv, ctx, state.worldMap, state.worldMapImage,
state.gt || state.pose, false, 'lyWorld', PALETTE.world);
state.gt || state.dispPose, false, 'lyWorld', PALETTE.world);
// PHAI = SLAM: ban do dang dung + pose UOC LUONG. Khung de xem quet toi
// dau, va lech bao nhieu so voi khung trai.
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap',
drawScene(cvR, ctxR, state.map, state.mapImage, state.dispPose, true, 'lyMap',
PALETTE.slam);
} else {
// Mot khung: uu tien ban do SLAM neu co, khong thi ban do the gioi.
@@ -832,7 +891,7 @@ function draw() {
drawScene(cv, ctx,
haveSlam ? state.map : state.worldMap,
haveSlam ? state.mapImage : state.worldMapImage,
state.pose, true, haveSlam ? 'lyMap' : 'lyWorld',
state.dispPose, true, haveSlam ? 'lyMap' : 'lyWorld',
haveSlam ? PALETTE.slam : PALETTE.world);
}
requestAnimationFrame(draw);
@@ -1257,7 +1316,12 @@ function updateGapChip() {
// Sai so du lieu va khoang cach ve la HAI so. Bang nhau nghia la hinh ve
// trung thuc va cai nhin thay la sai so that. Khac nhau nghia la con loi o
// tang hien thi -- da xay ra hai lan (thieu lop boc, va quen laser_x).
const drift = dDraw !== null && Math.abs(dDraw - dData) > 0.01;
//
// So voi pose DA DUA DI VE (displayPose() lam muot co chu dich, lech pose
// that vai cm khi dang chay) -- van bat duoc loi lop boc / laser_x.
const drawn = state.drawnPose || state.pose;
const dRef = state.gt ? Math.hypot(drawn.x - state.gt.x, drawn.y - state.gt.y) : dData;
const drift = dDraw !== null && Math.abs(dDraw - dRef) > 0.01;
el.textContent = 'gap ' + dData.toFixed(3) + ' m' +
(drift ? ' / ve ' + dDraw.toFixed(3) : '');
el.title = drift
@@ -1275,7 +1339,10 @@ for (const b of document.querySelectorAll('.vbtn')) {
function draw3d() {
if (state.robot) v3dSetShape(state.robot);
if (state.pose) v3dSetPose(V3D.robotGroup, state.pose);
if (state.dispPose) {
v3dSetPose(V3D.robotGroup, state.dispPose);
state.drawnPose = state.dispPose; // updateGapChip() so voi pose NAY
}
// Chua dinh vi xong: robot TAM o goc map -> ve MO. Nho do mo goc cua tung
// vat lieu (vai overlay von trong suot) de tra lai dung khi da chot. Chay moi
// khung vi v3dSetShape() co the tao vat lieu moi.
@@ -1307,9 +1374,9 @@ function draw3d() {
}
v3dSetScan(on('lyScan') ? state.scan : null,
anchorPose(state.pose, state.scanPose), state.robot);
anchorPose(state.dispPose, state.scanPose), state.robot);
v3dSetCloud(on('lyCloud') ? state.cloud : null,
anchorPose(state.pose, state.cloudPose));
anchorPose(state.dispPose, state.cloudPose));
// THE GIOI: tuong 3D dung tu ban do mo phong -- day la phan "Gazebo".
// Dung MOT lan (ban do the gioi la tinh), roi chi bat/tat.