Compare commits

...

9 Commits

Author SHA1 Message Date
trung09122002
f0c5ddb6b8 reloc,web: dinh vi lai TREN DOC (slope.enabled) -- loc gia thuyet bang do nghieng IMU vs do doc ban do, chan mu doc truc (ShiftScoreRatio), vong DUNG YEN khong xoay (ty le nho nhat >= 3 vong / hai cho cung pose), tu chay bo thang tren doc; camera VPR+PnP tren doc (>= 2 anh trung, khop nghieng, LiDAR khong phan doi, pose = trung binh camera) -- sim 10 cho chot dung 1.4-2.9 cm, 0 chot sai; web 3D: ban do uon theo san (FLH1), scan/quy dao theo z, het nen lung, sua ro GPU; CMake: TensorRT tren CMake < 3.17 2026-10-06 10:17:17 +07:00
trung09122002
b1ab04c51e drivers,tools: IMU WT61PC 115200 baud / 200 Hz -- mcu.baud 115200, imu_lag_sec 0.01 (uoc luong, can do lai bang wheel_odom/lag), FTDI low-latency 1 ms + log latency_timer, luat udev configuration_files/udev/99-imu.rules; tool vslam_imu_config (do / doi baud + tan so WT61PC bang lenh WitMotion); vslam_vo_bench --pitch-source sensor 2026-10-06 10:17:07 +07:00
trung09122002
6d552e231e slam: pose odometry DUNG LUC QUET cho SLAM (noi suy lich su EKF -- luc quay tai cho, ghep scan voi pose hien tai lam lech 0.7 do va xoay ca ban do) + vong dong xa (slam.yaml far_loops, mac dinh bat: node vua tao vs node cu cach >= 100 buoc trong 1 m, ICP xac nhan, addLink) -- sim vong doc 52 m: cuoi vong 17-22 cm -> 1.5 cm 2026-10-04 01:36:35 +07:00
trung09122002
f064dcf3ec slam,odometry,perception: di tren doc (G4, slam.yaml slope.enabled, mac dinh tat) -- z robot = tich -ds*sin(pitch IMU) kep phang < 1.5 do va neo vao ban do (HeightEstimator), odometry ngang, scan cho SLAM bu nghieng + bo tia cham san/doc theo ban do do cao tu depth (ScanLeveler, ElevationMap), z/roll/pitch luu vao node + do thi z 1-D + mat san theo node (height_map), voxel dat o z that va vat can tinh tu san cuc bo, xoa tuong gia LiDAR tren doc noi camera da thay mat san, web z uoc luong, --sim-imu-hz 2026-10-04 00:03:02 +07:00
trung09122002
6735b53423 tools: so nguon z tren doc (G3) -- vslam_vo_bench (F2M RTAB-Map tren IR+depth, hang tham chieu ds*sin(pitch) bang GravityAlign, num IMU Hz/bias/truot/nhieu IR), slope_eval/slope_fuse/slope_summary/slope_bakeoff.sh (3 muc giong that, DM-VIO ngoai repo); vslam_vsr_export them bias/nhieu IR; vslam_record --gl-headlight/--gl-ambient 2026-10-04 00:02:53 +07:00
trung09122002
213b5f23a6 tools: vslam_record kich ban doc (slope_loop, slope_lane5..30) lai theo waypoint khong qua FSM, --gl, --cam-decimate, nhieu IMU vao header; vslam_vsr_export doi .vsr sang dataset DM-VIO (mau IMU dung gio anh, T_cam_imu tu robot.yaml, su that IMU/camera/base, ha tan so/lech gio/nhieu IMU luc xuat) 2026-10-03 19:37:29 +07:00
trung09122002
f9fd18b5aa sim: camera ve bang GPU (lib tuy chon vslam_sim_gl, EGL + GLES3 + assimp) -- anh IR co texture that + depth khop tung pixel, vslam_node --sim-gl, tool vslam_render_preview 2026-10-03 19:13:50 +07:00
trung09122002
0dd2546ab1 drivers,sim: moi khung anh mot bo dem rieng (sua tranh chap voi SlamLoop o RealSense/sim/replay); sim: IMU dong hoc tu quy dao 6-DoF, tan so phat/tre/bias, ground truth vao .vsr, vslam_record --robot --gt 2026-10-03 18:55:55 +07:00
trung09122002
26ee1a3b72 sim: dia hinh 3D -- doc va san cao tu model vslam_terrain_*, robot di tren mat san, LiDAR tia 3D, ground truth 6-DoF, world slope_test (5 doc 5-30 do) 2026-10-03 18:31:13 +07:00
91 changed files with 10649 additions and 180 deletions

View File

@@ -60,7 +60,7 @@ Use this file for verified target-repository facts only. Keep unknown values as
- Cameras: RealSense D410 (depth + IR, **no RGB** — left IR doubles as the "rgb" channel for SLAM). 640x480 @ 30 fps, `decimate: 2` with CameraInfo still carrying full-res K (consumers must compensate). Driver `realsense_driver.cc`, built only with `-DVSLAM_WITH_REALSENSE=ON`; sensors.yaml states it is **not yet verified against real hardware**.
- LiDAR: LakiBeam 1L over UDP, bind 0.0.0.0:2368, expected 25 Hz, 270° FOV, range 0.05–40.0 m. Angle convention `theta = (flip ? -alpha : alpha) + angle_offset_deg` with `angle_offset_deg: 178.75`, `angle_flip: true` (sensors.yaml:52-53; the 1.25 deg off 180 is a MEASURED mount error, and the driver logs a suggestion line every 10 s that reads as a no-op when the value is already right).
- IMU: WT61PC wired straight to a UART (USB-FTDI adapter, `/dev/imu`, `mcu.protocol: wt61pc`), 9600 baud, 10 Hz by default. Stamped from the host clock minus `imu_lag_sec` (no `ClockSync`). The older ESP32-S3 path (`mcu.protocol: esp`, `/dev/ttyACM0`, `ClockSync`, `McuTimeUnwrapper` for uint32 `micros()` wrap every 71.58 min) is still supported.
- IMU: WT61PC wired straight to a UART (USB-FTDI adapter, `/dev/imu`, `mcu.protocol: wt61pc`), 115200 baud / 200 Hz (stored in the sensor 2026-10-06; factory default 9600 baud / 10 Hz), FTDI latency_timer 1 ms via `configuration_files/udev/99-imu.rules`. Stamped from the host clock minus `imu_lag_sec` (no `ClockSync`). The older ESP32-S3 path (`mcu.protocol: esp`, `/dev/ttyACM0`, `ClockSync`, `McuTimeUnwrapper` for uint32 `micros()` wrap every 71.58 min) is still supported.
- Compute target: Jetson AGX (arm64); jetson preset uses `CMAKE_PREFIX_PATH=/opt/vslam` and `CMAKE_INSTALL_PREFIX=/opt/vslam`, deps built from source (tools/build_deps.sh referenced by CMakePresets.json:40 — **script not present in repo**).
- Accelerators: none used. No CUDA/TensorRT/OpenCL in the build; all processing is CPU.
- Actuators or robot base: ZLAC8015D dual motor driver over **CANopen on `can0`, node id 1** (not serial), via `liblely-coapp`, gated by `-DVSLAM_WITH_CANOPEN=ON`. DCF at `configuration_files/master.dcf`, path resolved relative to the config dir. `encoder_counts_per_rev: 0` = fall back to 16384 (4096 "wire" x4); the x4 factor is **confirmed** by field data (2026-09-23, see Verification Notes).

View File

@@ -115,6 +115,19 @@ Dinh vi lai tu dong: dat robot o cho khac, **khong** cho pose ban dau.
--slam-reloc --slam-reloc-auto 2>&1 | tee logs/sim_reloc.log
```
Di tren doc: bat `slope.enabled: true` trong `slam.yaml` (xem ghi chu khoi `slope:`).
World thu `slope_test.world` co 5 lan doc 5/10/15/20/30 do noi hai mat bang chenh 1.5 m.
`--sim-imu-hz 100` cho IMU mo phong giong WT61PC sau khi doi 115200 baud.
```sh
./build/app/vslam_node --sim --sim-gl --sim-imu-hz 100 --world resources/worlds/slope_test.world \
--x 6.4 --y 4.0 --yaw 1.5708 --max-speed 0.3 --token t \
--slam --slam-db "slope_{stamp}.db" --slam-mode mapping 2>&1 | tee logs/sim_slope.log
```
Web hien `z uoc luong` canh `z that`. Robot that: **doi WT61PC sang 115200 baud / 100 Hz
va dat `mcu.baud: 115200` truoc khi bat** -- IMU 10 Hz cho sai ~19 cm moi doc 1.5 m (sim).
### Robot that (Jetson)
```sh
@@ -162,7 +175,8 @@ Dinh vi lai co **camera** (VPR + PnP, chot khi trung LiDAR): them `--slam-reloc-
- Luc xoay, cu 30 do chup mot anh; chot SOM khi anh va LiDAR cung chi mot cho. Log ghi
`bang camera+LiDAR` hoac `bang LiDAR`. Vi du do 02/10 (mot cho, mot ban do): camera+LiDAR
chot sau ~3 s, LiDAR-only sau ~13 s.
- Chua chay duoc trong mo phong: camera mo phong chi co depth, khong co anh.
- Trong mo phong: build them `-DVSLAM_SIM_WITH_GL=ON` (may co GPU) va chay `--sim --sim-gl` -- camera ve
bang GPU co anh IR (texture lay tu `~/gazebo_models/aws_hospital`). Khong co co nay thi chi co depth.
Xong thi tra lai hai dich vu:

View File

@@ -38,6 +38,11 @@ endif()
if(VSLAM_WITH_REALSENSE)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_REALSENSE=1)
endif()
# Ve camera mo phong bang GPU (--sim-gl). Lib tuy chon, chi may dev co GPU.
if(TARGET vslam_sim_gl)
target_link_libraries(vslam_node PRIVATE vslam_sim_gl)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_SIM_GL=1)
endif()
if(VSLAM_WITH_CANOPEN)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_CANOPEN=1)
endif()

View File

@@ -624,6 +624,68 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"slam.yaml voxel: obstacle_z_min phai nho hon obstacle_z_max");
}
}
// Khoi `far_loops:` -- vong dong xa luc quet. Vang mat = mac dinh.
if (!root["far_loops"].IsNull()) {
const ConfigNode v = root["far_loops"];
const StatusResponse r =
Reject(v, "slam.yaml far_loops",
{"enabled", "radius_m", "min_graph_gap", "max_corr_m", "max_corr_deg", "period_s"});
if (!r.ok()) return r;
FarLoopsConfig& c = out->far_loops;
c.enabled = v.get<bool>("enabled", c.enabled);
c.radius_m = v.get<double>("radius_m", c.radius_m);
c.min_graph_gap = v.get<int>("min_graph_gap", c.min_graph_gap);
c.max_corr_m = v.get<double>("max_corr_m", c.max_corr_m);
c.max_corr_deg = v.get<double>("max_corr_deg", c.max_corr_deg);
c.period_s = v.get<double>("period_s", c.period_s);
if (c.radius_m <= 0.0 || c.min_graph_gap < 10 || c.max_corr_m <= 0.0 ||
c.max_corr_deg <= 0.0 || c.period_s < 0.0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml far_loops: radius_m > 0, min_graph_gap >= 10, max_corr_m/deg > 0, "
"period_s >= 0");
}
}
// Khoi `slope:` -- di tren doc. Vang mat = tat.
if (!root["slope"].IsNull()) {
const ConfigNode v = root["slope"];
const StatusResponse r = Reject(
v, "slam.yaml slope",
{"enabled", "clamp_deg", "sigma_rel", "sigma_flat", "sigma_anchor", "anchor_radius_m",
"horizontal_odom", "level_scan", "floor_margin_m", "below_ground_m",
"elevation_cell_m", "elevation_radius_m", "elevation_max_depth_m", "depth_stride"});
if (!r.ok()) return r;
SlopeConfig& c = out->slope;
c.enabled = v.get<bool>("enabled", c.enabled);
c.clamp_deg = v.get<double>("clamp_deg", c.clamp_deg);
c.sigma_rel = v.get<double>("sigma_rel", c.sigma_rel);
c.sigma_flat = v.get<double>("sigma_flat", c.sigma_flat);
c.sigma_anchor = v.get<double>("sigma_anchor", c.sigma_anchor);
c.anchor_radius_m = v.get<double>("anchor_radius_m", c.anchor_radius_m);
c.horizontal_odom = v.get<bool>("horizontal_odom", c.horizontal_odom);
c.level_scan = v.get<bool>("level_scan", c.level_scan);
c.floor_margin_m = v.get<double>("floor_margin_m", c.floor_margin_m);
c.below_ground_m = v.get<double>("below_ground_m", c.below_ground_m);
c.elevation_cell_m = v.get<double>("elevation_cell_m", c.elevation_cell_m);
c.elevation_radius_m = v.get<double>("elevation_radius_m", c.elevation_radius_m);
c.elevation_max_depth_m = v.get<double>("elevation_max_depth_m", c.elevation_max_depth_m);
c.depth_stride = v.get<int>("depth_stride", c.depth_stride);
if (c.clamp_deg < 0.0 || c.clamp_deg > 10.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml slope.clamp_deg phai trong [0, 10]");
}
if (c.sigma_rel < 0.0 || c.sigma_flat < 0.0 || c.sigma_anchor <= 0.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml slope: sigma_rel/sigma_flat >= 0, sigma_anchor > 0");
}
if (c.elevation_cell_m <= 0.0 || c.elevation_radius_m <= 0.0 || c.depth_stride < 1) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml slope: elevation_cell_m, elevation_radius_m > 0, depth_stride >= 1");
}
}
}
#endif

View File

@@ -66,6 +66,41 @@ struct VoxelConfig {
size_t min_node_hits = 1;
};
// Di tren doc (G4). Doc tu khoi `slope:` trong slam.yaml. enabled = false thi
// moi duong cu giu nguyen tung byte -- xem slam.yaml.
struct SlopeConfig {
bool enabled = false;
// z = tich -ds*sin(pitch IMU); |pitch| < clamp -> coi la phang (dz = 0).
double clamp_deg = 1.5;
double sigma_rel = 0.05;
double sigma_flat = 0.005;
double sigma_anchor = 0.03;
// Neo z vao node ban do trong ban kinh nay (che do localization).
double anchor_radius_m = 0.6;
// Quang duong banh x cos(pitch) truoc khi vao EKF (doc 15 do: -3.4%).
bool horizontal_odom = true;
// Bu nghieng scan + bo tia cham san cho SLAM / dinh vi lai (KHONG cho an toan).
bool level_scan = true;
double floor_margin_m = 0.08;
double below_ground_m = 0.05;
// Ban do do cao san cuc bo tu depth camera.
double elevation_cell_m = 0.10;
double elevation_radius_m = 8.0;
double elevation_max_depth_m = 4.0;
int depth_stride = 4;
};
// Vong dong XA luc quet ban do (RtabmapSlam::TryFarLoopClosure). Doc tu khoi
// `far_loops:` trong slam.yaml.
struct FarLoopsConfig {
bool enabled = true;
double radius_m = 1.0; // node cu trong ban kinh nay (theo do thi)
int min_graph_gap = 100; // cach toi thieu bay nhieu node trong do thi
double max_corr_m = 0.5; // ICP chinh lon hon -> bo (sai cho)
double max_corr_deg = 10.0;
double period_s = 1.0; // toi da 1 lan thu moi chung nay giay
};
struct ThreadConfig {
int safety_priority = 50;
int driver_priority = 45;
@@ -127,6 +162,8 @@ struct AppConfig {
ThreadConfig threads;
SlamRuntimeConfig slam_runtime;
VoxelConfig voxel;
SlopeConfig slope;
FarLoopsConfig far_loops;
RecordConfig record;
std::string log_level = "info";

View File

@@ -57,6 +57,10 @@ void Usage(const char* argv0) {
" system.yaml gamepad.enabled. DEV mac dinh lay\n"
" tu system.yaml (/dev/input/js0)\n"
" --no-gamepad tat tay cam du system.yaml co bat\n"
" --sim-gl ve camera mo phong bang GPU: depth + anh IR co\n"
" texture (can --world, build VSLAM_SIM_WITH_GL=ON)\n"
" --sim-imu-hz N IMU mo phong phat N Hz (mac dinh moi buoc vat ly,\n"
" 200 Hz). 100 = WT61PC sau khi doi 115200 baud.\n"
" --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n"
" LiDAR/depth KHONG thay; chi sieu am + bumper.\n"
" --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n"
@@ -163,6 +167,8 @@ int main(int argc, char** argv) {
}
else if (a == "--no-gamepad") opts.gamepad_override = -1;
else if (a == "--sim-glass-at") opts.sim_glass_at = std::atof(next().c_str());
else if (a == "--sim-gl") opts.sim_gl = true;
else if (a == "--sim-imu-hz") opts.sim_imu_hz = std::atof(next().c_str());
else if (a == "--max-speed") opts.max_speed_override = std::atof(next().c_str());
else if (a == "--slam") opts.force_slam = true;
else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; }

View File

@@ -18,6 +18,9 @@
#include "vslam/node_constants.h"
#include "vslam/replay_source.h"
#include "vslam/sim_source.h"
#ifdef VSLAM_HAVE_SIM_GL
#include "vslam/sim_gl_renderer.h"
#endif
#ifdef VSLAM_HAVE_SLAM
#include "vslam/occupancy_export.h"
#include <opencv2/imgcodecs.hpp>
@@ -56,6 +59,35 @@ namespace {
//
// Chi de CANH BAO, khong dieu khien gi.
constexpr double kFastAccelWarn = 0.7;
#ifdef VSLAM_HAVE_SLAM
// Do cao SAN cho web (che do doc): luoi 0.2 m phu CUNG khung voi luoi 2D, moi
// o lay mat phang node gan nhat. Web uon mat phang ban do theo no -- khong co
// thi mat doc va san tang tren ve o z = 0, duoi tuong voxel (o z that), trong
// nhu san bi thung.
std::shared_ptr<const MapFloorGrid> BuildMapFloorGrid(const FloorModel& fm,
const OccupancyGrid& grid) {
if (fm.empty() || grid.resolution <= 0.0f) return nullptr;
auto fg = std::make_shared<MapFloorGrid>();
fg->resolution = 0.2f;
fg->origin_x = static_cast<float>(grid.origin.position.x);
fg->origin_y = static_cast<float>(grid.origin.position.y);
fg->width = static_cast<uint32_t>(std::ceil(grid.width * grid.resolution / fg->resolution));
fg->height = static_cast<uint32_t>(std::ceil(grid.height * grid.resolution / fg->resolution));
fg->mm.assign(static_cast<size_t>(fg->width) * fg->height, kFloorUnknown);
for (uint32_t r = 0; r < fg->height; ++r) {
for (uint32_t c = 0; c < fg->width; ++c) {
double fz = 0.0;
if (fm.FloorAt(fg->origin_x + (c + 0.5) * fg->resolution,
fg->origin_y + (r + 0.5) * fg->resolution, &fz)) {
fg->mm[static_cast<size_t>(r) * fg->width + c] = static_cast<int16_t>(
std::max(-32000.0, std::min(32000.0, std::round(fz * 1000.0))));
}
}
}
return fg;
}
#endif
} // namespace
StatusResponse Runtime::OpenSource() {
@@ -69,33 +101,42 @@ StatusResponse Runtime::OpenSource() {
sc.start_yaw = opts_.sim_start_yaw;
// Hinh hoc lay tu robot.yaml, KHONG go tay. Neu sim dung mot bo so va
// duong ong dung bo khac thi moi phep do deu do nham.
const RobotGeometry& g = cfg_->robot.geometry();
sc.wheel_radius = g.wheel_radius;
sc.wheel_separation = g.wheel_separation;
sc.robot_radius = g.robot_radius;
sc.camera_z = cfg_->robot.camera_height_above_floor();
sc.camera_pitch = cfg_->robot.camera_pitch();
// duong ong dung bo khac thi moi phep do deu do nham. Ham dung CHUNG voi
// vslam_record.
SimConfigFromRobot(cfg_->robot, &sc);
sc.max_linear = speed_limit_;
sc.max_angular = cfg_->robot.base().max_angular;
sc.accel_limit = accel_limit_;
sc.lidar_rate_hz = cfg_->sensors.lidar_hz;
sc.camera_rate_hz = cfg_->sensors.camera_hz;
sc.imu_rate_hz = cfg_->sensors.imu_hz;
sc.imu_output_hz = opts_.sim_imu_hz;
sc.enable_depth_camera = cfg_->sensors.camera_enable;
Transform t;
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
sc.lidar_x = t.translation.x;
}
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
sc.camera_x = t.translation.x;
}
source_->sim.reset(new SimSource(sc));
const StatusResponse st = source_->sim->Open();
if (!st.ok()) return st;
if (opts_.sim_gl) {
// Ve camera bang GPU: depth + anh IR tu mesh co texture that. Context
// GPU tao o khung dau tien, tren luong vong mo phong.
if (opts_.world_path.empty()) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"--sim-gl can --world (ve tu mesh cua world)");
}
#ifdef VSLAM_HAVE_SIM_GL
std::string err;
auto r = CreateGlCameraRenderer(source_->sim->world(), DefaultGlRendererConfig(), &err);
if (!r) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "--sim-gl: " + err);
}
source_->sim->SetCameraRenderer(r);
#else
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"--sim-gl: node build KHONG co -DVSLAM_SIM_WITH_GL=ON");
#endif
}
if (opts_.sim_glass_at != 0.0) {
// Buc kinh chan ngang hanh lang. Phai danh dau o DA BI CHIEM, nen
// chen tuong truoc roi moi danh dau la kinh.
@@ -552,7 +593,11 @@ StatusResponse Runtime::Start() {
vverif_.reset(new VisualVerifier);
VSLAM_INFO("slam: camera cho dinh vi lai -- mo ta VPR " << vpr_ids_.size()
<< " anh ban do trong " << dv << " s; chot khi PnP >= 12 inlier TRUNG"
" LiDAR (0.5 m / 10 do).");
" LiDAR (0.5 m / 10 do)"
<< (cfg_->slope.enabled
? "; tren doc: >= 2 anh trung nhau, khop do nghieng IMU, LiDAR "
"khong phan doi -> pose camera."
: "."));
}
}
}
@@ -562,6 +607,19 @@ StatusResponse Runtime::Start() {
{
OccupancyGrid shown = g;
VoxelGridPtr vptr;
// Ban do quet o che do doc: z node nam san trong DB. Giai do thi z
// TRUOC khi xuat, khong thi tang tren + mat doc ve het o z = 0 cho toi
// khi chot (slope_on_ chi bat o duoi doan nay).
const FloorModel* floor = nullptr;
if (cfg_->slope.enabled) {
ZGraphConfig zc;
zc.clamp_rad = cfg_->slope.clamp_deg * M_PI / 180.0;
zc.sigma_rel = cfg_->slope.sigma_rel;
slam_->SetUseHeights(true);
if (slam_->UpdateHeights(zc).ok() && !slam_->floor_model().empty()) {
floor = &slam_->floor_model();
}
}
if (voxel_enabled_) {
VoxelExportOptions vo;
vo.emit_size_m = cfg_->voxel.emit_size_m;
@@ -577,8 +635,12 @@ StatusResponse Runtime::Start() {
VoxelGrid vg;
const StatusResponse vst = slam_->ExportVoxels(vo, &vg);
if (vst.ok()) {
if (floor != nullptr) {
ClearLidarOnSeenRamps(&shown, slam_->floor_cells(), cfg_->voxel.emit_size_m,
*floor, cfg_->slope.clamp_deg * M_PI / 180.0, 1.0);
}
MarkVoxelObstacles(vg, cfg_->voxel.obstacle_z_min,
cfg_->voxel.obstacle_z_max, &shown);
cfg_->voxel.obstacle_z_max, &shown, floor);
vg.epoch = ++voxel_epoch_;
prev_voxel_cells_ = vg.cells;
vptr = std::make_shared<const VoxelGrid>(std::move(vg));
@@ -587,8 +649,11 @@ StatusResponse Runtime::Start() {
<< ") -- 3D se hien sau khi DA DINH VI, 2D van hien ngay.");
}
}
std::shared_ptr<const MapFloorGrid> floor_ptr;
if (floor != nullptr) floor_ptr = BuildMapFloorGrid(*floor, shown);
std::lock_guard<std::mutex> lk(slam_mu_);
slam_map_ = std::make_shared<const OccupancyGrid>(std::move(shown));
slam_map_floor_ = floor_ptr;
slam_published_version_ = 1;
slam_voxels_ = vptr;
}
@@ -618,6 +683,39 @@ StatusResponse Runtime::Start() {
}
#endif
// ---- Di tren doc (slam.yaml `slope:`) ----
// Tat thi khong tao gi: moi duong ben duoi kiem `slope_on_` truoc.
slope_on_ = cfg_->slope.enabled;
if (slope_on_) {
const SlopeConfig& sp = cfg_->slope;
HeightEstimatorConfig hc;
hc.clamp_rad = sp.clamp_deg * M_PI / 180.0;
hc.sigma_rel = sp.sigma_rel;
hc.sigma_flat = sp.sigma_flat;
hc.sigma_anchor = sp.sigma_anchor;
height_.reset(new HeightEstimator(hc));
ElevationMapConfig ec;
ec.cell_m = sp.elevation_cell_m;
ec.radius_m = sp.elevation_radius_m;
elev_.reset(new ElevationMap(ec));
level_cfg_.floor_margin = sp.floor_margin_m;
level_cfg_.below_ground = sp.below_ground_m;
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &laser_to_base_static_)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slope: robot.yaml khong co duong laser -> base_link");
}
have_cam_to_base_ = cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraDepthOpticalFrame,
&cam_to_base_static_);
#ifdef VSLAM_HAVE_SLAM
if (slam_) slam_->SetUseHeights(true);
#endif
VSLAM_INFO("slope: BAT -- z = tich -ds*sin(pitch IMU), kep phang < " << sp.clamp_deg
<< " do, neo vao node trong " << sp.anchor_radius_m << " m; odometry ngang "
<< (sp.horizontal_odom ? "BAT" : "tat") << "; bu nghieng scan cho SLAM "
<< (sp.level_scan ? "BAT" : "tat") << " (an toan van dung scan tho). "
<< "Can IMU >= 100 Hz -- 10 Hz cho sai ~19 cm moi doc 1.5 m (sim G3).");
}
{
const StatusResponse st = Wire();
if (!st.ok()) return st;
@@ -1069,12 +1167,15 @@ void Runtime::SlamLoop() {
LaserScanPtr scan;
{
std::lock_guard<std::mutex> lk(scan_mu_);
scan = latest_scan_; // chi copy shared_ptr
// Ban cho SLAM: bu nghieng khi di tren doc, con lai CHINH latest_scan_.
scan = latest_slam_scan_; // chi copy shared_ptr
}
Pose2D odom;
bool have_odom = false;
double z_now = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
if (slope_on_) z_now = height_->z();
// ⚠️ Dua cho SLAM pose cua EKF, KHONG phai cua wheel_odom.
//
// `map_correction` ma RTAB-Map tra ve la phep bien doi
@@ -1094,6 +1195,30 @@ void Runtime::SlamLoop() {
// ra de chan.
odom = ekf_->pose();
have_odom = have_odom_;
// Pose LUC QUET, khong phai luc vong nay chay toi (xem odom_hist_ trong
// runtime.h). Noi suy giua hai buoc encoder bao quanh stamp cua scan.
if (scan && !odom_hist_.empty()) {
const UnixTime ts = scan->header.stamp;
const OdomAt* lo = nullptr;
const OdomAt* hi = nullptr;
for (const OdomAt& e : odom_hist_) {
if (SecondsBetween(e.stamp, ts) <= 0.0) lo = &e;
else { hi = &e; break; }
}
if (lo != nullptr && hi != nullptr) {
const double span = SecondsBetween(hi->stamp, lo->stamp);
const double u = span > 0.0 ? SecondsBetween(ts, lo->stamp) / span : 0.0;
odom.x = lo->pose.x + u * (hi->pose.x - lo->pose.x);
odom.y = lo->pose.y + u * (hi->pose.y - lo->pose.y);
odom.theta = NormalizeAngle(lo->pose.theta +
u * NormalizeAngle(hi->pose.theta - lo->pose.theta));
if (slope_on_) z_now = lo->z + u * (hi->z - lo->z);
} else if (hi != nullptr) {
odom = hi->pose; // scan cu hon lich su (hiem): lay pose cu nhat
}
// lo != nullptr && hi == nullptr: scan moi hon buoc encoder cuoi --
// pose hien tai la gan nhat (EKF da cap nhat yaw tu IMU sau do).
}
}
if (!scan || !have_odom ||
@@ -1156,10 +1281,77 @@ void Runtime::SlamLoop() {
in.depth_info = depth_info.get();
in.infra1 = infra1.get();
in.camera_to_base = depth ? &cam_now : nullptr;
if (slope_on_) {
in.has_height = true;
in.z = z_now;
in.roll = tilt_roll_.load(std::memory_order_relaxed);
in.pitch = tilt_pitch_.load(std::memory_order_relaxed);
}
// --- KHONG MOT MUTEX NAO duoc giu qua dong nay ---
const SlamOutput out = slam_->Process(in);
// --- Vong dong xa (far_loops), CHI luc quet ---
// Phat hien ke can online cua RTAB-Map chi xet node trong 50 buoc do thi
// (RGBD/ProximityMaxGraphDepth), nen quay lai cho cu sau mot vong dai thi
// khong bao gio noi duoc. O day: node vua tao vs node CU gan nhat theo khong
// gian, ICP xac nhan. Xem RtabmapSlam::TryFarLoopClosure.
if (cfg_->far_loops.enabled && slam_->mode() == SlamMode::kMapping && out.processed) {
const auto now_fl = std::chrono::steady_clock::now();
if (std::chrono::duration<double>(now_fl - far_loops_at_).count() >= cfg_->far_loops.period_s) {
far_loops_at_ = now_fl;
std::string why;
const int r = slam_->TryFarLoopClosure(
cfg_->far_loops.radius_m, cfg_->far_loops.min_graph_gap, cfg_->far_loops.max_corr_m,
cfg_->far_loops.max_corr_deg * M_PI / 180.0, &why);
if (r > 0) {
far_loops_added_++;
VSLAM_INFO("slam: vong dong xa #" << far_loops_added_ << " -- " << why);
std::lock_guard<std::mutex> lk(slam_mu_);
map_correction_ = slam_->map_correction();
} else if (!why.empty()) {
VSLAM_INFO_THROTTLE(10.0, "slam: vong dong xa khong nhan -- " << why);
}
}
}
// --- Di tren doc: z ban do + neo z robot ---
// Do thi z giai lai khi do thi doi (theo nhip, toi da 1 lan/giay -- getGraph
// va giai Cholesky vai ms cho ca nghin node). Neo: z robot keo ve mat san
// cua node gan nhat. O mapping node gan nhat thuong la chinh node vua tao
// (neo khong doi gi) -- co tac dung sau mot lan dong vong lam z do thi doi.
if (slope_on_) {
const auto now_h = std::chrono::steady_clock::now();
if (out.map_version != heights_version_ &&
std::chrono::duration<double>(now_h - heights_at_).count() >= 1.0) {
ZGraphConfig zc;
zc.clamp_rad = cfg_->slope.clamp_deg * M_PI / 180.0;
zc.sigma_rel = cfg_->slope.sigma_rel;
size_t nz = 0;
if (slam_->UpdateHeights(zc, &nz).ok()) {
heights_version_ = out.map_version;
heights_at_ = now_h;
VSLAM_INFO_THROTTLE(30.0, "slope: do thi z " << nz << " node");
}
}
double z_ref = 0.0;
if (out.localized &&
slam_->HeightAt(out.pose_map.x, out.pose_map.y, cfg_->slope.anchor_radius_m, &z_ref)) {
std::lock_guard<std::mutex> lk(odom_mu_);
if (!height_anchored_) {
// Lan dau: robot co the dung o tang tren (z 1.5 m) trong khi uoc
// luong bat dau tu 0 -- cong cua Anchor() se tu choi mai.
height_->Reset(z_ref, cfg_->slope.sigma_anchor);
height_anchored_ = true;
VSLAM_INFO("slope: z robot = " << z_ref << " m theo ban do tai ("
<< out.pose_map.x << ", " << out.pose_map.y << ")");
} else if (!height_->Anchor(z_ref)) {
VSLAM_WARN_THROTTLE(10.0, "slope: bo neo z -- ban do " << z_ref << " m, uoc luong "
<< height_->z() << " m (node sai tang / sai cho?)");
}
}
}
bool need_map = false;
{
std::lock_guard<std::mutex> lk(slam_mu_);
@@ -1314,8 +1506,20 @@ void Runtime::SlamLoop() {
// Grid/* cua RTAB-Map keo pose lech (do 2026-09-24: TB 0.020 ->
// 0.052 m). Phai lam TRUOC khi `vg` bi move ben duoi.
if (st.ok()) {
// Di tren doc: do cao tinh tu SAN tai cho (mat doc khong la tuong).
const FloorModel* floor =
slope_on_ && !slam_->floor_model().empty() ? &slam_->floor_model() : nullptr;
if (floor != nullptr) {
// Tren doc lop LiDAR nhuong cho camera: tuong gia (LiDAR thay mat
// doc tu xa) xoa di noi camera da thay mat san. TRUOC lop vat
// can camera, de vat can that tren doc duoc danh lai.
const size_t nc = ClearLidarOnSeenRamps(
&grid, slam_->floor_cells(), cfg_->voxel.emit_size_m, *floor,
cfg_->slope.clamp_deg * M_PI / 180.0, 1.0);
VSLAM_INFO_THROTTLE(30.0, "slope: xoa " << nc << " o LiDAR tren doc (camera thay mat san)");
}
const size_t n = MarkVoxelObstacles(vg, cfg_->voxel.obstacle_z_min,
cfg_->voxel.obstacle_z_max, &grid);
cfg_->voxel.obstacle_z_max, &grid, floor);
VSLAM_INFO_THROTTLE(30.0, "slam: " << n << " o vat can tu camera ("
<< cfg_->voxel.obstacle_z_min << "-"
<< cfg_->voxel.obstacle_z_max
@@ -1336,9 +1540,13 @@ void Runtime::SlamLoop() {
// ban chua gop roi thay bang ban da gop CUNG version la web khong bao
// gio thay ban da gop.
if (st.ok()) {
// Di tren doc: do cao san de web uon mat phang ban do.
std::shared_ptr<const MapFloorGrid> floor_ptr;
if (slope_on_) floor_ptr = BuildMapFloorGrid(slam_->floor_model(), grid);
auto ptr = std::make_shared<const OccupancyGrid>(std::move(grid));
std::lock_guard<std::mutex> lk(slam_mu_);
slam_map_ = ptr;
slam_map_floor_ = floor_ptr;
slam_published_version_ = slam_map_version_;
}
}
@@ -1372,8 +1580,100 @@ constexpr double kRelocSpeed = 0.12; // m/s
constexpr int kRelocMaxCycles = 6;
constexpr double kRelocMaxDrive = 12.0; // m
constexpr double kRelocPhaseTimeout = 20.0; // s -- bi lop an toan chan thi thoi
// Tren doc: vong DUNG YEN -- khong xoay robot, khop scan tai cho (bo khop da
// thu moi huong bang phan mem). Sim 2026-10-05: xoay tai cho tren doc 15-30 do
// lam scan meo (6 vong deu MAU THUAN / khop sai cho); dung yen thi chon dung
// lan + huong. Doc that con truot banh khi xoay. Tu chay cung KHONG tu di tren
// doc: chua chot thi khop lai tai cho roi goi nguoi.
constexpr double kRelocStaticTiltDeg = 3.0; // nghieng hon nguong nay = tren doc
constexpr double kRelocStaticWindow = 3.0; // s gom scan tai cho moi vong
constexpr double kRelocTiltStableDeg = 0.3; // do nghieng coi la on dinh: doi duoi
constexpr double kRelocTiltStableSec = 1.0; // nguong nay trong chung nay giay
// Nguoi xoay robot qua goc nay trong vong dung yen -> doi thanh vong xoay thuong.
constexpr double kRelocStaticMaxTurn = 15.0 * M_PI / 180.0;
// Tu chay tren doc: khop tai cho kRelocStaticBeforeCreep lan chua chot thi BO
// THANG kRelocCreepStep (khong quay -- phia truoc khong thoang moi quay ve cho
// thoang; khong lui -- sau lung la vung mu LiDAR), tong toi da
// kRelocSlopeCreepMax. Hai goc nhin o hai cho khac nhau cung chi mot pose =
// luat chuoi sau khi di chuyen (Decide). Sim 2026-10-05: dung yen gan dinh doc
// 5 do, nguoi thang DUNG ca 6 vong nhung ty le 1.57-1.60 (bat --sim-gl) <
// chuan mot goc nhin 1.60 -> dung han goi nguoi.
constexpr int kRelocStaticBeforeCreep = 3;
constexpr double kRelocCreepStep = 0.5; // m
// Mu doc truc (dich 1 m van khop >= 95%): moi cho gan day nhin y het -> khop
// lai tai cho vo ich, bo NGAY va xa hon. Sim: giua lan doc bo 4 x 0.5 m van
// mu, dung han giua lan.
constexpr double kRelocCreepBlind = 1.5; // m
// = kRelocMaxDrive: lan doc dai 17 m, nhin XUONG doc thoai thi tia cam vao san
// duoi chan doc truoc khi toi tuong xa -> mu toi khi ra gan chan doc.
constexpr double kRelocSlopeCreepMax = kRelocMaxDrive; // m
constexpr double kRelocCreepMargin = 0.6; // m chua truoc vat can (lop an toan dung 0.45)
} // namespace
double Runtime::RelocFrontClear(const LaserScan& scan) const {
constexpr double kHalf = 15.0 * M_PI / 180.0; // = 3 o 10 do cua RelocPlanDrive
double near = reloc_cfg_.max_range;
bool seen = false;
for (size_t i = 0; i < scan.ranges.size(); ++i) {
const float r = scan.ranges[i];
if (std::isnan(r)) continue; // khong do duoc / bi bo
if (!std::isinf(r) && (r > scan.range_max || r <= scan.range_min)) continue; // bi cat
const double a = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
const double d = std::isinf(r) ? reloc_cfg_.max_range : static_cast<double>(r);
Point pl;
pl.x = d * std::cos(a);
pl.y = d * std::sin(a);
const Point pb = TransformPoint(slam_laser_to_base_, pl);
if (std::fabs(std::atan2(pb.y, pb.x)) > kHalf) continue;
seen = true;
if (!std::isinf(r)) near = std::min(near, std::hypot(pb.x, pb.y));
}
return seen ? near : 0.0;
}
bool Runtime::RelocPoseAdmissible(const Pose2D& p, double tilt_r, double tilt_p) const {
// Robot phai DUNG duoc o do: o TRONG cua ban do. Gia thuyet dat robot trong tuong /
// ngoai vung da quet khong duoc canh tranh (sim: doi thu cua cho dung nam ngoai tuong
// nha, y = -0.04).
const LikelihoodField* lf = reloc_field_.get();
const int c = static_cast<int>(std::lround((p.x - lf->origin_x()) / lf->resolution()));
const int r = static_cast<int>(std::lround((p.y - lf->origin_y()) / lf->resolution()));
if (!lf->Free(r, c)) return false;
double gx = 0.0, gy = 0.0;
if (!FloorGradientAt(slam_->floor_model(), p.x, p.y, reloc_cfg_.tilt_node_radius, &gx, &gy)) {
return true; // khong biet san o do -- khong loai
}
return TiltResidual(tilt_r, tilt_p, p.theta, gx, gy) <=
std::tan(reloc_cfg_.tilt_tol_deg * M_PI / 180.0);
}
bool Runtime::RelocOnSlope(double* deg) const {
// Goc giua truc z than va trong luc: cos = cos(roll) * cos(pitch).
const double r = tilt_roll_.load(std::memory_order_relaxed);
const double p = tilt_pitch_.load(std::memory_order_relaxed);
const double t = std::acos(std::min(1.0, std::cos(r) * std::cos(p)));
if (deg != nullptr) *deg = t * 180.0 / M_PI;
return slope_on_ && t > kRelocStaticTiltDeg * M_PI / 180.0;
}
RelocVerdict Runtime::RelocStaticDecide(const RelocMatch& m, const Pose2D& odom, double shift_ratio,
bool use_shift, bool* along_axis, std::string* why) {
*along_axis = false;
if (!m.ok) {
reloc_static_hist_.clear();
*why = "khong khop duoc";
return RelocVerdict::kFailed;
}
StaticRound r;
r.robot = Pose2DCompose(m.map_from_odom, odom);
r.map_from_odom = m.map_from_odom;
r.ratio = m.ratio();
r.ratio_yaw = m.ratio_yaw();
r.shift = shift_ratio;
return DecideStatic(&reloc_static_hist_, r, reloc_static_places_, reloc_cfg_, use_shift,
along_axis, why);
}
void Runtime::RelocCommand(double v, double w) {
std::lock_guard<std::mutex> lk(cmd_mu_);
raw_cmd_.linear.x = v;
@@ -1531,25 +1831,60 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
// Het quang duong, hoac lop an toan chan qua lau (vat can, sieu am) -> xoay.
if (moved >= reloc_drive_len_ || t > kRelocPhaseTimeout) {
reloc_total_drive_ += moved;
if (reloc_creeping_) {
reloc_slope_creep_ += moved;
reloc_creeping_ = false;
}
if (!yielding) RelocCommand(0.0, 0.0);
RelocStartSweep();
return;
}
if (!yielding) RelocCommand(kRelocSpeed, 0.0);
char buf[96];
std::snprintf(buf, sizeof(buf), "TU DI %.1f/%.1f m%s", moved, reloc_drive_len_,
char buf[128];
std::snprintf(buf, sizeof(buf), "%s %.1f/%.1f m%s",
reloc_creeping_ ? "BO THANG TREN DOC" : "TU DI", moved, reloc_drive_len_,
yielding ? " -- NHUONG NGUOI" : "");
SetRelocStatus(buf, true);
return;
}
// --- GOM (tu chay: pha XOAY; tay: nguoi xoay) ---
// --- GOM (tu chay: pha XOAY; tay: nguoi xoay; tren doc: DUNG YEN) ---
double tilt_deg = 0.0;
// Che do doc: CHO do nghieng IMU hop le VA ON DINH roi moi quyet xoay hay dung
// yen. Ngay luc khoi dong roll/pitch con = 0 gia -> vong dau tuong san phang,
// xoay 300 do roi TU DI 1 m tren doc (sim 2026-10-05). valid() bat tu mau IMU
// DAU, khi bo loc bu con dang hoi tu: sim 2026-10-06 vong dau thay 3.2 do tren
// doc 10 do -> anh camera dau bi xet theo luat san phang. On dinh = doi duoi
// kRelocTiltStableDeg trong kRelocTiltStableSec. Qua 8 s thi chay nhu cu.
if (!reloc_have_prev_ && slope_on_ &&
std::chrono::duration<double>(now - reloc_epoch_).count() < 8.0) {
double tdeg = 0.0;
RelocOnSlope(&tdeg);
if (!tilt_valid_.load(std::memory_order_relaxed) ||
std::fabs(tdeg - reloc_tilt_ref_deg_) > kRelocTiltStableDeg) {
reloc_tilt_ref_deg_ = tdeg;
reloc_tilt_ref_t_ = now;
}
if (std::chrono::duration<double>(now - reloc_tilt_ref_t_).count() < kRelocTiltStableSec) {
if (running && !yielding) RelocCommand(0.0, 0.0);
char tb[96];
std::snprintf(tb, sizeof(tb), "CHO IMU on dinh (nghieng %.1f do) truoc khi dinh vi lai", tdeg);
SetRelocStatus(tb, true);
return;
}
}
if (!reloc_have_prev_) {
reloc_t0_ = now;
reloc_swept_ = 0.0;
reloc_cam_have_last_ = false; // chup ngay anh dau cua vong gom
reloc_cam_shots_ = 0;
reloc_cam_best_inl_ = 0;
reloc_static_round_ = RelocOnSlope(&tilt_deg);
if (reloc_static_round_) {
VSLAM_INFO("slam: reloc vong " << reloc_cycle_ + 1 << " DUNG YEN tren doc (nghieng "
<< tilt_deg << " do) -- khong xoay, khop scan tai cho sau "
<< kRelocStaticWindow << " s.");
}
} else {
// Goc da quet do bang odom: xoay tai cho thi odometry rat chinh xac (ban
// ROS do: 0.1 do troi tren 1086 do xoay).
@@ -1559,8 +1894,13 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
reloc_have_prev_ = true;
const std::vector<Point> p = ScanToFrame(scan, odom);
reloc_pts_.insert(reloc_pts_.end(), p.begin(), p.end());
// Camera: chot SOM ngay giua vong xoay neu anh + LiDAR cung chi mot pose.
if (vpr_ && RelocCamera(scan, odom, now)) {
// Camera: chot SOM ngay giua vong xoay neu anh + LiDAR cung chi mot pose. Vong
// DUNG YEN: chup trong giay CUOI cua cua so -- LiDAR da gom du diem de kiem anh,
// do nghieng da lang sau khi robot vua dung (bo xong / vua khoi dong).
const bool cam_turn =
!reloc_static_round_ ||
std::chrono::duration<double>(now - reloc_t0_).count() >= kRelocStaticWindow - 1.0;
if (vpr_ && cam_turn && RelocCamera(scan, odom, now)) {
if (running && !yielding) RelocCommand(0.0, 0.0);
return;
}
@@ -1572,7 +1912,36 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
constexpr double kTimeout = 30.0;
const double elapsed = std::chrono::duration<double>(now - reloc_t0_).count();
const int swept_deg = static_cast<int>(reloc_swept_ * 180.0 / M_PI);
if (reloc_swept_ < kSweep && elapsed < kTimeout) {
if (reloc_static_round_ && reloc_swept_ > kRelocStaticMaxTurn) {
// Nguoi dang xoay robot -> de nguoi xoay het, khop nhu vong xoay thuong.
reloc_static_round_ = false;
VSLAM_INFO("slam: reloc -- robot dang duoc xoay, vong nay khop sau khi xoay du.");
} else if (!reloc_static_round_ && reloc_swept_ < kRelocStaticMaxTurn && RelocOnSlope(&tilt_deg)) {
// Moi xoay vai do ma da thay dang tren doc (do nghieng vua on dinh) -> dung.
reloc_static_round_ = true;
reloc_t0_ = now;
reloc_cam_have_last_ = false; // anh luc con xoay khong tinh -- chup lai cuoi cua so
VSLAM_INFO("slam: reloc -- phat hien dang tren doc (nghieng " << tilt_deg
<< " do) khi moi xoay " << reloc_swept_ * 180.0 / M_PI << " do -> DUNG YEN.");
}
if (reloc_static_round_ && elapsed < kRelocStaticWindow) {
if (running && !yielding) RelocCommand(0.0, 0.0);
RelocOnSlope(&tilt_deg);
char sb[160];
if (running) {
std::snprintf(sb, sizeof(sb),
"DUNG YEN TREN DOC (nghieng %.1f do) -- khop tai cho, lan %d/%d, da bo %.1f/%.0f m",
tilt_deg, reloc_static_here_ + 1, kRelocStaticBeforeCreep, reloc_slope_creep_,
kRelocSlopeCreepMax);
} else {
std::snprintf(sb, sizeof(sb), "%sDUNG YEN TREN DOC (nghieng %.1f do) -- khop tai cho, lan %d",
reloc_exec_ == RelocExec::kHalted ? "DUNG HAN tu chay -- " : "", tilt_deg,
reloc_cycle_ + 1);
}
SetRelocStatus(std::string(sb) + (yielding ? " -- NHUONG NGUOI" : "") + cam_note(), true);
return;
}
if (!reloc_static_round_ && reloc_swept_ < kSweep && elapsed < kTimeout) {
if (running) {
if (!yielding) RelocCommand(0.0, kRelocTurnRate);
SetRelocStatus("TU XOAY " + std::to_string(swept_deg) + "/300 do (vong " +
@@ -1594,17 +1963,64 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
// --- Khop toan cuc ---
const auto tm = std::chrono::steady_clock::now();
const RelocMatch m = GlobalMatch(*reloc_field_, reloc_pts_, reloc_cfg_);
// Che do doc: do nghieng IMU (theo trong luc, khong can ban do) loai gia
// thuyet ma mat san ban do o do khong the gay ra -- lat 180 do tren doc, doc
// o cho phang, sai lan. Chi phan xu giua cac gia thuyet LiDAR ngang diem
// (xem GlobalMatch). Robot vua dung xoay nen do nghieng la luc dung yen.
RelocAdmit admit;
const double tilt_r = tilt_roll_.load(std::memory_order_relaxed);
const double tilt_p = tilt_pitch_.load(std::memory_order_relaxed);
if (slope_on_ && !slam_->floor_model().empty()) {
admit = [this, odom, tilt_r, tilt_p](const Pose2D& T) {
return RelocPoseAdmissible(Pose2DCompose(T, odom), tilt_r, tilt_p);
};
}
const RelocMatch m = GlobalMatch(*reloc_field_, reloc_pts_, reloc_cfg_, admit);
const double ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - tm).count();
reloc_tracker_->Add(m, odom, std::chrono::duration<double>(now - reloc_epoch_).count());
const int streak = m.ok ? reloc_tracker_->Streak(m.map_from_odom) : 0;
const RelocVerdict v = Decide(m, streak, reloc_cfg_);
RelocVerdict v = Decide(m, streak, reloc_cfg_);
// Chot NHO do nghieng con phai qua kiem suy bien doc truc: bo loc loai het
// doi thu XA, nhung o hanh lang / doc deu vi tri doc truc van mu (doi thu
// nam trong reject_radius, cong ty le khong thay) -- xem ShiftScoreRatio.
double shift_ratio = -1.0;
bool along_axis = false;
std::string static_why;
if (admit && m.ok) {
shift_ratio = ShiftScoreRatio(*reloc_field_, reloc_pts_, m.map_from_odom, reloc_cfg_.tilt_shift_m);
}
if (reloc_static_round_) {
// Dung yen: ty le NHO NHAT qua moi vong cung cho; hoac hai cho (truoc / sau
// khi bo) cung pose, moi cho deu qua -- xem DecideStatic. KHONG dung streak
// cua tracker: no da cho chot sai 1.5-2 m o chan doc (ty le nhay 1.32).
v = RelocStaticDecide(m, odom, shift_ratio, static_cast<bool>(admit), &along_axis, &static_why);
} else {
reloc_static_hist_.clear();
reloc_static_places_.clear();
if (admit && m.ok && v == RelocVerdict::kAccept && m.tilt_used &&
shift_ratio >= reloc_cfg_.tilt_max_shift_ratio) {
v = RelocVerdict::kAmbiguous;
along_axis = true;
}
}
++reloc_cycle_;
VSLAM_INFO("slam: reloc vong " << reloc_cycle_ << " -- quet " << swept_deg << " do / "
<< elapsed << " s, " << m.points << " diem, ty le " << m.ratio() << " / huong "
<< m.ratio_yaw() << ", streak " << streak << " -> " << RelocVerdictName(v)
<< " (" << ms << " ms)");
std::string tilt_note;
if (admit) {
char tb[160];
std::snprintf(tb, sizeof(tb), "; nghieng IMU roll %.1f / pitch %.1f do: %s; dich %.1f m giu %.0f%% diem",
tilt_r * 180.0 / M_PI, tilt_p * 180.0 / M_PI,
m.tilt_used ? (std::to_string(m.tilt_rejected) + " ung vien mau thuan bi loai").c_str()
: m.tilt_conflict ? "MAU THUAN voi LiDAR -- bo qua, giu ket qua LiDAR"
: "khong loai ung vien nao",
reloc_cfg_.tilt_shift_m, 100.0 * shift_ratio);
tilt_note = tb;
}
VSLAM_INFO("slam: reloc vong " << reloc_cycle_ << (reloc_static_round_ ? " (DUNG YEN)" : "")
<< " -- quet " << swept_deg << " do / " << elapsed << " s, " << m.points
<< " diem, ty le " << m.ratio() << " / huong " << m.ratio_yaw() << ", streak "
<< streak << " -> " << RelocVerdictName(v) << " (" << ms << " ms)" << tilt_note
<< (static_why.empty() ? "" : "; " + static_why));
// Vong gom moi, du ket qua the nao.
reloc_pts_.clear();
@@ -1615,20 +2031,109 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
// Nhap nhang la ket qua DUNG, khong phai loi: tra loi sai tu tin te hon
// nhieu so voi im lang. Noi ro phai lam gi.
const char* hint =
v == RelocVerdict::kNeedCycles ? "DAI BIEN -- di chuyen >= 0.2 m roi xoay tiep"
along_axis ? "NHAP NHANG DOC TRUC (hanh lang / doc deu) -- di chuyen toi cho co dac diem"
: reloc_static_round_
? (v == RelocVerdict::kNeedCycles ? "DUNG YEN TREN DOC -- chua du tin cay"
: "DUNG YEN TREN DOC -- nhap nhang")
: v == RelocVerdict::kNeedCycles ? "DAI BIEN -- di chuyen >= 0.2 m roi xoay tiep"
: v == RelocVerdict::kAmbiguousYaw ? "NHAP NHANG HUONG -- di chuyen vai met roi xoay tiep"
: v == RelocVerdict::kAmbiguous ? "NHAP NHANG VI TRI -- di chuyen vai met roi xoay tiep"
: "KHONG KHOP -- xoay tiep";
char buf[160];
std::snprintf(buf, sizeof(buf), "%s (ty le %.2f / huong %.2f)", hint, m.ratio(), m.ratio_yaw());
VSLAM_WARN("slam: reloc chua chot -- " << buf);
char buf[220];
std::snprintf(buf, sizeof(buf), "%s (ty le %.2f / huong %.2f%s%s)", hint, m.ratio(),
m.ratio_yaw(), static_why.empty() ? "" : "; ", static_why.c_str());
// Nhap nhang voi CHO NAO: pose robot cua nguoi thang va hai doi thu.
char who[200] = "";
if (m.ok) {
const Pose2D w = Pose2DCompose(m.map_from_odom, odom);
const Pose2D p2 = Pose2DCompose(m.s2_from_odom, odom);
const Pose2D py = Pose2DCompose(m.s2_yaw_from_odom, odom);
std::snprintf(who, sizeof(who),
"; thang (%.2f, %.2f, %.0f do), doi thu vi tri (%.2f, %.2f, %.0f do), doi thu "
"huong (%.2f, %.2f, %.0f do)",
w.x, w.y, w.theta * 180.0 / M_PI, p2.x, p2.y, p2.theta * 180.0 / M_PI, py.x,
py.y, py.theta * 180.0 / M_PI);
}
VSLAM_WARN("slam: reloc chua chot -- " << buf << who);
if (!running) {
SetRelocStatus(buf, true);
return;
}
// Tu chay: sang cho khac roi xoay tiep -- doi xung cuc bo thuong vo khi
// doi goc nhin, va streak chi tang khi DA DI >= 0.2 m.
++reloc_exec_cycles_;
// ⚠️ Vong tren doc KHONG tinh vao tran kRelocMaxCycles (chung co tran rieng
// = quang bo): sim, bo xuong toi sanh roi vong xoay dau o sanh (ty le 1.43,
// can them mot vong) bi dung han ngay vi bo dem da len 20 tu cac vong doc.
if (!reloc_static_round_) ++reloc_exec_cycles_;
if (reloc_static_round_) {
// Tren doc: khop lai TAI CHO vai lan; chua chot thi BO 0.5 m roi khop
// tiep o cho moi (xem kRelocStaticBeforeCreep). Het tran bo / khong co
// huong nao thoang thi goi nguoi.
++reloc_static_here_;
// Mu doc truc -> bo ngay, xa hon; chi thieu tin cay -> khop lai tai cho vai lan.
// ⚠️ Xet THANG chi so dich cua vong nay, khong qua `along_axis`: ty le
// < min_ratio thi DecideStatic tra truoc khi kiem doc truc (sim: giua lan
// dich 1 m giu 100% ma van bo tung 0.5 m sau 3 lan).
const bool blind = admit && shift_ratio >= reloc_cfg_.tilt_max_shift_ratio;
if (!blind && reloc_static_here_ < kRelocStaticBeforeCreep) {
RelocStartSweep();
VSLAM_INFO("reloc_exec: vong " << reloc_cycle_ << " chua chot -- tren doc: khop lai tai cho ("
<< reloc_static_here_ << "/" << kRelocStaticBeforeCreep << ").");
SetRelocStatus(std::string(buf) + " -- tren doc: khop lai tai cho", true);
return;
}
char hb[160];
const double budget = std::min(kRelocSlopeCreepMax - reloc_slope_creep_,
kRelocMaxDrive - reloc_total_drive_);
double step = std::min(blind ? kRelocCreepBlind : kRelocCreepStep, budget);
if (step < 0.3) {
std::snprintf(hb, sizeof(hb), "tren doc: da bo %.1f m, %d lan khop tai cho chua chot",
reloc_slope_creep_, reloc_static_here_);
RelocHalt(hb);
return;
}
reloc_static_here_ = 0;
reloc_creeping_ = true;
// Chot CHO nay truoc khi bo: chot "hai cho" so cho moi voi no.
if (!reloc_static_hist_.empty()) {
reloc_static_places_.push_back(SummarizePlace(reloc_static_hist_));
while (reloc_static_places_.size() > 4) reloc_static_places_.erase(reloc_static_places_.begin());
reloc_static_hist_.clear();
}
const double clear = RelocFrontClear(scan);
if (clear - kRelocCreepMargin >= std::min(step, kRelocCreepStep)) {
// Thang toi, KHONG quay: quay tai cho tren doc lam truot banh.
step = std::min(step, clear - kRelocCreepMargin);
reloc_exec_ = RelocExec::kDrive;
reloc_drive_start_ = odom;
reloc_drive_len_ = step;
reloc_phase_t0_ = now;
VSLAM_INFO("reloc_exec: tren doc chua chot" << (blind ? " (MU doc truc)" : "") << " -- BO THANG "
<< step << " m (khong quay; da bo " << reloc_slope_creep_ << "/"
<< kRelocSlopeCreepMax << " m) roi khop tiep.");
char cb[64];
std::snprintf(cb, sizeof(cb), " -- BO THANG %.1f m tren doc", step);
SetRelocStatus(std::string(buf) + cb, true);
return;
}
// Phia truoc khong thoang (vd nhin xuong doc: tia cham san da bi bo) ->
// quay ve huong thoang nhat roi moi bo.
if (!RelocPlanDrive(scan, odom)) {
reloc_creeping_ = false;
RelocHalt("tren doc: phia truoc chi thoang " + std::to_string(clear) +
" m va khong co huong nao thoang >= 1 m");
return;
}
reloc_drive_len_ = std::min(reloc_drive_len_, step);
reloc_exec_ = RelocExec::kTurn;
reloc_phase_t0_ = now;
VSLAM_INFO("reloc_exec: tren doc chua chot, phia truoc khong thoang (" << clear
<< " m) -- quay ve huong " << reloc_turn_target_ * 180.0 / M_PI << " do (odom) roi bo "
<< reloc_drive_len_ << " m.");
SetRelocStatus(std::string(buf) + " -- QUAY roi BO tren doc", true);
return;
}
reloc_static_here_ = 0;
if (reloc_exec_cycles_ >= kRelocMaxCycles || reloc_total_drive_ >= kRelocMaxDrive) {
RelocHalt("het tran " + std::to_string(kRelocMaxCycles) + " vong / " +
std::to_string(static_cast<int>(kRelocMaxDrive)) + " m");
@@ -1649,8 +2154,15 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
// --- CHOT -> dung yen roi tinh chinh (RelocSettle) ---
if (running && !yielding) RelocCommand(0.0, 0.0);
char src[48];
std::snprintf(src, sizeof(src), "LiDAR, ty le %.2f", m.ratio());
// Lan dinh vi lai SAU (vd canh lac) khong duoc dung lai cac vong dung yen cu.
reloc_static_hist_.clear();
reloc_static_places_.clear();
char src[96];
std::snprintf(src, sizeof(src),
reloc_static_round_ ? "LiDAR + do nghieng IMU, DUNG YEN tren doc, ty le %.2f"
: m.tilt_used ? "LiDAR + do nghieng IMU, ty le %.2f"
: "LiDAR, ty le %.2f",
m.ratio());
RelocBeginSettle(m.map_from_odom, m.ratio(), odom, now, src);
}
@@ -1690,6 +2202,15 @@ constexpr double kCamAgreeM = 0.5;
constexpr double kCamAgreeRad = 10.0 * M_PI / 180.0;
constexpr double kCamLidarRadius = 2.5; // LiDAR cuc bo quanh node anh VPR
constexpr double kCamLidarYaw = 45.0 * M_PI / 180.0;
// --- Tren DOC (RelocOnSlope): luat rieng ---
// Sim 2026-10-06 (5 cho giua lan doc, robot dung yen): 3/5 cho ca 5 ung vien VPR+PnP
// DUNG toi 1-5 cm, 2/5 cho sai het (nham lan khac / lat 180 do -- do nghieng IMU loai
// duoc). Luat phang (LiDAR cuc bo quanh node phai TRUNG PnP) chan ca ung vien dung
// (LiDAR mu doc lan) va mot lan con chot pose LiDAR roi tinh chinh keo lech 0.75 m.
// Tren doc: LiDAR chi can KHONG PHAN DOI; pose chot la TRUNG BINH cac pose CAMERA, khong
// tinh chinh LiDAR (do: tinh chinh keo pose 8-13 cm doc lan, diem chi nhich 0.996 -> 0.999).
constexpr double kCamSlopeLidarKeep = 0.9; // diem LiDAR tai pose camera / tot nhat quanh do
constexpr size_t kCamSlopeMinAgree = 2; // ung vien tu node KHAC nhau phai trung nhau
cv::Matx44d MatxFromTransform(const Transform& t) {
const Vector3 ex = RotateVector(t.rotation, Vector3{1.0, 0.0, 0.0});
@@ -1768,7 +2289,21 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom,
TiltLift(roll, pitch, cfg_->robot.geometry().wheel_radius), slam_cam_to_link_));
std::vector<Pose2D> acc; // T_map_odom (pose LiDAR) cua ung vien DUOC CHOT
std::vector<Pose2D> cams; // tren doc: pose robot theo camera cua ung vien duoc chot
std::string why;
// Tren doc: luat rieng (xem kCamSlopeLidarKeep). Phang: luat da kiem, giu nguyen.
const bool slope_cam = !slam_->floor_model().empty() && RelocOnSlope();
const double tilt_r = tilt_roll_.load(std::memory_order_relaxed);
const double tilt_p = tilt_pitch_.load(std::memory_order_relaxed);
auto lidar_at = [this](const Pose2D& T) {
const double c = std::cos(T.theta), s = std::sin(T.theta);
std::vector<Point> m(reloc_pts_.size());
for (size_t i = 0; i < reloc_pts_.size(); ++i) {
m[i].x = T.x + c * reloc_pts_[i].x - s * reloc_pts_[i].y;
m[i].y = T.y + s * reloc_pts_[i].x + c * reloc_pts_[i].y;
}
return reloc_field_->MeanScore(m);
};
for (size_t k = 0; k < topk; ++k) {
const int id = vpr_ids_[sc[k].second];
auto it = vpr_shots_.find(id);
@@ -1785,13 +2320,64 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom,
}
const PnpResult r = vverif_->Solve(qf, it->second.f, it->second.T_map_base);
reloc_cam_best_inl_ = std::max(reloc_cam_best_inl_, r.inliers);
if (r.inliers < kCamMinInliers || std::fabs(r.dz) > kCamMaxDz || r.tilt_deg > kCamMaxTiltDeg) {
// `dz` = do cao robot SO VOI node anh (ca hai da can trong luc). San phang: ~0. Tren
// doc: = chenh san giua hai cho theo mo hinh san -- hai diem cach 2 m tren doc 15 do
// chenh 0.5 m, dung nguong phang 0.3 m la loai oan nghiem DUNG.
double dz_expect = 0.0;
if (slope_on_ && !slam_->floor_model().empty() && r.inliers > 0) {
double zq = 0.0, zn = 0.0;
const cv::Matx44d& Tm = it->second.T_map_base;
if (slam_->floor_model().FloorAt(r.x, r.y, &zq) &&
slam_->floor_model().FloorAt(Tm(0, 3), Tm(1, 3), &zn)) {
dz_expect = zq - zn;
}
}
if (r.inliers > 0) {
VSLAM_INFO("slam: reloc camera -- node " << id << " giong " << sc[k].first << ", PnP "
<< r.inliers << "/" << r.matches << " inlier, pose (" << r.x << ", " << r.y << ", "
<< r.yaw * 180.0 / M_PI << " do), dz " << r.dz << " (ky vong " << dz_expect
<< "), nghieng " << r.tilt_deg << " do");
}
if (r.inliers < kCamMinInliers || std::fabs(r.dz - dz_expect) > kCamMaxDz ||
r.tilt_deg > kCamMaxTiltDeg) {
continue;
}
Pose2D cam;
cam.x = r.x;
cam.y = r.y;
cam.theta = r.yaw;
if (slope_cam) {
// 1. Do nghieng IMU khop do doc ban do tai pose camera + dung tren o trong: loai
// nham lan (doc goc khac) va lat 180 do (doc nguoc dau).
if (!RelocPoseAdmissible(cam, tilt_r, tilt_p)) {
VSLAM_INFO("slam: reloc camera -- node " << id << " loai: do nghieng / o trong khong khop");
continue;
}
// 2. LiDAR KHONG PHAN DOI: diem tai pose camera >= kCamSlopeLidarKeep x tot nhat
// quanh do. Hanh lang/doc deu: LiDAR dung moi cho doc truc -> khong phan doi.
const Pose2D Tcam = Pose2DCompose(cam, Pose2DInverse(odom));
Point cc;
cc.x = cam.x;
cc.y = cam.y;
const RelocHypothesis hb = LocalMatch(*reloc_field_, reloc_pts_, odom, cc, kCamLidarRadius,
reloc_cfg_);
const double s_cam = lidar_at(Tcam);
const double s_best = hb.score > 0.0 ? lidar_at(hb.map_from_odom) : -1.0;
if (s_cam <= 0.0 || (s_best > 0.0 && s_cam < kCamSlopeLidarKeep * s_best)) {
VSLAM_INFO("slam: reloc camera -- node " << id << " loai: LiDAR phan doi (diem " << s_cam
<< " / tot nhat " << s_best << ")");
continue;
}
acc.push_back(Tcam); // pose CAMERA -- LiDAR mu doc lan, khong lay pose LiDAR
cams.push_back(cam);
if (why.empty()) {
char b[120];
std::snprintf(b, sizeof(b), "node %d, giong %.2f, PnP %d inlier, LiDAR %.0f%%", id,
sc[k].first, r.inliers, s_best > 0.0 ? 100.0 * s_cam / s_best : 100.0);
why = b;
}
continue;
}
// LiDAR cuc bo quanh node anh VPR: gioi han huong truoc, tu do huong sau (nhu da do).
const cv::Matx44d& Tn = it->second.T_map_base;
Point center;
@@ -1815,6 +2401,10 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom,
}
}
}
if (reloc_cam_best_inl_ == 0 && topk > 0) {
VSLAM_INFO("slam: reloc camera -- anh " << reloc_cam_shots_ << ": top-" << topk << " node giong "
<< sc[0].first << ".." << sc[topk - 1].first << ", khong PnP nao ra inlier.");
}
if (acc.empty()) return false;
for (const Pose2D& T : acc) {
if (!CamAgree(Pose2DCompose(T, odom), Pose2DCompose(acc[0], odom))) {
@@ -1823,11 +2413,37 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom,
return false;
}
}
if (slope_cam && acc.size() < kCamSlopeMinAgree) {
VSLAM_INFO("slam: reloc camera -- tren doc moi " << acc.size() << " ung vien dat, can "
<< kCamSlopeMinAgree << " trung nhau -- chua chot.");
return false;
}
// Chot: vong gom nay coi nhu xong.
++reloc_cycle_;
reloc_pts_.clear();
reloc_have_prev_ = false;
reloc_swept_ = 0.0;
if (slope_cam) {
// Moi ung vien la PnP voi mot anh ban do KHAC -> lay trung binh. Anh va scan cung luc,
// robot dung yen: dat pose ngay, khong qua buoc tinh chinh LiDAR.
const double n = static_cast<double>(cams.size());
Pose2D mean;
double dth = 0.0;
for (const Pose2D& c : cams) {
mean.x += c.x / n;
mean.y += c.y / n;
dth += AngleDiff(c.theta, cams[0].theta) / n;
}
mean.theta = NormalizeAngle(cams[0].theta + dth);
const Pose2D T = Pose2DCompose(mean, Pose2DInverse(odom));
RelocBeginSettle(T, 0.0, odom, now,
"camera tren doc (" + std::to_string(cams.size()) + " ung vien trung; " + why + ")");
reloc_static_hist_.clear();
reloc_static_places_.clear();
RelocFinish(T, odom, scan, "trung binh " + std::to_string(cams.size()) +
" pose camera, khong tinh chinh LiDAR -- mu doc lan");
return true;
}
RelocBeginSettle(acc[0], 0.0, odom, now, "camera+LiDAR (" + why + ")");
return true;
}
@@ -1921,6 +2537,25 @@ void Runtime::RelocFinish(const Pose2D& map_from_odom, const Pose2D& odom,
return;
}
reloc_active_ = false;
if (slope_on_) {
// z robot theo ban do tai pose vua chot. Do thi z chua giai (RTAB-Map chua
// nhan khung nao trong luc dinh vi) thi giai ngay.
if (slam_->floor_model().empty()) {
ZGraphConfig zc;
zc.clamp_rad = cfg_->slope.clamp_deg * M_PI / 180.0;
zc.sigma_rel = cfg_->slope.sigma_rel;
slam_->UpdateHeights(zc);
}
double z_ref = 0.0;
if (slam_->HeightAt(pose.x, pose.y, 2.0, &z_ref)) {
std::lock_guard<std::mutex> lk(odom_mu_);
height_->Reset(z_ref, cfg_->slope.sigma_anchor);
height_anchored_ = true;
VSLAM_INFO("slope: z robot = " << z_ref << " m theo ban do sau dinh vi lai");
} else {
height_anchored_ = false;
}
}
if (opts_.slam_reloc_auto && reloc_exec_ != RelocExec::kOff) {
// Chot roi thi DUNG HAN tu chay, ke ca dang nhuong nguoi.
if (reloc_exec_ != RelocExec::kHalted) RelocCommand(0.0, 0.0);
@@ -1975,6 +2610,11 @@ void Runtime::RelocWatch(const LaserScan& scan, const Pose2D& pose_map) {
reloc_tracker_->Clear();
reloc_ref_score_ = -1.0;
reloc_lost_pending_ = false;
reloc_static_hist_.clear();
reloc_static_places_.clear();
reloc_static_here_ = 0;
reloc_slope_creep_ = 0.0;
reloc_creeping_ = false;
if (opts_.slam_reloc_auto) {
// Lan dinh vi MOI: dat lai tran cung.
reloc_exec_cycles_ = 0;
@@ -2095,6 +2735,13 @@ void Runtime::WebLoop() {
snap.roll = tilt_roll_.load(std::memory_order_relaxed);
snap.pitch = tilt_pitch_.load(std::memory_order_relaxed);
snap.accel_ok = tilt_accel_ok_.load(std::memory_order_relaxed);
if (slope_on_) {
std::lock_guard<std::mutex> lk(odom_mu_);
snap.have_height = true;
snap.height_z = height_->z();
snap.height_sigma = height_->sigma();
snap.on_slope = height_->on_slope();
}
{
std::lock_guard<std::mutex> lk(safety_mu_);
@@ -2121,6 +2768,9 @@ void Runtime::WebLoop() {
snap.ground_truth = have_gt_latched ? gt_latched
: source_->sim->ground_truth();
source_->sim->true_tilt(&snap.gt_roll, &snap.gt_pitch);
// Do cao san THAT duoi robot. Chi khac 0 khi world co dia hinh (doc,
// san cao); uoc luong hien van la 2D nen day la thuoc do cho no.
snap.gt_z = source_->sim->ground_truth_3d().z;
}
// pose_map = map_correction * pose_odom.
@@ -2175,7 +2825,10 @@ void Runtime::WebLoop() {
}
snap.slam.voxels_source = voxels_source;
#endif
if (slam_map_) snap.map = slam_map_;
if (slam_map_) {
snap.map = slam_map_;
snap.map_floor = slam_map_floor_;
}
} else {
snap.pose_map = ekf_pose;
snap.slam.mode = !snap.slam.reloc.empty() ? "dinh vi lai"
@@ -2185,6 +2838,7 @@ void Runtime::WebLoop() {
// Dang dinh vi lai: ban do DB dung san luc Init.
if (slam_map_) {
snap.map = slam_map_;
snap.map_floor = slam_map_floor_;
snap.slam.map_version = static_cast<uint32_t>(slam_published_version_);
}
snap.voxels = slam_voxels_;

View File

@@ -28,6 +28,7 @@
#include <atomic>
#include <chrono>
#include <deque>
#include <functional>
#include <memory>
#include <map>
@@ -39,9 +40,12 @@
#include "app_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/ekf_se2.h"
#include "vslam/elevation_map.h"
#include "vslam/gamepad.h"
#include "vslam/geometry.h"
#include "vslam/height_estimator.h"
#include "vslam/perception_pipeline.h"
#include "vslam/scan_leveler.h"
#include "vslam/safety_monitor.h"
#include "vslam/scan_sanitizer.h"
#include "vslam/teleop_model.h"
@@ -90,6 +94,11 @@ struct RuntimeOptions {
// Kinh vo hinh voi LiDAR va depth; chi sieu am thay. Dung de chay nhanh
// US_BLOCKED va BUMPER cua FSM -- hai nhanh chua bao gio chay end-to-end.
double sim_glass_at = 0.0;
// Ve camera mo phong bang GPU (vslam_sim_gl): depth + anh IR co texture.
// Can --world va node build voi -DVSLAM_SIM_WITH_GL=ON.
bool sim_gl = false;
// Tan so PHAT IMU cua sim (SimConfig::imu_output_hz). 0 = moi buoc vat ly.
double sim_imu_hz = 0.0;
bool force_slam = false; // --slam: ghi de slam.yaml enabled
bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM
std::string slam_db;
@@ -127,6 +136,8 @@ class Runtime {
// wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20
// file .launch cua ban ROS.
StatusResponse Wire();
// Di tren doc: mot khung depth -> ban do do cao san cuc bo (luong camera).
void AddDepthToElevation(const CameraFrame& f);
// runtime.cc
StatusResponse OpenSource();
@@ -168,6 +179,19 @@ class Runtime {
bool RelocPlanDrive(const LaserScan& scan, const Pose2D& odom);
void RelocStartSweep();
void RelocHalt(const std::string& why);
// Dang dung tren doc (che do doc bat, nghieng than so voi trong luc qua
// nguong) -> vong dinh vi lai DUNG YEN, khong xoay robot. `deg`: goc nghieng.
bool RelocOnSlope(double* deg = nullptr) const;
// Khoang thoang PHIA TRUOC (+-15 do, frame base) theo scan; 0 = khong co tia
// nao trong quat do (khong biet -> khong di).
double RelocFrontClear(const LaserScan& scan) const;
// Che do doc: pose robot `p` (map) co hop khong -- dung tren o TRONG cua ban do, va
// do doc ban do tai do gay ra dung do nghieng IMU (roll/pitch) dang do.
bool RelocPoseAdmissible(const Pose2D& p, double tilt_r, double tilt_p) const;
// Quyet dinh cho vong DUNG YEN: trung vi `static_rounds` vong lien tiep cung
// nguoi thang thay cho mot vong. `*along_axis` = bi chan vi mu doc truc.
RelocVerdict RelocStaticDecide(const RelocMatch& m, const Pose2D& odom, double shift_ratio,
bool use_shift, bool* along_axis, std::string* why);
// Sau khi CHOT: cho robot DUNG YEN, gom scan luc dung yen (khong nhoe do
// quay), khop cuc bo quanh pose vua chot roi moi dat pose ban dau.
void RelocSettle(const LaserScan& scan, const Pose2D& odom,
@@ -228,12 +252,26 @@ class Runtime {
// web_tx doc.
mutable std::mutex scan_mu_;
LaserScanPtr latest_scan_;
// Scan cho SLAM / dinh vi lai / canh lac: BU NGHIENG khi slope_on_ (xem
// ScanLeveler), con lai CHINH la latest_scan_. An toan + web dung ban tho.
LaserScanPtr latest_slam_scan_;
// odom_mu_: wheel_odom_ va ekf_. CHI luong source cham vao chung; hai luong
// kia chi doc ban sao pose.
mutable std::mutex odom_mu_;
Odometry latest_odom_;
bool have_odom_ = false;
// Lich su pose EKF (moi buoc encoder, ~2 s) de SLAM lay pose DUNG LUC QUET.
// Ghep scan voi pose HIEN TAI thi luc quay tai cho 0.6 rad/s, tre 20 ms la
// lech 0.7 do -- lien ket ICP ke can o cho quay mang lech goc do vao do
// thi va xoay ca ban do (do trong sim doc 04/10: 0.56 do -> 0.2 m sau 20 m
// hanh lang).
struct OdomAt {
UnixTime stamp;
Pose2D pose;
double z = 0.0;
};
std::deque<OdomAt> odom_hist_;
// perc_mu_: ket qua perception.
mutable std::mutex perc_mu_;
@@ -325,6 +363,8 @@ class Runtime {
size_t last_map_occ_ = 0;
size_t last_map_free_ = 0;
OccupancyGridPtr slam_map_;
// Do cao san cua ban do (che do doc), cung phien ban voi slam_map_.
std::shared_ptr<const MapFloorGrid> slam_map_floor_;
double slam_process_ms_ = 0.0;
int slam_loops_ = 0;
// Phat hien KE CAN -- co che cat sai so cong don that su cua SLAM scan-only.
@@ -355,6 +395,21 @@ class Runtime {
double reloc_swept_ = 0.0; // rad da xoay trong vong gom nay
Pose2D reloc_prev_odom_;
bool reloc_have_prev_ = false;
// Vong gom nay DUNG YEN tren doc (chot luc dau vong, xem RelocOnSlope): khong
// xoay, gom scan tai cho vai giay roi khop -- bo khop da thu moi huong.
bool reloc_static_round_ = false;
// Do nghieng (do) va luc no doi qua nguong lan cuoi -- cho on dinh truoc vong dau.
double reloc_tilt_ref_deg_ = -1.0;
std::chrono::steady_clock::time_point reloc_tilt_ref_t_;
// Ket qua cac vong DUNG YEN lien tiep cung nguoi thang (xem DecideStatic),
// va tom tat cac CHO dung truoc (moi lan bo tren doc chot mot cho).
std::vector<StaticRound> reloc_static_hist_;
std::vector<StaticPlace> reloc_static_places_;
// Tu chay tren doc: so lan khop tai cho o CHO hien tai, quang da BO tren doc
// (tong, co tran), va pha DI hien tai co phai la mot lan BO khong.
int reloc_static_here_ = 0;
double reloc_slope_creep_ = 0.0;
bool reloc_creeping_ = false;
std::chrono::steady_clock::time_point reloc_t0_; // dau vong gom
std::chrono::steady_clock::time_point reloc_epoch_; // moc thoi gian cho tracker
int reloc_cycle_ = 0;
@@ -472,6 +527,36 @@ class Runtime {
std::atomic<double> tilt_roll_{0.0};
std::atomic<double> tilt_pitch_{0.0};
std::atomic<bool> tilt_accel_ok_{false};
// GravityAlign da khoi tao (co mau IMU) -- truoc do roll/pitch = 0 gia. Dinh
// vi lai tren doc CHO co nay roi moi quyet xoay hay dung yen.
std::atomic<bool> tilt_valid_{false};
// ---- Di tren doc (slam.yaml `slope:`) ----
// slope_on_ doc-only sau Start(). Tat thi KHONG doi tuong nao duoi day
// duoc tao, va moi duong cu giu nguyen.
bool slope_on_ = false;
// Duoi odom_mu_: luong encoder cong buoc, luong slam neo.
std::unique_ptr<HeightEstimator> height_;
// elev_mu_: ban do do cao san cuc bo + thong ke bu nghieng scan. THU TU
// KHOA: odom_mu_ roi moi elev_mu_, KHONG BAO GIO nguoc lai.
mutable std::mutex elev_mu_;
std::unique_ptr<ElevationMap> elev_;
ScanLevelerConfig level_cfg_;
ScanLevelStats level_stats_;
UnixTime elev_pruned_;
// Tinh, doc-only sau Start(): base_link <- laser_link / camera optical.
Transform laser_to_base_static_ = TransformIdentity();
Transform cam_to_base_static_ = TransformIdentity();
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).
bool height_anchored_ = false;
// CHI luong slam: lan thu vong dong xa cuoi (far_loops).
std::chrono::steady_clock::time_point far_loops_at_{};
uint64_t far_loops_added_ = 0;
uint64_t heights_version_ = 0;
std::chrono::steady_clock::time_point heights_at_{};
std::atomic<bool> estop_{false};
std::atomic<bool> stop_{false};

View File

@@ -18,10 +18,14 @@
#include "runtime.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/json_parse.h"
#include "vslam/log.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
namespace vslam {
@@ -36,8 +40,32 @@ StatusResponse Runtime::Wire() {
// rieng thi "cai nao chay truoc" la mot bay co that.
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.
LaserScanPtr slam_scan = copy;
if (slope_on_ && cfg_->slope.level_scan) {
Pose2D od;
double z = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
z = height_->z();
}
const double roll = tilt_roll_.load(std::memory_order_relaxed);
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
auto lv = std::make_shared<LaserScan>();
{
std::lock_guard<std::mutex> lk(elev_mu_);
LevelScan(*copy, laser_to_base_static_, roll, pitch,
cfg_->robot.geometry().wheel_radius, od, z, elev_.get(), level_cfg_,
lv.get(), &level_stats_);
}
slam_scan = lv;
}
std::lock_guard<std::mutex> lk(scan_mu_);
latest_scan_ = copy;
latest_slam_scan_ = slam_scan;
});
}
@@ -55,6 +83,7 @@ StatusResponse Runtime::Wire() {
tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed);
tilt_accel_ok_.store(perception_->gravity().accel_ok(),
std::memory_order_relaxed);
tilt_valid_.store(perception_->gravity().valid(), std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(odom_mu_);
wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z);
@@ -162,8 +191,29 @@ StatusResponse Runtime::Wire() {
gyro_ok ? std::max(2.4e-7 * dt, 1e-12) : 1e9;
const double var_tr = std::max(o.twist.covariance[0] * dt * dt, 1e-12);
ekf_->UpdateOdomDelta(e.stamp, d_trans, d_theta, d_theta_gyro,
// Di tren doc: z cong tu quang duong DOC mat doc; EKF (SE(2)) nhan
// quang duong NGANG -- doc 15 do ma khong chieu thi ban do gian 3.4%.
double d_trans_ekf = d_trans;
if (slope_on_) {
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
height_->OnWheelStep(d_trans, pitch);
if (cfg_->slope.horizontal_odom) d_trans_ekf = d_trans * std::cos(pitch);
}
ekf_->UpdateOdomDelta(e.stamp, d_trans_ekf, d_theta, d_theta_gyro,
var_tr, var_th_enc, var_th_gyro);
if (slope_on_) {
// Vet banh: san duoi robot o dung z robot. Thu tu khoa odom_mu_ ->
// elev_mu_ (xem runtime.h).
const Pose2D p = ekf_->pose();
std::lock_guard<std::mutex> lk2(elev_mu_);
elev_->AddFootprint(p.x, p.y, height_->z(), 0.15, e.stamp);
}
// Lich su pose cho SLAM (pose LUC QUET, xem runtime.h).
odom_hist_.push_back(OdomAt{e.stamp, ekf_->pose(), slope_on_ ? height_->z() : 0.0});
while (odom_hist_.size() > 2 &&
SecondsBetween(e.stamp, odom_hist_.front().stamp) > 2.0) {
odom_hist_.pop_front();
}
}
gyro_dtheta_ = 0.0;
gyro_dt_ = 0.0;
@@ -234,6 +284,9 @@ StatusResponse Runtime::Wire() {
have_depth_ = true;
}
// Di tren doc: depth -> ban do do cao san cuc bo (cho ScanLeveler).
if (slope_on_ && have_cam_to_base_) AddDepthToElevation(f);
// Ca chuoi perception chay INLINE o day: depth -> cloud -> loc ->
// can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong
// camera.
@@ -397,4 +450,62 @@ StatusResponse Runtime::Wire() {
return StatusResponse::Ok();
}
void Runtime::AddDepthToElevation(const CameraFrame& f) {
const Image& d = *f.depth;
if (d.data == nullptr || d.width == 0 || d.height == 0) return;
const CameraInfo& ci = f.depth_info;
const double fx = ci.fx_binned(), fy = ci.fy_binned();
const double cx = ci.cx_binned(), cy = ci.cy_binned();
if (fx <= 0.0 || fy <= 0.0) return;
Pose2D od;
double z = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
z = height_->z();
}
const double roll = tilt_roll_.load(std::memory_order_relaxed);
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
// base_footprint DA CAN <- optical: CHUNG TiltLift voi GravityAlign va
// ScanLeveler -- ba ban hinh hoc lech nhau la lop loi da co trong repo cu.
const Transform fp_from_cam = TransformCompose(
TiltLift(roll, pitch, cfg_->robot.geometry().wheel_radius), cam_to_base_static_);
const double c = std::cos(od.theta), s = std::sin(od.theta);
const int stride = std::max(1, cfg_->slope.depth_stride);
const double dmax = cfg_->slope.elevation_max_depth_m;
std::vector<PointXYZ> pts;
pts.reserve((d.width / stride + 1) * (d.height / stride + 1));
for (uint32_t v = 0; v < d.height; v += static_cast<uint32_t>(stride)) {
const uint8_t* row = d.data + static_cast<size_t>(v) * d.step;
for (uint32_t u = 0; u < d.width; u += static_cast<uint32_t>(stride)) {
double depth = 0.0;
if (d.format == PixelFormat::kMono16) {
uint16_t raw;
std::memcpy(&raw, row + 2 * u, 2);
depth = raw * static_cast<double>(d.depth_scale);
} else if (d.format == PixelFormat::kFloat32) {
float raw;
std::memcpy(&raw, row + 4 * u, 4);
depth = raw;
} else {
return;
}
if (!(depth > 0.2) || depth > dmax) continue;
const Point p = TransformPoint(
fp_from_cam, Point{(u - cx) / fx * depth, (v - cy) / fy * depth, depth});
pts.push_back(PointXYZ{static_cast<float>(od.x + c * p.x - s * p.y),
static_cast<float>(od.y + s * p.x + c * p.y),
static_cast<float>(z + p.z)});
}
}
std::lock_guard<std::mutex> lk(elev_mu_);
elev_->AddPoints(pts, f.header.stamp);
if (SecondsBetween(f.header.stamp, elev_pruned_) > 1.0) {
elev_->Prune(od.x, od.y, f.header.stamp);
elev_pruned_ = f.header.stamp;
}
}
} // namespace vslam

View File

@@ -178,13 +178,17 @@ mcu:
# duoi CHI co nghia voi `esp`.
protocol: wt61pc
# wt61pc: /dev/imu do luat udev tao (cap FTDI 0403:6001 -> SYMLINK+="imu");
# 9600 la baud mac dinh cua cam bien. Cong duoc KHOA DOC QUYEN: chuong trinh
# khac (imu_ros_node cua motor_control) mo cong sau se loi EBUSY.
# wt61pc: /dev/imu do luat udev tao (configuration_files/udev/99-imu.rules: cap
# FTDI 0403:6001 -> SYMLINK+="imu", latency_timer 1 ms). Cam bien DA DOI
# sang 115200 baud / 200 Hz (2026-10-06, luu trong cam bien; xuat xuong
# 9600 / 10 Hz). Day la baud HOST nghe, phai trung baud da luu trong cam
# bien: sai thi IMU im, log "checksum sai". Cong duoc KHOA DOC QUYEN:
# chuong trinh khac (imu_ros_node cua motor_control) mo cong sau se loi
# EBUSY.
# esp: /dev/ttyACM0 @ 115200 theo firmware that. Gia tri cu la 921600 --
# doc sai baud cho ra RAC chu khong cho ra loi, nen no hong im lang.
port: /dev/imu
baud: 9600
baud: 115200
# ClockSync khop micros() cua MCU voi dong ho host bang fit tuyen tinh.
#
@@ -259,7 +263,14 @@ mcu:
# ⚠️ 0.07 do duoc tren duong ESP32 + USB-CDC. Voi protocol: wt61pc (UART
# thang, khong ESP32) duong truyen khac, nen DO LAI bang quy trinh o tren
# truoc khi tin con so nay.
imu_lag_sec: 0.07
#
# --- 2026-10-06: 115200 baud / 200 Hz -> 0.01 la UOC LUONG, CHUA DO ---
# ~2 ms day 2 khung Acc+Gyro qua day 115200 baud
# ~3-10 ms loc / trung binh noi bo o che do 200 Hz (o 10 Hz la ~50 ms)
# ~1 ms USB (latency_timer 1 ms, xem luat udev)
# Giu 0.07 o 200 Hz la lech gyro ~60 ms. Do lai theo quy trinh tren: may do
# co bin 10 ms, nen lan chay sau bao ~0 ms la dat.
imu_lag_sec: 0.01
# Ban ghi encoder `E,<micros>,<ticks_l>,<ticks_r>` la MO RONG moi -- giao
# thuc cu chi co I/B/P.

View File

@@ -170,6 +170,68 @@ voxel:
# Tuong va ban ghe dung yen thi nhieu node thay nen van giu.
min_node_hits: 3
# ============ 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
# khong bao gio noi duoc -- sai so cuoi vong o lai trong ban do. Khoi nay: sau
# moi node, tim node CU (cach >= min_graph_gap buoc) trong ban kinh radius_m
# theo do thi, ICP giua hai scan (Icp/* cua chinh ban do), nhan neu chinh <
# max_corr, them lien ket.
#
# Do trong sim (slope_test, vong 52 m, 04/10):
# khong co (cu) cuoi vong lech 11.7 cm
# RGBD/ProximityMaxGraphDepth 0 van 0 lien ket ve dau vong
# detectMoreLoopClosures cua RTAB-Map TE HON: 33 cm -- them hang tram
# lien ket giua node CUNG luot trong hanh lang, ICP khong rang buoc doc
# truc keo ban do truot
# far_loops (khoi nay) 1.5 cm, 2 lien ket
#
# Ban kinh 1 m: chi ghep node ma do thi DA cho la cung cho -- khong tao vong
# giua hai noi khac nhau tru khi ban do da vo san. Tat: enabled: false.
far_loops:
enabled: true
radius_m: 1.0
min_graph_gap: 100 # ~10 m quang duong o RGBD/LinearUpdate 0.1
max_corr_m: 0.5
max_corr_deg: 10.0
period_s: 1.0
# ============ DI TREN DOC (G4) ============
# Pose SLAM van la SE(2) (Reg/Force3DoF). Khoi nay them, BEN CANH no:
# * z robot = tich -ds*sin(pitch IMU), kep ve 0 khi |pitch| < clamp_deg, neo
# vao z cua node ban do o che do localization;
# * z / roll / pitch luu vao MOI node (userData cua RTAB-Map) -> ban do 3D va
# lop vat can tinh theo SAN cuc bo, doc khong con bi coi la tuong;
# * quang duong banh x cos(pitch) truoc EKF (odometry NGANG);
# * scan cho SLAM / dinh vi lai duoc bu nghieng va bo tia cham san / mat doc
# (ban do do cao san cuc bo tu depth). Lop AN TOAN van dung scan tho.
#
# ⚠️ CAN IMU >= 100 Hz. Do trong sim (G3, 03/10): IMU 100 Hz -> sai dz qua doc
# 1.5 m trung vi 1.8 cm, max 8 cm; IMU 10 Hz (WT61PC mac dinh, 9600 baud) ->
# 19 cm, va khong chinh bo loc nao cuu duoc. Doi cam bien sang 115200 baud /
# 100 Hz va dat `mcu.baud: 115200` trong sensors.yaml TRUOC khi bat.
#
# ⚠️ Gioi han NOI RO: doc that < clamp_deg bi coi la phang; tuong gia o chan
# doc LEN chi bo duoc khi camera da thay mat doc truoc do (re vao doc o goc
# hep thi con). Nhieu tang chong len nhau tai cung (x, y) KHONG ho tro.
#
# enabled: false = moi duong cu giu nguyen.
slope:
enabled: false
clamp_deg: 1.5 # duoi nguong = mat bang (doc xe lan >= 2.9 do)
sigma_rel: 0.05 # sai he thong tren doc: 5% do cao da leo
sigma_flat: 0.005 # troi tren mat bang, m / sqrt(m)
sigma_anchor: 0.03 # sai z ban do dung de neo
anchor_radius_m: 0.6 # neo vao node trong ban kinh nay
horizontal_odom: true
level_scan: true
floor_margin_m: 0.08 # cao hon san da biet duoi nguong = cham san
below_ground_m: 0.05 # thap hon mat dat duoi robot = san duoi chan doc
elevation_cell_m: 0.10
elevation_radius_m: 8.0
elevation_max_depth_m: 4.0
depth_stride: 4 # lay 1/4 x 1/4 diem anh depth cho ban do do cao
# ============ KHOI RTAB-MAP ============
# Ghi de len mac dinh cua du an (xem BuildRtabmapParams). De trong thi dung
# mac dinh -- do la lua chon dung cho hau het truong hop.

View File

@@ -0,0 +1,15 @@
# /dev/imu cho IMU WT61PC qua cap USB-FTDI (0403:6001) -- sensors.yaml `mcu.port`.
#
# latency_timer=1: cap FTDI day byte len host moi 1 ms thay vi 16 ms (mac dinh).
# O 200 Hz (5 ms/mau) 16 ms la ~3 mau den cung mot luc, stamp IMU giat.
# Wt61pcBridge log `imu: latency_timer cap FTDI = N ms` luc mo cong.
#
# Nguon: goi imu_uart cua namnc (ROS 2), 2026-10-06. Cai tren Jetson, mot lan:
# sudo cp configuration_files/udev/99-imu.rules /etc/udev/rules.d/
# sudo udevadm control --reload-rules && sudo udevadm trigger
# ls -l /dev/imu # -> ttyUSBn
# cat /sys/bus/usb-serial/devices/ttyUSB*/latency_timer # phai ra 1
#
# Luat khop MOI cap FTDI 0403:6001: cam them mot cap cung loai thi ca hai deu
# tranh ten /dev/imu.
KERNEL=="ttyUSB*", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE="0666", GROUP="robotics", SYMLINK+="imu", ATTR{latency_timer}="1", RUN+="/bin/chmod 777 /dev/%k"

View File

@@ -45,3 +45,11 @@ endif()
if(VSLAM_BUILD_SIM)
add_subdirectory(vslam_sim)
endif()
# Ve anh camera mo phong bang GPU (anh IR + depth tu mesh co texture that).
# TUY CHON, chi may dev co GPU: sim van chay khong co no (depth raycast CPU,
# khong co anh IR).
option(VSLAM_SIM_WITH_GL "Ve camera mo phong bang GPU (EGL + GLES3 + assimp)" OFF)
if(VSLAM_BUILD_SIM AND VSLAM_SIM_WITH_GL)
add_subdirectory(vslam_sim_gl)
endif()

View File

@@ -73,6 +73,10 @@ enum class VsrStream : uint8_t {
// bao "xanh" cho mot he da mat hai nhanh an toan.
kUltrasonic = 11,
kBumper = 12,
// MO RONG: tu the THAT 6-DoF, CHI ban ghi tu bo mo phong. De cham diem
// offline (VO/VIO, z tren doc). Replay khong dua no vao duong ong nao --
// khong stage nao duoc doc su that.
kGroundTruth = 13,
};
const char* VsrStreamName(VsrStream s);
@@ -109,6 +113,11 @@ bool DecodeUltrasonicPayload(const std::string& buf, double* range, size_t* coun
void EncodeBumperPayload(uint32_t mask, std::string* out);
bool DecodeBumperPayload(const std::string& buf, uint32_t* mask);
// Ground truth 6-DoF: sau double x, y, z, roll, pitch, yaw cua base_footprint
// trong frame world (z = do cao san duoi robot; pitch duong = mui chuc xuong).
void EncodeGroundTruthPayload(const double pose6[6], std::string* out);
bool DecodeGroundTruthPayload(const std::string& buf, double pose6[6]);
void EncodeCameraInfoPayload(const CameraInfo& info, std::string* out);
bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out);

View File

@@ -37,6 +37,7 @@
#include <thread>
#include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
@@ -323,22 +324,30 @@ class RealSenseDriver : public CameraInterface {
depth_img->data = static_cast<const uint8_t*>(depth.get_data());
depth_img->keep_alive = keep; // KHONG copy: giu frameset song
} else {
Decimate16(praw, sw, sh, static_cast<int>(cfg_.decimate), &depth_buf_,
// MOI khung mot bo dem RIENG tu pool, anh giu no qua keep_alive.
//
// ⚠️ Truoc day la MOT bo dem dung chung, "hop le toi lan goi Loop()
// sau" -- du cho perception chay INLINE trong callback, nhung SlamLoop
// giu khung depth/IR moi nhat qua Rtabmap::process (100-600 ms) tren
// luong KHAC, va `BuildSensorData` boc cv::Mat quanh bo dem ma khong
// copy. Khung sau (33 ms) ghi de giua chung: anh luu vao DB co the la
// nua khung nay nua khung kia.
auto buf = buf_pool_->Acquire();
Decimate16(praw, sw, sh, static_cast<int>(cfg_.decimate), buf.get(),
&depth_img->width, &depth_img->height);
depth_img->step = depth_img->width * 2;
depth_img->data = depth_buf_.data();
// Bo dem cua ta: hop le toi lan goi Loop() sau. Consumer chay INLINE
// trong callback (xem PerceptionPipeline) nen dieu do la du.
depth_img->data = buf->data();
depth_img->keep_alive = buf;
}
out.depth = depth_img;
if (cfg_.enable_infra1) {
rs2::video_frame ir = fs.get_infrared_frame(1);
if (ir) out.infra1 = WrapIr(ir, out.header, keep, &ir1_buf_);
if (ir) out.infra1 = WrapIr(ir, out.header, keep);
}
if (cfg_.enable_infra2) {
rs2::video_frame ir = fs.get_infrared_frame(2);
if (ir) out.infra2 = WrapIr(ir, out.header, keep, &ir2_buf_);
if (ir) out.infra2 = WrapIr(ir, out.header, keep);
}
out.depth_info = info_;
@@ -354,8 +363,7 @@ class RealSenseDriver : public CameraInterface {
}
ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr,
const std::shared_ptr<FrameKeepAlive>& keep,
std::vector<uint8_t>* buf) {
const std::shared_ptr<FrameKeepAlive>& keep) {
auto img = std::make_shared<Image>();
img->header = hdr;
img->format = PixelFormat::kMono8;
@@ -367,10 +375,13 @@ class RealSenseDriver : public CameraInterface {
img->data = static_cast<const uint8_t*>(ir.get_data());
img->keep_alive = keep;
} else {
// Bo dem rieng moi khung, nhu depth o tren.
auto buf = buf_pool_->Acquire();
Decimate8(static_cast<const uint8_t*>(ir.get_data()), w, h,
static_cast<int>(cfg_.decimate), buf, &img->width, &img->height);
static_cast<int>(cfg_.decimate), buf.get(), &img->width, &img->height);
img->step = img->width;
img->data = buf->data();
img->keep_alive = buf;
}
return img;
}
@@ -384,7 +395,10 @@ class RealSenseDriver : public CameraInterface {
float depth_scale_ = 0.001f;
CameraInfo info_;
std::vector<uint8_t> depth_buf_, ir1_buf_, ir2_buf_;
// Bo dem anh da decimate (depth + IR). Moi khung lay bo dem rieng va tra
// ve pool khi KHONG CON AI giu anh -- 0 malloc o trang thai on dinh.
std::shared_ptr<BufferPool<std::vector<uint8_t>>> buf_pool_ =
BufferPool<std::vector<uint8_t>>::Create(12);
std::atomic<bool> running_{false};
std::thread thread_;

View File

@@ -121,6 +121,7 @@ const char* VsrStreamName(VsrStream s) {
case VsrStream::kEvent: return "event";
case VsrStream::kUltrasonic: return "ultrasonic";
case VsrStream::kBumper: return "bumper";
case VsrStream::kGroundTruth: return "ground_truth";
}
return "?";
}
@@ -225,6 +226,15 @@ bool DecodeBumperPayload(const std::string& buf, uint32_t* mask) {
return r.ok;
}
void EncodeGroundTruthPayload(const double pose6[6], std::string* o) {
for (int i = 0; i < 6; ++i) PutF64(o, pose6[i]);
}
bool DecodeGroundTruthPayload(const std::string& buf, double pose6[6]) {
Reader r(buf);
for (int i = 0; i < 6; ++i) pose6[i] = r.F64();
return r.ok;
}
void EncodeEncoderPayload(double l, double rr, std::string* o) {
PutF64(o, l);
PutF64(o, rr);

View File

@@ -7,6 +7,7 @@
#include <mutex>
#include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/log.h"
#include "vslam/record_io.h"
#include "vslam/scan_sanitizer.h"
@@ -163,9 +164,20 @@ struct ReplaySource::Impl {
// roi phat mot lan khi thay chunk depth ke tiep hoac khi het file.
CameraFrame pending_frame;
bool have_pending = false;
std::vector<uint8_t> depth_storage;
std::vector<uint8_t> infra1_storage;
std::vector<uint8_t> infra2_storage;
// Kho nho cho anh giai ma. MOI anh mot kho rieng, giu qua keep_alive:
// SlamLoop giu khung moi nhat qua Rtabmap::process tren luong khac, va ba
// kho dung chung (nhu truoc day) bi khung sau ghi de giua chung.
std::shared_ptr<BufferPool<std::vector<uint8_t>>> img_pool =
BufferPool<std::vector<uint8_t>>::Create(12);
// Giai ma mot anh vao kho rieng. null neu payload hong.
ImagePtr DecodeImage(const std::string& payload) {
auto img = std::make_shared<Image>();
auto storage = img_pool->Acquire();
if (!DecodeImagePayload(payload, img.get(), storage.get())) return nullptr;
img->keep_alive = storage;
return img;
}
CameraInfo last_info;
bool have_info = false;
@@ -360,22 +372,22 @@ void ReplaySource::Run() {
case VsrStream::kDepth: {
// Chunk depth moi = khung truoc da day du -> phat khung truoc.
impl_->FlushCameraFrame();
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->depth_storage)) break;
ImagePtr img = impl_->DecodeImage(payload);
if (!img) break;
impl_->pending_frame.header = img->header;
impl_->pending_frame.depth = img;
impl_->have_pending = true;
break;
}
case VsrStream::kInfra1: {
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->infra1_storage)) break;
ImagePtr img = impl_->DecodeImage(payload);
if (!img) break;
impl_->pending_frame.infra1 = img;
break;
}
case VsrStream::kInfra2: {
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->infra2_storage)) break;
ImagePtr img = impl_->DecodeImage(payload);
if (!img) break;
impl_->pending_frame.infra2 = img;
break;
}
@@ -385,6 +397,10 @@ void ReplaySource::Run() {
}
break;
}
case VsrStream::kGroundTruth:
// Su that tu bo mo phong: chi de cham diem offline. KHONG dua vao
// duong ong -- khong stage nao duoc doc no.
break;
case VsrStream::kCmdVel:
// Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra.
// Replay khong tu dong ap chung: viec do do wiring quyet dinh.

View File

@@ -10,7 +10,10 @@
// ho host. O day khong co MCU, nen stamp lay tu dong ho HOST luc nhan xong
// khung gyro. De jitter khong chui thang vao stamp: cap USB-FTDI gom byte
// theo latency_timer (mac dinh 16 ms), nen mot lan read() co the mang nhieu
// khung. Thoi diem cua mot khung duoc suy NGUOC tu luc read() tra ve, tru
// khung. Driver bat ASYNC_LOW_LATENCY (ftdi_sio -> 1 ms) va luat udev
// configuration_files/udev/99-imu.rules dat san 1 ms: o 200 Hz (5 ms/mau)
// 16 ms la ~3 mau mot lan doc. Log luc mo cong bao gia tri that.
// Thoi diem cua mot khung duoc suy NGUOC tu luc read() tra ve, tru
// di thoi gian truyen cua cac byte toi sau no trong cung lan doc.
// Phan tre con lai (loc noi bo cua cam bien + thoi gian truyen khung) la
// HANG SO, tru bang `mcu.imu_lag_sec`. Con so 0.07 do duoc tren duong ESP32;
@@ -39,13 +42,17 @@
#include <errno.h>
#include <fcntl.h>
#include <linux/serial.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <memory>
#include <mutex>
#include <string>
@@ -74,6 +81,28 @@ speed_t BaudConstant(uint32_t baud) {
}
}
// Cap FTDI gom byte latency_timer ms roi moi day len host (mac dinh 16 ms; o
// 200 Hz la ~3 mau mot lan). ASYNC_LOW_LATENCY -> ftdi_sio dat 1 ms. Cong khong
// phai FTDI (pty khi test) thi ioctl loi -> bo qua.
void SetLowLatency(int fd) {
serial_struct ss{};
if (::ioctl(fd, TIOCGSERIAL, &ss) != 0) return;
ss.flags |= ASYNC_LOW_LATENCY;
::ioctl(fd, TIOCSSERIAL, &ss);
}
// latency_timer (ms) cua cap FTDI sau `port` (/dev/imu -> ttyUSB0); -1 = khong
// doc duoc (khong phai FTDI, hoac khong co sysfs).
int FtdiLatencyMs(const std::string& port) {
char real[PATH_MAX];
if (::realpath(port.c_str(), real) == nullptr) return -1;
const char* name = std::strrchr(real, '/');
std::ifstream f(std::string("/sys/class/tty/") + (name != nullptr ? name + 1 : real) +
"/device/latency_timer");
int ms = -1;
return (f >> ms) ? ms : -1;
}
class Wt61pcBridge : public McuInterface {
public:
Wt61pcBridge(const McuConfig& cfg, ClockPtr clock)
@@ -112,6 +141,13 @@ class Wt61pcBridge : public McuInterface {
<< ", doc quyen cong. Stamp lay tu dong ho HOST luc nhan xong "
"khung gyro, tru imu_lag_sec = " << cfg_.imu_lag_sec * 1000.0
<< " ms -- do lai bang log `wheel_odom/lag` sau khi doi nguon IMU.");
const int lat = FtdiLatencyMs(cfg_.port);
if (lat > 2) {
VSLAM_WARN("imu: latency_timer cap FTDI = " << lat << " ms -- moi lan doc gom nhieu "
"mau, stamp IMU giat. Cai configuration_files/udev/99-imu.rules (1 ms).");
} else if (lat >= 0) {
VSLAM_INFO("imu: latency_timer cap FTDI = " << lat << " ms");
}
if (cfg_.baud <= 9600) {
VSLAM_INFO("imu: 9600 baud chi du ~29 Hz (cam bien mac dinh 10 Hz). "
"wheel_odom bo gyro khi IMU cham hon encoder -- xem muc mcu "
@@ -195,6 +231,7 @@ class Wt61pcBridge : public McuInterface {
<< std::strerror(errno) << ") -- chuong trinh khac mo cong "
"sau se chia nhau luong byte.");
}
SetLowLatency(fd);
::tcflush(fd, TCIOFLUSH); // bo byte cu, tranh bat dau giua mot khung
fd_ = fd;
return StatusResponse::Ok();

View File

@@ -7,6 +7,7 @@ vslam_add_library(vslam_odometry
PUBLIC_HDRS
wheel_odometry.h
ekf_se2.h
height_estimator.h
PUBLIC_DEPS
vslam_common
FIND_DEPS

View File

@@ -0,0 +1,102 @@
#ifndef VSLAM_HEIGHT_ESTIMATOR_H
#define VSLAM_HEIGHT_ESTIMATOR_H
// Do cao z cua robot (base_footprint) khi di tren doc: bo loc Kalman MOT
// chieu.
//
// ================== VI SAO KHONG LAY TU SLAM ==================
// Pose SLAM la SE(2) (`Reg/Force3DoF`): RTAB-Map khong co z. Lop nay tinh z
// BEN CANH, roi z di vao node ban do (userData), ban do 3D va web.
//
// ================== DU DOAN ==================
// dz = -ds * sin(pitch)
// ds = quang duong banh (DOC mat doc), pitch = GravityAlign (duong = mui chuc
// xuong, nen len doc pitch am). Da so trong sim (G3, 03/10): IMU 100 Hz cho sai
// dz qua doc 1.5 m trung vi 1.8 cm, max 8 cm -- tot hon odometry thi giac F2M
// (6 / 33 cm). IMU 10 Hz thi KHONG du (19 cm): bo loc bu cua GravityAlign o
// 10 Hz co hang so thoi gian 5 s, bias gyro bi khuech dai thanh ~0.6 do.
//
// KEP MAT BANG: |pitch| < clamp -> dz = 0. Bias gia toc ke 0.02 m/s^2 lam
// lech pitch 0.12 do = 21 cm troi moi 100 m tren san PHANG; kep la triet tieu
// no. Doi lai: doc that < clamp (mac dinh 1.5 do) bi coi la phang -- 1 do qua
// 30 m la 52 cm mat. Doc tiep can cho xe lan la >= 2.9 do (1:20), nen nguong
// 1.5 do khong cat doc nao trong pham vi du an.
//
// ================== NEO ==================
// `Anchor(z_ref)`: z cua ban do tai cho robot dang dung (node gan nhat). Do
// khong chac lon dan theo do cao DA LEO tu lan neo truoc (sai ti le tren doc)
// va theo quang duong (sai nho tren phang), nen sau mot doan doc thi neo keo
// manh, tren san phang thi neo keo nhe. Lech qua xa -> tu choi (node sai tang,
// sai cho).
//
// ⚠️ Sai tren doc la sai HE THONG (truot banh, lech pitch cung dau suot doan
// doc), nen no tang TUYEN TINH theo do cao da leo: sigma = rel * sum|dz|.
// Cong phuong sai tung buoc (sum (rel*dz)^2) la coi moi buoc doc lap -- ra
// sigma 3 mm sau 1.4 m doc thay vi 7 cm, va neo khong keo duoc gi.
//
// Khong khoa: nguoi goi giu mutex (luong encoder ghi, luong slam neo).
#include <cstdint>
namespace vslam {
struct HeightEstimatorConfig {
double clamp_rad = 0.0261799; // 1.5 do: duoi nguong = mat bang, dz = 0
// Sai tuong doi cua dz tren doc (truot banh, sai pitch): sigma = rel * |dz|
// cong don tu lan neo truoc.
double sigma_rel = 0.05;
// Troi tren mat bang, m / sqrt(m): sigma = flat * sqrt(quang duong).
double sigma_flat = 0.005;
// Sai cua z ban do dung de neo (z node + noi suy theo doc), m.
double sigma_anchor = 0.03;
// Neo lech hon max(gate_min, gate_sigma * sigma) thi tu choi.
double gate_min = 0.30;
double gate_sigma = 4.0;
};
struct HeightEstimatorStats {
uint64_t steps = 0;
uint64_t clamped = 0; // buoc bi kep ve 0 (mat bang)
uint64_t anchors = 0;
uint64_t anchors_rejected = 0;
double last_anchor_err = 0.0; // z_ref - z truoc khi neo
double climbed = 0.0; // tong |dz| da cong
};
class HeightEstimator {
public:
explicit HeightEstimator(HeightEstimatorConfig cfg = {});
// Dat lai z (vd sau dinh vi lai: z cua ban do tai pose moi). sigma = do
// khong chac ban dau.
void Reset(double z, double sigma);
// Mot buoc banh: ds co dau (lui = am), pitch cua than LUC do.
void OnWheelStep(double ds, double pitch);
// Keo z ve z_ref (z ban do tai cho robot). Tra false neu bi tu choi.
bool Anchor(double z_ref);
double z() const { return z_; }
double sigma() const;
double pitch() const { return pitch_; } // pitch cua buoc cuoi
bool on_slope() const { return on_slope_; } // buoc cuoi KHONG bi kep
const HeightEstimatorStats& stats() const { return stats_; }
const HeightEstimatorConfig& config() const { return cfg_; }
private:
HeightEstimatorConfig cfg_;
double P() const;
double z_ = 0.0;
double P_base_ = 0.0; // phuong sai sau lan neo / reset cuoi
double climb_ = 0.0; // sum |dz| tu do
double dist_ = 0.0; // sum |ds| tu do
double pitch_ = 0.0;
bool on_slope_ = false;
HeightEstimatorStats stats_;
};
} // namespace vslam
#endif // VSLAM_HEIGHT_ESTIMATOR_H

View File

@@ -0,0 +1,60 @@
#include "vslam/height_estimator.h"
#include <algorithm>
#include <cmath>
#include <utility>
namespace vslam {
HeightEstimator::HeightEstimator(HeightEstimatorConfig cfg) : cfg_(std::move(cfg)) {}
void HeightEstimator::Reset(double z, double sigma) {
z_ = z;
P_base_ = sigma * sigma;
climb_ = 0.0;
dist_ = 0.0;
}
double HeightEstimator::P() const {
const double rel = cfg_.sigma_rel * climb_;
return P_base_ + rel * rel + cfg_.sigma_flat * cfg_.sigma_flat * dist_;
}
double HeightEstimator::sigma() const { return std::sqrt(P()); }
void HeightEstimator::OnWheelStep(double ds, double pitch) {
stats_.steps++;
pitch_ = pitch;
on_slope_ = std::fabs(pitch) >= cfg_.clamp_rad;
double dz = 0.0;
if (on_slope_) {
dz = -ds * std::sin(pitch);
} else {
stats_.clamped++;
}
z_ += dz;
stats_.climbed += std::fabs(dz);
climb_ += std::fabs(dz);
dist_ += std::fabs(ds);
}
bool HeightEstimator::Anchor(double z_ref) {
const double err = z_ref - z_;
stats_.last_anchor_err = err;
const double R = cfg_.sigma_anchor * cfg_.sigma_anchor;
const double P_now = P();
const double gate = std::max(cfg_.gate_min, cfg_.gate_sigma * std::sqrt(P_now + R));
if (std::fabs(err) > gate) {
stats_.anchors_rejected++;
return false;
}
const double K = P_now / (P_now + R);
z_ += K * err;
P_base_ = (1.0 - K) * P_now;
climb_ = 0.0;
dist_ = 0.0;
stats_.anchors++;
return true;
}
} // namespace vslam

View File

@@ -19,6 +19,8 @@ vslam_add_library(vslam_perception
gravity_align.h
cliff_detect.h
perception_pipeline.h
elevation_map.h
scan_leveler.h
FIND_DEPS
vslam_common
)

View File

@@ -0,0 +1,72 @@
#ifndef VSLAM_ELEVATION_MAP_H
#define VSLAM_ELEVATION_MAP_H
// Ban do do cao SAN cuc bo, frame odom: moi o 10 cm giu do cao THAP NHAT da
// thay (diem depth) hoac do cao noi banh xe DA cham (vet robot).
//
// ================== VI SAO ==================
// LiDAR mot mat phang cao 0.2165 m tren san. Lai tren san phang toi chan mot
// doc len, tia ngang cham mat doc o 0.2165 / tan(goc) truoc chan doc (15 do:
// 0.81 m, 30 do: 0.38 m) -- mot "buc tuong" tai MOT diem co dinh tren the gioi,
// tuc trong y het tuong that va bi ve vao ban do (G0, 03/10). Rieng scan thi
// khong phan biet duoc. Camera thay mat doc tu 1.1 m den ~4 m TRUOC khi robot
// toi do, nen tich lai do cao san o day roi hoi lai khi loc scan
// (ScanLeveler). Camera mu duoi 1.1 m, nen phai TICH LAI qua thoi gian, khong
// dung duoc mat na depth tung khung.
//
// Gia tri moi o la MIN: o co ca san lan vat can (chan tuong, chan ban) van ra
// do cao san mien la camera thay duoc chan. Nhieu depth keo min xuong vai cm
// -- an toan cho phep "cham san?" (nguong 8 cm).
//
// KHONG khoa -- nguoi goi giu mutex.
#include <cstdint>
#include <unordered_map>
#include <vector>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct ElevationMapConfig {
double cell_m = 0.10;
// Bo o xa robot hon / cu hon nguong nay (Prune). z robot troi dan, nen o
// cu lau thi do cao cua no khong con cung goc voi z hien tai.
double radius_m = 8.0;
double max_age_sec = 60.0;
};
class ElevationMap {
public:
explicit ElevationMap(ElevationMapConfig cfg = {});
// Diem DA o frame odom (x, y, z tuyet doi).
void AddPoints(const std::vector<PointXYZ>& pts, UnixTime stamp);
// Banh xe dang cham san tai (x, y) o do cao z: moi o trong ban kinh r lay
// DUNG z (ghi de -- vet banh la do cao san chac chan nhat).
void AddFootprint(double x, double y, double z, double r, UnixTime stamp);
// Do cao san tai (x, y); false neu chua biet.
bool FloorAt(double x, double y, double* z) const;
void Prune(double cx, double cy, UnixTime now);
void Clear() { cells_.clear(); }
size_t size() const { return cells_.size(); }
const ElevationMapConfig& config() const { return cfg_; }
private:
struct Cell {
float z;
int64_t stamp_ns;
};
uint64_t Key(double x, double y) const;
ElevationMapConfig cfg_;
std::unordered_map<uint64_t, Cell> cells_;
};
} // namespace vslam
#endif // VSLAM_ELEVATION_MAP_H

View File

@@ -0,0 +1,70 @@
#ifndef VSLAM_SCAN_LEVELER_H
#define VSLAM_SCAN_LEVELER_H
// Bu nghieng scan LiDAR cho SLAM 2D tren doc.
//
// ================== VAN DE ==================
// RTAB-Map 2D coi moi diem scan nam tren MOT mat phang ngang. Tren doc thi sai
// theo hai kieu:
// 1. Than nghieng -> tia nghieng: tuong cach 2 m tren doc 15 do doc ra
// 2 / cos(15) = 2.07 m, va goc cua tia lech di (tia 45 do -> 46 do).
// 2. Tia CHAM SAN / MAT DOC: dung tren san phang truoc doc len, tia cham
// mat doc o 0.2165 / tan(goc) (tuong gia co dinh tren the gioi); dang
// xuong doc (chuc mui), tia cham san duoi chan doc.
//
// ================== CACH LAM ==================
// Moi tia: diem cham -> frame base_link (ngoai lai tinh) -> base_footprint DA
// CAN trong luc (TiltLift, CHUNG ham voi GravityAlign / CliffDetect) -> do cao
// h so voi mat dat duoi robot, va do cao tuyet doi H = z_robot + h.
// * Biet do cao san tai do (ElevationMap) va H - san < floor_margin -> tia
// cham san/doc -> BO (NaN).
// * Khong biet san va h < -below_ground -> diem THAP hon cho robot dung, tuc
// san duoi chan doc khi dang xuong -> BO.
// * Con lai: chieu xuong mat phang ngang, tinh lai khoang cach va goc tu goc
// LiDAR (vi tri TINH trong base_link -- RTAB-Map dat lai diem dung cho do),
// xep vao o goc gan nhat, giu tia gan nhat moi o.
// Tia bo thanh NaN ("khong do duoc"), KHONG phai inf ("trong toi range_max"):
// inf se xoa trang ca vung sau mat doc tren luoi 2D.
//
// ⚠️ GIOI HAN: tuong gia khi tien toi chan doc LEN chi bo duoc neu camera da
// thay mat doc (ElevationMap co o do). Re vao chan doc o goc hep / camera bi
// che thi tuong gia van con.
//
// Chi cap cho SLAM / dinh vi lai / canh lac. Lop AN TOAN van dung scan THO:
// heuristic o day khong bao gio duoc xoa mot vat can that khoi luong dung xe.
#include <cstdint>
#include "vslam/elevation_map.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct ScanLevelerConfig {
// Diem cao hon san da biet duoi nguong nay = cham san / mat doc.
double floor_margin = 0.08;
// Khong biet san: diem thap hon mat dat duoi robot qua nguong nay = san duoi
// chan doc.
double below_ground = 0.05;
};
struct ScanLevelStats {
uint64_t scans = 0;
uint64_t rays = 0; // tia huu han vao
uint64_t kept = 0;
uint64_t dropped_floor = 0; // cham san theo ElevationMap
uint64_t dropped_below = 0; // thap hon mat dat duoi robot
uint64_t rebinned = 0; // doi sang o goc khac sau khi chieu
};
// laser_to_base: base_link <- laser_link (tinh). roll/pitch: nghieng than
// (GravityAlign). odom: base_footprint trong odom; z_robot: do cao robot
// (HeightEstimator). em co the null.
void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
double pitch, double wheel_radius, const Pose2D& odom, double z_robot,
const ElevationMap* em, const ScanLevelerConfig& cfg, LaserScan* out,
ScanLevelStats* stats);
} // namespace vslam
#endif // VSLAM_SCAN_LEVELER_H

View File

@@ -0,0 +1,66 @@
#include "vslam/elevation_map.h"
#include <cmath>
#include <utility>
namespace vslam {
ElevationMap::ElevationMap(ElevationMapConfig cfg) : cfg_(std::move(cfg)) {}
uint64_t ElevationMap::Key(double x, double y) const {
// Hai chi so 32 bit co dau gop vao 64 bit KHONG dau: dich trai so am la hanh
// vi khong xac dinh truoc C++20.
const int32_t ix = static_cast<int32_t>(std::floor(x / cfg_.cell_m));
const int32_t iy = static_cast<int32_t>(std::floor(y / cfg_.cell_m));
return (static_cast<uint64_t>(static_cast<uint32_t>(ix)) << 32) | static_cast<uint32_t>(iy);
}
void ElevationMap::AddPoints(const std::vector<PointXYZ>& pts, UnixTime stamp) {
const int64_t ns = stamp.toNSec();
for (const PointXYZ& p : pts) {
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
auto it = cells_.find(Key(p.x, p.y));
if (it == cells_.end()) {
cells_.emplace(Key(p.x, p.y), Cell{p.z, ns});
} else {
if (p.z < it->second.z) it->second.z = p.z;
it->second.stamp_ns = ns;
}
}
}
void ElevationMap::AddFootprint(double x, double y, double z, double r, UnixTime stamp) {
const int64_t ns = stamp.toNSec();
const int n = static_cast<int>(std::ceil(r / cfg_.cell_m));
for (int dx = -n; dx <= n; ++dx) {
for (int dy = -n; dy <= n; ++dy) {
const double px = x + dx * cfg_.cell_m, py = y + dy * cfg_.cell_m;
if (std::hypot(px - x, py - y) > r) continue;
cells_[Key(px, py)] = Cell{static_cast<float>(z), ns};
}
}
}
bool ElevationMap::FloorAt(double x, double y, double* z) const {
auto it = cells_.find(Key(x, y));
if (it == cells_.end()) return false;
*z = it->second.z;
return true;
}
void ElevationMap::Prune(double cx, double cy, UnixTime now) {
const int64_t now_ns = now.toNSec();
const int64_t max_age = static_cast<int64_t>(cfg_.max_age_sec * 1e9);
for (auto it = cells_.begin(); it != cells_.end();) {
const int32_t ix = static_cast<int32_t>(static_cast<uint32_t>(it->first >> 32));
const int32_t iy = static_cast<int32_t>(static_cast<uint32_t>(it->first & 0xffffffffu));
const double x = (ix + 0.5) * cfg_.cell_m, y = (iy + 0.5) * cfg_.cell_m;
if (std::hypot(x - cx, y - cy) > cfg_.radius_m || now_ns - it->second.stamp_ns > max_age) {
it = cells_.erase(it);
} else {
++it;
}
}
}
} // namespace vslam

View File

@@ -0,0 +1,87 @@
#include "vslam/scan_leveler.h"
#include <cmath>
#include <limits>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
namespace vslam {
void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
double pitch, double wheel_radius, const Pose2D& odom, double z_robot,
const ElevationMap* em, const ScanLevelerConfig& cfg, LaserScan* out,
ScanLevelStats* stats) {
ScanLevelStats local;
ScanLevelStats& st = stats != nullptr ? *stats : local;
st.scans++;
*out = in;
const size_t n = in.ranges.size();
if (n == 0 || in.angle_increment == 0.0f) 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);
// base_footprint (can trong luc) <- laser_link.
const Transform fp_from_laser =
TransformCompose(TiltLift(roll, pitch, wheel_radius), laser_to_base);
// Goc LiDAR TINH tren mat phang ngang (RTAB-Map dat diem bang ngoai lai
// tinh, nen tinh lai khoang cach/goc tu dung goc do).
const double lx0 = laser_to_base.translation.x, ly0 = laser_to_base.translation.y;
const double laser_yaw = YawFromQuaternion(laser_to_base.rotation);
const double c_th = std::cos(odom.theta), s_th = std::sin(odom.theta);
// Luot 1: tia KHONG huu han va sentinel cua sector mask giu nguyen o cu.
// Sentinel (> range_max) = than robot bi cat -- khong tia nao duoc de len.
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;
}
}
// Luot 2: tia huu han -> chieu, loc, xep lai.
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (!std::isfinite(r) || r > in.range_max) continue;
st.rays++;
const double a = in.angle_min + static_cast<double>(i) * in.angle_increment;
const Point p = TransformPoint(fp_from_laser, Point{r * std::cos(a), r * std::sin(a), 0.0});
const double h = p.z;
const double wx = odom.x + c_th * p.x - s_th * p.y;
const double wy = odom.y + s_th * p.x + c_th * p.y;
double floor = 0.0;
if (em != nullptr && em->FloorAt(wx, wy, &floor)) {
if (z_robot + h - floor < cfg.floor_margin) {
st.dropped_floor++;
continue;
}
} else if (h < -cfg.below_ground) {
st.dropped_below++;
continue;
}
const double dx = p.x - lx0, dy = p.y - ly0;
const double rh = std::hypot(dx, dy);
const double ah = NormalizeAngle(std::atan2(dy, dx) - laser_yaw);
const long j = std::lround((ah - in.angle_min) / in.angle_increment);
if (j < 0 || j >= static_cast<long>(n) || masked[static_cast<size_t>(j)]) continue;
if (static_cast<size_t>(j) != i) st.rebinned++;
float& slot = out->ranges[static_cast<size_t>(j)];
if (!std::isfinite(slot) || rh < slot) {
slot = static_cast<float>(rh);
if (!out->intensities.empty() && i < in.intensities.size()) {
out->intensities[static_cast<size_t>(j)] = in.intensities[i];
}
}
st.kept++;
}
}
} // namespace vslam

View File

@@ -9,6 +9,7 @@ find_package(yaml-cpp REQUIRED)
vslam_add_library(vslam_sim
PUBLIC_HDRS
sim_source.h
sim_camera_renderer.h
occupancy_map_io.h
gazebo_world.h
PUBLIC_DEPS

View File

@@ -57,8 +57,17 @@ struct WorldModel {
// `CGMClassic` mot minh ra bao loi 239 x 111 m, va ca the gioi phinh tu
// 25x51 m len 263x146 m.
double sx = 1.0, sy = 1.0, sz = 1.0;
// Model DIA HINH: mat robot di LEN duoc (san, doc, chieu nghi), khong phai
// vat can. Nhan bang TEN model (`kTerrainModelPrefix`), KHONG bang phap
// tuyen: mat ban, mat giuong, mat ghe cung huong len, va lay theo phap
// tuyen la cho robot leo len ban.
bool terrain = false;
};
// Model co ten bat dau bang chuoi nay la dia hinh. Xem `WorldModel::terrain`.
constexpr const char* kTerrainModelPrefix = "vslam_terrain_";
struct GazeboWorld {
std::string world_path;
std::vector<WorldModel> models;
@@ -80,9 +89,13 @@ StatusResponse LoadGazeboWorld(const std::string& world_path,
// Raster hoa mesh VA CHAM cua world thanh luoi chiem dung 2D.
//
// Chi lay tam giac nam trong dai do cao [z_min, z_max] so voi SAN: do la dai
// ma LiDAR 2D thuc su quet. Lay het moi do cao se bien ca mat san thanh vat
// can, va lay qua cao se bo lot ban ghe.
// Chi lay tam giac nam trong dai do cao [z_min, z_max] tinh tu MAT SAN CUC BO
// cua tung o: do la dai ma LiDAR 2D thuc su quet. Lay het moi do cao se bien
// ca mat san thanh vat can, va lay qua cao se bo lot ban ghe.
//
// World khong co model dia hinh thi mat san o moi o la 0 -- dung y het truoc
// day. Co dia hinh (san cao, doc) thi dai z TRUOT theo san: mot cai tu dung
// tren san tang 2 cao 1.5 m van la vat can, va mat doc KHONG thanh tuong.
//
// `resolution` met/o. `pad` la vien trong them quanh bao loi, tinh bang met.
struct WorldRasterOptions {
@@ -92,10 +105,28 @@ struct WorldRasterOptions {
double pad = 1.0;
};
// Dia hinh rut tu world, cung kich thuoc va goc voi luoi.
struct WorldTerrain {
// Do cao mat tren cua dia hinh tai TAM moi o (m, he world). O khong co dia
// hinh = 0. Nhieu tam giac chong nhau thi lay cao nhat (mat tren).
std::vector<float> floor_z;
// Dinh cua vat can cao nhat trong moi o bi chiem (m, he world); 0 = o
// trong. Cho phep raycast 3D biet tuong cao toi dau thay vi gia dinh mot
// chieu cao chung.
std::vector<float> wall_top;
size_t terrain_cells = 0; // so o co dia hinh; 0 = world phang
float floor_min = 0.0f, floor_max = 0.0f;
};
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out);
// Nhu tren, va tra them dia hinh. `terrain` co the null.
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out, WorldTerrain* terrain);
// ---------------------------------------------------------------------------
// Chi muc doan 2D, de raycast trung MAT TUONG chu khong trung bien o
// ---------------------------------------------------------------------------
@@ -135,10 +166,15 @@ struct WorldSegments {
// LiDAR do duoc phai la thu robot dam vao. Vai model trong bo nay co hull va
// cham don gian hoa khac han mesh hien thi (do duoc: PatientWheelChair,
// nursesstation_01), va Gazebo cung hanh xu y het.
//
// Model dia hinh khong sinh doan nao (no la san, khong phai tuong). `floor_z`
// (tu `WorldTerrain`, cung kich thuoc `grid`) dua dai z ve mat san cuc bo;
// null = san phang o 0, y het truoc day.
StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt,
const OccupancyGrid& grid,
WorldSegments* out);
WorldSegments* out,
const std::vector<float>* floor_z = nullptr);
// ---------------------------------------------------------------------------
// Xuat hinh hoc cho khung 3D

View File

@@ -0,0 +1,51 @@
#ifndef VSLAM_SIM_CAMERA_RENDERER_H
#define VSLAM_SIM_CAMERA_RENDERER_H
// Ve anh camera cho bo mo phong.
//
// Interface nay KHONG phu thuoc do hoa: vslam_sim chi biet no, con cai dat GPU
// (EGL + OpenGL ES, texture that cua model) nam o lib TUY CHON vslam_sim_gl.
// Nho vay bo mo phong van build va chay tren Jetson / CI khong co GPU -- khi
// khong co renderer thi camera mo phong ve depth bang raycast CPU nhu cu va
// khong co anh IR.
#include <cstdint>
#include <string>
#include <vector>
namespace vslam {
// Tu the va noi suy cua MOT khung anh.
//
// Frame QUANG HOC theo quy uoc anh (giong RealSense va depth cua sim): +X
// phai, +Y xuong, +Z toi truoc. Pixel (u, v) co TAM tai toa do nguyen, kieu
// OpenCV: tia qua pixel u di theo ((u - cx) / fx, (v - cy) / fy, 1).
struct SimCameraView {
// Hang-chinh. Cot j la truc j cua frame quang hoc, viet trong world.
double R_wc[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
double t_wc[3] = {0, 0, 0}; // tam camera trong world, m
double fx = 0, fy = 0, cx = 0, cy = 0;
int width = 0, height = 0;
double near_m = 0.05, far_m = 30.0;
};
class SimCameraRenderer {
public:
virtual ~SimCameraRenderer() = default;
// Ve mot khung. `ir`: width*height byte, anh xam, HANG TREN CUNG TRUOC.
// `depth_z`: width*height float, Z-DEPTH (hinh chieu len truc quang) theo
// met; 0 = tia khong trung gi. Tra false neu khong ve duoc.
//
// ⚠️ Context GPU gan voi LUONG tao ra no: moi lan goi phai tren CUNG mot
// luong (luong vong mo phong).
virtual bool Render(const SimCameraView& view, std::vector<uint8_t>* ir,
std::vector<float>* depth_z) = 0;
// Mo ta ngan cho log, vd "NVIDIA GeForce RTX 4060 (EGL, GLES 3.2)".
virtual std::string Describe() const = 0;
};
} // namespace vslam
#endif // VSLAM_SIM_CAMERA_RENDERER_H

View File

@@ -35,12 +35,14 @@
// co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va
// toan bo duong ong du lieu.
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "vslam/clock.h"
#include "vslam/gazebo_world.h"
#include "vslam/sim_camera_renderer.h"
#include "vslam/driver_interfaces.h"
#include "vslam/vslam_common.h"
@@ -184,10 +186,37 @@ struct SimConfig {
// docs/SIM_VS_REAL.md cu phai ghi "kinh phai kiem bang du lieu that".
double glass_lidar_pass_rate = 1.0; // 1.0 = xuyen hoan toan
// Buoc VAT LY cua bo mo phong, va (mac dinh) tan so phat IMU.
double imu_rate_hz = 200.0;
double gyro_noise_stddev = 4.9e-4;
double accel_noise_stddev = 6.9e-3;
// ================== MO HINH IMU ==================
// kLegacy: cong thuc cu -- gia toc doc than + huong tam, gyro tu lo xo (va
// toc do doi nghieng do dia hinh). Giu nguyen tung byte ban ghi cu.
// kKinematic: gyro va gia toc ke tinh TU quy dao 6-DoF that cua DIEM DAT
// IMU (dao ham tu the, dao ham bac hai vi tri, cong trong luc). Tich phan
// IMU khop dung quy dao -- dieu kien toi thieu de thu VIO tren doc.
// kAuto: kKinematic khi dia hinh 3D bat, kLegacy khi khong.
enum class ImuModel { kAuto, kLegacy, kKinematic };
ImuModel imu_model = ImuModel::kAuto;
// Tan so PHAT IMU, Hz. 0 = moi buoc vat ly, nhu cu. Buoc vat ly van theo
// `imu_rate_hz`: ha tan so phat de giong WT61PC (10 Hz) khong keo ca dong
// hoc, LiDAR va camera xuong theo.
double imu_output_hz = 0.0;
// Mau phat ra la so do CU hon stamp bao nhieu giay (loc trong cam bien +
// truyen). Driver that tru `imu_lag_sec`; phan lech con lai la sai so dong
// bo camera-IMU ma VIO phai chiu.
double imu_delay_sec = 0.0;
// --- Chi mo hinh kKinematic (dung RNG RIENG, khong xao chuoi nhieu cu) ---
double gyro_bias_sigma = 0.0; // rad/s, sigma bias DAU moi truc
double accel_bias_sigma = 0.0; // m/s^2
double gyro_bias_rw = 0.0; // rad/s/sqrt(s), bias troi ngau nhien
double accel_bias_rw = 0.0; // m/s^2/sqrt(s)
double imu_lpf_hz = 0.0; // loc thong thap bac 1 trong cam bien; 0 = tat
// Vi tri diem dat IMU so voi base_link (robot.yaml: imu_link).
double imu_x = 0.0, imu_y = 0.0, imu_z = 0.06;
// ================== NGHIENG THAN ROBOT ==================
// Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG,
// quay gap lam no NGHIENG ra ngoai. Gazebo mo phong dieu nay qua vat ly
@@ -210,6 +239,29 @@ struct SimConfig {
bool follow_terrain_slope = true;
double wheelbase_for_slope = 0.44; // khoang cach truoc-sau de do doc
// ================== DIA HINH 3D (DOC, SAN NHIEU TANG) ==================
// Tat = hanh vi cu, giu NGUYEN tung byte: robot o z = 0, LiDAR quet mat
// phang ngang, camera o do cao co dinh. Do cao san chi de camera thay vuc.
//
// Bat thi robot di TREN mat san:
// * z = san duoi robot; roll/pitch theo dia hinh (truoc-sau, trai-phai);
// * lenh v la toc do BANH doc mat doc: di ngang v*cos(pitch), encoder
// dem quang duong doc doc;
// * LiDAR quet tia 3D nghieng theo than, cham doc/san/tuong that -- nen
// "tuong gia" o chan doc hien ra dung cho (0.2165 / tan(goc));
// * camera dat theo tu the 6-DoF; gyro thay toc do doi nghieng do dia hinh;
// * chenh san giua hai o ke nhau > max_step la vat can (mep bac, mep san
// cao) -- robot khong roi khoi mep doc.
//
// kAuto: bat khi world co model dia hinh (`vslam_terrain_*`).
enum class TerrainMode { kAuto, kOff, kOn };
TerrainMode terrain = TerrainMode::kAuto;
double max_step = 0.05; // m, chenh san toi da giua hai o ke nhau
// LiDAR nghieng theo CA lo xo giam xoc (mac dinh chi theo dia hinh). Than
// ngoc 2 do khi tang toc la tia cham san phang o ~6 m -- that, nhung lam
// nhieu moi bai do doc, nen de nut rieng.
bool lidar_follow_suspension = false;
double encoder_rate_hz = 50.0;
// ================== HAI LOAI TRUOT, RAT KHAC NHAU ==================
@@ -251,6 +303,23 @@ struct SimConfig {
double speed = 1.0;
};
// Tu the that 6-DoF cua robot (chi de danh gia).
//
// (x, y, z) la `base_footprint`: diem tren MAT SAN duoi tam robot, z la do
// cao san o do. roll/pitch la nghieng THAT cua than (dia hinh + lo xo), cung
// quy uoc voi `true_tilt` (pitch duong = mui chuc xuong).
struct SimPose3 {
double x = 0.0, y = 0.0, z = 0.0;
double roll = 0.0, pitch = 0.0, yaw = 0.0;
};
class RobotModel;
// Dien hinh hoc robot THAT (robot.yaml) vao cau hinh mo phong: banh, ban kinh
// than, vi tri LiDAR / camera / IMU. vslam_node va moi tool dung CHUNG ham
// nay -- sim va duong ong dung hai bo so khac nhau thi moi phep do deu do nham.
void SimConfigFromRobot(const RobotModel& robot, SimConfig* cfg);
// So huu ca bon nguon, y het ReplaySource.
class SimSource {
public:
@@ -281,6 +350,29 @@ class SimSource {
// z am = bac hut xuong / cau thang di xuong.
void SetFloorHeight(double x0, double y0, double x1, double y1, float z);
// Doc TUYEN TINH theo x: san tang deu tu `z_at_x0` (o x0) toi `z_at_x1` (o
// x1), khong doi theo y. Cho bai kiem dia hinh 3D khong can file world.
void SetFloorRamp(double x0, double y0, double x1, double y1, float z_at_x0,
float z_at_x1);
// Dia hinh 3D dang bat chua (sau Open(); xem SimConfig::terrain).
bool terrain_active() const;
// Tu the that 6-DoF. CHI de danh gia, nhu `ground_truth()`.
SimPose3 ground_truth_3d() const;
// Goi lai voi tu the that moi `1 / rate_hz` giay mo phong (0 = moi buoc vat
// ly), tren luong chay Run()/RunFor(). Cho tool GHI su that vao ban ghi de
// cham diem offline -- KHONG duoc noi vao duong ong uoc luong.
using GroundTruthCallback = std::function<void(UnixTime, const SimPose3&)>;
void SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz = 0.0);
// Ve camera bang renderer ngoai (GPU, vslam_sim_gl): depth VA anh IR
// (`CameraFrame::infra1`) tu mesh co texture, thay raycast CPU. null = raycast
// CPU nhu cu, khong co anh IR. Goi truoc Run(); renderer duoc goi tren luong
// vong mo phong.
void SetCameraRenderer(std::shared_ptr<SimCameraRenderer> r);
// Danh dau mot vung hinh chu nhat (toa do THE GIOI, met) la KINH.
//
// O kinh phai la o BI CHIEM trong ban do (data >= 50) -- kinh la vat can

View File

@@ -155,6 +155,7 @@ StatusResponse LoadGazeboWorld(const std::string& world_path,
if (uri.empty()) { skip++; continue; }
m.model_name = uri.substr(uri.rfind('/') + 1);
m.terrain = m.model_name.rfind(kTerrainModelPrefix, 0) == 0;
std::string root;
const std::string dir = ResolveModelUri(uri, roots, &root);
@@ -597,6 +598,12 @@ bool ReadObjTriangles(const std::string& path, std::vector<Tri>* out) {
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out) {
return RasterizeGazeboWorld(world, opt, out, nullptr);
}
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out, WorldTerrain* terrain) {
if (!(opt.resolution > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"resolution phai duong");
@@ -675,15 +682,70 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
// o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM.
out->data.assign(static_cast<size_t>(w) * h, 0);
// --- Luot 2: to tam giac trong dai do cao ---
// --- Luot 1.5: dia hinh -> do cao san ---
//
// Do cao mat tren tai TAM o, noi suy trong tam giac. Tam giac dung thang
// (suy bien tren mat bang) la mat ben cua doc/bac, khong dinh nghia san nen
// bo qua. Chong nhau thi lay CAO NHAT: mot hop kin co ca mat day lan mat tren.
const size_t n_cells = static_cast<size_t>(w) * h;
std::vector<float> ground(n_cells, 0.0f);
std::vector<uint8_t> covered(n_cells, 0);
size_t n_terrain_models = 0, n_terrain_cells = 0;
for (const Loaded& L : loaded) {
if (!L.m->terrain) continue;
n_terrain_models++;
for (const Tri& t : L.tris) {
const double ax = t.x[0], ay = t.y[0];
const double bx = t.x[1], by = t.y[1];
const double cx = t.x[2], cy = t.y[2];
const double den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
if (std::fabs(den) < 1e-12) continue;
const int cx0 = std::max(0, static_cast<int>((std::min({ax, bx, cx}) - minx) / res));
const int cx1 = std::min(static_cast<int>(w) - 1,
static_cast<int>((std::max({ax, bx, cx}) - minx) / res));
const int cy0 = std::max(0, static_cast<int>((std::min({ay, by, cy}) - miny) / res));
const int cy1 = std::min(static_cast<int>(h) - 1,
static_cast<int>((std::max({ay, by, cy}) - miny) / res));
for (int gy = cy0; gy <= cy1; ++gy) {
for (int gx = cx0; gx <= cx1; ++gx) {
const double px = minx + (gx + 0.5) * res;
const double py = miny + (gy + 0.5) * res;
const double l1 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / den;
const double l2 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / den;
const double l3 = 1.0 - l1 - l2;
if (l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9) continue;
const float z = static_cast<float>(l1 * t.z[0] + l2 * t.z[1] + l3 * t.z[2]);
const size_t idx = static_cast<size_t>(gy) * w + gx;
if (!covered[idx]) {
covered[idx] = 1;
ground[idx] = z;
n_terrain_cells++;
} else if (z > ground[idx]) {
ground[idx] = z;
}
}
}
}
}
// O khong co dia hinh la san 0, nen min/max luon tinh ca 0. World phang:
// fmin = fmax = 0 va luot 2 duoi day y het truoc.
float fmin = 0.0f, fmax = 0.0f;
for (float f : ground) { fmin = std::min(fmin, f); fmax = std::max(fmax, f); }
// --- Luot 2: to tam giac VAT CAN trong dai do cao, tinh tu san cuc bo ---
std::vector<float> top(n_cells, 0.0f);
size_t n_used = 0;
for (const Loaded& L : loaded) {
if (L.m->terrain) continue; // dia hinh la san, khong phai vat can
for (const Tri& t : L.tris) {
// Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua:
// mesh day dac nen mot tam giac bien bi bo van con hang xom phu.
//
// Day la phep loc THO theo dai cua ca ban do; dai dung cua tung o kiem
// ben duoi, theo san cua chinh o do.
const double tz0 = std::min({t.z[0], t.z[1], t.z[2]});
const double tz1 = std::max({t.z[0], t.z[1], t.z[2]});
if (tz1 < opt.z_min || tz0 > opt.z_max) continue;
if (tz1 < fmin + opt.z_min || tz0 > fmax + opt.z_max) continue;
n_used++;
// Bao loi cua tam giac, roi kiem tung o bang toa do trong tam.
@@ -721,7 +783,13 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9;
}
if (inside) {
out->data[static_cast<size_t>(gy) * w + gx] = 100;
const size_t idx = static_cast<size_t>(gy) * w + gx;
// Dai z cua RIENG o nay. World phang: san 0, trung phep loc tho
// o tren nen khong bo them o nao.
const double f = ground[idx];
if (tz1 < f + opt.z_min || tz0 > f + opt.z_max) continue;
out->data[idx] = 100;
if (tz1 > top[idx]) top[idx] = static_cast<float>(tz1);
}
}
}
@@ -734,6 +802,18 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
<< minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri
<< " tam giac (" << n_used << " trong dai z ["
<< opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem");
if (n_terrain_models > 0) {
VSLAM_INFO("world -> dia hinh: " << n_terrain_models << " model, "
<< n_terrain_cells << " o, san tu " << fmin << " den " << fmax
<< " m; dai z cua vat can tinh tu san cuc bo");
}
if (terrain != nullptr) {
terrain->floor_z = std::move(ground);
terrain->wall_top = std::move(top);
terrain->terrain_cells = n_terrain_cells;
terrain->floor_min = fmin;
terrain->floor_max = fmax;
}
return StatusResponse::Ok();
}
@@ -742,7 +822,8 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt,
const OccupancyGrid& grid,
WorldSegments* out) {
WorldSegments* out,
const std::vector<float>* floor_z) {
if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
}
@@ -759,6 +840,18 @@ StatusResponse BuildWorldSegments(const GazeboWorld& world,
const double ox = out->origin_x, oy = out->origin_y;
const int W = static_cast<int>(grid.width), H = static_cast<int>(grid.height);
// San cuc bo tai mot diem, de dai z truot theo dia hinh. Khong co ban do
// san thi la 0 -- y het truoc.
const bool have_floor =
floor_z != nullptr && floor_z->size() == static_cast<size_t>(W) * H;
auto floor_at = [&](double x, double y) -> double {
if (!have_floor) return 0.0;
const int fx = static_cast<int>(std::floor((x - ox) / res));
const int fy = static_cast<int>(std::floor((y - oy) / res));
if (fx < 0 || fy < 0 || fx >= W || fy >= H) return 0.0;
return (*floor_z)[static_cast<size_t>(fy) * grid.width + fx];
};
// --- Gom doan tu canh cua tam giac trong dai z ---
//
// Lay CA BA canh cua moi tam giac. Canh nam trong long vat the (vd canh cua
@@ -767,6 +860,7 @@ StatusResponse BuildWorldSegments(const GazeboWorld& world,
std::map<std::string, std::vector<Tri>> cache;
for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue;
if (m.terrain) continue; // dia hinh la san: tia cham no o raycast 3D
auto it = cache.find(m.model_name);
if (it == cache.end()) {
std::vector<Tri> tris;
@@ -789,7 +883,8 @@ StatusResponse BuildWorldSegments(const GazeboWorld& world,
}
const double zlo = std::min({Z[0], Z[1], Z[2]});
const double zhi = std::max({Z[0], Z[1], Z[2]});
if (zhi < opt.z_min || zlo > opt.z_max) continue;
const double f = floor_at((X[0] + X[1] + X[2]) / 3.0, (Y[0] + Y[1] + Y[2]) / 3.0);
if (zhi < f + opt.z_min || zlo > f + opt.z_max) continue;
for (int e = 0; e < 3; ++e) {
const int a = e, b = (e + 1) % 3;
out->seg.push_back(static_cast<float>(X[a]));

View File

@@ -1,21 +1,54 @@
#include "vslam/sim_source.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <deque>
#include <functional>
#include <mutex>
#include <random>
#include <thread>
#include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
#include "vslam/occupancy_map_io.h"
#include "vslam/robot_model.h"
#include <limits>
namespace vslam {
namespace {
// Raycast dia hinh 3D: chi noi suy san khi tia da xuong trong dai nay tren
// mat san cua o. Lon hon nhieu sai khac giua gia tri o va gia tri noi suy
// (o doc 30 do: < 1.5 cm), nho hon do cao LiDAR (0.2165 m).
constexpr double kSmoothFloorBand = 0.15;
// Ma tran xoay R = Rz(yaw) * Ry(pitch) * Rx(roll), REP-103: than -> the gioi.
// pitch DUONG = mui chuc xuong, roll DUONG = ben trai nhac len. Tinh MOT lan
// cho moi scan / moi khung anh, khong goi sin/cos cho tung tia.
struct Rot3 {
double m[9];
static Rot3 FromRPY(double roll, double pitch, double yaw) {
const double cr = std::cos(roll), sr = std::sin(roll);
const double cp = std::cos(pitch), sp = std::sin(pitch);
const double cy = std::cos(yaw), sy = std::sin(yaw);
Rot3 r;
r.m[0] = cy * cp; r.m[1] = cy * sp * sr - sy * cr; r.m[2] = cy * sp * cr + sy * sr;
r.m[3] = sy * cp; r.m[4] = sy * sp * sr + cy * cr; r.m[5] = sy * sp * cr - cy * sr;
r.m[6] = -sp; r.m[7] = cp * sr; r.m[8] = cp * cr;
return r;
}
void Apply(double x, double y, double z, double* ox, double* oy, double* oz) const {
*ox = m[0] * x + m[1] * y + m[2] * z;
*oy = m[3] * x + m[4] * y + m[5] * z;
*oz = m[6] * x + m[7] * y + m[8] * z;
}
};
// Bon lop nay la interface driver THAT, y het ReplaySource. vslam_node khong
// phan biet duoc phan cung / file .vsr / mo phong.
@@ -185,10 +218,18 @@ struct SimSource::Impl {
double us_acc = 0.0, bump_acc = 0.0;
bool bumper_now = false;
// Bo dem anh depth, cap phat mot lan. Anh khong so huu bo nho (xem
// vslam_common.h), nen bo dem nay phai song it nhat bang khung anh.
std::vector<uint8_t> depth_buf;
uint32_t depth_w = 0, depth_h = 0;
// Bo dem anh depth. Anh khong so huu bo nho (xem vslam_common.h), nen MOI
// khung lay mot bo dem rieng tu pool va giu no qua keep_alive -- SlamLoop
// giu khung moi nhat qua Rtabmap::process tren luong khac, va mot bo dem
// dung chung se bi khung sau ghi de giua chung.
std::shared_ptr<BufferPool<std::vector<uint8_t>>> depth_pool =
BufferPool<std::vector<uint8_t>>::Create(8);
// Renderer GPU tuy chon (SetCameraRenderer). null = raycast CPU, khong co IR.
std::shared_ptr<SimCameraRenderer> renderer;
std::vector<uint8_t> gl_ir;
std::vector<float> gl_depth;
bool gl_fail_logged = false;
std::shared_ptr<ReplayClock> clock;
// Trang thai that cua robot.
@@ -204,6 +245,39 @@ struct SimSource::Impl {
double terrain_pitch = 0.0; // nghieng do DIA HINH, cong vao than
double last_accel = 0.0;
// --- Dia hinh 3D (SimConfig::terrain). Tat thi khong truong nao duoi day
// duoc doc, va moi duong cu giu nguyen tung byte. ---
bool terrain_on = false; // chot o Open()
double ground_z = 0.0; // san duoi tam robot (base_footprint)
double terrain_roll = 0.0; // nghieng ngang do dia hinh
double terrain_pitch_rate = 0.0, terrain_roll_rate = 0.0;
// Goc dia hinh da co gia tri dau chua. Chua thi lan tinh dau KHONG sinh toc
// do goc -- neu khong, robot dat san tren doc se "quay" 10 do trong 5 ms.
bool terrain_ready = false;
bool steps_dirty = true; // san vua doi -> tinh lai mat na bac
std::vector<uint8_t> step_block; // o sat mep bac (chenh > max_step)
// Dinh vat can cao nhat moi o (he world, tu mesh). 0 = khong biet -> dung
// `wall_height` nhu cu.
std::vector<float> wall_top;
// --- IMU dong hoc (SimConfig::imu_model) va phat thua / tre ---
bool imu_kinematic = false; // chot o Open()
// RNG RIENG cho IMU dong hoc: dung chung `rng` se xao toan bo chuoi nhieu
// cua LiDAR/camera va moi ban ghi cu doi theo.
std::mt19937 imu_rng{1234};
Rot3 imu_R_prev{}; // tu the buoc truoc
double imu_p[3][3] = {}; // vi tri diem dat IMU: k-2, k-1, k
int imu_hist = 0; // so buoc da co lich su (toi da 3)
double imu_bg[3] = {0.0, 0.0, 0.0}, imu_ba[3] = {0.0, 0.0, 0.0};
bool imu_lpf_init = false;
double imu_lpf_w[3] = {0.0, 0.0, 0.0}, imu_lpf_f[3] = {0.0, 0.0, 0.0};
double imu_out_acc = 0.0;
std::deque<std::pair<double, ImuPtr>> imu_fifo; // (thoi diem DO, mau)
// --- Ground truth cho tool ghi ---
SimSource::GroundTruthCallback gt_cb;
double gt_period = 0.0, gt_acc = 0.0;
std::atomic<bool> stop{false};
mutable std::mutex state_mu;
Stats stats;
@@ -354,6 +428,82 @@ struct SimSource::Impl {
return inf;
}
// Do cao san NOI SUY SONG TUYEN giua tam cac o (chi dia hinh 3D).
//
// Gia tri tung o la bac thang 5 cm: o doc 30 do moi o nhay 2.9 cm, va
// robot / tia doc san se thay rang cua thay vi mat doc. Ngoai ban do kep vao
// o bien -- robot khong ra duoc ngoai (va cham), con tia ra ngoai thi raycast
// da dung tu truoc.
double FloorAtSmooth(double wx, double wy) const {
if (floor_z.empty() || !std::isfinite(wx) || !std::isfinite(wy)) return 0.0;
const int W = static_cast<int>(map.width), H = static_cast<int>(map.height);
const double fx = std::min(
std::max((wx - map.origin.position.x) / map.resolution - 0.5, 0.0), W - 1.0);
const double fy = std::min(
std::max((wy - map.origin.position.y) / map.resolution - 0.5, 0.0), H - 1.0);
const int x0 = static_cast<int>(fx), y0 = static_cast<int>(fy);
const int x1 = std::min(x0 + 1, W - 1), y1 = std::min(y0 + 1, H - 1);
const double tx = fx - x0, ty = fy - y0;
auto at = [&](int cx, int cy) {
return static_cast<double>(
floor_z[static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx)]);
};
const double a = at(x0, y0) * (1.0 - tx) + at(x1, y0) * tx;
const double b = at(x0, y1) * (1.0 - tx) + at(x1, y1) * tx;
return a * (1.0 - ty) + b * ty;
}
// O nao sat mep bac -- chenh san voi mot o ke > max_step. Danh dau CA HAI
// phia mep, va CellBlocked() coi chung nhu tuong: robot khong leo duoc
// len bac, cung khong roi khoi mep san cao.
void RebuildStepMask() {
const uint32_t W = map.width, H = map.height;
step_block.assign(static_cast<size_t>(W) * H, 0);
const float lim = static_cast<float>(cfg.max_step);
size_t n = 0;
for (uint32_t cy = 0; cy < H; ++cy) {
for (uint32_t cx = 0; cx < W; ++cx) {
const size_t i = static_cast<size_t>(cy) * W + cx;
const float f = floor_z[i];
const bool step = (cx + 1 < W && std::fabs(floor_z[i + 1] - f) > lim) ||
(cx > 0 && std::fabs(floor_z[i - 1] - f) > lim) ||
(cy + 1 < H && std::fabs(floor_z[i + W] - f) > lim) ||
(cy > 0 && std::fabs(floor_z[i - W] - f) > lim);
if (step) { step_block[i] = 1; n++; }
}
}
steps_dirty = false;
VSLAM_DEBUG("sim: mat na bac: " << n << " o chenh > " << cfg.max_step << " m");
}
// z, pitch, roll do DIA HINH tai tu the hien tai, va toc do doi cua chung
// (cho gyro). Bon diem do: truoc/sau cach nhau `wheelbase_for_slope`,
// trai/phai cach nhau `wheel_separation`.
void UpdateTerrainPose(double dt) {
const double hl = cfg.wheelbase_for_slope / 2.0;
const double hw = cfg.wheel_separation / 2.0;
const double c = std::cos(yaw), s = std::sin(yaw);
const double ff = FloorAtSmooth(x + hl * c, y + hl * s);
const double fb = FloorAtSmooth(x - hl * c, y - hl * s);
const double fl = FloorAtSmooth(x - hw * s, y + hw * c);
const double fr = FloorAtSmooth(x + hw * s, y - hw * c);
// Doc len phia truoc -> mui ngoc len -> pitch AM (quy uoc cu). Ben TRAI
// cao hon -> roll DUONG (quay quanh +X dua +Y len).
const double np = -std::atan2(ff - fb, 2.0 * hl);
const double nr = std::atan2(fl - fr, 2.0 * hw);
if (terrain_ready && dt > 0.0) {
terrain_pitch_rate = (np - terrain_pitch) / dt;
terrain_roll_rate = (nr - terrain_roll) / dt;
} else {
terrain_pitch_rate = 0.0;
terrain_roll_rate = 0.0;
terrain_ready = true;
}
terrain_pitch = np;
terrain_roll = nr;
ground_z = FloorAtSmooth(x, y);
}
// Do cao san tai mot diem the gioi. Ngoai ban do coi nhu phang.
float FloorAt(double wx, double wy) const {
const int cx = static_cast<int>(
@@ -567,7 +717,13 @@ struct SimSource::Impl {
// depth camera. Mot robot dich vu di vao cua kinh la truong hop that,
// va no la ly do nhanh US_BLOCKED cua FSM ton tai.
if (map.data[idx] >= 50 && !(idx < glass.size() && glass[idx])) {
const double lo = fz, hi = fz + cfg.wall_height;
const double lo = fz;
double hi = fz + cfg.wall_height;
// Dia hinh 3D: vat can cao dung bang mesh cua no. Tuong 4 m ben doc
// khong duoc thanh tuong 2 m chi vi san o day bang 0.
if (terrain_on && idx < wall_top.size() && wall_top[idx] > lo) {
hi = wall_top[idx];
}
if ((z_enter >= lo && z_enter <= hi) || (z_exit >= lo && z_exit <= hi) ||
(z_enter > hi && z_exit < lo) || (z_enter < lo && z_exit > hi)) {
// Chi tinh chinh theo mat phang XY: tuong trong dai z la thang dung,
@@ -581,8 +737,18 @@ struct SimSource::Impl {
// Cham san: tia tut xuong duoi mat san trong o nay. Noi suy tuyen tinh
// giua hai dau o de khong luong tu hoa khoang cach theo kich thuoc o.
const double gap_enter = z_enter - fz;
const double gap_exit = z_exit - fz;
//
// Dia hinh 3D: san tai hai dau o lay NOI SUY, de mat doc la mat phang
// chu khong phai bac thang. Chi tinh khi tia da xuong gan san -- tia
// LiDAR cach san 0.22 m bay qua hang tram o, va noi suy o moi o la
// phi.
double f_in = fz, f_out = fz;
if (terrain_on && std::min(z_enter, z_exit) < fz + kSmoothFloorBand) {
f_in = FloorAtSmooth(ox + dx * t_enter * res, oy + dy * t_enter * res);
f_out = FloorAtSmooth(ox + dx * t_exit * res, oy + dy * t_exit * res);
}
const double gap_enter = z_enter - f_in;
const double gap_exit = z_exit - f_out;
if (gap_enter > 0.0 && gap_exit <= 0.0) {
const double frac = gap_enter / (gap_enter - gap_exit);
return (t_enter + frac * (t_exit - t_enter)) * res;
@@ -614,8 +780,10 @@ struct SimSource::Impl {
cy >= static_cast<int>(map.height)) {
return true;
}
return map.data[static_cast<size_t>(cy) * map.width +
static_cast<size_t>(cx)] >= 50;
const size_t idx = static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx);
if (map.data[idx] >= 50) return true;
// Dia hinh 3D: mep bac / mep san cao cung chan nhu tuong.
return terrain_on && idx < step_block.size() && step_block[idx] != 0;
}
// Kiem va cham: lay 8 diem tren vanh robot.
@@ -649,11 +817,24 @@ struct SimSource::Impl {
prev_v = v;
// Tich phan pose THAT.
const double nx = x + v * std::cos(yaw) * dt;
const double ny = y + v * std::sin(yaw) * dt;
const double nyaw = NormalizeAngle(yaw + w * dt);
double nx, ny, nyaw;
if (terrain_on) {
// Lenh v la toc do BANH, doc mat san: di NGANG v*cos(pitch). Than quay
// quanh truc z CUA NO (dang nghieng), nen huong tren mat bang doi
// w*cos(roll)/cos(pitch) -- bo qua thi sai 15% o doc 30 do.
const double ct = std::cos(terrain_pitch);
const double cr = std::cos(terrain_roll);
nx = x + v * ct * std::cos(yaw) * dt;
ny = y + v * ct * std::sin(yaw) * dt;
nyaw = NormalizeAngle(yaw + w * cr / std::max(ct, 0.1) * dt);
} else {
nx = x + v * std::cos(yaw) * dt;
ny = y + v * std::sin(yaw) * dt;
nyaw = NormalizeAngle(yaw + w * dt);
}
std::lock_guard<std::mutex> lk(state_mu);
if (terrain_on && steps_dirty) RebuildStepMask();
if (Collides(nx, ny)) {
// Dung tai cho. Robot that se truot va quay, nhung "dung han" la mo
// hinh trung thuc hon voi mot robot dich vu co bumper cat nguon.
@@ -690,7 +871,10 @@ struct SimSource::Impl {
roll += roll_rate * dt;
// Nghieng do DIA HINH: do chenh lech do cao san giua truoc va sau robot.
if (cfg.follow_terrain_slope) {
if (terrain_on) {
// Ca z, pitch va roll, voi toc do doi cho gyro.
UpdateTerrainPose(dt);
} else if (cfg.follow_terrain_slope) {
const double half = cfg.wheelbase_for_slope / 2.0;
const double fz = FloorAt(x + half * std::cos(yaw), y + half * std::sin(yaw));
const double bz = FloorAt(x - half * std::cos(yaw), y - half * std::sin(yaw));
@@ -728,6 +912,45 @@ struct SimSource::Impl {
right_rad += vr / cfg.wheel_radius * dt;
}
// LiDAR tren dia hinh 3D: MOT mat phang quet gan cung vao than, nghieng
// theo dia hinh (va theo lo xo neu `lidar_follow_suspension`). Moi tia la
// tia 3D, cham tuong / vat can / MAT SAN that.
//
// Day la thu cho thay loi cua SLAM 2D tren doc: dung o san phang nhin vao
// chan doc goc t, tia ngang cham mat doc o 0.2165 / tan(t) -- mot "tuong"
// khong co that, va no lui dan khi robot tien len.
void FillScan3D(LaserScan* s) {
double rx, ry, rz, ryaw, rroll, rpitch;
{
std::lock_guard<std::mutex> lk(state_mu);
rx = x; ry = y; rz = ground_z; ryaw = yaw;
rroll = terrain_roll;
rpitch = terrain_pitch;
if (cfg.lidar_follow_suspension) { rroll += roll; rpitch += pitch; }
}
const Rot3 R = Rot3::FromRPY(rroll, rpitch, ryaw);
// Goc tia: base_footprint (tren san) + R * (lidar_x, 0, r_banh + lidar_z).
// `lidar_z` do tu TAM TRUC banh, nhu laser_link trong robot.yaml.
double ox, oy, oz;
R.Apply(cfg.lidar_x, 0.0, cfg.wheel_radius + cfg.lidar_z, &ox, &oy, &oz);
ox += rx; oy += ry; oz += rz;
std::normal_distribution<double> noise(0.0, cfg.lidar_noise_stddev);
for (uint32_t i = 0; i < cfg.lidar_samples; ++i) {
const double a = s->angle_min + i * s->angle_increment;
double dx, dy, dz;
R.Apply(std::cos(a), std::sin(a), 0.0, &dx, &dy, &dz);
const double r = RaycastDepth(ox, oy, oz, dx, dy, dz, cfg.lidar_range_max);
if (std::isinf(r)) {
s->ranges[i] = std::numeric_limits<float>::infinity();
} else {
const double rn = r + noise(rng);
s->ranges[i] = static_cast<float>(
rn < cfg.lidar_range_min ? cfg.lidar_range_min : rn);
}
}
}
LaserScanPtr MakeScan(UnixTime stamp) {
auto s = std::make_shared<LaserScan>();
s->header.stamp = stamp;
@@ -742,6 +965,11 @@ struct SimSource::Impl {
s->range_max = static_cast<float>(cfg.lidar_range_max);
s->ranges.resize(cfg.lidar_samples);
if (terrain_on) {
FillScan3D(s.get());
return s;
}
double rx, ry, ryaw;
{
std::lock_guard<std::mutex> lk(state_mu);
@@ -776,24 +1004,25 @@ struct SimSource::Impl {
const uint32_t w = cfg.depth_width / dec;
const uint32_t h = cfg.depth_height / dec;
if (depth_w != w || depth_h != h) {
depth_w = w;
depth_h = h;
depth_buf.assign(static_cast<size_t>(w) * h * 2, 0); // 16UC1
}
// 16UC1. Vong lap ben duoi ghi MOI diem anh, nen khong can xoa truoc.
auto buf = depth_pool->Acquire();
buf->resize(static_cast<size_t>(w) * h * 2);
std::vector<uint8_t>& depth_buf = *buf;
double rx, ry, ryaw;
double rx, ry, rz, ryaw;
{
std::lock_guard<std::mutex> lk(state_mu);
rx = x;
ry = y;
rz = ground_z;
ryaw = yaw;
}
// Vi tri camera trong the gioi.
const double cx_w = rx + cfg.camera_x * std::cos(ryaw);
const double cy_w = ry + cfg.camera_x * std::sin(ryaw);
const double cz_w = cfg.camera_z;
// Vi tri camera trong the gioi. Dia hinh 3D tinh lai ben duoi, theo tu the
// 6-DoF cua than.
double cx_w = rx + cfg.camera_x * std::cos(ryaw);
double cy_w = ry + cfg.camera_x * std::sin(ryaw);
double cz_w = cfg.camera_z;
// Noi suy tu HFOV. Anh da decimate nen fx/fy tinh theo kich thuoc DA
// giam; binning trong CameraInfo bao cho consumer biet dieu do.
@@ -810,12 +1039,80 @@ struct SimSource::Impl {
std::lock_guard<std::mutex> lk(state_mu);
body_roll = roll;
body_pitch = pitch + terrain_pitch;
if (terrain_on) body_roll += terrain_roll;
}
const double total_pitch = cfg.camera_pitch + body_pitch;
const double cp = std::cos(total_pitch), sp = std::sin(total_pitch);
const double cr_b = std::cos(body_roll), sr_b = std::sin(body_roll);
const double cy_r = std::cos(ryaw), sy_r = std::sin(ryaw);
// Dia hinh 3D: than xoay du ba goc, camera chuc `camera_pitch` TREN than.
// (Duong cu cong camera_pitch vao pitch cua than va xoay roll truoc --
// chi dung khi roll = 0, du cho san phang.)
const Rot3 R_body = Rot3::FromRPY(body_roll, body_pitch, ryaw);
const double ccp = std::cos(cfg.camera_pitch), csp = std::sin(cfg.camera_pitch);
if (terrain_on) {
R_body.Apply(cfg.camera_x, 0.0, cfg.camera_z, &cx_w, &cy_w, &cz_w);
cx_w += rx;
cy_w += ry;
cz_w += rz;
}
// Huong (don vi) trong THE GIOI cua mot huong trong frame quang hoc.
// Quang hoc -> than robot: +Z_quang = +X_than, +X_quang = -Y_than,
// +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo than.
// Raycast CPU va renderer GPU dung CHUNG ham nay, nen tia cua hai duong
// trung nhau tung pixel.
auto to_world = [&](double bx0, double by0, double bz0, double* wx, double* wy,
double* wz) {
if (terrain_on) {
// Chuc camera tren than (quanh y than), roi xoay theo than.
const double mx = bx0 * ccp + bz0 * csp;
const double mz = -bx0 * csp + bz0 * ccp;
R_body.Apply(mx, by0, mz, wx, wy, wz);
} else {
// Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch).
const double by1 = by0 * cr_b - bz0 * sr_b;
const double bz1 = by0 * sr_b + bz0 * cr_b;
const double px = bx0 * cp + bz1 * sp;
*wz = -bx0 * sp + bz1 * cp;
const double py = by1;
*wx = px * cy_r - py * sy_r;
*wy = px * sy_r + py * cy_r;
}
};
// Renderer GPU: ve CA khung mot lan (depth + IR), vong lap ben duoi chi
// ap nhieu. Ve hong thi khung nay quay ve raycast CPU.
bool use_gl = false;
if (renderer) {
SimCameraView view;
// Cot j cua R_wc = truc j cua frame quang hoc trong world.
double ax[3][3];
to_world(0.0, -1.0, 0.0, &ax[0][0], &ax[0][1], &ax[0][2]); // +X quang
to_world(0.0, 0.0, -1.0, &ax[1][0], &ax[1][1], &ax[1][2]); // +Y quang
to_world(1.0, 0.0, 0.0, &ax[2][0], &ax[2][1], &ax[2][2]); // +Z quang
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) view.R_wc[i * 3 + j] = ax[j][i];
}
view.t_wc[0] = cx_w;
view.t_wc[1] = cy_w;
view.t_wc[2] = cz_w;
view.fx = fx;
view.fy = fy;
view.cx = ppx;
view.cy = ppy;
view.width = static_cast<int>(w);
view.height = static_cast<int>(h);
view.far_m = std::max(cfg.depth_far, 1.0) + 1.0;
use_gl = renderer->Render(view, &gl_ir, &gl_depth);
if (!use_gl && !gl_fail_logged) {
gl_fail_logged = true;
VSLAM_WARN("sim: renderer GPU ve hong -- camera quay ve raycast CPU, KHONG co anh IR");
}
}
// Khong dung mot `normal_distribution` chung: sigma phu thuoc KHOANG
// CACH cua tung diem anh, nen phan phoi duoc dung ngay trong vong lap.
std::uniform_real_distribution<double> uni01(0.0, 1.0);
@@ -828,20 +1125,16 @@ struct SimSource::Impl {
const double oz = 1.0;
const double inv = 1.0 / std::sqrt(ox * ox + oy * oy + oz * oz);
// Quang hoc -> than robot: +Z_quang = +X_than, +X_quang = -Y_than,
// +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo yaw.
const double bx0 = oz * inv, by0 = -ox * inv, bz0 = -oy * inv;
// Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch).
const double by1 = by0 * cr_b - bz0 * sr_b;
const double bz1 = by0 * sr_b + bz0 * cr_b;
const double px = bx0 * cp + bz1 * sp;
const double pz = -bx0 * sp + bz1 * cp;
const double py = by1;
const double wx = px * cy_r - py * sy_r;
const double wy = px * sy_r + py * cy_r;
double d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far);
double d;
if (use_gl) {
// GPU tra thang Z-DEPTH; 0 = khong trung gi.
const float zg = gl_depth[static_cast<size_t>(v) * w + u];
d = zg > 0.0f ? static_cast<double>(zg) : std::numeric_limits<double>::infinity();
} else {
double wx, wy, pz;
to_world(oz * inv, -ox * inv, -oy * inv, &wx, &wy, &pz);
d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far);
}
uint16_t mm = 0; // 0 = khong do duoc, dung quy uoc cua RealSense
// Depth dropout: D410 that mat diem o be mat toi, be mat bong, va o
@@ -866,7 +1159,9 @@ struct SimSource::Impl {
// dung ra phang o z=0 bi cliff_detect khop thanh z0 = -0.254 m,
// doc +0.114 -- va 87/1903 tia trong cua so roi duoi nguong, tuc
// BAO VUC GIA tren san hoan toan phang, MAD 0.037 van lot cong.
d *= inv;
//
// GPU da tra Z-depth roi -- nhan them la sai lan nua.
if (!use_gl) d *= inv;
// Nhieu depth theo MO HINH STEREO, khong phai hang so.
//
@@ -928,6 +1223,22 @@ struct SimSource::Impl {
img->format = PixelFormat::kMono16;
img->depth_scale = 0.001f;
img->data = depth_buf.data();
img->keep_alive = buf;
if (use_gl) {
// Anh IR cung kich thuoc, cung K va cung stamp voi depth -- giong
// RealSense: hai anh IR va depth thang hang tung pixel.
auto ibuf = depth_pool->Acquire();
ibuf->assign(gl_ir.begin(), gl_ir.end());
auto ir = std::make_shared<Image>();
ir->header = img->header;
ir->width = w;
ir->height = h;
ir->step = w;
ir->format = PixelFormat::kMono8;
ir->data = ibuf->data();
ir->keep_alive = ibuf;
out->infra1 = ir;
}
out->header = img->header;
out->depth = img;
@@ -966,6 +1277,14 @@ struct SimSource::Impl {
cur_rr = roll_rate;
cur_pr = pitch_rate;
cur_accel = last_accel;
if (terrain_on) {
// Than nghieng theo dia hinh thi gyro PHAI thay luc no nghieng --
// khong thi gia toc ke bao "dang tren doc" con gyro bao "chua he xoay",
// va moi bo loc (gravity_align, VIO) bi hai cam bien cai nhau.
cur_roll += terrain_roll;
cur_rr += terrain_roll_rate;
cur_pr += terrain_pitch_rate;
}
}
// Con quay do van toc goc THAT tren ca ba truc.
@@ -1005,6 +1324,169 @@ struct SimSource::Impl {
m->linear_acceleration_covariance[8] = m->linear_acceleration_covariance[0];
return m;
}
// IMU tinh TU quy dao that (SimConfig::ImuModel::kKinematic). Goi sau
// StepPhysics, MOI buoc vat ly -- lich su vi tri can deu buoc.
//
// gyro = Log(R_truoc^T R) / dt (van toc goc trong he THAN)
// accel = R^T (a + (0, 0, g)), a = sai phan lui bac hai vi tri diem dat IMU
//
// Tich phan nguoc (xoay gia toc ve the gioi bang tu the that, tru trong
// luc, tich phan hai lan) ra DUNG quy dao, sai so chi o muc lam tron. Mo
// hinh cu chi xap xi: thieu gia toc theo phuong dung khi len doc, thieu
// canh tay don cua diem dat IMU khi than nghieng.
// Tu the THAT va vi tri diem dat IMU o trang thai hien tai:
// base_footprint + R * (imu_x, imu_y, r_banh + imu_z).
void ImuTruth(Rot3* R, double p[3]) {
double rx, ry, rz, ryaw, rroll, rpitch;
{
std::lock_guard<std::mutex> lk(state_mu);
rx = x; ry = y; ryaw = yaw;
rz = terrain_on ? ground_z : 0.0;
rroll = roll + (terrain_on ? terrain_roll : 0.0);
rpitch = pitch + terrain_pitch;
}
*R = Rot3::FromRPY(rroll, rpitch, ryaw);
R->Apply(cfg.imu_x, cfg.imu_y, cfg.wheel_radius + cfg.imu_z, &p[0], &p[1], &p[2]);
p[0] += rx; p[1] += ry; p[2] += rz;
}
// Gieo lich su IMU tai tu the hien tai, robot coi nhu dang dung yen. Goi
// o Open(): mau dau tien phai mang CA chuyen dong cua buoc vat ly dau tien,
// khong thi tich phan IMU lech su that ngay tu dau.
void SeedImuHistory() {
double p[3];
ImuTruth(&imu_R_prev, p);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) imu_p[i][j] = p[j];
}
imu_hist = 1;
}
ImuPtr MakeImuKinematic(UnixTime stamp, double dt) {
Rot3 R;
double pnow[3];
ImuTruth(&R, pnow);
if (imu_hist == 0) SeedImuHistory();
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) imu_p[i][j] = imu_p[i + 1][j];
}
for (int j = 0; j < 3; ++j) imu_p[2][j] = pnow[j];
imu_hist = std::min(imu_hist + 1, 3);
double w[3] = {0.0, 0.0, 0.0};
if (dt > 0.0) {
// Rr = R_truoc^T * R, roi Log() ve vector quay.
double Rr[9];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
Rr[i * 3 + j] = imu_R_prev.m[0 * 3 + i] * R.m[0 * 3 + j] +
imu_R_prev.m[1 * 3 + i] * R.m[1 * 3 + j] +
imu_R_prev.m[2 * 3 + i] * R.m[2 * 3 + j];
}
}
const double c = std::max(-1.0, std::min(1.0, (Rr[0] + Rr[4] + Rr[8] - 1.0) / 2.0));
const double th = std::acos(c);
const double k = th < 1e-9 ? 0.5 : th / (2.0 * std::sin(th));
w[0] = k * (Rr[7] - Rr[5]) / dt;
w[1] = k * (Rr[2] - Rr[6]) / dt;
w[2] = k * (Rr[3] - Rr[1]) / dt;
}
imu_R_prev = R;
double a[3] = {0.0, 0.0, 0.0};
if (dt > 0.0) {
for (int j = 0; j < 3; ++j) {
a[j] = (imu_p[2][j] - 2.0 * imu_p[1][j] + imu_p[0][j]) / (dt * dt);
}
}
const double aw[3] = {a[0], a[1], a[2] + kGravity};
double f[3];
for (int i = 0; i < 3; ++i) {
f[i] = R.m[0 * 3 + i] * aw[0] + R.m[1 * 3 + i] * aw[1] + R.m[2 * 3 + i] * aw[2];
}
// Bias troi + nhieu trang.
std::normal_distribution<double> n01(0.0, 1.0);
const double sq = std::sqrt(std::max(dt, 0.0));
for (int i = 0; i < 3; ++i) {
if (cfg.gyro_bias_rw > 0.0) imu_bg[i] += cfg.gyro_bias_rw * sq * n01(imu_rng);
if (cfg.accel_bias_rw > 0.0) imu_ba[i] += cfg.accel_bias_rw * sq * n01(imu_rng);
w[i] += imu_bg[i];
f[i] += imu_ba[i];
if (cfg.gyro_noise_stddev > 0.0) w[i] += cfg.gyro_noise_stddev * n01(imu_rng);
if (cfg.accel_noise_stddev > 0.0) f[i] += cfg.accel_noise_stddev * n01(imu_rng);
}
// Loc trong cam bien (WT61PC co loc noi): lam tre va lam mem tin hieu.
if (cfg.imu_lpf_hz > 0.0 && dt > 0.0) {
const double al = dt / (dt + 1.0 / (2.0 * M_PI * cfg.imu_lpf_hz));
if (!imu_lpf_init) {
for (int i = 0; i < 3; ++i) { imu_lpf_w[i] = w[i]; imu_lpf_f[i] = f[i]; }
imu_lpf_init = true;
}
for (int i = 0; i < 3; ++i) {
imu_lpf_w[i] += al * (w[i] - imu_lpf_w[i]);
imu_lpf_f[i] += al * (f[i] - imu_lpf_f[i]);
w[i] = imu_lpf_w[i];
f[i] = imu_lpf_f[i];
}
}
auto m = std::make_shared<Imu>();
m->header.stamp = stamp;
m->header.frame_id = kImuFrame;
m->angular_velocity.x = w[0];
m->angular_velocity.y = w[1];
m->angular_velocity.z = w[2];
m->linear_acceleration.x = f[0];
m->linear_acceleration.y = f[1];
m->linear_acceleration.z = f[2];
m->orientation_covariance[0] = -1.0; // khong co orientation
const double gv = cfg.gyro_noise_stddev * cfg.gyro_noise_stddev;
const double av = cfg.accel_noise_stddev * cfg.accel_noise_stddev;
m->angular_velocity_covariance[0] = gv;
m->angular_velocity_covariance[4] = gv;
m->angular_velocity_covariance[8] = gv;
m->linear_acceleration_covariance[0] = av;
m->linear_acceleration_covariance[4] = av;
m->linear_acceleration_covariance[8] = av;
return m;
}
// Phat mau IMU theo tan so phat va do tre. Tra true neu da phat.
//
// Mac dinh (imu_output_hz = 0, imu_delay_sec = 0): phat MOI mau ngay khi do,
// y het truoc. Co tre: mau phat luc `now` la mau DO tai `now - delay`, mang
// stamp `now` -- dung cai driver that thay khi dong dau bang gio nhan.
bool EmitImu(UnixTime now, ImuPtr meas, double dt) {
if (cfg.imu_output_hz <= 0.0 && cfg.imu_delay_sec <= 0.0) {
mcu.PushImu(std::move(meas));
return true;
}
const double t = sim_elapsed;
imu_fifo.emplace_back(t, std::move(meas));
imu_out_acc += dt;
const double period = cfg.imu_output_hz > 0.0 ? 1.0 / cfg.imu_output_hz : dt;
if (imu_out_acc + 1e-9 < period) {
// Khong de hang doi phinh khi tan so phat thap: giu toi da 2 s.
while (imu_fifo.size() > 1 && imu_fifo.front().first < t - cfg.imu_delay_sec - 2.0) {
imu_fifo.pop_front();
}
return false;
}
imu_out_acc -= period;
ImuPtr pick;
const double want = t - cfg.imu_delay_sec;
while (!imu_fifo.empty() && imu_fifo.front().first <= want + 1e-9) {
pick = imu_fifo.front().second;
imu_fifo.pop_front();
}
if (!pick) return false; // vua khoi dong, chua du tre
auto out = std::make_shared<Imu>(*pick);
out->header.stamp = now;
mcu.PushImu(std::move(out));
return true;
}
};
// ---------------------------------------------------------------------------
@@ -1017,18 +1499,21 @@ StatusResponse SimSource::Open() {
// chuoi do phai giong nhau giua hai lan ghi cung mot kich ban.
impl_->rng.seed(impl_->cfg.seed);
WorldTerrain terr;
if (!impl_->cfg.world_path.empty()) {
const StatusResponse st = LoadGazeboWorld(
impl_->cfg.world_path, impl_->cfg.world_model_paths, &impl_->world);
if (!st.ok()) return st;
WorldRasterOptions wo;
const StatusResponse rs = RasterizeGazeboWorld(impl_->world, wo, &impl_->map);
const StatusResponse rs =
RasterizeGazeboWorld(impl_->world, wo, &impl_->map, &terr);
if (!rs.ok()) return rs;
// Chi muc doan 2D, de khoang cach tra ve trung MAT TUONG chu khong trung
// bien o. Khong dung duoc thi van chay -- chi la moi tia dung som toi mot
// o, y nhu truoc day.
const StatusResponse ss =
BuildWorldSegments(impl_->world, wo, impl_->map, &impl_->segments);
const StatusResponse ss = BuildWorldSegments(
impl_->world, wo, impl_->map, &impl_->segments,
terr.terrain_cells > 0 ? &terr.floor_z : nullptr);
if (!ss.ok()) {
VSLAM_WARN("sim: khong dung duoc chi muc doan (" << ss.message
<< ") -- raycast se luong tu hoa theo o "
@@ -1048,13 +1533,63 @@ StatusResponse SimSource::Open() {
}
// San phang mac dinh. SetFloorHeight() tao bac hut xuong.
impl_->floor_z.assign(static_cast<size_t>(impl_->map.width) * impl_->map.height, 0.0f);
impl_->glass.assign(static_cast<size_t>(impl_->map.width) * impl_->map.height, 0);
const size_t n_cells = static_cast<size_t>(impl_->map.width) * impl_->map.height;
impl_->floor_z.assign(n_cells, 0.0f);
impl_->glass.assign(n_cells, 0);
impl_->wall_top.clear();
impl_->step_block.clear();
// World co dia hinh (san cao, doc): san lay tu mesh dia hinh.
if (terr.terrain_cells > 0 && terr.floor_z.size() == n_cells) {
impl_->floor_z = terr.floor_z;
}
if (terr.wall_top.size() == n_cells) impl_->wall_top = terr.wall_top;
const SimConfig::TerrainMode tm = impl_->cfg.terrain;
impl_->terrain_on = tm == SimConfig::TerrainMode::kOn ||
(tm == SimConfig::TerrainMode::kAuto && terr.terrain_cells > 0);
if (impl_->terrain_on) {
VSLAM_INFO("sim: dia hinh 3D BAT -- " << terr.terrain_cells << " o dia hinh, san tu "
<< terr.floor_min << " den " << terr.floor_max
<< " m. Robot di tren mat san, LiDAR quet tia 3D, chenh san > "
<< impl_->cfg.max_step << " m la vat can.");
}
impl_->x = impl_->cfg.start_x;
impl_->y = impl_->cfg.start_y;
impl_->yaw = impl_->cfg.start_yaw;
if (impl_->terrain_on) {
impl_->RebuildStepMask();
impl_->terrain_ready = false;
impl_->UpdateTerrainPose(0.0);
}
// Mo hinh IMU. RNG rieng, gieo tu seed: cung kich ban => cung chuoi nhieu.
const SimConfig::ImuModel im = impl_->cfg.imu_model;
impl_->imu_kinematic = im == SimConfig::ImuModel::kKinematic ||
(im == SimConfig::ImuModel::kAuto && impl_->terrain_on);
impl_->imu_rng.seed(impl_->cfg.seed + 101u);
impl_->imu_hist = 0;
if (impl_->imu_kinematic) impl_->SeedImuHistory();
impl_->imu_lpf_init = false;
impl_->imu_fifo.clear();
impl_->imu_out_acc = 0.0;
for (int i = 0; i < 3; ++i) { impl_->imu_bg[i] = 0.0; impl_->imu_ba[i] = 0.0; }
if (impl_->imu_kinematic) {
std::normal_distribution<double> n01(0.0, 1.0);
for (int i = 0; i < 3; ++i) {
impl_->imu_bg[i] = impl_->cfg.gyro_bias_sigma * n01(impl_->imu_rng);
impl_->imu_ba[i] = impl_->cfg.accel_bias_sigma * n01(impl_->imu_rng);
}
VSLAM_INFO("sim: IMU dong hoc -- tinh tu quy dao 6-DoF that"
<< (impl_->cfg.imu_output_hz > 0.0
? ", phat " + std::to_string(impl_->cfg.imu_output_hz) + " Hz"
: std::string(""))
<< (impl_->cfg.imu_delay_sec > 0.0
? ", tre " + std::to_string(impl_->cfg.imu_delay_sec) + " s"
: std::string("")));
}
if (impl_->Collides(impl_->x, impl_->y)) {
// Bao NGAY thay vi de robot ket ngay tu khung dau tien va nguoi dung ngoi
// doan tai sao no khong nhuc nhich.
@@ -1093,6 +1628,10 @@ void SimSource::SetMapForTest(const OccupancyGrid& m) {
impl_->map = m;
impl_->floor_z.assign(static_cast<size_t>(m.width) * m.height, 0.0f);
impl_->glass.assign(static_cast<size_t>(m.width) * m.height, 0);
impl_->wall_top.clear();
impl_->step_block.clear();
impl_->steps_dirty = true;
impl_->terrain_ready = false;
}
bool SimSource::true_bumper() const { return impl_->bumper_now; }
@@ -1143,16 +1682,102 @@ void SimSource::SetFloorHeight(double x0, double y0, double x1, double y1, float
impl_->floor_z[static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx)] = z;
}
}
// Dia hinh 3D: mat na bac tinh lai o buoc vat ly sau, va goc dia hinh lay
// lai tu dau (khong sinh toc do goc gia).
impl_->steps_dirty = true;
impl_->terrain_ready = false;
VSLAM_INFO("sim: dat do cao san " << z << " m cho vung (" << x0 << ", " << y0
<< ") - (" << x1 << ", " << y1 << ")");
}
void SimSource::SetFloorRamp(double x0, double y0, double x1, double y1,
float z_at_x0, float z_at_x1) {
const OccupancyGrid& m = impl_->map;
if (x1 == x0) return;
auto to_cell = [&](double w, double origin) {
return static_cast<int>(std::floor((w - origin) / m.resolution));
};
const int cx0 = std::max(0, to_cell(std::min(x0, x1), m.origin.position.x));
const int cy0 = std::max(0, to_cell(std::min(y0, y1), m.origin.position.y));
const int cx1 = std::min<int>(static_cast<int>(m.width) - 1,
to_cell(std::max(x0, x1), m.origin.position.x));
const int cy1 = std::min<int>(static_cast<int>(m.height) - 1,
to_cell(std::max(y0, y1), m.origin.position.y));
std::lock_guard<std::mutex> lk(impl_->state_mu);
for (int cy = cy0; cy <= cy1; ++cy) {
for (int cx = cx0; cx <= cx1; ++cx) {
// Do cao tai TAM o, cung quy uoc voi raster dia hinh tu world.
const double wx = m.origin.position.x + (cx + 0.5) * m.resolution;
const double t = std::min(1.0, std::max(0.0, (wx - x0) / (x1 - x0)));
impl_->floor_z[static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx)] =
static_cast<float>(z_at_x0 + t * (z_at_x1 - z_at_x0));
}
}
impl_->steps_dirty = true;
impl_->terrain_ready = false;
VSLAM_INFO("sim: doc tu x = " << x0 << " (" << z_at_x0 << " m) toi x = " << x1
<< " (" << z_at_x1 << " m)");
}
bool SimSource::terrain_active() const { return impl_->terrain_on; }
void SimSource::SetCameraRenderer(std::shared_ptr<SimCameraRenderer> r) {
impl_->renderer = std::move(r);
impl_->gl_fail_logged = false;
}
void SimSource::SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz) {
impl_->gt_cb = std::move(cb);
impl_->gt_period = rate_hz > 0.0 ? 1.0 / rate_hz : 0.0;
impl_->gt_acc = 0.0;
}
void SimConfigFromRobot(const RobotModel& robot, SimConfig* c) {
const RobotGeometry& g = robot.geometry();
c->wheel_radius = g.wheel_radius;
c->wheel_separation = g.wheel_separation;
c->robot_radius = g.robot_radius;
c->camera_z = robot.camera_height_above_floor();
c->camera_pitch = robot.camera_pitch();
Transform t;
if (robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
c->lidar_x = t.translation.x;
// Do cao LiDAR tren TAM TRUC. Duong 2D cu khong dung; dia hinh 3D thi
// can de tia o dung 0.2165 m tren san.
c->lidar_z = t.translation.z;
}
if (robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
c->camera_x = t.translation.x;
}
if (robot.StaticTransform(kBaseLinkFrame, kImuFrame, &t)) {
c->imu_x = t.translation.x;
c->imu_y = t.translation.y;
c->imu_z = t.translation.z;
}
}
void SimSource::true_tilt(double* roll_out, double* pitch_out) const {
std::lock_guard<std::mutex> lk(impl_->state_mu);
*roll_out = impl_->roll;
// Tat dia hinh 3D thi KHONG cong (ke ca 0.0): giu dung tung bit nhu cu.
*roll_out = impl_->terrain_on ? impl_->roll + impl_->terrain_roll : impl_->roll;
*pitch_out = impl_->pitch + impl_->terrain_pitch;
}
SimPose3 SimSource::ground_truth_3d() const {
std::lock_guard<std::mutex> lk(impl_->state_mu);
SimPose3 p;
p.x = impl_->x;
p.y = impl_->y;
p.yaw = impl_->yaw;
// Tat dia hinh 3D thi robot luon o z = 0, ke ca khi SetFloorHeight tao vuc:
// do cao san luc do chi de camera NHIN thay, robot khong di len no.
p.z = impl_->terrain_on ? impl_->ground_z : 0.0;
p.roll = impl_->terrain_on ? impl_->roll + impl_->terrain_roll : impl_->roll;
p.pitch = impl_->pitch + impl_->terrain_pitch;
return p;
}
Pose2D SimSource::ground_truth() const {
std::lock_guard<std::mutex> lk(impl_->state_mu);
return Pose2D{impl_->x, impl_->y, impl_->yaw};
@@ -1207,13 +1832,24 @@ void SimSource::RunFor(double seconds) {
impl_->StepPhysics(dt);
impl_->sim_elapsed += dt;
impl_->mcu.PushImu(impl_->MakeImu(now));
ImuPtr meas = impl_->imu_kinematic ? impl_->MakeImuKinematic(now, dt)
: impl_->MakeImu(now);
const bool imu_out = impl_->EmitImu(now, std::move(meas), dt);
{
std::lock_guard<std::mutex> lk(impl_->state_mu);
impl_->stats.imu++;
if (imu_out) impl_->stats.imu++;
impl_->stats.sim_time_sec += dt;
}
// Su that cho tool ghi (SetGroundTruthCallback). Khong stage nao doc no.
if (impl_->gt_cb) {
impl_->gt_acc += dt;
if (impl_->gt_period <= 0.0 || impl_->gt_acc + 1e-9 >= impl_->gt_period) {
if (impl_->gt_period > 0.0) impl_->gt_acc -= impl_->gt_period;
impl_->gt_cb(now, ground_truth_3d());
}
}
enc_acc += dt;
if (enc_acc >= enc_period) {
enc_acc -= enc_period;

View File

@@ -0,0 +1,38 @@
# Ve anh camera mo phong bang GPU: EGL KHONG man hinh + OpenGL ES 3, mesh hien
# thi va texture THAT cua model (assimp), anh tu OpenCV.
#
# TUY CHON (-DVSLAM_SIM_WITH_GL=ON), chi cho may dev co GPU: vslam_sim KHONG
# phu thuoc lib nay -- no chi biet interface SimCameraRenderer
# (vslam/sim_camera_renderer.h). Jetson va CI van build sim nhu cu.
#
# Khong dung find_package(assimp): goi libassimp-dev 5.0.1 cua Ubuntu 20.04
# co file cmake tro sai ten thu vien. Tim thang thu vien va header thi chac.
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs)
find_library(VSLAM_EGL_LIB EGL)
find_library(VSLAM_GLES_LIB GLESv2)
find_library(VSLAM_ASSIMP_LIB assimp)
find_path(VSLAM_EGL_INC EGL/egl.h)
find_path(VSLAM_GLES_INC GLES3/gl3.h)
find_path(VSLAM_ASSIMP_INC assimp/scene.h)
foreach(v VSLAM_EGL_LIB VSLAM_GLES_LIB VSLAM_ASSIMP_LIB VSLAM_EGL_INC VSLAM_GLES_INC VSLAM_ASSIMP_INC)
if(NOT ${v})
message(FATAL_ERROR "VSLAM_SIM_WITH_GL=ON nhung thieu ${v}. Ubuntu: "
"apt install libegl-dev libgles-dev libassimp-dev")
endif()
endforeach()
vslam_add_library(vslam_sim_gl
PUBLIC_HDRS
sim_gl_renderer.h
PUBLIC_DEPS
vslam_sim
vslam_common
FIND_DEPS
vslam_sim
vslam_common
)
target_include_directories(vslam_sim_gl SYSTEM PRIVATE
${VSLAM_EGL_INC} ${VSLAM_GLES_INC} ${VSLAM_ASSIMP_INC} ${OpenCV_INCLUDE_DIRS})
target_link_libraries(vslam_sim_gl PRIVATE
${VSLAM_EGL_LIB} ${VSLAM_GLES_LIB} ${VSLAM_ASSIMP_LIB} ${OpenCV_LIBS})

View File

@@ -0,0 +1,69 @@
#ifndef VSLAM_SIM_GL_RENDERER_H
#define VSLAM_SIM_GL_RENDERER_H
// Ve anh camera mo phong bang GPU: EGL KHONG man hinh + OpenGL ES 3, mesh
// HIEN THI cua world voi texture THAT cua model (assimp: OBJ/MTL, COLLADA).
//
// ================== VI SAO CAN ==================
// Raycast CPU cua bo mo phong chi ra DEPTH, tren tuong ep tu luoi 2D: khong co
// anh, va hinh hoc chi la 2.5D. VO/VIO (F2M, DM-VIO) can ANH co van that de
// bam diem, va can depth KHOP voi anh do. Ve ca hai tu CUNG mot mesh trong
// MOT luot GPU thi chung khop tung pixel.
//
// ================== GIOI HAN (noi ro) ==================
// * Anh "IR" la do sang texture * chieu sang don gian (ambient + den chieu
// theo huong camera), emitter TAT: khong co cham laser, khong rolling
// shutter, khong nhoe chuyen dong, khong tu dong phoi sang. Anh sach hon
// camera that -- ket qua VO trong sim LAC QUAN.
// * Model khong co texture (tuong/san tu sinh) duoc phu mot texture anh
// that theo toa do the gioi (triplanar). Van that, nhung khong dung nghia.
// * Chi xet yaw cua model (giong bo doc world): do doc phai nam san trong
// dinh mesh.
//
// ⚠️ Context GPU tao LUOI o lan Render() dau tien, tren luong goi, va moi lan
// goi sau phai tren CUNG luong do (luong vong mo phong).
#include <memory>
#include <string>
#include "vslam/gazebo_world.h"
#include "vslam/sim_camera_renderer.h"
namespace vslam {
struct GlRendererConfig {
// Texture cho model KHONG co texture: dia hinh (`vslam_terrain_*`) va vat
// khac. Phu theo toa do THE GIOI (triplanar), moi lan lap `texture_tile_m`
// met. Rong = mau dac (khong co van -- VO se khong bam duoc).
std::string fallback_floor_texture;
std::string fallback_wall_texture;
double texture_tile_m = 2.0;
// Chieu sang anh IR: ambient + den chieu dat tai camera (emitter TAT).
double ambient = 0.55;
double headlight = 0.45;
// Cho phep renderer PHAN MEM (Mesa llvmpipe). Mac dinh tu choi: may co ca
// driver Mesa, va chon nham thiet bi la cham ~100 lan ma khong bao loi.
bool allow_software = false;
};
// Cau hinh mac dinh: texture cho model khong co texture lay tu bo model AWS
// tren may (~/gazebo_models/aws_hospital): san/doc = anh THAM that, vat khac =
// anh VAI rem that -- ca hai lap duoc, co van cho VO bam. Bien moi truong
// VSLAM_SIM_FLOOR_TEXTURE / VSLAM_SIM_WALL_TEXTURE ghi de (duong dan anh).
// Khong tim thay anh nao thi de rong (mau dac) va log canh bao.
GlRendererConfig DefaultGlRendererConfig();
// Nap mesh + texture cua `world` NGAY (CPU), dua len GPU o lan Render() dau.
// Tra nullptr va dien `error` neu khong nap duoc mesh nao.
std::shared_ptr<SimCameraRenderer> CreateGlCameraRenderer(const GazeboWorld& world,
const GlRendererConfig& cfg,
std::string* error);
// Hop bao he WORLD cua mesh HIEN THI cua mot model, doc bang assimp voi CUNG
// quy uoc nhu renderer (ti le `<scale>`, yaw, tinh tien). Cho bai kiem so voi
// bo doc world cua vslam_sim. false neu khong doc duoc.
bool AssimpModelBounds(const WorldModel& m, double mn[3], double mx[3]);
} // namespace vslam
#endif // VSLAM_SIM_GL_RENDERER_H

View File

@@ -0,0 +1,704 @@
#include "vslam/sim_gl_renderer.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include <assimp/Importer.hpp>
#include <assimp/config.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <sys/stat.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
// ---------------------------------------------------------------------------
// Du lieu phia CPU: nap mot lan luc tao, khong can context GPU.
// ---------------------------------------------------------------------------
struct CpuTexture {
int w = 0, h = 0;
std::vector<uint8_t> rgba; // hang DUOI cung truoc -- quy uoc texture GL
};
struct CpuMesh {
std::vector<float> v; // moi dinh: x y z nx ny nz u v, he WORLD
std::vector<uint32_t> idx;
int tex = -1; // chi so CpuTexture; -1 = mau dac
bool triplanar = false; // phu texture theo toa do world (model khong UV)
float color[3] = {0.7f, 0.7f, 0.7f};
};
std::string DirOf(const std::string& p) {
const size_t s = p.rfind('/');
return s == std::string::npos ? std::string(".") : p.substr(0, s);
}
// Nap anh texture. Lat DOC: OBJ va COLLADA dat v = 0 o DAY anh, con anh doc
// tu file thi hang tren cung truoc.
int LoadTexture(const std::string& path, std::map<std::string, int>* cache,
std::vector<CpuTexture>* out) {
auto it = cache->find(path);
if (it != cache->end()) return it->second;
cv::Mat img = cv::imread(path, cv::IMREAD_COLOR);
if (img.empty()) {
VSLAM_WARN("sim_gl: khong doc duoc texture " << path << " -- dung mau dac");
(*cache)[path] = -1;
return -1;
}
// 2048 la du cho anh 640x480 nhin vat cach vai met; texture 8K cua vai
// model chi ton bo nho GPU va thoi gian nap.
const int kMax = 2048;
if (img.cols > kMax || img.rows > kMax) {
const double s = static_cast<double>(kMax) / std::max(img.cols, img.rows);
cv::resize(img, img, cv::Size(), s, s, cv::INTER_AREA);
}
cv::Mat rgba;
cv::cvtColor(img, rgba, cv::COLOR_BGR2RGBA);
cv::flip(rgba, rgba, 0);
CpuTexture t;
t.w = rgba.cols;
t.h = rgba.rows;
t.rgba.assign(rgba.data, rgba.data + rgba.total() * 4);
out->push_back(std::move(t));
const int id = static_cast<int>(out->size()) - 1;
(*cache)[path] = id;
return id;
}
// Doc mesh HIEN THI cua mot model bang assimp, bien doi sang world theo CUNG
// thu tu voi bo doc world (gazebo_world.cc): ti le `<scale>` -> yaw -> tinh tien.
// `meshes`/`textures` co the null (chi lay hop bao).
bool LoadModel(const WorldModel& m, const GlRendererConfig* cfg,
std::map<std::string, int>* tex_cache, std::vector<CpuTexture>* textures,
std::vector<CpuMesh>* meshes, double mn[3], double mx[3]) {
const std::string& path = !m.visual_obj.empty() ? m.visual_obj : m.collision_obj;
if (path.empty()) return false;
Assimp::Importer imp;
// Bo <up_axis> cua COLLADA, y nhu bo doc world: file cua bo model AWS khai
// Y_UP nhung du lieu (hoac node goc) DA la Z-up. Don vi <unit> va bien doi
// node thi giu -- PreTransformVertices nuong ca hai vao dinh.
imp.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true);
const aiScene* sc =
imp.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals |
aiProcess_PreTransformVertices |
aiProcess_JoinIdenticalVertices);
if (sc == nullptr || sc->mRootNode == nullptr) {
VSLAM_WARN("sim_gl: assimp khong doc duoc " << path << ": " << imp.GetErrorString());
return false;
}
const double cyw = std::cos(m.yaw), syw = std::sin(m.yaw);
const std::string dir = DirOf(path);
for (int k = 0; k < 3; ++k) { mn[k] = 1e18; mx[k] = -1e18; }
bool any = false;
for (unsigned mi = 0; mi < sc->mNumMeshes; ++mi) {
const aiMesh* am = sc->mMeshes[mi];
if (am->mNumVertices == 0 || am->mNumFaces == 0) continue;
CpuMesh cm;
if (meshes != nullptr && am->mMaterialIndex < sc->mNumMaterials) {
const aiMaterial* mat = sc->mMaterials[am->mMaterialIndex];
aiColor3D kd(0.7f, 0.7f, 0.7f);
if (mat->Get(AI_MATKEY_COLOR_DIFFUSE, kd) == AI_SUCCESS) {
cm.color[0] = kd.r; cm.color[1] = kd.g; cm.color[2] = kd.b;
}
aiString tp;
if (mat->GetTextureCount(aiTextureType_DIFFUSE) > 0 &&
mat->GetTexture(aiTextureType_DIFFUSE, 0, &tp) == AI_SUCCESS) {
std::string t = tp.C_Str();
// '*' dau = texture nhung trong file -- bo model nay khong dung.
if (!t.empty() && t[0] != '*') {
std::replace(t.begin(), t.end(), '\\', '/');
cm.tex = LoadTexture(t[0] == '/' ? t : dir + "/" + t, tex_cache, textures);
}
}
}
const bool has_uv = am->HasTextureCoords(0);
if (meshes != nullptr && cfg != nullptr && (cm.tex < 0 || !has_uv)) {
// Khong co texture (tuong/san tu sinh): phu anh that theo toa do world.
const std::string& fb = m.terrain ? cfg->fallback_floor_texture
: cfg->fallback_wall_texture;
if (!fb.empty()) {
cm.tex = LoadTexture(fb, tex_cache, textures);
cm.triplanar = cm.tex >= 0;
}
}
cm.v.reserve(static_cast<size_t>(am->mNumVertices) * 8);
for (unsigned k = 0; k < am->mNumVertices; ++k) {
const aiVector3D& p = am->mVertices[k];
const double px = p.x * m.sx, py = p.y * m.sy, pz = p.z * m.sz;
const double wx = px * cyw - py * syw + m.x;
const double wy = px * syw + py * cyw + m.y;
const double wz = pz + m.z;
double nx = 0.0, ny = 0.0, nz = 1.0;
if (am->HasNormals()) {
// Ti le KHONG deu: phap tuyen chia (khong nhan) cho ti le, roi chuan hoa.
const double ax = am->mNormals[k].x / m.sx;
const double ay = am->mNormals[k].y / m.sy;
const double az = am->mNormals[k].z / m.sz;
const double rx = ax * cyw - ay * syw, ry = ax * syw + ay * cyw;
const double n = std::sqrt(rx * rx + ry * ry + az * az);
if (n > 1e-12) { nx = rx / n; ny = ry / n; nz = az / n; }
}
const float u = has_uv ? am->mTextureCoords[0][k].x : 0.0f;
const float w = has_uv ? am->mTextureCoords[0][k].y : 0.0f;
const float vals[8] = {static_cast<float>(wx), static_cast<float>(wy),
static_cast<float>(wz), static_cast<float>(nx),
static_cast<float>(ny), static_cast<float>(nz), u, w};
cm.v.insert(cm.v.end(), vals, vals + 8);
mn[0] = std::min(mn[0], wx); mx[0] = std::max(mx[0], wx);
mn[1] = std::min(mn[1], wy); mx[1] = std::max(mx[1], wy);
mn[2] = std::min(mn[2], wz); mx[2] = std::max(mx[2], wz);
any = true;
}
for (unsigned f = 0; f < am->mNumFaces; ++f) {
const aiFace& face = am->mFaces[f];
if (face.mNumIndices != 3) continue; // diem / doan sau Triangulate
cm.idx.push_back(face.mIndices[0]);
cm.idx.push_back(face.mIndices[1]);
cm.idx.push_back(face.mIndices[2]);
}
if (meshes != nullptr && !cm.idx.empty()) meshes->push_back(std::move(cm));
}
return any;
}
// ---------------------------------------------------------------------------
// Shader. Mot luot ve ra HAI anh: do sang IR (attachment 0) va Z-depth
// (attachment 1, float) -- cung mesh, cung pixel, nen khop tung diem.
// ---------------------------------------------------------------------------
const char* kVertex = R"(#version 300 es
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNrm;
layout(location = 2) in vec2 aUv;
uniform mat4 uProj;
uniform mat4 uView;
out vec3 vWorld;
out vec3 vNrm;
out vec2 vUv;
out float vZ;
void main() {
vWorld = aPos;
vNrm = aNrm;
vUv = aUv;
vec4 pc = uView * vec4(aPos, 1.0);
vZ = -pc.z; // Z-depth: camera GL nhin theo -z
gl_Position = uProj * pc;
}
)";
const char* kFragment = R"(#version 300 es
precision highp float;
in vec3 vWorld;
in vec3 vNrm;
in vec2 vUv;
in float vZ;
uniform sampler2D uTex;
uniform int uHasTex;
uniform int uTriplanar;
uniform float uTriScale;
uniform vec3 uColor;
uniform vec3 uCamPos;
uniform float uAmbient;
uniform float uHeadlight;
layout(location = 0) out vec4 oIr;
layout(location = 1) out vec4 oDepth;
vec3 Tri(vec3 p, vec3 n) {
vec3 w = abs(n);
w /= (w.x + w.y + w.z + 1e-6);
vec3 a = texture(uTex, p.yz * uTriScale).rgb;
vec3 b = texture(uTex, p.xz * uTriScale).rgb;
vec3 c = texture(uTex, p.xy * uTriScale).rgb;
return a * w.x + b * w.y + c * w.z;
}
void main() {
vec3 n = normalize(vNrm);
vec3 base = uColor;
if (uHasTex == 1) {
base = (uTriplanar == 1) ? Tri(vWorld, n) : texture(uTex, vUv).rgb;
}
// Den chieu dat tai camera; abs() vi vai mesh co phap tuyen nguoc.
vec3 l = normalize(uCamPos - vWorld);
float lit = uAmbient + uHeadlight * abs(dot(n, l));
float g = clamp(dot(base, vec3(0.299, 0.587, 0.114)) * lit, 0.0, 1.0);
oIr = vec4(g, g, g, 1.0);
oDepth = vec4(vZ, 0.0, 0.0, 1.0);
}
)";
GLuint Compile(GLenum type, const char* src, std::string* err) {
const GLuint s = glCreateShader(type);
glShaderSource(s, 1, &src, nullptr);
glCompileShader(s);
GLint ok = 0;
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[2048] = {0};
glGetShaderInfoLog(s, sizeof(log), nullptr, log);
*err = log;
glDeleteShader(s);
return 0;
}
return s;
}
bool IsSoftware(const char* renderer) {
if (renderer == nullptr) return true;
const std::string r = renderer;
return r.find("llvmpipe") != std::string::npos ||
r.find("softpipe") != std::string::npos ||
r.find("SwiftShader") != std::string::npos;
}
// Ma tran 4x4 COT-chinh (quy uoc GL).
struct Mat4 {
float m[16];
};
class GlCameraRenderer : public SimCameraRenderer {
public:
GlCameraRenderer(std::vector<CpuMesh> meshes, std::vector<CpuTexture> textures,
GlRendererConfig cfg)
: meshes_(std::move(meshes)), textures_(std::move(textures)), cfg_(std::move(cfg)) {}
~GlCameraRenderer() override {
// Tren luong khac thi chi huy context: tai nguyen GL di theo no. KHONG
// eglTerminate -- display cua thiet bi dung chung giua cac renderer.
if (ctx_ != EGL_NO_CONTEXT && std::this_thread::get_id() == thread_) {
eglMakeCurrent(dpy_, surf_, surf_, ctx_);
for (const Gpu& g : gpu_) {
glDeleteVertexArrays(1, &g.vao);
glDeleteBuffers(1, &g.vbo);
glDeleteBuffers(1, &g.ibo);
}
if (!gl_tex_.empty()) glDeleteTextures(static_cast<GLsizei>(gl_tex_.size()), gl_tex_.data());
DropFbo();
if (prog_ != 0) glDeleteProgram(prog_);
eglMakeCurrent(dpy_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
if (ctx_ != EGL_NO_CONTEXT) eglDestroyContext(dpy_, ctx_);
if (surf_ != EGL_NO_SURFACE) eglDestroySurface(dpy_, surf_);
}
bool Render(const SimCameraView& view, std::vector<uint8_t>* ir,
std::vector<float>* depth_z) override {
if (!init_tried_) {
init_tried_ = true;
thread_ = std::this_thread::get_id();
ok_ = InitGpu();
// Du lieu CPU khong can nua: GPU da giu ban sao.
meshes_.clear();
meshes_.shrink_to_fit();
textures_.clear();
textures_.shrink_to_fit();
}
if (!ok_) return false;
if (std::this_thread::get_id() != thread_) {
VSLAM_ERROR("sim_gl: Render() goi tu luong khac luong tao context -- bo khung");
return false;
}
if (view.width <= 0 || view.height <= 0) return false;
if (eglGetCurrentContext() != ctx_) eglMakeCurrent(dpy_, surf_, surf_, ctx_);
if (!EnsureFbo(view.width, view.height)) return false;
const int w = view.width, h = view.height;
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glViewport(0, 0, w, h);
const GLenum bufs[2] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, bufs);
const float c0[4] = {0.0f, 0.0f, 0.0f, 1.0f};
const float c1[4] = {0.0f, 0.0f, 0.0f, 0.0f};
const float one = 1.0f;
glClearBufferfv(GL_COLOR, 0, c0);
glClearBufferfv(GL_COLOR, 1, c1);
glClearBufferfv(GL_DEPTH, 0, &one);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDisable(GL_CULL_FACE); // vai mesh quay mat nguoc, ve ca hai mat
Mat4 proj, viewm;
Projection(view, &proj);
ViewMatrix(view, &viewm);
glUseProgram(prog_);
glUniformMatrix4fv(loc_proj_, 1, GL_FALSE, proj.m);
glUniformMatrix4fv(loc_view_, 1, GL_FALSE, viewm.m);
glUniform3f(loc_campos_, static_cast<float>(view.t_wc[0]),
static_cast<float>(view.t_wc[1]), static_cast<float>(view.t_wc[2]));
glUniform1f(loc_amb_, static_cast<float>(cfg_.ambient));
glUniform1f(loc_head_, static_cast<float>(cfg_.headlight));
glUniform1f(loc_triscale_, static_cast<float>(1.0 / std::max(0.05, cfg_.texture_tile_m)));
glUniform1i(loc_tex_, 0);
glActiveTexture(GL_TEXTURE0);
for (const Gpu& g : gpu_) {
glUniform3f(loc_color_, g.color[0], g.color[1], g.color[2]);
glUniform1i(loc_hastex_, g.tex >= 0 ? 1 : 0);
glUniform1i(loc_tri_, g.triplanar ? 1 : 0);
if (g.tex >= 0) glBindTexture(GL_TEXTURE_2D, gl_tex_[static_cast<size_t>(g.tex)]);
glBindVertexArray(g.vao);
glDrawElements(GL_TRIANGLES, g.count, GL_UNSIGNED_INT, nullptr);
}
glBindVertexArray(0);
rgba_.resize(static_cast<size_t>(w) * h * 4);
rgbaf_.resize(static_cast<size_t>(w) * h * 4);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, rgba_.data());
glReadBuffer(GL_COLOR_ATTACHMENT1);
glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, rgbaf_.data());
const GLenum e = glGetError();
if (e != GL_NO_ERROR) {
VSLAM_ERROR("sim_gl: loi GL 0x" << std::hex << e << std::dec << " khi ve");
return false;
}
// glReadPixels tra hang DUOI cung truoc; anh thi hang TREN truoc.
ir->resize(static_cast<size_t>(w) * h);
depth_z->resize(static_cast<size_t>(w) * h);
for (int r = 0; r < h; ++r) {
const size_t src = static_cast<size_t>(h - 1 - r) * w;
const size_t dst = static_cast<size_t>(r) * w;
for (int c = 0; c < w; ++c) {
(*ir)[dst + c] = rgba_[(src + c) * 4];
(*depth_z)[dst + c] = rgbaf_[(src + c) * 4];
}
}
return true;
}
std::string Describe() const override { return describe_; }
private:
struct Gpu {
GLuint vao = 0, vbo = 0, ibo = 0;
GLsizei count = 0;
int tex = -1;
bool triplanar = false;
float color[3] = {0.7f, 0.7f, 0.7f};
};
bool InitGpu() {
auto query_devices =
reinterpret_cast<PFNEGLQUERYDEVICESEXTPROC>(eglGetProcAddress("eglQueryDevicesEXT"));
auto get_display = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (query_devices == nullptr || get_display == nullptr) {
VSLAM_ERROR("sim_gl: EGL thieu EGL_EXT_device_enumeration / platform_device");
return false;
}
EGLDeviceEXT devs[16];
EGLint n = 0;
if (!query_devices(16, devs, &n) || n <= 0) {
VSLAM_ERROR("sim_gl: khong co thiet bi EGL nao");
return false;
}
std::string rejected;
for (EGLint i = 0; i < n; ++i) {
EGLDisplay d = get_display(EGL_PLATFORM_DEVICE_EXT, devs[i], nullptr);
EGLint maj = 0, min = 0;
if (d == EGL_NO_DISPLAY || !eglInitialize(d, &maj, &min)) continue;
if (!eglBindAPI(EGL_OPENGL_ES_API)) continue;
const EGLint cattr[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES3_BIT, EGL_NONE};
EGLConfig conf;
EGLint nc = 0;
if (!eglChooseConfig(d, cattr, &conf, 1, &nc) || nc < 1) continue;
const EGLint xattr[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
EGLContext c = eglCreateContext(d, conf, EGL_NO_CONTEXT, xattr);
if (c == EGL_NO_CONTEXT) continue;
const EGLint pattr[] = {EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE};
EGLSurface s = eglCreatePbufferSurface(d, conf, pattr);
if (s == EGL_NO_SURFACE || !eglMakeCurrent(d, s, s, c)) {
if (s != EGL_NO_SURFACE) eglDestroySurface(d, s);
eglDestroyContext(d, c);
continue;
}
const char* rend = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
const char* ext = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
const bool soft = IsSoftware(rend);
const bool fbuf = ext != nullptr && std::strstr(ext, "GL_EXT_color_buffer_float") != nullptr;
if ((soft && !cfg_.allow_software) || !fbuf) {
rejected += std::string(rend ? rend : "?") + (soft ? " (phan mem)" : " (thieu float FBO)") + "; ";
eglMakeCurrent(d, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroySurface(d, s);
eglDestroyContext(d, c);
continue;
}
dpy_ = d;
ctx_ = c;
surf_ = s;
describe_ = std::string(rend ? rend : "?") + " (EGL, " +
reinterpret_cast<const char*>(glGetString(GL_VERSION)) + ")";
break;
}
if (ctx_ == EGL_NO_CONTEXT) {
VSLAM_ERROR("sim_gl: khong co GPU dung duoc. Da bo: " << rejected
<< "(allow_software = true de chay CHAM tren CPU)");
return false;
}
std::string err;
const GLuint vs = Compile(GL_VERTEX_SHADER, kVertex, &err);
if (vs == 0) { VSLAM_ERROR("sim_gl: vertex shader: " << err); return false; }
const GLuint fs = Compile(GL_FRAGMENT_SHADER, kFragment, &err);
if (fs == 0) { VSLAM_ERROR("sim_gl: fragment shader: " << err); return false; }
prog_ = glCreateProgram();
glAttachShader(prog_, vs);
glAttachShader(prog_, fs);
glLinkProgram(prog_);
glDeleteShader(vs);
glDeleteShader(fs);
GLint linked = 0;
glGetProgramiv(prog_, GL_LINK_STATUS, &linked);
if (!linked) {
char log[2048] = {0};
glGetProgramInfoLog(prog_, sizeof(log), nullptr, log);
VSLAM_ERROR("sim_gl: link shader: " << log);
return false;
}
loc_proj_ = glGetUniformLocation(prog_, "uProj");
loc_view_ = glGetUniformLocation(prog_, "uView");
loc_tex_ = glGetUniformLocation(prog_, "uTex");
loc_hastex_ = glGetUniformLocation(prog_, "uHasTex");
loc_tri_ = glGetUniformLocation(prog_, "uTriplanar");
loc_triscale_ = glGetUniformLocation(prog_, "uTriScale");
loc_color_ = glGetUniformLocation(prog_, "uColor");
loc_campos_ = glGetUniformLocation(prog_, "uCamPos");
loc_amb_ = glGetUniformLocation(prog_, "uAmbient");
loc_head_ = glGetUniformLocation(prog_, "uHeadlight");
// Texture.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
gl_tex_.resize(textures_.size(), 0);
if (!gl_tex_.empty()) glGenTextures(static_cast<GLsizei>(gl_tex_.size()), gl_tex_.data());
for (size_t i = 0; i < textures_.size(); ++i) {
glBindTexture(GL_TEXTURE_2D, gl_tex_[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, textures_[i].w, textures_[i].h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, textures_[i].rgba.data());
glGenerateMipmap(GL_TEXTURE_2D);
// Mipmap + loc tuyen tinh: van o xa khong nhap nhay (aliasing) -- mot
// nguon "dac trung" gia ma VO se bam vao.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
// Mesh.
size_t tris = 0;
for (const CpuMesh& cm : meshes_) {
Gpu g;
g.tex = cm.tex;
g.triplanar = cm.triplanar;
std::copy(cm.color, cm.color + 3, g.color);
g.count = static_cast<GLsizei>(cm.idx.size());
glGenVertexArrays(1, &g.vao);
glBindVertexArray(g.vao);
glGenBuffers(1, &g.vbo);
glBindBuffer(GL_ARRAY_BUFFER, g.vbo);
glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(cm.v.size() * sizeof(float)),
cm.v.data(), GL_STATIC_DRAW);
glGenBuffers(1, &g.ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g.ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
static_cast<GLsizeiptr>(cm.idx.size() * sizeof(uint32_t)), cm.idx.data(),
GL_STATIC_DRAW);
const GLsizei stride = 8 * sizeof(float);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride,
reinterpret_cast<const void*>(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride,
reinterpret_cast<const void*>(6 * sizeof(float)));
glBindVertexArray(0);
gpu_.push_back(g);
tris += cm.idx.size() / 3;
}
const GLenum e = glGetError();
if (e != GL_NO_ERROR) {
VSLAM_ERROR("sim_gl: loi GL 0x" << std::hex << e << std::dec << " khi nap mesh");
return false;
}
VSLAM_INFO("sim_gl: ve camera bang " << describe_ << " -- " << gpu_.size() << " mesh, "
<< tris << " tam giac, " << gl_tex_.size() << " texture");
return true;
}
void DropFbo() {
if (fbo_ != 0) glDeleteFramebuffers(1, &fbo_);
if (rb_ir_ != 0) glDeleteRenderbuffers(1, &rb_ir_);
if (rb_depth_ != 0) glDeleteRenderbuffers(1, &rb_depth_);
if (rb_z_ != 0) glDeleteRenderbuffers(1, &rb_z_);
fbo_ = rb_ir_ = rb_depth_ = rb_z_ = 0;
fbo_w_ = fbo_h_ = 0;
}
bool EnsureFbo(int w, int h) {
if (fbo_ != 0 && fbo_w_ == w && fbo_h_ == h) return true;
DropFbo();
glGenFramebuffers(1, &fbo_);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glGenRenderbuffers(1, &rb_ir_);
glBindRenderbuffer(GL_RENDERBUFFER, rb_ir_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb_ir_);
glGenRenderbuffers(1, &rb_depth_);
glBindRenderbuffer(GL_RENDERBUFFER, rb_depth_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA32F, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, rb_depth_);
glGenRenderbuffers(1, &rb_z_);
glBindRenderbuffer(GL_RENDERBUFFER, rb_z_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb_z_);
const GLenum st = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (st != GL_FRAMEBUFFER_COMPLETE) {
VSLAM_ERROR("sim_gl: framebuffer khong day du (0x" << std::hex << st << std::dec << ")");
DropFbo();
return false;
}
fbo_w_ = w;
fbo_h_ = h;
return true;
}
// Phep chieu tu noi suy pinhole. Tam pixel o toa do NGUYEN (kieu OpenCV),
// con GL lay mau o x + 0.5: cong 0.5 vao cx, cy de tia qua pixel u cua GL
// trung tia qua pixel u cua raycast CPU.
static void Projection(const SimCameraView& v, Mat4* P) {
const double W = v.width, H = v.height, n = v.near_m, f = v.far_m;
const double cx = v.cx + 0.5, cy = v.cy + 0.5;
std::fill(P->m, P->m + 16, 0.0f);
P->m[0] = static_cast<float>(2.0 * v.fx / W);
P->m[5] = static_cast<float>(2.0 * v.fy / H);
P->m[8] = static_cast<float>(1.0 - 2.0 * cx / W);
P->m[9] = static_cast<float>(2.0 * cy / H - 1.0);
P->m[10] = static_cast<float>(-(f + n) / (f - n));
P->m[11] = -1.0f;
P->m[14] = static_cast<float>(-2.0 * f * n / (f - n));
}
// World -> camera GL (x phai, y LEN, nhin theo -z). Frame quang hoc (y
// XUONG, z truoc) doi sang GL bang diag(1, -1, -1).
static void ViewMatrix(const SimCameraView& v, Mat4* V) {
// R_gl_w = diag(1,-1,-1) * R_wc^T. Hang i cua R_wc^T = cot i cua R_wc.
double R[9];
for (int i = 0; i < 3; ++i) {
const double s = i == 0 ? 1.0 : -1.0;
for (int j = 0; j < 3; ++j) R[i * 3 + j] = s * v.R_wc[j * 3 + i];
}
double t[3];
for (int i = 0; i < 3; ++i) {
t[i] = -(R[i * 3 + 0] * v.t_wc[0] + R[i * 3 + 1] * v.t_wc[1] + R[i * 3 + 2] * v.t_wc[2]);
}
std::fill(V->m, V->m + 16, 0.0f);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) V->m[j * 4 + i] = static_cast<float>(R[i * 3 + j]);
V->m[12 + i] = static_cast<float>(t[i]);
}
V->m[15] = 1.0f;
}
std::vector<CpuMesh> meshes_;
std::vector<CpuTexture> textures_;
GlRendererConfig cfg_;
bool init_tried_ = false, ok_ = false;
std::thread::id thread_;
EGLDisplay dpy_ = EGL_NO_DISPLAY;
EGLContext ctx_ = EGL_NO_CONTEXT;
EGLSurface surf_ = EGL_NO_SURFACE;
GLuint prog_ = 0;
GLint loc_proj_ = -1, loc_view_ = -1, loc_tex_ = -1, loc_hastex_ = -1, loc_tri_ = -1;
GLint loc_triscale_ = -1, loc_color_ = -1, loc_campos_ = -1, loc_amb_ = -1, loc_head_ = -1;
std::vector<Gpu> gpu_;
std::vector<GLuint> gl_tex_;
GLuint fbo_ = 0, rb_ir_ = 0, rb_depth_ = 0, rb_z_ = 0;
int fbo_w_ = 0, fbo_h_ = 0;
std::vector<uint8_t> rgba_;
std::vector<float> rgbaf_;
std::string describe_ = "sim_gl (chua khoi tao)";
};
} // namespace
namespace {
std::string TexturePath(const char* env, const char* home_rel) {
if (const char* e = std::getenv(env)) {
if (*e != '\0') return e;
}
const char* home = std::getenv("HOME");
if (home == nullptr) return "";
const std::string p = std::string(home) + "/gazebo_models/" + home_rel;
struct stat st;
if (::stat(p.c_str(), &st) != 0) {
VSLAM_WARN("sim_gl: khong thay texture " << p << " (dat " << env
<< ") -- model khong co texture se la MAU DAC, VO khong bam duoc");
return "";
}
return p;
}
} // namespace
GlRendererConfig DefaultGlRendererConfig() {
GlRendererConfig c;
c.fallback_floor_texture = TexturePath(
"VSLAM_SIM_FLOOR_TEXTURE",
"aws_hospital/aws_robomaker_residential_Carpet_01/materials/textures/aws_Carpet_01.png");
c.fallback_wall_texture = TexturePath(
"VSLAM_SIM_WALL_TEXTURE",
"aws_hospital/aws_robomaker_hospital_curtain_open_01/meshes/"
"aws_robomaker_hospital_curtain_open_01_visual.png");
return c;
}
std::shared_ptr<SimCameraRenderer> CreateGlCameraRenderer(const GazeboWorld& world,
const GlRendererConfig& cfg,
std::string* error) {
std::vector<CpuMesh> meshes;
std::vector<CpuTexture> textures;
std::map<std::string, int> cache;
size_t loaded = 0, failed = 0;
for (const WorldModel& m : world.models) {
double mn[3], mx[3];
if (LoadModel(m, &cfg, &cache, &textures, &meshes, mn, mx)) {
loaded++;
} else {
failed++;
}
}
if (meshes.empty()) {
if (error != nullptr) *error = "khong nap duoc mesh hien thi nao tu world";
return nullptr;
}
VSLAM_INFO("sim_gl: nap " << loaded << " model (" << failed << " khong doc duoc), "
<< meshes.size() << " mesh, " << textures.size() << " texture");
return std::make_shared<GlCameraRenderer>(std::move(meshes), std::move(textures), cfg);
}
bool AssimpModelBounds(const WorldModel& m, double mn[3], double mx[3]) {
return LoadModel(m, nullptr, nullptr, nullptr, nullptr, mn, mx);
}
} // namespace vslam

View File

@@ -38,6 +38,7 @@ vslam_add_library(vslam_slam
sensor_data_builder.h
occupancy_export.h
voxel_export.h
height_map.h
global_localizer.h
vpr_encoder.h
visual_verifier.h
@@ -62,7 +63,22 @@ if(VSLAM_WITH_TENSORRT)
if(NOT DEFINED CUDAToolkit_ROOT AND EXISTS /usr/local/cuda)
set(CUDAToolkit_ROOT /usr/local/cuda)
endif()
find_package(CUDAToolkit REQUIRED)
# FindCUDAToolkit chi co tu CMake 3.17 (JetPack 6: 3.22). May dev Ubuntu 20.04 co CMake
# 3.16 nhung van co TensorRT + CUDA (chay VPR trong mo phong) -> tim tay cudart.
if(CMAKE_VERSION VERSION_LESS 3.17)
find_path(VSLAM_CUDA_INCLUDE_DIR cuda_runtime_api.h HINTS ${CUDAToolkit_ROOT}/include)
find_library(VSLAM_CUDART cudart HINTS ${CUDAToolkit_ROOT}/lib64)
if(NOT VSLAM_CUDA_INCLUDE_DIR OR NOT VSLAM_CUDART)
message(FATAL_ERROR "VSLAM_WITH_TENSORRT=ON nhung khong thay CUDA runtime trong "
"${CUDAToolkit_ROOT}")
endif()
set(_vslam_cudart ${VSLAM_CUDART})
set(_vslam_cuda_inc ${VSLAM_CUDA_INCLUDE_DIR})
else()
find_package(CUDAToolkit REQUIRED)
set(_vslam_cudart CUDA::cudart)
set(_vslam_cuda_inc "")
endif()
find_path(TENSORRT_INCLUDE_DIR NvInfer.h PATH_SUFFIXES aarch64-linux-gnu x86_64-linux-gnu)
find_library(TENSORRT_NVINFER nvinfer)
if(NOT TENSORRT_INCLUDE_DIR OR NOT TENSORRT_NVINFER)
@@ -70,7 +86,7 @@ if(VSLAM_WITH_TENSORRT)
"(JetPack: goi libnvinfer-dev)")
endif()
target_sources(vslam_slam PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/vpr_tensorrt.cc)
target_include_directories(vslam_slam SYSTEM PRIVATE ${TENSORRT_INCLUDE_DIR})
target_link_libraries(vslam_slam PRIVATE ${TENSORRT_NVINFER} CUDA::cudart)
target_include_directories(vslam_slam SYSTEM PRIVATE ${TENSORRT_INCLUDE_DIR} ${_vslam_cuda_inc})
target_link_libraries(vslam_slam PRIVATE ${TENSORRT_NVINFER} ${_vslam_cudart})
target_compile_definitions(vslam_slam PRIVATE VSLAM_HAVE_TENSORRT=1)
endif()

View File

@@ -32,6 +32,7 @@
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
@@ -81,6 +82,37 @@ struct GlobalLocalizerConfig {
// --- Canh "da lac" ---
double lost_score_ratio = 0.55; // diem tut duoi ty le nay so voi luc khop
double lost_hold = 3.0; // s, phai tut lien tuc ngan nay
// --- Do nghieng IMU vs do doc ban do (che do doc, xem GlobalMatch) ---
// Gia thuyet ma mat san o do gay ra do nghieng lech qua nguong nay so voi
// IMU thi bi loai. 3.5 do: tach duoc doc 5 do khoi san phang (5 do) va cac
// lan 5/10/15/20/30 do khoi nhau, van chiu sai IMU + sai do nghieng node
// ~1-2 do.
double tilt_tol_deg = 3.5;
// Chi tin do doc cua node trong ban kinh nay; xa hon = khong biet san o do
// (khong loai).
double tilt_node_radius = 1.5; // m
// Chot NHO do nghieng (tilt_used) con phai qua kiem suy bien doc truc: dich
// pose `tilt_shift_m` theo 8 huong ma diem LiDAR van >= ty le nay so voi
// pose chot -> hanh lang / doc deu, vi tri doc truc khong quan sat duoc ->
// KHONG chot. Xem ShiftScoreRatio. Do sim 2026-10-05 (dich 1 m): giua lan doc
// MU = 100% (5 ca, mot ca da chot lech 0.77 m); gan dinh doc 5 do thay tuong
// sanh tren cach 10 m = 90-92% (8/8 vong dung cho, lech 7 cm); sanh 62-65%.
double tilt_shift_m = 1.0;
double tilt_max_shift_ratio = 0.95;
// --- Vong DUNG YEN tren doc (runtime: khong xoay robot) ---
// Dung yen thi cac vong nhin GAN NHU Y HET: streak (can di >= 0.2 m) khong
// ap dung, va thu mai roi chot o vong vot qua cong la "dao nhieu". Sim
// 2026-10-05, cung mot cho: ty le NHAY hai muc -- ~1.44 khi tim thay doi thu
// that (12 m doc cung lan), ~1.63 khi vong do bo sot no; trung vi 3 vong van
// lot (1.63 / 1.40 / 1.64). Nen quyet bang ty le NHO NHAT qua moi vong lien
// tiep CUNG nguoi thang (doi thu tung hien ra = co that), can >= `static_rounds`
// vong. Nguong mac dinh = min_ratio_fast (chuan mot goc nhin).
int static_rounds = 3;
double static_min_ratio = 1.60;
double static_agree_m = 0.3;
double static_agree_deg = 5.0;
};
// Truong likelihood tren luoi chiem dung. Dung chung cho khop toan cuc VA cho
@@ -130,22 +162,61 @@ struct RelocMatch {
double s1 = 0.0; // diem nguoi thang
double s2 = 0.0; // doi thu VI TRI tot nhat (> reject_radius)
double s2_yaw = 0.0; // doi thu HUONG tot nhat (cung cho)
// T_map_odom cua hai doi thu tren (de log "nhap nhang voi cho nao").
Pose2D s2_from_odom;
Pose2D s2_yaw_from_odom;
size_t points = 0; // so diem da dung sau khi gop
std::vector<RelocHypothesis> hyps; // da tinh chinh, [0] = nguoi thang
// Loc bang bang chung ngoai LiDAR (`admit` cua GlobalMatch):
bool tilt_used = false; // ket qua tren DA loai it nhat mot gia thuyet
int tilt_rejected = 0; // so gia thuyet mau thuan bi loai (ung vien + doi thu)
// LiDAR CHAC CHAN o mot cho ma bang chung noi khong the -> bo loc, giu ket
// qua LiDAR nhu cu (khong te hon truoc), nhung phai biet.
bool tilt_conflict = false;
double ratio() const { return s1 / (s2 > 1e-9 ? s2 : 1e-9); }
double ratio_yaw() const { return s1 / (s2_yaw > 1e-9 ? s2_yaw : 1e-9); }
};
// Bang chung DOC LAP voi LiDAR cho mot gia thuyet T_map_odom: false = mau
// thuan (vd do nghieng IMU khac do doc ban do tai cho do). Xem GlobalMatch.
using RelocAdmit = std::function<bool(const Pose2D& map_from_odom)>;
// Gop diem ve o luoi `res` roi rut con toi `max_points` (giu thu tu).
std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
size_t max_points);
// Khop TOAN CUC. `pts_odom`: diem da gom trong frame ODOM (co dinh trong luc
// xoay), da cat theo max_range. Tra ok=false neu khong co dinh nao > 0.
//
// `admit` (tuy chon) chi PHAN XU giua cac gia thuyet LiDAR KHONG phan biet
// duoc: gia thuyet bi loai khong duoc thang va khong tinh la doi thu. Nguoi
// thang hop le phai co diem >= s_tot_nhat / min_ratio (trong dai ma LiDAR mot
// minh cung nhap nhang) -- khong bao gio day mot khop LiDAR KEM ro len thang.
// Khong co gia thuyet hop le nao trong dai do -> giu ket qua LiDAR nhu cu,
// danh dau `tilt_conflict`.
//
// ⚠️ Vi sao can (sim 2026-10-05, slope_test.world): robot dat giua doc 5/10/15
// do, 6 vong x 3 doc deu NHAP NHANG (ty le ~1.00). LiDAR nghieng theo doc chi
// thay hai tuong lan; ban sao doi xung (cho phang o dau kia lan, mui nguoc)
// khop y het. IMU biet robot dang chuc 15 do -- ban sao do o san phang.
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg);
const GlobalLocalizerConfig& cfg,
const RelocAdmit& admit = nullptr);
// Suy bien DOC TRUC: diem trung binh cua dam diem tai pose dich `shift_m` theo
// 8 huong (giu huong xoay), chia cho diem tai chinh pose -- lon nhat trong 8.
// ~1 = co mot huong dich ma khop khong xau di (hanh lang, doc deu): vi tri doc
// huong do KHONG quan sat duoc. -1 neu khong tinh duoc.
//
// ⚠️ Cong ty le chi so voi doi thu XA hon reject_radius (2 m). Sim 2026-10-05:
// robot DUNG YEN giua doc 30 do, bo loc nghieng loai het doi thu xa (lan khac,
// cho phang) -> ty le 2.17 -> chot lech 0.77 m DOC lan, cong khong thay.
double ShiftScoreRatio(const LikelihoodField& field, const std::vector<Point>& pts_odom,
const Pose2D& map_from_odom, double shift_m,
size_t max_points = 1500);
// Khop CUC BO: robot phai nam trong `radius` quanh `center` (frame map). De
// XAC MINH ung vien tu nguon khac (VPR). `odom_now`: pose robot trong frame
@@ -205,6 +276,40 @@ const char* RelocVerdictName(RelocVerdict v);
// Thu tu cong nhu ban ROS: huong truoc, roi vi tri, roi dai bien + streak.
RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg);
// --- Vong DUNG YEN (robot khong xoay, vd tren doc) ---
struct StaticRound {
Pose2D robot; // pose robot trong map theo nguoi thang vong do
Pose2D map_from_odom; // T_map_odom cua nguoi thang (bat bien khi robot di)
double ratio = 0.0;
double ratio_yaw = 0.0;
double shift = -1.0; // ShiftScoreRatio; < 0 = khong tinh
};
// Tom tat cac vong o MOT cho dung (goi khi roi cho do).
struct StaticPlace {
Pose2D map_from_odom;
size_t rounds = 0;
double min_ratio = 0.0;
double min_yaw = 0.0;
double max_shift = -1.0;
};
StaticPlace SummarizePlace(const std::vector<StaticRound>& hist);
// Them `r` vao `hist` (xoa truoc neu nguoi thang KHAC vong truoc qua
// static_agree_m / static_agree_deg) roi quyet. Chot khi MOT trong hai:
// 1. MOT cho: >= static_rounds vong, ty le NHO NHAT >= static_min_ratio;
// 2. HAI cho khac nhau (`prev`, truoc khi bo): MOI cho >= static_rounds vong
// voi ty le NHO NHAT >= min_ratio, CUNG T_map_odom (static_agree_*).
// Ca hai: ty le huong nho nhat >= min_ratio_yaw, shift lon nhat < nguong (neu
// `use_shift`).
//
// ⚠️ Vi sao KHONG dung streak cua HypothesisTracker o day: sim 2026-10-05, bo
// xuong chan doc 10 / 15 do, nguoi thang SAI on dinh (cao hon 2 m doc lan),
// streak len 4-6 qua cac lan bo trong khi ty le 1.0-1.2; mot vong nhay 1.32 /
// 1.34 -> chot sai 2.0 / 1.5 m. Ty le NHO NHAT moi cho chan duoc kieu do.
RelocVerdict DecideStatic(std::vector<StaticRound>* hist, const StaticRound& r,
const std::vector<StaticPlace>& prev, const GlobalLocalizerConfig& cfg,
bool use_shift, bool* along_axis, std::string* why);
} // namespace vslam
#endif // VSLAM_GLOBAL_LOCALIZER_H

View File

@@ -0,0 +1,110 @@
#ifndef VSLAM_HEIGHT_MAP_H
#define VSLAM_HEIGHT_MAP_H
// z cua ban do khi pose SLAM la SE(2): do cao tung node va mat san quanh no.
//
// ================== NGUON ==================
// Moi node mang z / roll / pitch DO luc tao (HeightEstimator + GravityAlign),
// luu trong userData cua RTAB-Map. z do co troi (truot banh, sai pitch), va
// do thi SE(2) cua RTAB-Map khong biet gi ve no.
//
// ================== DO THI z 1-D ==================
// Sau moi lan toi uu cua RTAB-Map, giai lai z bang binh phuong toi thieu:
// * lien ket LANG GIENG (node lien tiep): z_j - z_i = z_do_j - z_do_i,
// sigma = min + rel * |dz| (sai he thong ti le voi do cao leo);
// * lien ket VONG / lan can (cung cho, hai lan qua): z_j - z_i = mat phang
// doc cua node i keo toi node j. Ca hai node PHANG (|pitch| < clamp) ->
// 0, chat (3 cm). Tren doc -> theo pitch, long hon (hai node cach 1 m tren
// doc 30 do lech 0.58 m -- dz = 0 o day la SAI);
// * node dau tien neo o z do cua no; moi node co mot prior rat long ve z do
// de do thi khong lien thong van giai duoc.
// Nho vay khi robot quay ve cho cu sau mot vong co doc, sai z don ra deu
// tren vong thay vi don het vao mot cho.
//
// ================== MAT SAN ==================
// FloorModel: do cao san tai (x, y) = MAT PHANG cua node GAN NHAT (z, pitch,
// roll cua no) keo toi do. Dung cho: cat voxel theo do cao TREN san, lop vat
// can tinh theo san cuc bo (doc khong con la tuong), va neo z robot luc dinh
// vi. Node gan nhat chu khong trung binh: canh dinh doc, trung binh hai mat
// phang (doc + chieu nghi) cho ra mot san khong co that.
//
// Khong phu thuoc RTAB-Map -- test duoc rieng.
#include <map>
#include <vector>
namespace vslam {
struct NodeHeight {
double z = 0.0; // do cao base_footprint (mat san duoi robot), m
double roll = 0.0; // nghieng than luc tao node (ROS: duong = trai len)
double pitch = 0.0; // duong = mui chuc xuong
};
struct ZGraphLink {
int from = 0;
int to = 0;
bool neighbor = false; // lien tiep (odometry) hay vong / lan can
// Vi tri node `to` trong frame node `from` (mat phang ngang), m.
double dx = 0.0;
double dy = 0.0;
};
struct ZGraphConfig {
double clamp_rad = 0.0261799; // 1.5 do: duoi nguong = phang
double sigma_neighbor = 0.01;
double sigma_rel = 0.05;
double sigma_loop_flat = 0.03;
double sigma_loop_slope = 0.10;
double sigma_first = 0.01;
double sigma_prior = 2.0; // prior long ve z do cua MOI node
};
// Tra z da toi uu cho moi node trong `meas`. Lien ket toi node khong co trong
// `meas` bi bo qua.
std::map<int, double> SolveZGraph(const std::map<int, NodeHeight>& meas,
const std::vector<ZGraphLink>& links,
const ZGraphConfig& cfg = {});
struct FloorNode {
double x = 0.0, y = 0.0, theta = 0.0; // pose (da toi uu) trong frame map
double z = 0.0, roll = 0.0, pitch = 0.0;
};
class FloorModel {
public:
// radius: chi dung node trong ban kinh nay (camera thay toi ~4 m).
void Build(const std::vector<FloorNode>& nodes, double radius = 4.0, double cell = 0.25);
// Do cao san tai (x, y) theo mat phang node gan nhat; false neu khong node
// nao trong ban kinh. `dist`: khoang cach toi node do.
bool FloorAt(double x, double y, double* z, double* dist = nullptr) const;
// Node gan nhat (trong ban kinh) cua (x, y); false neu khong co.
bool NearestNode(double x, double y, FloorNode* node, double* dist = nullptr) const;
bool empty() const { return nodes_.empty(); }
size_t size() const { return nodes_.size(); }
private:
std::vector<FloorNode> nodes_;
double radius_ = 4.0, cell_ = 0.25, x0_ = 0.0, y0_ = 0.0;
int w_ = 0, h_ = 0;
std::vector<int> nearest_; // moi o: chi so node gan nhat, -1 = khong co
};
// Do cao mat phang cua node n tai (x, y).
double PlaneZ(const FloorNode& n, double x, double y);
// Do doc SAN tai (x, y): gradient (dz/dx, dz/dy, frame map) cua mat phang node
// gan nhat. false neu node gan nhat xa hon `max_dist` (khong biet san o do).
bool FloorGradientAt(const FloorModel& fm, double x, double y, double max_dist, double* gx,
double* gy);
// Do lech giua do nghieng than DO DUOC (roll, pitch -- ROS, tu IMU) va do
// nghieng ma mat san gradient (gx, gy) GAY RA cho robot mui huong `yaw` (frame
// map). Don vi: do doc (tan) -- 0.087 ~ 5 do. Dinh vi lai dung no de loai gia
// thuyet mau thuan voi IMU: quay nguoc 180 do tren doc, doc o cho phang, doc
// sai goc.
double TiltResidual(double roll, double pitch, double yaw, double gx, double gy);
} // namespace vslam
#endif // VSLAM_HEIGHT_MAP_H

View File

@@ -24,6 +24,7 @@
#include <opencv2/core.hpp>
#include "vslam/height_map.h"
#include "vslam/rtabmap_params.h"
#include "vslam/slam_types.h"
#include "vslam/voxel_export.h"
@@ -101,6 +102,33 @@ class RtabmapSlam {
std::vector<int> MapNodeIds() const;
StatusResponse GetNodeView(int id, bool with_depth, NodeView* out);
// ---- z ban do khi di tren doc (height_map.h) ----
// Giai lai do thi z tu z DO cua node (userData) va lien ket cua do thi,
// dung lai mat san. Node chua co z do thi nap tu DB (ban do quet truoc).
// CHI luong slam goi. `nodes_out`: so node co z.
StatusResponse UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out = nullptr);
// Do cao san tai (x, y) frame map theo mat phang node gan nhat, chi khi
// node do trong `radius`. false neu khong co. CHI luong slam goi.
bool HeightAt(double x, double y, double radius, double* z) const;
const FloorModel& floor_model() const;
// Bat dung z node + mat san cho ban do voxel (sau UpdateHeights).
void SetUseHeights(bool on);
// O 2D noi camera thay mat san trong lan ExportVoxels cuoi (che do doc).
const std::vector<uint64_t>& floor_cells() const;
// Vong dong XA: node vua tao vs node CU (cach >= min_graph_gap buoc trong do
// thi) nam trong ban kinh `radius_m` theo do thi da toi uu -- tuc lan di
// TRUOC qua cung cho. Dang ky ICP giua hai scan (tham so Icp/* cua chinh ban
// do); nhan neu ICP dat va chinh so voi do thi < max_corr; them lien ket.
//
// KHONG ghep node cung mot luot di: lien ket ICP trong hanh lang khong rang
// buoc doc truc va keo ban do truot (do trong sim 04/10: detectMoreLoopClosures
// cua RTAB-Map them hang tram lien ket nhu vay, sai 12 cm -> 33 cm).
// Tra 1 = da them, 0 = khong co ung vien / ICP khong dat, -1 = loi. `detail`:
// ly do. CHI luong slam, CHI che do mapping.
int TryFarLoopClosure(double radius_m, int min_graph_gap, double max_corr_m,
double max_corr_rad, std::string* detail);
StatusResponse Close(bool save_database);
const SlamStats& stats() const;

View File

@@ -51,6 +51,13 @@ struct SlamInput {
// Than robot chuc len/xuong khi tang/giam toc. Coi camera nam ngang thi san
// o 3 m bi day len ~0.2 m va thanh vat can gia trong ban do 3D.
const Transform* camera_to_base = nullptr;
// Di tren doc (slam.yaml `slope:`): do cao base_footprint va nghieng than
// luc nay. Co thi luu vao node (userData cua RTAB-Map) -- xem height_map.h.
bool has_height = false;
double z = 0.0;
double roll = 0.0;
double pitch = 0.0;
};
struct SlamOutput {

View File

@@ -22,9 +22,11 @@
#include <cstddef>
#include <cstdint>
#include <map>
#include <unordered_map>
#include <vector>
#include "vslam/height_map.h"
#include "vslam/vslam_common.h"
namespace rtabmap {
@@ -65,13 +67,32 @@ struct VoxelExportOptions {
// nhieu depth va nguoi di ngang chi o 1-2 khung; tuong, ban ghe dung yen
// thi nhieu node thay. 1 = giu moi voxel (hanh vi cu).
size_t min_node_hits = 1;
// Di tren doc: z cua tung node (do thi z) + mat san. Co ca hai thi diem dat
// o z THAT (z node + z cuc bo), va dai z_min..z_max tinh tu SAN tai cho diem
// do (mat doc khong lot vao ban do nhu vat can). Null = duong cu (moi node
// o z = 0, dai tinh tu san duoi node).
const std::map<int, double>* node_z = nullptr;
const FloorModel* floor = nullptr;
// Che do doc: thu cac o 2D (kich thuoc emit_size_m, khoa PackFloorCell) noi
// camera THAY MAT SAN (|cao - san| <= floor_band). Dung cho
// ClearLidarOnSeenRamps. Null = khong thu.
std::vector<uint64_t>* floor_cells = nullptr;
double floor_band = 0.05;
};
// Khoa o 2D (ix, iy) cua floor_cells.
inline uint64_t PackFloorCell(int32_t ix, int32_t iy) {
return (static_cast<uint64_t>(static_cast<uint32_t>(ix)) << 32) | static_cast<uint32_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.
struct VoxelNodeCache {
std::unordered_map<int, std::vector<float>> nodes; // id -> x,y,z,x,y,z...
// Diem node da cat theo dai z RONG (che do doc). Doi che do thi xoa cache.
bool wide = false;
};
// Gom diem -> tap voxel. KHONG chua kieu nao cua RTAB-Map, nen test duoc ma
@@ -156,8 +177,26 @@ void NodeCloudFromSensorData(const rtabmap::SensorData& data,
// mat san). La LOP VAT CAN tu camera cho nhung thu LiDAR (0.22 m) khong cat
// ngang: mat ghe, khung giuong, ke thap. Chi THEM o bi chiem, khong xoa.
// Tra ve so o moi danh dau (truoc do trong/chua biet).
//
// `floor` (di tren doc): do cao tinh tu SAN TAI CHO voxel (FloorModel) thay vi
// tu z = 0 -- mat doc va san tang tren khong con bi danh la tuong. Null =
// duong cu.
size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
OccupancyGrid* grid);
OccupancyGrid* grid, const FloorModel* floor = nullptr);
// Di tren doc: TREN DOC, lop LiDAR nhuong cho camera.
//
// LiDAR ngang thay mat doc len tu xa (> 4 m, ngoai tam depth) nhu mot buc
// tuong -- tuong gia vao node TRUOC khi camera kip thay mat doc, va cac scan
// sau BO tia cham doc (NaN) nen khong tia nao xoa duoc no. O day: o LiDAR bi
// chiem ma (1) node ban do gan nhat (trong `max_node_dist`) dang TREN DOC
// (|pitch| >= clamp) va (2) camera da THAY MAT SAN o do (floor_cells) -> tra
// ve trong. Vat can THAT tren doc van duoc MarkVoxelObstacles danh lai (goi
// SAU ham nay). Camera chua thay thi giu nguyen -- khong co bang chung.
// Tra ve so o da xoa.
size_t ClearLidarOnSeenRamps(OccupancyGrid* grid, const std::vector<uint64_t>& floor_cells,
double cell_size, const FloorModel& floor, double clamp_rad,
double max_node_dist);
// Hieu hai tap DA SAP XEP: `added` co trong `now` ma khong co trong `prev`,
// `removed` thi nguoc lai. O(n + m), mot luot.

View File

@@ -2,6 +2,7 @@
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <limits>
#include <unordered_set>
@@ -321,7 +322,8 @@ Pose2D ToMap(const Refined& rf, const Point& cen, const LikelihoodField& f) {
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg) {
const GlobalLocalizerConfig& cfg,
const RelocAdmit& admit) {
RelocMatch out;
if (field.empty() || pts_odom.empty()) return out;
@@ -354,6 +356,15 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
if (peaks.empty() || peaks[0].score <= 0.0) return out;
// T_map_odom cua mot o tho: TAM dam diem dat vao tam khoi (r, c), xoay th.
auto coarse_map = [&](int r, int c, double th) {
Refined q;
q.x = block_center(c);
q.y = block_center(r);
q.th = th;
return ToMap(q, cz.cen, field);
};
// --- Gom TOP-K dinh tho, khu trung trong reject_radius ---
// Xet nhieu dinh chu khong chi cai cao nhat: muc tho dung max-pool nen rat
// rong rai, thu tu o day chua chac dung.
@@ -370,17 +381,98 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
if (static_cast<int>(cand.size()) >= cfg.max_candidates) break;
}
// Co bang chung ngoai: them dinh TOT NHAT HOP LE cua moi goc. Dinh tho cao
// nhat moi goc co the deu la ban sao doi xung bi loai, va khi do cho that
// khong bao gio duoc tinh chinh. Chi goi `admit` khi o vuot dinh hien tai.
std::vector<AnglePeak> acand;
if (admit) {
std::vector<AnglePeak> apeaks;
for (int ia = 0; ia < n_ang; ++ia) {
const double th = ia * step;
const std::vector<float>& sc = scores[ia];
AnglePeak bp{0.0, -1, -1, th};
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > bp.score && admit(coarse_map(r, c, th))) bp = AnglePeak{v, r, c, th};
}
}
if (bp.r >= 0) apeaks.push_back(bp);
}
std::sort(apeaks.begin(), apeaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
const double min_sep = cfg.min_angle_sep_deg * kDegToRad;
for (int i = 0; i < std::min<int>(cfg.top_k, static_cast<int>(apeaks.size())); ++i) {
const AnglePeak& p = apeaks[i];
bool dup = false;
auto near = [&](const AnglePeak& q) {
const double dr = p.r - q.r, dc = p.c - q.c;
return dr * dr + dc * dc <= rad_c * rad_c;
};
// Dinh LiDAR goc o CUNG cho nhung lat huong la ung vien KHAC han.
for (const AnglePeak& q : cand) {
if (near(q) && std::fabs(AngleDiff(p.th, q.th)) < min_sep) { dup = true; break; }
}
for (const AnglePeak& q : acand) {
if (!dup && near(q)) { dup = true; break; }
}
if (!dup) acand.push_back(p);
if (static_cast<int>(acand.size()) >= cfg.max_candidates) break;
}
}
// ⚠️ Tinh chinh TUNG ung vien roi moi so diem voi nhau. So o muc tho (co
// max-pool) thi gan nhu moi cho canh tuong deu diem cao -- ban ROS do duoc
// tot/xau chi cach nhau 1.18 lan, cong chan loai ca ca DUNG.
auto refine_all = [&](const std::vector<AnglePeak>& src, std::vector<Refined>* dst) {
for (const AnglePeak& p : src) {
const Refined rf = Refine(field, P, block_center(p.c), block_center(p.r), p.th, rc, cfg);
if (rf.score >= 0.0) dst->push_back(rf);
}
std::sort(dst->begin(), dst->end(),
[](const Refined& a, const Refined& b) { return a.score > b.score; });
};
std::vector<Refined> refined;
for (const AnglePeak& p : cand) {
const Refined rf = Refine(field, P, block_center(p.c), block_center(p.r), p.th, rc, cfg);
if (rf.score >= 0.0) refined.push_back(rf);
}
refine_all(cand, &refined);
if (refined.empty()) return out;
std::sort(refined.begin(), refined.end(),
[](const Refined& a, const Refined& b) { return a.score > b.score; });
// --- Loc bang bang chung ngoai LiDAR (xem global_localizer.h) ---
// Nguoi thang hop le phai nam trong dai LiDAR mot minh cung nhap nhang
// (>= s_tot_nhat / min_ratio). Ngoai dai do = LiDAR CHAC o cho bang chung noi
// khong the -> giu nguyen ket qua LiDAR (y het khong co `admit`: ung vien them
// tu `acand` khong duoc dung), chi danh dau.
bool filt = false;
if (admit) {
std::vector<Refined> keep;
refine_all(acand, &keep); // dinh hop le them -- da hop le o muc tho
keep.erase(std::remove_if(keep.begin(), keep.end(),
[&](const Refined& rf) { return !admit(ToMap(rf, cz.cen, field)); }),
keep.end());
for (const Refined& rf : refined) {
if (admit(ToMap(rf, cz.cen, field))) {
keep.push_back(rf);
} else {
++out.tilt_rejected;
}
}
std::sort(keep.begin(), keep.end(),
[](const Refined& a, const Refined& b) { return a.score > b.score; });
if (!keep.empty() && keep[0].score >= refined[0].score / cfg.min_ratio) {
refined.swap(keep);
filt = true;
} else {
out.tilt_conflict = true;
}
}
// Doi thu cung phai hop le: gia thuyet bang chung noi khong the thi khong
// canh tranh. ⚠️ Ke ca khi KHONG ung vien nao bi loai: ban lat 180 do o CUNG
// cho khong nam trong danh sach tinh chinh (gom theo vi tri) ma chi hien o
// doi thu HUONG -- dung ca lan doc. Xung dot thi moi thu nhu cu.
auto rival_ok = [&](int r, int c, double th) {
if (!filt || admit(coarse_map(r, c, th))) return true;
++out.tilt_rejected;
return false;
};
const Refined& best = refined[0];
// --- Doi thu VI TRI ---
@@ -389,8 +481,10 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
// chot bua (9.3% duong tinh gia, sai 9-13 m). Nen quet lai diem THO o vung xa.
double s2 = 0.0;
for (size_t i = 1; i < refined.size(); ++i) {
if (std::hypot(refined[i].x - best.x, refined[i].y - best.y) > cfg.reject_radius) {
s2 = std::max(s2, refined[i].score);
if (std::hypot(refined[i].x - best.x, refined[i].y - best.y) > cfg.reject_radius &&
refined[i].score > s2) {
s2 = refined[i].score;
out.s2_from_odom = ToMap(refined[i], cz.cen, field);
}
}
const int rw = static_cast<int>(std::lround(best.y / res)) / k;
@@ -408,13 +502,18 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > fv && is_far(r, c)) { fv = v; fr = r; fc = c; fth = ia * step; }
if (v > fv && is_far(r, c) && rival_ok(r, c, ia * step)) {
fv = v; fr = r; fc = c; fth = ia * step;
}
}
}
}
if (fr >= 0 && fv > 0.0) {
const Refined alt = Refine(field, P, block_center(fc), block_center(fr), fth, rc, cfg);
s2 = std::max(s2, alt.score);
if (alt.score > s2) {
s2 = alt.score;
out.s2_from_odom = ToMap(alt, cz.cen, field);
}
}
}
@@ -432,15 +531,18 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > gv && !is_far(r, c)) { gv = v; gr = r; gc = c; gth = th; }
if (v > gv && !is_far(r, c) && rival_ok(r, c, th)) { gv = v; gr = r; gc = c; gth = th; }
}
}
}
if (gr >= 0 && gv > 0.0) {
s2_yaw = Refine(field, P, block_center(gc), block_center(gr), gth, rc, cfg).score;
const Refined alt = Refine(field, P, block_center(gc), block_center(gr), gth, rc, cfg);
s2_yaw = alt.score;
out.s2_yaw_from_odom = ToMap(alt, cz.cen, field);
}
}
out.tilt_used = filt && out.tilt_rejected > 0;
for (const Refined& rf : refined) out.hyps.push_back({ToMap(rf, cz.cen, field), rf.score});
out.map_from_odom = out.hyps[0].map_from_odom;
out.s1 = best.score;
@@ -450,6 +552,32 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
return out;
}
double ShiftScoreRatio(const LikelihoodField& field, const std::vector<Point>& pts_odom,
const Pose2D& map_from_odom, double shift_m, size_t max_points) {
if (field.empty() || pts_odom.empty()) return -1.0;
const std::vector<Point> pts = DownsamplePoints(pts_odom, field.resolution(), max_points);
auto score = [&](const Pose2D& T) {
const double c = std::cos(T.theta), s = std::sin(T.theta);
std::vector<Point> m(pts.size());
for (size_t i = 0; i < pts.size(); ++i) {
m[i].x = T.x + c * pts[i].x - s * pts[i].y;
m[i].y = T.y + s * pts[i].x + c * pts[i].y;
}
return field.MeanScore(m);
};
const double s0 = score(map_from_odom);
if (s0 <= 0.0) return -1.0;
double best = 0.0;
for (int k = 0; k < 8; ++k) {
const double a = k * M_PI / 4.0;
Pose2D t = map_from_odom;
t.x += shift_m * std::cos(a);
t.y += shift_m * std::sin(a);
best = std::max(best, score(t));
}
return best / s0;
}
RelocHypothesis LocalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom, const Pose2D& odom_now,
const Point& center, double radius,
@@ -610,4 +738,95 @@ RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig
return RelocVerdict::kAccept;
}
StaticPlace SummarizePlace(const std::vector<StaticRound>& hist) {
StaticPlace p;
if (hist.empty()) return p;
p.map_from_odom = hist.back().map_from_odom;
p.rounds = hist.size();
p.min_ratio = 1e9;
p.min_yaw = 1e9;
p.max_shift = -1.0;
for (const StaticRound& h : hist) {
p.min_ratio = std::min(p.min_ratio, h.ratio);
p.min_yaw = std::min(p.min_yaw, h.ratio_yaw);
p.max_shift = std::max(p.max_shift, h.shift);
}
return p;
}
RelocVerdict DecideStatic(std::vector<StaticRound>* hist, const StaticRound& r,
const std::vector<StaticPlace>& prev, const GlobalLocalizerConfig& cfg,
bool use_shift, bool* along_axis, std::string* why) {
*along_axis = false;
// Robot dung yen -> nguoi thang cac vong phai la CUNG mot pose robot.
if (!hist->empty()) {
const Pose2D& b = hist->back().robot;
if (std::hypot(r.robot.x - b.x, r.robot.y - b.y) > cfg.static_agree_m ||
std::fabs(AngleDiff(r.robot.theta, b.theta)) > cfg.static_agree_deg * kDegToRad) {
hist->clear();
}
}
hist->push_back(r);
// Giu MOI vong lien tiep cung cho (chan tren de khong phinh): doi thu tung
// hien ra o bat ky vong nao deu tinh.
constexpr size_t kMaxHist = 30;
while (hist->size() > kMaxHist) hist->erase(hist->begin());
const size_t k = static_cast<size_t>(std::max(1, cfg.static_rounds));
const StaticPlace cur = SummarizePlace(*hist);
const size_t n = cur.rounds;
char b[200];
if (cur.min_yaw < cfg.min_ratio_yaw) {
std::snprintf(b, sizeof(b), "ty le huong nho nhat %zu vong %.2f < %.2f", n, cur.min_yaw,
cfg.min_ratio_yaw);
*why = b;
return RelocVerdict::kAmbiguousYaw;
}
if (cur.min_ratio < cfg.min_ratio) {
std::snprintf(b, sizeof(b), "ty le nho nhat %zu vong %.2f < %.2f", n, cur.min_ratio, cfg.min_ratio);
*why = b;
return RelocVerdict::kAmbiguous;
}
if (use_shift && cur.max_shift >= cfg.tilt_max_shift_ratio) {
*along_axis = true;
std::snprintf(b, sizeof(b), "dich %.1f m van giu %.0f%% diem", cfg.tilt_shift_m,
100.0 * cur.max_shift);
*why = b;
return RelocVerdict::kAmbiguous;
}
if (n < k) {
std::snprintf(b, sizeof(b), "cho %zu vong lien tiep cung cho (%zu/%zu), ty le nho nhat %.2f", k, n,
k, cur.min_ratio);
*why = b;
return RelocVerdict::kNeedCycles;
}
// 1. Mot cho, chuan mot goc nhin.
if (cur.min_ratio >= cfg.static_min_ratio) {
std::snprintf(b, sizeof(b), "%zu vong cung cho: ty le nho nhat %.2f / huong %.2f", n, cur.min_ratio,
cur.min_yaw);
*why = b;
return RelocVerdict::kAccept;
}
// 2. Hai cho khac nhau, MOI cho deu qua min_ratio o moi vong cua no, cung gia thuyet.
for (const StaticPlace& p : prev) {
if (p.rounds < k || p.min_ratio < cfg.min_ratio || p.min_yaw < cfg.min_ratio_yaw) continue;
if (use_shift && p.max_shift >= cfg.tilt_max_shift_ratio) continue;
if (std::hypot(p.map_from_odom.x - cur.map_from_odom.x, p.map_from_odom.y - cur.map_from_odom.y) >
cfg.static_agree_m ||
std::fabs(AngleDiff(p.map_from_odom.theta, cur.map_from_odom.theta)) >
cfg.static_agree_deg * kDegToRad) {
continue;
}
std::snprintf(b, sizeof(b),
"hai cho cung pose: ty le nho nhat %.2f (cho nay, %zu vong) / %.2f (cho truoc, %zu vong)",
cur.min_ratio, n, p.min_ratio, p.rounds);
*why = b;
return RelocVerdict::kAccept;
}
std::snprintf(b, sizeof(b),
"ty le nho nhat %zu vong %.2f < %.2f -- can them mot cho khac (sau khi bo) cung pose",
n, cur.min_ratio, cfg.static_min_ratio);
*why = b;
return RelocVerdict::kNeedCycles;
}
} // namespace vslam

View File

@@ -0,0 +1,174 @@
#include "vslam/height_map.h"
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include <algorithm>
#include <cmath>
#include <limits>
namespace vslam {
std::map<int, double> SolveZGraph(const std::map<int, NodeHeight>& meas,
const std::vector<ZGraphLink>& links,
const ZGraphConfig& cfg) {
std::map<int, double> out;
if (meas.empty()) return out;
std::map<int, int> index;
for (const auto& kv : meas) {
const int k = static_cast<int>(index.size());
index[kv.first] = k;
}
const int n = static_cast<int>(index.size());
// Phuong trinh chuan H z = g, H = sum w a a^T.
std::vector<Eigen::Triplet<double>> trip;
Eigen::VectorXd g = Eigen::VectorXd::Zero(n);
auto add_rel = [&](int i, int j, double dz, double sigma) {
// z_j - z_i = dz
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
trip.emplace_back(j, j, w);
trip.emplace_back(i, j, -w);
trip.emplace_back(j, i, -w);
g(i) -= w * dz;
g(j) += w * dz;
};
auto add_abs = [&](int i, double z, double sigma) {
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
g(i) += w * z;
};
for (const auto& kv : meas) add_abs(index[kv.first], kv.second.z, cfg.sigma_prior);
add_abs(index[meas.begin()->first], meas.begin()->second.z, cfg.sigma_first);
for (const ZGraphLink& l : links) {
auto a = meas.find(l.from), b = meas.find(l.to);
if (a == meas.end() || b == meas.end() || l.from == l.to) continue;
const int i = index[l.from], j = index[l.to];
if (l.neighbor) {
const double dz = b->second.z - a->second.z;
add_rel(i, j, dz, cfg.sigma_neighbor + cfg.sigma_rel * std::fabs(dz));
continue;
}
const bool flat_a = std::fabs(a->second.pitch) < cfg.clamp_rad;
const bool flat_b = std::fabs(b->second.pitch) < cfg.clamp_rad;
if (flat_a && flat_b) {
add_rel(i, j, 0.0, cfg.sigma_loop_flat);
} else {
// Mat phang doc cua node `from`, keo toi `to`.
FloorNode fa;
fa.roll = a->second.roll;
fa.pitch = a->second.pitch;
const double dz = PlaneZ(fa, l.dx, l.dy);
add_rel(i, j, dz, cfg.sigma_loop_slope + cfg.sigma_rel * std::fabs(dz));
}
}
Eigen::SparseMatrix<double> H(n, n);
H.setFromTriplets(trip.begin(), trip.end());
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(H);
if (solver.info() != Eigen::Success) {
for (const auto& kv : meas) out[kv.first] = kv.second.z;
return out;
}
const Eigen::VectorXd z = solver.solve(g);
for (const auto& kv : index) out[kv.first] = z(kv.second);
return out;
}
double PlaneZ(const FloorNode& n, double x, double y) {
const double dx = x - n.x, dy = y - n.y;
const double c = std::cos(n.theta), s = std::sin(n.theta);
const double fwd = c * dx + s * dy;
const double left = -s * dx + c * dy;
// Ry(pitch): +x chuc xuong khi pitch duong; Rx(roll): +y len khi roll duong.
return n.z - fwd * std::tan(n.pitch) + left * std::tan(n.roll);
}
void FloorModel::Build(const std::vector<FloorNode>& nodes, double radius, double cell) {
nodes_ = nodes;
radius_ = radius;
cell_ = cell;
nearest_.clear();
w_ = h_ = 0;
if (nodes_.empty()) return;
double xmin = std::numeric_limits<double>::max(), ymin = xmin;
double xmax = std::numeric_limits<double>::lowest(), ymax = xmax;
for (const FloorNode& f : nodes_) {
xmin = std::min(xmin, f.x);
xmax = std::max(xmax, f.x);
ymin = std::min(ymin, f.y);
ymax = std::max(ymax, f.y);
}
x0_ = xmin - radius - cell;
y0_ = ymin - radius - cell;
w_ = static_cast<int>(std::ceil((xmax - xmin + 2 * radius + 2 * cell) / cell));
h_ = static_cast<int>(std::ceil((ymax - ymin + 2 * radius + 2 * cell) / cell));
nearest_.assign(static_cast<size_t>(w_) * h_, -1);
std::vector<float> best(nearest_.size(), std::numeric_limits<float>::max());
const int rc = static_cast<int>(std::ceil(radius / cell));
const double r2 = radius * radius;
for (size_t k = 0; k < nodes_.size(); ++k) {
const FloorNode& f = nodes_[k];
const int cx = static_cast<int>((f.x - x0_) / cell), cy = static_cast<int>((f.y - y0_) / cell);
for (int iy = std::max(0, cy - rc); iy <= std::min(h_ - 1, cy + rc); ++iy) {
for (int ix = std::max(0, cx - rc); ix <= std::min(w_ - 1, cx + rc); ++ix) {
const double px = x0_ + (ix + 0.5) * cell, py = y0_ + (iy + 0.5) * cell;
const double d2 = (px - f.x) * (px - f.x) + (py - f.y) * (py - f.y);
if (d2 > r2) continue;
const size_t i = static_cast<size_t>(iy) * w_ + ix;
if (d2 < best[i]) {
best[i] = static_cast<float>(d2);
nearest_[i] = static_cast<int>(k);
}
}
}
}
}
bool FloorModel::NearestNode(double x, double y, FloorNode* node, double* dist) const {
if (nodes_.empty()) return false;
const int ix = static_cast<int>(std::floor((x - x0_) / cell_));
const int iy = static_cast<int>(std::floor((y - y0_) / cell_));
if (ix < 0 || iy < 0 || ix >= w_ || iy >= h_) return false;
const int k = nearest_[static_cast<size_t>(iy) * w_ + ix];
if (k < 0) return false;
*node = nodes_[static_cast<size_t>(k)];
if (dist != nullptr) *dist = std::hypot(x - node->x, y - node->y);
return true;
}
bool FloorModel::FloorAt(double x, double y, double* z, double* dist) const {
FloorNode f;
if (!NearestNode(x, y, &f, dist)) return false;
*z = PlaneZ(f, x, y);
return true;
}
bool FloorGradientAt(const FloorModel& fm, double x, double y, double max_dist, double* gx,
double* gy) {
FloorNode n;
double d = 0.0;
if (!fm.NearestNode(x, y, &n, &d) || d > max_dist) return false;
// Dao ham cua PlaneZ: z = z_n - fwd * tan(pitch) + left * tan(roll).
const double c = std::cos(n.theta), s = std::sin(n.theta);
const double tp = std::tan(n.pitch), tr = std::tan(n.roll);
*gx = -tp * c - tr * s;
*gy = -tp * s + tr * c;
return true;
}
double TiltResidual(double roll, double pitch, double yaw, double gx, double gy) {
const double c = std::cos(yaw), s = std::sin(yaw);
const double sf = gx * c + gy * s; // doc theo huong mui (len = duong)
const double sl = -gx * s + gy * c; // doc sang trai
// Than nam tren mat do, R = Rz(yaw) Ry(pitch) Rx(roll): truc x than nam trong
// mat -> tan(pitch) = -sf; truc y than nam trong mat -> tan(roll) = sl * cos(pitch).
const double mf = -std::tan(pitch);
const double ml = std::tan(roll) / std::max(1e-6, std::cos(pitch));
return std::hypot(mf - sf, ml - sl);
}
} // namespace vslam

View File

@@ -3,14 +3,17 @@
#include <rtabmap/core/Memory.h>
#include <rtabmap/core/Optimizer.h>
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/RegistrationIcp.h>
#include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/Statistics.h>
#include <rtabmap/utilite/ULogger.h>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <mutex>
#include <set>
#include "vslam/geometry.h"
#include "vslam/log.h"
@@ -45,6 +48,14 @@ class RtabmapSlamImpl {
// Diem depth theo node cho ban do voxel. Chi ExportVoxels (luong slam) cham.
VoxelNodeCache voxel_cache;
// ---- z ban do (di tren doc). CHI luong slam cham. ----
std::map<int, NodeHeight> node_meas; // z DO luc tao node
std::set<int> node_no_height; // node DB khong co userData z
std::map<int, double> node_z; // z sau do thi z
FloorModel floor;
bool use_heights = false;
std::vector<uint64_t> floor_cells;
void RecordMs(double ms) {
stats.last_ms = ms;
stats.max_ms = std::max(stats.max_ms, ms);
@@ -282,6 +293,15 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
in.camera_to_base != nullptr ? *in.camera_to_base
: impl_->camera_to_base,
impl_->next_id++);
if (in.has_height) {
// z / roll / pitch DO cua node -> DB (userData). Ban do quet xong mo lai
// o localization van co z.
cv::Mat ud(1, 3, CV_64FC1);
ud.at<double>(0) = in.z;
ud.at<double>(1) = in.roll;
ud.at<double>(2) = in.pitch;
data.setUserData(ud);
}
// Phuong sai odom: nguoi goi dat thi dung, khong thi lay tu slam.yaml.
const double lin_var = in.odom_linear_var > 0.0
@@ -319,6 +339,12 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
}
impl_->stats.frames_processed++;
if (in.has_height && impl_->cfg.mode == SlamMode::kMapping) {
// RTAB-Map tu sinh id node (Mem/GenerateIds) -- id cua SensorData chi la
// goi y. Node vua them la node cuoi cua bo nho.
const int id = impl_->rtabmap.getLastLocationId();
if (id > 0) impl_->node_meas[id] = NodeHeight{in.z, in.roll, in.pitch};
}
out.loop_closure_id = impl_->rtabmap.getLoopClosureId();
const rtabmap::Statistics& st = impl_->rtabmap.getStatistics();
auto stat = [&](const std::string& k, double dflt) {
@@ -377,9 +403,195 @@ StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt,
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
if (impl_->use_heights && !impl_->node_z.empty()) {
VoxelExportOptions o = opt;
o.node_z = &impl_->node_z;
o.floor = &impl_->floor;
impl_->floor_cells.clear();
o.floor_cells = &impl_->floor_cells;
return ExportVoxelGrid(impl_->rtabmap, o, &impl_->voxel_cache, out);
}
return ExportVoxelGrid(impl_->rtabmap, opt, &impl_->voxel_cache, out);
}
void RtabmapSlam::SetUseHeights(bool on) { impl_->use_heights = on; }
const std::vector<uint64_t>& RtabmapSlam::floor_cells() const { return impl_->floor_cells; }
int RtabmapSlam::TryFarLoopClosure(double radius_m, int min_graph_gap, double max_corr_m,
double max_corr_rad, std::string* detail) {
if (!impl_->inited || impl_->cfg.mode != SlamMode::kMapping) return 0;
const int cur = impl_->rtabmap.getLastLocationId();
const std::map<int, rtabmap::Transform>& poses = impl_->rtabmap.getLocalOptimizedPoses();
const auto itc = poses.find(cur);
if (cur <= 0 || itc == poses.end() || itc->second.isNull()) return 0;
// Ung vien: node CU (thu tu id = thu tu thoi gian), gan nhat trong ban kinh.
std::vector<int> ids;
ids.reserve(poses.size());
for (const auto& kv : poses) ids.push_back(kv.first);
const long ci = std::lower_bound(ids.begin(), ids.end(), cur) - ids.begin();
int cand = 0;
double best = radius_m;
for (long i = 0; i + min_graph_gap < ci; ++i) {
const rtabmap::Transform& p = poses.at(ids[static_cast<size_t>(i)]);
if (p.isNull()) continue;
const double d = std::hypot(p.x() - itc->second.x(), p.y() - itc->second.y());
if (d <= best) {
best = d;
cand = ids[static_cast<size_t>(i)];
}
}
if (cand == 0) return 0;
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
if (mem == nullptr) return -1;
const std::multimap<int, rtabmap::Link> links = mem->getLinks(cur);
if (links.find(cand) != links.end()) return 0; // da noi roi
try {
rtabmap::SensorData a = mem->getNodeData(cur, false, true, false, false);
rtabmap::SensorData b = mem->getNodeData(cand, false, true, false, false);
a.uncompressData();
b.uncompressData();
if (a.laserScanRaw().isEmpty() || b.laserScanRaw().isEmpty()) {
if (detail != nullptr) *detail = "node khong co scan";
return 0;
}
const rtabmap::Transform guess = itc->second.inverse() * poses.at(cand);
rtabmap::RegistrationIcp reg(impl_->rtabmap.getParameters());
rtabmap::RegistrationInfo info;
const rtabmap::Transform t = reg.computeTransformation(a, b, guess, &info);
if (t.isNull()) {
if (detail != nullptr) *detail = "ICP tu choi: " + info.rejectedMsg;
return 0;
}
const rtabmap::Transform corr = guess.inverse() * t;
const double ct = std::hypot(corr.x(), corr.y());
const double cr = std::fabs(corr.theta());
if (ct > max_corr_m || cr > max_corr_rad) {
if (detail != nullptr) {
*detail = "chinh qua lon (" + std::to_string(ct) + " m, " + std::to_string(cr) + " rad)";
}
return 0;
}
// Thong tin = nghich dao hiep phuong sai ICP, chan duoi phuong sai de
// khong co truc nao "chac tuyet doi".
cv::Mat inf = cv::Mat::eye(6, 6, CV_64FC1);
for (int k = 0; k < 6; ++k) {
const double v = info.covariance.empty() ? 1e-4 : info.covariance.at<double>(k, k);
inf.at<double>(k, k) = 1.0 / std::max(v, 1e-6);
}
if (!impl_->rtabmap.addLink(rtabmap::Link(cur, cand, rtabmap::Link::kUserClosure, t, inf))) {
if (detail != nullptr) *detail = "addLink tu choi";
return 0;
}
if (detail != nullptr) {
*detail = "noi " + std::to_string(cur) + " -> " + std::to_string(cand) + " (cach " +
std::to_string(ci - (std::lower_bound(ids.begin(), ids.end(), cand) - ids.begin())) +
" node, " + std::to_string(best) + " m), chinh " + std::to_string(ct) + " m / " +
std::to_string(cr * 180.0 / M_PI) + " do, ti le khop " +
std::to_string(info.icpInliersRatio);
}
} catch (const std::exception& e) {
if (detail != nullptr) *detail = std::string("nem: ") + e.what();
return -1;
}
std::lock_guard<std::mutex> lk(impl_->out_mu);
impl_->map_correction = FromRtabmap(impl_->rtabmap.getMapCorrection());
impl_->map_version++;
impl_->stats.loop_closures++;
return 1;
}
const FloorModel& RtabmapSlam::floor_model() const { return impl_->floor; }
StatusResponse RtabmapSlam::UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
std::map<int, rtabmap::Transform> poses;
std::multimap<int, rtabmap::Link> links;
impl_->rtabmap.getGraph(poses, links, /*optimized=*/true, /*global=*/false);
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "do thi rong");
}
// Node chua co z do: nap userData tu DB (ban do quet o phien truoc). Node
// DB khong co (quet truoc khi co che do doc) thi nho lai, khong hoi mai.
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
for (const auto& kv : poses) {
const int id = kv.first;
if (id <= 0 || impl_->node_meas.count(id) || impl_->node_no_height.count(id)) continue;
if (mem == nullptr) break;
const rtabmap::SensorData d = mem->getNodeData(id, false, false, true, false);
cv::Mat ud;
d.uncompressDataConst(nullptr, nullptr, nullptr, &ud);
if (ud.type() == CV_64FC1 && ud.total() == 3) {
impl_->node_meas[id] = NodeHeight{ud.at<double>(0), ud.at<double>(1), ud.at<double>(2)};
} else {
impl_->node_no_height.insert(id);
}
}
std::map<int, NodeHeight> meas;
for (const auto& kv : poses) {
auto it = impl_->node_meas.find(kv.first);
if (it != impl_->node_meas.end()) meas[kv.first] = it->second;
}
std::vector<ZGraphLink> zl;
for (const auto& kv : links) {
const rtabmap::Link& l = kv.second;
ZGraphLink z;
z.from = l.from();
z.to = l.to();
switch (l.type()) {
case rtabmap::Link::kNeighbor:
case rtabmap::Link::kNeighborMerged:
z.neighbor = true;
break;
case rtabmap::Link::kGlobalClosure:
case rtabmap::Link::kLocalSpaceClosure:
case rtabmap::Link::kLocalTimeClosure:
case rtabmap::Link::kUserClosure:
z.neighbor = false;
break;
default:
continue;
}
if (l.transform().isNull()) continue;
z.dx = l.transform().x();
z.dy = l.transform().y();
zl.push_back(z);
}
impl_->node_z = SolveZGraph(meas, zl, cfg);
std::vector<FloorNode> fn;
fn.reserve(impl_->node_z.size());
for (const auto& kv : impl_->node_z) {
const auto p = poses.find(kv.first);
if (p == poses.end() || p->second.isNull()) continue;
const NodeHeight& m = meas[kv.first];
FloorNode f;
f.x = p->second.x();
f.y = p->second.y();
f.theta = p->second.theta();
f.z = kv.second;
f.roll = m.roll;
f.pitch = m.pitch;
fn.push_back(f);
}
impl_->floor.Build(fn);
if (nodes_out != nullptr) *nodes_out = impl_->node_z.size();
return StatusResponse::Ok();
}
bool RtabmapSlam::HeightAt(double x, double y, double radius, double* z) const {
double d = 0.0;
if (!impl_->floor.FloorAt(x, y, z, &d)) return false;
return d <= radius;
}
namespace {
cv::Matx44d ToMatx44(const rtabmap::Transform& t) {
return cv::Matx44d(t.r11(), t.r12(), t.r13(), t.x(), t.r21(), t.r22(), t.r23(), t.y(),

View File

@@ -230,13 +230,17 @@ void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
}
size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
OccupancyGrid* grid) {
OccupancyGrid* grid, const FloorModel* floor) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f) return 0;
const double r = vg.resolution;
const double inv = 1.0 / grid->resolution;
size_t marked = 0;
for (const VoxelIndex& k : vg.cells) {
const double z = vg.origin_z + (k.z + 0.5) * r;
double z = vg.origin_z + (k.z + 0.5) * r;
if (floor != nullptr) {
double f = 0.0;
if (floor->FloorAt(vg.origin_x + (k.x + 0.5) * r, vg.origin_y + (k.y + 0.5) * r, &f)) z -= f;
}
if (z < z_min || z > z_max) continue;
// Luoi 2D khong xoay (occupancy_export dat orientation = dong nhat), va
// hang 0 la ymin -- cung quy uoc voi RTAB-Map/map_server.
@@ -255,6 +259,38 @@ size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
return marked;
}
size_t ClearLidarOnSeenRamps(OccupancyGrid* grid, const std::vector<uint64_t>& floor_cells,
double cell_size, const FloorModel& floor, double clamp_rad,
double max_node_dist) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f || floor_cells.empty()) {
return 0;
}
std::vector<uint64_t> seen(floor_cells);
std::sort(seen.begin(), seen.end());
seen.erase(std::unique(seen.begin(), seen.end()), seen.end());
const double res = grid->resolution;
const double inv = 1.0 / cell_size;
size_t cleared = 0;
for (uint32_t r = 0; r < grid->height; ++r) {
for (uint32_t c = 0; c < grid->width; ++c) {
int8_t& v = grid->data[static_cast<size_t>(r) * grid->width + c];
if (v < 50) continue;
const double x = grid->origin.position.x + (c + 0.5) * res;
const double y = grid->origin.position.y + (r + 0.5) * res;
FloorNode n;
double d = 0.0;
if (!floor.NearestNode(x, y, &n, &d) || d > max_node_dist) continue;
if (std::fabs(n.pitch) < clamp_rad) continue;
const uint64_t k = PackFloorCell(static_cast<int32_t>(std::floor(x * inv)),
static_cast<int32_t>(std::floor(y * inv)));
if (!std::binary_search(seen.begin(), seen.end(), k)) continue;
v = 0;
++cleared;
}
}
return cleared;
}
void NodeCloudFromSensorData(const rtabmap::SensorData& data,
const VoxelExportOptions& opt,
std::vector<float>* out) {
@@ -298,11 +334,30 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
it = poses.count(it->first) ? std::next(it) : cache->nodes.erase(it);
}
// Di tren doc: diem dat o z THAT, va dai z cat theo SAN tai cho diem -- ca
// hai viec lam O DAY, nen bo gom nhan moi z. Cache diem cua node giu dai
// rong hon (mat doc xuong phia truoc o z am so voi node).
const bool use_floor = opt.node_z != nullptr && opt.floor != nullptr;
VoxelExportOptions acc_opt = opt;
if (use_floor) {
acc_opt.z_min = -1e9;
acc_opt.z_max = 1e9;
}
VoxelExportOptions node_opt = opt;
if (use_floor) {
node_opt.z_min = opt.z_min - 3.0;
node_opt.z_max = opt.z_max + 3.0;
}
if (cache->wide != use_floor) {
cache->nodes.clear();
cache->wide = use_floor;
}
// 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;
VoxelAccumulator acc(opt);
VoxelHitCounter hits(opt);
VoxelAccumulator acc(acc_opt);
VoxelHitCounter hits(acc_opt);
size_t nodes_used = 0, fetched = 0, pending = 0, no_points = 0;
for (const auto& kv : poses) {
@@ -320,7 +375,7 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
// moi node va ban do 3D im lang rong khong.
data.uncompressData();
std::vector<float> pts;
NodeCloudFromSensorData(data, opt, &pts);
NodeCloudFromSensorData(data, node_opt, &pts);
it = cache->nodes.emplace(kv.first, std::move(pts)).first;
}
const std::vector<float>& pts = it->second;
@@ -336,12 +391,31 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
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();
double z_off = 0.0;
if (use_floor) {
const auto zi = opt.node_z->find(kv.first);
if (zi != opt.node_z->end()) z_off = zi->second;
}
if (count_hits) hits.BeginNode();
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;
const double wy = r10 * px + r11 * py + r12 * pz + ty;
const double wz = r20 * px + r21 * py + r22 * pz + tz;
double wz = r20 * px + r21 * py + r22 * pz + tz;
if (use_floor) {
wz += z_off;
double f = z_off;
opt.floor->FloorAt(wx, wy, &f);
const double h = wz - f;
if (opt.floor_cells != nullptr && std::fabs(h) <= opt.floor_band) {
const double inv = 1.0 / opt.emit_size_m;
opt.floor_cells->push_back(
PackFloorCell(static_cast<int32_t>(std::floor(wx * inv)),
static_cast<int32_t>(std::floor(wy * inv))));
}
if (h < opt.z_min || h > opt.z_max) continue;
}
if (count_hits) hits.AddPoint(wx, wy, wz);
else acc.AddPoint(wx, wy, wz);
}

View File

@@ -80,12 +80,31 @@ void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out);
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
float quant_m, const Pose2D& delta, std::string* out);
// Do cao SAN cua ban do (slam.yaml slope.enabled): luoi THO, mm, kFloorUnknown
// = chua biet. Web uon mat phang ban do 2D theo luoi nay -- khong co no thi
// mat doc va san tang tren duoc ve o z = 0, nam DUOI tuong voxel (o z that)
// va trong nhu san bi thung.
constexpr int16_t kFloorUnknown = -32768;
struct MapFloorGrid {
float resolution = 0.2f;
uint32_t width = 0;
uint32_t height = 0;
float origin_x = 0.0f;
float origin_y = 0.0f;
std::vector<int16_t> mm; // hang chinh, hang 0 = y nho nhat (nhu OccupancyGrid)
};
// RLE hang-chinh. Xem rle.h.
// `type` cho phep dung chung bo ma hoa cho ban do SLAM (kMapFull) va ban do
// THE GIOI cua bo mo phong (kWorldMap): khung giong het nhau, chi khac y
// nghia. Mot bo ma hoa thu hai se la hai cho de lech dinh dang.
//
// `floor_grid` (tuy chon): khoi do cao san NOI SAU phan RLE -- magic "FLH1", f32
// res, i32 w, i32 h, f32 ox, f32 oy, roi w*h int16 (mm). Khong co thi khung y
// het cu.
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
BinaryType type = BinaryType::kMapFull);
BinaryType type = BinaryType::kMapFull,
const MapFloorGrid* floor_grid = nullptr);
// (kMapPatch = 4 da bi BO. No noi duoc vao dau: cong per-session chi la mot
// atomic `acked_map_version_`, khong dien ta noi "session nay dang giu luoi
@@ -149,7 +168,9 @@ struct BinaryHeader {
bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out);
bool DecodeScan(const std::string& buf, LaserScan* out);
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out);
// `floor_grid` (tuy chon) nhan khoi do cao san neu khung co; khong co thi width = 0.
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out,
MapFloorGrid* floor_grid = nullptr);
// Giai mot manh. `out` duoc NOI THEM, khong xoa -- rap nhieu manh bang cach
// goi lien tiep. `total`/`chunk_index`/`chunk_count`/`epoch` tra qua con tro

View File

@@ -13,6 +13,7 @@
#include <string>
#include <vector>
#include "vslam/binary_codec.h"
#include "vslam/stats.h"
#include "vslam/vslam_common.h"
@@ -138,6 +139,13 @@ struct WebSnapshot {
double pitch = 0.0;
bool accel_ok = true;
// Di tren doc (slam.yaml `slope:`): z UOC LUONG cua robot. Chi xuat khi bat
// -- 0 khi tat la noi doi, client khong phan biet duoc "o san" voi "khong biet".
bool have_height = false;
double height_z = 0.0;
double height_sigma = 0.0;
bool on_slope = false;
// ============ GROUND TRUTH ============
// CHI co khi chay mo phong. Day la tuong duong cua /ground_truth/odom trong
// repo cu, noi ghi ro "khong estimator nao duoc subscribe".
@@ -151,6 +159,7 @@ struct WebSnapshot {
Pose2D ground_truth;
double gt_roll = 0.0; // nghieng THAT, de doi chung gravity_align
double gt_pitch = 0.0;
double gt_z = 0.0; // do cao san THAT duoi robot (world co doc)
SafetySnapshot safety;
SlamSnapshot slam;
@@ -173,6 +182,8 @@ struct WebSnapshot {
Pose2D cloud_delta;
bool have_cloud_delta = false;
OccupancyGridPtr map; // ban do SLAM dung
// Do cao SAN cua ban do (che do doc), gui kem khung map. Null = phang.
std::shared_ptr<const MapFloorGrid> map_floor;
// Ban do THE GIOI cua bo mo phong (khung nhin "Gazebo"). Null khi chay
// that -- luc do khong co su that nao de doi chieu.
OccupancyGridPtr world_map;

View File

@@ -147,7 +147,7 @@ void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points
}
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
BinaryType type) {
BinaryType type, const MapFloorGrid* floor_grid) {
PutHeader(out, type, stamp);
PutF32(out, map.resolution);
PutI32(out, static_cast<int32_t>(map.width));
@@ -169,6 +169,19 @@ void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
(*out)[run_count_off + static_cast<size_t>(i)] =
static_cast<char>((r32 >> (8 * i)) & 0xFF);
}
// Khoi do cao san (che do doc), NOI SAU phan RLE -- xem binary_codec.h.
const MapFloorGrid* fg = floor_grid;
if (fg != nullptr && fg->width > 0 && fg->height > 0 &&
fg->mm.size() == static_cast<size_t>(fg->width) * fg->height) {
out->append("FLH1", 4);
PutF32(out, fg->resolution);
PutI32(out, static_cast<int32_t>(fg->width));
PutI32(out, static_cast<int32_t>(fg->height));
PutF32(out, fg->origin_x);
PutF32(out, fg->origin_y);
for (int16_t v : fg->mm) PutI16(out, v);
}
}
// --- Ban do voxel 3D -------------------------------------------------------
@@ -333,9 +346,10 @@ bool DecodeScan(const std::string& buf, LaserScan* out) {
return true;
}
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) {
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out, MapFloorGrid* floor_grid) {
BinaryHeader h;
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false;
if (floor_grid != nullptr) *floor_grid = MapFloorGrid{};
size_t o = kBinaryHeaderSize;
if (buf.size() < o + 28) return false;
@@ -351,6 +365,25 @@ bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) {
const size_t expected = static_cast<size_t>(out->width) * out->height;
if (!RleDecode(buf, o, runs, expected, &out->data)) return false;
// Khoi do cao san tuy chon, ngay sau RLE (3 byte moi run).
o += static_cast<size_t>(runs) * 3;
if (floor_grid != nullptr && buf.size() >= o + 24 && buf.compare(o, 4, "FLH1") == 0) {
MapFloorGrid f;
f.resolution = GetF32(buf, o + 4);
f.width = static_cast<uint32_t>(GetI32(buf, o + 8));
f.height = static_cast<uint32_t>(GetI32(buf, o + 12));
f.origin_x = GetF32(buf, o + 16);
f.origin_y = GetF32(buf, o + 20);
const size_t n = static_cast<size_t>(f.width) * f.height;
if (buf.size() >= o + 24 + 2 * n) {
f.mm.resize(n);
for (size_t i = 0; i < n; ++i) {
f.mm[i] = static_cast<int16_t>(GetU16(buf, o + 24 + 2 * i));
}
*floor_grid = std::move(f);
}
}
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
return true;
}

View File

@@ -115,6 +115,15 @@ void WriteStateJson(const WebSnapshot& s, std::string* out) {
Num("x", s.pose_map.x, 3, out); Comma(out);
Num("y", s.pose_map.y, 3, out); Comma(out);
Num("yaw", s.pose_map.theta, 4, out);
if (s.have_height) {
// z + nghieng: khung 3D dat robot len doc. Chi khi BAT che do doc.
Comma(out);
Num("z", s.height_z, 3, out); Comma(out);
Num("roll", s.roll, 4, out); Comma(out);
Num("pitch", s.pitch, 4, out); Comma(out);
Num("z_sigma", s.height_sigma, 3, out); Comma(out);
Bool("on_slope", s.on_slope, out);
}
out->push_back('}'); Comma(out);
// Bu do tre cua scan: quy tia tu pose HIEN TAI ve pose LUC QUET. Cloud
@@ -141,6 +150,7 @@ void WriteStateJson(const WebSnapshot& s, std::string* out) {
Num("yaw", s.ground_truth.theta, 4, out); Comma(out);
Num("roll", s.gt_roll, 4, out); Comma(out);
Num("pitch", s.gt_pitch, 4, out); Comma(out);
Num("z", s.gt_z, 3, out); Comma(out);
// Sai so vi tri cua uoc luong so voi su that. Tinh o day thay vi de
// client tu tru: neu sau nay map va gt khac goc toa do thi phep tru
// ngay tren client se sai am tham.

View File

@@ -830,7 +830,8 @@ void WebServer::Publish(const WebSnapshot& snap) {
if (s->acked_map_version() == snap.slam.map_version) continue;
if (!buf) {
buf = std::make_shared<std::string>();
EncodeMapFull(*snap.map, snap.stamp, buf.get());
EncodeMapFull(*snap.map, snap.stamp, buf.get(), BinaryType::kMapFull,
snap.map_floor.get());
}
s->Send(buf, true, /*is_map=*/true);
s->set_acked_map_version(snap.slam.map_version);

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-09-30a';
const UI_VERSION = '2026-10-05c';
// ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau.
//
@@ -68,6 +68,8 @@ const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_PATH = 5;
const T_WORLD_MAP = 6;
// Ban do voxel 3D: tap day du (chia manh) va phan them/bot.
const T_VOXEL_FULL = 7, T_VOXEL_DELTA = 8;
// Khoi do cao SAN noi sau RLE cua khung ban do (che do doc, binary_codec.h).
const FLOOR_MAGIC = 0x31484C46; // 'FLH1' little-endian
// Ba ngu nghia cua mot tia. Lan lon chung la lam sai ca man hinh.
const R_NAN = 0xFFFF; // khong do duoc (duoi range_min)
@@ -229,7 +231,21 @@ function onBinary(dv) {
cells.fill(val, p, p + len);
p += len;
}
const grid = { res, w, h, ox, oy, cells };
// Do cao san (mm, -32768 = chua biet) ngay sau RLE. Khong co thi ban do
// phang nhu cu.
let floor = null;
const fo = off + 28 + runs * 3;
if (type === T_MAP_FULL && dv.byteLength >= fo + 24 &&
dv.getUint32(fo, true) === FLOOR_MAGIC) {
const fw = dv.getInt32(fo + 8, true), fh = dv.getInt32(fo + 12, true);
if (fw > 0 && fh > 0 && dv.byteLength >= fo + 24 + fw * fh * 2) {
const mm = new Int16Array(fw * fh);
for (let i = 0; i < fw * fh; i++) mm[i] = dv.getInt16(fo + 24 + i * 2, true);
floor = { res: dv.getFloat32(fo + 4, true), w: fw, h: fh,
ox: dv.getFloat32(fo + 16, true), oy: dv.getFloat32(fo + 20, true), mm };
}
}
const grid = { res, w, h, ox, oy, cells, floor };
if (type === T_WORLD_MAP) {
// Ban do THE GIOI: su that, de lai cho chuan. KHONG lan vao state.map.
state.worldMap = grid;
@@ -394,6 +410,13 @@ function onState(s) {
// khong phan biet duoc "dung o goc" voi "khong biet".
state.gt = s.gt || null;
txt('gtErr', s.gt ? fmt(s.gt.err, 3) + ' m' : '--');
// Do cao san THAT (sim co doc). Pose uoc luong hien la 2D: chua co z.
txt('gtZ', s.gt && s.gt.z !== undefined ? fmt(s.gt.z, 3) + ' m' : '--');
// z uoc luong: chi co khi slam.yaml slope.enabled. +-sigma, (doc) khi |pitch|
// vuot nguong kep.
txt('estZ', s.pose && s.pose.z !== undefined
? fmt(s.pose.z, 3) + ' m \u00b1' + fmt(s.pose.z_sigma, 2) + (s.pose.on_slope ? ' (doc)' : '')
: '--');
state.slamMode = s.slam.mode;
txt('mode', s.slam.mode);
@@ -613,6 +636,11 @@ function anchorPose(robotPose, anchoredAt) {
x: robotPose.x + c * lx - s * ly,
y: robotPose.y + s * lx + c * ly,
yaw: robotPose.yaw + (anchoredAt.yaw - state.pose.yaw),
// Cao do san duoi robot va do nghieng than (che do doc): khung 3D nang
// scan/cloud len theo z, va xoay scan tho theo roll/pitch.
z: robotPose.z,
roll: robotPose.roll,
pitch: robotPose.pitch,
};
}
@@ -1307,7 +1335,7 @@ function draw3d() {
v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion });
}
if (V3D.mapMesh) V3D.mapMesh.visible = on('lyMap') && !!state.map;
if (on('lyPath')) v3dSetPath(state.path);
if (on('lyPath')) v3dSetPath(state.path, state.map && state.map.floor);
else if (V3D.pathLine) V3D.pathLine.visible = false;
v3dRender(cv3d, on('lyFollow'), split3d);

View File

@@ -425,6 +425,19 @@ function v3dSetPose(group, p) {
group.position.x = p.x;
group.position.z = -p.y;
group.rotation.y = p.yaw;
// Cao do va nghieng CHI khi pose mang chung -- hien chi ground truth cua sim
// (`gt.z/roll/pitch`). Pose uoc luong la 2D: KHONG dong vao y, de hop dong
// o tren van dung (test/www/test_robot_marker.js muc 4).
//
// Nhom NGOAI duoc dat cao do san (`z`), phep nang wheel_radius van o tang
// trong. Goc: ROS R = Rz(yaw) Ry(pitch) Rx(roll); three.js y-len, z = -y_ros
// -> Ry(yaw) Rz(-pitch) Rx(roll), tuc thu tu 'YZX'.
if (p.z !== undefined) group.position.y = p.z;
if (p.roll !== undefined || p.pitch !== undefined) {
group.rotation.order = 'YZX';
group.rotation.x = p.roll || 0;
group.rotation.z = -(p.pitch || 0);
}
}
// scan: mang [x0,y0, x1,y1, ...] trong frame LASER (xem ghi chu ben trong).
@@ -443,8 +456,16 @@ function v3dSetScan(arr, pose, r) {
const n = arr.length / 2;
const pos = new Float32Array(n * 3);
// Scan nam o do cao cua LiDAR, khong phai o san. Ve o san se lam nguoi xem
// tuong LiDAR thay duoc vat thap -- no KHONG thay.
const z = r.laser_z + r.wheel_radius;
// tuong LiDAR thay duoc vat thap -- no KHONG thay. Cong cao do san duoi
// robot (che do doc), khong thi o tang tren scan ve chui duoi san.
const z0 = pose.z || 0;
const zl = r.laser_z + r.wheel_radius; // goc LiDAR tren san, he footprint
// Web nhan scan THO: tia nam trong mat phang LiDAR, NGHIENG theo than robot.
// Tren doc 15 do ve phang thi diem cach 3 m lech ~0.8 m (chui vao mat doc)
// -> xoay theo roll/pitch quanh footprint, nhu v3dSetPose xoay hinh robot.
// ROS R = Rz(yaw) Ry(pitch) Rx(roll); khong co tilt thi y het cu.
const cr = Math.cos(pose.roll || 0), sr = Math.sin(pose.roll || 0);
const cp = Math.cos(pose.pitch || 0), sp = Math.sin(pose.pitch || 0);
// ⚠️ Scan den trong frame LASER, khong phai frame BASE.
//
// `laser_link` cach `base_link` 0.24 m ve phia truoc (robot.yaml). Dat thang
@@ -456,9 +477,12 @@ function v3dSetScan(arr, pose, r) {
const lx = r.laser_x || 0, ly = r.laser_y || 0;
for (let i = 0; i < n; ++i) {
const x = arr[i * 2] + lx, y = arr[i * 2 + 1] + ly;
pos[i * 3] = pose.x + c * x - s * y;
pos[i * 3 + 1] = z;
pos[i * 3 + 2] = -(pose.y + s * x + c * y);
// Rx(roll) roi Ry(pitch), trong he footprint (truoc khi quay yaw).
const y1 = y * cr - zl * sr, z1 = y * sr + zl * cr;
const x2 = x * cp + z1 * sp, z2 = -x * sp + z1 * cp;
pos[i * 3] = pose.x + c * x2 - s * y1;
pos[i * 3 + 1] = z0 + z2;
pos[i * 3 + 2] = -(pose.y + s * x2 + c * y1);
}
V3D.scanPts.geometry.dispose();
V3D.scanPts.geometry = new THREE.BufferGeometry();
@@ -480,10 +504,11 @@ function v3dSetCloud(arr, pose) {
const c = Math.cos(pose.yaw), s = Math.sin(pose.yaw);
const n = arr.length / 3;
const pos = new Float32Array(n * 3), col = new Float32Array(n * 3);
const z0 = pose.z || 0; // cao do san duoi robot (che do doc)
for (let i = 0; i < n; ++i) {
const x = arr[i * 3], y = arr[i * 3 + 1], z = arr[i * 3 + 2];
pos[i * 3] = pose.x + c * x - s * y;
pos[i * 3 + 1] = z;
pos[i * 3 + 1] = z0 + z;
pos[i * 3 + 2] = -(pose.y + s * x + c * y);
// To mau theo do cao, cung bang mau voi khung 2D.
const t = Math.max(0, Math.min(1, z / 1.2));
@@ -605,12 +630,22 @@ function v3dSetMapCloud(v, visible) {
// San dat o TOA DO THE GIOI chu khong theo robot. Dat theo robot la dung cai
// bay "sàn troi theo robot": robot dung yen giua man hinh con ca the gioi
// truot qua, trong y het loi dinh vi.
//
// ⚠️ Chi dung lai khi BAO the gioi doi. Chay tu `.world`, v3dSetWorld() goi
// ham nay MOI khung hinh (nhanh mesh that thoat som truoc khoa worldKey), va
// ban cu dung lai mat san + GridHelper moi khung ma khong giai phong cai cu.
// Do tren slope_test.world: geometry tren GPU tang ~1 moi khung (20 -> 203
// sau 183 khung), tuc ~3600/phut o 60 fps -- trinh duyet cham dan.
function v3dSetGround(grid) {
if (!V3D.ready || !grid) return;
const key = grid.w + 'x' + grid.h + '@' + grid.res + ':' + grid.ox + ',' + grid.oy;
if (V3D.groundKey === key && V3D.floorMesh) return;
V3D.groundKey = key;
const r = grid.res;
if (V3D.floorMesh) {
V3D.root.remove(V3D.floorMesh);
V3D.floorMesh.geometry.dispose();
V3D.floorMesh.material.dispose();
}
const fw = grid.w * r, fh = grid.h * r;
V3D.floorMesh = new THREE.Mesh(
@@ -627,7 +662,11 @@ function v3dSetGround(grid) {
const span = Math.max(fw, fh);
V3D.scene.fog.near = span * 0.35;
V3D.scene.fog.far = span * 1.4;
if (V3D.gridHelper) V3D.root.remove(V3D.gridHelper);
if (V3D.gridHelper) {
V3D.root.remove(V3D.gridHelper);
V3D.gridHelper.geometry.dispose();
V3D.gridHelper.material.dispose();
}
V3D.gridHelper = new THREE.GridHelper(Math.ceil(span), Math.ceil(span),
0x93a2b0, 0xa6b3c0);
V3D.root.add(V3D.gridHelper);
@@ -831,11 +870,69 @@ function v3dSetWorld(grid, wallHeight) {
v3dSetGround(grid);
}
// Ban do occupancy -> mot mat phang co texture, dat o san.
// --- Do cao SAN cua ban do (che do doc) ---
//
// Luoi tho (0.2 m, mm, -32768 = chua biet) di kem khung ban do SLAM. O chua
// biet (xa moi node > 4 m: tuong LiDAR thay tu xa) lay gia tri o DA BIET gan
// nhat -- de 0 thi mat phang tu tang tren cam xuong z = 0 thanh mot tam xien.
const FLOOR_UNKNOWN = -32768;
// Mat ban do uon dat CAO hon san uoc luong 4 cm. Trong khung gop, mesh san
// THAT cua world (doc, san) la mat duc trung cho voi no: thap hon du chi 2 mm
// la bi che, ngang nhau la nhap nhay rang cua -- chinh la "nen bi lung". Da do
// (sim, map 645 node): sai uoc - that p1 -2.3 cm, p50 +3.3 cm; nang 3 cm con
// 0.3% o chim, 4 cm con 0%. Robot that khong co mesh world: chi noi 4 cm.
const FLOOR_LIFT = 0.04;
function v3dFloorFill(fl) {
const n = fl.w * fl.h;
const out = new Int16Array(fl.mm);
const q = new Int32Array(n);
let head = 0, tail = 0;
for (let i = 0; i < n; ++i) if (out[i] !== FLOOR_UNKNOWN) q[tail++] = i;
if (tail === 0) return null;
while (head < tail) {
const i = q[head++], c = i % fl.w, r = (i - c) / fl.w;
const nb = [c > 0 ? i - 1 : -1, c + 1 < fl.w ? i + 1 : -1,
r > 0 ? i - fl.w : -1, r + 1 < fl.h ? i + fl.w : -1];
for (const j of nb) {
if (j >= 0 && out[j] === FLOOR_UNKNOWN) { out[j] = out[i]; q[tail++] = j; }
}
}
return { ...fl, mm: out };
}
// Do cao san (m) tai (x, y) ROS: noi suy song tuyen giua TAM 4 o quanh diem
// (dinh mat phang nam dung GOC o -- lay o gan nhat thi tren doc 15 do lech
// ~3 cm theo phia lam tron). null neu ngoai luoi / chua biet.
function v3dFloorAt(fl, x, y) {
if (!fl) return null;
const gx = (x - fl.ox) / fl.res - 0.5, gy = (y - fl.oy) / fl.res - 0.5;
const c0 = Math.floor(gx), r0 = Math.floor(gy);
const fx = gx - c0, fy = gy - r0;
let sw = 0, sz = 0;
for (let k = 0; k < 4; ++k) {
const c = c0 + (k & 1), r = r0 + (k >> 1);
if (c < 0 || r < 0 || c >= fl.w || r >= fl.h) continue;
const v = fl.mm[r * fl.w + c];
if (v === FLOOR_UNKNOWN) continue;
const wgt = ((k & 1) ? fx : 1 - fx) * ((k >> 1) ? fy : 1 - fy);
sw += wgt;
sz += wgt * v;
}
return sw > 1e-6 ? (sz / sw) * 0.001 : null;
}
// Ban do occupancy -> mot mat phang co texture, dat o san -- UON theo do cao
// san khi ban do co (che do doc): mat doc va san tang tren o dung cao do,
// khong nam bep o z = 0 duoi tuong voxel.
function v3dSetMap(map) {
if (!V3D.ready || !map || !map.w || !map.h) return;
if (V3D.mapKey === map.version) return;
V3D.mapKey = map.version;
// Khoa theo MANG O, khong theo so phien ban: khung JSON mang phien ban moi
// toi TRUOC khung ban do, nen khoa theo phien ban co the chot luoi CU voi
// phien ban MOI roi khong bao gio ve lai -- ma o che do dinh vi phien ban
// chi doi khi co lien ket moi.
if (V3D.mapData === map.data) return;
V3D.mapData = map.data;
const cv = document.createElement('canvas');
cv.width = map.w; cv.height = map.h;
@@ -867,23 +964,57 @@ function v3dSetMap(map) {
tex.magFilter = THREE.NearestFilter;
tex.minFilter = THREE.LinearMipmapLinearFilter;
if (V3D.mapMesh) { V3D.root.remove(V3D.mapMesh); V3D.mapMesh.geometry.dispose(); }
if (V3D.mapMesh) {
V3D.root.remove(V3D.mapMesh);
V3D.mapMesh.geometry.dispose();
if (V3D.mapMesh.material.map) V3D.mapMesh.material.map.dispose();
V3D.mapMesh.material.dispose();
}
const wM = map.w * map.res, hM = map.h * map.res;
const fl = map.floor ? v3dFloorFill(map.floor) : null;
let geom;
if (fl) {
// Mot dinh moi o luoi san, tran 256 doan moi chieu (ban do 100 m van
// chi ~66k dinh).
const sx = Math.max(1, Math.min(256, Math.round(wM / fl.res)));
const sy = Math.max(1, Math.min(256, Math.round(hM / fl.res)));
geom = new THREE.PlaneGeometry(wM, hM, sx, sy);
// Dinh cuc bo (x, y, z) -> sau rotation.x = -PI/2 la ROS (x, y, z) quanh
// tam mat phang: cuc bo +y = ROS +y, cuc bo +z = LEN.
const p = geom.attributes.position;
for (let i = 0; i < p.count; ++i) {
const z = v3dFloorAt(fl, map.ox + wM / 2 + p.getX(i), map.oy + hM / 2 + p.getY(i));
p.setZ(i, z === null ? 0 : z);
}
p.needsUpdate = true;
} else {
geom = new THREE.PlaneGeometry(wM, hM);
}
V3D.mapMesh = new THREE.Mesh(
new THREE.PlaneGeometry(wM, hM),
geom,
new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false }));
V3D.mapMesh.rotation.x = -Math.PI / 2;
// Hoi thap hon san mot chut de khong z-fight voi luoi va vanh cliff.
V3D.mapMesh.position.set(map.ox + wM / 2, -0.002, -(map.oy + hM / 2));
// Phang: hoi thap hon san mot chut de khong z-fight voi luoi va vanh cliff.
// Uon: nang FLOOR_LIFT len tren mesh san that cua world (xem tren).
V3D.mapMesh.position.set(map.ox + wM / 2, fl ? FLOOR_LIFT : -0.002, -(map.oy + hM / 2));
V3D.mapHasFloor = !!fl;
V3D.root.add(V3D.mapMesh);
}
function v3dSetPath(pts) {
// `floor` (tuy chon): luoi do cao san cua ban do -- quy dao di theo mat doc /
// tang tren thay vi chui duoi san.
function v3dSetPath(pts, floor) {
if (!V3D.ready) return;
if (V3D.pathLine) { V3D.root.remove(V3D.pathLine); V3D.pathLine.geometry.dispose(); }
if (!pts || pts.length < 4) return;
// Quy dao luon nam sat node nen khong can lap o chua biet nhu v3dSetMap.
// Ve TREN mat ban do uon (nang FLOOR_LIFT), khong thi lop trong suot phu len
// lam quy dao mo di.
const v = [];
for (let i = 0; i + 1 < pts.length; i += 2) v.push(toScene(pts[i], pts[i + 1], 0.01));
for (let i = 0; i + 1 < pts.length; i += 2) {
const z = v3dFloorAt(floor, pts[i], pts[i + 1]);
v.push(toScene(pts[i], pts[i + 1], z === null ? 0.01 : z + FLOOR_LIFT + 0.01));
}
V3D.pathLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(v),
new THREE.LineBasicMaterial({ color: 0xffb300 }));
@@ -899,6 +1030,10 @@ function v3dSetPath(pts) {
function v3dSetWorldVisible(on) {
if (V3D.meshWorld) V3D.meshWorld.visible = on;
if (V3D.worldMesh) V3D.worldMesh.visible = on;
// Mat san the gioi (z = 0) o lai lam moc khi tat the gioi -- tru khi ban do
// co do cao san: luc do no nam duoi tang tren nhu mot san sai cho (xem nua
// SLAM trong v3dRender).
if (V3D.floorMesh) V3D.floorMesh.visible = on || !V3D.mapHasFloor;
}
// Dat khung nhin ve mot goc chuan.
@@ -976,17 +1111,21 @@ function v3dRender(canvas, follow, splitSlam) {
}
// Tam quay: bam theo robot neu bat, khong thi theo diem pan cua nguoi dung.
let cx = V3D.orbit.tx, cz = V3D.orbit.ty;
// Bam ca CAO DO (che do doc): o tang tren 1.5 m ma tam quay van o san duoi
// thi camera xoay quanh mot diem chui duoi chan robot. Pose 2D (khong z)
// thi robotGroup o y = 0, y het cu.
let cx = V3D.orbit.tx, cz = V3D.orbit.ty, cy = 0;
if (follow && V3D.robotGroup) {
cx = V3D.robotGroup.position.x + V3D.orbit.tx;
cz = V3D.robotGroup.position.z + V3D.orbit.ty;
cy = V3D.robotGroup.position.y;
}
const o = V3D.orbit;
V3D.camera.position.set(
cx + o.dist * Math.cos(o.el) * Math.cos(o.az),
o.dist * Math.sin(o.el),
cy + o.dist * Math.sin(o.el),
cz + o.dist * Math.cos(o.el) * Math.sin(o.az));
V3D.camera.lookAt(cx, 0.2, cz);
V3D.camera.lookAt(cx, cy + 0.2, cz);
const r = V3D.renderer;
if (!splitSlam) {
@@ -1025,7 +1164,10 @@ function v3dRender(canvas, follow, splitSlam) {
show(hid);
// --- Nua PHAI: chi SLAM, khong co the gioi ---
hid = hide([V3D.meshWorld, V3D.worldMesh]);
// Ban do co do cao san (che do doc) thi an ca mat san THE GIOI (z = 0, tu
// v3dSetGround): duoi tang tren 1.5 m no hien qua lop ban do trong suot
// nhu mot "san" sai cho -- SLAM da tu mang mat san cua no.
hid = hide([V3D.meshWorld, V3D.worldMesh, V3D.mapHasFloor ? V3D.floorMesh : null]);
r.setViewport(half, 0, w - half, h);
r.setScissor(half, 0, w - half, h);
r.render(V3D.scene, V3D.camera);

View File

@@ -73,6 +73,9 @@
<!-- Ground truth chi co khi mo phong. Sai so la thuoc do duy nhat
cho biet uoc luong dang tot hay te. -->
<tr><td>sai so</td><td id="gtErr">--</td></tr>
<!-- Do cao san that (mo phong co doc). Uoc luong chua co z. -->
<tr><td>z uoc luong</td><td id="estZ">--</td></tr>
<tr><td>z that</td><td id="gtZ">--</td></tr>
</table>
</section>

View File

@@ -0,0 +1,842 @@
# Tuong va cot cua world doc. Z-UP, met.
# Sinh boi tools/gen_slope_world.py -- dung sua tay.
v -0.2000 -0.2000 4.0000
vt -0.2000 -0.2000
v 0.0000 -0.2000 4.0000
vt 0.0000 -0.2000
v 0.0000 33.7000 4.0000
vt 0.0000 33.7000
v -0.2000 33.7000 4.0000
vt -0.2000 33.7000
f 1/1 2/2 3/3
f 1/1 3/3 4/4
v -0.2000 33.7000 0.0000
vt -0.2000 33.7000
v 0.0000 33.7000 0.0000
vt 0.0000 33.7000
v 0.0000 -0.2000 0.0000
vt 0.0000 -0.2000
v -0.2000 -0.2000 0.0000
vt -0.2000 -0.2000
f 5/5 6/6 7/7
f 5/5 7/7 8/8
v -0.2000 -0.2000 0.0000
vt -0.2000 0.0000
v 0.0000 -0.2000 0.0000
vt 0.0000 0.0000
v 0.0000 -0.2000 4.0000
vt 0.0000 4.0000
v -0.2000 -0.2000 4.0000
vt -0.2000 4.0000
f 9/9 10/10 11/11
f 9/9 11/11 12/12
v 0.0000 33.7000 0.0000
vt 0.0000 0.0000
v -0.2000 33.7000 0.0000
vt -0.2000 0.0000
v -0.2000 33.7000 4.0000
vt -0.2000 4.0000
v 0.0000 33.7000 4.0000
vt 0.0000 4.0000
f 13/13 14/14 15/15
f 13/13 15/15 16/16
v -0.2000 33.7000 0.0000
vt 33.7000 0.0000
v -0.2000 -0.2000 0.0000
vt -0.2000 0.0000
v -0.2000 -0.2000 4.0000
vt -0.2000 4.0000
v -0.2000 33.7000 4.0000
vt 33.7000 4.0000
f 17/17 18/18 19/19
f 17/17 19/19 20/20
v 0.0000 -0.2000 0.0000
vt -0.2000 0.0000
v 0.0000 33.7000 0.0000
vt 33.7000 0.0000
v 0.0000 33.7000 4.0000
vt 33.7000 4.0000
v 0.0000 -0.2000 4.0000
vt -0.2000 4.0000
f 21/21 22/22 23/23
f 21/21 23/23 24/24
v 12.8000 -0.2000 4.0000
vt 12.8000 -0.2000
v 13.0000 -0.2000 4.0000
vt 13.0000 -0.2000
v 13.0000 33.7000 4.0000
vt 13.0000 33.7000
v 12.8000 33.7000 4.0000
vt 12.8000 33.7000
f 25/25 26/26 27/27
f 25/25 27/27 28/28
v 12.8000 33.7000 0.0000
vt 12.8000 33.7000
v 13.0000 33.7000 0.0000
vt 13.0000 33.7000
v 13.0000 -0.2000 0.0000
vt 13.0000 -0.2000
v 12.8000 -0.2000 0.0000
vt 12.8000 -0.2000
f 29/29 30/30 31/31
f 29/29 31/31 32/32
v 12.8000 -0.2000 0.0000
vt 12.8000 0.0000
v 13.0000 -0.2000 0.0000
vt 13.0000 0.0000
v 13.0000 -0.2000 4.0000
vt 13.0000 4.0000
v 12.8000 -0.2000 4.0000
vt 12.8000 4.0000
f 33/33 34/34 35/35
f 33/33 35/35 36/36
v 13.0000 33.7000 0.0000
vt 13.0000 0.0000
v 12.8000 33.7000 0.0000
vt 12.8000 0.0000
v 12.8000 33.7000 4.0000
vt 12.8000 4.0000
v 13.0000 33.7000 4.0000
vt 13.0000 4.0000
f 37/37 38/38 39/39
f 37/37 39/39 40/40
v 12.8000 33.7000 0.0000
vt 33.7000 0.0000
v 12.8000 -0.2000 0.0000
vt -0.2000 0.0000
v 12.8000 -0.2000 4.0000
vt -0.2000 4.0000
v 12.8000 33.7000 4.0000
vt 33.7000 4.0000
f 41/41 42/42 43/43
f 41/41 43/43 44/44
v 13.0000 -0.2000 0.0000
vt -0.2000 0.0000
v 13.0000 33.7000 0.0000
vt 33.7000 0.0000
v 13.0000 33.7000 4.0000
vt 33.7000 4.0000
v 13.0000 -0.2000 4.0000
vt -0.2000 4.0000
f 45/45 46/46 47/47
f 45/45 47/47 48/48
v -0.2000 -0.2000 4.0000
vt -0.2000 -0.2000
v 13.0000 -0.2000 4.0000
vt 13.0000 -0.2000
v 13.0000 0.0000 4.0000
vt 13.0000 0.0000
v -0.2000 0.0000 4.0000
vt -0.2000 0.0000
f 49/49 50/50 51/51
f 49/49 51/51 52/52
v -0.2000 0.0000 0.0000
vt -0.2000 0.0000
v 13.0000 0.0000 0.0000
vt 13.0000 0.0000
v 13.0000 -0.2000 0.0000
vt 13.0000 -0.2000
v -0.2000 -0.2000 0.0000
vt -0.2000 -0.2000
f 53/53 54/54 55/55
f 53/53 55/55 56/56
v -0.2000 -0.2000 0.0000
vt -0.2000 0.0000
v 13.0000 -0.2000 0.0000
vt 13.0000 0.0000
v 13.0000 -0.2000 4.0000
vt 13.0000 4.0000
v -0.2000 -0.2000 4.0000
vt -0.2000 4.0000
f 57/57 58/58 59/59
f 57/57 59/59 60/60
v 13.0000 0.0000 0.0000
vt 13.0000 0.0000
v -0.2000 0.0000 0.0000
vt -0.2000 0.0000
v -0.2000 0.0000 4.0000
vt -0.2000 4.0000
v 13.0000 0.0000 4.0000
vt 13.0000 4.0000
f 61/61 62/62 63/63
f 61/61 63/63 64/64
v -0.2000 0.0000 0.0000
vt 0.0000 0.0000
v -0.2000 -0.2000 0.0000
vt -0.2000 0.0000
v -0.2000 -0.2000 4.0000
vt -0.2000 4.0000
v -0.2000 0.0000 4.0000
vt 0.0000 4.0000
f 65/65 66/66 67/67
f 65/65 67/67 68/68
v 13.0000 -0.2000 0.0000
vt -0.2000 0.0000
v 13.0000 0.0000 0.0000
vt 0.0000 0.0000
v 13.0000 0.0000 4.0000
vt 0.0000 4.0000
v 13.0000 -0.2000 4.0000
vt -0.2000 4.0000
f 69/69 70/70 71/71
f 69/69 71/71 72/72
v -0.2000 33.5000 4.0000
vt -0.2000 33.5000
v 13.0000 33.5000 4.0000
vt 13.0000 33.5000
v 13.0000 33.7000 4.0000
vt 13.0000 33.7000
v -0.2000 33.7000 4.0000
vt -0.2000 33.7000
f 73/73 74/74 75/75
f 73/73 75/75 76/76
v -0.2000 33.7000 0.0000
vt -0.2000 33.7000
v 13.0000 33.7000 0.0000
vt 13.0000 33.7000
v 13.0000 33.5000 0.0000
vt 13.0000 33.5000
v -0.2000 33.5000 0.0000
vt -0.2000 33.5000
f 77/77 78/78 79/79
f 77/77 79/79 80/80
v -0.2000 33.5000 0.0000
vt -0.2000 0.0000
v 13.0000 33.5000 0.0000
vt 13.0000 0.0000
v 13.0000 33.5000 4.0000
vt 13.0000 4.0000
v -0.2000 33.5000 4.0000
vt -0.2000 4.0000
f 81/81 82/82 83/83
f 81/81 83/83 84/84
v 13.0000 33.7000 0.0000
vt 13.0000 0.0000
v -0.2000 33.7000 0.0000
vt -0.2000 0.0000
v -0.2000 33.7000 4.0000
vt -0.2000 4.0000
v 13.0000 33.7000 4.0000
vt 13.0000 4.0000
f 85/85 86/86 87/87
f 85/85 87/87 88/88
v -0.2000 33.7000 0.0000
vt 33.7000 0.0000
v -0.2000 33.5000 0.0000
vt 33.5000 0.0000
v -0.2000 33.5000 4.0000
vt 33.5000 4.0000
v -0.2000 33.7000 4.0000
vt 33.7000 4.0000
f 89/89 90/90 91/91
f 89/89 91/91 92/92
v 13.0000 33.5000 0.0000
vt 33.5000 0.0000
v 13.0000 33.7000 0.0000
vt 33.7000 0.0000
v 13.0000 33.7000 4.0000
vt 33.7000 4.0000
v 13.0000 33.5000 4.0000
vt 33.5000 4.0000
f 93/93 94/94 95/95
f 93/93 95/95 96/96
v 2.4000 8.0000 4.0000
vt 2.4000 8.0000
v 2.6000 8.0000 4.0000
vt 2.6000 8.0000
v 2.6000 25.5000 4.0000
vt 2.6000 25.5000
v 2.4000 25.5000 4.0000
vt 2.4000 25.5000
f 97/97 98/98 99/99
f 97/97 99/99 100/100
v 2.4000 25.5000 0.0000
vt 2.4000 25.5000
v 2.6000 25.5000 0.0000
vt 2.6000 25.5000
v 2.6000 8.0000 0.0000
vt 2.6000 8.0000
v 2.4000 8.0000 0.0000
vt 2.4000 8.0000
f 101/101 102/102 103/103
f 101/101 103/103 104/104
v 2.4000 8.0000 0.0000
vt 2.4000 0.0000
v 2.6000 8.0000 0.0000
vt 2.6000 0.0000
v 2.6000 8.0000 4.0000
vt 2.6000 4.0000
v 2.4000 8.0000 4.0000
vt 2.4000 4.0000
f 105/105 106/106 107/107
f 105/105 107/107 108/108
v 2.6000 25.5000 0.0000
vt 2.6000 0.0000
v 2.4000 25.5000 0.0000
vt 2.4000 0.0000
v 2.4000 25.5000 4.0000
vt 2.4000 4.0000
v 2.6000 25.5000 4.0000
vt 2.6000 4.0000
f 109/109 110/110 111/111
f 109/109 111/111 112/112
v 2.4000 25.5000 0.0000
vt 25.5000 0.0000
v 2.4000 8.0000 0.0000
vt 8.0000 0.0000
v 2.4000 8.0000 4.0000
vt 8.0000 4.0000
v 2.4000 25.5000 4.0000
vt 25.5000 4.0000
f 113/113 114/114 115/115
f 113/113 115/115 116/116
v 2.6000 8.0000 0.0000
vt 8.0000 0.0000
v 2.6000 25.5000 0.0000
vt 25.5000 0.0000
v 2.6000 25.5000 4.0000
vt 25.5000 4.0000
v 2.6000 8.0000 4.0000
vt 8.0000 4.0000
f 117/117 118/118 119/119
f 117/117 119/119 120/120
v 5.0000 8.0000 4.0000
vt 5.0000 8.0000
v 5.2000 8.0000 4.0000
vt 5.2000 8.0000
v 5.2000 25.5000 4.0000
vt 5.2000 25.5000
v 5.0000 25.5000 4.0000
vt 5.0000 25.5000
f 121/121 122/122 123/123
f 121/121 123/123 124/124
v 5.0000 25.5000 0.0000
vt 5.0000 25.5000
v 5.2000 25.5000 0.0000
vt 5.2000 25.5000
v 5.2000 8.0000 0.0000
vt 5.2000 8.0000
v 5.0000 8.0000 0.0000
vt 5.0000 8.0000
f 125/125 126/126 127/127
f 125/125 127/127 128/128
v 5.0000 8.0000 0.0000
vt 5.0000 0.0000
v 5.2000 8.0000 0.0000
vt 5.2000 0.0000
v 5.2000 8.0000 4.0000
vt 5.2000 4.0000
v 5.0000 8.0000 4.0000
vt 5.0000 4.0000
f 129/129 130/130 131/131
f 129/129 131/131 132/132
v 5.2000 25.5000 0.0000
vt 5.2000 0.0000
v 5.0000 25.5000 0.0000
vt 5.0000 0.0000
v 5.0000 25.5000 4.0000
vt 5.0000 4.0000
v 5.2000 25.5000 4.0000
vt 5.2000 4.0000
f 133/133 134/134 135/135
f 133/133 135/135 136/136
v 5.0000 25.5000 0.0000
vt 25.5000 0.0000
v 5.0000 8.0000 0.0000
vt 8.0000 0.0000
v 5.0000 8.0000 4.0000
vt 8.0000 4.0000
v 5.0000 25.5000 4.0000
vt 25.5000 4.0000
f 137/137 138/138 139/139
f 137/137 139/139 140/140
v 5.2000 8.0000 0.0000
vt 8.0000 0.0000
v 5.2000 25.5000 0.0000
vt 25.5000 0.0000
v 5.2000 25.5000 4.0000
vt 25.5000 4.0000
v 5.2000 8.0000 4.0000
vt 8.0000 4.0000
f 141/141 142/142 143/143
f 141/141 143/143 144/144
v 7.6000 8.0000 4.0000
vt 7.6000 8.0000
v 7.8000 8.0000 4.0000
vt 7.8000 8.0000
v 7.8000 25.5000 4.0000
vt 7.8000 25.5000
v 7.6000 25.5000 4.0000
vt 7.6000 25.5000
f 145/145 146/146 147/147
f 145/145 147/147 148/148
v 7.6000 25.5000 0.0000
vt 7.6000 25.5000
v 7.8000 25.5000 0.0000
vt 7.8000 25.5000
v 7.8000 8.0000 0.0000
vt 7.8000 8.0000
v 7.6000 8.0000 0.0000
vt 7.6000 8.0000
f 149/149 150/150 151/151
f 149/149 151/151 152/152
v 7.6000 8.0000 0.0000
vt 7.6000 0.0000
v 7.8000 8.0000 0.0000
vt 7.8000 0.0000
v 7.8000 8.0000 4.0000
vt 7.8000 4.0000
v 7.6000 8.0000 4.0000
vt 7.6000 4.0000
f 153/153 154/154 155/155
f 153/153 155/155 156/156
v 7.8000 25.5000 0.0000
vt 7.8000 0.0000
v 7.6000 25.5000 0.0000
vt 7.6000 0.0000
v 7.6000 25.5000 4.0000
vt 7.6000 4.0000
v 7.8000 25.5000 4.0000
vt 7.8000 4.0000
f 157/157 158/158 159/159
f 157/157 159/159 160/160
v 7.6000 25.5000 0.0000
vt 25.5000 0.0000
v 7.6000 8.0000 0.0000
vt 8.0000 0.0000
v 7.6000 8.0000 4.0000
vt 8.0000 4.0000
v 7.6000 25.5000 4.0000
vt 25.5000 4.0000
f 161/161 162/162 163/163
f 161/161 163/163 164/164
v 7.8000 8.0000 0.0000
vt 8.0000 0.0000
v 7.8000 25.5000 0.0000
vt 25.5000 0.0000
v 7.8000 25.5000 4.0000
vt 25.5000 4.0000
v 7.8000 8.0000 4.0000
vt 8.0000 4.0000
f 165/165 166/166 167/167
f 165/165 167/167 168/168
v 10.2000 8.0000 4.0000
vt 10.2000 8.0000
v 10.4000 8.0000 4.0000
vt 10.4000 8.0000
v 10.4000 25.5000 4.0000
vt 10.4000 25.5000
v 10.2000 25.5000 4.0000
vt 10.2000 25.5000
f 169/169 170/170 171/171
f 169/169 171/171 172/172
v 10.2000 25.5000 0.0000
vt 10.2000 25.5000
v 10.4000 25.5000 0.0000
vt 10.4000 25.5000
v 10.4000 8.0000 0.0000
vt 10.4000 8.0000
v 10.2000 8.0000 0.0000
vt 10.2000 8.0000
f 173/173 174/174 175/175
f 173/173 175/175 176/176
v 10.2000 8.0000 0.0000
vt 10.2000 0.0000
v 10.4000 8.0000 0.0000
vt 10.4000 0.0000
v 10.4000 8.0000 4.0000
vt 10.4000 4.0000
v 10.2000 8.0000 4.0000
vt 10.2000 4.0000
f 177/177 178/178 179/179
f 177/177 179/179 180/180
v 10.4000 25.5000 0.0000
vt 10.4000 0.0000
v 10.2000 25.5000 0.0000
vt 10.2000 0.0000
v 10.2000 25.5000 4.0000
vt 10.2000 4.0000
v 10.4000 25.5000 4.0000
vt 10.4000 4.0000
f 181/181 182/182 183/183
f 181/181 183/183 184/184
v 10.2000 25.5000 0.0000
vt 25.5000 0.0000
v 10.2000 8.0000 0.0000
vt 8.0000 0.0000
v 10.2000 8.0000 4.0000
vt 8.0000 4.0000
v 10.2000 25.5000 4.0000
vt 25.5000 4.0000
f 185/185 186/186 187/187
f 185/185 187/187 188/188
v 10.4000 8.0000 0.0000
vt 8.0000 0.0000
v 10.4000 25.5000 0.0000
vt 25.5000 0.0000
v 10.4000 25.5000 4.0000
vt 25.5000 4.0000
v 10.4000 8.0000 4.0000
vt 8.0000 4.0000
f 189/189 190/190 191/191
f 189/189 191/191 192/192
v 2.3000 3.8000 4.0000
vt 2.3000 3.8000
v 2.7000 3.8000 4.0000
vt 2.7000 3.8000
v 2.7000 4.2000 4.0000
vt 2.7000 4.2000
v 2.3000 4.2000 4.0000
vt 2.3000 4.2000
f 193/193 194/194 195/195
f 193/193 195/195 196/196
v 2.3000 4.2000 0.0000
vt 2.3000 4.2000
v 2.7000 4.2000 0.0000
vt 2.7000 4.2000
v 2.7000 3.8000 0.0000
vt 2.7000 3.8000
v 2.3000 3.8000 0.0000
vt 2.3000 3.8000
f 197/197 198/198 199/199
f 197/197 199/199 200/200
v 2.3000 3.8000 0.0000
vt 2.3000 0.0000
v 2.7000 3.8000 0.0000
vt 2.7000 0.0000
v 2.7000 3.8000 4.0000
vt 2.7000 4.0000
v 2.3000 3.8000 4.0000
vt 2.3000 4.0000
f 201/201 202/202 203/203
f 201/201 203/203 204/204
v 2.7000 4.2000 0.0000
vt 2.7000 0.0000
v 2.3000 4.2000 0.0000
vt 2.3000 0.0000
v 2.3000 4.2000 4.0000
vt 2.3000 4.0000
v 2.7000 4.2000 4.0000
vt 2.7000 4.0000
f 205/205 206/206 207/207
f 205/205 207/207 208/208
v 2.3000 4.2000 0.0000
vt 4.2000 0.0000
v 2.3000 3.8000 0.0000
vt 3.8000 0.0000
v 2.3000 3.8000 4.0000
vt 3.8000 4.0000
v 2.3000 4.2000 4.0000
vt 4.2000 4.0000
f 209/209 210/210 211/211
f 209/209 211/211 212/212
v 2.7000 3.8000 0.0000
vt 3.8000 0.0000
v 2.7000 4.2000 0.0000
vt 4.2000 0.0000
v 2.7000 4.2000 4.0000
vt 4.2000 4.0000
v 2.7000 3.8000 4.0000
vt 3.8000 4.0000
f 213/213 214/214 215/215
f 213/213 215/215 216/216
v 10.1000 3.8000 4.0000
vt 10.1000 3.8000
v 10.5000 3.8000 4.0000
vt 10.5000 3.8000
v 10.5000 4.2000 4.0000
vt 10.5000 4.2000
v 10.1000 4.2000 4.0000
vt 10.1000 4.2000
f 217/217 218/218 219/219
f 217/217 219/219 220/220
v 10.1000 4.2000 0.0000
vt 10.1000 4.2000
v 10.5000 4.2000 0.0000
vt 10.5000 4.2000
v 10.5000 3.8000 0.0000
vt 10.5000 3.8000
v 10.1000 3.8000 0.0000
vt 10.1000 3.8000
f 221/221 222/222 223/223
f 221/221 223/223 224/224
v 10.1000 3.8000 0.0000
vt 10.1000 0.0000
v 10.5000 3.8000 0.0000
vt 10.5000 0.0000
v 10.5000 3.8000 4.0000
vt 10.5000 4.0000
v 10.1000 3.8000 4.0000
vt 10.1000 4.0000
f 225/225 226/226 227/227
f 225/225 227/227 228/228
v 10.5000 4.2000 0.0000
vt 10.5000 0.0000
v 10.1000 4.2000 0.0000
vt 10.1000 0.0000
v 10.1000 4.2000 4.0000
vt 10.1000 4.0000
v 10.5000 4.2000 4.0000
vt 10.5000 4.0000
f 229/229 230/230 231/231
f 229/229 231/231 232/232
v 10.1000 4.2000 0.0000
vt 4.2000 0.0000
v 10.1000 3.8000 0.0000
vt 3.8000 0.0000
v 10.1000 3.8000 4.0000
vt 3.8000 4.0000
v 10.1000 4.2000 4.0000
vt 4.2000 4.0000
f 233/233 234/234 235/235
f 233/233 235/235 236/236
v 10.5000 3.8000 0.0000
vt 3.8000 0.0000
v 10.5000 4.2000 0.0000
vt 4.2000 0.0000
v 10.5000 4.2000 4.0000
vt 4.2000 4.0000
v 10.5000 3.8000 4.0000
vt 3.8000 4.0000
f 237/237 238/238 239/239
f 237/237 239/239 240/240
v 4.6000 5.0000 4.0000
vt 4.6000 5.0000
v 5.6000 5.0000 4.0000
vt 5.6000 5.0000
v 5.6000 5.2000 4.0000
vt 5.6000 5.2000
v 4.6000 5.2000 4.0000
vt 4.6000 5.2000
f 241/241 242/242 243/243
f 241/241 243/243 244/244
v 4.6000 5.2000 0.0000
vt 4.6000 5.2000
v 5.6000 5.2000 0.0000
vt 5.6000 5.2000
v 5.6000 5.0000 0.0000
vt 5.6000 5.0000
v 4.6000 5.0000 0.0000
vt 4.6000 5.0000
f 245/245 246/246 247/247
f 245/245 247/247 248/248
v 4.6000 5.0000 0.0000
vt 4.6000 0.0000
v 5.6000 5.0000 0.0000
vt 5.6000 0.0000
v 5.6000 5.0000 4.0000
vt 5.6000 4.0000
v 4.6000 5.0000 4.0000
vt 4.6000 4.0000
f 249/249 250/250 251/251
f 249/249 251/251 252/252
v 5.6000 5.2000 0.0000
vt 5.6000 0.0000
v 4.6000 5.2000 0.0000
vt 4.6000 0.0000
v 4.6000 5.2000 4.0000
vt 4.6000 4.0000
v 5.6000 5.2000 4.0000
vt 5.6000 4.0000
f 253/253 254/254 255/255
f 253/253 255/255 256/256
v 4.6000 5.2000 0.0000
vt 5.2000 0.0000
v 4.6000 5.0000 0.0000
vt 5.0000 0.0000
v 4.6000 5.0000 4.0000
vt 5.0000 4.0000
v 4.6000 5.2000 4.0000
vt 5.2000 4.0000
f 257/257 258/258 259/259
f 257/257 259/259 260/260
v 5.6000 5.0000 0.0000
vt 5.0000 0.0000
v 5.6000 5.2000 0.0000
vt 5.2000 0.0000
v 5.6000 5.2000 4.0000
vt 5.2000 4.0000
v 5.6000 5.0000 4.0000
vt 5.0000 4.0000
f 261/261 262/262 263/263
f 261/261 263/263 264/264
v 4.9000 29.3000 4.0000
vt 4.9000 29.3000
v 5.3000 29.3000 4.0000
vt 5.3000 29.3000
v 5.3000 29.7000 4.0000
vt 5.3000 29.7000
v 4.9000 29.7000 4.0000
vt 4.9000 29.7000
f 265/265 266/266 267/267
f 265/265 267/267 268/268
v 4.9000 29.7000 1.5000
vt 4.9000 29.7000
v 5.3000 29.7000 1.5000
vt 5.3000 29.7000
v 5.3000 29.3000 1.5000
vt 5.3000 29.3000
v 4.9000 29.3000 1.5000
vt 4.9000 29.3000
f 269/269 270/270 271/271
f 269/269 271/271 272/272
v 4.9000 29.3000 1.5000
vt 4.9000 1.5000
v 5.3000 29.3000 1.5000
vt 5.3000 1.5000
v 5.3000 29.3000 4.0000
vt 5.3000 4.0000
v 4.9000 29.3000 4.0000
vt 4.9000 4.0000
f 273/273 274/274 275/275
f 273/273 275/275 276/276
v 5.3000 29.7000 1.5000
vt 5.3000 1.5000
v 4.9000 29.7000 1.5000
vt 4.9000 1.5000
v 4.9000 29.7000 4.0000
vt 4.9000 4.0000
v 5.3000 29.7000 4.0000
vt 5.3000 4.0000
f 277/277 278/278 279/279
f 277/277 279/279 280/280
v 4.9000 29.7000 1.5000
vt 29.7000 1.5000
v 4.9000 29.3000 1.5000
vt 29.3000 1.5000
v 4.9000 29.3000 4.0000
vt 29.3000 4.0000
v 4.9000 29.7000 4.0000
vt 29.7000 4.0000
f 281/281 282/282 283/283
f 281/281 283/283 284/284
v 5.3000 29.3000 1.5000
vt 29.3000 1.5000
v 5.3000 29.7000 1.5000
vt 29.7000 1.5000
v 5.3000 29.7000 4.0000
vt 29.7000 4.0000
v 5.3000 29.3000 4.0000
vt 29.3000 4.0000
f 285/285 286/286 287/287
f 285/285 287/287 288/288
v 7.5000 29.3000 4.0000
vt 7.5000 29.3000
v 7.9000 29.3000 4.0000
vt 7.9000 29.3000
v 7.9000 29.7000 4.0000
vt 7.9000 29.7000
v 7.5000 29.7000 4.0000
vt 7.5000 29.7000
f 289/289 290/290 291/291
f 289/289 291/291 292/292
v 7.5000 29.7000 1.5000
vt 7.5000 29.7000
v 7.9000 29.7000 1.5000
vt 7.9000 29.7000
v 7.9000 29.3000 1.5000
vt 7.9000 29.3000
v 7.5000 29.3000 1.5000
vt 7.5000 29.3000
f 293/293 294/294 295/295
f 293/293 295/295 296/296
v 7.5000 29.3000 1.5000
vt 7.5000 1.5000
v 7.9000 29.3000 1.5000
vt 7.9000 1.5000
v 7.9000 29.3000 4.0000
vt 7.9000 4.0000
v 7.5000 29.3000 4.0000
vt 7.5000 4.0000
f 297/297 298/298 299/299
f 297/297 299/299 300/300
v 7.9000 29.7000 1.5000
vt 7.9000 1.5000
v 7.5000 29.7000 1.5000
vt 7.5000 1.5000
v 7.5000 29.7000 4.0000
vt 7.5000 4.0000
v 7.9000 29.7000 4.0000
vt 7.9000 4.0000
f 301/301 302/302 303/303
f 301/301 303/303 304/304
v 7.5000 29.7000 1.5000
vt 29.7000 1.5000
v 7.5000 29.3000 1.5000
vt 29.3000 1.5000
v 7.5000 29.3000 4.0000
vt 29.3000 4.0000
v 7.5000 29.7000 4.0000
vt 29.7000 4.0000
f 305/305 306/306 307/307
f 305/305 307/307 308/308
v 7.9000 29.3000 1.5000
vt 29.3000 1.5000
v 7.9000 29.7000 1.5000
vt 29.7000 1.5000
v 7.9000 29.7000 4.0000
vt 29.7000 4.0000
v 7.9000 29.3000 4.0000
vt 29.3000 4.0000
f 309/309 310/310 311/311
f 309/309 311/311 312/312
v 9.7000 30.5000 4.0000
vt 9.7000 30.5000
v 10.9000 30.5000 4.0000
vt 10.9000 30.5000
v 10.9000 30.7000 4.0000
vt 10.9000 30.7000
v 9.7000 30.7000 4.0000
vt 9.7000 30.7000
f 313/313 314/314 315/315
f 313/313 315/315 316/316
v 9.7000 30.7000 1.5000
vt 9.7000 30.7000
v 10.9000 30.7000 1.5000
vt 10.9000 30.7000
v 10.9000 30.5000 1.5000
vt 10.9000 30.5000
v 9.7000 30.5000 1.5000
vt 9.7000 30.5000
f 317/317 318/318 319/319
f 317/317 319/319 320/320
v 9.7000 30.5000 1.5000
vt 9.7000 1.5000
v 10.9000 30.5000 1.5000
vt 10.9000 1.5000
v 10.9000 30.5000 4.0000
vt 10.9000 4.0000
v 9.7000 30.5000 4.0000
vt 9.7000 4.0000
f 321/321 322/322 323/323
f 321/321 323/323 324/324
v 10.9000 30.7000 1.5000
vt 10.9000 1.5000
v 9.7000 30.7000 1.5000
vt 9.7000 1.5000
v 9.7000 30.7000 4.0000
vt 9.7000 4.0000
v 10.9000 30.7000 4.0000
vt 10.9000 4.0000
f 325/325 326/326 327/327
f 325/325 327/327 328/328
v 9.7000 30.7000 1.5000
vt 30.7000 1.5000
v 9.7000 30.5000 1.5000
vt 30.5000 1.5000
v 9.7000 30.5000 4.0000
vt 30.5000 4.0000
v 9.7000 30.7000 4.0000
vt 30.7000 4.0000
f 329/329 330/330 331/331
f 329/329 331/331 332/332
v 10.9000 30.5000 1.5000
vt 30.5000 1.5000
v 10.9000 30.7000 1.5000
vt 30.7000 1.5000
v 10.9000 30.7000 4.0000
vt 30.7000 4.0000
v 10.9000 30.5000 4.0000
vt 30.5000 4.0000
f 333/333 334/334 335/335
f 333/333 335/335 336/336

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<model>
<name>vslam_slope_test_walls</name>
<version>1.0</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>vslam_cpp</name>
<email></email>
</author>
<description>
Tuong bao, tuong ngan lan va cot.
Sinh boi tools/gen_slope_world.py.
</description>
</model>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" ?>
<sdf version="1.6">
<model name="vslam_slope_test_walls">
<link name="link">
<visual name="visual">
<geometry>
<mesh>
<uri>model://vslam_slope_test_walls/meshes/walls.obj</uri>
</mesh>
</geometry>
</visual>
<collision name="collision">
<geometry>
<mesh>
<uri>model://vslam_slope_test_walls/meshes/walls.obj</uri>
</mesh>
</geometry>
</collision>
</link>
<static>1</static>
</model>
</sdf>

View File

@@ -0,0 +1,122 @@
# Dia hinh world doc: san duoi z=0, san tren z=1.50, 5 lan doc.
# Z-UP, met. Sinh boi tools/gen_slope_world.py -- dung sua tay.
v 0.0000 0.0000 0.0000
vt 0.0000 0.0000
v 12.8000 0.0000 0.0000
vt 12.8000 0.0000
v 12.8000 8.0000 0.0000
vt 12.8000 8.0000
v 0.0000 8.0000 0.0000
vt 0.0000 8.0000
f 1/1 2/2 3/3
f 1/1 3/3 4/4
v 0.0000 25.5000 1.5000
vt 0.0000 25.5000
v 12.8000 25.5000 1.5000
vt 12.8000 25.5000
v 12.8000 33.5000 1.5000
vt 12.8000 33.5000
v 0.0000 33.5000 1.5000
vt 0.0000 33.5000
f 5/5 6/6 7/7
f 5/5 7/7 8/8
v 0.0000 8.0000 0.0000
vt 0.0000 8.0000
v 2.4000 8.0000 0.0000
vt 2.4000 8.0000
v 2.4000 25.1451 1.5000
vt 2.4000 25.1451
v 0.0000 25.1451 1.5000
vt 0.0000 25.1451
f 9/9 10/10 11/11
f 9/9 11/11 12/12
v 0.0000 25.1451 1.5000
vt 0.0000 25.1451
v 2.4000 25.1451 1.5000
vt 2.4000 25.1451
v 2.4000 25.5000 1.5000
vt 2.4000 25.5000
v 0.0000 25.5000 1.5000
vt 0.0000 25.5000
f 13/13 14/14 15/15
f 13/13 15/15 16/16
v 2.6000 8.0000 0.0000
vt 2.6000 8.0000
v 5.0000 8.0000 0.0000
vt 5.0000 8.0000
v 5.0000 16.5069 1.5000
vt 5.0000 16.5069
v 2.6000 16.5069 1.5000
vt 2.6000 16.5069
f 17/17 18/18 19/19
f 17/17 19/19 20/20
v 2.6000 16.5069 1.5000
vt 2.6000 16.5069
v 5.0000 16.5069 1.5000
vt 5.0000 16.5069
v 5.0000 25.5000 1.5000
vt 5.0000 25.5000
v 2.6000 25.5000 1.5000
vt 2.6000 25.5000
f 21/21 22/22 23/23
f 21/21 23/23 24/24
v 5.2000 8.0000 0.0000
vt 5.2000 8.0000
v 7.6000 8.0000 0.0000
vt 7.6000 8.0000
v 7.6000 13.5981 1.5000
vt 7.6000 13.5981
v 5.2000 13.5981 1.5000
vt 5.2000 13.5981
f 25/25 26/26 27/27
f 25/25 27/27 28/28
v 5.2000 13.5981 1.5000
vt 5.2000 13.5981
v 7.6000 13.5981 1.5000
vt 7.6000 13.5981
v 7.6000 25.5000 1.5000
vt 7.6000 25.5000
v 5.2000 25.5000 1.5000
vt 5.2000 25.5000
f 29/29 30/30 31/31
f 29/29 31/31 32/32
v 7.8000 8.0000 0.0000
vt 7.8000 8.0000
v 10.2000 8.0000 0.0000
vt 10.2000 8.0000
v 10.2000 12.1212 1.5000
vt 10.2000 12.1212
v 7.8000 12.1212 1.5000
vt 7.8000 12.1212
f 33/33 34/34 35/35
f 33/33 35/35 36/36
v 7.8000 12.1212 1.5000
vt 7.8000 12.1212
v 10.2000 12.1212 1.5000
vt 10.2000 12.1212
v 10.2000 25.5000 1.5000
vt 10.2000 25.5000
v 7.8000 25.5000 1.5000
vt 7.8000 25.5000
f 37/37 38/38 39/39
f 37/37 39/39 40/40
v 10.4000 8.0000 0.0000
vt 10.4000 8.0000
v 12.8000 8.0000 0.0000
vt 12.8000 8.0000
v 12.8000 10.5981 1.5000
vt 12.8000 10.5981
v 10.4000 10.5981 1.5000
vt 10.4000 10.5981
f 41/41 42/42 43/43
f 41/41 43/43 44/44
v 10.4000 10.5981 1.5000
vt 10.4000 10.5981
v 12.8000 10.5981 1.5000
vt 12.8000 10.5981
v 12.8000 25.5000 1.5000
vt 12.8000 25.5000
v 10.4000 25.5000 1.5000
vt 10.4000 25.5000
f 45/45 46/46 47/47
f 45/45 47/47 48/48

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<model>
<name>vslam_terrain_slope_test</name>
<version>1.0</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>vslam_cpp</name>
<email></email>
</author>
<description>
San, chieu nghi va 5 lan doc (dia hinh).
Sinh boi tools/gen_slope_world.py.
</description>
</model>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" ?>
<sdf version="1.6">
<model name="vslam_terrain_slope_test">
<link name="link">
<visual name="visual">
<geometry>
<mesh>
<uri>model://vslam_terrain_slope_test/meshes/terrain.obj</uri>
</mesh>
</geometry>
</visual>
<collision name="collision">
<geometry>
<mesh>
<uri>model://vslam_terrain_slope_test/meshes/terrain.obj</uri>
</mesh>
</geometry>
</collision>
</link>
<static>1</static>
</model>
</sdf>

View File

@@ -0,0 +1,95 @@
<?xml version="1.0" ?>
<!-- World co DOC cho mo phong dia hinh 3D. Sinh boi
tools/gen_slope_world.py -- dung sua tay.
Xuat phat goi y: --x 6.4 --y 4 --yaw 1.5708 (sanh duoi, nhin
vao lan 15 do). Lan doc theo x: 5 do o x = 1.2, 10 do o x = 3.8, 15 do o x = 6.4, 20 do o x = 9.0, 30 do o x = 11.6. -->
<sdf version="1.6">
<world name="slope_test">
<include><uri>model://ground_plane</uri></include>
<include><uri>model://sun</uri></include>
<model name="vslam_terrain_slope_test_1">
<include>
<uri>model://vslam_terrain_slope_test</uri>
<static>true</static>
<pose>0.000 0.000 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="vslam_slope_test_walls_1">
<include>
<uri>model://vslam_slope_test_walls</uri>
<static>true</static>
<pose>0.000 0.000 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="MetalCabinet_1">
<include>
<uri>model://MetalCabinet</uri>
<static>true</static>
<pose>0.600 1.000 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="StorageRack_1">
<include>
<uri>model://StorageRack</uri>
<static>true</static>
<pose>3.000 0.600 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="IVStand_1">
<include>
<uri>model://IVStand</uri>
<static>true</static>
<pose>5.100 1.000 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="PatientWheelChair_1">
<include>
<uri>model://PatientWheelChair</uri>
<static>true</static>
<pose>7.700 1.000 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="BedTable_1">
<include>
<uri>model://BedTable</uri>
<static>true</static>
<pose>9.500 0.800 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="VendingMachine_1">
<include>
<uri>model://VendingMachine</uri>
<static>true</static>
<pose>12.100 1.200 0.000 0 0 -1.5708</pose>
</include>
</model>
<model name="MetalCabinet_2">
<include>
<uri>model://MetalCabinet</uri>
<static>true</static>
<pose>0.600 32.600 1.500 0 0 0.0000</pose>
</include>
</model>
<model name="IVStand_2">
<include>
<uri>model://IVStand</uri>
<static>true</static>
<pose>5.100 32.800 1.500 0 0 0.0000</pose>
</include>
</model>
<model name="StorageRack_2">
<include>
<uri>model://StorageRack</uri>
<static>true</static>
<pose>6.400 32.900 1.500 0 0 3.1416</pose>
</include>
</model>
<model name="BedTable_2">
<include>
<uri>model://BedTable</uri>
<static>true</static>
<pose>11.800 32.600 1.500 0 0 0.0000</pose>
</include>
</model>
</world>
</sdf>

View File

@@ -52,6 +52,7 @@ endif()
if(VSLAM_BUILD_ODOMETRY)
vslam_add_test(test_wheel_odometry LIBS vslam_odometry vslam_common)
vslam_add_test(test_ekf_se2 LIBS vslam_odometry vslam_common)
vslam_add_test(test_height_estimator LIBS vslam_odometry vslam_common)
endif()
if(VSLAM_BUILD_SAFETY)
@@ -73,6 +74,7 @@ endif()
if(VSLAM_BUILD_PERCEPTION)
vslam_add_test(test_perception LIBS vslam_perception vslam_common)
vslam_add_test(test_scan_leveler LIBS vslam_perception vslam_common)
if(VSLAM_BUILD_SIM)
# Test TICH HOP sim -> perception. Khoa quy uoc Z-depth cua anh mo phong
# va bai "san phang thi khong duoc bao vuc" -- thu ma ban ROS chi kiem
@@ -87,6 +89,15 @@ if(VSLAM_BUILD_SIM)
# Doc `.world` cua Gazebo. Fixture rieng trong test/data/world -- KHONG can
# bo model 3 GB cua AWS, nen bai kiem nay chay duoc tren may sach.
vslam_add_test(test_gazebo_world LIBS vslam_sim vslam_drivers vslam_common)
# Dia hinh 3D: doc, san cao, robot di tren mat san, LiDAR tia 3D. Fixture
# test/data/world/ramp.world (mot doc 10 do).
vslam_add_test(test_sim_terrain LIBS vslam_sim vslam_drivers vslam_common)
# IMU mo phong (mo hinh dong hoc, phat thua, tre, bias) va su that 6-DoF.
vslam_add_test(test_sim_imu LIBS vslam_sim vslam_drivers vslam_common)
# Ve camera bang GPU (lib tuy chon). May khong co GPU thi cac bai SKIP.
if(TARGET vslam_sim_gl)
vslam_add_test(test_sim_gl LIBS vslam_sim_gl vslam_sim vslam_drivers vslam_common)
endif()
if(VSLAM_BUILD_ODOMETRY)
# Test TICH HOP: sim -> encoder -> wheel_odom -> EKF, do sai so so voi
# ground truth. Day la bai L2 cua repo cu viet lai khong ROS.
@@ -98,6 +109,7 @@ endif()
if(VSLAM_BUILD_SLAM)
vslam_add_test(test_slam LIBS vslam_slam vslam_common)
vslam_add_test(test_voxel_export LIBS vslam_slam vslam_common)
vslam_add_test(test_height_map LIBS vslam_slam vslam_common)
vslam_add_test(test_global_localizer LIBS vslam_slam vslam_common)
endif()
@@ -248,6 +260,15 @@ if(VSLAM_NODE_EXE AND TARGET vslam_world_export)
${CMAKE_CURRENT_SOURCE_DIR}/www/test_orbit_camera.js)
set_tests_properties(www_orbit_camera PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT")
# Do cao san (che do doc): khoi FLH1 sau RLE, mat phang ban do uon theo san,
# scan/cloud/quy dao nang theo z. Sai dau o phep doi truc -> doc nghieng
# nguoc, van ve duoc. Kem: mat san the gioi KHONG dung lai moi khung (ban
# cu ro ~1 geometry GPU moi khung khi chay tu `.world`).
add_test(NAME www_map_floor
COMMAND ${VSLAM_NODE_EXE}
${CMAKE_CURRENT_SOURCE_DIR}/www/test_map_floor.js)
set_tests_properties(www_map_floor PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT")
else()
message(STATUS "vslam: khong tim thay `node` -- bo qua bai kiem frontend")
endif()

View File

@@ -0,0 +1,22 @@
# cot 0.4 x 0.4 x 1.0 m, day o goc model. Dat tren san cao 1.5 m: z the gioi 1.5..2.5,
# NGOAI dai z tuyet doi [0.05, 1.2] cu nhung TRONG dai tinh tu san cuc bo.
v -0.200 -0.200 0.000
v 0.200 -0.200 0.000
v 0.200 0.200 0.000
v -0.200 0.200 0.000
v -0.200 -0.200 1.000
v 0.200 -0.200 1.000
v 0.200 0.200 1.000
v -0.200 0.200 1.000
f 1 2 3
f 1 3 4
f 5 6 7
f 5 7 8
f 1 2 6
f 1 6 5
f 3 4 8
f 3 8 7
f 2 3 7
f 2 7 6
f 4 1 5
f 4 5 8

View File

@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<sdf version="1.6"><model name="pillar_upper"><static>true</static><link name="l">
<visual name="visual"><geometry><mesh>
<uri>model://pillar_upper/meshes/pillar.obj</uri>
</mesh></geometry></visual>
<collision name="collision"><geometry><mesh>
<uri>model://pillar_upper/meshes/pillar.obj</uri>
</mesh></geometry></collision>
</link></model></sdf>

View File

@@ -0,0 +1,22 @@
# mat ban 0.8 x 0.6 x 0.05 m o do cao 0.70..0.75 m. Mat tren huong LEN nhung
# KHONG phai dia hinh: phai la vat can, va san duoi no van la 0.
v -0.400 -0.300 0.700
v 0.400 -0.300 0.700
v 0.400 0.300 0.700
v -0.400 0.300 0.700
v -0.400 -0.300 0.750
v 0.400 -0.300 0.750
v 0.400 0.300 0.750
v -0.400 0.300 0.750
f 1 2 3
f 1 3 4
f 5 6 7
f 5 7 8
f 1 2 6
f 1 6 5
f 3 4 8
f 3 8 7
f 2 3 7
f 2 7 6
f 4 1 5
f 4 5 8

View File

@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<sdf version="1.6"><model name="table_slab"><static>true</static><link name="l">
<visual name="visual"><geometry><mesh>
<uri>model://table_slab/meshes/slab.obj</uri>
</mesh></geometry></visual>
<collision name="collision"><geometry><mesh>
<uri>model://table_slab/meshes/slab.obj</uri>
</mesh></geometry></collision>
</link></model></sdf>

View File

@@ -0,0 +1,21 @@
# Fixture dia hinh: san duoi z=0 (x -4..0), doc 10 do len 1.5 m (x 0..8.5069),
# san tren z=1.5 (x 8.5069..12.5069). y -1.5..1.5. Z-UP, met. Ten model bat dau
# bang vslam_terrain_ nen bo mo phong coi day la SAN, khong phai vat can.
v -4.00000 -1.50000 0.00000
v 0.00000 -1.50000 0.00000
v 0.00000 1.50000 0.00000
v -4.00000 1.50000 0.00000
f 1 2 3
f 1 3 4
v 0.00000 -1.50000 0.00000
v 8.50692 -1.50000 1.50000
v 8.50692 1.50000 1.50000
v 0.00000 1.50000 0.00000
f 5 6 7
f 5 7 8
v 8.50692 -1.50000 1.50000
v 12.50692 -1.50000 1.50000
v 12.50692 1.50000 1.50000
v 8.50692 1.50000 1.50000
f 9 10 11
f 9 11 12

View File

@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<sdf version="1.6"><model name="vslam_terrain_ramp"><static>true</static><link name="l">
<visual name="visual"><geometry><mesh>
<uri>model://vslam_terrain_ramp/meshes/ramp.obj</uri>
</mesh></geometry></visual>
<collision name="collision"><geometry><mesh>
<uri>model://vslam_terrain_ramp/meshes/ramp.obj</uri>
</mesh></geometry></collision>
</link></model></sdf>

View File

@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<!-- Fixture dia hinh 3D: MOT doc 10 do noi san z = 0 voi san cao 1.5 m.
- vslam_terrain_ramp: dia hinh (ten bat dau bang vslam_terrain_) -> SAN.
- pillar_upper: cot dung TREN san cao (z 1.5..2.5). Dai z tuyet doi cu
[0.05, 1.2] se bo no; tinh tu san cuc bo thi no la vat can.
- table_slab: mat ban huong len o 0.70 m. Khong phai dia hinh -> vat can,
va robot khong duoc "leo" len no. -->
<sdf version="1.6"><world name="ramp">
<model name="vslam_terrain_ramp_1"><include>
<uri>model://vslam_terrain_ramp</uri><static>true</static>
<pose>0 0 0 0 0 0</pose>
</include></model>
<model name="pillar_upper_1"><include>
<uri>model://pillar_upper</uri><static>true</static>
<pose>10.5 0 1.5 0 0 0</pose>
</include></model>
<model name="table_slab_1"><include>
<uri>model://table_slab</uri><static>true</static>
<pose>-2.5 1.0 0 0 0 0</pose>
</include></model>
</world></sdf>

View File

@@ -129,6 +129,60 @@ TEST(BinaryCodec, MapFullNenTotTrenBanDoThua) {
EXPECT_EQ(out.data, m.data);
}
// Che do doc: khoi do cao san noi sau RLE. Phan luoi 2D phai giai y het khung
// khong co khoi (client cu bo qua duoi khung), va khoi giu dung tung o, ke ca
// o CHUA BIET va gia tri am (tang ham).
TEST(BinaryCodec, MapFullKhoiDoCaoSan) {
OccupancyGrid m;
m.width = 40;
m.height = 30;
m.resolution = 0.05f;
m.origin.position.x = -1.25;
m.origin.position.y = -2.5;
m.data.assign(static_cast<size_t>(m.width) * m.height, -1);
for (uint32_t x = 5; x < 35; ++x) m.data[10 * m.width + x] = 100;
MapFloorGrid f;
f.resolution = 0.2f;
f.width = 10;
f.height = 8;
f.origin_x = -1.25f;
f.origin_y = -2.5f;
f.mm.assign(80, kFloorUnknown);
f.mm[0] = 0;
f.mm[17] = 1500;
f.mm[79] = -320;
std::string plain, with_floor;
EncodeMapFull(m, UnixTime::fromSec(2.0), &plain);
EncodeMapFull(m, UnixTime::fromSec(2.0), &with_floor, BinaryType::kMapFull, &f);
ASSERT_EQ(with_floor.size(), plain.size() + 24 + 80 * 2);
EXPECT_EQ(with_floor.compare(0, plain.size(), plain), 0);
OccupancyGrid out;
MapFloorGrid fout;
ASSERT_TRUE(DecodeMapFull(with_floor, &out, &fout));
EXPECT_EQ(out.data, m.data);
EXPECT_EQ(fout.width, f.width);
EXPECT_EQ(fout.height, f.height);
EXPECT_NEAR(fout.resolution, f.resolution, 1e-6);
EXPECT_NEAR(fout.origin_x, f.origin_x, 1e-6);
EXPECT_NEAR(fout.origin_y, f.origin_y, 1e-6);
EXPECT_EQ(fout.mm, f.mm);
// Khung khong co khoi: luoi san tra ve rong, khong phai rac cua lan truoc.
ASSERT_TRUE(DecodeMapFull(plain, &out, &fout));
EXPECT_EQ(fout.width, 0u);
EXPECT_TRUE(fout.mm.empty());
// Kich thuoc sai (mm thieu o) -> khong ghi khoi, khung y het ban phang.
MapFloorGrid bad = f;
bad.mm.pop_back();
std::string with_bad;
EncodeMapFull(m, UnixTime::fromSec(2.0), &with_bad, BinaryType::kMapFull, &bad);
EXPECT_EQ(with_bad, plain);
}
// --- Ban do voxel 3D -------------------------------------------------------
namespace {

View File

@@ -261,6 +261,292 @@ TEST(GlobalLocalizer, PhongDoiXungQuay180ChanOCongHuong) {
EXPECT_EQ(Decide(m, 5, cfg), RelocVerdict::kAmbiguousYaw);
}
// --- Bang chung ngoai LiDAR (`admit`) -------------------------------------
//
// Tren doc, do nghieng IMU noi robot dang chuc bao nhieu, ve phia nao; ban do
// biet doc o dau. Hai test dau la hai ca LiDAR nhap nhang o tren -- bang chung
// ngoai phai PHAN XU dung. Hai test sau khoa phan an toan: khong bao gio day
// mot khop LiDAR kem ro len thang, va bang chung "cai gi cung duoc" khong lam
// lech nguoi thang.
TEST(GlobalLocalizer, BangChungNgoaiTachHaiPhongGiongHet) {
OccupancyGrid g = MakeGrid(24.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
AsymRoom(&g, 12.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
// Vd phong phai la san doc ma IMU do phang: robot KHONG the o do.
const RelocAdmit admit = [&](const Pose2D& T) { return Pose2DCompose(T, odom).x < 12.0; };
const RelocMatch m = GlobalMatch(f, pts, cfg, admit);
ASSERT_TRUE(m.ok);
EXPECT_TRUE(m.tilt_used);
EXPECT_FALSE(m.tilt_conflict);
EXPECT_GT(m.tilt_rejected, 0);
const Pose2D est = Pose2DCompose(m.map_from_odom, odom);
EXPECT_LT(std::hypot(est.x - truth.x, est.y - truth.y), 0.1);
EXPECT_LT(std::fabs(AngleDiff(est.theta, truth.theta)) * 180.0 / M_PI, 1.0);
EXPECT_EQ(Decide(m, cfg.min_cycles, cfg), RelocVerdict::kAccept)
<< "ty le " << m.ratio() << ", ty le huong " << m.ratio_yaw();
for (const RelocHypothesis& h : m.hyps) {
EXPECT_LT(Pose2DCompose(h.map_from_odom, odom).x, 12.0) << "gia thuyet bi loai van tra ve";
}
}
TEST(GlobalLocalizer, BangChungNgoaiChonHuongPhongDoiXung) {
// Phong doi xung quay 180 do: LiDAR khong biet huong (PhongDoiXungQuay180...).
// Bang chung chi nhan nua huong quanh `want` -> ra DUNG `want`, ca hai chieu:
// chinh bang chung quyet dinh, khong phai may rui.
OccupancyGrid g = MakeGrid(9.0, 6.0);
Room(&g, 0.5, 0.5, 8.5, 5.5);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth{4.5, 3.0, 0.3};
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
for (const double want : {truth.theta, truth.theta + M_PI}) {
const RelocAdmit admit = [&](const Pose2D& T) {
return std::fabs(AngleDiff(Pose2DCompose(T, odom).theta, want)) < M_PI / 2;
};
const RelocMatch m = GlobalMatch(f, pts, cfg, admit);
ASSERT_TRUE(m.ok);
const Pose2D est = Pose2DCompose(m.map_from_odom, odom);
EXPECT_LT(std::fabs(AngleDiff(est.theta, want)) * 180.0 / M_PI, 1.0) << "want " << want;
EXPECT_LT(std::hypot(est.x - truth.x, est.y - truth.y), 0.1);
EXPECT_GE(m.ratio_yaw(), cfg.min_ratio_yaw) << "doi thu huong (lat 180) chua bi loai";
EXPECT_NE(Decide(m, cfg.min_cycles, cfg), RelocVerdict::kAmbiguousYaw);
}
}
TEST(GlobalLocalizer, BangChungMauThuanLiDARChacThiGiuLiDAR) {
// Phong KHONG doi xung: LiDAR chac chan. Bang chung noi "khong the o do"
// (vd IMU hong) -- KHONG duoc day mot cho kem han len thang. Ket qua phai y
// het khi khong co bang chung, va danh dau xung dot.
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
const RelocMatch base = GlobalMatch(f, pts, cfg);
const RelocAdmit admit = [&](const Pose2D& T) {
const Pose2D p = Pose2DCompose(T, odom);
return std::hypot(p.x - truth.x, p.y - truth.y) > 1.5;
};
const RelocMatch m = GlobalMatch(f, pts, cfg, admit);
ASSERT_TRUE(m.ok);
EXPECT_TRUE(m.tilt_conflict);
EXPECT_FALSE(m.tilt_used);
EXPECT_NEAR(m.map_from_odom.x, base.map_from_odom.x, 1e-9);
EXPECT_NEAR(m.map_from_odom.y, base.map_from_odom.y, 1e-9);
EXPECT_NEAR(m.map_from_odom.theta, base.map_from_odom.theta, 1e-9);
EXPECT_DOUBLE_EQ(m.s1, base.s1);
EXPECT_DOUBLE_EQ(m.s2, base.s2);
EXPECT_DOUBLE_EQ(m.s2_yaw, base.s2_yaw);
}
TEST(GlobalLocalizer, BangChungChapNhanHetKhongLechNguoiThang) {
// San phang + IMU phang: moi gia thuyet hop le. Nguoi thang va cong phai
// nhu cu; ung vien them chi co the lam doi thu MANH hon (than trong hon).
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
const RelocMatch base = GlobalMatch(f, pts, cfg);
const RelocMatch m = GlobalMatch(f, pts, cfg, [](const Pose2D&) { return true; });
ASSERT_TRUE(m.ok);
EXPECT_FALSE(m.tilt_used);
EXPECT_FALSE(m.tilt_conflict);
const Pose2D a = Pose2DCompose(base.map_from_odom, odom);
const Pose2D b = Pose2DCompose(m.map_from_odom, odom);
EXPECT_LT(std::hypot(a.x - b.x, a.y - b.y), 0.01);
EXPECT_LT(std::fabs(AngleDiff(a.theta, b.theta)), 0.002);
EXPECT_LE(m.ratio(), base.ratio() + 1e-9);
EXPECT_EQ(Decide(m, cfg.min_cycles, cfg), Decide(base, cfg.min_cycles, cfg));
}
TEST(GlobalLocalizer, SuyBienDocTrucHanhLangVaPhong) {
// Hanh lang dai 20 m chi co hai tuong song song: dich doc hanh lang khong
// lam xau khop (~100%). Phong khong doi xung: dich 1 m thi tut ro. Day la
// kiem chan chot nho do nghieng (sim: doc 30 do, chot lech 0.77 m doc lan).
OccupancyGrid g = MakeGrid(24.0, 6.0);
Fill(&g, 0.0, 1.5, 24.0, 4.5, 0);
Fill(&g, 0.0, 1.5, 24.0, 1.6, 100);
Fill(&g, 0.0, 4.4, 24.0, 4.5, 100);
const LikelihoodField fc = LikelihoodField::FromGrid(g, 0.15);
const Pose2D in_corridor{12.0, 3.0, 0.2};
const Pose2D odom{-1.0, 0.5, -0.3};
// T_map_odom dung = truth o (-) odom.
auto T_of = [&](const Pose2D& truth) { return Pose2DCompose(truth, Pose2DInverse(odom)); };
const double rc =
ShiftScoreRatio(fc, ToOdom(Raycast(g, in_corridor, 720, 6.0), odom), T_of(in_corridor), 1.0);
EXPECT_GT(rc, 0.95) << "hanh lang ma dich doc truc lai tut diem";
OccupancyGrid r = MakeGrid(12.0, 10.0);
AsymRoom(&r, 0.0, 0.0);
const LikelihoodField fr = LikelihoodField::FromGrid(r, 0.15);
const double rr =
ShiftScoreRatio(fr, ToOdom(Raycast(r, kAsymTruth), odom), T_of(kAsymTruth), 1.0);
EXPECT_GT(rr, 0.0);
EXPECT_LT(rr, 0.9) << "phong co dac diem ma dich 1 m van giu diem";
}
// --- Vong DUNG YEN (DecideStatic) ---
//
// Dung yen thi cac vong nhin gan y het: thu mai roi chot o vong VOT qua cong
// la dao nhieu. Sim 2026-10-05 da lot hai lan: chot vong le (1.63 sau 21 vong
// ~1.44), roi trung vi 3 vong (1.63 / 1.40 / 1.64). Luat: NHO NHAT qua moi vong
// cung cho.
namespace {
StaticRound Round(double x, double ratio, double yaw = 3.5, double shift = 0.85) {
StaticRound r;
r.robot = Pose2D{x, 23.0, 1.67};
r.map_from_odom = r.robot; // odom trung map trong test
r.ratio = ratio;
r.ratio_yaw = yaw;
r.shift = shift;
return r;
}
} // namespace
TEST(GlobalLocalizer, DungYenKhongDaoNhieu) {
const GlobalLocalizerConfig cfg;
std::vector<StaticRound> h;
bool ax = false;
std::string why;
// Doi thu that (~1.44) chi bi bo sot o vai vong -> KHONG bao gio chot.
for (const double r : {1.63, 1.40, 1.64, 1.63, 1.65, 1.62, 1.64}) {
EXPECT_NE(DecideStatic(&h, Round(1.2, r), {}, cfg, true, &ax, &why), RelocVerdict::kAccept)
<< "vong " << h.size() << ": " << why;
}
}
TEST(GlobalLocalizer, DungYenDuVongDeuCaoThiChot) {
const GlobalLocalizerConfig cfg;
std::vector<StaticRound> h;
bool ax = false;
std::string why;
EXPECT_EQ(DecideStatic(&h, Round(1.2, 1.64), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles);
EXPECT_EQ(DecideStatic(&h, Round(1.21, 1.95), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles);
EXPECT_EQ(DecideStatic(&h, Round(1.19, 1.96), {}, cfg, true, &ax, &why), RelocVerdict::kAccept) << why;
EXPECT_FALSE(ax);
}
TEST(GlobalLocalizer, DungYenDoiNguoiThangThiDemLai) {
const GlobalLocalizerConfig cfg;
std::vector<StaticRound> h;
bool ax = false;
std::string why;
DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why);
DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why);
// Vong 3 ra cho khac (cach 1 m) -> dem lai tu dau, chua du vong.
EXPECT_EQ(DecideStatic(&h, Round(2.2, 2.0), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles);
EXPECT_EQ(h.size(), 1u);
}
TEST(GlobalLocalizer, DungYenChanMuDocTrucVaNhapNhang) {
const GlobalLocalizerConfig cfg;
bool ax = false;
std::string why;
{
// Mot vong mu doc truc (dich 1 m giu 100%) la du chan, ke ca ty le cao.
std::vector<StaticRound> h;
DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why);
DecideStatic(&h, Round(1.2, 2.0, 3.5, 1.0), {}, cfg, true, &ax, &why);
EXPECT_EQ(DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why), RelocVerdict::kAmbiguous);
EXPECT_TRUE(ax);
// Khong ap kiem doc truc (vd khong co bang chung nghieng) -> qua.
std::vector<StaticRound> h2 = h;
h2.pop_back();
EXPECT_EQ(DecideStatic(&h2, Round(1.2, 2.0), {}, cfg, false, &ax, &why), RelocVerdict::kAccept);
}
{
std::vector<StaticRound> h;
for (int i = 0; i < 3; ++i) DecideStatic(&h, Round(1.2, 2.0, 1.1), {}, cfg, true, &ax, &why);
EXPECT_EQ(DecideStatic(&h, Round(1.2, 2.0, 1.1), {}, cfg, true, &ax, &why),
RelocVerdict::kAmbiguousYaw);
}
{
std::vector<StaticRound> h;
for (int i = 0; i < 3; ++i) DecideStatic(&h, Round(1.2, 1.2), {}, cfg, true, &ax, &why);
EXPECT_EQ(DecideStatic(&h, Round(1.2, 1.2), {}, cfg, true, &ax, &why), RelocVerdict::kAmbiguous);
EXPECT_FALSE(ax);
}
}
// Hai cho (truoc / sau khi bo tren doc). Robot di 0.5 m nen pose robot doi,
// nhung T_map_odom cua CUNG gia thuyet giu nguyen.
namespace {
StaticRound Placed(double y, double ratio, const Pose2D& T) {
StaticRound r;
r.robot = Pose2D{1.2, y, 1.67};
r.map_from_odom = T;
r.ratio = ratio;
r.ratio_yaw = 3.5;
r.shift = 0.85;
return r;
}
// Chay cac vong o mot cho; tra verdict vong cuoi.
RelocVerdict AtPlace(std::vector<StaticRound>* h, const std::vector<StaticPlace>& prev, double y,
const Pose2D& T, std::initializer_list<double> ratios, std::string* why) {
const GlobalLocalizerConfig cfg;
bool ax = false;
RelocVerdict v = RelocVerdict::kFailed;
for (const double r : ratios) v = DecideStatic(h, Placed(y, r, T), prev, cfg, true, &ax, why);
return v;
}
} // namespace
TEST(GlobalLocalizer, HaiChoCungPoseMoiChoDeuQuaThiChot) {
// Sim: gan dinh doc 5 do, cho 1 ty le 1.57-1.60 (duoi chuan mot cho 1.60),
// bo 0.5 m, cho 2 ~1.49 -> hai cho cung pose, moi cho deu >= 1.30 -> chot.
const Pose2D T{0.1, -0.2, 0.05};
std::vector<StaticRound> h;
std::vector<StaticPlace> places;
std::string why;
EXPECT_NE(AtPlace(&h, places, 23.0, T, {1.57, 1.60, 1.58}, &why), RelocVerdict::kAccept) << why;
places.push_back(SummarizePlace(h));
h.clear();
EXPECT_EQ(AtPlace(&h, places, 23.5, T, {1.49}, &why), RelocVerdict::kNeedCycles) << "1 vong chua du";
EXPECT_EQ(AtPlace(&h, places, 23.5, T, {1.47, 1.50}, &why), RelocVerdict::kAccept) << why;
}
TEST(GlobalLocalizer, HaiChoMaMotChoTungTutThiKhongChot) {
// Dung kieu chot SAI o chan doc 10 / 15 do: nguoi thang sai on dinh, ty le
// 1.0-1.2 roi mot vong nhay 1.32. Moi cho phai qua o MOI vong cua no.
const Pose2D T{0.1, -0.2, 0.05};
std::vector<StaticRound> h;
std::vector<StaticPlace> places;
std::string why;
AtPlace(&h, places, 9.0, T, {1.05, 1.19, 1.32}, &why);
places.push_back(SummarizePlace(h));
h.clear();
EXPECT_NE(AtPlace(&h, places, 8.5, T, {1.32, 1.34, 1.31}, &why), RelocVerdict::kAccept) << why;
}
TEST(GlobalLocalizer, HaiChoKhacGiaThuyetThiKhongChot) {
// Hai cho deu qua 1.30 nhung chi ve HAI pose khac nhau (T lech 0.5 m) -> khong chot.
std::vector<StaticRound> h;
std::vector<StaticPlace> places;
std::string why;
AtPlace(&h, places, 23.0, Pose2D{0.1, -0.2, 0.05}, {1.5, 1.5, 1.5}, &why);
places.push_back(SummarizePlace(h));
h.clear();
EXPECT_NE(AtPlace(&h, places, 23.5, Pose2D{0.1, 0.3, 0.05}, {1.5, 1.5, 1.5}, &why),
RelocVerdict::kAccept) << why;
}
TEST(GlobalLocalizer, DiemCanhLacTutKhiPoseSai) {
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);

View File

@@ -0,0 +1,89 @@
// HeightEstimator: z tren doc tu ds*sin(pitch), kep mat bang, neo ban do.
#include <gtest/gtest.h>
#include <cmath>
#include "vslam/height_estimator.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
// Lai `dist` m doc mat doc voi pitch co dinh, buoc 1 cm.
void Drive(HeightEstimator* h, double dist, double pitch) {
const double step = dist >= 0 ? 0.01 : -0.01;
const int n = static_cast<int>(std::round(std::fabs(dist) / 0.01));
for (int i = 0; i < n; ++i) h->OnWheelStep(step, pitch);
}
} // namespace
TEST(HeightEstimator, LenDocDungDoCao) {
// Doc 15 do, cao 1.5 m: duong doc dai 1.5 / sin(15) = 5.796 m. Len doc thi
// mui NGOC len: pitch AM (quy uoc ROS, duong = chuc xuong).
HeightEstimator h;
Drive(&h, 3.0, 0.0);
Drive(&h, 1.5 / std::sin(15 * kDeg), -15 * kDeg);
Drive(&h, 3.0, 0.0);
EXPECT_NEAR(h.z(), 1.5, 0.002);
}
TEST(HeightEstimator, LuiXuongDocCungDung) {
// Lui xuong doc: ds am, mui van ngoc (pitch am) -> z giam.
HeightEstimator h;
h.Reset(1.5, 0.0);
Drive(&h, -1.5 / std::sin(10 * kDeg), -10 * kDeg);
EXPECT_NEAR(h.z(), 0.0, 0.002);
}
TEST(HeightEstimator, KepMatBangTrietTieuBiasPitch) {
// Bias pitch 0.5 do tren san phang 100 m: khong kep la 87 cm, kep la 0.
HeightEstimator h;
Drive(&h, 100.0, 0.5 * kDeg);
EXPECT_DOUBLE_EQ(h.z(), 0.0);
EXPECT_EQ(h.stats().clamped, h.stats().steps);
EXPECT_FALSE(h.on_slope());
}
TEST(HeightEstimator, DocNhoHonNguongBiCoiLaPhang) {
// Gioi han NOI RO: doc 1 do < nguong 1.5 do -> bi bo qua.
HeightEstimator h;
Drive(&h, 30.0, -1.0 * kDeg);
EXPECT_DOUBLE_EQ(h.z(), 0.0);
}
TEST(HeightEstimator, NeoKeoVeZBanDo) {
// Sau mot doc, z lech 10 cm (vd truot banh): neo keo ve gan ban do.
HeightEstimator h;
Drive(&h, 5.0 * 1.1, -15 * kDeg); // truot 10%: dem nhieu hon that
const double z_true = 5.0 * std::sin(15 * kDeg);
ASSERT_GT(h.z() - z_true, 0.1);
EXPECT_TRUE(h.Anchor(z_true));
EXPECT_LT(std::fabs(h.z() - z_true), 0.03);
// Neo lan nua thi sat hon, P giam.
const double s1 = h.sigma();
EXPECT_TRUE(h.Anchor(z_true));
EXPECT_LT(h.sigma(), s1);
}
TEST(HeightEstimator, NeoQuaXaBiTuChoi) {
// z ban do lech 1 m so voi uoc luong vua di 3 m phang: nhieu kha nang la
// node sai tang / sai cho -- khong duoc keo.
HeightEstimator h;
Drive(&h, 3.0, 0.0);
EXPECT_FALSE(h.Anchor(1.0));
EXPECT_DOUBLE_EQ(h.z(), 0.0);
EXPECT_EQ(h.stats().anchors_rejected, 1u);
}
TEST(HeightEstimator, TrenPhangNeoKeoNhe) {
// Di 50 m phang (P nho): neo lech 5 cm chi keo mot phan -- mot node ban do
// khong duoc dat lai z o noi robot da biet chac.
HeightEstimator h;
h.Reset(0.0, 0.0);
Drive(&h, 1.0, 0.0);
h.Anchor(0.05);
EXPECT_GT(h.z(), 0.0);
EXPECT_LT(h.z(), 0.03);
}

133
test/test_height_map.cc Normal file
View File

@@ -0,0 +1,133 @@
// Do thi z 1-D va mat san theo node (height_map.h).
#include <gtest/gtest.h>
#include <cmath>
#include <map>
#include <vector>
#include "vslam/height_map.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
}
TEST(ZGraph, VongCoDocDonSaiDeuVaKhepVe0) {
// Vong: 10 node phang z=0, 6 node len doc 15 do (+0.25 moi node), 10 node
// phang tren z=1.5, 6 node xuong, 10 node phang ve gan cho xuat phat. z DO
// troi them 1 cm moi node tren doc (truot banh): ve den noi dz do = +0.12.
std::map<int, NodeHeight> meas;
int id = 1;
double z = 0.0;
auto push = [&](int n, double step, double pitch) {
for (int k = 0; k < n; ++k) {
z += step;
meas[id++] = NodeHeight{z, 0.0, pitch};
}
};
push(10, 0.0, 0.0);
push(6, 0.25 + 0.01, -15 * kDeg);
push(10, 0.0, 0.0);
push(6, -0.25 + 0.01, 15 * kDeg);
push(10, 0.0, 0.0);
const int last = id - 1;
ASSERT_NEAR(meas[last].z, 0.12, 1e-9);
std::vector<ZGraphLink> links;
for (int i = 1; i < last; ++i) links.push_back(ZGraphLink{i, i + 1, true, 1.0, 0.0});
// Ve dung cho cu: vong dong node cuoi -> node dau, ca hai phang.
links.push_back(ZGraphLink{last, 1, false, 0.05, 0.0});
const std::map<int, double> zo = SolveZGraph(meas, links);
EXPECT_NEAR(zo.at(last), zo.at(1), 0.02);
EXPECT_NEAR(zo.at(1), 0.0, 0.01);
// San tren: that 1.5, do 1.56. Sai don ra -> gan 1.5 hon so do.
EXPECT_LT(std::fabs(zo.at(20) - 1.5), std::fabs(meas.at(20).z - 1.5));
}
TEST(ZGraph, VongTrenDocTheoMatPhangDoc) {
// Hai lan qua CUNG doc 15 do: node B nam 1 m phia truoc node A (doc len). dz
// dung = 1 * tan(15) = 0.268, KHONG phai 0. So do cua B lech 0.2 m.
std::map<int, NodeHeight> meas;
meas[1] = NodeHeight{0.5, 0.0, -15 * kDeg};
meas[2] = NodeHeight{0.5 + 0.268 + 0.2, 0.0, -15 * kDeg};
std::vector<ZGraphLink> links{ZGraphLink{1, 2, false, 1.0, 0.0}};
ZGraphConfig cfg;
cfg.sigma_first = 0.001;
const std::map<int, double> zo = SolveZGraph(meas, links, cfg);
EXPECT_NEAR(zo.at(2) - zo.at(1), std::tan(15 * kDeg), 0.02);
}
TEST(ZGraph, NodeKhongLienKetGiuZDo) {
std::map<int, NodeHeight> meas;
meas[1] = NodeHeight{0.0, 0.0, 0.0};
meas[7] = NodeHeight{1.5, 0.0, 0.0};
const std::map<int, double> zo = SolveZGraph(meas, {});
EXPECT_NEAR(zo.at(7), 1.5, 1e-6);
}
TEST(FloorModel, MatPhangDocVaNodeGanNhat) {
// Node phang o x = -2 (z 0), node tren doc 15 do o x = 0 (z 0.5, huong +x,
// mui ngoc = pitch am).
std::vector<FloorNode> nodes(2);
nodes[0].x = -2.0;
nodes[1].z = 0.5;
nodes[1].pitch = -15 * kDeg;
FloorModel fm;
fm.Build(nodes, 4.0, 0.25);
double z = 0;
ASSERT_TRUE(fm.FloorAt(1.0, 0.0, &z));
EXPECT_NEAR(z, 0.5 + std::tan(15 * kDeg), 1e-6);
// Gan node phang hon -> mat phang phang.
ASSERT_TRUE(fm.FloorAt(-1.7, 0.1, &z));
EXPECT_NEAR(z, 0.0, 1e-9);
// Ngoai ban kinh moi node.
EXPECT_FALSE(fm.FloorAt(10.0, 0.0, &z));
}
TEST(FloorModel, RollNghiengSangTrai) {
// roll duong = ben TRAI (+y) cao len.
std::vector<FloorNode> nodes(1);
nodes[0].theta = M_PI / 2; // huong +y cua map; ben trai = -x
nodes[0].roll = 5 * kDeg;
FloorModel fm;
fm.Build(nodes);
double z = 0;
ASSERT_TRUE(fm.FloorAt(-1.0, 0.0, &z));
EXPECT_NEAR(z, std::tan(5 * kDeg), 1e-6);
}
// Do doc san + do lech nghieng: nen cua viec loai gia thuyet dinh vi lai tren
// doc (GlobalMatch + `admit`). Sai dau o day thi bo loc loai DUNG cho that.
TEST(FloorModel, DoDocVaDoLechNghieng) {
// Doc 15 do di LEN theo +y cua map (node huong +y, mui ngoc = pitch am).
std::vector<FloorNode> nodes(1);
nodes[0].theta = M_PI / 2;
nodes[0].pitch = -15 * kDeg;
FloorModel fm;
fm.Build(nodes);
double gx = 0, gy = 0;
ASSERT_TRUE(FloorGradientAt(fm, 0.3, 0.2, 1.5, &gx, &gy));
EXPECT_NEAR(gx, 0.0, 1e-9);
EXPECT_NEAR(gy, std::tan(15 * kDeg), 1e-9);
// Node xa hon max_dist -> khong biet san o do.
EXPECT_FALSE(FloorGradientAt(fm, 3.0, 0.0, 1.5, &gx, &gy));
const double t15 = std::tan(15 * kDeg);
// Robot mui LEN doc (yaw +y) do duoc pitch -15: khop.
EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, M_PI / 2, 0.0, t15), 0.0, 1e-9);
// Cung do nghieng nhung gia thuyet mui XUONG doc (lat 180 do): lech 2 lan doc.
EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, -M_PI / 2, 0.0, t15), 2 * t15, 1e-9);
// Gia thuyet o san PHANG: lech dung bang doc do duoc.
EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, 0.3, 0.0, 0.0), t15, 1e-9);
// Mui NGANG doc (yaw +x, doc len ve +y = ben TRAI): roll duong, pitch 0.
const double roll = std::atan(t15); // cos(pitch) = 1
EXPECT_NEAR(TiltResidual(roll, 0.0, 0.0, 0.0, t15), 0.0, 1e-9);
EXPECT_NEAR(TiltResidual(-roll, 0.0, 0.0, 0.0, t15), 2 * t15, 1e-9);
// Than nghieng ca hai truc (mui len doc cheo 45 do): van khop khi dung huong.
const double g = 0.2; // doc theo +y
const double sf = g * std::sin(M_PI / 4), sl = g * std::cos(M_PI / 4);
const double p = -std::atan(sf), r = std::atan(sl * std::cos(p));
EXPECT_NEAR(TiltResidual(r, p, M_PI / 4, 0.0, g), 0.0, 1e-9);
}

View File

@@ -149,6 +149,35 @@ TEST(RecordIo, RoundTripImuVaEncoder) {
std::remove(path.c_str());
}
TEST(RecordIo, RoundTripGroundTruth) {
// Stream MO RONG cua ban ghi mo phong: tu the THAT 6-DoF de cham diem
// offline. Ten stream phai co, khong thi log replay in "?".
const std::string path = TempPath("gt");
const double pose[6] = {1.5, -2.25, 0.4363, 0.01, -0.1745, 1.5708};
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
std::string p;
EncodeGroundTruthPayload(pose, &p);
w.Write(VsrStream::kGroundTruth, UnixTime::fromSec(200.0), p);
w.Close();
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
ASSERT_TRUE(r.Next(&h, &payload));
EXPECT_EQ(h.stream, VsrStream::kGroundTruth);
EXPECT_STREQ(VsrStreamName(h.stream), "ground_truth");
double back[6] = {};
ASSERT_TRUE(DecodeGroundTruthPayload(payload, back));
for (int i = 0; i < 6; ++i) EXPECT_DOUBLE_EQ(back[i], pose[i]) << "truong " << i;
r.Close();
std::remove(path.c_str());
}
TEST(RecordIo, RoundTripImage) {
const std::string path = TempPath("img");
std::vector<uint8_t> pixels(320 * 240 * 2);

View File

@@ -5,6 +5,7 @@
#include <cmath>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string>
#include <unistd.h>
@@ -320,6 +321,66 @@ TEST(ReplaySource, LenhMotorKhiReplayDiVaoHuKhong) {
std::remove(path.c_str());
}
TEST(ReplaySource, AnhCuKhongBiKhungSauGhiDe) {
// Nhu bo mo phong va driver RealSense: anh da phat ra phai giu nguyen noi
// dung du nguon da giai ma them nhieu khung -- SlamLoop giu khung moi nhat
// qua Rtabmap::process tren luong khac. Truoc day ba kho giai ma dung chung.
const std::string path = TempPath("img_hold");
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
for (int k = 0; k < 6; ++k) {
const UnixTime stamp = UnixTime::fromSec(1737000000.0 + 0.1 * k);
std::vector<uint8_t> depth(4 * 2 * 2), ir(4 * 2);
for (size_t i = 0; i < depth.size(); ++i) depth[i] = static_cast<uint8_t>(10 * k + i);
for (size_t i = 0; i < ir.size(); ++i) ir[i] = static_cast<uint8_t>(100 + 10 * k + i);
Image d;
d.header.stamp = stamp;
d.width = 4; d.height = 2; d.step = 8;
d.format = PixelFormat::kMono16;
d.depth_scale = 0.001f;
d.data = depth.data();
Image r = d;
r.step = 4;
r.format = PixelFormat::kMono8;
r.data = ir.data();
std::string pd, pr;
EncodeImagePayload(d, &pd);
EncodeImagePayload(r, &pr);
w.Write(VsrStream::kDepth, stamp, pd);
w.Write(VsrStream::kInfra1, stamp, pr);
}
w.Close();
}
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
std::vector<CameraFrame> frames;
std::vector<std::vector<uint8_t>> depth_copy, ir_copy;
rs.camera()->SetCallback([&](const CameraFrame& f) {
frames.push_back(f);
depth_copy.emplace_back(f.depth->data, f.depth->data + 16);
ir_copy.emplace_back(f.infra1->data, f.infra1->data + 8);
});
rs.camera()->Open();
rs.Run();
ASSERT_EQ(frames.size(), 6u);
for (size_t k = 0; k < frames.size(); ++k) {
EXPECT_EQ(std::memcmp(frames[k].depth->data, depth_copy[k].data(), 16), 0)
<< "depth khung " << k << " bi ghi de";
EXPECT_EQ(std::memcmp(frames[k].infra1->data, ir_copy[k].data(), 8), 0)
<< "IR khung " << k << " bi ghi de";
EXPECT_EQ(frames[k].depth->data[0], static_cast<uint8_t>(10 * k));
}
std::remove(path.c_str());
}
TEST(ReplaySource, FileKhongTonTaiThiBaoLoi) {
ReplayConfig cfg;
cfg.path = "/khong/ton/tai/abc.vsr";

237
test/test_scan_leveler.cc Normal file
View File

@@ -0,0 +1,237 @@
// ScanLeveler + ElevationMap: bu nghieng scan LiDAR tren doc, bo tia cham
// san / mat doc.
//
// Hinh hoc robot nay: laser_link o (0, 0, 0.13) tren base_link, banh r 0.0865
// -> LiDAR cao 0.2165 m tren san khi robot nam ngang.
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <vector>
#include "vslam/elevation_map.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/scan_leveler.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
constexpr double kWheel = 0.0865;
Transform LaserToBase() {
Transform t = TransformIdentity();
t.translation.z = 0.13;
return t;
}
// 360 tia, 1 do / tia, tia i o goc -180 + i do.
LaserScan EmptyScan() {
LaserScan s;
s.angle_min = static_cast<float>(-M_PI);
s.angle_increment = static_cast<float>(kDeg);
s.angle_max = static_cast<float>(-M_PI + 359 * kDeg);
s.range_min = 0.05f;
s.range_max = 30.0f;
s.ranges.assign(360, std::numeric_limits<float>::infinity());
return s;
}
size_t Bin(double deg) { return static_cast<size_t>(std::lround(deg + 180.0)); }
// Goc LiDAR trong frame base_footprint da can, luc than nghieng (roll, pitch).
Point LaserOrigin(double roll, double pitch) {
const Transform T = TransformCompose(TiltLift(roll, pitch, kWheel), LaserToBase());
return TransformPoint(T, Point{0, 0, 0});
}
// Huong tia goc a trong frame da can. CHI phep quay: `TransformVector` cua
// repo cong ca tinh tien.
Vector3 RayDir(double a, double roll, double pitch) {
const Transform T = TransformCompose(TiltLift(roll, pitch, kWheel), LaserToBase());
return RotateVector(T.rotation, Vector3{std::cos(a), std::sin(a), 0.0});
}
} // namespace
TEST(ScanLeveler, NamNgangThiGiuNguyen) {
// Tuong x = 3 m: robot ngang thi scan ra phai Y HET vao.
LaserScan in = EmptyScan();
for (int d = -60; d <= 60; ++d) in.ranges[Bin(d)] = static_cast<float>(3.0 / std::cos(d * kDeg));
LaserScan out;
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out, &st);
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;
}
}
EXPECT_EQ(st.rebinned, 0u);
EXPECT_EQ(st.kept, 121u);
}
TEST(ScanLeveler, LenDocTuongDoRaKhoangCachNgang) {
// Than ngoc 15 do (pitch AM). Tuong dung o x = 2.0 m trong frame
// base_footprint da can: tia 0 do di xien len, cham tuong o r > 2, va scan
// can phai bao DUNG 2.0 m (RTAB-Map dat diem bang ngoai lai tinh (0, 0)).
const double pitch = -15 * kDeg;
const Point o = LaserOrigin(0.0, pitch);
const Vector3 d = RayDir(0.0, 0.0, pitch);
const double r = (2.0 - o.x) / d.x;
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(r);
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, pitch, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out,
nullptr);
EXPECT_GT(r, 2.05);
EXPECT_NEAR(out.ranges[Bin(0)], 2.0, 1e-4);
}
TEST(ScanLeveler, TiaXienDoiSangOGocMoi) {
// Than ngoc 15 do: tia 45 do chieu xuong mat phang ngang thanh ~46 do.
const double pitch = -15 * kDeg;
LaserScan in = EmptyScan();
in.ranges[Bin(45)] = 3.0f;
LaserScan out;
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, pitch, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out, &st);
const double a_new = std::atan2(std::sin(45 * kDeg), std::cos(45 * kDeg) * std::cos(15 * kDeg));
const size_t j = Bin(std::round(a_new / kDeg));
EXPECT_NE(j, Bin(45));
EXPECT_TRUE(std::isfinite(out.ranges[j]));
// O cu khong con tia nao: "khong do duoc" (NaN), khong phai "trong" (inf).
EXPECT_TRUE(std::isnan(out.ranges[Bin(45)]));
EXPECT_EQ(st.rebinned, 1u);
}
TEST(ScanLeveler, XuongDocTiaChamSanDuoiBiBo) {
// Dang xuong doc 15 do (chuc mui = pitch DUONG), giua doc o z = 0.75: tia
// truoc cam xuong san duoi chan doc. Khong co ElevationMap van bo duoc vi
// diem cham THAP hon mat dat duoi robot.
const double pitch = 15 * kDeg, z_robot = 0.75;
const Point o = LaserOrigin(0.0, pitch);
const Vector3 d = RayDir(0.0, 0.0, pitch);
const double r = (o.z + z_robot) / -d.z; // toi z tuyet doi = 0
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(r);
LaserScan out;
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, pitch, kWheel, Pose2D{}, z_robot, nullptr, ScanLevelerConfig{},
&out, &st);
EXPECT_TRUE(std::isnan(out.ranges[Bin(0)]));
EXPECT_EQ(st.dropped_below, 1u);
}
TEST(ScanLeveler, TuongGiaChanDocLenBoKhiCameraDaThayDoc) {
// Robot ngang tren san, chan doc 15 do o x = 1.0 m: tia ngang cao 0.2165 m
// cham mat doc o x = 1.0 + 0.2165 / tan(15) = 1.808 m -- "tuong" gia.
const double foot = 1.0, t15 = std::tan(15 * kDeg);
const double h_laser = LaserOrigin(0.0, 0.0).z;
const double x_hit = foot + h_laser / t15;
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(x_hit);
// Khong co ban do do cao: khong phan biet duoc voi tuong that -> GIU (gioi
// han da noi ro trong scan_leveler.h).
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out,
nullptr);
EXPECT_NEAR(out.ranges[Bin(0)], x_hit, 1e-4);
// Camera da thay mat doc (diem moi 2 cm tren be mat): bo.
ElevationMap em;
std::vector<PointXYZ> pts;
for (double x = 0.0; x < 4.0; x += 0.02) {
for (double y = -0.5; y <= 0.5; y += 0.02) {
pts.push_back(PointXYZ{static_cast<float>(x), static_cast<float>(y),
static_cast<float>(x > foot ? (x - foot) * t15 : 0.0)});
}
}
em.AddPoints(pts, UnixTime::fromNSec(1));
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, &em, ScanLevelerConfig{}, &out, &st);
EXPECT_TRUE(std::isnan(out.ranges[Bin(0)]));
EXPECT_EQ(st.dropped_floor, 1u);
}
TEST(ScanLeveler, TuongThatCanhDocVanGiu) {
// Tuong that o x = 1.8 m ngay canh vung doc: san duoi chan tuong (camera
// thay) o z = 0 -> diem cao 0.2165 m tren san -> GIU.
ElevationMap em;
std::vector<PointXYZ> pts;
for (double x = 0.0; x < 3.0; x += 0.02) pts.push_back(PointXYZ{static_cast<float>(x), 0.0f, 0.0f});
em.AddPoints(pts, UnixTime::fromNSec(1));
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = 1.8f;
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, &em, ScanLevelerConfig{}, &out, nullptr);
EXPECT_NEAR(out.ranges[Bin(0)], 1.8, 1e-4);
}
TEST(ScanLeveler, PoseOdomDungTrongElevationMap) {
// ElevationMap o frame ODOM: robot o (10, 5) quay 90 do, tia 0 do huong +y
// cua odom. Mat doc o vung y > 6 chi co o odom -- phai tra dung o.
const double t15 = std::tan(15 * kDeg);
ElevationMap em;
std::vector<PointXYZ> pts;
for (double y = 5.0; y < 9.0; y += 0.02) {
for (double x = 9.5; x <= 10.5; x += 0.02) {
pts.push_back(PointXYZ{static_cast<float>(x), static_cast<float>(y),
static_cast<float>(y > 6.0 ? (y - 6.0) * t15 : 0.0)});
}
}
em.AddPoints(pts, UnixTime::fromNSec(1));
const double h_laser = LaserOrigin(0.0, 0.0).z;
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(1.0 + h_laser / t15);
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{10.0, 5.0, M_PI / 2}, 0.0, &em,
ScanLevelerConfig{}, &out, nullptr);
EXPECT_TRUE(std::isnan(out.ranges[Bin(0)]));
}
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.
LaserScan in = EmptyScan();
in.ranges[Bin(90)] = in.range_max + 1.0f;
in.ranges[Bin(89)] = 2.0f;
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, -15 * kDeg, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out,
nullptr);
EXPECT_FLOAT_EQ(out.ranges[Bin(90)], in.range_max + 1.0f);
}
TEST(ElevationMap, MinVetBanhVaPrune) {
ElevationMap em;
double z = 0;
EXPECT_FALSE(em.FloorAt(0.05, 0.05, &z));
// Hai diem cung o: giu MIN.
em.AddPoints({PointXYZ{0.05f, 0.05f, 0.30f}, PointXYZ{0.06f, 0.04f, 0.10f}}, UnixTime::fromNSec(1));
ASSERT_TRUE(em.FloorAt(0.05, 0.05, &z));
EXPECT_FLOAT_EQ(z, 0.10f);
// Toa do am khong dung o voi toa do duong (khoa ghep hai chi so co dau).
em.AddPoints({PointXYZ{-0.05f, 0.05f, 1.0f}, PointXYZ{0.05f, -0.05f, 2.0f}}, UnixTime::fromNSec(1));
ASSERT_TRUE(em.FloorAt(-0.05, 0.05, &z));
EXPECT_FLOAT_EQ(z, 1.0f);
ASSERT_TRUE(em.FloorAt(0.05, -0.05, &z));
EXPECT_FLOAT_EQ(z, 2.0f);
// Vet banh GHI DE (ke ca cao hon min cu).
em.AddFootprint(0.0, 0.0, 0.5, 0.25, UnixTime::fromNSec(2));
ASSERT_TRUE(em.FloorAt(0.05, 0.05, &z));
EXPECT_FLOAT_EQ(z, 0.5f);
// Prune: o xa hon ban kinh bi bo.
em.AddPoints({PointXYZ{20.0f, 0.0f, 0.0f}}, UnixTime::fromNSec(3));
em.Prune(0.0, 0.0, UnixTime::fromNSec(4));
EXPECT_FALSE(em.FloorAt(20.0, 0.0, &z));
EXPECT_TRUE(em.FloorAt(0.05, 0.05, &z));
// Prune: o cu hon max_age bi bo.
em.Prune(0.0, 0.0, UnixTime::fromNSec(static_cast<int64_t>(61e9)));
EXPECT_EQ(em.size(), 0u);
}

182
test/test_sim_gl.cc Normal file
View File

@@ -0,0 +1,182 @@
// Ve camera mo phong bang GPU (vslam_sim_gl).
//
// May khong co GPU dung duoc (CI, container) thi cac bai nay SKIP, khong do:
// renderer GPU la tuy chon, va bo mo phong van chay bang raycast CPU.
//
// Khoa:
// * depth GPU dung khoang cach toi mm (tia qua pixel giua);
// * hop bao mesh doc bang assimp khop bo doc world cua vslam_sim (OBJ met,
// OBJ cm + <scale>, COLLADA co <matrix>, COLLADA khai Y_UP) -- lech quy
// uoc la anh va luoi chiem dung noi hai chuyen khac nhau;
// * bo mo phong dung renderer: co anh IR cung kich thuoc depth, va depth GPU
// KHOP depth raycast CPU tren san / doc / tuong.
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include "vslam/gazebo_world.h"
#include "vslam/sim_gl_renderer.h"
#include "vslam/sim_source.h"
using namespace vslam;
namespace {
std::string WorldDir() {
const char* e = std::getenv("VSLAM_TEST_DATA_DIR");
return (e != nullptr ? std::string(e) : std::string("test/data")) + "/world";
}
GazeboWorld Load(const std::string& name) {
GazeboWorld w;
const StatusResponse st =
LoadGazeboWorld(WorldDir() + "/" + name, {WorldDir() + "/models"}, &w);
EXPECT_TRUE(st.ok()) << st.message;
return w;
}
// Camera dat tai (x, y, z), nhin theo yaw, khong chuc.
SimCameraView View(double x, double y, double z, double yaw, int w, int h, double fx) {
const double cy = std::cos(yaw), sy = std::sin(yaw);
SimCameraView v;
// Cot: X quang = phai = -trai, Y quang = xuong, Z quang = truoc.
const double cols[3][3] = {{sy, -cy, 0.0}, {0.0, 0.0, -1.0}, {cy, sy, 0.0}};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) v.R_wc[i * 3 + j] = cols[j][i];
}
v.t_wc[0] = x; v.t_wc[1] = y; v.t_wc[2] = z;
v.width = w; v.height = h;
v.fx = v.fy = fx;
v.cx = w / 2.0; v.cy = h / 2.0;
return v;
}
// Renderer cho world, hoac nullptr (kem ly do) neu may khong ve duoc.
std::shared_ptr<SimCameraRenderer> MakeRenderer(const GazeboWorld& w, std::string* why) {
GlRendererConfig cfg = DefaultGlRendererConfig();
auto r = CreateGlCameraRenderer(w, cfg, why);
if (!r) return nullptr;
std::vector<uint8_t> ir;
std::vector<float> d;
if (!r->Render(View(0, 0, 1, 0, 8, 8, 4.0), &ir, &d)) {
*why = "khong co GPU dung duoc (xem log sim_gl)";
return nullptr;
}
return r;
}
} // namespace
TEST(SimGl, DepthDungKhoangCachToiMm) {
// mini.world: hop box_m 2.0 x 1.0 x 0.5 m tam o goc. Mesh CHI co day, nap
// va hai mat +-y (khong co mat +-x), nen nhin vao mat y = -0.5: camera o
// y = -2.5, cao giua hop, nhin +y -- pixel giua thay mat do o Z = 2.0.
const GazeboWorld w = Load("mini.world");
std::string why;
auto r = MakeRenderer(w, &why);
if (!r) GTEST_SKIP() << why;
std::vector<uint8_t> ir;
std::vector<float> d;
const int W = 160, H = 120;
ASSERT_TRUE(r->Render(View(0.0, -2.5, 0.25, M_PI / 2, W, H, 120.0), &ir, &d));
ASSERT_EQ(d.size(), static_cast<size_t>(W) * H);
EXPECT_NEAR(d[static_cast<size_t>(H / 2) * W + W / 2], 2.0, 1e-3);
// Goc tren trai nhin len troi: khong trung gi.
EXPECT_EQ(d[0], 0.0f);
EXPECT_EQ(ir[0], 0);
}
TEST(SimGl, HopBaoAssimpKhopBoDocWorld) {
const GazeboWorld w = Load("mini.world");
WorldMeshes ref;
ASSERT_TRUE(ExportWorldMeshes(w, /*visual=*/true, &ref).ok());
size_t checked = 0;
for (const WorldMeshInstance& in : ref.instances) {
// Hop bao THE GIOI cua the hien theo bo doc world: tam giac he model
// (da ap <scale>) -> yaw -> tinh tien.
const WorldMeshGeom& g = ref.geoms[in.geom];
double rmn[3] = {1e18, 1e18, 1e18}, rmx[3] = {-1e18, -1e18, -1e18};
const double c = std::cos(in.yaw), s = std::sin(in.yaw);
for (size_t k = 0; k + 2 < g.tri.size(); k += 3) {
const double p[3] = {g.tri[k] * c - g.tri[k + 1] * s + in.x,
g.tri[k] * s + g.tri[k + 1] * c + in.y, g.tri[k + 2] + in.z};
for (int a = 0; a < 3; ++a) { rmn[a] = std::min(rmn[a], p[a]); rmx[a] = std::max(rmx[a], p[a]); }
}
// The hien tuong ung trong world (cung ten model, cung vi tri).
for (const WorldModel& m : w.models) {
if (m.model_name != g.model_name || std::fabs(m.x - in.x) > 1e-6 ||
std::fabs(m.y - in.y) > 1e-6) {
continue;
}
double amn[3], amx[3];
ASSERT_TRUE(AssimpModelBounds(m, amn, amx)) << m.name;
for (int a = 0; a < 3; ++a) {
EXPECT_NEAR(amn[a], rmn[a], 0.01) << m.name << " truc " << a;
EXPECT_NEAR(amx[a], rmx[a], 0.01) << m.name << " truc " << a;
}
checked++;
break;
}
}
EXPECT_GE(checked, 4u) << "phai kiem du OBJ met, OBJ cm, DAE matrix, DAE Y_UP";
}
TEST(SimGl, BoMoPhongCoAnhIrVaDepthKhopRaycastCpu) {
// Cung tu the tren world doc: mot sim ve bang GPU, mot sim raycast CPU. Tat
// nhieu depth de so thang. Hinh hoc CPU la 2.5D (tuong ep tu luoi) nen chi
// so TRUNG VI -- san, mat doc va tuong phai khop toi vai cm.
auto make = [](bool gpu, std::string* why, CameraFrame* out) -> bool {
SimConfig c;
c.speed = 0.0;
c.world_path = WorldDir() + "/ramp.world";
c.world_model_paths = {WorldDir() + "/models"};
c.enable_depth_camera = true;
c.depth_disparity_noise_px = 0.0;
c.depth_noise_floor = 0.0;
c.camera_z = 0.445;
c.camera_x = 0.095;
c.camera_pitch = 0.0;
c.wheel_radius = 0.0865;
c.start_x = -1.5;
SimSource sim(c);
if (!sim.Open().ok()) { *why = "sim khong mo duoc"; return false; }
if (gpu) {
auto r = MakeRenderer(sim.world(), why);
if (!r) return false;
sim.SetCameraRenderer(r);
}
bool have = false;
sim.camera()->SetCallback([&](const CameraFrame& f) { *out = f; have = true; });
sim.camera()->Open();
sim.RunFor(0.1);
if (!have) *why = "khong co khung camera";
return have;
};
std::string why;
CameraFrame gpu, cpu;
if (!make(true, &why, &gpu)) GTEST_SKIP() << why;
ASSERT_TRUE(make(false, &why, &cpu)) << why;
ASSERT_TRUE(gpu.infra1 != nullptr) << "renderer GPU phai cho anh IR";
EXPECT_TRUE(cpu.infra1 == nullptr) << "raycast CPU khong co anh IR";
ASSERT_EQ(gpu.infra1->width, gpu.depth->width);
ASSERT_EQ(gpu.infra1->height, gpu.depth->height);
const size_t n = static_cast<size_t>(gpu.depth->width) * gpu.depth->height;
std::vector<double> diff;
for (size_t i = 0; i < n; ++i) {
const uint16_t a = static_cast<uint16_t>(gpu.depth->data[2 * i] | (gpu.depth->data[2 * i + 1] << 8));
const uint16_t b = static_cast<uint16_t>(cpu.depth->data[2 * i] | (cpu.depth->data[2 * i + 1] << 8));
if (a == 0 || b == 0) continue;
diff.push_back(std::fabs(static_cast<double>(a) - b) * 0.001);
}
ASSERT_GT(diff.size(), n / 4) << "qua it diem co depth o ca hai";
std::nth_element(diff.begin(), diff.begin() + diff.size() / 2, diff.end());
EXPECT_LT(diff[diff.size() / 2], 0.02) << "trung vi |depth GPU - depth CPU|";
}

308
test/test_sim_imu.cc Normal file
View File

@@ -0,0 +1,308 @@
// IMU mo phong va su that 6-DoF.
//
// ================== VI SAO BAI KIEM NAY TON TAI ==================
// VIO (DM-VIO, F2M co IMU) tin rang tich phan gyro ra dung tu the va tich
// phan gia toc ke (tru trong luc) ra dung quy dao. Mot IMU mo phong noi doi
// mot chut la VIO trong sim "tot" vi ly do sai, hoac "te" vi ly do sai. Mo
// hinh cu chi xap xi (bo gia toc theo phuong dung khi len doc, bo canh tay
// don cua diem dat IMU) -- du cho gravity_align, khong du cho VIO.
//
// Bai nay khoa:
// * tich phan gyro ra DUNG tu the that, ke ca khi quay tren doc;
// * tich phan gia toc ke ra DUNG vi tri that cua diem dat IMU;
// * tan so phat thap (WT61PC 10 Hz) khong keo buoc vat ly theo;
// * do tre: mau phat ra la mau cu, dung bang so buoc;
// * bias dau lam lech gyro nhu cau hinh;
// * su that phat dung tan so; hinh hoc lay dung tu robot.yaml.
#include <gtest/gtest.h>
#include <cmath>
#include <cstdlib>
#include <string>
#include <vector>
#include "vslam/node_constants.h"
#include "vslam/robot_model.h"
#include "vslam/sim_source.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
std::string DataDir() {
const char* e = std::getenv("VSLAM_TEST_DATA_DIR");
return e != nullptr ? std::string(e) : std::string("test/data");
}
std::string ConfigSrcDir() {
const char* e = std::getenv("VSLAM_CONFIG_SRC_DIR");
return e != nullptr ? std::string(e) : std::string("configuration_files");
}
// Doc 10 do cua test/data/world/ramp.world, khong nhieu, IMU dong hoc.
SimConfig RampCfg() {
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.world_path = DataDir() + "/world/ramp.world";
c.world_model_paths = {DataDir() + "/world/models"};
c.wheel_radius = 0.0865;
c.wheel_separation = 0.40;
c.lidar_x = 0.0;
c.lidar_z = 0.13;
c.lidar_noise_stddev = 0.0;
c.gyro_noise_stddev = 0.0;
c.accel_noise_stddev = 0.0;
c.imu_model = SimConfig::ImuModel::kKinematic;
c.start_x = -2.0;
return c;
}
SimConfig FlatCfg() {
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.gyro_noise_stddev = 0.0;
c.accel_noise_stddev = 0.0;
return c;
}
// --- Ma tran 3x3 hang-chinh, chi cho bai kiem ---
struct M3 {
double m[9];
};
M3 FromRPY(double r, double p, double y) {
const double cr = std::cos(r), sr = std::sin(r);
const double cp = std::cos(p), sp = std::sin(p);
const double cy = std::cos(y), sy = std::sin(y);
return M3{{cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr,
sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr,
-sp, cp * sr, cp * cr}};
}
M3 Mul(const M3& a, const M3& b) {
M3 o{};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
double s = 0.0;
for (int k = 0; k < 3; ++k) s += a.m[i * 3 + k] * b.m[k * 3 + j];
o.m[i * 3 + j] = s;
}
}
return o;
}
// Exp(w) theo Rodrigues.
M3 Exp(double wx, double wy, double wz) {
const double th = std::sqrt(wx * wx + wy * wy + wz * wz);
const M3 K{{0, -wz, wy, wz, 0, -wx, -wy, wx, 0}};
const M3 K2 = Mul(K, K);
const double a = th < 1e-12 ? 1.0 : std::sin(th) / th;
const double b = th < 1e-12 ? 0.5 : (1.0 - std::cos(th)) / (th * th);
M3 o{{1, 0, 0, 0, 1, 0, 0, 0, 1}};
for (int i = 0; i < 9; ++i) o.m[i] += a * K.m[i] + b * K2.m[i];
return o;
}
double AngleBetween(const M3& a, const M3& b) {
double tr = 0.0; // trace(a^T b)
for (int i = 0; i < 3; ++i) {
for (int k = 0; k < 3; ++k) tr += a.m[k * 3 + i] * b.m[k * 3 + i];
}
return std::acos(std::max(-1.0, std::min(1.0, (tr - 1.0) / 2.0)));
}
// Vi tri diem dat IMU theo tu the that, cung quy uoc voi bo mo phong.
void ImuPoint(const SimConfig& c, const SimPose3& p, double out[3]) {
const M3 R = FromRPY(p.roll, p.pitch, p.yaw);
const double v[3] = {c.imu_x, c.imu_y, c.wheel_radius + c.imu_z};
const double base[3] = {p.x, p.y, p.z};
for (int i = 0; i < 3; ++i) {
out[i] = base[i] + R.m[i * 3 + 0] * v[0] + R.m[i * 3 + 1] * v[1] + R.m[i * 3 + 2] * v[2];
}
}
// Lai: tu x = -2 thang len doc (~1.8 m vao doc, z ~0.3 m), roi re trai nhe
// NGAY TREN doc -- doi ca roll lan pitch.
void DriveRampAndTurn(SimSource* sim) {
for (int i = 0; i < 260; ++i) { sim->base()->SetVelocity(0.30, 0.0); sim->RunFor(0.05); }
for (int i = 0; i < 60; ++i) { sim->base()->SetVelocity(0.25, 0.25); sim->RunFor(0.05); }
}
} // namespace
TEST(SimImu, TichPhanGyroRaDungTuThe) {
SimSource sim(RampCfg());
ASSERT_TRUE(sim.Open().ok());
const double dt = 1.0 / RampCfg().imu_rate_hz;
const SimPose3 p0 = sim.ground_truth_3d();
M3 R = FromRPY(p0.roll, p0.pitch, p0.yaw);
sim.mcu()->SetImuCallback([&](ImuPtr m) {
R = Mul(R, Exp(m->angular_velocity.x * dt, m->angular_velocity.y * dt,
m->angular_velocity.z * dt));
});
sim.mcu()->Open();
sim.base()->Open();
DriveRampAndTurn(&sim);
const SimPose3 p1 = sim.ground_truth_3d();
ASSERT_GT(p1.z, 0.2) << "chua len doc";
ASSERT_GT(std::fabs(p1.roll), 0.5 * kDeg) << "chua quay tren doc -- roll khong doi";
EXPECT_LT(AngleBetween(R, FromRPY(p1.roll, p1.pitch, p1.yaw)), 1e-6);
}
TEST(SimImu, TichPhanGiaTocRaDungQuyDao) {
const SimConfig c = RampCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const double dt = 1.0 / c.imu_rate_hz;
const SimPose3 p0 = sim.ground_truth_3d();
M3 R = FromRPY(p0.roll, p0.pitch, p0.yaw);
double pos[3];
ImuPoint(c, p0, pos);
double vel[3] = {0.0, 0.0, 0.0};
sim.mcu()->SetImuCallback([&](ImuPtr m) {
// Tu the lay tu tich phan gyro (da kiem o bai tren la dung).
R = Mul(R, Exp(m->angular_velocity.x * dt, m->angular_velocity.y * dt,
m->angular_velocity.z * dt));
const double f[3] = {m->linear_acceleration.x, m->linear_acceleration.y,
m->linear_acceleration.z};
for (int i = 0; i < 3; ++i) {
double a = R.m[i * 3 + 0] * f[0] + R.m[i * 3 + 1] * f[1] + R.m[i * 3 + 2] * f[2];
if (i == 2) a -= kGravity;
vel[i] += a * dt;
pos[i] += vel[i] * dt;
}
});
sim.mcu()->Open();
sim.base()->Open();
DriveRampAndTurn(&sim);
double truth[3];
ImuPoint(c, sim.ground_truth_3d(), truth);
const double err = std::hypot(std::hypot(pos[0] - truth[0], pos[1] - truth[1]),
pos[2] - truth[2]);
EXPECT_LT(err, 1e-3) << "tich phan IMU lech quy dao that " << err << " m";
EXPECT_GT(truth[2], 0.3) << "phai len doc thi bai nay moi kiem gia toc dung";
}
TEST(SimImu, TanSoPhatThapKhongKeoTheoVatLy) {
// WT61PC that phat 10 Hz. Ha tan so PHAT khong duoc keo LiDAR, encoder va
// buoc vat ly xuong theo.
SimConfig c = FlatCfg();
c.imu_output_hz = 10.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
int imu = 0, scans = 0, enc = 0;
sim.mcu()->SetImuCallback([&](ImuPtr) { imu++; });
sim.lidar()->SetCallback([&](LaserScanPtr) { scans++; });
sim.base()->SetEncoderCallback([&](const EncoderReading&) { enc++; });
sim.mcu()->Open();
sim.lidar()->Open();
sim.base()->Open();
sim.RunFor(2.0);
EXPECT_EQ(imu, 20);
EXPECT_EQ(scans, 50);
EXPECT_EQ(enc, 100);
}
TEST(SimImu, DoTreLaMauCuDungSoBuoc) {
// Tre 0.05 s o buoc 5 ms: mau phat thu j la mau do o buoc j, phat muon 10
// buoc. Hai lan chay giong het nhau (khong nhieu) nen so duoc tung gia tri.
auto run = [](double delay, std::vector<double>* gz) {
SimConfig c = FlatCfg();
c.imu_delay_sec = delay;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.mcu()->SetImuCallback([gz](ImuPtr m) { gz->push_back(m->angular_velocity.z); });
sim.mcu()->Open();
sim.base()->Open();
for (int i = 0; i < 20; ++i) { sim.base()->SetVelocity(0.2, 0.6); sim.RunFor(0.05); }
};
std::vector<double> a, b;
run(0.0, &a);
run(0.05, &b);
ASSERT_EQ(a.size() - b.size(), 10u);
for (size_t j = 0; j < b.size(); ++j) {
ASSERT_EQ(b[j], a[j]) << "mau " << j;
}
}
TEST(SimImu, BiasDauLamLechGyroKhiDungYen) {
SimConfig c = FlatCfg();
c.imu_model = SimConfig::ImuModel::kKinematic;
c.gyro_bias_sigma = 0.01;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
std::vector<double> gz;
sim.mcu()->SetImuCallback([&](ImuPtr m) { gz.push_back(m->angular_velocity.z); });
sim.mcu()->Open();
sim.RunFor(1.0);
ASSERT_FALSE(gz.empty());
// Dung yen, khong nhieu: gyro bang dung bias, va bias khac 0.
EXPECT_GT(std::fabs(gz.back()), 1e-5);
for (double v : gz) EXPECT_EQ(v, gz.back());
}
TEST(SimImu, MacDinhWorldPhangGiuMoHinhCu) {
// kAuto khong co dia hinh = mo hinh cu. Hai lan chay (kAuto, kLegacy) phai
// ra cung tung mau -- dieu kien de ban ghi hoi quy khong doi.
auto run = [](SimConfig::ImuModel model, std::vector<double>* v) {
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.imu_model = model;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.mcu()->SetImuCallback([v](ImuPtr m) {
v->push_back(m->linear_acceleration.x);
v->push_back(m->angular_velocity.z);
});
sim.mcu()->Open();
sim.base()->Open();
for (int i = 0; i < 20; ++i) { sim.base()->SetVelocity(0.3, 0.4); sim.RunFor(0.05); }
};
std::vector<double> a, b;
run(SimConfig::ImuModel::kAuto, &a);
run(SimConfig::ImuModel::kLegacy, &b);
EXPECT_EQ(a, b);
}
TEST(SimGroundTruth, PhatDungTanSoVaKhopTuThe) {
SimSource sim(RampCfg());
ASSERT_TRUE(sim.Open().ok());
int every = 0;
SimPose3 last;
sim.SetGroundTruthCallback([&](UnixTime, const SimPose3& p) { every++; last = p; });
sim.RunFor(1.0);
EXPECT_EQ(every, 200); // moi buoc vat ly
const SimPose3 now = sim.ground_truth_3d();
EXPECT_EQ(last.x, now.x);
EXPECT_EQ(last.z, now.z);
int at25 = 0;
sim.SetGroundTruthCallback([&](UnixTime, const SimPose3&) { at25++; }, 25.0);
sim.RunFor(2.0);
EXPECT_EQ(at25, 50);
}
TEST(SimConfigRobot, LayHinhHocRobotThat) {
RobotModel robot;
ASSERT_TRUE(robot.LoadFile(ConfigSrcDir() + "/robot.yaml").ok());
SimConfig c;
SimConfigFromRobot(robot, &c);
EXPECT_NEAR(c.wheel_radius, robot.geometry().wheel_radius, 1e-12);
EXPECT_NEAR(c.wheel_separation, robot.geometry().wheel_separation, 1e-12);
EXPECT_NEAR(c.camera_z, robot.camera_height_above_floor(), 1e-12);
// LiDAR o 0.2165 m tren SAN: tam truc (r banh) + laser_link z.
EXPECT_NEAR(c.wheel_radius + c.lidar_z, 0.2165, 1e-6);
Transform t;
ASSERT_TRUE(robot.StaticTransform(kBaseLinkFrame, kImuFrame, &t));
EXPECT_NEAR(c.imu_z, t.translation.z, 1e-12);
ASSERT_TRUE(robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t));
EXPECT_NEAR(c.camera_x, t.translation.x, 1e-12);
}

View File

@@ -5,6 +5,7 @@
#include <gtest/gtest.h>
#include <cmath>
#include <cstring>
#include <limits>
#include <vector>
@@ -743,6 +744,37 @@ TEST(SimTilt, TatFollowTerrainThiKhongNghiengTheoDoc) {
EXPECT_NEAR(p, 0.0, 0.02);
}
TEST(SimCamera, KhungCuKhongBiKhungSauGhiDe) {
// SlamLoop giu khung depth moi nhat qua Rtabmap::process (100-600 ms) tren
// luong khac, va BuildSensorData boc cv::Mat quanh bo dem ma khong copy.
// Mot bo dem dung chung thi khung sau ghi de len anh DANG duoc doc -- anh
// luu vao DB la nua khung nay nua khung kia. Moi khung phai co bo dem rieng.
SimSource sim(CamCfg());
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
std::vector<CameraFrame> frames;
std::vector<std::vector<uint8_t>> copies;
sim.camera()->SetCallback([&](const CameraFrame& f) {
frames.push_back(f);
const size_t n = static_cast<size_t>(f.depth->step) * f.depth->height;
copies.emplace_back(f.depth->data, f.depth->data + n);
});
sim.camera()->Open();
// Quay tai cho: moi khung nhin mot huong khac.
for (int i = 0; i < 10; ++i) { sim.base()->SetVelocity(0.0, 0.8); sim.RunFor(0.1); }
ASSERT_GE(frames.size(), 10u);
size_t overwritten = 0;
for (size_t i = 0; i < frames.size(); ++i) {
if (std::memcmp(frames[i].depth->data, copies[i].data(), copies[i].size()) != 0) {
overwritten++;
}
}
EXPECT_EQ(overwritten, 0u) << "anh da phat ra bi khung sau ghi de";
// Cac khung phai khac nhau that (robot dang quay), khong thi bai nay khong
// kiem duoc gi.
EXPECT_NE(copies.front(), copies.back());
}
TEST(SimCamera, CAMERA_NGHIENG_THEO_THAN) {
// Camera gan cung vao than. Than ngoc len thi camera nhin xa hon tren san.
// Day la thu lam `cliff_detect` kho: mat phang san ky vong dich theo tung

311
test/test_sim_terrain.cc Normal file
View File

@@ -0,0 +1,311 @@
// Dia hinh 3D trong bo mo phong: doc, san cao, robot di TREN mat san.
//
// ================== VI SAO BAI KIEM NAY TON TAI ==================
// Truoc day bo mo phong phang hoan toan: robot o z = 0, LiDAR quet mat phang
// ngang, mat doc trong world thanh TUONG. Du an phuc vu robot di giua cac toa
// nha qua doc, va moi phep do tren doc (SLAM, VO, z) deu dua vao viec bo mo
// phong noi dung su that. Bai nay khoa cac su that do bang so tinh tay:
//
// * mat doc la SAN, do cao tai x bang x*tan(goc);
// * vat tren san cao van la vat can; mat ban KHONG thanh san;
// * robot len doc: z = x*tan, pitch = -goc, encoder dem quang duong DOC doc;
// * LiDAR dung o san phang thay "tuong gia" o chan doc cach 0.2165/tan(goc);
// * tich phan gyro bang dung goc nghieng that (khong thi VIO vo nghia);
// * mep bac chan robot.
//
// Fixture: test/data/world/ramp.world -- MOT doc 10 do len san cao 1.5 m.
#include <gtest/gtest.h>
#include <cmath>
#include <cstdlib>
#include <string>
#include <vector>
#include "vslam/gazebo_world.h"
#include "vslam/sim_source.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
constexpr double kH = 1.5; // san tren cua fixture
constexpr double kRampDeg = 10.0;
const double kTan = std::tan(kRampDeg * kDeg);
const double kRampLen = kH / kTan; // 8.507 m
// LiDAR robot that: tam truc + 0.13 m, banh r = 0.0865 m (robot.yaml).
constexpr double kLidarAboveFloor = 0.0865 + 0.13;
std::string WorldDir() {
const char* e = std::getenv("VSLAM_TEST_DATA_DIR");
return (e != nullptr ? std::string(e) : std::string("test/data")) + "/world";
}
GazeboWorld LoadRamp() {
GazeboWorld w;
const StatusResponse st = LoadGazeboWorld(WorldDir() + "/ramp.world",
{WorldDir() + "/models"}, &w);
EXPECT_TRUE(st.ok()) << st.message;
return w;
}
size_t CellOf(const OccupancyGrid& g, double x, double y) {
const int cx = static_cast<int>(std::floor((x - g.origin.position.x) / g.resolution));
const int cy = static_cast<int>(std::floor((y - g.origin.position.y) / g.resolution));
return static_cast<size_t>(cy) * g.width + static_cast<size_t>(cx);
}
double CellCenterX(const OccupancyGrid& g, double x) {
const double c = std::floor((x - g.origin.position.x) / g.resolution);
return g.origin.position.x + (c + 0.5) * g.resolution;
}
SimConfig RampCfg() {
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.world_path = WorldDir() + "/ramp.world";
c.world_model_paths = {WorldDir() + "/models"};
c.wheel_radius = 0.0865;
c.wheel_separation = 0.40;
c.lidar_x = 0.0;
c.lidar_z = 0.13;
c.lidar_noise_stddev = 0.0;
c.gyro_noise_stddev = 0.0;
c.accel_noise_stddev = 0.0;
c.start_x = -2.0;
c.start_y = 0.0;
c.start_yaw = 0.0;
return c;
}
// Lai thang cho toi khi x vuot `x_stop`, hoac het `max_s` giay mo phong.
void DriveUntilX(SimSource* sim, double v, double x_stop, double max_s = 80.0) {
for (double t = 0.0; t < max_s; t += 0.05) {
sim->base()->SetVelocity(v, 0.0);
sim->RunFor(0.05);
if (sim->ground_truth().x >= x_stop) return;
}
}
// Tia thang truoc (goc 0) cua mot scan.
double FrontRange(const LaserScan& s) {
const int i = static_cast<int>(std::lround(-s.angle_min / s.angle_increment));
return s.ranges[static_cast<size_t>(i)];
}
} // namespace
// --- Raster world ------------------------------------------------------------
TEST(GazeboTerrain, DocLaSanKhongPhaiTuong) {
const GazeboWorld w = LoadRamp();
OccupancyGrid g;
WorldTerrain t;
ASSERT_TRUE(RasterizeGazeboWorld(w, WorldRasterOptions{}, &g, &t).ok());
ASSERT_EQ(t.floor_z.size(), static_cast<size_t>(g.width) * g.height);
EXPECT_GT(t.terrain_cells, 0u);
EXPECT_NEAR(t.floor_max, kH, 1e-3);
// Gia tri lay tai TAM o: so voi x tam o, khong voi x hoi.
for (double x : {1.0, 3.0, 5.0, 7.0}) {
const size_t i = CellOf(g, x, 0.0);
EXPECT_NEAR(t.floor_z[i], CellCenterX(g, x) * kTan, 1e-3) << "x = " << x;
EXPECT_LT(g.data[i], 50) << "mat doc thanh VAT CAN o x = " << x;
}
EXPECT_NEAR(t.floor_z[CellOf(g, 10.0, 0.0)], kH, 1e-4);
EXPECT_NEAR(t.floor_z[CellOf(g, -2.0, 0.0)], 0.0, 1e-6);
}
TEST(GazeboTerrain, VatTrenSanCaoVanLaVatCan) {
// Cot z 1.5..2.5 dung tren san cao. Dai z tuyet doi cu [0.05, 1.2] bo no --
// robot se di xuyen qua. Tinh tu san cuc bo thi no la vat can.
const GazeboWorld w = LoadRamp();
OccupancyGrid g;
WorldTerrain t;
ASSERT_TRUE(RasterizeGazeboWorld(w, WorldRasterOptions{}, &g, &t).ok());
const size_t i = CellOf(g, 10.5, 0.0);
EXPECT_GE(g.data[i], 50);
EXPECT_NEAR(t.wall_top[i], 2.5, 1e-3);
}
TEST(GazeboTerrain, MatBanKhongThanhSan) {
// Mat ban huong LEN nhung khong phai dia hinh: van la vat can, san duoi = 0.
const GazeboWorld w = LoadRamp();
OccupancyGrid g;
WorldTerrain t;
ASSERT_TRUE(RasterizeGazeboWorld(w, WorldRasterOptions{}, &g, &t).ok());
const size_t i = CellOf(g, -2.5, 1.0);
EXPECT_GE(g.data[i], 50);
EXPECT_NEAR(t.floor_z[i], 0.0, 1e-6);
}
TEST(GazeboTerrain, WorldPhangRaLuoiNhuCu) {
// World khong co model dia hinh: hai ban ham phai ra CUNG mot luoi -- day la
// dieu kien de ban ghi hoi quy cu khong doi.
GazeboWorld w;
ASSERT_TRUE(LoadGazeboWorld(WorldDir() + "/mini.world", {WorldDir() + "/models"}, &w).ok());
OccupancyGrid a, b;
WorldTerrain t;
ASSERT_TRUE(RasterizeGazeboWorld(w, WorldRasterOptions{}, &a).ok());
ASSERT_TRUE(RasterizeGazeboWorld(w, WorldRasterOptions{}, &b, &t).ok());
EXPECT_EQ(t.terrain_cells, 0u);
ASSERT_EQ(a.width, b.width);
ASSERT_EQ(a.height, b.height);
EXPECT_EQ(a.data, b.data);
}
// --- Bo mo phong -------------------------------------------------------------
TEST(SimTerrain, TuBatKhiWorldCoDiaHinh) {
{
SimSource sim(RampCfg());
ASSERT_TRUE(sim.Open().ok());
EXPECT_TRUE(sim.terrain_active());
}
{
SimConfig c = RampCfg();
c.terrain = SimConfig::TerrainMode::kOff;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
EXPECT_FALSE(sim.terrain_active());
EXPECT_EQ(sim.ground_truth_3d().z, 0.0);
}
}
TEST(SimTerrain, LenDocZVaPitchDung) {
SimSource sim(RampCfg());
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
DriveUntilX(&sim, 0.35, 4.0);
const SimPose3 p = sim.ground_truth_3d();
ASSERT_GE(p.x, 4.0);
EXPECT_NEAR(p.z, p.x * kTan, 0.01);
// Pitch AM = mui ngoc len. Toc do da on dinh, lo xo giam xoc da tat dao dong.
EXPECT_NEAR(p.pitch, -kRampDeg * kDeg, 0.2 * kDeg);
EXPECT_NEAR(p.roll, 0.0, 1e-6);
// Len het doc: san tren phang.
DriveUntilX(&sim, 0.35, kRampLen + 1.0);
const SimPose3 q = sim.ground_truth_3d();
EXPECT_NEAR(q.z, kH, 0.01);
EXPECT_NEAR(q.pitch, 0.0, 0.2 * kDeg);
}
TEST(SimTerrain, EncoderDemQuangDuongDocMatDoc) {
// Banh lan TREN mat doc: encoder dem quang duong doc doc, dai hon quang
// duong ngang 1/cos(goc). Odometry 2D cong thang so nay vao ban do ngang la
// sai 1.5% o 10 do, 15% o 30 do.
SimSource sim(RampCfg());
ASSERT_TRUE(sim.Open().ok());
EncoderReading last;
sim.base()->SetEncoderCallback([&](const EncoderReading& e) { last = e; });
sim.base()->Open();
DriveUntilX(&sim, 0.30, 2.0);
const double x1 = sim.ground_truth().x;
const double e1 = (last.left_rad + last.right_rad) / 2.0;
DriveUntilX(&sim, 0.30, 6.0);
const double x2 = sim.ground_truth().x;
const double e2 = (last.left_rad + last.right_rad) / 2.0;
const double along = (e2 - e1) * 0.0865;
EXPECT_NEAR(along / (x2 - x1), 1.0 / std::cos(kRampDeg * kDeg), 0.003)
<< "doc doc " << along << " m, ngang " << (x2 - x1) << " m";
}
TEST(SimTerrain, LidarThayTuongGiaOChanDoc) {
// Dung o san phang, cach chan doc 1.5 m, nhin vao doc. Tia ngang o
// 0.2165 m cham mat doc o 0.2165 / tan(10 do) = 1.228 m sau chan doc.
SimConfig c = RampCfg();
c.start_x = -1.5;
{
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
LaserScanPtr scan;
sim.lidar()->SetCallback([&](LaserScanPtr s) { scan = s; });
sim.lidar()->Open();
sim.RunFor(0.1);
ASSERT_TRUE(scan != nullptr);
EXPECT_NEAR(FrontRange(*scan), 1.5 + kLidarAboveFloor / kTan, 0.02);
}
{
// Tat dia hinh 3D: LiDAR 2D cu khong thay doc (doc la san), chi thay cot
// tren san cao o x = 10.3.
c.terrain = SimConfig::TerrainMode::kOff;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
LaserScanPtr scan;
sim.lidar()->SetCallback([&](LaserScanPtr s) { scan = s; });
sim.lidar()->Open();
sim.RunFor(0.1);
ASSERT_TRUE(scan != nullptr);
EXPECT_GT(FrontRange(*scan), 5.0);
}
}
TEST(SimTerrain, TichPhanGyroBangGocNghiengThat) {
// Gyro va gia toc ke phai noi CUNG mot chuyen. Truoc day pitch do dia hinh
// vao trong luc nhung khong vao gyro: tich phan gyro bao "chua he nghieng"
// trong khi gia toc ke bao "dang len doc 10 do".
SimConfig c = RampCfg();
c.start_x = -1.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
double integ = 0.0;
const double dt = 1.0 / c.imu_rate_hz;
sim.mcu()->SetImuCallback([&](ImuPtr m) { integ += m->angular_velocity.y * dt; });
sim.mcu()->Open();
sim.base()->Open();
const double p0 = sim.ground_truth_3d().pitch;
DriveUntilX(&sim, 0.35, 2.0);
const double p1 = sim.ground_truth_3d().pitch;
ASSERT_LT(p1, -5.0 * kDeg) << "chua len doc";
EXPECT_NEAR(integ, p1 - p0, 1e-3);
}
TEST(SimTerrain, MepBacChanRobot) {
// Bac cao 0.3 m truoc mat: khong leo duoc, robot dung truoc mep, van o z = 0.
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.terrain = SimConfig::TerrainMode::kOn;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.SetFloorHeight(1.0, -3.0, 3.0, 3.0, 0.3f);
sim.base()->Open();
for (int i = 0; i < 100; ++i) { sim.base()->SetVelocity(0.3, 0.0); sim.RunFor(0.05); }
const SimPose3 p = sim.ground_truth_3d();
EXPECT_LT(p.x, 1.0 - c.robot_radius + 0.05);
EXPECT_NEAR(p.z, 0.0, 1e-6);
EXPECT_GT(sim.stats().collisions, 0u);
}
TEST(SimTerrain, DocTongHopKhongCanWorld) {
// SetFloorRamp: doc tuyen tinh cho bai kiem khong co file world.
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.terrain = SimConfig::TerrainMode::kOn;
c.wheel_separation = 0.40;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
// 15 do: len 0.536 m tren 2 m.
const double tan15 = std::tan(15.0 * kDeg);
sim.SetFloorRamp(1.0, -3.0, 3.0, 3.0, 0.0f, static_cast<float>(2.0 * tan15));
sim.base()->Open();
for (int i = 0; i < 200 && sim.ground_truth().x < 2.0; ++i) {
sim.base()->SetVelocity(0.3, 0.0);
sim.RunFor(0.05);
}
const SimPose3 p = sim.ground_truth_3d();
ASSERT_GE(p.x, 2.0);
EXPECT_NEAR(p.z, (p.x - 1.0) * tan15, 0.01);
EXPECT_NEAR(p.pitch, -15.0 * kDeg, 0.3 * kDeg);
}

405
test/www/test_map_floor.js Normal file
View File

@@ -0,0 +1,405 @@
// Do cao SAN cua ban do SLAM (che do doc): giai khoi FLH1 o app.js, uon mat
// phang ban do va nang scan/cloud/quy dao o app3d.js.
//
// ================== VI SAO CAN BAI KIEM NAY ==================
// Mat phang ban do 2D ve phang o z = 0 trong khi tuong voxel o z that: tren
// tang cao 1.5 m nguoi xem thay tuong lo lung con san "thung" xuong tang duoi.
// Sai mot dau trong phep doi truc cuc bo -> ROS (PlaneGeometry quay -PI/2
// quanh X) thi doc nghieng NGUOC chieu -- van ve duoc, khong mot loi nao.
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const WWW = path.join(__dirname, '..', '..', 'libs', 'vslam_web', 'www');
let bad = 0;
function check(name, cond, chiTiet) {
if (cond) return;
bad++;
console.log(` ${name}: HONG${chiTiet ? ' -- ' + chiTiet : ''}`);
}
const near = (a, b, tol) => a !== null && Math.abs(a - b) <= tol;
// --- Khung ban do y het binary_codec.cc EncodeMapFull ----------------------
// Luoi 2D 0.05 m, 40 x 20 o, mot run duy nhat (toan o trong = 0).
const MAP = { res: 0.05, w: 40, h: 20, ox: -1.0, oy: 2.0 };
// Luoi san 0.2 m phu cung khung: 10 x 5 o. Doc 1 m/1 m theo +x tu cot 2 toi
// cot 7 (z = 0 .. 1.0), san tren 1.5 m o cot 8-9; hang 4 chua biet. Mot HO
// -0.1 m o goc tay-nam (hang 0, cot 0-1) de bat loi lat chieu y.
const FL = { res: 0.2, w: 10, h: 5 };
function floorMm(c, r) {
if (r === 4) return -32768;
if (c >= 8) return 1500;
if (c < 2) return r === 0 ? -100 : 0;
return Math.round((c - 2) * 200); // tam o: doc 45 do de so de doc
}
function mapFrame(withFloor) {
const n = MAP.w * MAP.h;
const runs = Math.ceil(n / 65535);
const tail = withFloor ? 24 + FL.w * FL.h * 2 : 0;
const buf = new ArrayBuffer(16 + 28 + runs * 3 + tail);
const dv = new DataView(buf);
dv.setUint8(0, 0x56); dv.setUint8(1, 0x53); dv.setUint8(2, 0x4C); dv.setUint8(3, 0x31);
dv.setUint8(4, 3);
dv.setUint8(5, 1);
let o = 16;
dv.setFloat32(o, MAP.res, true);
dv.setInt32(o + 4, MAP.w, true);
dv.setInt32(o + 8, MAP.h, true);
dv.setFloat32(o + 12, MAP.ox, true);
dv.setFloat32(o + 16, MAP.oy, true);
dv.setFloat32(o + 20, 0, true);
dv.setUint32(o + 24, runs, true);
o += 28;
dv.setUint16(o, n, true);
dv.setInt8(o + 2, 0);
o += 3;
if (withFloor) {
'FLH1'.split('').forEach((ch, i) => dv.setUint8(o + i, ch.charCodeAt(0)));
dv.setFloat32(o + 4, FL.res, true);
dv.setInt32(o + 8, FL.w, true);
dv.setInt32(o + 12, FL.h, true);
dv.setFloat32(o + 16, MAP.ox, true);
dv.setFloat32(o + 20, MAP.oy, true);
for (let r = 0; r < FL.h; ++r) {
for (let c = 0; c < FL.w; ++c) {
dv.setInt16(o + 24 + (r * FL.w + c) * 2, floorMm(c, r), true);
}
}
}
return dv;
}
// --- Phan 1: app.js giai khoi ----------------------------------------------
const el = () => ({
textContent: '', className: '', value: '', checked: false, style: {},
width: 0, height: 0, clientWidth: 800, clientHeight: 600,
addEventListener() {}, getContext: () => ctx2d(), classList: { toggle() {}, add() {}, remove() {} },
appendChild() {}, querySelectorAll: () => [], getBoundingClientRect: () =>
({ left: 0, top: 0, width: 800, height: 600 }),
});
const ctx2d = () => new Proxy({}, {
get: (t, k) => (k === 'canvas' ? el() : () => ({ data: new Uint8ClampedArray(4) })),
});
const ws = { readyState: 1, send() {} };
const sbApp = {
console, Date, Math, JSON, Set, Map, Number, String, Array, Object,
Float32Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
DataView, ArrayBuffer, isNaN, parseFloat, parseInt,
document: {
getElementById: () => el(), querySelectorAll: () => [], querySelector: () => el(),
addEventListener() {}, createElement: () => el(), body: el(), documentElement: el(),
},
window: { addEventListener() {}, devicePixelRatio: 1, location: { search: '', host: 'x' } },
location: { search: '', host: 'x', protocol: 'http:' },
navigator: { userAgent: 'node' },
requestAnimationFrame: () => 0,
setInterval: () => 0, setTimeout: () => 0, clearTimeout: () => 0,
fetch: () => new Promise(() => {}),
URLSearchParams: class { constructor() {} get() { return null; } },
WebSocket: function () { return ws; },
performance: { now: () => 0 },
// rasterize() cua app.js dung ImageData khi nhan khung ban do.
ImageData: function (w, h) { this.width = w; this.height = h;
this.data = new Uint8ClampedArray(w * h * 4); },
};
sbApp.globalThis = sbApp;
vm.createContext(sbApp);
try {
vm.runInContext(fs.readFileSync(path.join(WWW, 'app.js'), 'utf8'), sbApp, { filename: 'app.js' });
} catch (e) {
console.log(' (app.js dung som: ' + e.message + ')');
}
let state = null;
try { state = vm.runInContext('state', sbApp); } catch (e) { /* bao o duoi */ }
if (typeof sbApp.onBinary !== 'function' || !state) {
console.log(' KHONG lay duoc onBinary/state tu app.js\n\n => HONG');
process.exit(1);
}
sbApp.onBinary(mapFrame(true));
const g = state.map;
check('giai: co ban do', g && g.w === MAP.w && g.h === MAP.h);
const f = g && g.floor;
check('giai: co khoi san', f && f.w === FL.w && f.h === FL.h, JSON.stringify(f && { w: f.w, h: f.h }));
if (f) {
check('giai: res/goc', Math.abs(f.res - 0.2) < 1e-6 && Math.abs(f.ox - MAP.ox) < 1e-6 &&
Math.abs(f.oy - MAP.oy) < 1e-6);
check('giai: san tren', f.mm[2 * FL.w + 9] === 1500, String(f.mm[2 * FL.w + 9]));
check('giai: o chua biet', f.mm[4 * FL.w + 3] === -32768, String(f.mm[4 * FL.w + 3]));
}
// Luoi 2D khong bi khoi phia sau lam lech.
check('giai: o 2D dung', g && g.cells.every((v) => v === 0));
sbApp.onBinary(mapFrame(false));
check('khong khoi: floor = null', state.map && state.map.floor === null);
// --- Phan 2: app3d.js uon mat phang + nang scan/cloud/quy dao --------------
class V3 {
constructor(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; }
set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }
}
const node = () => ({ position: new V3(), rotation: { x: 0, y: 0, z: 0 }, userData: {},
visible: true });
class Attr {
constructor(a, n) { this.array = a; this.itemSize = n; this.count = a.length / n; }
getX(i) { return this.array[i * 3]; }
getY(i) { return this.array[i * 3 + 1]; }
setZ(i, v) { this.array[i * 3 + 2] = v; }
}
// Bo cuc dinh y het three.js PlaneGeometry: hang tu +h/2 xuong -h/2, cot tu
// -w/2 sang +w/2, mat phang z = 0.
class PlaneGeometry {
constructor(w, h, sx = 1, sy = 1) {
const a = [];
for (let iy = 0; iy <= sy; ++iy) {
for (let ix = 0; ix <= sx; ++ix) a.push(ix * w / sx - w / 2, -(iy * h / sy - h / 2), 0);
}
this.attributes = { position: new Attr(new Float32Array(a), 3) };
}
dispose() {}
}
class BufferGeometry {
constructor() { this.attributes = {}; }
setAttribute(n, a) { this.attributes[n] = a; }
setFromPoints(p) { this.points = p; return this; }
dispose() {}
}
const obj = () => class {
constructor(g, m) { Object.assign(this, node()); this.geometry = g; this.material = m; }
};
const THREE = {
PlaneGeometry, BufferGeometry, Vector3: V3,
BufferAttribute: class { constructor(a, n) { this.array = a; this.itemSize = n; } },
Mesh: obj(), Points: obj(), Line: obj(),
MeshBasicMaterial: class { constructor(o) { Object.assign(this, o); } dispose() {} },
PointsMaterial: class { constructor(o) { Object.assign(this, o); } },
LineBasicMaterial: class { constructor(o) { Object.assign(this, o); } },
CanvasTexture: class { dispose() {} },
NearestFilter: 1, LinearMipmapLinearFilter: 2,
};
class Root {
constructor() { this.children = []; }
add(c) { this.children.push(c); }
remove(c) { this.children = this.children.filter((x) => x !== c); }
}
const canvas = () => ({
width: 0, height: 0,
getContext: () => ({
createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }),
putImageData() {},
}),
});
const sb3 = { THREE, console, Math, Int16Array, Int32Array, Float32Array,
window: {}, document: { createElement: canvas } };
vm.createContext(sb3);
vm.runInContext(fs.readFileSync(path.join(WWW, 'app3d.js'), 'utf8') +
'\n;this.__V3D = V3D; this.__at = v3dFloorAt; this.__fill = v3dFloorFill;' +
'\n;this.__map = v3dSetMap; this.__scan = v3dSetScan; this.__cloud = v3dSetCloud;' +
'\n;this.__path = v3dSetPath; this.__render = v3dRender; this.__lift = FLOOR_LIFT;' +
'\n;this.__worldVis = v3dSetWorldVisible; this.__ground = v3dSetGround;', sb3);
const V3D = sb3.__V3D;
V3D.ready = true;
V3D.root = new Root();
const L = sb3.__lift; // mat ban do uon nang len tren san uoc luong
check('nang: 2-10 cm', L >= 0.02 && L <= 0.1, String(L));
// v3dFloorAt: tam o tra dung gia tri o; giua hai tam noi suy tuyen tinh.
{
const fl = f;
const cx = (c) => MAP.ox + (c + 0.5) * 0.2, cy = (r) => MAP.oy + (r + 0.5) * 0.2;
check('at: tam o san duoi', near(sb3.__at(fl, cx(0), cy(1)), 0.0, 1e-6));
check('at: tam o san tren', near(sb3.__at(fl, cx(9), cy(1)), 1.5, 1e-6));
// Giua tam cot 4 (0.4) va cot 5 (0.6) -> 0.5.
check('at: noi suy tren doc', near(sb3.__at(fl, cx(4) + 0.1, cy(1)), 0.5, 1e-6),
String(sb3.__at(fl, cx(4) + 0.1, cy(1))));
// Chi o chua biet -> null (khong phai 0).
check('at: chua biet = null', sb3.__at(fl, cx(3), cy(4)) === null,
String(sb3.__at(fl, cx(3), cy(4))));
check('at: ngoai luoi = null', sb3.__at(fl, MAP.ox - 5, cy(1)) === null);
check('at: khong co luoi = null', sb3.__at(null, 0, 0) === null);
// Lap o chua biet bang o DA BIET gan nhat: hang 4 lay hang 3.
const filled = sb3.__fill(fl);
check('fill: khong con o chua biet', filled && filled.mm.every((v) => v !== -32768));
check('fill: lay o ke', filled && filled.mm[4 * FL.w + 9] === 1500 &&
filled.mm[4 * FL.w + 4] === 400, filled && String(filled.mm.slice(40)));
check('fill: khong dong vao luoi goc', fl.mm[4 * FL.w + 9] === -32768);
}
// v3dSetMap: dinh mat phang o dung cao do san, dung chieu doc.
{
sb3.__map({ ...g, data: g.cells, floor: f });
const m = V3D.mapMesh;
check('map: co mesh', !!m);
if (m) {
check('map: quay -PI/2 quanh X', Math.abs(m.rotation.x + Math.PI / 2) < 1e-9);
const p = m.geometry.attributes.position;
check('map: chia doan theo luoi san', p.count === (FL.w + 1) * (FL.h + 1), String(p.count));
// Dinh cuc bo -> ROS: x = pos.x + lx, y = -pos.z + ly, z = pos.y + lz.
const ros = (i) => [m.position.x + p.getX(i), -m.position.z + p.getY(i),
m.position.y + p.array[i * 3 + 2]];
const zAt = (qx, qy) => {
for (let i = 0; i < p.count; ++i) {
const [x, y, z] = ros(i);
if (Math.abs(x - qx) < 1e-4 && Math.abs(y - qy) < 1e-4) return z;
}
return null;
};
let maxEast = -1e9, maxWest = -1e9;
for (let i = 0; i < p.count; ++i) {
const [x, , z] = ros(i);
if (x > MAP.ox + 1.9) maxEast = Math.max(maxEast, z);
if (x < MAP.ox + 0.1) maxWest = Math.max(maxWest, z);
}
// Ca mat nang L tren san uoc luong (khong chim duoi mesh san that).
check('map: nang L', Math.abs(m.position.y - L) < 1e-9, String(m.position.y));
check('map: co co mapHasFloor', V3D.mapHasFloor === true);
// Chieu x: mep dong (cot 9, san tren) ~1.5; mep tay (san duoi) ~0.
check('map: mep dong o san tren', Math.abs(maxEast - (1.5 + L)) < 0.01, String(maxEast));
check('map: mep tay o san duoi', Math.abs(maxWest - L) < 0.01, String(maxWest));
// Chieu y: ho o goc tay-NAM (y nho), goc tay-BAC phang.
const sw = zAt(MAP.ox, MAP.oy), nw = zAt(MAP.ox, MAP.oy + 1.0);
check('map: ho o goc tay-nam', near(sw, -0.1 + L, 1e-3), String(sw));
check('map: goc tay-bac phang', near(nw, L, 1e-3), String(nw));
// Dinh tai x = ox + 1.0 (ranh cot 4|5) tren hang giua: (0.4 + 0.6) / 2.
const mid = zAt(MAP.ox + 1.0, MAP.oy + 0.4);
check('map: dinh giua doc', near(mid, 0.5 + L, 1e-3), String(mid));
}
// Cung mang o -> khong dung lai; mang moi -> dung lai.
const truoc = V3D.mapMesh;
sb3.__map({ ...g, data: g.cells, floor: f });
check('map: cung du lieu khong dung lai', V3D.mapMesh === truoc);
sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null });
check('map: du lieu moi dung lai', V3D.mapMesh !== truoc);
const pf = V3D.mapMesh.geometry.attributes.position;
check('map: khong san -> phang', pf.count === 4 &&
[0, 1, 2, 3].every((i) => pf.array[i * 3 + 2] === 0));
// Ban do phang giu nguyen cao do cu (duoi luoi va vanh cliff).
check('map: khong san -> y cu', V3D.mapMesh.position.y === -0.002 && V3D.mapHasFloor === false,
String(V3D.mapMesh.position.y));
}
// Scan/cloud nang theo cao do san duoi robot; quy dao theo luoi san.
{
const r = { laser_x: 0.24, laser_y: 0, laser_z: 0.1415, wheel_radius: 0.075 };
sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 1.5 }, r);
const sy = V3D.scanPts.geometry.attributes.position.array[1];
check('scan: nang theo z', Math.abs(sy - (1.5 + 0.1415 + 0.075)) < 1e-6, String(sy));
sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0 }, r);
const sy0 = V3D.scanPts.geometry.attributes.position.array[1];
check('scan: khong z -> nhu cu', Math.abs(sy0 - (0.1415 + 0.075)) < 1e-6, String(sy0));
sb3.__cloud(new Float32Array([1.0, 0.0, 0.3]), { x: 0, y: 0, yaw: 0, z: 1.5 });
const cy = V3D.cloudPts.geometry.attributes.position.array[1];
check('cloud: nang theo z', Math.abs(cy - 1.8) < 1e-6, String(cy));
// Scan THO nghieng theo than: doc 15 do mui NGANG len (pitch ROS am).
// Diem 1 m truoc LiDAR: he footprint (1.24, 0, 0.2165) quay Ry(-15 do).
const P = -15 * Math.PI / 180;
sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 0.5, pitch: P }, r);
const a = V3D.scanPts.geometry.attributes.position.array;
const ex = 1.24 * Math.cos(P) + 0.2165 * Math.sin(P);
const ez = -1.24 * Math.sin(P) + 0.2165 * Math.cos(P);
check('scan: pitch keo diem truoc len', Math.abs(a[0] - ex) < 1e-6 && Math.abs(a[1] - (0.5 + ez)) < 1e-6,
a[0] + ', ' + a[1]);
// Roll +10 do (ROS: ben TRAI len): diem 1 m ben trai cao hon goc LiDAR.
const R = 10 * Math.PI / 180;
sb3.__scan(new Float32Array([0.0, 1.0]), { x: 0, y: 0, yaw: 0, roll: R }, r);
const b = V3D.scanPts.geometry.attributes.position.array;
check('scan: roll keo ben trai len',
Math.abs(b[1] - (Math.sin(R) + 0.2165 * Math.cos(R))) < 1e-6 &&
Math.abs(b[2] + (Math.cos(R) - 0.2165 * Math.sin(R))) < 1e-6, b[1] + ', ' + b[2]);
const cx = (c) => MAP.ox + (c + 0.5) * 0.2, yy = MAP.oy + 0.3;
sb3.__path([cx(0), yy, cx(9), yy], f);
const pts = V3D.pathLine.geometry.points;
// Tren mat ban do uon (nang L) 1 cm.
check('path: diem san duoi', pts && Math.abs(pts[0].y - (L + 0.01)) < 1e-6,
pts && String(pts[0].y));
check('path: diem san tren', pts && Math.abs(pts[1].y - (1.5 + L + 0.01)) < 1e-6,
pts && String(pts[1].y));
sb3.__path([cx(0), yy, cx(9), yy], null);
const pts0 = V3D.pathLine.geometry.points;
check('path: khong luoi -> 0.01 nhu cu', pts0 && pts0.every((q) => Math.abs(q.y - 0.01) < 1e-9));
}
// v3dRender: tam quay bam CAO DO robot khi "bam robot"; nua SLAM an mat san
// the gioi khi ban do co do cao san.
{
const calls = [];
V3D.floorMesh = { visible: true };
V3D.renderer = {
setSize() {}, setScissorTest() {}, setViewport() {}, setScissor() {},
render() { calls.push(V3D.floorMesh.visible); },
};
V3D.camera = { aspect: 1, updateProjectionMatrix() {}, position: new V3(),
lookAt(x, y, z) { this.look = [x, y, z]; } };
V3D.robotGroup = { position: new V3(2, 1.5, -3) };
const cv = { clientWidth: 800, clientHeight: 600, width: 800, height: 600 };
const o = V3D.orbit;
sb3.__map({ ...g, data: new Int8Array(g.cells), floor: f }); // co san
sb3.__render(cv, true, true);
check('render: tam quay o cao do robot', Math.abs(V3D.camera.look[1] - 1.7) < 1e-9,
String(V3D.camera.look));
check('render: camera nang theo robot',
Math.abs(V3D.camera.position.y - (1.5 + o.dist * Math.sin(o.el))) < 1e-9);
check('render: nua the gioi CO san, nua SLAM KHONG', calls.length === 2 && calls[0] === true &&
calls[1] === false, JSON.stringify(calls));
check('render: tra lai san sau khi ve', V3D.floorMesh.visible === true);
calls.length = 0;
sb3.__render(cv, false, true);
check('render: khong bam -> tam quay 0.2 nhu cu', Math.abs(V3D.camera.look[1] - 0.2) < 1e-9,
String(V3D.camera.look));
// Tat "the gioi": ban do co san -> an mat san z = 0; bat lai -> hien.
sb3.__worldVis(false);
check('tat the gioi + co san -> an mat san', V3D.floorMesh.visible === false);
sb3.__worldVis(true);
check('bat the gioi -> hien mat san', V3D.floorMesh.visible === true);
calls.length = 0;
sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null }); // ban do phang
sb3.__render(cv, false, true);
check('render: ban do phang -> nua SLAM van co san', calls[1] === true, JSON.stringify(calls));
sb3.__worldVis(false);
check('tat the gioi + ban do phang -> giu mat san nhu cu', V3D.floorMesh.visible === true);
}
// v3dSetGround: duoc goi MOI khung khi chay tu `.world`. Cung luoi -> KHONG
// dung lai (ban cu dung lai moi khung va ro GridHelper tren GPU); luoi moi ->
// dung lai va giai phong ca geometry lan material cu.
{
let disposed = 0;
const disp = () => { disposed++; };
THREE.GridHelper = class {
constructor() { Object.assign(this, node()); this.geometry = { dispose: disp };
this.material = { dispose: disp }; }
};
THREE.MeshStandardMaterial = class { constructor(o) { Object.assign(this, o); } dispose() { disp(); } };
V3D.scene = { fog: { near: 0, far: 0 } };
V3D.floorMesh = null;
V3D.gridHelper = null;
const wg = { res: 0.05, w: 400, h: 600, ox: -1, oy: -2 };
sb3.__ground(wg);
const f1 = V3D.floorMesh, g1 = V3D.gridHelper;
const n0 = V3D.root.children.length;
for (let i = 0; i < 100; ++i) sb3.__ground(wg);
check('ground: cung luoi khong dung lai', V3D.floorMesh === f1 && V3D.gridHelper === g1 &&
disposed === 0, String(disposed));
check('ground: root khong phinh', V3D.root.children.length === n0);
check('ground: suong mu theo bao the gioi', Math.abs(V3D.scene.fog.far - 30 * 1.4) < 1e-9,
String(V3D.scene.fog.far));
f1.geometry.dispose = disp;
sb3.__ground({ ...wg, w: 500 });
check('ground: luoi moi dung lai', V3D.floorMesh !== f1 && V3D.gridHelper !== g1);
check('ground: giai phong san + luoi cu (geometry + material)', disposed === 4, String(disposed));
check('ground: root van 1 san 1 luoi', V3D.root.children.length === n0 &&
!V3D.root.children.includes(f1) && !V3D.root.children.includes(g1));
}
console.log(bad ? '\n => HONG' : '\n => DAT');
process.exit(bad ? 1 : 0);

View File

@@ -50,6 +50,16 @@ if(VSLAM_BUILD_SLAM)
add_executable(vslam_pnp_eval vslam_pnp_eval.cc)
target_link_libraries(vslam_pnp_eval PRIVATE vslam_slam vslam_common)
# vslam_vo_bench: odometry thi giac RTAB-Map (F2M) tren anh IR + depth cua
# .vsr -> quy dao TUM. Cham z tren doc (G3), bo tham so RIENG, khong ke
# thua slam.yaml (ICP + Force3DoF lam mat z).
# Hang tham chieu ds*sin(pitch) dung GravityAlign cua vslam_perception.
if(VSLAM_BUILD_DRIVERS AND VSLAM_BUILD_PERCEPTION)
add_executable(vslam_vo_bench vslam_vo_bench.cc)
target_link_libraries(vslam_vo_bench
PRIVATE vslam_slam vslam_perception vslam_drivers vslam_common)
endif()
# vslam_vpr_check: doi chieu VPR TensorRT (C++) voi PyTorch -- chi khi co TensorRT.
if(VSLAM_WITH_TENSORRT)
add_executable(vslam_vpr_check vslam_vpr_check.cc)
@@ -57,12 +67,37 @@ if(VSLAM_BUILD_SLAM)
endif()
endif()
# vslam_render_preview: ve MOT khung camera mo phong bang GPU ra PNG, de nhin
# texture/depth truoc khi tin. Chi khi co lib tuy chon vslam_sim_gl.
if(TARGET vslam_sim_gl)
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs)
add_executable(vslam_render_preview vslam_render_preview.cc)
target_include_directories(vslam_render_preview SYSTEM PRIVATE ${OpenCV_INCLUDE_DIRS})
target_link_libraries(vslam_render_preview
PRIVATE vslam_sim_gl vslam_sim vslam_common ${OpenCV_LIBS})
endif()
# vslam_record: ghi .vsr tu bo mo phong theo kich ban co ten. Hat giong co
# dinh => cung kich ban cho cung file, byte giong byte -- dieu kien de
# regress.sh so ket qua duoc.
if(VSLAM_BUILD_SIM AND VSLAM_BUILD_DRIVERS)
add_executable(vslam_record vslam_record.cc)
target_link_libraries(vslam_record PRIVATE vslam_sim vslam_drivers vslam_common)
# --gl: ve camera bang GPU khi co lib tuy chon.
if(TARGET vslam_sim_gl)
target_link_libraries(vslam_record PRIVATE vslam_sim_gl)
target_compile_definitions(vslam_record PRIVATE VSLAM_HAVE_SIM_GL=1)
endif()
# vslam_vsr_export: .vsr (anh IR + IMU + su that) -> thu muc dataset cho
# DM-VIO. Lam xau IMU (ha tan so, lech gio, nhieu) o buoc nay, khong ghi lai.
# Can OpenCV de ghi PNG; build khong co OpenCV thi bo qua tool nay.
find_package(OpenCV QUIET COMPONENTS core imgcodecs)
if(OpenCV_FOUND)
add_executable(vslam_vsr_export vslam_vsr_export.cc)
target_include_directories(vslam_vsr_export SYSTEM PRIVATE ${OpenCV_INCLUDE_DIRS})
target_link_libraries(vslam_vsr_export PRIVATE vslam_drivers vslam_common ${OpenCV_LIBS})
endif()
endif()
# vslam_replay: phat lai .vsr qua TOAN BO duong ong roi xuat JSON phang.
@@ -89,6 +124,13 @@ add_executable(vslam_lidar_probe vslam_lidar_probe.cc)
# duoc tren may chi co tay cam cam vao, truoc khi build ca cay.
add_executable(vslam_joy_probe vslam_joy_probe.cc)
# vslam_imu_config: doc / doi baud va tan so phat cua IMU WT61PC qua CHINH cong
# serial (lenh WitMotion: mo khoa -> ghi -> luu), khong can phan mem cua hang.
if(VSLAM_BUILD_DRIVERS)
add_executable(vslam_imu_config vslam_imu_config.cc)
target_link_libraries(vslam_imu_config PRIVATE vslam_drivers vslam_common)
endif()
# vslam_world_export: `.world` cua Gazebo -> luoi chiem dung .pgm + .yaml.
#
# Cho phep dung the gioi mo phong TU CHINH file world, thay vi tu mot .db da

267
tools/gen_slope_world.py Normal file
View File

@@ -0,0 +1,267 @@
#!/usr/bin/env python3
"""Sinh world mo phong co DOC: resources/worlds/slope_test.world + hai model.
Bo cuc (nhin tu tren xuong, x sang phai, y len tren; met):
y=33.5 +--------------------------------------------------+
| SANH TREN (san cao H = 1.5 m) |
y=25.5 +---------+---------+---------+---------+----------+
| 5 do | 10 do | 15 do | 20 do | 30 do |
| | | | | | lan rong 2.4 m,
| doc | doc | doc | doc | doc | ngan boi tuong
| dai | | | | ngan | 0.2 m
y=8 +---------+---------+---------+---------+----------+
| SANH DUOI (z = 0) |
y=0 +--------------------------------------------------+
x=0 x=12.8
Moi lan: doc bat dau o y = 8 (z = 0) va len toi H, roi di phang o H toi sanh
tren. Nam doc CUNG noi hai mat bang, nen di len lan nay xuong lan kia la mot
vong khep kin -- dung thu SLAM can thu: khep vong ca x, y LAN z.
Do dai doc = H / tan(goc): 17.1 m (5 do), 8.5 (10), 5.6 (15), 4.1 (20),
2.6 m (30 do).
Model `vslam_terrain_slope_test` la DIA HINH: bo mo phong coi mat cua no la
SAN robot di len, khong phai vat can (xem libs/vslam_sim/include/vslam/
gazebo_world.h, `kTerrainModelPrefix`). Mesh co toa do texture (vt) theo met,
de giai doan render GPU dan texture ma khong phai sinh lai.
Do dac co texture lay tu ~/gazebo_models/aws_hospital_fuel; thieu thi bo doc
world bo qua (khong loi), chi mat vai vat cho camera bam.
Chay tu goc repo:
python3 tools/gen_slope_world.py
export GAZEBO_MODEL_PATH=$PWD/resources/models
./build/app/vslam_node --sim --world resources/worlds/slope_test.world \\
--x 6.4 --y 4 --yaw 1.5708 --token t
"""
import argparse
import math
import os
H = 1.5 # chenh hai mat bang, m
ANGLES = [5, 10, 15, 20, 30] # do, tu trai sang phai
LANE_W = 2.4 # be rong long lan
WALL_T = 0.2 # be day tuong
HALL_D = 8.0 # chieu sau moi sanh
LANE_LEN = 17.5 # chieu dai lan (>= doc 5 do dai nhat)
WALL_H = H + 2.5 # tuong cao toi day, du che ca tang tren
XI = len(ANGLES) * LANE_W + (len(ANGLES) - 1) * WALL_T # be rong long nha
Y_LANE0 = HALL_D
Y_LANE1 = HALL_D + LANE_LEN
Y_TOP = Y_LANE1 + HALL_D
TERRAIN = 'vslam_terrain_slope_test'
WALLS = 'vslam_slope_test_walls'
# Do dac co texture: (model, x, y, z, yaw). Chi dat sat tuong dau/cuoi va o
# KHE GIUA cac duong vao lan (tam lan x = 1.2, 3.8, 6.4, 9.0, 11.6, moi ben
# 0.6 m) -- dat chan duong vao lan nao la lan do khong chay thu duoc: lop an
# toan dung xe truoc khi toi doc (da mac: xe lan o (12.0, 6.6) chan lan 30 do).
FURNITURE = [
('MetalCabinet', 0.6, 1.0, 0.0, 0.0),
('StorageRack', 3.0, 0.6, 0.0, 0.0),
('IVStand', 5.1, 1.0, 0.0, 0.0),
('PatientWheelChair', 7.7, 1.0, 0.0, 0.0),
('BedTable', 9.5, 0.8, 0.0, 0.0),
('VendingMachine', 12.1, 1.2, 0.0, -math.pi / 2),
('MetalCabinet', 0.6, 32.6, H, 0.0),
('IVStand', 5.1, 32.8, H, 0.0),
('StorageRack', 6.4, 32.9, H, math.pi),
('BedTable', 11.8, 32.6, H, 0.0),
]
class Obj:
"""Mesh OBJ: Z-up, met. Mat huong LEN khi dinh di nguoc kim dong ho tu tren."""
def __init__(self, header):
self.lines = ['# ' + l for l in header.splitlines()]
self.nv = 0
def quad(self, p, uv=None):
"""p: 4 dinh (x, y, z) theo thu tu vong. uv mac dinh = (x, y) met."""
base = self.nv
for i, (x, y, z) in enumerate(p):
self.lines.append('v %.4f %.4f %.4f' % (x, y, z))
u, w = uv[i] if uv else (x, y)
self.lines.append('vt %.4f %.4f' % (u, w))
self.nv += 4
a, b, c, d = (base + k + 1 for k in range(4))
self.lines.append('f %d/%d %d/%d %d/%d' % (a, a, b, b, c, c))
self.lines.append('f %d/%d %d/%d %d/%d' % (a, a, c, c, d, d))
def box(self, x0, y0, z0, x1, y1, z1):
"""Hop kin, mat huong RA ngoai. uv cua mat dung theo (doc tuong, z)."""
self.quad([(x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)]) # tren
self.quad([(x0, y1, z0), (x1, y1, z0), (x1, y0, z0), (x0, y0, z0)]) # day
self.quad([(x0, y0, z0), (x1, y0, z0), (x1, y0, z1), (x0, y0, z1)],
[(x0, z0), (x1, z0), (x1, z1), (x0, z1)]) # -y
self.quad([(x1, y1, z0), (x0, y1, z0), (x0, y1, z1), (x1, y1, z1)],
[(x1, z0), (x0, z0), (x0, z1), (x1, z1)]) # +y
self.quad([(x0, y1, z0), (x0, y0, z0), (x0, y0, z1), (x0, y1, z1)],
[(y1, z0), (y0, z0), (y0, z1), (y1, z1)]) # -x
self.quad([(x1, y0, z0), (x1, y1, z0), (x1, y1, z1), (x1, y0, z1)],
[(y0, z0), (y1, z0), (y1, z1), (y0, z1)]) # +x
def text(self):
return '\n'.join(self.lines) + '\n'
def lane_x(i):
x0 = i * (LANE_W + WALL_T)
return x0, x0 + LANE_W
def terrain_mesh():
m = Obj('Dia hinh world doc: san duoi z=0, san tren z=%.2f, %d lan doc.\n'
'Z-UP, met. Sinh boi tools/gen_slope_world.py -- dung sua tay.'
% (H, len(ANGLES)))
m.quad([(0, 0, 0), (XI, 0, 0), (XI, Y_LANE0, 0), (0, Y_LANE0, 0)])
m.quad([(0, Y_LANE1, H), (XI, Y_LANE1, H), (XI, Y_TOP, H), (0, Y_TOP, H)])
for i, deg in enumerate(ANGLES):
x0, x1 = lane_x(i)
y_top = Y_LANE0 + H / math.tan(math.radians(deg))
m.quad([(x0, Y_LANE0, 0), (x1, Y_LANE0, 0), (x1, y_top, H), (x0, y_top, H)])
if y_top < Y_LANE1 - 1e-6:
m.quad([(x0, y_top, H), (x1, y_top, H), (x1, Y_LANE1, H), (x0, Y_LANE1, H)])
return m.text()
def walls_mesh():
m = Obj('Tuong va cot cua world doc. Z-UP, met.\n'
'Sinh boi tools/gen_slope_world.py -- dung sua tay.')
t = WALL_T
# Vong ngoai.
m.box(-t, -t, 0, 0, Y_TOP + t, WALL_H)
m.box(XI, -t, 0, XI + t, Y_TOP + t, WALL_H)
m.box(-t, -t, 0, XI + t, 0, WALL_H)
m.box(-t, Y_TOP, 0, XI + t, Y_TOP + t, WALL_H)
# Tuong ngan lan.
for i in range(len(ANGLES) - 1):
_, x1 = lane_x(i)
m.box(x1, Y_LANE0, 0, x1 + t, Y_LANE1, WALL_H)
# Vai cot va mau tuong de LiDAR co cho bam trong hai sanh rong. Dat o KHE
# giua cac duong vao/ra lan (xem FURNITURE), khong chan lan nao.
m.box(2.3, 3.8, 0, 2.7, 4.2, WALL_H)
m.box(10.1, 3.8, 0, 10.5, 4.2, WALL_H)
m.box(4.6, 5.0, 0, 5.6, 5.2, WALL_H)
m.box(4.9, 29.3, H, 5.3, 29.7, WALL_H)
m.box(7.5, 29.3, H, 7.9, 29.7, WALL_H)
m.box(9.7, 30.5, H, 10.9, 30.7, WALL_H)
return m.text()
SDF = '''<?xml version="1.0" ?>
<sdf version="1.6">
<model name="{name}">
<link name="link">
<visual name="visual">
<geometry>
<mesh>
<uri>model://{name}/meshes/{mesh}</uri>
</mesh>
</geometry>
</visual>
<collision name="collision">
<geometry>
<mesh>
<uri>model://{name}/meshes/{mesh}</uri>
</mesh>
</geometry>
</collision>
</link>
<static>1</static>
</model>
</sdf>
'''
CONFIG = '''<?xml version="1.0" ?>
<model>
<name>{name}</name>
<version>1.0</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>vslam_cpp</name>
<email></email>
</author>
<description>
{desc}
Sinh boi tools/gen_slope_world.py.
</description>
</model>
'''
def include(name, uri, x, y, z, yaw):
return (' <model name="%s">\n'
' <include>\n'
' <uri>model://%s</uri>\n'
' <static>true</static>\n'
' <pose>%.3f %.3f %.3f 0 0 %.4f</pose>\n'
' </include>\n'
' </model>\n' % (name, uri, x, y, z, yaw))
def world_text():
parts = ['<?xml version="1.0" ?>\n',
'<!-- World co DOC cho mo phong dia hinh 3D. Sinh boi\n'
' tools/gen_slope_world.py -- dung sua tay.\n'
' Xuat phat goi y: --x 6.4 --y 4 --yaw 1.5708 (sanh duoi, nhin\n'
' vao lan 15 do). Lan doc theo x: ',
', '.join('%d do o x = %.1f' % (d, sum(lane_x(i)) / 2)
for i, d in enumerate(ANGLES)),
'. -->\n',
'<sdf version="1.6">\n <world name="slope_test">\n',
' <include><uri>model://ground_plane</uri></include>\n',
' <include><uri>model://sun</uri></include>\n',
include(TERRAIN + '_1', TERRAIN, 0, 0, 0, 0),
include(WALLS + '_1', WALLS, 0, 0, 0, 0)]
count = {}
for name, x, y, z, yaw in FURNITURE:
count[name] = count.get(name, 0) + 1
parts.append(include('%s_%d' % (name, count[name]), name, x, y, z, yaw))
parts.append(' </world>\n</sdf>\n')
return ''.join(parts)
def write(path, text):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as f:
f.write(text)
print('ghi', path)
def main():
here = os.path.dirname(os.path.abspath(__file__))
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--root', default=os.path.dirname(here),
help='goc repo (mac dinh: thu muc cha cua tools/)')
a = ap.parse_args()
models = os.path.join(a.root, 'resources', 'models')
write(os.path.join(models, TERRAIN, 'meshes', 'terrain.obj'), terrain_mesh())
write(os.path.join(models, TERRAIN, 'model.sdf'),
SDF.format(name=TERRAIN, mesh='terrain.obj'))
write(os.path.join(models, TERRAIN, 'model.config'),
CONFIG.format(name=TERRAIN, desc='San, chieu nghi va 5 lan doc (dia hinh).'))
write(os.path.join(models, WALLS, 'meshes', 'walls.obj'), walls_mesh())
write(os.path.join(models, WALLS, 'model.sdf'),
SDF.format(name=WALLS, mesh='walls.obj'))
write(os.path.join(models, WALLS, 'model.config'),
CONFIG.format(name=WALLS, desc='Tuong bao, tuong ngan lan va cot.'))
write(os.path.join(a.root, 'resources', 'worlds', 'slope_test.world'), world_text())
for i, deg in enumerate(ANGLES):
x0, x1 = lane_x(i)
print('lan %2d do: x %.1f-%.1f, doc dai %.2f m, chan doc y = %.1f, '
'tuong gia o chan doc cach %.2f m' %
(deg, x0, x1, H / math.tan(math.radians(deg)), Y_LANE0,
0.2165 / math.tan(math.radians(deg))))
if __name__ == '__main__':
main()

165
tools/slope_bakeoff.sh Executable file
View File

@@ -0,0 +1,165 @@
#!/usr/bin/env bash
# So tai nguon z tren doc (G3): tham chieu ds*sin(pitch), F2M (RTAB-Map),
# DM-VIO -- tren cac ban ghi doc cua `vslam_record --scenario slope_all --gl`.
#
# tools/slope_bakeoff.sh DS_DIR OUT_DIR [kich_ban ...]
#
# DS_DIR chua slope_*.vsr. Can build co vslam_vo_bench, vslam_vsr_export;
# DM-VIO build NGOAI repo (GPLv3, khong link vao vslam_node) -- dat DMVIO_BIN
# (mac dinh ~/opt/dmvio/src/dm-vio/build/bin/dmvio_dataset); khong co thi bo qua.
#
# Ba muc "giong that", CHOT TRUOC khi chay (03/10):
# L0 sach : IMU 200 Hz, khong bias, banh khong truot, anh sach
# L1 nang cap : IMU 100 Hz, bias accel 0.02 / gyro 0.001, truot 3%, nhieu IR
# sigma 2, lech gio camera-IMU 5 ms (chi DM-VIO dung)
# L2 hien tai : IMU 10 Hz (WT61PC bay gio), bias 0.05 / 0.003, truot 5%,
# nhieu IR sigma 3, lech gio 20 ms
# F2M va DM-VIO moi cau hinh chay 2 lan (ca hai khong tat dinh).
# DM-VIO chay hai che do: mode=1 (khong hieu chuan quang hoc, uoc luong do
# sang affine -- dung cho camera that co tu phoi sang; CHOT TRUOC) va mode=2
# (anh "hoan hao", co dinh affine -- sim khong doi phoi sang; THEM SAU khi
# mode=1 vo tren slope_lane5, la truong hop tot nhat cua DM-VIO trong sim).
#
# STEPS="ref f2m dmvio" (mac dinh ca ba) chon buoc; EVAL_ONLY=1 chi cham diem.
# Tham so F2M (Odom/VisKeyFrameThr=60, Vis/MaxDepth=0) va nhieu IMU cua DM-VIO
# (x10 mat do that cua sim) chon tren slope_lane15 -- cac kich ban khac la du
# lieu CHUA NHIN.
set -euo pipefail
DS=${1:?DS_DIR}
OUT=${2:?OUT_DIR}
shift 2
SCEN=("$@")
if [ ${#SCEN[@]} -eq 0 ]; then
SCEN=(slope_loop slope_lane5 slope_lane10 slope_lane15 slope_lane20 slope_lane30)
fi
ROOT=$(cd "$(dirname "$0")/.." && pwd)
BIN=${BIN:-$ROOT/build/tools}
DMVIO_BIN=${DMVIO_BIN:-$HOME/opt/dmvio/src/dm-vio/build/bin/dmvio_dataset}
ROBOT=${ROBOT:-$ROOT/configuration_files/robot.yaml}
JOBS=${JOBS:-6}
mkdir -p "$OUT"
level_args() { # $1 = muc -> bien dung chung
case $1 in
L0) IMU_HZ=0; AB=0,0,0; GB=0,0,0; ENC=1.0; IRN=0; OFS=0 ;;
L1) IMU_HZ=100; AB=0.02,-0.01,0.02; GB=0.001,-0.001,0.0005; ENC=1.03; IRN=2; OFS=5 ;;
L2) IMU_HZ=10; AB=0.05,-0.03,0.05; GB=0.003,-0.002,0.001; ENC=1.05; IRN=3; OFS=20 ;;
esac
}
# Nhieu IMU cho DM-VIO: x10 mat do that cua sim (sigma moi mau 4.9e-4 rad/s,
# 6.9e-3 m/s^2 o 200 Hz). euroc.yaml cua DM-VIO (x100) lam hong ti le.
cat > "$OUT/dmvio_sim_x10.yaml" <<'EOF'
accelerometer_noise_density: 4.88e-3
gyroscope_noise_density: 3.46e-4
accelerometer_random_walk: 1.0e-3
gyroscope_random_walk: 1.0e-4
integration_sigma: 0.316227
EOF
run_f2m() { # scen level rep
local s=$1 l=$2 r=$3
level_args "$l"
"$BIN/vslam_vo_bench" --in "$DS/$s.vsr" --robot "$ROBOT" \
--out "$OUT/$s/$l/f2m_r$r.txt" --stats "$OUT/$s/$l/f2m_r$r.json" \
--param Odom/VisKeyFrameThr=60 --param Vis/MaxDepth=0 \
--enc-scale "$ENC" --ir-noise "$IRN" --seed "$r" > "$OUT/$s/$l/f2m_r$r.log" 2>&1 || true
}
run_ref() { # scen level
local s=$1 l=$2
level_args "$l"
"$BIN/vslam_vo_bench" --in "$DS/$s.vsr" --robot "$ROBOT" --no-vo \
--out /dev/null --ref-out "$OUT/$s/$l/ref.txt" \
--imu-hz "$IMU_HZ" --accel-bias "$AB" --gyro-bias "$GB" --enc-scale "$ENC" \
> "$OUT/$s/$l/ref.log" 2>&1 || true
}
run_dmvio() { # scen level rep mode
local s=$1 l=$2 r=$3 m=$4 d="$OUT/$s/$l/dmvio_data"
local o="$OUT/$s/$l/dmvio_m${m}_r$r"
rm -rf "$o"
mkdir -p "$o"
(cd "$o" && env LD_LIBRARY_PATH= "$DMVIO_BIN" files="$d/cam0/images" imuFile="$d/imu.txt" \
calib="$d/camera.txt" imuCalib="$d/camchain.yaml" settingsFile="$OUT/dmvio_sim_x10.yaml" \
mode="$m" nogui=1 preset=0 quiet=1 useimu=1 start=2 resultsPrefix="$o/" > "$o/run.log" 2>&1) || true
}
STEPS=${STEPS:-ref f2m dmvio}
has_step() { [[ " $STEPS " == *" $1 "* ]]; }
if [ "${EVAL_ONLY:-0}" != 1 ]; then
# --- 1. Tham chieu + F2M (song song, moi tien trinh ~1 nhan) ---
pids=()
for s in "${SCEN[@]}"; do
for l in L0 L1 L2; do
mkdir -p "$OUT/$s/$l"
if has_step ref; then
run_ref "$s" "$l" &
pids+=($!)
fi
if has_step f2m; then
for r in 1 2; do
run_f2m "$s" "$l" "$r" &
pids+=($!)
if [ ${#pids[@]} -ge "$JOBS" ]; then wait "${pids[0]}"; pids=("${pids[@]:1}"); fi
done
fi
done
done
wait
# --- 2. DM-VIO (xuat dataset da lam xau, roi chay; moi lan da luong) ---
if ! has_step dmvio; then
:
elif [ -x "$DMVIO_BIN" ]; then
for s in "${SCEN[@]}"; do
for l in L0 L1 L2; do
level_args "$l"
d="$OUT/$s/$l/dmvio_data"
rm -rf "$d"
"$BIN/vslam_vsr_export" --in "$DS/$s.vsr" --out "$d" --robot "$ROBOT" \
--imu-hz "$IMU_HZ" --imu-offset-ms "$OFS" --accel-bias "$AB" --gyro-bias "$GB" \
--ir-noise "$IRN" > "$OUT/$s/$l/export.log" 2>&1
for m in 1 2; do
run_dmvio "$s" "$l" 1 "$m" &
run_dmvio "$s" "$l" 2 "$m" &
done
wait
# Giu gt, bo anh (moi bo ~100 MB).
rm -rf "$d/cam0/images"
done
done
else
echo "khong co DM-VIO ($DMVIO_BIN) -- bo qua" >&2
fi
fi # EVAL_ONLY
# --- 3. Cham diem ---
rm -f "$OUT/summary.txt"
for s in "${SCEN[@]}"; do
gt="$OUT/$s/L0/dmvio_data/gt_base_tum.txt"
[ -f "$gt" ] || { "$BIN/vslam_vsr_export" --in "$DS/$s.vsr" --out "$OUT/$s/gt" --robot "$ROBOT" >/dev/null 2>&1; rm -rf "$OUT/$s/gt/cam0/images"; gt="$OUT/$s/gt/gt_base_tum.txt"; }
for l in L0 L1 L2; do
# Bo loc z ung vien cho G4, ghep offline: kep mat bang, lai F2M + pitch IMU.
python3 "$ROOT/tools/slope_fuse.py" "$OUT/$s/$l"
args=(--gt "$gt" --title "$s $l" --json "$OUT/$s/$l/eval.json" --plot "$OUT/$s/$l/z.png"
--plot-only ref,ref_clamp,f2m_r1,f2m_clamp_r1,hyb_clamp_r1,dmvio_m1_r1,dmvio_m2_r1
--est "ref=$OUT/$s/$l/ref.txt" --est "ref_clamp=$OUT/$s/$l/ref_clamp.txt")
for r in 1 2; do
if [ -s "$OUT/$s/$l/f2m_r$r.txt" ]; then
args+=(--est "f2m_r$r=$OUT/$s/$l/f2m_r$r.txt" --stats "f2m_r$r=$OUT/$s/$l/f2m_r$r.json")
args+=(--est "hyb_r$r=$OUT/$s/$l/hyb_r$r.txt" --est "hyb_clamp_r$r=$OUT/$s/$l/hyb_clamp_r$r.txt"
--est "f2m_clamp_r$r=$OUT/$s/$l/f2m_clamp_r$r.txt")
fi
for m in 1 2; do
if [ -s "$OUT/$s/$l/dmvio_m${m}_r$r/resultScaled.txt" ]; then
args+=(--est "dmvio_m${m}_r$r=$OUT/$s/$l/dmvio_m${m}_r$r/resultScaled.txt,0.1465")
fi
done
done
n=$(grep -c . "$OUT/$s/L0/dmvio_data/cam0/times.txt" 2>/dev/null || echo 0)
python3 "$ROOT/tools/slope_eval.py" "${args[@]}" --frames "$n" | tee -a "$OUT/summary.txt"
done
done
python3 "$ROOT/tools/slope_summary.py" "$OUT" --md "$OUT/summary.md"

241
tools/slope_eval.py Normal file
View File

@@ -0,0 +1,241 @@
#!/usr/bin/env python3
"""Cham diem z tren doc: so quy dao uoc luong (TUM) voi su that cua bo mo phong.
Dung cho G3 (so F2M / DM-VIO / tham chieu ds*sin(pitch)). Moi quy dao NEO z
tai pose DAU TIEN cua no (z_uoc(t) - z_uoc(t0) + z_that(t0)) -- giong vslam_node
neo z vao ban do; khong can ti le, khong can xoay (moi frame deu da theo trong
luc: odom F2M bat dau tu robot dung tren san phang, DM-VIO tu can trong luc).
Chi so (tieu chi DANG KY TRUOC trong ke hoach, 03/10):
* Sai dz moi lan qua doc: tu mau CUOI tren mat bang xuat phat toi mau DAU tren
mat bang den (chan -> dinh hoac nguoc lai). Dat: <= max(5 cm, 3% do cao)
voi doc <= 15 do, <= 10 cm voi 20/30 do.
* Troi z tren mat bang: |dz uoc| tren moi doan mat bang (cat 1 m hai dau --
chuyen tiep chan/dinh doc), doan con >= 2 m, quy ra cm / 100 m quang
duong. Dat: <= 5 cm / 100 m.
* Bam: ti le khung co pose (tu file --stats neu co). Dat: >= 98%.
* Kem theo: RMSE z ca lan chay, sai z cuoi, RMSE pitch, ms/khung.
python3 tools/slope_eval.py --gt DIR/gt_base_tum.txt \\
--est f2m=f2m.txt --est ref=ref.txt --est dmvio=resultScaled.txt,0.1465 \\
[--stats f2m=f2m.json] [--title lane15] [--plot out.png] [--json out.json]
`--est TEN=FILE[,body_z]`: body_z = do cao diem cua quy dao tren base_footprint
theo truc z THAN (DM-VIO xuat diem IMU: 0.1465 m) -- doi ve base_footprint.
"""
import argparse
import json
import math
import sys
import numpy as np
def load_tum(path):
d = np.loadtxt(path, comments='#')
if d.ndim == 1:
d = d[None, :]
return d
def quat_to_R(qx, qy, qz, qw):
n = np.sqrt(qx * qx + qy * qy + qz * qz + qw * qw)
qx, qy, qz, qw = qx / n, qy / n, qz / n, qw / n
R = np.empty(qx.shape + (3, 3))
R[..., 0, 0] = 1 - 2 * (qy * qy + qz * qz)
R[..., 0, 1] = 2 * (qx * qy - qz * qw)
R[..., 0, 2] = 2 * (qx * qz + qy * qw)
R[..., 1, 0] = 2 * (qx * qy + qz * qw)
R[..., 1, 1] = 1 - 2 * (qx * qx + qz * qz)
R[..., 1, 2] = 2 * (qy * qz - qx * qw)
R[..., 2, 0] = 2 * (qx * qz - qy * qw)
R[..., 2, 1] = 2 * (qy * qz + qx * qw)
R[..., 2, 2] = 1 - 2 * (qx * qx + qy * qy)
return R
def pitch_of(d):
"""Pitch ROS (duong = mui chuc xuong) tu cot qx qy qz qw."""
qx, qy, qz, qw = d[:, 4], d[:, 5], d[:, 6], d[:, 7]
return np.arcsin(np.clip(2 * (qw * qy - qz * qx), -1, 1))
def to_footprint(d, body_z):
"""Doi diem cach base_footprint `body_z` theo truc z than ve base_footprint."""
if body_z == 0.0:
return d
R = quat_to_R(d[:, 4], d[:, 5], d[:, 6], d[:, 7])
out = d.copy()
out[:, 1:4] -= body_z * R[:, :, 2]
return out
def plateaus(z, lo, hi, tol):
"""Nhan tung mau GT: 0 = mat bang duoi, 1 = mat bang tren, -1 = tren doc."""
lab = np.full(len(z), -1)
lab[np.abs(z - lo) < tol] = 0
lab[np.abs(z - hi) < tol] = 1
return lab
def runs(lab):
"""Cac doan lien tiep cung nhan: (nhan, i_dau, i_cuoi)."""
out = []
s = 0
for i in range(1, len(lab) + 1):
if i == len(lab) or lab[i] != lab[s]:
out.append((lab[s], s, i - 1))
s = i
return out
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--gt', required=True, help='gt_base_tum.txt (base_footprint)')
ap.add_argument('--est', action='append', default=[], help='TEN=FILE[,body_z]')
ap.add_argument('--stats', action='append', default=[], help='TEN=FILE.json (vslam_vo_bench)')
ap.add_argument('--frames', type=int, default=0, help='so khung anh (de tinh %% bam khi khong co --stats)')
ap.add_argument('--title', default='')
ap.add_argument('--plot', default='')
ap.add_argument('--plot-only', default='', help='ten,ten,... chi ve cac quy dao nay')
ap.add_argument('--json', default='')
a = ap.parse_args()
gt = load_tum(a.gt)
tg, zg, pg = gt[:, 0], gt[:, 3], pitch_of(gt)
H = zg.max() - zg.min()
lo, hi = zg.min(), zg.max()
lab = plateaus(zg, lo, hi, 0.005)
segs = runs(lab)
# Lan qua doc: mat bang A -> (doc) -> mat bang B khac A.
crossings = []
for k in range(1, len(segs) - 1):
if segs[k][0] != -1:
continue
a_lab, a_s, a_e = segs[k - 1]
b_lab, b_s, b_e = segs[k + 1]
if a_lab in (0, 1) and b_lab in (0, 1) and a_lab != b_lab:
i0, i1 = a_e, b_s
ang = np.degrees(np.median(np.abs(pg[i0:i1 + 1])))
crossings.append((i0, i1, 'len' if b_lab == 1 else 'xuong', ang))
flats = [(s, e) for l, s, e in segs if l in (0, 1)]
xy = gt[:, 1:3]
stats = {}
for s in a.stats:
k, p = s.split('=', 1)
with open(p) as f:
stats[k] = json.load(f)
results = {'title': a.title, 'H': H, 'methods': {}}
series = {}
for spec in a.est:
name, rest = spec.split('=', 1)
parts = rest.split(',')
body_z = float(parts[1]) if len(parts) > 1 else 0.0
e = to_footprint(load_tum(parts[0]), body_z)
te = e[:, 0]
ze = e[:, 3] - e[0, 3] + np.interp(te[0], tg, zg)
series[name] = (te, ze)
zei = lambda t: np.interp(t, te, ze)
zgi = np.interp(te, tg, zg)
err = ze - zgi
pe = pitch_of(e)
perr = pe - np.interp(te, tg, pg)
m = {
'poses': int(len(e)),
'rmse_z': float(np.sqrt(np.mean(err ** 2))),
'max_abs_z': float(np.max(np.abs(err))),
'end_z': float(err[-1]),
'rmse_pitch_deg': float(np.degrees(np.sqrt(np.mean(perr ** 2)))),
'crossings': [],
'flats': [],
}
for i0, i1, kind, ang in crossings:
t0, t1 = tg[i0], tg[i1]
dz_true = zg[i1] - zg[i0]
dz_est = zei(t1) - zei(t0)
lim = max(0.05, 0.03 * abs(dz_true)) if ang <= 15.5 else 0.10
m['crossings'].append({
't0': float(t0 - tg[0]), 't1': float(t1 - tg[0]), 'kind': kind,
'angle_deg': float(ang), 'dz_true': float(dz_true), 'dz_err': float(dz_est - dz_true),
'limit': float(lim), 'pass': bool(abs(dz_est - dz_true) <= lim)})
for s, e_ in flats:
# Cat 1 m hai dau: o chan/dinh doc than xe da chuc trong khi tam
# xe (z that) chua len -- do la chuyen tiep, khong phai mat bang.
cum = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(xy[s:e_ + 1], axis=0), axis=1))])
if cum[-1] < 4.0:
continue
i_s = int(np.searchsorted(cum, 1.0))
i_e = int(np.searchsorted(cum, cum[-1] - 1.0))
d = float(cum[i_e] - cum[i_s])
s, e_ = s + i_s, s + i_e
if d < 2.0:
continue
dz = float(zei(tg[e_]) - zei(tg[s]))
m['flats'].append({'t0': float(tg[s] - tg[0]), 'dist_m': d, 'dz': dz,
'cm_per_100m': 100.0 * abs(dz) / d * 100.0})
if name in stats:
st = stats[name]
m['track_pct'] = 100.0 * (st['frames'] - st['lost']) / max(1, st['frames'])
m['ms_mean'] = st.get('ms_mean')
elif a.frames > 0:
m['track_pct'] = 100.0 * len(e) / a.frames
worst_flat = max([f['cm_per_100m'] for f in m['flats']], default=0.0)
m['worst_flat_cm_per_100m'] = worst_flat
m['pass_crossings'] = all(c['pass'] for c in m['crossings'])
m['pass_flat'] = worst_flat <= 5.0
m['pass_track'] = m.get('track_pct', 100.0) >= 98.0
results['methods'][name] = m
# --- In bang ---
print(f"== {a.title} (do cao {H:.3f} m, {len(crossings)} lan qua doc, {len(flats)} doan mat bang)")
for name, m in results['methods'].items():
cr = ' '.join(f"{c['kind']}{c['angle_deg']:.0f}:{c['dz_err']*100:+.1f}cm{'' if c['pass'] else '!'}"
for c in m['crossings'])
tr = f"{m['track_pct']:.1f}%" if 'track_pct' in m else '-'
ms = f"{m['ms_mean']:.1f}" if m.get('ms_mean') is not None else '-'
print(f" {name:10s} dz qua doc [{cr}] | troi mat bang max {m['worst_flat_cm_per_100m']:.1f} cm/100m "
f"| RMSE z {m['rmse_z']*100:.1f} cm, cuoi {m['end_z']*100:+.1f} cm | pitch {m['rmse_pitch_deg']:.2f} do "
f"| bam {tr} | {ms} ms")
if a.json:
with open(a.json, 'w') as f:
json.dump(results, f, indent=1)
if a.plot:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
colors = {'ref': 'tab:blue', 'ref_clamp': 'tab:cyan', 'f2m': 'tab:green', 'f2m_clamp': 'tab:brown', 'hyb': 'tab:olive',
'hyb_clamp': 'tab:purple', 'dmvio_m1': 'tab:red', 'dmvio_m2': 'tab:orange'}
only = [x for x in a.plot_only.split(',') if x]
fig, ax = plt.subplots(2, 1, figsize=(10, 6.5), sharex=True)
ax[0].plot(tg - tg[0], zg, 'k-', lw=2, label='that')
for name, (te, ze) in series.items():
if only and name not in only:
continue
fam = name.rsplit('_r', 1)[0] if name.rsplit('_r', 1)[-1].isdigit() else name
c = colors.get(fam)
ax[0].plot(te - tg[0], ze, lw=1, label=name, color=c)
ax[1].plot(te - tg[0], (ze - np.interp(te, tg, zg)) * 100, lw=1, label=name, color=c)
# Kep truc: quy dao vo (DM-VIO mat ti le) di ra ngoai khung thay vi
# ep moi thu khac thanh duong thang.
ax[0].set_ylim(zg.min() - 0.6, zg.max() + 0.6)
ax[1].set_ylim(-60, 60)
for i0, i1, kind, ang in crossings:
for x in ax:
x.axvspan(tg[i0] - tg[0], tg[i1] - tg[0], color='0.9', zorder=0)
ax[0].set_ylabel('z (m)')
ax[1].set_ylabel('sai z (cm)')
ax[1].set_xlabel('t (s) -- nen xam = dang tren doc; duong ra ngoai khung = vo')
ax[0].set_title(a.title)
ax[0].legend(loc='best', fontsize=8)
ax[1].axhline(0, color='k', lw=0.5)
ax[1].grid(alpha=0.3)
fig.tight_layout()
fig.savefig(a.plot, dpi=110)
return 0
if __name__ == '__main__':
sys.exit(main())

110
tools/slope_fuse.py Normal file
View File

@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Ghep nguon z OFFLINE tu ket qua vslam_vo_bench -- thu cac bo loc z cho G4
truoc khi viet C++.
Vao (cung thu muc, ra cua vslam_vo_bench):
ref.txt tham chieu: z = tich -ds*sin(pitch), pitch/roll cua GravityAlign
f2m_rN.txt odometry F2M (base_footprint, frame odom)
Ra (TUM, cung thu muc):
ref_clamp.txt tham chieu + KEP MAT BANG: |pitch IMU| < nguong -> dz = 0
hyb_rN.txt LAI: buoc dich chuyen trong frame THAN tu F2M (met, khong
truot banh), xoay bang roll/pitch IMU (khong troi):
dz = -sin(p)*dx + cos(p)*sin(r)*dy + cos(p)*cos(r)*dz
hyb_clamp_rN.txt lai + kep mat bang
f2m_clamp_rN.txt dz cua CHINH F2M, kep mat bang theo pitch IMU -- dung
thiet ke G4 trong ke hoach (dz VO + dz = 0 o node phang)
Nguong kep mac dinh 1.5 do: duoi doc thu nho nhat (5 do), tren sai pitch do
bias IMU muc L2 (~0.9 do). CHOT TRUOC khi cham. Doc that < 1.5 do se bi coi
la phang -- noi ro trong bao cao.
python3 tools/slope_fuse.py DIR [--clamp-deg 1.5]
"""
import argparse
import glob
import os
import sys
import numpy as np
def load(p):
d = np.loadtxt(p, comments='#')
return d[None, :] if d.ndim == 1 else d
def rpy(d):
qx, qy, qz, qw = d[:, 4], d[:, 5], d[:, 6], d[:, 7]
roll = np.arctan2(2 * (qw * qx + qy * qz), 1 - 2 * (qx * qx + qy * qy))
pitch = np.arcsin(np.clip(2 * (qw * qy - qz * qx), -1, 1))
return roll, pitch
def rot(d):
qx, qy, qz, qw = d[:, 4], d[:, 5], d[:, 6], d[:, 7]
R = np.empty((len(d), 3, 3))
R[:, 0, 0] = 1 - 2 * (qy * qy + qz * qz)
R[:, 0, 1] = 2 * (qx * qy - qz * qw)
R[:, 0, 2] = 2 * (qx * qz + qy * qw)
R[:, 1, 0] = 2 * (qx * qy + qz * qw)
R[:, 1, 1] = 1 - 2 * (qx * qx + qz * qz)
R[:, 1, 2] = 2 * (qy * qz - qx * qw)
R[:, 2, 0] = 2 * (qx * qz - qy * qw)
R[:, 2, 1] = 2 * (qy * qz + qx * qw)
R[:, 2, 2] = 1 - 2 * (qx * qx + qy * qy)
return R
def save(p, d, z, header):
out = d.copy()
out[:, 3] = z
np.savetxt(p, out, fmt='%.9f %.6f %.6f %.6f %.9f %.9f %.9f %.9f', header=header)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('dir')
ap.add_argument('--clamp-deg', type=float, default=1.5)
a = ap.parse_args()
th = np.radians(a.clamp_deg)
ref_p = os.path.join(a.dir, 'ref.txt')
if not os.path.exists(ref_p):
print(f'{a.dir}: thieu ref.txt', file=sys.stderr)
return 1
ref = load(ref_p)
r_roll, r_pitch = rpy(ref)
dz = np.diff(ref[:, 3])
dz[np.abs(r_pitch[1:]) < th] = 0.0
save(os.path.join(a.dir, 'ref_clamp.txt'), ref, ref[0, 3] + np.concatenate([[0.0], np.cumsum(dz)]),
f'tham chieu + kep mat bang (|pitch| < {a.clamp_deg} do -> dz = 0)')
for f in sorted(glob.glob(os.path.join(a.dir, 'f2m_r*.txt'))):
tag = os.path.basename(f)[len('f2m_'):-len('.txt')]
e = load(f)
if len(e) < 2:
continue
R = rot(e)
dp_w = np.diff(e[:, 1:4], axis=0)
dp_b = np.einsum('kji,kj->ki', R[:-1], dp_w) # R_prev^T * dp
roll = np.interp(e[1:, 0], ref[:, 0], r_roll)
pitch = np.interp(e[1:, 0], ref[:, 0], r_pitch)
dzh = (-np.sin(pitch) * dp_b[:, 0] + np.cos(pitch) * np.sin(roll) * dp_b[:, 1]
+ np.cos(pitch) * np.cos(roll) * dp_b[:, 2])
z0 = e[0, 3]
save(os.path.join(a.dir, f'hyb_{tag}.txt'), e, z0 + np.concatenate([[0.0], np.cumsum(dzh)]),
'lai: buoc than F2M xoay bang roll/pitch IMU')
dzc = dzh.copy()
dzc[np.abs(pitch) < th] = 0.0
save(os.path.join(a.dir, f'hyb_clamp_{tag}.txt'), e, z0 + np.concatenate([[0.0], np.cumsum(dzc)]),
f'lai + kep mat bang (|pitch| < {a.clamp_deg} do)')
dzf = np.diff(e[:, 3])
dzf[np.abs(pitch) < th] = 0.0
save(os.path.join(a.dir, f'f2m_clamp_{tag}.txt'), e, z0 + np.concatenate([[0.0], np.cumsum(dzf)]),
f'dz F2M + kep mat bang theo pitch IMU (|pitch| < {a.clamp_deg} do)')
return 0
if __name__ == '__main__':
sys.exit(main())

118
tools/slope_summary.py Normal file
View File

@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Tong hop ket qua tools/slope_bakeoff.sh: doc OUT/<kich_ban>/<muc>/eval.json,
gop theo (phuong phap, muc), in bang markdown.
python3 tools/slope_summary.py OUT_DIR [--md OUT.md]
Phuong phap = ten bo hau to _rN (moi lan chay lap). Lan chay KHONG co ket qua
(DM-VIO vo tien trinh) tinh la HONG, khong bo qua.
"""
import argparse
import glob
import json
import os
import re
import sys
from collections import defaultdict
import numpy as np
# So lan chay ky vong moi (kich ban, muc) -- de dem lan vo.
EXPECT = {'ref': 1, 'ref_clamp': 1, 'f2m': 2, 'f2m_clamp': 2, 'hyb': 2, 'hyb_clamp': 2,
'dmvio_m1': 2, 'dmvio_m2': 2}
ORDER = ['ref', 'ref_clamp', 'f2m', 'f2m_clamp', 'hyb', 'hyb_clamp', 'dmvio_m1', 'dmvio_m2']
LABEL = {
'ref': 'Tham chieu ds*sin(pitch IMU)',
'ref_clamp': 'Tham chieu + kep mat bang',
'f2m': 'F2M (RTAB-Map, IR+depth)',
'f2m_clamp': 'F2M + kep mat bang (thiet ke G4 cu)',
'hyb': 'Lai: buoc F2M + pitch IMU',
'hyb_clamp': 'Lai + kep mat bang',
'dmvio_m1': 'DM-VIO mode=1 (nhu camera that)',
'dmvio_m2': 'DM-VIO mode=2 (anh hoan hao)',
}
LEVEL = {'L0': 'L0 sach', 'L1': 'L1 nang cap (IMU 100 Hz)', 'L2': 'L2 hien tai (IMU 10 Hz)'}
BROKEN_CM = 50.0 # sai dz qua doc > 50 cm = vo (mat ti le / no)
def family(name):
return re.sub(r'_r\d+$', '', name)
def main():
ap = argparse.ArgumentParser()
ap.add_argument('out')
ap.add_argument('--md', default='')
a = ap.parse_args()
agg = defaultdict(lambda: {'cross': [], 'cross_pass': 0, 'cross_n': 0, 'flat': [], 'rmse': [],
'end': [], 'runs': 0, 'broken': 0, 'scen': set(), 'by_angle': defaultdict(list),
'ms': []})
scen_levels = defaultdict(set)
for p in sorted(glob.glob(os.path.join(a.out, '*', 'L*', 'eval.json'))):
lvl = os.path.basename(os.path.dirname(p))
scen = os.path.basename(os.path.dirname(os.path.dirname(p)))
scen_levels[lvl].add(scen)
with open(p) as f:
ev = json.load(f)
for name, m in ev['methods'].items():
fam = family(name)
g = agg[(fam, lvl)]
g['runs'] += 1
g['scen'].add(scen)
errs = [abs(c['dz_err']) * 100 for c in m['crossings']]
if any(e > BROKEN_CM for e in errs):
g['broken'] += 1
g['cross'] += errs
g['cross_pass'] += sum(c['pass'] for c in m['crossings'])
g['cross_n'] += len(m['crossings'])
for c in m['crossings']:
g['by_angle'][round(c['angle_deg'])].append(abs(c['dz_err']) * 100)
g['flat'].append(m['worst_flat_cm_per_100m'])
g['rmse'].append(m['rmse_z'] * 100)
g['end'].append(abs(m['end_z']) * 100)
if m.get('ms_mean'):
g['ms'].append(m['ms_mean'])
lines = []
for lvl in sorted(scen_levels):
n_scen = len(scen_levels[lvl])
lines.append(f"\n### {LEVEL.get(lvl, lvl)} -- {n_scen} kich ban\n")
lines.append('| Phuong phap | Lan chay (vo) | Qua doc dat | Sai dz trung vi / max (cm) | '
'Troi mat bang trung vi / max (cm/100m) | RMSE z trung vi (cm) | ms/khung |')
lines.append('|---|---|---|---|---|---|---|')
for fam in ORDER:
g = agg.get((fam, lvl))
exp = EXPECT.get(fam, 1) * n_scen
if g is None:
lines.append(f"| {LABEL.get(fam, fam)} | 0/{exp} | - | - | - | - | - |")
continue
missing = exp - g['runs']
bad = g['broken'] + max(0, missing)
cr = np.array(g['cross']) if g['cross'] else np.array([np.nan])
ms = f"{np.mean(g['ms']):.1f}" if g['ms'] else '-'
lines.append(
f"| {LABEL.get(fam, fam)} | {g['runs']}/{exp} ({bad}) | {g['cross_pass']}/{g['cross_n']} | "
f"{np.nanmedian(cr):.1f} / {np.nanmax(cr):.0f} | {np.median(g['flat']):.0f} / {np.max(g['flat']):.0f} | "
f"{np.median(g['rmse']):.1f} | {ms} |")
# Theo goc doc, muc L1 (phan cung dich).
lines.append('\n### Sai dz qua doc theo goc, L1 (trung vi |cm|)\n')
angles = sorted({ang for (fam, lvl), g in agg.items() if lvl == 'L1' for ang in g['by_angle']})
lines.append('| Phuong phap | ' + ' | '.join(f'{x} do' for x in angles) + ' |')
lines.append('|---|' + '---|' * len(angles))
for fam in ORDER:
g = agg.get((fam, 'L1'))
if g is None:
continue
cells = [f"{np.median(g['by_angle'][x]):.1f}" if g['by_angle'].get(x) else '-' for x in angles]
lines.append(f"| {LABEL.get(fam, fam)} | " + ' | '.join(cells) + ' |')
text = '\n'.join(lines)
print(text)
if a.md:
with open(a.md, 'w') as f:
f.write(text + '\n')
return 0
if __name__ == '__main__':
sys.exit(main())

310
tools/vslam_imu_config.cc Normal file
View File

@@ -0,0 +1,310 @@
// vslam_imu_config -- doc / doi baud va tan so phat cua IMU WT61PC (WitMotion,
// ban DFRobot SEN0386) qua CHINH cong serial, khong can phan mem cua hang.
//
// vslam_imu_config [--port /dev/imu] chi DO: baud, tan so
// vslam_imu_config [--port P] --baud 115200 --rate-hz 100 [--yes]
//
// Khong co --yes thi chi do va in cac lenh SE gui. Can cong RANH: dung
// vslam_node va motor_control (imu_ros_node) truoc -- driver khoa doc quyen.
//
// ================== GIAO THUC (WIT Standard Protocol) ==================
// mo khoa FF AA 69 88 B5 hieu luc 10 s
// ghi FF AA <dia chi> <byte thap> <byte cao>
// 0x03 RRATE: 0x06 10 Hz, 0x07 20, 0x08 50, 0x09 100, 0x0B 200
// 0x04 BAUD : 0x02 9600, 0x03 19200, 0x04 38400, 0x05 57600,
// 0x06 115200, 0x07 230400
// luu FF AA 00 00 00
// Thu vien Arduino cua DFRobot chi gui `FF AA 03 xx 00` (khong mo khoa, khong
// luu) va dien dan DFRobot co nhieu bao "doi tan so khong an" -- nen o day
// LUON mo khoa truoc va luu sau.
//
// ================== TRINH TU ==================
// 1. Do baud hien tai (thu lan luot, tim khung 0x55 dung checksum).
// 2. Mo khoa -> doi baud -> luu, o baud CU.
// 3. Mo lai o baud MOI, phai thay khung; mo khoa -> luu lan nua (mot so
// firmware doi baud NGAY khi nhan lenh, lenh luu o baud cu thanh rac).
// 4. Mo khoa -> doi tan so -> luu.
// 5. Do lai tan so that.
// Lo mat baud (vd mat dien giua chung): chay lai khong tham so -- buoc 1 do
// qua moi baud ho tro.
#include <fcntl.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <thread>
#include <vector>
#include "vslam/wt61pc_protocol.h"
namespace {
speed_t BaudConstant(int baud) {
switch (baud) {
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
default: return 0;
}
}
int BaudCode(int baud) {
switch (baud) {
case 9600: return 0x02;
case 19200: return 0x03;
case 38400: return 0x04;
case 57600: return 0x05;
case 115200: return 0x06;
case 230400: return 0x07;
default: return -1;
}
}
int RateCode(int hz) {
switch (hz) {
case 10: return 0x06;
case 20: return 0x07;
case 50: return 0x08;
case 100: return 0x09;
case 200: return 0x0B;
default: return -1;
}
}
// Go khoa doc quyen TRUOC khi dong: neu con ai giu tty (vd cong gia khi test)
// thi co TIOCEXCL ton tai sau close va lan mo ke tiep bao EBUSY.
void ClosePort(int fd) {
::ioctl(fd, TIOCNXCL);
::close(fd);
}
int OpenPort(const std::string& port, int baud) {
const int fd = ::open(port.c_str(), O_RDWR | O_NOCTTY);
if (fd < 0) {
std::fprintf(stderr, "khong mo duoc %s: %s%s\n", port.c_str(), std::strerror(errno),
errno == EBUSY ? " -- cong dang bi giu: dung vslam_node / motor_control truoc"
: "");
return -1;
}
if (::ioctl(fd, TIOCEXCL) != 0) {
std::fprintf(stderr, "%s: khong khoa doc quyen duoc (%s)\n", port.c_str(), std::strerror(errno));
}
termios tio{};
if (::tcgetattr(fd, &tio) != 0) {
ClosePort(fd);
return -1;
}
::cfmakeraw(&tio);
tio.c_cflag |= CLOCAL | CREAD;
tio.c_cc[VMIN] = 0;
tio.c_cc[VTIME] = 1; // read() cho toi 0.1 s
::cfsetispeed(&tio, BaudConstant(baud));
::cfsetospeed(&tio, BaudConstant(baud));
if (::tcsetattr(fd, TCSANOW, &tio) != 0) {
ClosePort(fd);
return -1;
}
::tcflush(fd, TCIOFLUSH);
return fd;
}
struct Probe {
int frames = 0;
int gyro = 0;
uint64_t bad = 0;
double seconds = 0.0;
double roll = 0.0, pitch = 0.0;
bool have_angle = false;
double hz() const { return seconds > 0.0 ? gyro / seconds : 0.0; }
};
Probe Listen(int fd, double seconds) {
Probe p;
vslam::Wt61pcParser parser;
vslam::Wt61pcFrame f;
const auto t0 = std::chrono::steady_clock::now();
uint8_t buf[256];
while (true) {
const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
if (el >= seconds) {
p.seconds = el;
break;
}
const ssize_t n = ::read(fd, buf, sizeof(buf));
for (ssize_t i = 0; i < n; ++i) {
if (!parser.Push(buf[i], &f)) continue;
p.frames++;
if (f.type == vslam::Wt61pcType::kGyro) p.gyro++;
if (f.type == vslam::Wt61pcType::kAngle) {
p.roll = f.x;
p.pitch = f.y;
p.have_angle = true;
}
}
}
p.bad = parser.bad_checksum();
return p;
}
bool Send(int fd, uint8_t addr, uint8_t lo, uint8_t hi, const char* what) {
const uint8_t cmd[5] = {0xFF, 0xAA, addr, lo, hi};
std::printf(" gui %-22s FF AA %02X %02X %02X\n", what, addr, lo, hi);
if (::write(fd, cmd, sizeof(cmd)) != static_cast<ssize_t>(sizeof(cmd))) {
std::fprintf(stderr, " ghi loi: %s\n", std::strerror(errno));
return false;
}
::tcdrain(fd);
std::this_thread::sleep_for(std::chrono::milliseconds(150));
return true;
}
bool Unlock(int fd) { return Send(fd, 0x69, 0x88, 0xB5, "mo khoa"); }
bool Save(int fd) { return Send(fd, 0x00, 0x00, 0x00, "luu"); }
// Thu lan luot cac baud; tra baud thay khung hop le, 0 neu khong thay.
int Detect(const std::string& port, int first, Probe* out) {
std::vector<int> order{first, 9600, 115200, 57600, 38400, 19200, 230400};
for (size_t i = 0; i < order.size(); ++i) {
const int b = order[i];
if (b <= 0 || BaudConstant(b) == 0) continue;
bool dup = false;
for (size_t j = 0; j < i; ++j) dup = dup || order[j] == b;
if (dup) continue;
const int fd = OpenPort(port, b);
if (fd < 0) return -1;
const Probe p = Listen(fd, 1.5);
ClosePort(fd);
std::printf(" thu %6d baud: %3d khung hop le, checksum sai %llu\n", b, p.frames,
static_cast<unsigned long long>(p.bad));
if (p.frames >= 5) {
*out = p;
return b;
}
}
return 0;
}
void Report(int baud, const Probe& p) {
std::printf("=> %d baud, gyro %.1f Hz", baud, p.hz());
if (p.have_angle) {
std::printf(", goc cam bien roll %.2f / pitch %.2f do", p.roll * 180.0 / M_PI,
p.pitch * 180.0 / M_PI);
}
std::printf("\n");
}
} // namespace
int main(int argc, char** argv) {
std::string port = "/dev/imu";
int want_baud = 0, want_hz = 0, guess = 9600;
bool yes = false;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--port") port = next();
else if (a == "--baud") want_baud = std::atoi(next().c_str());
else if (a == "--rate-hz") want_hz = std::atoi(next().c_str());
else if (a == "--guess") guess = std::atoi(next().c_str());
else if (a == "--yes") yes = true;
else {
std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str());
return 2;
}
}
if ((want_baud != 0 && BaudCode(want_baud) < 0) || (want_hz != 0 && RateCode(want_hz) < 0)) {
std::fprintf(stderr, "ho tro --baud 9600/19200/38400/57600/115200/230400, "
"--rate-hz 10/20/50/100/200\n");
return 2;
}
std::printf("[1] do IMU o %s\n", port.c_str());
Probe p;
const int cur = Detect(port, guess, &p);
if (cur < 0) return 1;
if (cur == 0) {
std::fprintf(stderr, "khong thay khung WT61PC o baud nao -- kiem day (TX cam bien -> RX cap), "
"nguon, va dung cong.\n");
return 1;
}
Report(cur, p);
if (want_baud == 0 && want_hz == 0) return 0;
const int new_baud = want_baud != 0 ? want_baud : cur;
const int new_hz = want_hz != 0 ? want_hz : static_cast<int>(std::lround(p.hz()));
// Moi chu ky 33 byte (gia toc + gyro + goc), 10 bit moi byte.
const double max_hz = new_baud / 10.0 / 33.0;
if (new_hz > 0.8 * max_hz) {
std::fprintf(stderr, "%d Hz qua tai %d baud (toi da ~%.0f Hz) -- tang --baud.\n", new_hz,
new_baud, 0.8 * max_hz);
return 2;
}
if (!yes) {
std::printf("[chua gui gi] se doi: %d baud -> %d baud, tan so -> %d Hz. Them --yes de lam.\n",
cur, new_baud, new_hz);
return 0;
}
if (new_baud != cur) {
std::printf("[2] doi baud %d -> %d\n", cur, new_baud);
int fd = OpenPort(port, cur);
if (fd < 0) return 1;
bool ok = Unlock(fd) && Send(fd, 0x04, static_cast<uint8_t>(BaudCode(new_baud)), 0x00, "baud") &&
Save(fd);
ClosePort(fd);
if (!ok) return 1;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::printf("[3] mo lai o %d baud\n", new_baud);
fd = OpenPort(port, new_baud);
if (fd < 0) return 1;
const Probe q = Listen(fd, 1.5);
if (q.frames < 5) {
ClosePort(fd);
std::fprintf(stderr, "khong thay khung o %d baud -- cam bien chua doi baud. Chay lai khong "
"tham so de do baud hien tai.\n", new_baud);
return 1;
}
std::printf(" thay %d khung -- da o %d baud. Luu lan nua o baud moi.\n", q.frames, new_baud);
ok = Unlock(fd) && Save(fd);
ClosePort(fd);
if (!ok) return 1;
}
std::printf("[4] doi tan so -> %d Hz\n", new_hz);
int fd = OpenPort(port, new_baud);
if (fd < 0) return 1;
const bool ok = Unlock(fd) && Send(fd, 0x03, static_cast<uint8_t>(RateCode(new_hz)), 0x00, "tan so") &&
Save(fd);
if (!ok) {
ClosePort(fd);
return 1;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
::tcflush(fd, TCIFLUSH);
std::printf("[5] do lai\n");
const Probe r = Listen(fd, 3.0);
ClosePort(fd);
Report(new_baud, r);
if (std::fabs(r.hz() - new_hz) > 0.15 * new_hz) {
std::fprintf(stderr, "TAN SO CHUA DUNG (%.1f Hz, muon %d Hz). Thu tat/bat nguon cam bien roi "
"chay lai khong tham so de xem gia tri da luu.\n", r.hz(), new_hz);
return 1;
}
std::printf("XONG. Dat `mcu.baud: %d` trong sensors.yaml; bao nguoi dung imu_ros_node doi "
"baudrate sang %d. Tat/bat nguon roi chay lai khong tham so de chac da LUU.\n",
new_baud, new_baud);
return 0;
}

View File

@@ -13,16 +13,25 @@
// vat can cua cliff_detect.
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "vslam/driver_interfaces.h"
#include "vslam/record_format.h"
#include "vslam/record_io.h"
#include "vslam/robot_model.h"
#include "vslam/sim_source.h"
#ifdef VSLAM_HAVE_SIM_GL
#include "vslam/sim_gl_renderer.h"
#endif
namespace {
@@ -52,8 +61,125 @@ struct Scenario {
double start_x = 0.0, start_y = 0.0, start_yaw = 0.0;
};
// --- Kich ban DOC ---
// Chay trong file .world (tuong doi VSLAM_RESOURCE_DIR), lai theo WAYPOINT
// bang bo bam duong -- KHONG qua lop an toan, nen doc 30 do van co du lieu.
// Luon dung hinh hoc robot THAT, luon ghi su that 6-DoF, anh IR neu --gl.
// KHONG nam trong `--scenario all`: bo hoi quy chi dung kich ban phang.
//
// Tach rieng khoi `Scenario` (tra theo ten): them truong vao `Scenario` lam
// moi dong khoi tao cu thieu truong va -Wextra canh bao.
struct SlopeInfo {
const char* world = nullptr;
std::vector<std::pair<double, double>> waypoints;
double cruise = 0.30; // m/s doc mat san
};
std::vector<std::pair<std::string, SlopeInfo>>& SlopeTable() {
static std::vector<std::pair<std::string, SlopeInfo>> t;
return t;
}
const SlopeInfo* FindSlope(const char* name) {
for (const auto& e : SlopeTable()) {
if (e.first == name) return &e.second;
}
return nullptr;
}
// Kich ban DOC trong worlds/slope_test.world (tools/gen_slope_world.py): tam
// lan x = 1.2 / 3.8 / 6.4 / 9.0 / 11.6 cho doc 5 / 10 / 15 / 20 / 30 do, chan
// doc y = 8, san cao 1.5 m tu y = 25.5.
void AddSlopeScenarios(std::vector<Scenario>* v) {
const char* kWorld = "worlds/slope_test.world";
SlopeTable().clear();
{
Scenario s{};
s.name = "slope_loop";
s.what = "doc: len lan 15 do, qua san tren, xuong lan 20 do, ve cho cu";
s.camera = true;
s.camera_hz = 20.0;
s.start_x = 6.4;
s.start_y = 4.0;
s.start_yaw = M_PI / 2.0;
v->push_back(s);
SlopeInfo si;
si.world = kWorld;
si.waypoints = {{6.4, 7.0}, {6.4, 24.5}, {6.4, 27.6}, {9.0, 27.6},
{9.0, 24.5}, {9.0, 6.6}, {6.4, 6.0}, {6.4, 4.0}};
SlopeTable().emplace_back(s.name, si);
}
// Quay dau o y = 27.5 (san tren, 2 m qua dinh lan): doc 5 do dai 17.15 m,
// dinh o y = 25.15, nen quay som hon (24.5) la con tren doc -- thieu doan
// dinh doc, cho kho nhat cua VO. San tren trong tu y 25.5 toi cot o 29.3.
const struct { const char* name; const char* what; double x; } lanes[] = {
{"slope_lane5", "doc 5 do: len het lan, qua dinh, quay xuong", 1.2},
{"slope_lane10", "doc 10 do: len het lan, qua dinh, quay xuong", 3.8},
{"slope_lane15", "doc 15 do: len het lan, qua dinh, quay xuong", 6.4},
{"slope_lane20", "doc 20 do: len het lan, qua dinh, quay xuong", 9.0},
{"slope_lane30", "doc 30 do: len het lan, qua dinh, quay xuong", 11.6},
};
for (const auto& l : lanes) {
Scenario s{};
s.name = l.name;
s.what = l.what;
s.camera = true;
s.camera_hz = 20.0;
s.start_x = l.x;
s.start_y = 5.0;
s.start_yaw = M_PI / 2.0;
v->push_back(s);
SlopeInfo si;
si.world = kWorld;
si.waypoints = {{l.x, 27.5}, {l.x, 5.5}};
SlopeTable().emplace_back(s.name, si);
}
}
// Bam waypoint bang SU THAT (nhu nguoi lai nhin thay robot): quay ve phia
// diem ke, tien khi da gan dung huong. Lenh phat lai moi lat 50 ms (watchdog
// cua base), `after_slice` chay sau moi lat (ham hang doi ghi).
bool DriveWaypoints(vslam::SimSource* sim, const std::vector<std::pair<double, double>>& wps,
double cruise, const std::function<void()>& after_slice,
double* sim_s) {
constexpr double kSlice = 0.05;
constexpr double kMaxS = 900.0;
size_t k = 0;
double t = 0.0;
while (k < wps.size() && t < kMaxS) {
const vslam::SimPose3 p = sim->ground_truth_3d();
const double dx = wps[k].first - p.x, dy = wps[k].second - p.y;
if (std::hypot(dx, dy) < 0.25) {
++k;
continue;
}
double err = std::atan2(dy, dx) - p.yaw;
err = std::atan2(std::sin(err), std::cos(err));
const double wz = std::max(-0.6, std::min(0.6, 1.5 * err));
const double vx = std::fabs(err) < 0.2 ? cruise : (std::fabs(err) < 0.6 ? 0.3 * cruise : 0.0);
sim->base()->SetVelocity(vx, wz);
sim->RunFor(kSlice);
t += kSlice;
after_slice();
}
// Dung han nua giay: khung cuoi co robot dung yen.
for (int i = 0; i < 10; ++i) {
sim->base()->SetVelocity(0.0, 0.0);
sim->RunFor(kSlice);
t += kSlice;
after_slice();
}
*sim_s = t;
return k == wps.size();
}
std::string ResourceDir() {
const char* e = std::getenv("VSLAM_RESOURCE_DIR");
return e != nullptr && *e != '\0' ? std::string(e) : std::string("resources");
}
std::vector<Scenario> Scenarios() {
return {
std::vector<Scenario> v = {
{"straight", "tich phan odometry, EKF, ScanSanitizer",
{{0.35, 0.0, 8.0}, {0.0, 0.0, 1.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
@@ -130,6 +256,8 @@ std::vector<Scenario> Scenarios() {
{"spin", "cong vat can cua cliff_detect trong hanh lang hep",
{{0.0, 1.0, 7.0}}, 0.0, 0.0, false, -0.40f, true, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
};
AddSlopeScenarios(&v);
return v;
}
} // namespace
@@ -137,6 +265,13 @@ std::vector<Scenario> Scenarios() {
int main(int argc, char** argv) {
std::string name, out_dir = ".";
bool list = false;
// Mac dinh GIU hinh hoc cu cua SimConfig va KHONG ghi su that: bo hoi quy
// (tools/regress.sh) so voi ban ghi dung bang cach do.
std::string robot_yaml;
bool write_gt = false;
bool use_gl = false; // ve camera bang GPU (anh IR) -- chi kich ban doc
uint32_t cam_decimate = 2; // anh 640x480 / N, nhu crop_decimate cua robot
double gl_headlight = -1.0, gl_ambient = -1.0; // am = mac dinh renderer
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
@@ -144,10 +279,26 @@ int main(int argc, char** argv) {
if (a == "--scenario") name = next();
else if (a == "--out-dir") out_dir = next();
else if (a == "--list") list = true;
else if (a == "--robot") robot_yaml = next();
else if (a == "--gt") write_gt = true;
else if (a == "--gl") use_gl = true;
else if (a == "--cam-decimate") cam_decimate = static_cast<uint32_t>(std::atoi(next().c_str()));
else if (a == "--gl-headlight") gl_headlight = std::atof(next().c_str());
else if (a == "--gl-ambient") gl_ambient = std::atof(next().c_str());
else if (a == "--help") {
std::printf("cach dung: %s --scenario TEN --out-dir D\n"
std::printf("cach dung: %s --scenario TEN --out-dir D [--robot robot.yaml] [--gt]\n"
" %s --list\n"
" %s --scenario all --out-dir D\n", argv[0], argv[0], argv[0]);
" %s --scenario all --out-dir D\n"
" --robot F hinh hoc robot THAT (banh, LiDAR, camera, IMU) tu robot.yaml\n"
" thay vi so mac dinh cu cua SimConfig\n"
" --gt ghi them tu the THAT 6-DoF (stream ground_truth) moi\n"
" buoc vat ly, de cham diem offline\n"
" kich ban doc (slope_*, hoac slope_all): chay worlds/slope_test.world,\n"
" hinh hoc robot that, luon ghi su that. Can\n"
" GAZEBO_MODEL_PATH=$PWD/resources/models.\n"
" --gl ve camera bang GPU: ghi them anh IR (build VSLAM_SIM_WITH_GL)\n"
" --cam-decimate N anh 640x480 / N (mac dinh 2 = 320x240 nhu robot)\n",
argv[0], argv[0], argv[0]);
return 0;
}
}
@@ -159,9 +310,47 @@ int main(int argc, char** argv) {
return name.empty() && !list ? 2 : 0;
}
vslam::RobotModel robot;
if (!robot_yaml.empty()) {
const vslam::StatusResponse rs = robot.LoadFile(robot_yaml);
if (!rs.ok()) {
std::fprintf(stderr, "%s: %s\n", robot_yaml.c_str(), rs.message.c_str());
return 1;
}
}
// Kich ban doc LUON dung hinh hoc robot that: --robot, hoac robot.yaml cua
// VSLAM_CONFIG_DIR / configuration_files.
vslam::RobotModel slope_robot;
bool slope_robot_ok = false;
auto load_slope_robot = [&]() -> bool {
if (slope_robot_ok) return true;
std::string p = robot_yaml;
if (p.empty()) {
const char* cd = std::getenv("VSLAM_CONFIG_DIR");
p = (cd != nullptr && *cd != '\0' ? std::string(cd) : std::string("configuration_files")) +
"/robot.yaml";
}
const vslam::StatusResponse rs = slope_robot.LoadFile(p);
if (!rs.ok()) {
std::fprintf(stderr, "kich ban doc can robot.yaml: %s: %s\n", p.c_str(), rs.message.c_str());
return false;
}
slope_robot_ok = true;
return true;
};
int written = 0;
for (const Scenario& s : all) {
if (name != "all" && name != s.name) continue;
const SlopeInfo* si = FindSlope(s.name);
const bool slope = si != nullptr;
// `all` = bo hoi quy (chi kich ban phang). `slope_all` = moi kich ban doc.
const bool pick = (name == "all" && !slope) || (name == "slope_all" && slope) || name == s.name;
if (!pick) continue;
if (use_gl && !slope) {
std::fprintf(stderr, "%s: --gl chi cho kich ban doc (can mesh cua world)\n", s.name);
return 2;
}
vslam::SimConfig cfg;
cfg.seed = 1234; // co dinh: cung kich ban => cung file
@@ -176,12 +365,40 @@ int main(int argc, char** argv) {
cfg.lidar_cut_at = s.lidar_cut_at;
cfg.lidar_cut_for = s.lidar_cut_for;
cfg.camera_rate_hz = s.camera_hz;
if (!robot_yaml.empty()) vslam::SimConfigFromRobot(robot, &cfg);
if (slope) {
if (!load_slope_robot()) return 1;
vslam::SimConfigFromRobot(slope_robot, &cfg);
cfg.world_path = ResourceDir() + "/" + si->world;
// Nhanh nhat co the; ham theo hang doi ghi ben duoi nen khong rot chunk.
cfg.speed = 0.0;
cfg.depth_decimate = std::max<uint32_t>(1, cam_decimate);
// Noi suy D410 THAT o 640x480: fx = 595.914 -> HFOV 56.5 do (mac dinh sim 69).
cfg.depth_hfov_rad = 2.0 * std::atan(320.0 / 595.914);
}
vslam::SimSource sim(cfg);
if (!sim.Open().ok()) {
std::fprintf(stderr, "%s: sim khong mo duoc\n", s.name);
return 1;
}
if (use_gl) {
#ifdef VSLAM_HAVE_SIM_GL
std::string gerr;
vslam::GlRendererConfig gc = vslam::DefaultGlRendererConfig();
if (gl_headlight >= 0.0) gc.headlight = gl_headlight;
if (gl_ambient >= 0.0) gc.ambient = gl_ambient;
auto r = vslam::CreateGlCameraRenderer(sim.world(), gc, &gerr);
if (!r) {
std::fprintf(stderr, "%s: --gl: %s\n", s.name, gerr.c_str());
return 1;
}
sim.SetCameraRenderer(r);
#else
std::fprintf(stderr, "--gl: tool build KHONG co -DVSLAM_SIM_WITH_GL=ON\n");
return 2;
#endif
}
if (s.glass_at != 0.0) {
// Kinh phai la o BI CHIEM: no la vat can THAT, chi la vat can ma
// LiDAR va depth khong thay.
@@ -203,10 +420,24 @@ int main(int argc, char** argv) {
}
const std::string path = out_dir + "/" + s.name + ".vsr";
// Kich ban doc: ghi nhieu IMU vao header de bo xuat DM-VIO lay dung mat do
// nhieu, khong doan.
char imu_note[160] = "";
if (slope) {
std::snprintf(imu_note, sizeof(imu_note),
",\"gyro_noise_stddev\":%.6g,\"accel_noise_stddev\":%.6g",
cfg.gyro_noise_stddev, cfg.accel_noise_stddev);
}
vslam::RecordWriterConfig wc;
wc.path = path;
wc.compress = false; // nen = khong tat dinh giua cac phien ban zstd
wc.config_json = std::string("{\"scenario\":\"") + s.name + "\",\"seed\":1234}";
wc.config_json = std::string("{\"scenario\":\"") + s.name + "\",\"seed\":1234" +
(robot_yaml.empty() ? "" : ",\"robot\":\"" + robot_yaml + "\"") +
(write_gt || slope ? ",\"ground_truth\":true" : "") +
(slope ? std::string(",\"world\":\"") + si->world + "\",\"gl\":" +
(use_gl ? "true" : "false") + imu_note
: std::string("")) +
"}";
vslam::RecordWriter w(wc);
const vslam::StatusResponse st = w.Open();
@@ -251,6 +482,15 @@ int main(int argc, char** argv) {
vslam::EncodeEncoderPayload(e.left_rad, e.right_rad, &b_enc);
w.Write(vslam::VsrStream::kEncoder, e.stamp, b_enc);
});
std::string b_gt, b_ir;
if (write_gt || slope) {
sim.SetGroundTruthCallback([&](vslam::UnixTime t, const vslam::SimPose3& p) {
const double v[6] = {p.x, p.y, p.z, p.roll, p.pitch, p.yaw};
b_gt.clear();
vslam::EncodeGroundTruthPayload(v, &b_gt);
w.Write(vslam::VsrStream::kGroundTruth, t, b_gt);
});
}
if (sim.camera() != nullptr) {
sim.camera()->SetCallback([&](const vslam::CameraFrame& f) {
if (!f.depth) return;
@@ -260,6 +500,13 @@ int main(int argc, char** argv) {
b_depth.clear();
vslam::EncodeImagePayload(*f.depth, &b_depth);
w.Write(vslam::VsrStream::kDepth, f.header.stamp, b_depth);
// Anh IR (chi khi ve bang GPU). SAU depth: replay rap khung theo thu
// tu camera_info -> depth -> infra1.
if (f.infra1) {
b_ir.clear();
vslam::EncodeImagePayload(*f.infra1, &b_ir);
w.Write(vslam::VsrStream::kInfra1, f.header.stamp, b_ir);
}
});
sim.camera()->Open();
}
@@ -278,6 +525,20 @@ int main(int argc, char** argv) {
// Phat lai o 20 Hz cung la dung cai ma luong safety lam tren robot that.
constexpr double kSlice = 0.05;
double total = 0.0;
if (slope) {
// Ham: writer chay luong rieng va DROP khi hang doi day -- cho no ghi
// bot truoc khi mo phong chay tiep (sim chay nhanh hon thoi gian thuc).
auto throttle = [&w]() {
while (w.Stats().queue_bytes > (48u << 20)) {
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
};
if (!DriveWaypoints(&sim, si->waypoints, si->cruise, throttle, &total)) {
std::fprintf(stderr, "%s: KHONG toi het waypoint trong thoi gian cho phep\n", s.name);
w.Close();
return 1;
}
}
for (const Leg& leg : s.legs) {
double left = leg.seconds;
while (left > 1e-9) {

View File

@@ -0,0 +1,127 @@
// vslam_render_preview -- ve MOT khung camera mo phong bang GPU ra file PNG.
//
// vslam_render_preview --world W.world [--models DIR]... --x X --y Y --yaw R
// [--z 0.445] [--pitch 0] [--w 640] [--h 480]
// [--hfov-deg 69 | --fx F] --out PREFIX
//
// Ra: PREFIX_ir.png (anh xam 8 bit), PREFIX_depth.png (16 bit, mm -- dung
// quy uoc RealSense), PREFIX_depth_vis.png (to mau de nhin). In GPU dang dung,
// ti le diem co depth, do sang/do tuong phan anh IR.
//
// Dung de NHIN truoc khi tin: texture co len khong, depth co khop hinh khong,
// camera co dung huong khong. `--z` la do cao camera so voi z = 0 cua world
// (cong them san neu dung tren san cao). `--pitch` duong = chuc xuong.
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include "vslam/gazebo_world.h"
#include "vslam/sim_gl_renderer.h"
int main(int argc, char** argv) {
std::string world, out;
std::vector<std::string> models;
double x = 0, y = 0, z = 0.445, yaw = 0, pitch = 0, hfov_deg = 69.0, fx = 0;
int w = 640, h = 480;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--world") world = next();
else if (a == "--models") models.push_back(next());
else if (a == "--x") x = std::atof(next().c_str());
else if (a == "--y") y = std::atof(next().c_str());
else if (a == "--z") z = std::atof(next().c_str());
else if (a == "--yaw") yaw = std::atof(next().c_str());
else if (a == "--pitch") pitch = std::atof(next().c_str());
else if (a == "--w") w = std::atoi(next().c_str());
else if (a == "--h") h = std::atoi(next().c_str());
else if (a == "--hfov-deg") hfov_deg = std::atof(next().c_str());
else if (a == "--fx") fx = std::atof(next().c_str());
else if (a == "--out") out = next();
else {
std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str());
return 2;
}
}
if (world.empty() || out.empty()) {
std::fprintf(stderr, "can --world va --out\n");
return 2;
}
vslam::GazeboWorld gw;
vslam::StatusResponse st = vslam::LoadGazeboWorld(world, models, &gw);
if (!st.ok()) {
std::fprintf(stderr, "world: %s\n", st.message.c_str());
return 1;
}
std::string err;
auto r = vslam::CreateGlCameraRenderer(gw, vslam::DefaultGlRendererConfig(), &err);
if (!r) {
std::fprintf(stderr, "renderer: %s\n", err.c_str());
return 1;
}
// Than: Rz(yaw) * Ry(pitch). Quang hoc: X = -Y than, Y = -Z than, Z = X than.
const double cy = std::cos(yaw), sy = std::sin(yaw), cp = std::cos(pitch), sp = std::sin(pitch);
const double fwd[3] = {cy * cp, sy * cp, -sp};
const double left[3] = {-sy, cy, 0.0};
const double up[3] = {cy * sp, sy * sp, cp};
vslam::SimCameraView v;
for (int i = 0; i < 3; ++i) {
v.R_wc[i * 3 + 0] = -left[i];
v.R_wc[i * 3 + 1] = -up[i];
v.R_wc[i * 3 + 2] = fwd[i];
}
v.t_wc[0] = x;
v.t_wc[1] = y;
v.t_wc[2] = z;
v.width = w;
v.height = h;
v.fx = fx > 0 ? fx : (w / 2.0) / std::tan(hfov_deg * M_PI / 360.0);
v.fy = v.fx;
v.cx = w / 2.0;
v.cy = h / 2.0;
std::vector<uint8_t> ir;
std::vector<float> depth;
if (!r->Render(v, &ir, &depth)) {
std::fprintf(stderr, "ve hong (xem log)\n");
return 1;
}
cv::Mat im_ir(h, w, CV_8UC1, ir.data());
cv::Mat im_d(h, w, CV_16UC1);
size_t valid = 0;
double dmin = 1e9, dmax = 0;
for (int rr = 0; rr < h; ++rr) {
for (int c = 0; c < w; ++c) {
const float d = depth[static_cast<size_t>(rr) * w + c];
im_d.at<uint16_t>(rr, c) = d > 0 ? static_cast<uint16_t>(std::min(65535.0f, d * 1000.0f)) : 0;
if (d > 0) { valid++; dmin = std::min<double>(dmin, d); dmax = std::max<double>(dmax, d); }
}
}
cv::Mat vis8, vis;
im_d.convertTo(vis8, CV_8UC1, 255.0 / std::max(1.0, dmax * 1000.0));
cv::applyColorMap(vis8, vis, cv::COLORMAP_JET);
vis.setTo(cv::Scalar(0, 0, 0), im_d == 0);
cv::imwrite(out + "_ir.png", im_ir);
cv::imwrite(out + "_depth.png", im_d);
cv::imwrite(out + "_depth_vis.png", vis);
cv::Scalar mean, sd;
cv::meanStdDev(im_ir, mean, sd, im_d > 0);
std::printf("%s\n", r->Describe().c_str());
std::printf("depth: %.1f%% diem co gia tri, %.3f..%.3f m | IR (vung co depth): "
"trung binh %.1f, do lech %.1f\n",
100.0 * valid / (static_cast<double>(w) * h), valid ? dmin : 0.0, dmax,
mean[0], sd[0]);
std::printf("ghi %s_ir.png, %s_depth.png, %s_depth_vis.png\n", out.c_str(), out.c_str(),
out.c_str());
return 0;
}

453
tools/vslam_vo_bench.cc Normal file
View File

@@ -0,0 +1,453 @@
// vslam_vo_bench -- chay odometry thi giac RTAB-Map (mac dinh F2M) tren anh
// IR + depth cua mot ban ghi .vsr, xuat quy dao TUM de cham diem z tren doc.
//
// vslam_vo_bench --in X.vsr --out TRAJ.txt [--robot robot.yaml]
// [--guess wheel|none] [--param Key=Value]... [--stats S.json]
// [--reset-after N] [--ref-out REF.txt] [--imu-orient]
// [--imu-hz N] [--accel-bias x,y,z] [--gyro-bias x,y,z]
// [--enc-scale K] [--ir-noise SIGMA] [--seed N] [--no-vo]
// [--ga-alpha A] [--pitch-source ga|sensor] [--sensor-hz N]
// [--sensor-bias-deg B] [--sensor-noise-deg S] [--sensor-lag-ms L]
//
// Ra: TRAJ.txt = "giay x y z qx qy qz qw" cua base_footprint trong frame
// odom (goc = tu the robot o khung dau), chi khung odometry TINH DUOC.
// S.json = so khung, so khung mat bam, so lan reset, ms/khung.
// REF.txt = HANG THAM CHIEU, cung dinh dang, tai cung cac khung anh: z tich
// tu encoder va pitch cua GravityAlign (dung class vslam_node dung):
// z += -ds * sin(pitch), xy += ds * cos(pitch). VO phai thang hang nay moi
// dang chi phi.
//
// --imu-orient: dua roll/pitch cua GravityAlign vao moi khung (rtabmap::IMU,
// khong co yaw). RTAB-Map dung no de dat tu the dau theo trong luc va doan
// phep quay -- giu pitch khoi troi, la thu F2M mot minh khong co.
//
// ================== NUM "GIONG THAT" ==================
// Ban ghi sim SACH (IMU 200 Hz khong bias, banh khong truot, anh khong
// nhieu) -- thuan loi qua muc cho moi thu song nho IMU. Lam xau o day:
// --imu-hz N chi giu ~N mau IMU/giay (WT61PC hien 10 Hz)
// --accel-bias x,y,z cong bias co dinh (m/s^2) -- x lam lech pitch
// --gyro-bias x,y,z (rad/s)
// --enc-scale K encoder doc K lan quang duong that (truot banh /
// sai ban kinh) -- ca doan F2M lan tham chieu
// --ir-noise SIGMA nhieu Gauss tren anh IR truoc khi vao VO
// --no-vo chi tinh tham chieu (nhanh)
// --pitch-source sensor pitch cua hang tham chieu lay tu goc DA LOC cua
// chinh cam bien (khung Angle 0x53 cua WT61PC) thay vi
// tu loc gyro/accel tho. Gia lap: pitch THAT (stream
// ground truth) lay mau --sensor-hz, cong bias + nhieu,
// tre --sensor-lag-ms, giu gia tri giua hai mau. LAC
// QUAN: bo loc trong cam bien that co sai rieng (vd khi
// xe tang toc) -- phai do lai tren robot.
// --ga-alpha A alpha bo loc bu cua GravityAlign (mac dinh 0.98 cua
// pipeline.yaml, tinh MOI MAU: 10 Hz -> tau 5 s,
// 200 Hz -> tau 0.25 s)
//
// ================== BO THAM SO RIENG ==================
// KHONG ke thua slam.yaml: SLAM dang chay Reg/Strategy=1 (ICP) va
// Reg/Force3DoF=true -- ke thua la mat z ngay tu dau. O day:
// Odom/Strategy=0 (F2M), Reg/Strategy=0 (thi giac), Reg/Force3DoF=false,
// Vis/MaxDepth=4 (depth stereo xa hon thi sai so binh phuong khoang cach),
// Vis/MinInliers=15, OdomF2M/BundleAdjustment=1.
// Ngoai lai base_link <- camera_depth_optical_frame TINH tu robot.yaml (khong
// TiltLift: odometry tu tinh chuc ngoc cua than).
//
// Doan chuyen dong (--guess wheel, mac dinh): encoder banh -> buoc SE(2) cua
// than giua hai khung. Tren doc buoc nay van dung trong frame THAN (banh lan
// doc mat doc = truc x cua than).
//
// Mat bam: odometry tra pose rong. Sau N khung mat lien tiep (--reset-after,
// mac dinh 5) thi reset odometry TAI pose doan bang encoder -- giong cach
// vslam_node se lam khi VO hong. Moi lan reset la mot lan dem.
#include <algorithm>
#include <array>
#include <deque>
#include <chrono>
#include <random>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <opencv2/core.hpp>
#include <rtabmap/core/CameraModel.h>
#include <rtabmap/core/IMU.h>
#include <rtabmap/core/Odometry.h>
#include <rtabmap/core/OdometryInfo.h>
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/utilite/ULogger.h>
#include "vslam/gravity_align.h"
#include "vslam/node_constants.h"
#include "vslam/record_format.h"
#include "vslam/record_io.h"
#include "vslam/robot_model.h"
#include "vslam/sensor_data_builder.h"
namespace {
struct PendingImage {
int64_t t = -1;
cv::Mat mat;
};
cv::Mat ToMat(const vslam::Image& img) {
const int type = img.format == vslam::PixelFormat::kMono16 ? CV_16UC1 : CV_8UC1;
// Ban sao sau: payload cua chunk bi ghi de o lan doc ke tiep.
return cv::Mat(static_cast<int>(img.height), static_cast<int>(img.width), type,
const_cast<uint8_t*>(img.data), img.step)
.clone();
}
bool ParseVec3(const std::string& s, double v[3]) {
return std::sscanf(s.c_str(), "%lf,%lf,%lf", &v[0], &v[1], &v[2]) == 3;
}
void WriteTum(FILE* f, double t, const rtabmap::Transform& T) {
float x, y, z, qx, qy, qz, qw;
T.getTranslation(x, y, z);
const Eigen::Quaternionf q = T.getQuaternionf();
qx = q.x(); qy = q.y(); qz = q.z(); qw = q.w();
std::fprintf(f, "%.9f %.6f %.6f %.6f %.9f %.9f %.9f %.9f\n", t, x, y, z, qx, qy, qz, qw);
}
} // namespace
int main(int argc, char** argv) {
std::string in, out, robot_yaml, stats_path, ref_path, guess_mode = "wheel";
int reset_after = 5;
bool imu_orient = false, no_vo = false;
double imu_hz = 0.0, enc_scale = 1.0, ir_noise = 0.0, ga_alpha = -1.0;
std::string pitch_source = "ga";
double sensor_hz = 10.0, sensor_bias_deg = 0.0, sensor_noise_deg = 0.0, sensor_lag_ms = 0.0;
double accel_bias[3] = {0, 0, 0}, gyro_bias[3] = {0, 0, 0};
uint32_t seed = 1;
rtabmap::ParametersMap params;
params[rtabmap::Parameters::kOdomStrategy()] = "0";
params[rtabmap::Parameters::kRegStrategy()] = "0";
params[rtabmap::Parameters::kRegForce3DoF()] = "false";
params[rtabmap::Parameters::kVisMaxDepth()] = "4.0";
params[rtabmap::Parameters::kVisMinInliers()] = "15";
params[rtabmap::Parameters::kOdomF2MBundleAdjustment()] = "1";
params[rtabmap::Parameters::kOdomResetCountdown()] = "0";
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--in") in = next();
else if (a == "--out") out = next();
else if (a == "--robot") robot_yaml = next();
else if (a == "--stats") stats_path = next();
else if (a == "--guess") guess_mode = next();
else if (a == "--reset-after") reset_after = std::atoi(next().c_str());
else if (a == "--ref-out") ref_path = next();
else if (a == "--imu-orient") imu_orient = true;
else if (a == "--no-vo") no_vo = true;
else if (a == "--imu-hz") imu_hz = std::atof(next().c_str());
else if (a == "--enc-scale") enc_scale = std::atof(next().c_str());
else if (a == "--ga-alpha") ga_alpha = std::atof(next().c_str());
else if (a == "--pitch-source") pitch_source = next();
else if (a == "--sensor-hz") sensor_hz = std::atof(next().c_str());
else if (a == "--sensor-bias-deg") sensor_bias_deg = std::atof(next().c_str());
else if (a == "--sensor-noise-deg") sensor_noise_deg = std::atof(next().c_str());
else if (a == "--sensor-lag-ms") sensor_lag_ms = std::atof(next().c_str());
else if (a == "--ir-noise") ir_noise = std::atof(next().c_str());
else if (a == "--seed") seed = static_cast<uint32_t>(std::atoi(next().c_str()));
else if (a == "--accel-bias" || a == "--gyro-bias") {
if (!ParseVec3(next(), a == "--accel-bias" ? accel_bias : gyro_bias)) {
std::fprintf(stderr, "%s can x,y,z\n", a.c_str());
return 2;
}
}
else if (a == "--param") {
const std::string kv = next();
const size_t eq = kv.find('=');
if (eq == std::string::npos) {
std::fprintf(stderr, "--param can Key=Value: %s\n", kv.c_str());
return 2;
}
params[kv.substr(0, eq)] = kv.substr(eq + 1);
} else {
std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str());
return 2;
}
}
if (in.empty() || out.empty() || (guess_mode != "wheel" && guess_mode != "none")) {
std::fprintf(stderr, "can --in, --out; --guess wheel|none\n");
return 2;
}
if (robot_yaml.empty()) {
const char* cd = std::getenv("VSLAM_CONFIG_DIR");
robot_yaml = (cd != nullptr && *cd != '\0' ? std::string(cd) : std::string("configuration_files")) +
"/robot.yaml";
}
vslam::RobotModel robot;
const vslam::StatusResponse rs = robot.LoadFile(robot_yaml);
if (!rs.ok()) {
std::fprintf(stderr, "%s: %s\n", robot_yaml.c_str(), rs.message.c_str());
return 1;
}
vslam::Transform T_bl_cam, T_bl_imu;
if (!robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kCameraDepthOpticalFrame, &T_bl_cam) ||
!robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kImuFrame, &T_bl_imu)) {
std::fprintf(stderr, "robot.yaml thieu camera_depth_optical_frame / imu_link\n");
return 1;
}
const rtabmap::Transform imu_local = vslam::ToRtabmap(T_bl_imu);
const rtabmap::Transform local = vslam::ToRtabmap(T_bl_cam);
const double r_wheel = robot.geometry().wheel_radius;
const double sep = robot.geometry().wheel_separation;
// base_link -> base_footprint: chi tinh tien z.
const rtabmap::Transform T_bl_fp(0, 0, static_cast<float>(-r_wheel), 0, 0, 0);
ULogger::setType(ULogger::kTypeConsole);
ULogger::setLevel(ULogger::kError);
std::unique_ptr<rtabmap::Odometry> odom(rtabmap::Odometry::create(params));
vslam::RecordReader reader;
const vslam::StatusResponse st = reader.Open(in);
if (!st.ok()) {
std::fprintf(stderr, "%s: %s\n", in.c_str(), st.message.c_str());
return 1;
}
FILE* fo = std::fopen(out.c_str(), "w");
if (fo == nullptr) {
std::fprintf(stderr, "khong ghi duoc %s\n", out.c_str());
return 1;
}
std::fprintf(fo, "# vslam_vo_bench %s: base_footprint trong frame odom (TUM)\n", in.c_str());
FILE* fr = nullptr;
if (!ref_path.empty()) {
fr = std::fopen(ref_path.c_str(), "w");
if (fr == nullptr) {
std::fprintf(stderr, "khong ghi duoc %s\n", ref_path.c_str());
return 1;
}
std::fprintf(fr, "# tham chieu ds*sin(pitch GravityAlign) %s: base_footprint (TUM)\n",
in.c_str());
}
// Mac dinh cua GravityAlignConfig = pipeline.yaml (alpha 0.98, LPF 0.05,
// cong 1.0, tru gia toc odom).
vslam::GravityAlignConfig gcfg;
gcfg.wheel_radius = r_wheel;
if (ga_alpha >= 0.0) gcfg.alpha = ga_alpha;
vslam::GravityAlign ga(gcfg);
double rx = 0, ry = 0, rz = 0; // tham chieu: xy ngang + z tich luy
int64_t enc_t = -1, imu_kept_t = -1;
// --pitch-source sensor: goc cam bien gia lap tu ground truth (xem dau file).
const bool use_sensor = pitch_source == "sensor";
double s_roll = 0.0, s_pitch = 0.0;
int64_t s_next = -1;
std::deque<std::array<double, 3>> s_pending; // {t_den_ns, roll, pitch}
std::normal_distribution<double> n_ang(0.0, 1.0);
auto ref_pitch = [&]() { return use_sensor ? s_pitch : ga.pitch(); };
auto ref_roll = [&]() { return use_sensor ? s_roll : ga.roll(); };
std::mt19937 rng(seed);
std::normal_distribution<double> n01(0.0, 1.0);
vslam::CameraInfo info;
bool have_info = false;
PendingImage depth, ir;
// Odometry banh: pose SE(2) tich luy cua than, cap nhat moi encoder.
bool enc_init = false;
double enc_l = 0, enc_r = 0, wx = 0, wy = 0, wyaw = 0;
double fx_prev = 0, fy_prev = 0, fyaw_prev = 0; // pose banh luc khung truoc
int frames = 0, lost = 0, lost_run = 0, resets = 0, keyframes = 0;
long inliers_sum = 0;
std::vector<double> ms;
rtabmap::Transform last_pose = rtabmap::Transform::getIdentity();
rtabmap::Transform guess_since_last = rtabmap::Transform::getIdentity();
vslam::VsrChunkHeader h;
std::string payload;
std::vector<uint8_t> storage;
while (reader.Next(&h, &payload)) {
const int64_t t = static_cast<int64_t>(h.stamp_ns);
if (h.stream == vslam::VsrStream::kCameraInfo && !have_info) {
have_info = vslam::DecodeCameraInfoPayload(payload, &info);
continue;
}
if (h.stream == vslam::VsrStream::kEncoder) {
double l, r;
if (!vslam::DecodeEncoderPayload(payload, &l, &r)) continue;
if (enc_init) {
const double dl = (l - enc_l) * r_wheel * enc_scale;
const double dr = (r - enc_r) * r_wheel * enc_scale;
const double ds = 0.5 * (dl + dr), dth = (dr - dl) / sep;
wx += ds * std::cos(wyaw + 0.5 * dth);
wy += ds * std::sin(wyaw + 0.5 * dth);
// Tham chieu: pitch duong = mui chuc xuong, nen len doc pitch am.
const double p = ref_pitch();
rx += ds * std::cos(p) * std::cos(wyaw + 0.5 * dth);
ry += ds * std::cos(p) * std::sin(wyaw + 0.5 * dth);
rz += -ds * std::sin(p);
wyaw += dth;
const double dt = (t - enc_t) * 1e-9;
if (dt > 0.0) ga.FeedOdom(vslam::UnixTime::fromNSec(t), ds / dt, dth / dt);
}
enc_l = l;
enc_r = r;
enc_t = t;
enc_init = true;
continue;
}
if (use_sensor && h.stream == vslam::VsrStream::kGroundTruth) {
double g[6];
if (!vslam::DecodeGroundTruthPayload(payload, g)) continue;
const double d2r = M_PI / 180.0;
if (s_next < 0 || t >= s_next) {
s_pending.push_back({static_cast<double>(t) + sensor_lag_ms * 1e6,
g[3] + sensor_noise_deg * d2r * n_ang(rng),
g[4] + sensor_bias_deg * d2r + sensor_noise_deg * d2r * n_ang(rng)});
s_next = t + static_cast<int64_t>(1e9 / sensor_hz);
}
while (!s_pending.empty() && s_pending.front()[0] <= static_cast<double>(t)) {
s_roll = s_pending.front()[1];
s_pitch = s_pending.front()[2];
s_pending.pop_front();
}
continue;
}
if (h.stream == vslam::VsrStream::kImu) {
vslam::Imu m;
if (!vslam::DecodeImuPayload(payload, &m)) continue;
// Ha tan so: giu mau cach mau giu truoc >= 1/N (dung sai 1 ms).
if (imu_hz > 0.0 && imu_kept_t >= 0 &&
t - imu_kept_t < static_cast<int64_t>(1e9 / imu_hz) - 1000000) {
continue;
}
imu_kept_t = t;
m.linear_acceleration.x += accel_bias[0];
m.linear_acceleration.y += accel_bias[1];
m.linear_acceleration.z += accel_bias[2];
m.angular_velocity.x += gyro_bias[0];
m.angular_velocity.y += gyro_bias[1];
m.angular_velocity.z += gyro_bias[2];
ga.FeedImu(m);
continue;
}
if (h.stream != vslam::VsrStream::kDepth && h.stream != vslam::VsrStream::kInfra1) continue;
vslam::Image img;
if (!vslam::DecodeImagePayload(payload, &img, &storage)) continue;
PendingImage& slot = h.stream == vslam::VsrStream::kDepth ? depth : ir;
slot.t = t;
slot.mat = ToMat(img);
if (depth.t != ir.t || !have_info) continue; // cho du cap cung gio
// Buoc banh tu khung truoc, trong frame than.
const double c = std::cos(fyaw_prev), s = std::sin(fyaw_prev);
const double ddx = c * (wx - fx_prev) + s * (wy - fy_prev);
const double ddy = -s * (wx - fx_prev) + c * (wy - fy_prev);
const double ddyaw = wyaw - fyaw_prev;
fx_prev = wx; fy_prev = wy; fyaw_prev = wyaw;
const rtabmap::Transform wheel_step(static_cast<float>(ddx), static_cast<float>(ddy), 0.0f,
0.0f, 0.0f, static_cast<float>(ddyaw));
rtabmap::Transform guess = guess_mode == "wheel" ? wheel_step : rtabmap::Transform();
if (no_vo) {
frames++;
depth.t = ir.t = -1;
if (fr != nullptr) {
const rtabmap::Transform ref(static_cast<float>(rx), static_cast<float>(ry),
static_cast<float>(rz), static_cast<float>(ref_roll()),
static_cast<float>(ref_pitch()), static_cast<float>(wyaw));
WriteTum(fr, t * 1e-9, ref);
}
continue;
}
if (ir_noise > 0.0) {
for (int yy = 0; yy < ir.mat.rows; ++yy) {
uint8_t* row = ir.mat.ptr<uint8_t>(yy);
for (int xx = 0; xx < ir.mat.cols; ++xx) {
const double v = row[xx] + ir_noise * n01(rng);
row[xx] = static_cast<uint8_t>(std::min(255.0, std::max(0.0, std::round(v))));
}
}
}
rtabmap::CameraModel model(info.fx_binned(), info.fy_binned(), info.cx_binned(),
info.cy_binned(), local, 0.0,
cv::Size(ir.mat.cols, ir.mat.rows));
rtabmap::SensorData data(ir.mat, depth.mat, model, frames + 1, t * 1e-9);
if (imu_orient && ga.valid()) {
// Huong IMU trong the gioi, yaw 0: RTAB-Map chi lay roll/pitch.
const Eigen::Quaterniond q = rtabmap::Transform(0, 0, 0, static_cast<float>(ga.roll()),
static_cast<float>(ga.pitch()), 0)
.getQuaterniond();
data.setIMU(rtabmap::IMU(cv::Vec4d(q.x(), q.y(), q.z(), q.w()),
cv::Mat::eye(3, 3, CV_64FC1) * 1e-4, cv::Vec3d(), cv::Mat(),
cv::Vec3d(), cv::Mat(), imu_local));
}
rtabmap::OdometryInfo oi;
const auto t0 = std::chrono::steady_clock::now();
rtabmap::Transform pose = odom->process(data, guess, &oi);
ms.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
.count());
frames++;
depth.t = ir.t = -1;
if (fr != nullptr) {
const rtabmap::Transform ref(static_cast<float>(rx), static_cast<float>(ry),
static_cast<float>(rz), static_cast<float>(ref_roll()),
static_cast<float>(ref_pitch()), static_cast<float>(wyaw));
WriteTum(fr, t * 1e-9, ref);
}
if (pose.isNull()) {
lost++;
lost_run++;
guess_since_last = guess_since_last * wheel_step;
if (reset_after > 0 && lost_run >= reset_after) {
// Tiep tuc tu pose doan bang banh -- VO mat bam thi vslam_node cung
// chi con banh + IMU.
last_pose = last_pose * guess_since_last;
guess_since_last = rtabmap::Transform::getIdentity();
odom->reset(last_pose);
resets++;
lost_run = 0;
}
continue;
}
lost_run = 0;
last_pose = pose;
guess_since_last = rtabmap::Transform::getIdentity();
inliers_sum += oi.reg.inliers;
if (oi.keyFrameAdded) keyframes++;
WriteTum(fo, t * 1e-9, pose * T_bl_fp);
}
std::fclose(fo);
if (fr != nullptr) std::fclose(fr);
if (frames == 0) {
std::fprintf(stderr, "khong co cap IR + depth nao (ghi bang vslam_record --gl)\n");
return 1;
}
if (no_vo) {
std::printf("%d khung, chi tham chieu (--no-vo)\n", frames);
return 0;
}
std::vector<double> sorted = ms;
std::sort(sorted.begin(), sorted.end());
double sum = 0;
for (double v : ms) sum += v;
const double mean = sum / ms.size();
const double p95 = sorted[static_cast<size_t>(0.95 * (sorted.size() - 1))];
const int ok = frames - lost;
std::printf("%d khung, mat bam %d (%.1f%%), reset %d, keyframe %d, inlier TB %.0f, "
"%.1f ms/khung (p95 %.1f)\n",
frames, lost, 100.0 * lost / frames, resets, keyframes,
ok > 0 ? static_cast<double>(inliers_sum) / ok : 0.0, mean, p95);
if (!stats_path.empty()) {
FILE* fs = std::fopen(stats_path.c_str(), "w");
if (fs != nullptr) {
std::fprintf(fs,
"{\"in\":\"%s\",\"frames\":%d,\"lost\":%d,\"resets\":%d,\"keyframes\":%d,"
"\"inliers_mean\":%.1f,\"ms_mean\":%.2f,\"ms_p95\":%.2f,\"guess\":\"%s\"}\n",
in.c_str(), frames, lost, resets, keyframes,
ok > 0 ? static_cast<double>(inliers_sum) / ok : 0.0, mean, p95,
guess_mode.c_str());
std::fclose(fs);
}
}
return 0;
}

412
tools/vslam_vsr_export.cc Normal file
View File

@@ -0,0 +1,412 @@
// vslam_vsr_export -- doi ban ghi .vsr cua bo mo phong (anh IR + IMU + su
// that) sang thu muc dataset cho DM-VIO, dinh dang TUM-VI "dso".
//
// vslam_vsr_export --in X.vsr --out DIR [--robot robot.yaml]
// [--imu-hz 0] [--imu-offset-ms 0]
// [--gyro-noise 0] [--accel-noise 0] [--seed 1]
// [--accel-bias x,y,z] [--gyro-bias x,y,z] [--ir-noise 0]
//
// Ra (DM-VIO doc theo src/dso/util/DatasetReader.h):
// DIR/cam0/images/<ns>.png anh IR 8 bit. DM-VIO ghep anh voi times.txt
// theo THU TU ten file da sap -- ten 19 chu so.
// DIR/cam0/times.txt "ns giay" moi anh.
// DIR/imu.txt "#..." roi "ns wx wy wz ax ay az". CO mau dung
// gio MOI anh: DM-VIO bo khung thieu mau trung gio.
// DIR/camera.txt pinhole kieu DSO, khong meo.
// DIR/camchain.yaml cam0/T_cam_imu (Kalibr) + noi suy.
// DIR/imu_noise.yaml mat do nhieu / bias (Kalibr imu.yaml).
// DIR/gt_imu.csv su that diem dat IMU, "ns,px,py,pz,qw,qx,qy,qz"
// (TUM-VI) -- dung cho gtFile cua DM-VIO.
// DIR/gt_cam_tum.txt su that camera (frame quang hoc), TUM.
// DIR/gt_base_tum.txt su that base_footprint, TUM.
// DIR/export.json thong so da dung.
//
// ================== LAM XAU DU LIEU O DAY, KHONG GHI LAI ==================
// Ban ghi mang IMU SACH 200 Hz. Muon thu "giong robot that" (WT61PC 10 Hz,
// lech gio camera-IMU, nhieu lon hon) thi lam o buoc xuat nay -- khong phai
// render lai anh:
// --imu-hz N giu moi k mau de con ~N Hz (0 = giu nguyen)
// --imu-offset-ms D CONG D ms vao stamp IMU: lech dong ho camera-IMU ma
// DM-VIO khong tu uoc luong
// --gyro-noise S, --accel-noise S them nhieu trang (sigma moi mau)
// --accel-bias / --gyro-bias x,y,z cong bias co dinh (m/s^2, rad/s)
// --ir-noise S nhieu Gauss tren anh IR (muc xam)
#include <sys/stat.h>
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <string>
#include <vector>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include "vslam/geometry.h"
#include "vslam/node_constants.h"
#include "vslam/record_format.h"
#include "vslam/record_io.h"
#include "vslam/robot_model.h"
namespace {
using vslam::Transform;
struct ImuS {
int64_t t = 0;
double w[3] = {0, 0, 0};
double a[3] = {0, 0, 0};
};
struct GtS {
int64_t t = 0;
double p[6] = {0, 0, 0, 0, 0, 0}; // x y z roll pitch yaw (base_footprint)
};
struct Frame {
int64_t t = 0;
int w = 0, h = 0;
std::vector<uint8_t> px;
};
bool MakeDir(const std::string& p) {
std::string cur;
for (size_t i = 0; i <= p.size(); ++i) {
if (i == p.size() || p[i] == '/') {
if (!cur.empty() && ::mkdir(cur.c_str(), 0775) != 0 && errno != EEXIST) return false;
}
if (i < p.size()) cur.push_back(p[i]);
}
return true;
}
Transform PoseOf(const GtS& g) {
Transform t;
t.translation.x = g.p[0];
t.translation.y = g.p[1];
t.translation.z = g.p[2];
t.rotation = vslam::QuaternionFromRPY(g.p[3], g.p[4], g.p[5]);
return t;
}
void WriteTum(FILE* f, int64_t t, const Transform& T) {
std::fprintf(f, "%.9f %.6f %.6f %.6f %.9f %.9f %.9f %.9f\n", t * 1e-9, T.translation.x,
T.translation.y, T.translation.z, T.rotation.x, T.rotation.y, T.rotation.z,
T.rotation.w);
}
// So theo khoa trong JSON phang cua header ("key":so). Khong co thi `def`.
double JsonNumber(const std::string& json, const std::string& key, double def) {
const std::string k = "\"" + key + "\":";
const size_t p = json.find(k);
if (p == std::string::npos) return def;
return std::strtod(json.c_str() + p + k.size(), nullptr);
}
ImuS Lerp(const ImuS& a, const ImuS& b, int64_t t) {
const double u = static_cast<double>(t - a.t) / static_cast<double>(b.t - a.t);
ImuS o;
o.t = t;
for (int i = 0; i < 3; ++i) {
o.w[i] = a.w[i] + u * (b.w[i] - a.w[i]);
o.a[i] = a.a[i] + u * (b.a[i] - a.a[i]);
}
return o;
}
} // namespace
int main(int argc, char** argv) {
std::string in, out, robot_yaml;
double imu_hz = 0.0, offset_ms = 0.0, gyro_noise = 0.0, accel_noise = 0.0, ir_noise = 0.0;
double accel_bias[3] = {0, 0, 0}, gyro_bias[3] = {0, 0, 0};
// Nhieu SAN co trong ban ghi (sigma moi mau) -- de ghi mat do nhieu dung vao
// imu_noise.yaml. vslam_record ghi chung vao header cua kich ban doc; am =
// chua biet, lay tu header.
double sim_gyro_sigma = -1.0, sim_accel_sigma = -1.0;
uint32_t seed = 1;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--in") in = next();
else if (a == "--out") out = next();
else if (a == "--robot") robot_yaml = next();
else if (a == "--imu-hz") imu_hz = std::atof(next().c_str());
else if (a == "--imu-offset-ms") offset_ms = std::atof(next().c_str());
else if (a == "--gyro-noise") gyro_noise = std::atof(next().c_str());
else if (a == "--accel-noise") accel_noise = std::atof(next().c_str());
else if (a == "--sim-gyro-sigma") sim_gyro_sigma = std::atof(next().c_str());
else if (a == "--sim-accel-sigma") sim_accel_sigma = std::atof(next().c_str());
else if (a == "--seed") seed = static_cast<uint32_t>(std::atoi(next().c_str()));
else if (a == "--ir-noise") ir_noise = std::atof(next().c_str());
else if (a == "--accel-bias" || a == "--gyro-bias") {
double* v = a == "--accel-bias" ? accel_bias : gyro_bias;
if (std::sscanf(next().c_str(), "%lf,%lf,%lf", &v[0], &v[1], &v[2]) != 3) {
std::fprintf(stderr, "%s can x,y,z\n", a.c_str());
return 2;
}
}
else {
std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str());
return 2;
}
}
if (in.empty() || out.empty()) {
std::fprintf(stderr, "can --in va --out\n");
return 2;
}
if (robot_yaml.empty()) {
const char* cd = std::getenv("VSLAM_CONFIG_DIR");
robot_yaml = (cd != nullptr && *cd != '\0' ? std::string(cd) : std::string("configuration_files")) +
"/robot.yaml";
}
// --- Ngoai suy cam bien tu robot.yaml (CUNG nguon voi bo mo phong) ---
vslam::RobotModel robot;
const vslam::StatusResponse rs = robot.LoadFile(robot_yaml);
if (!rs.ok()) {
std::fprintf(stderr, "%s: %s\n", robot_yaml.c_str(), rs.message.c_str());
return 1;
}
Transform T_cam_imu, T_bl_cam, T_bl_imu;
if (!robot.StaticTransform(vslam::kCameraDepthOpticalFrame, vslam::kImuFrame, &T_cam_imu) ||
!robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kCameraDepthOpticalFrame, &T_bl_cam) ||
!robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kImuFrame, &T_bl_imu)) {
std::fprintf(stderr, "robot.yaml thieu frame camera/IMU\n");
return 1;
}
Transform T_fp_bl = vslam::TransformIdentity();
T_fp_bl.translation.z = robot.geometry().wheel_radius;
// --- Doc ban ghi ---
vslam::RecordReader r;
vslam::StatusResponse st = r.Open(in);
if (!st.ok()) {
std::fprintf(stderr, "%s: %s\n", in.c_str(), st.message.c_str());
return 1;
}
const std::string& cj = r.info().config_json;
if (sim_gyro_sigma < 0.0) sim_gyro_sigma = JsonNumber(cj, "gyro_noise_stddev", 0.0);
if (sim_accel_sigma < 0.0) sim_accel_sigma = JsonNumber(cj, "accel_noise_stddev", 0.0);
if (sim_gyro_sigma <= 0.0 || sim_accel_sigma <= 0.0) {
std::fprintf(stderr, "canh bao: header khong ghi nhieu IMU -- imu_noise.yaml chi tinh nhieu "
"them luc xuat (dung --sim-gyro-sigma / --sim-accel-sigma)\n");
}
std::vector<ImuS> imu;
std::vector<GtS> gt;
std::vector<Frame> frames;
vslam::CameraInfo info;
bool have_info = false;
vslam::VsrChunkHeader h;
std::string payload;
std::vector<uint8_t> storage;
while (r.Next(&h, &payload)) {
const int64_t t = static_cast<int64_t>(h.stamp_ns);
switch (h.stream) {
case vslam::VsrStream::kImu: {
vslam::Imu m;
if (!vslam::DecodeImuPayload(payload, &m)) break;
ImuS s;
s.t = t;
s.w[0] = m.angular_velocity.x; s.w[1] = m.angular_velocity.y; s.w[2] = m.angular_velocity.z;
s.a[0] = m.linear_acceleration.x; s.a[1] = m.linear_acceleration.y;
s.a[2] = m.linear_acceleration.z;
imu.push_back(s);
break;
}
case vslam::VsrStream::kGroundTruth: {
GtS g;
g.t = t;
if (vslam::DecodeGroundTruthPayload(payload, g.p)) gt.push_back(g);
break;
}
case vslam::VsrStream::kCameraInfo:
if (vslam::DecodeCameraInfoPayload(payload, &info)) have_info = true;
break;
case vslam::VsrStream::kInfra1: {
vslam::Image img;
if (!vslam::DecodeImagePayload(payload, &img, &storage)) break;
if (img.format != vslam::PixelFormat::kMono8) break;
Frame f;
f.t = t;
f.w = static_cast<int>(img.width);
f.h = static_cast<int>(img.height);
f.px.resize(static_cast<size_t>(f.w) * f.h);
for (int y = 0; y < f.h; ++y) {
std::copy(img.data + static_cast<size_t>(y) * img.step,
img.data + static_cast<size_t>(y) * img.step + f.w,
f.px.begin() + static_cast<long>(y) * f.w);
}
frames.push_back(std::move(f));
break;
}
default:
break;
}
}
if (imu.size() < 10 || frames.empty() || !have_info) {
std::fprintf(stderr, "ban ghi thieu IMU (%zu), anh IR (%zu) hoac camera_info -- ghi bang "
"vslam_record --gl va kich ban doc\n", imu.size(), frames.size());
return 1;
}
// --- Lam xau IMU: ha tan so, lech gio, them nhieu ---
std::vector<int64_t> dts;
for (size_t i = 1; i < imu.size(); ++i) dts.push_back(imu[i].t - imu[i - 1].t);
std::nth_element(dts.begin(), dts.begin() + dts.size() / 2, dts.end());
const double src_hz = 1e9 / static_cast<double>(dts[dts.size() / 2]);
const int keep_every = imu_hz > 0.0 ? std::max(1, static_cast<int>(std::lround(src_hz / imu_hz))) : 1;
const int64_t offset_ns = static_cast<int64_t>(std::llround(offset_ms * 1e6));
std::mt19937 rng(seed);
std::normal_distribution<double> n01(0.0, 1.0);
std::vector<ImuS> q;
for (size_t i = 0; i < imu.size(); i += static_cast<size_t>(keep_every)) {
ImuS s = imu[i];
s.t += offset_ns;
for (int k = 0; k < 3; ++k) {
if (gyro_noise > 0.0) s.w[k] += gyro_noise * n01(rng);
if (accel_noise > 0.0) s.a[k] += accel_noise * n01(rng);
s.w[k] += gyro_bias[k];
s.a[k] += accel_bias[k];
}
q.push_back(s);
}
const double out_hz = src_hz / keep_every;
// --- Mau IMU dung gio MOI anh (noi suy tuyen tinh) ---
std::vector<Frame*> used;
std::vector<ImuS> merged = q;
for (Frame& f : frames) {
if (f.t < q.front().t || f.t > q.back().t) continue; // ngoai khoang IMU
used.push_back(&f);
auto it = std::lower_bound(q.begin(), q.end(), f.t,
[](const ImuS& s, int64_t t) { return s.t < t; });
if (it != q.end() && it->t == f.t) continue; // da co mau trung gio
merged.push_back(Lerp(*(it - 1), *it, f.t));
}
std::sort(merged.begin(), merged.end(), [](const ImuS& a, const ImuS& b) { return a.t < b.t; });
// --- Ghi ---
if (!MakeDir(out + "/cam0/images")) {
std::fprintf(stderr, "khong tao duoc %s\n", out.c_str());
return 1;
}
FILE* ft = std::fopen((out + "/cam0/times.txt").c_str(), "w");
std::mt19937 rng_img(seed + 7); // rieng: doi --ir-noise khong doi nhieu IMU
std::vector<uint8_t> noisy;
for (const Frame* f : used) {
char name[64];
std::snprintf(name, sizeof(name), "/cam0/images/%019lld.png", static_cast<long long>(f->t));
const uint8_t* px = f->px.data();
if (ir_noise > 0.0) {
noisy.resize(f->px.size());
for (size_t i = 0; i < noisy.size(); ++i) {
const double v = f->px[i] + ir_noise * n01(rng_img);
noisy[i] = static_cast<uint8_t>(std::min(255.0, std::max(0.0, std::round(v))));
}
px = noisy.data();
}
const cv::Mat m(f->h, f->w, CV_8UC1, const_cast<uint8_t*>(px));
cv::imwrite(out + name, m);
std::fprintf(ft, "%lld %.9f\n", static_cast<long long>(f->t), f->t * 1e-9);
}
std::fclose(ft);
FILE* fi = std::fopen((out + "/imu.txt").c_str(), "w");
std::fprintf(fi, "#timestamp [ns] w_x w_y w_z [rad/s] a_x a_y a_z [m/s^2]\n");
for (const ImuS& s : merged) {
std::fprintf(fi, "%lld %.9f %.9f %.9f %.9f %.9f %.9f\n", static_cast<long long>(s.t), s.w[0],
s.w[1], s.w[2], s.a[0], s.a[1], s.a[2]);
}
std::fclose(fi);
// Noi suy o DO PHAN GIAI ANH: K cua camera_info la anh goc, binning bao da
// decimate bao nhieu (giong image_proc/crop_decimate).
const double bx = std::max<uint32_t>(1, info.binning_x), by = std::max<uint32_t>(1, info.binning_y);
const double fx = info.k[0] / bx, fy = info.k[4] / by, cx = info.k[2] / bx, cy = info.k[5] / by;
const int W = used.front()->w, H = used.front()->h;
FILE* fc = std::fopen((out + "/camera.txt").c_str(), "w");
std::fprintf(fc, "Pinhole %.6f %.6f %.6f %.6f 0\n%d %d\nnone\n%d %d\n", fx, fy, cx, cy, W, H, W, H);
std::fclose(fc);
// T_cam_imu dang ma tran 4x4 (Kalibr).
const vslam::Vector3 ex = vslam::RotateVector(T_cam_imu.rotation, vslam::Vector3{1, 0, 0});
const vslam::Vector3 ey = vslam::RotateVector(T_cam_imu.rotation, vslam::Vector3{0, 1, 0});
const vslam::Vector3 ez = vslam::RotateVector(T_cam_imu.rotation, vslam::Vector3{0, 0, 1});
FILE* fk = std::fopen((out + "/camchain.yaml").c_str(), "w");
std::fprintf(fk,
"# Sinh boi vslam_vsr_export tu robot.yaml (%s): camera = "
"camera_depth_optical_frame, imu = imu_link.\n"
"cam0:\n T_cam_imu:\n"
" - [%.9f, %.9f, %.9f, %.9f]\n - [%.9f, %.9f, %.9f, %.9f]\n"
" - [%.9f, %.9f, %.9f, %.9f]\n - [0.0, 0.0, 0.0, 1.0]\n"
" camera_model: pinhole\n intrinsics: [%.6f, %.6f, %.6f, %.6f]\n"
" distortion_model: radtan\n distortion_coeffs: [0.0, 0.0, 0.0, 0.0]\n"
" resolution: [%d, %d]\n timeshift_cam_imu: 0.0\n",
robot_yaml.c_str(), ex.x, ey.x, ez.x, T_cam_imu.translation.x, ex.y, ey.y, ez.y,
T_cam_imu.translation.y, ex.z, ey.z, ez.z, T_cam_imu.translation.z, fx, fy, cx, cy,
W, H);
std::fclose(fk);
// Mat do nhieu = sigma moi mau / sqrt(tan so RA): ha tan so bang cach bo mau
// (khong lay trung binh) giu nguyen sigma moi mau, nen mat do TANG. Bias: sim
// khong troi bias, ghi gia tri NHO nhung khac 0 -- bo loc can no de khong tin
// IMU tuyet doi.
const double g_sig = std::sqrt(sim_gyro_sigma * sim_gyro_sigma + gyro_noise * gyro_noise);
const double a_sig = std::sqrt(sim_accel_sigma * sim_accel_sigma + accel_noise * accel_noise);
FILE* fn = std::fopen((out + "/imu_noise.yaml").c_str(), "w");
std::fprintf(fn,
"# Kalibr imu.yaml. Nhieu tu bo mo phong (sigma moi mau %.3g rad/s, %.3g m/s^2 o "
"%.0f Hz)%s.\n"
"gyroscope_noise_density: %.6e\naccelerometer_noise_density: %.6e\n"
"gyroscope_random_walk: 1.0e-05\naccelerometer_random_walk: 1.0e-04\n"
"update_rate: %.1f\n",
sim_gyro_sigma, sim_accel_sigma, src_hz,
(gyro_noise > 0 || accel_noise > 0) ? " + nhieu them luc xuat" : "",
g_sig / std::sqrt(out_hz), a_sig / std::sqrt(out_hz), out_hz);
std::fclose(fn);
// Su that: IMU (TUM-VI csv, cho DM-VIO), camera va base (TUM, cho cham diem).
FILE* fg = std::fopen((out + "/gt_imu.csv").c_str(), "w");
FILE* fgc = std::fopen((out + "/gt_cam_tum.txt").c_str(), "w");
FILE* fgb = std::fopen((out + "/gt_base_tum.txt").c_str(), "w");
std::fprintf(fg, "#timestamp [ns],p_x,p_y,p_z,q_w,q_x,q_y,q_z\n");
std::fprintf(fgc, "# timestamp x y z qx qy qz qw -- camera_depth_optical_frame trong world\n");
std::fprintf(fgb, "# timestamp x y z qx qy qz qw -- base_footprint trong world\n");
for (const GtS& g : gt) {
const Transform T_w_fp = PoseOf(g);
const Transform T_w_bl = vslam::TransformCompose(T_w_fp, T_fp_bl);
const Transform T_w_imu = vslam::TransformCompose(T_w_bl, T_bl_imu);
const Transform T_w_cam = vslam::TransformCompose(T_w_bl, T_bl_cam);
std::fprintf(fg, "%lld,%.6f,%.6f,%.6f,%.9f,%.9f,%.9f,%.9f\n", static_cast<long long>(g.t),
T_w_imu.translation.x, T_w_imu.translation.y, T_w_imu.translation.z,
T_w_imu.rotation.w, T_w_imu.rotation.x, T_w_imu.rotation.y, T_w_imu.rotation.z);
WriteTum(fgc, g.t, T_w_cam);
WriteTum(fgb, g.t, T_w_fp);
}
std::fclose(fg);
std::fclose(fgc);
std::fclose(fgb);
FILE* fj = std::fopen((out + "/export.json").c_str(), "w");
std::fprintf(fj,
"{\"in\":\"%s\",\"robot\":\"%s\",\"images\":%zu,\"imu_src_hz\":%.3f,"
"\"imu_out_hz\":%.3f,\"imu_offset_ms\":%.3f,\"gyro_noise\":%.3g,"
"\"accel_noise\":%.3g,\"accel_bias\":[%g,%g,%g],\"gyro_bias\":[%g,%g,%g],"
"\"ir_noise\":%.3g,\"seed\":%u,\"fx\":%.4f,\"fy\":%.4f,\"cx\":%.4f,"
"\"cy\":%.4f,\"width\":%d,\"height\":%d}\n",
in.c_str(), robot_yaml.c_str(), used.size(), src_hz, out_hz, offset_ms,
gyro_noise, accel_noise, accel_bias[0], accel_bias[1], accel_bias[2], gyro_bias[0],
gyro_bias[1], gyro_bias[2], ir_noise, seed, fx, fy, cx, cy, W, H);
std::fclose(fj);
std::printf("xuat %zu anh %dx%d, %zu mau IMU (%.1f Hz -> %.1f Hz, lech %.1f ms), %zu su that "
"-> %s\n",
used.size(), W, H, merged.size(), src_hz, out_hz, offset_ms, gt.size(), out.c_str());
return 0;
}