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

@@ -69,7 +69,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
Reject(l, "sensors.yaml lidar",
{"host", "port", "expected_rate_hz", "range_min", "range_max",
"stamp_mismatch_warn", "sector_masks",
"angle_offset_deg", "angle_flip", "filters"});
"angle_offset_deg", "angle_flip", "filters",
"stamp_offset_sec", "deskew"});
if (!r.ok()) return r;
}
out->sanitizer.range_min = l.get<double>("range_min", 0.05);
@@ -94,6 +95,11 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
l.get<double>("angle_offset_deg", out->lidar_driver.angle_offset_deg);
out->lidar_driver.inverted =
l.get<bool>("angle_flip", out->lidar_driver.inverted);
// Gio scan so voi odometry va chinh meo -- do tren ban do that, xem
// sensors.yaml.
out->lidar_driver.stamp_offset_sec =
l.get<double>("stamp_offset_sec", out->lidar_driver.stamp_offset_sec);
out->lidar_driver.deskew = l.get<bool>("deskew", out->lidar_driver.deskew);
// --- Bon bo loc scan ---
const ConfigNode ft = l["filters"];
@@ -584,7 +590,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
const StatusResponse r =
Reject(v, "slam.yaml voxel",
{"emit_size_m", "z_min", "z_max", "max_cells", "delta_max_ratio",
"obstacle_z_min", "obstacle_z_max", "min_node_hits"});
"obstacle_z_min", "obstacle_z_max", "min_node_hits",
"clear_after_views"});
if (!r.ok()) return r;
out->voxel.emit_size_m = v.get<double>("emit_size_m", out->voxel.emit_size_m);
@@ -605,6 +612,13 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"slam.yaml voxel.min_node_hits phai >= 1");
}
out->voxel.min_node_hits = static_cast<size_t>(hits);
const int clear = v.get<int>("clear_after_views",
static_cast<int>(out->voxel.clear_after_views));
if (clear < 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml voxel.clear_after_views phai >= 0 (0 = tat)");
}
out->voxel.clear_after_views = static_cast<size_t>(clear);
if (out->voxel.emit_size_m <= 0.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,

View File

@@ -64,6 +64,9 @@ struct VoxelConfig {
// Voxel phai duoc it nhat bay nhieu node khac nhau thay moi giu -- ap cho ca
// ban do 3D lan lop vat can 2D. 1 = giu moi voxel.
size_t min_node_hits = 1;
// Xoa voxel ma bay nhieu node SAU lan thay cuoi nhin xuyen qua (vat da roi
// di). 0 = tat. Xem slam.yaml khoi `voxel:`.
size_t clear_after_views = 0;
};
// Di tren doc (G4). Doc tu khoi `slope:` trong slam.yaml. enabled = false thi

View File

@@ -551,8 +551,10 @@ StatusResponse Runtime::Start() {
if (opts_.slam_reloc) {
const auto t0 = std::chrono::steady_clock::now();
OccupancyGrid g;
const StatusResponse gst =
ExportOccupancyGridFromDb(slam_->database_path(), 0.05, reloc_cfg_.max_range, &g);
// Cung cach cap nhat o (GridGlobal/*) voi ban do dang hien.
const std::map<std::string, std::string> gp = slam_->rtabmap_parameters();
const StatusResponse gst = ExportOccupancyGridFromDb(
slam_->database_path(), 0.05, reloc_cfg_.max_range, &g, nullptr, &gp);
if (!gst.ok()) {
return StatusResponse::Error(gst.code, "--slam-reloc: dung luoi tu DB: " + gst.message);
}
@@ -627,6 +629,7 @@ StatusResponse Runtime::Start() {
vo.z_max = cfg_->voxel.z_max;
vo.max_cells = cfg_->voxel.max_cells;
vo.min_node_hits = cfg_->voxel.min_node_hits;
vo.clear_after_views = cfg_->voxel.clear_after_views;
// Nap depth CUA MOI node (mac dinh 40 node/lan xuat): o day chi xuat
// MOT lan truoc khi chot -> 40/971 node chi la mot manh quanh goc map,
// trong nhu PCL cua phien dinh vi. Doi vai giay luc khoi dong; cache
@@ -727,6 +730,24 @@ StatusResponse Runtime::Start() {
<< "Can IMU >= 100 Hz -- 10 Hz cho sai ~19 cm moi doc 1.5 m (sim G3).");
}
// Chinh meo scan: CHI LiDAR that (--live, --replay ban ghi that). Scan sim
// chup tuc thoi -- chinh meo o do la LAM meo.
deskew_on_ = cfg_->lidar_driver.deskew && opts_.source != SourceKind::kSim;
if (deskew_on_) {
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &laser_to_base_static_)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"deskew: robot.yaml khong co duong laser -> base_link");
}
const LidarConfig& lc = cfg_->lidar_driver;
sweep_.start_rad = lc.angle_offset_deg * M_PI / 180.0;
sweep_.dir = lc.inverted ? -1 : +1;
sweep_.period_s = lc.scan_freq_hz > 0.0 ? 1.0 / lc.scan_freq_hz : 0.04;
VSLAM_INFO("lidar: chinh meo scan BAT -- vong " << sweep_.period_s * 1e3 << " ms, bat dau "
<< lc.angle_offset_deg << " do, goc " << (sweep_.dir < 0 ? "GIAM" : "TANG")
<< " theo thoi gian; stamp_offset " << lc.stamp_offset_sec * 1e3
<< " ms. Ban cho SLAM / dinh vi lai, an toan + web giu scan tho.");
}
{
const StatusResponse st = Wire();
if (!st.ok()) return st;
@@ -1474,6 +1495,7 @@ void Runtime::SlamLoop() {
vo.z_max = cfg_->voxel.z_max;
vo.max_cells = cfg_->voxel.max_cells;
vo.min_node_hits = cfg_->voxel.min_node_hits;
vo.clear_after_views = cfg_->voxel.clear_after_views;
VoxelGrid vg;
const auto t_vox = std::chrono::steady_clock::now();

View File

@@ -561,6 +561,10 @@ class Runtime {
// Tinh, doc-only sau Start(): base_link <- laser_link / camera optical.
Transform laser_to_base_static_ = TransformIdentity();
Transform cam_to_base_static_ = TransformIdentity();
// Chinh meo scan (sensors.yaml `lidar.deskew`, CHI LiDAR that). Doc-only sau
// Start(); can laser_to_base_static_ o tren.
bool deskew_on_ = false;
SweepTiming sweep_;
bool have_cam_to_base_ = false;
// CHI luong slam: lan giai do thi z cuoi; da neo z lan nao chua (lan DAU
// sau khoi dong / dinh vi lai thi DAT THANG z ban do, khong qua cong).

View File

@@ -41,9 +41,22 @@ StatusResponse Runtime::Wire() {
auto copy = std::make_shared<LaserScan>(*s);
sanitizer_->Apply(copy.get());
// Di tren doc: ban BU NGHIENG + bo tia cham san cho SLAM / dinh vi lai.
// An toan va web giu ban tho. Tat thi hai con tro la MOT.
// Ban cho SLAM / dinh vi lai: CHINH MEO (LiDAR that) roi BU NGHIENG (doc).
// An toan va web giu ban tho. Tat ca hai thi hai con tro la MOT.
LaserScanPtr slam_scan = copy;
if (deskew_on_) {
// w ~ gyro 200 Hz qua EKF (lech 0.008 rad/s x 40 ms: khong dang ke),
// v theo encoder. Kep de mot mau van toc hong khong be cong scan.
double w = 0.0, v = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
w = std::max(-2.0, std::min(2.0, ekf_->vyaw()));
v = std::max(-1.0, std::min(1.0, ekf_->vx()));
}
auto dsk = std::make_shared<LaserScan>();
DeskewScan(*copy, laser_to_base_static_, sweep_, w, v, dsk.get());
slam_scan = dsk;
}
if (slope_on_ && cfg_->slope.level_scan) {
Pose2D od;
double z = 0.0;
@@ -57,7 +70,7 @@ StatusResponse Runtime::Wire() {
auto lv = std::make_shared<LaserScan>();
{
std::lock_guard<std::mutex> lk(elev_mu_);
LevelScan(*copy, laser_to_base_static_, roll, pitch,
LevelScan(*slam_scan, laser_to_base_static_, roll, pitch,
cfg_->robot.geometry().wheel_radius, od, z, elev_.get(), level_cfg_,
lv.get(), &level_stats_);
// Ti le tia giu lai (cong don tu luc chay) -- san phang phai ~100%.

View File

@@ -72,6 +72,22 @@ lidar:
# |(t_cuoi - t_dau) - scan_time| > nguong nay.
stamp_mismatch_warn: 0.005
# --- Gio cua scan so voi odometry: DO tren ban do that ---
# Driver dong dau scan luc NHAN XONG vong quet. ICP scan luc robot dang QUAY
# voi scan gan do luc gan dung yen (ban do 28/09 + 01/10, 88 + 179 cap): scan
# tre +55..57 ms so voi odometry SAU khi chinh meo (+72..79 ms neu khong).
# Quay 0.8 rad/s ma khong bu -> moi scan lech 2.5-3.5 do, tuong dup sau moi
# lan quay. Doi phan cung / driver thi do lai.
stamp_offset_sec: -0.055
# Chinh meo: moi tia chup o mot thoi diem khac trong vong quet 40 ms (25 Hz);
# quay 0.8 rad/s thi tia dau va tia cuoi lech 1.8 do. Dua moi tia ve khung
# robot luc stamp theo w, v cua EKF. Chieu quet DO tren ban do that: goc GIAM
# theo thoi gian khi angle_flip: true (vong bat dau o angle_offset_deg, phia
# sau); chieu nguoc lai lam scan khop TE hon. Chi LiDAR that (--live,
# --replay) -- scan sim chup tuc thoi. Ban cho SLAM / dinh vi lai; an toan va
# web van dung scan tho.
deskew: true
# ============ BON BO LOC SCAN ============
# Chay TREN scan tho, truoc ScanSanitizer. Nguon: lakibeam.yaml cua
# base_kit -- bo tham so da duoc chinh tren chinh con robot nay.

View File

@@ -170,6 +170,15 @@ voxel:
# Tuong va ban ghe dung yen thi nhieu node thay nen van giu.
min_node_hits: 3
# LAN NHIN MOI NHAT QUYET DINH (07/10). Truoc day lop nay CHI THEM: 3 nguoi
# dung tren duong luc quet thanh vat can vinh vien, quay lai quet van con.
# Gio: voxel ma >= bay nhieu node SAU lan thay cuoi nhin XUYEN qua (depth xa
# hon voxel + 0.10 + 0.03 z^2 m) va khong node nao trong do con thay -> XOA,
# ca khoi ban do 3D lan lop vat can 2D. Bi che (depth gan hon) thi khong tinh
# -- khong biet thi khong xoa. Ap ca luc quet lan luc mo ban do da luu.
# 0 = tat (chi them, nhu truoc).
clear_after_views: 2
# ============ VONG DONG XA (chi khi quet) ============
# Phat hien ke can cua RTAB-Map chi xet node trong 50 buoc do thi
# (RGBD/ProximityMaxGraphDepth), nen quay lai cho cu sau mot vong DAI thi
@@ -300,6 +309,16 @@ rtabmap:
Grid/CellSize: "0.05"
Grid/RangeMax: "12.0"
Grid/RayTracing: "true"
# Luoi 2D theo LAN NHIN MOI NHAT (07/10). Moi o cong log-odds: trung +0.85,
# truot (tia di xuyen qua) -0.62, kep trong [-1.39, +1.39]. Mac dinh RTAB-Map
# kep +3.5 va truot -0.41: o da chac chiem can ~9 lan nhin xuyen qua moi xoa
# -> nguoi dung lai roi di, quay lai quet van con tren ban do. Bo nay: 3 lan
# xuyen qua -> trong, 2 lan thay vat -> chiem. Doi lai: vat rat manh (chan
# ghe) co the chap chon khi tia luot sat ben canh.
GridGlobal/ProbHit: "0.7"
GridGlobal/ProbMiss: "0.35"
GridGlobal/ProbClampingMin: "0.2"
GridGlobal/ProbClampingMax: "0.8"
Grid/3D: "false"
Grid/DepthDecimation: "4"

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.

View File

@@ -6,6 +6,7 @@
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
@@ -232,6 +233,102 @@ TEST(ScanLeveler, ScanLakiBeam0Den2PiGiuCaHaiNua) {
}
}
namespace {
// Phong chu nhat |x| <= 4, |y| <= 3 (khung laser luc stamp). Tia tu (ox, oy)
// huong th -> khoang cach toi tuong.
double RoomRay(double ox, double oy, double th) {
const double c = std::cos(th), s = std::sin(th);
double t = 1e9;
if (c > 1e-12) t = std::min(t, (4.0 - ox) / c);
if (c < -1e-12) t = std::min(t, (-4.0 - ox) / c);
if (s > 1e-12) t = std::min(t, (3.0 - oy) / s);
if (s < -1e-12) t = std::min(t, (-3.0 - oy) / s);
return t;
}
// Scan kieu LakiBeam (1440 tia, [0, 2pi), quat mu 90 do phia sau) chup khi
// robot quay w, tien v: tia i chup truoc stamp `lag` giay, luc do robot lui
// v*lag va quay -w*lag so voi luc stamp.
LaserScan LakiScan(const SweepTiming& tm, double w, double v) {
const size_t n = 1440;
const double inc = 2.0 * M_PI / static_cast<double>(n);
LaserScan s;
s.angle_min = 0.0f;
s.angle_increment = static_cast<float>(inc);
s.angle_max = static_cast<float>(2.0 * M_PI - inc);
s.range_min = 0.05f;
s.range_max = 30.0f;
s.ranges.assign(n, std::numeric_limits<float>::infinity());
for (size_t i = 0; i < n; ++i) {
const double a = static_cast<double>(i) * inc;
if (std::fabs(NormalizeAngle(a - M_PI)) < 45 * kDeg) continue; // quat mu
double f = std::fmod(tm.dir > 0 ? a - tm.start_rad : tm.start_rad - a, 2.0 * M_PI);
if (f < 0.0) f += 2.0 * M_PI;
const double lag = tm.period_s * (1.0 - f / (2.0 * M_PI));
const double yaw = -w * lag;
s.ranges[i] = static_cast<float>(RoomRay(-v * lag, 0.0, a + yaw));
}
return s;
}
// Sai lech |r - r_dung| tren cac o ca hai cung huu han; tra trung vi va p95.
void RangeErr(const LaserScan& got, const LaserScan& ref, double* med, double* p95) {
std::vector<double> e;
for (size_t i = 0; i < ref.ranges.size(); ++i) {
if (std::isfinite(got.ranges[i]) && std::isfinite(ref.ranges[i])) {
e.push_back(std::fabs(got.ranges[i] - ref.ranges[i]));
}
}
std::sort(e.begin(), e.end());
*med = e.empty() ? 1e9 : e[e.size() / 2];
*p95 = e.empty() ? 1e9 : e[e.size() * 95 / 100];
}
} // namespace
TEST(ScanLeveler, ChinhMeoDungYenThiGiuNguyen) {
const SweepTiming tm{178.75 * kDeg, -1, 0.04};
const LaserScan in = LakiScan(tm, 0.0, 0.0);
LaserScan out;
DeskewScan(in, LaserToBase(), tm, 0.0, 0.0, &out);
ASSERT_EQ(out.ranges.size(), in.ranges.size());
for (size_t i = 0; i < in.ranges.size(); ++i) {
if (std::isfinite(in.ranges[i])) {
EXPECT_NEAR(out.ranges[i], in.ranges[i], 1e-4) << "tia " << i;
} else {
EXPECT_TRUE(std::isinf(out.ranges[i])) << "tia " << i;
}
}
}
TEST(ScanLeveler, ChinhMeoKhiQuayVaChayKhopScanDungYen) {
// Robot quay 0.8 rad/s (toi da tay cam) va tien 0.5 m/s: scan tho lech scan
// dung yen tai stamp; chinh meo dung chieu quet phai keo ve gan nhu trung.
const SweepTiming tm{178.75 * kDeg, -1, 0.04};
const LaserScan ref = LakiScan(tm, 0.0, 0.0);
const LaserScan raw = LakiScan(tm, 0.8, 0.5);
double med_raw = 0, p95_raw = 0;
RangeErr(raw, ref, &med_raw, &p95_raw);
LaserScan out;
DeskewScan(raw, LaserToBase(), tm, 0.8, 0.5, &out);
double med = 0, p95 = 0;
RangeErr(out, ref, &med, &p95);
EXPECT_GT(p95_raw, 0.05); // khong chinh: lech ro
EXPECT_LT(med, 0.005);
EXPECT_LT(p95, 0.02);
EXPECT_LT(p95, p95_raw / 4.0);
// Sai chieu quet thi KHONG keo ve duoc -- chieu la thu phai do (07/10: do
// tren ban do that, dir -1).
SweepTiming wrong = tm;
wrong.dir = +1;
DeskewScan(raw, LaserToBase(), wrong, 0.8, 0.5, &out);
double med_w = 0, p95_w = 0;
RangeErr(out, ref, &med_w, &p95_w);
EXPECT_GT(p95_w, 2.0 * p95);
}
TEST(ScanLeveler, SentinelSectorMaskGiuNguyen) {
// Tia bi sector mask cat (range_max + 1 = than robot): giu nguyen, va khong
// tia nao duoc xep de len o do.

View File

@@ -8,11 +8,18 @@
#include <gtest/gtest.h>
#include <rtabmap/core/LocalGrid.h>
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/global_map/OccupancyGrid.h>
#include <opencv2/core.hpp>
#include <cmath>
#include <map>
#include <cstdlib>
#include <limits>
#include <utility>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/occupancy_export.h"
@@ -388,6 +395,68 @@ TEST(OccupancyExport, DbKhongTonTaiThiBaoKhongTonTai) {
EXPECT_FALSE(f.exists);
}
namespace {
// Luoi cuc bo 2D cua mot node: 1 x N, CV_32FC2 (x, y) trong frame node.
cv::Mat Cells(const std::vector<std::pair<float, float>>& xy) {
cv::Mat m(1, static_cast<int>(xy.size()), CV_32FC2);
for (size_t i = 0; i < xy.size(); ++i) {
m.at<cv::Vec2f>(0, static_cast<int>(i)) = cv::Vec2f(xy[i].first, xy[i].second);
}
return m;
}
// O tai (x, y) sau khi ghep 6 node: node 1-3 thay NGUOI o x = 1.0 (tia dung o
// do); node 4-6 tia di XUYEN qua x = 1.0 toi tuong x = 2.0.
int NguoiRoiDi(const rtabmap::ParametersMap& grid_global, float x, float y) {
rtabmap::LocalGridCache cache;
std::map<int, rtabmap::Transform> poses;
for (int id = 1; id <= 6; ++id) {
const bool nguoi = id <= 3;
const float hit = nguoi ? 1.0f : 2.0f;
std::vector<std::pair<float, float>> empty;
for (float e = 0.05f; e < hit - 0.01f; e += 0.05f) empty.emplace_back(e, 0.0f);
// Mot o lech ngang: RTAB-Map KHONG dung ban do khi moi o thang hang
// (khung ymin == ymax).
empty.emplace_back(0.05f, 0.5f);
cache.add(id, cv::Mat(), Cells({{hit, 0.0f}}), Cells(empty), 0.05f);
poses[id] = rtabmap::Transform::getIdentity();
}
rtabmap::ParametersMap p = grid_global;
p[rtabmap::Parameters::kGridCellSize()] = "0.05";
p[rtabmap::Parameters::kGrid3D()] = "false";
rtabmap::OccupancyGrid grid(&cache, p);
grid.update(poses);
float xmin = 0.0f, ymin = 0.0f;
const cv::Mat m = grid.getMap(xmin, ymin);
const int c = static_cast<int>(std::floor((x - xmin) / 0.05f));
const int r = static_cast<int>(std::floor((y - ymin) / 0.05f));
if (m.empty() || r < 0 || c < 0 || r >= m.rows || c >= m.cols) return -2;
return m.at<int8_t>(r, c);
}
} // namespace
TEST(OccupancyExport, LuoiTheoLanNhinMoiNhat) {
// 07/10: 3 nguoi dung tren duong luc quet, roi di; quay lai quet van con tren
// ban do. GridGlobal/* cua slam.yaml (repo): 3 lan nhin xuyen qua -> TRONG.
// Mac dinh RTAB-Map (kep 0.971, truot 0.4): van CHIEM -- do la loi cu.
const char* dir = std::getenv("VSLAM_CONFIG_SRC_DIR");
if (dir == nullptr) GTEST_SKIP() << "khong co VSLAM_CONFIG_SRC_DIR";
RtabmapConfig c = LoadRtabmapConfig(ConfigNode::LoadFile(std::string(dir) + "/slam.yaml"));
ASSERT_TRUE(ApplySlamProfile("real", &c).ok());
std::vector<std::string> unknown;
const std::map<std::string, std::string> all = BuildRtabmapParams(c, &unknown);
rtabmap::ParametersMap gg;
for (const auto& kv : all) {
if (kv.first.rfind("GridGlobal/", 0) == 0) gg.insert(kv);
}
ASSERT_FALSE(gg.empty());
EXPECT_EQ(NguoiRoiDi(gg, 1.0f, 0.0f), 0); // cho nguoi dung: TRONG
EXPECT_EQ(NguoiRoiDi(gg, 2.0f, 0.0f), 100); // tuong van CHIEM
EXPECT_EQ(NguoiRoiDi(rtabmap::ParametersMap(), 1.0f, 0.0f), 100); // mac dinh: loi cu
}
TEST(SensorDataBuilder, FrameLaserSaiLamMoiDiemLechDungBangNo) {
// Loi da mac: `RtabmapSlam` co bien `laser_to_base` nhung KHONG co setter.
// Moi scan bi dat o goc toa do thay vi o (0.24, 0, 0.20). ICP van hoi tu --

View File

@@ -382,3 +382,121 @@ TEST(VoxelHitCounter, CatZVanDungNhuVoxelAccumulator) {
ASSERT_EQ(g.cells.size(), 1u);
EXPECT_TRUE(Has(g.cells, 0, 0, 10));
}
// ---------------- Lan nhin moi nhat quyet dinh (07/10) ----------------
// 3 nguoi dung tren duong luc quet thanh vat can VINH VIEN: lop camera chi
// them, khong bao gio xoa. VoxelCarver hoi cac node SAU lan cuoi voxel duoc
// thay: nhin xuyen qua -> xoa; con thay -> giu; bi che -> khong biet.
namespace {
// Camera cao 0.4 m nhin +x, anh nho 80x60, f = 60 px. Tuong o x = 3 m.
// `nguoi`: khoi depth 1.5 m giua anh. `vat_gan` > 0: khoi do o khoang cach nay
// (che tam nhin).
NodeDepthView Canh(bool nguoi, double vat_gan = 0.0) {
NodeDepthView v;
v.w = 80;
v.h = 60;
v.fx = v.fy = 60.0f;
v.cx = 39.5f;
v.cy = 29.5f;
const float cam[12] = {0, 0, 1, 0, -1, 0, 0, 0, 0, -1, 0, 0.4f}; // base <- optical
std::copy(cam, cam + 12, v.cam);
v.depth_mm.assign(80 * 60, 3000);
for (int y = 22; y < 38; ++y) {
for (int x = 32; x < 48; ++x) {
if (nguoi) v.depth_mm[y * 80 + x] = 1500;
if (vat_gan > 0.0) v.depth_mm[y * 80 + x] = static_cast<uint16_t>(vat_gan * 1000.0);
}
}
return v;
}
const float kPoseGoc[12] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0};
} // namespace
TEST(VoxelCarver, NguoiDaDiThiXoa) {
// Node 0-2 thay nguoi o x = 1.5 m; node 3-5 nhin thang qua cho do toi tuong.
std::vector<NodeDepthView> v;
for (int n = 0; n < 6; ++n) v.push_back(Canh(n < 3));
VoxelCarver c(3.5, 2);
for (int n = 0; n < 6; ++n) c.AddView(n, kPoseGoc, &v[n]);
EXPECT_TRUE(c.Gone(1.5, 0.0, 0.4, 2)); // lan cuoi thay: node 2
// Tuong: lan cuoi thay la node 5, khong con node nao sau -> giu.
EXPECT_FALSE(c.Gone(3.0, 0.0, 0.4, 5));
}
TEST(VoxelCarver, LanNhinMoiNhatQuyetDinh) {
// Node 3-4 nhin xuyen qua nhung node 5 (MOI NHAT) lai thay nguoi -> giu.
std::vector<NodeDepthView> v;
for (int n = 0; n < 6; ++n) v.push_back(Canh(n < 3 || n == 5));
VoxelCarver c(3.5, 2);
for (int n = 0; n < 6; ++n) c.AddView(n, kPoseGoc, &v[n]);
EXPECT_FALSE(c.Gone(1.5, 0.0, 0.4, 2));
}
TEST(VoxelCarver, BiCheThiKhongXoa) {
// Node sau co vat GAN hon (0.8 m) che tam nhin: khong biet -> khong xoa.
std::vector<NodeDepthView> v;
for (int n = 0; n < 6; ++n) v.push_back(n < 3 ? Canh(true) : Canh(false, 0.8));
VoxelCarver c(3.5, 2);
for (int n = 0; n < 6; ++n) c.AddView(n, kPoseGoc, &v[n]);
EXPECT_FALSE(c.Gone(1.5, 0.0, 0.4, 2));
}
TEST(VoxelCarver, NgoaiKhungNhinThiKhongTinh) {
std::vector<NodeDepthView> v;
for (int n = 0; n < 6; ++n) v.push_back(Canh(false));
VoxelCarver c(3.5, 2);
for (int n = 0; n < 6; ++n) c.AddView(n, kPoseGoc, &v[n]);
EXPECT_FALSE(c.Gone(-1.0, 0.0, 0.4, 0)); // sau lung camera
EXPECT_FALSE(c.Gone(5.0, 0.0, 0.4, 0)); // xa hon ban kinh 3.5 m
EXPECT_FALSE(c.Gone(1.0, 3.0, 0.4, 0)); // ngoai goc nhin
}
TEST(VoxelHitCounter, XoaVoxelMaNodeSauNhinXuyenQua) {
// 6 node deu thay tuong (3, 0, 0.4); node 0-2 thay them nguoi (1.5, 0, 0.4).
// Node 3-5 nhin xuyen qua cho nguoi -> nguoi bi xoa, tuong giu.
VoxelExportOptions o = Opt(0.05);
o.min_node_hits = 3;
VoxelHitCounter h(o);
std::vector<NodeDepthView> v;
for (int n = 0; n < 6; ++n) v.push_back(Canh(n < 3));
VoxelCarver c(3.5, 2);
for (int n = 0; n < 6; ++n) {
c.AddView(n, kPoseGoc, &v[n]);
h.BeginNode(n);
h.AddPoint(3.01, 0.01, 0.41);
if (n < 3) h.AddPoint(1.51, 0.01, 0.41);
h.EndNode();
}
VoxelGrid g;
h.Finish(&g, &c);
EXPECT_EQ(h.carved(), 1u);
ASSERT_EQ(g.cells.size(), 1u);
EXPECT_TRUE(Has(g.cells, 60, 0, 8)); // tuong
}
TEST(NodeDepthView, LayMinMoiKhoiVaChiaTieuCu) {
// Depth 320x240 nen 3 m, MOT pixel vat gan 1 m: khoi 4x4 chua no phai la
// 1 m (than trong -- chan nguoi vai pixel van la "thay vat").
const int w = 320, h = 240;
cv::Mat depth(h, w, CV_16UC1, cv::Scalar(3000));
depth.at<uint16_t>(121, 161) = 1000;
cv::Mat gray = cv::Mat::zeros(h, w, CV_8UC1);
const rtabmap::Transform base_to_optical =
rtabmap::Transform(0, 0, 0.4f, 0, 0, 0) * rtabmap::CameraModel::opticalRotation();
rtabmap::CameraModel model(300.0, 300.0, 159.5, 119.5, base_to_optical, 0.0,
cv::Size(w, h));
rtabmap::SensorData data(gray, depth, model, 1, 0.0);
NodeDepthView v;
NodeDepthViewFromSensorData(data, 4, &v);
ASSERT_EQ(v.w, 80);
ASSERT_EQ(v.h, 60);
EXPECT_NEAR(v.fx, 75.0, 1e-3);
EXPECT_NEAR(v.cx, 39.5, 1e-3);
EXPECT_EQ(v.depth_mm[30 * 80 + 40], 1000);
EXPECT_EQ(v.depth_mm[0], 3000);
EXPECT_NEAR(v.cam[11], 0.4, 1e-6);
}