Compare commits

..

48 Commits

Author SHA1 Message Date
trung09122002
3b5703e41a tools: gen_world_from_db.py -- sinh world mo phong tu DB ban do that: dia hinh tu do cao node, tuong tu luoi log-odds (bo tia LiDAR cham san doc), ban SAO DB ha Admin.version 0.23 -> 0.21 de may dev mo duoc; in cho xuat phat (dinh doc lon nhat) + lenh sim 2026-10-08 15:52:02 +07:00
trung09122002
fc03420d2c slope: test doc tu dong (--slope-test) -- dinh vi lai xong robot tu tim truc doc tren ban do (do cao san cua node), quay mat xuong doc, cho nut Y (gamepad.button_test) roi chay N luot xuong/len, moi luot mot van toc (mac dinh 10 luot 0.10..0.46 m/s)
Lenh di qua FSM an toan nhu moi lenh khac; dung han khi lech duong > 0.4 m, scan mat khop 1.5 s, pose nhay > 0.3 m, nghieng > 20 do. Do lech dinh vi 2 lan/giay (khop scan voi likelihood field, doc lap RTAB-Map) ra logs/slope_test_<gio>.csv + bang tong. Sim 08/10 (slope_two_ramps, 10 luot): lech that trung vi 0.9 cm, max 3.0 cm, sai z trung vi 0.3 cm, khong troi tu luot 1 den 10.
2026-10-08 15:52:02 +07:00
trung09122002
f8049be038 web: chi lam muot HINH robot (truot 50 ms, bo du doan van toc 0.15 s lam vuot roi giat khi dung quay); scan + cloud neo theo pose THAT de dinh vao tuong -- neo theo pose muot thi lac quanh tuong moi khi xoay, roi mat 2026-10-07 16:21:10 +07:00
trung09122002
31f84eb082 map,lidar,web: ban do theo lan nhin MOI NHAT + scan dung gio. Luoi 2D: GridGlobal/* (3 lan nhin xuyen qua -> trong, truoc ~9; truoc 07/10 khong truyen vao bo ghep luoi); lop camera + 3D: xoa voxel ma >= 2 node sau nhin xuyen qua (VoxelCarver) -- nguoi dung roi di thi quay lai quet la mat. LiDAR: stamp_offset -55 ms + chinh meo theo chieu quet (do tren ban do that 28/09 + 01/10); web: robot troi muot 2026-10-07 16:04:28 +07:00
trung09122002
61c3a75fb1 slope: bu nghieng scan giu CA vong scan LakiBeam -- lidar_core phat goc [0, 2pi) (angle_min 0), LevelScan dua ve [-pi, pi) roi tru nen bo het nua -pi..0: ban do that tu 06/10 chi con nua scan (325 vs 620-730 diem); RayIndex lay goc theo vong tron + test scan LakiBeam; log slope/scan ti le tia giu 2026-10-07 14:57:49 +07:00
trung09122002
cc3df0ecb2 odom: goc quay EKF theo ENCODER mac dinh (pipeline.yaml ekf.gyro_yaw: false) -- WT61PC lech mot chieu khi chay: 07/10 gyro - encoder +0.11..+0.38 rad moi 30 s du quay trai hay phai (+71 do / 2.5 phut); log odom/yaw in hieu tuyet doi + nguon EKF 2026-10-07 14:42:00 +07:00
trung09122002
3935ffe0cc odom: goc quay EKF -- GyroYawFuser (gyro giu tong, encoder lap khoang chua ve) thay cua so 0.5-1.5 buoc roi vut: IMU 200 Hz toi theo cum lam ban do 07/10 dem thieu 9.9% moi goc quay; log odom/yaw 30 s 2026-10-07 13:25:51 +07:00
trung09122002
b5574a17b5 reloc: dung XIEN tren doc -- tu chay quay mat theo chieu doc (IMU) de camera nhan ra; bo loc nghieng + neo z noi suy giua hai lan cung mat doc (doc rong) -- sim doc rong quet 3 lan: 8/8 cho xien chot dung 0.5-4.4 cm, 6/8 bang camera (11-55 s) 2026-10-07 09:07:11 +07:00
trung09122002
35fef155f5 sim: slope_two_ramps -- hai doc rong het nha (8 m) thay hanh lang 2.4 m, giong doc ngoai troi; README 2026-10-06 15:27:49 +07:00
trung09122002
994edd1da3 reloc,web: chua chot thi ve robot tu cho bat dau quet (node dau ban do) thay vi goc map -- trong mo phong goc world thuong la goc nha 2026-10-06 15:12:00 +07:00
trung09122002
3f60ecf630 sim: world slope_two_ramps -- sanh giua + doc 10 do / 15 do len hai tang 1.5 m, khong doi xung, quet mot vong ~85 m (tools/gen_two_ramp_world.py); README 2026-10-06 14:40:37 +07:00
trung09122002
788c08c916 docs,config: README cho doc (gioi thieu, lenh quet / dinh vi lai sim + robot that, udev IMU, sao luu ban do, bang log dau) + slam.yaml slope.enabled mac dinh BAT 2026-10-06 11:08:47 +07:00
trung09122002
28f124275a config: imu_lag_sec 0.03 -- do tren robot 06/10 (115200 / 200 Hz): dat 0.01 thi wheel_odom/lag bao 20 ms on dinh 1000-5000 mau 2026-10-06 10:41:18 +07:00
trung09122002
25fc247cfb slam: height_map.h thieu #include <cstddef> (size_t) -- GCC 11 tren Jetson bao loi, GCC 9 may dev khong 2026-10-06 10:32:14 +07:00
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
trung09122002
be2aa17e3e drivers: IMU WT61PC noi thang UART (mcu.protocol: wt61pc), bo ESP32 -- doc quyen cong, tach khung co resync, canh bao khi im 2026-10-02 14:01:19 +07:00
trung09122002
a8388102d8 docs: README -- dung them motor_control truoc khi chay robot, so do reloc camera tren robot that 2026-10-02 11:04:03 +07:00
trung09122002
5f47e83fd9 docs: README -- GAZEBO_MODEL_PATH cho mo phong, dinh vi lai bang camera (--slam-reloc-vpr), yaw bang rad 2026-10-01 11:37:33 +07:00
trung09122002
fed62c280a web: mo trang khong con lam dinh vi lai tu dong nhuong 5 s; vpr_encoder.h sua comment; reloc bench --refine-sigma 2026-10-01 11:21:28 +07:00
trung09122002
dbd508d910 reloc: gan lai camera (VPR + PnP) vao node -- chi bat khi co --slam-reloc-vpr; duong LiDAR giu nguyen ban 29/09
Code camera lay nguyen tu 1d3cb2f, giu hien thi yaw bang rad (153bb1b).
Kiem mo phong (co tuong, khong co co camera): vong 1 trung tung chu so voi ban 29/09
(1059 diem, ty le 1.16046 / 2.22805), chot sau 4 vong lech 0.042 m.
2026-10-01 11:17:03 +07:00
trung09122002
f4b45afead reloc: dong DA DINH VI / TIM THAY hien yaw bang rad, cung don vi voi o POSE tren web 2026-10-01 11:06:56 +07:00
trung09122002
e9be787948 reloc: tra node ve ban chieu 29/09 (2c6c839) -- tam go camera VPR khoi node
Mo phong lech tu 30/09 la do thieu GAZEBO_MODEL_PATH (khong nap tuong benh vien), khong phai do code.
Thu vien VPR / VisualVerifier van giu trong libs/, gan lai vao node sau khi chay on trong mo phong.
2026-10-01 10:53:00 +07:00
trung09122002
1d3cb2f037 reloc: --slam-reloc-vpr -- camera (VPR TensorRT + PnP) ket hop LiDAR, chot khi hai nguon trung 2026-09-30 15:24:31 +07:00
trung09122002
c6c42d177f reloc: VisualVerifier (ORB + PnP bang depth anh ban do) + vslam_pnp_eval -- trung khop ban Python 2430/2430 cap 2026-09-30 15:09:53 +07:00
trung09122002
2fc289db1c vslam_vpr_check: cham theo ty le TIM DUNG CHO (top-1/top-5) thay vi giong het PyTorch 2026-09-30 15:03:06 +07:00
trung09122002
1552ec2636 vpr: VprEncoder TensorRT (chi Jetson, -DVSLAM_WITH_TENSORRT=ON) + vslam_vpr_check + tools/vpr_export_onnx.py 2026-09-30 14:50:47 +07:00
trung09122002
cccc048eaf reloc eval: camera (VPR+PnP) ket hop LiDAR -- 25/09: 85->159, 28/09: 29->40, 0 chot sai ca hai ban 2026-09-30 14:27:02 +07:00
trung09122002
29d07e4db5 reloc bench: --gicp xac minh 3D bang depth; analyzer: luat trung khop 3D tai pose doan (R3: 137 -> 153 dung, 0 sai) 2026-09-30 13:55:44 +07:00
trung09122002
e7e38c0b48 docs: README gon lai -- mo ta, cong nghe, build (dev + Jetson), chay mapping va relocalization 2026-09-30 09:57:09 +07:00
trung09122002
2c6c839269 reloc: ban do 3D luc khoi dong nap du moi node (khong gioi han 40 node/lan) 2026-09-29 14:50:34 +07:00
trung09122002
0f3e46d83a web: hang 'ban do 3D' (nguon + so o); tu bat lop cloud da quet khi co voxel; ui 2026-09-29a 2026-09-29 14:44:09 +07:00
trung09122002
36db5126c2 reloc: web hien map DB (2D+3D) ngay luc khoi dong; robot o goc map toi khi chot roi nhay ve cho that 2026-09-29 14:32:14 +07:00
trung09122002
60853531aa reloc: --slam-reloc(-auto) tu dinh vi lai trong node (tu xoay/tu di, nguoi luon thang); web ve robot mo o vi tri doan; sieu am cho xoay; LocalMatch gioi han huong 2026-09-29 11:16:04 +07:00
trung09122002
399a46139e reloc: LocalMatch + bench --split-id/--vpr-csv + phan tich ghep VPR/LiDAR; robot that: 85 -> 108 chot dung, 0 sai 2026-09-29 10:26:00 +07:00
trung09122002
ca3b7854ea update 2026-09-29 10:00:22 +07:00
trung09122002
7258f15ab5 tools/vpr_eval.py: do VPR tren anh IR D410 -- CosPlace/EigenPlaces top-1 dung cho 88-89% 2026-09-29 09:59:51 +07:00
trung09122002
89ab2e7868 slam.yaml: profiles sim/real -- odom sigma va ICP ratio tach theo moi truong 2026-09-28 14:40:48 +07:00
trung09122002
c8c08223ed web: chi gui lenh khi dang lai -- het de len lenh tay cam 2026-09-28 11:13:56 +07:00
trung09122002
6edf5f6961 web 3D: lat hang lop ban do da quet -- het lat guong theo y 2026-09-28 10:58:16 +07:00
trung09122002
4baa38c12c zlac: doc 0x606C du phong boc try rieng -- khong terminate khi bus CAN nghen 2026-09-28 10:39:31 +07:00
142 changed files with 21620 additions and 1193 deletions

3
.gitignore vendored
View File

@@ -17,6 +17,9 @@ resources/records/*
!resources/records/.keep !resources/records/.keep
resources/maps/* resources/maps/*
!resources/maps/.keep !resources/maps/.keep
# Mo hinh VPR: ONNX ~111 MB + engine TensorRT rieng tung may -- sinh bang tools/vpr_export_onnx.py
resources/vpr/*
!resources/vpr/.keep
test/data/*.vsr test/data/*.vsr
# Log chay + anh bao cao -- nang, rieng tung may, khong commit # Log chay + anh bao cao -- nang, rieng tung may, khong commit

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**. - 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). - 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 behind an ESP32-S3 MCU on `/dev/ttyACM0` @ 115200 baud, expected 200 Hz. `ClockSync` fits MCU `micros()` to host clock; `McuTimeUnwrapper` is mandatory (uint32 wraps every 71.58 min). - 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**). - 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. - 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). - 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).

1164
README.md

File diff suppressed because it is too large Load Diff

View File

@@ -38,6 +38,11 @@ endif()
if(VSLAM_WITH_REALSENSE) if(VSLAM_WITH_REALSENSE)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_REALSENSE=1) target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_REALSENSE=1)
endif() 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) if(VSLAM_WITH_CANOPEN)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_CANOPEN=1) target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_CANOPEN=1)
endif() endif()

View File

@@ -69,7 +69,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
Reject(l, "sensors.yaml lidar", Reject(l, "sensors.yaml lidar",
{"host", "port", "expected_rate_hz", "range_min", "range_max", {"host", "port", "expected_rate_hz", "range_min", "range_max",
"stamp_mismatch_warn", "sector_masks", "stamp_mismatch_warn", "sector_masks",
"angle_offset_deg", "angle_flip", "filters"}); "angle_offset_deg", "angle_flip", "filters",
"stamp_offset_sec", "deskew"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->sanitizer.range_min = l.get<double>("range_min", 0.05); out->sanitizer.range_min = l.get<double>("range_min", 0.05);
@@ -94,6 +95,11 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
l.get<double>("angle_offset_deg", out->lidar_driver.angle_offset_deg); l.get<double>("angle_offset_deg", out->lidar_driver.angle_offset_deg);
out->lidar_driver.inverted = out->lidar_driver.inverted =
l.get<bool>("angle_flip", out->lidar_driver.inverted); l.get<bool>("angle_flip", out->lidar_driver.inverted);
// Gio scan so voi odometry va chinh meo -- do tren ban do that, xem
// sensors.yaml.
out->lidar_driver.stamp_offset_sec =
l.get<double>("stamp_offset_sec", out->lidar_driver.stamp_offset_sec);
out->lidar_driver.deskew = l.get<bool>("deskew", out->lidar_driver.deskew);
// --- Bon bo loc scan --- // --- Bon bo loc scan ---
const ConfigNode ft = l["filters"]; const ConfigNode ft = l["filters"];
@@ -206,13 +212,27 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
{ {
const StatusResponse r = const StatusResponse r =
Reject(mc, "sensors.yaml mcu", Reject(mc, "sensors.yaml mcu",
{"port", "baud", "sync_window", "max_skew_warn", {"protocol", "port", "baud", "sync_window", "max_skew_warn",
"expected_imu_rate_hz", "ticks_per_rev", "imu_lag_sec", "expected_imu_rate_hz", "ticks_per_rev", "imu_lag_sec",
"expect_timestamps"}); "expect_timestamps"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->sensors.imu_hz = mc.get<double>("expected_imu_rate_hz", 200.0); out->sensors.imu_hz = mc.get<double>("expected_imu_rate_hz", 200.0);
// esp = ESP32 + USB-CDC (cach cu). wt61pc = cam bien noi thang UART/USB-FTDI.
// Sai ten thi tu choi, khong doan: chon nham thi IMU im lang.
{
const std::string p = mc.get<std::string>("protocol", "esp");
if (p == "esp") {
out->mcu_driver.protocol = McuProtocol::kEspText;
} else if (p == "wt61pc") {
out->mcu_driver.protocol = McuProtocol::kWt61pc;
} else {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"sensors.yaml mcu.protocol = \"" + p + "\" khong biet. Chon: esp | wt61pc.");
}
}
out->mcu_driver.port = mc.get<std::string>("port", "/dev/ttyACM0"); out->mcu_driver.port = mc.get<std::string>("port", "/dev/ttyACM0");
out->mcu_driver.baud = static_cast<uint32_t>(mc.get<int>("baud", 115200)); out->mcu_driver.baud = static_cast<uint32_t>(mc.get<int>("baud", 115200));
out->mcu_driver.imu_frame_id = kImuFrame; out->mcu_driver.imu_frame_id = kImuFrame;
@@ -292,7 +312,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
{ {
const StatusResponse r = const StatusResponse r =
Reject(e, "pipeline.yaml ekf", Reject(e, "pipeline.yaml ekf",
{"q_x", "q_y", "q_yaw", "q_vx", "q_vyaw", "max_dt"}); {"q_x", "q_y", "q_yaw", "q_vx", "q_vyaw", "max_dt", "gyro_yaw"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->ekf.q_x = e.get<double>("q_x", out->ekf.q_x); out->ekf.q_x = e.get<double>("q_x", out->ekf.q_x);
@@ -301,6 +321,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
out->ekf.q_vx = e.get<double>("q_vx", out->ekf.q_vx); out->ekf.q_vx = e.get<double>("q_vx", out->ekf.q_vx);
out->ekf.q_vyaw = e.get<double>("q_vyaw", out->ekf.q_vyaw); out->ekf.q_vyaw = e.get<double>("q_vyaw", out->ekf.q_vyaw);
out->ekf.sensor_timeout = e.get<double>("max_dt", out->ekf.sensor_timeout); out->ekf.sensor_timeout = e.get<double>("max_dt", out->ekf.sensor_timeout);
out->ekf_gyro_yaw = e.get<bool>("gyro_yaw", out->ekf_gyro_yaw);
const ConfigNode d = root["depth_filter"]; const ConfigNode d = root["depth_filter"];
{ {
@@ -569,7 +590,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
const StatusResponse r = const StatusResponse r =
Reject(v, "slam.yaml voxel", Reject(v, "slam.yaml voxel",
{"emit_size_m", "z_min", "z_max", "max_cells", "delta_max_ratio", {"emit_size_m", "z_min", "z_max", "max_cells", "delta_max_ratio",
"obstacle_z_min", "obstacle_z_max", "min_node_hits"}); "obstacle_z_min", "obstacle_z_max", "min_node_hits",
"clear_after_views"});
if (!r.ok()) return r; if (!r.ok()) return r;
out->voxel.emit_size_m = v.get<double>("emit_size_m", out->voxel.emit_size_m); out->voxel.emit_size_m = v.get<double>("emit_size_m", out->voxel.emit_size_m);
@@ -590,6 +612,13 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"slam.yaml voxel.min_node_hits phai >= 1"); "slam.yaml voxel.min_node_hits phai >= 1");
} }
out->voxel.min_node_hits = static_cast<size_t>(hits); out->voxel.min_node_hits = static_cast<size_t>(hits);
const int clear = v.get<int>("clear_after_views",
static_cast<int>(out->voxel.clear_after_views));
if (clear < 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml voxel.clear_after_views phai >= 0 (0 = tat)");
}
out->voxel.clear_after_views = static_cast<size_t>(clear);
if (out->voxel.emit_size_m <= 0.0) { if (out->voxel.emit_size_m <= 0.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument, return StatusResponse::Error(StatusCode::kInvalidArgument,
@@ -610,6 +639,68 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"slam.yaml voxel: obstacle_z_min phai nho hon obstacle_z_max"); "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 #endif
@@ -674,7 +765,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"min_angular_kick", "idle_publish_sec", "reopen_period_sec", "min_angular_kick", "idle_publish_sec", "reopen_period_sec",
"turbo_linear", "turbo_angular", "slow_linear", "slow_angular", "turbo_linear", "turbo_angular", "slow_linear", "slow_angular",
"axis_linear", "axis_linear_dpad", "axis_angular", "axis_linear", "axis_linear_dpad", "axis_angular",
"axis_angular_dpad", "button_enable", "button_zero", "axis_angular_dpad", "button_enable", "button_zero", "button_test",
"button_turbo", "button_slow", "invert_linear", "button_turbo", "button_slow", "invert_linear",
"invert_angular", "lt_stop", "axis_lt", "lt_press_above"}); "invert_angular", "lt_stop", "axis_lt", "lt_press_above"});
if (!r.ok()) return r; if (!r.ok()) return r;
@@ -714,6 +805,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
out->gamepad.button_enable = out->gamepad.button_enable =
gp.get<int>("button_enable", out->gamepad.button_enable); gp.get<int>("button_enable", out->gamepad.button_enable);
out->gamepad.button_zero = gp.get<int>("button_zero", out->gamepad.button_zero); out->gamepad.button_zero = gp.get<int>("button_zero", out->gamepad.button_zero);
out->gamepad.button_test = gp.get<int>("button_test", out->gamepad.button_test);
out->gamepad.button_turbo = out->gamepad.button_turbo =
gp.get<int>("button_turbo", out->gamepad.button_turbo); gp.get<int>("button_turbo", out->gamepad.button_turbo);
out->gamepad.button_slow = gp.get<int>("button_slow", out->gamepad.button_slow); out->gamepad.button_slow = gp.get<int>("button_slow", out->gamepad.button_slow);

View File

@@ -64,6 +64,44 @@ struct VoxelConfig {
// Voxel phai duoc it nhat bay nhieu node khac nhau thay moi giu -- ap cho ca // Voxel phai duoc it nhat bay nhieu node khac nhau thay moi giu -- ap cho ca
// ban do 3D lan lop vat can 2D. 1 = giu moi voxel. // ban do 3D lan lop vat can 2D. 1 = giu moi voxel.
size_t min_node_hits = 1; size_t min_node_hits = 1;
// Xoa voxel ma bay nhieu node SAU lan thay cuoi nhin xuyen qua (vat da roi
// di). 0 = tat. Xem slam.yaml khoi `voxel:`.
size_t clear_after_views = 0;
};
// Di tren doc (G4). Doc tu khoi `slope:` trong slam.yaml. enabled = false thi
// 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 { struct ThreadConfig {
@@ -115,6 +153,7 @@ struct AppConfig {
WheelOdometryConfig wheel_odom; // robot.yaml + pipeline.yaml WheelOdometryConfig wheel_odom; // robot.yaml + pipeline.yaml
EkfSe2Config ekf; // pipeline.yaml EkfSe2Config ekf; // pipeline.yaml
bool ekf_gyro_yaw = false; // pipeline.yaml ekf.gyro_yaw: goc quay EKF theo gyro
PerceptionConfig perception; // pipeline.yaml + robot.yaml PerceptionConfig perception; // pipeline.yaml + robot.yaml
SafetyConfig safety; // safety.yaml SafetyConfig safety; // safety.yaml
@@ -127,6 +166,8 @@ struct AppConfig {
ThreadConfig threads; ThreadConfig threads;
SlamRuntimeConfig slam_runtime; SlamRuntimeConfig slam_runtime;
VoxelConfig voxel; VoxelConfig voxel;
SlopeConfig slope;
FarLoopsConfig far_loops;
RecordConfig record; RecordConfig record;
std::string log_level = "info"; 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" " system.yaml gamepad.enabled. DEV mac dinh lay\n"
" tu system.yaml (/dev/input/js0)\n" " tu system.yaml (/dev/input/js0)\n"
" --no-gamepad tat tay cam du system.yaml co bat\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" " --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n"
" LiDAR/depth KHONG thay; chi sieu am + bumper.\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" " --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n"
@@ -69,6 +73,26 @@ void Usage(const char* argv0) {
" pose ban dau cho localization -- tuong duong\n" " pose ban dau cho localization -- tuong duong\n"
" /initialpose. BAT BUOC tren robot that: RTAB-Map\n" " /initialpose. BAT BUOC tren robot that: RTAB-Map\n"
" khong dinh vi toan cuc duoc bang scan khong.\n" " khong dinh vi toan cuc duoc bang scan khong.\n"
" --slam-reloc localization KHONG can pose ban dau: XOAY TAI CHO\n"
" ~300 do, node tu tim vi tri bang khop scan LiDAR\n"
" voi toan ban do. Khong di cung --slam-init-pose.\n"
" --slam-reloc-auto kem --slam-reloc: robot TU XOAY + TU DI (0.12 m/s,\n"
" 0.4 rad/s, toi da 6 vong / 12 m) toi khi chot.\n"
" Lenh van qua lop an toan; tay cam/web ra lenh\n"
" la tu chay nhuong ngay. THU TREN MO PHONG TRUOC.\n"
" --slam-reloc-vpr [ENGINE.plan]\n"
" kem --slam-reloc: CAMERA cung dinh vi lai (VPR + PnP,\n"
" chot khi trung LiDAR). Can build -DVSLAM_WITH_TENSORRT=ON;\n"
" mac dinh $VSLAM_RESOURCE_DIR/vpr/eigenplaces_r50_fp16.plan\n"
" --slope-test kem --slam-reloc: TEST DOC TU DONG. Dat robot o DINH doc;\n"
" chot xong tu tim doc tren ban do, quay mat xuong, cho Y\n"
" tren tay cam (mo phong: tu chay), roi xuong / len N luot,\n"
" moi luot mot van toc. Do lech dinh vi + z 2 Hz,\n"
" CSV logs/slope_test_*.csv + bang tong. Gat can = tam dung.\n"
" --slope-test-loops N so luot (mac dinh 10)\n"
" --slope-test-speeds V1,V2,.. van toc moi luot, m/s (toi da = tran an toan\n"
" 0.5; sim nang bang --max-speed). A:B = chia deu A -> B\n"
" cho so luot. Mac dinh 0.10,0.14,...,0.46\n"
" --check nap va KIEM cau hinh roi thoat, khong chay gi\n", " --check nap va KIEM cau hinh roi thoat, khong chay gi\n",
argv0, vslam::ConfigDir().c_str()); argv0, vslam::ConfigDir().c_str());
} }
@@ -152,6 +176,8 @@ int main(int argc, char** argv) {
} }
else if (a == "--no-gamepad") opts.gamepad_override = -1; 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-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 == "--max-speed") opts.max_speed_override = std::atof(next().c_str());
else if (a == "--slam") opts.force_slam = true; else if (a == "--slam") opts.force_slam = true;
else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; } else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; }
@@ -165,6 +191,34 @@ int main(int argc, char** argv) {
} }
opts.have_slam_init_pose = true; opts.have_slam_init_pose = true;
} }
else if (a == "--slam-reloc") opts.slam_reloc = true;
else if (a == "--slam-reloc-auto") opts.slam_reloc_auto = true;
else if (a == "--slam-reloc-vpr") {
// Duong dan engine la TUY CHON (giong --gamepad [DEV]).
opts.slam_reloc_vpr = true;
if (i + 1 < argc && argv[i + 1][0] != '-') opts.vpr_engine = argv[++i];
}
else if (a == "--slope-test") opts.slope_test = true;
else if (a == "--slope-test-loops") opts.slope_test_loops = std::atoi(next().c_str());
else if (a == "--slope-test-speeds") {
const std::string v = next();
// "A:B" = chia deu A -> B cho so luot (runtime tinh, vi --slope-test-loops
// co the dung sau).
const size_t colon = v.find(':');
if (colon != std::string::npos) {
opts.slope_test_vmin = std::atof(v.substr(0, colon).c_str());
opts.slope_test_vmax = std::atof(v.substr(colon + 1).c_str());
continue;
}
size_t b = 0;
while (b <= v.size()) {
const size_t e = v.find(',', b);
const std::string tok = v.substr(b, e == std::string::npos ? std::string::npos : e - b);
if (!tok.empty()) opts.slope_test_speeds.push_back(std::atof(tok.c_str()));
if (e == std::string::npos) break;
b = e + 1;
}
}
else if (a == "--check") check_only = true; else if (a == "--check") check_only = true;
else if (a == "--help" || a == "-h") { Usage(argv[0]); return 0; } else if (a == "--help" || a == "-h") { Usage(argv[0]); return 0; }
else { else {

File diff suppressed because it is too large Load Diff

View File

@@ -28,6 +28,8 @@
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <cstdio>
#include <deque>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <map> #include <map>
@@ -39,9 +41,13 @@
#include "app_config.h" #include "app_config.h"
#include "vslam/driver_interfaces.h" #include "vslam/driver_interfaces.h"
#include "vslam/ekf_se2.h" #include "vslam/ekf_se2.h"
#include "vslam/gyro_yaw_fuser.h"
#include "vslam/elevation_map.h"
#include "vslam/gamepad.h" #include "vslam/gamepad.h"
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/height_estimator.h"
#include "vslam/perception_pipeline.h" #include "vslam/perception_pipeline.h"
#include "vslam/scan_leveler.h"
#include "vslam/safety_monitor.h" #include "vslam/safety_monitor.h"
#include "vslam/scan_sanitizer.h" #include "vslam/scan_sanitizer.h"
#include "vslam/teleop_model.h" #include "vslam/teleop_model.h"
@@ -49,8 +55,12 @@
#include "vslam/wheel_odometry.h" #include "vslam/wheel_odometry.h"
#ifdef VSLAM_HAVE_SLAM #ifdef VSLAM_HAVE_SLAM
#include "vslam/global_localizer.h"
#include "vslam/rtabmap_slam.h" #include "vslam/rtabmap_slam.h"
#include "vslam/visual_verifier.h"
#include "vslam/slope_test.h"
#include "vslam/voxel_export.h" #include "vslam/voxel_export.h"
#include "vslam/vpr_encoder.h"
#endif #endif
namespace vslam { namespace vslam {
@@ -87,6 +97,11 @@ struct RuntimeOptions {
// Kinh vo hinh voi LiDAR va depth; chi sieu am thay. Dung de chay nhanh // 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. // US_BLOCKED va BUMPER cua FSM -- hai nhanh chua bao gio chay end-to-end.
double sim_glass_at = 0.0; 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 force_slam = false; // --slam: ghi de slam.yaml enabled
bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM
std::string slam_db; std::string slam_db;
@@ -95,6 +110,25 @@ struct RuntimeOptions {
// ROS, thu ma `dock_init.py` phat tu dock. // ROS, thu ma `dock_init.py` phat tu dock.
bool have_slam_init_pose = false; bool have_slam_init_pose = false;
Pose2D slam_init_pose; Pose2D slam_init_pose;
// --slam-reloc: localization KHONG pose ban dau -- tu dinh vi lai bang khop
// scan LiDAR toan ban do (vslam/global_localizer.h).
bool slam_reloc = false;
// --slam-reloc-auto: robot TU XOAY va TU DI de gom scan (reloc_exec cua ban
// ROS). Mac dinh TAT: robot tu chay khi CHUA biet minh o dau.
bool slam_reloc_auto = false;
// --slam-reloc-vpr [ENGINE]: CAMERA cung dinh vi lai -- VPR (TensorRT) goi y cho, PnP cho
// pose, chot khi TRUNG khop LiDAR. Can -DVSLAM_WITH_TENSORRT=ON; khong co thi canh bao
// roi chay bang LiDAR nhu cu.
bool slam_reloc_vpr = false;
std::string vpr_engine; // rong = $VSLAM_RESOURCE_DIR/vpr/eigenplaces_r50_fp16.plan
// --slope-test: test doc tu dong sau khi dinh vi lai (can --slam-reloc). Robot tu
// tim huong doc tren ban do, quay mat xuong, cho nut Y (sim: tu chay), roi xuong /
// len `slope_test_loops` luot, moi luot mot van toc. Xem vslam/slope_test.h.
bool slope_test = false;
int slope_test_loops = 10;
std::vector<double> slope_test_speeds; // rong = mac dinh SlopeTestConfig
// `--slope-test-speeds A:B`: chia DEU tu A toi B cho so luot (vmax > 0 = dung).
double slope_test_vmin = 0.0, slope_test_vmax = 0.0;
}; };
class Runtime { class Runtime {
@@ -113,6 +147,8 @@ class Runtime {
// wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20 // wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20
// file .launch cua ban ROS. // file .launch cua ban ROS.
StatusResponse Wire(); StatusResponse Wire();
// Di tren doc: mot khung depth -> ban do do cao san cuc bo (luong camera).
void AddDepthToElevation(const CameraFrame& f);
// runtime.cc // runtime.cc
StatusResponse OpenSource(); StatusResponse OpenSource();
@@ -132,6 +168,62 @@ class Runtime {
void ReportCloudScanAlign(const PointCloudXYZ& cloud); void ReportCloudScanAlign(const PointCloudXYZ& cloud);
void WebLoop(); void WebLoop();
void SlamLoop(); void SlamLoop();
#ifdef VSLAM_HAVE_SLAM
// Dinh vi lai tu dong (--slam-reloc). CHI luong slam goi, TRUOC Process():
// gom scan theo goc da xoay, du thi khop toan cuc, chot thi SetInitialPose.
void RelocStep(const LaserScan& scan, const Pose2D& odom);
// Sau Process(): scan tai pose dang tin con khop ban do khong -- tut lau
// thi quay lai gom (nghi da lac).
void RelocWatch(const LaserScan& scan, const Pose2D& pose_map);
// Diem scan (frame laser) -> frame cua `pose` (odom hoac map), cat max_range.
std::vector<Point> ScanToFrame(const LaserScan& scan, const Pose2D& pose) const;
// `pending` = CHUA dinh vi xong: web khong ve robot theo pose uoc luong.
void SetRelocStatus(const std::string& s, bool pending);
// --- Tu chay (--slam-reloc-auto) ---
// Lenh di qua `raw_cmd_` NHU MOI NGUON KHAC -> van qua lop an toan.
void RelocCommand(double v, double w);
// Co ai KHAC ghi raw_cmd_ trong 0.5 s qua khong (tay cam, web).
bool RelocHumanCommanding();
// Chon huong thoang nhat trong scan, dat muc tieu QUAY + DI. false = khong
// co cho nao du rong.
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,
std::chrono::steady_clock::time_point now);
void RelocFinish(const Pose2D& map_from_odom, const Pose2D& odom, const LaserScan& scan,
const std::string& how);
// Bat dau pha dung yen + tinh chinh sau khi CHOT -- chung cho LiDAR va camera.
void RelocBeginSettle(const Pose2D& map_from_odom, double ratio, const Pose2D& odom,
std::chrono::steady_clock::time_point now, const std::string& src);
// Camera: cu 30 do xoay chup mot anh -> VPR top-5 -> PnP -> so voi LiDAR cuc bo quanh
// node anh. true = da CHOT (da vao RelocBeginSettle).
bool RelocCamera(const LaserScan& scan, const Pose2D& odom,
std::chrono::steady_clock::time_point now);
// Test doc tu dong (--slope-test). Luong slam: lap duong sau khi chot, do 2 Hz
// (lech dinh vi theo do khop scan-ban do, z), ghi CSV, bang tong khi xong.
void SlopeTestSlamStep(const SlamOutput& out, const LaserScan& scan);
void SlopeTestSummary(SlopeTestPhase end);
// Luong RIENG 20 Hz: lai. Vong slam khung 100-600 ms moi lan RTAB-Map xu ly --
// lenh tu do se cu qua cmd_timeout cua FSM va xe giat cuc.
void SlopeLoop();
#endif
void ApplyThreadPriority(std::thread* t, int prio, const char* name); void ApplyThreadPriority(std::thread* t, int prio, const char* name);
AppConfig* cfg_; AppConfig* cfg_;
@@ -178,12 +270,26 @@ class Runtime {
// web_tx doc. // web_tx doc.
mutable std::mutex scan_mu_; mutable std::mutex scan_mu_;
LaserScanPtr latest_scan_; 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 // odom_mu_: wheel_odom_ va ekf_. CHI luong source cham vao chung; hai luong
// kia chi doc ban sao pose. // kia chi doc ban sao pose.
mutable std::mutex odom_mu_; mutable std::mutex odom_mu_;
Odometry latest_odom_; Odometry latest_odom_;
bool have_odom_ = false; 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. // perc_mu_: ket qua perception.
mutable std::mutex perc_mu_; mutable std::mutex perc_mu_;
@@ -239,6 +345,9 @@ class Runtime {
Twist raw_cmd_; Twist raw_cmd_;
UnixTime raw_cmd_stamp_; UnixTime raw_cmd_stamp_;
bool have_raw_cmd_ = false; bool have_raw_cmd_ = false;
// Stamp cua lan GHI GAN NHAT boi dinh vi lai tu chay. raw_cmd_stamp_ moi hon
// cai nay nghia la NGUOI (tay cam/web) vua ra lenh -> tu chay nhuong.
UnixTime reloc_cmd_stamp_;
// teleop_mu_: TeleopModel co trang thai (toc do dieu chinh duoc luc chay). // teleop_mu_: TeleopModel co trang thai (toc do dieu chinh duoc luc chay).
mutable std::mutex teleop_mu_; mutable std::mutex teleop_mu_;
@@ -272,6 +381,8 @@ class Runtime {
size_t last_map_occ_ = 0; size_t last_map_occ_ = 0;
size_t last_map_free_ = 0; size_t last_map_free_ = 0;
OccupancyGridPtr slam_map_; 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; double slam_process_ms_ = 0.0;
int slam_loops_ = 0; int slam_loops_ = 0;
// Phat hien KE CAN -- co che cat sai so cong don that su cua SLAM scan-only. // Phat hien KE CAN -- co che cat sai so cong don that su cua SLAM scan-only.
@@ -291,6 +402,119 @@ class Runtime {
std::vector<VoxelIndex> prev_voxel_cells_; std::vector<VoxelIndex> prev_voxel_cells_;
uint32_t voxel_epoch_ = 0; uint32_t voxel_epoch_ = 0;
uint32_t voxel_seq_ = 0; uint32_t voxel_seq_ = 0;
// ⚠️ Dinh vi lai tu dong: RIENG cua luong SlamLoop, KHONG duoi mutex nao --
// tru `reloc_status_` (duoi slam_mu_, WebLoop doc).
std::unique_ptr<LikelihoodField> reloc_field_; // null = khong bat --slam-reloc
GlobalLocalizerConfig reloc_cfg_;
std::unique_ptr<HypothesisTracker> reloc_tracker_;
bool reloc_active_ = false; // dang gom/khop: CHUA dua gi cho RTAB-Map
std::vector<Point> reloc_pts_; // diem da gom, frame odom
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;
// Tu chay tren doc co camera: da quay mat theo chieu doc o CHO nay chua, va pha QUAY
// hien tai co phai lan quay theo chieu doc khong (chu tren web).
bool reloc_aligned_here_ = false;
bool reloc_aligning_ = 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
// Truoc khi chot, web ve robot (mo) tu pose nay: node DAU TIEN cua ban do (cho bat dau
// quet). Robot that: trung goc map. Mo phong: ban do theo toa do world nen goc map la goc
// world (thuong la goc nha) -- ve o cho bat dau quet cho de nhin. Ghi trong Start() truoc
// khi luong web chay, sau do chi doc.
Pose2D reloc_view_origin_;
int reloc_cycle_ = 0;
double reloc_ref_score_ = -1.0; // diem luc chot -- moc cho canh "da lac"
bool reloc_lost_pending_ = false;
std::chrono::steady_clock::time_point reloc_lost_since_;
std::chrono::steady_clock::time_point reloc_watch_next_;
Transform slam_laser_to_base_ = TransformIdentity(); // doc-only sau Start()
std::string reloc_status_; // duoi slam_mu_
bool reloc_pending_ = false; // duoi slam_mu_: chua dinh vi xong
// Tu chay: XOAY (gom) -> khop -> chua chot thi QUAY ve cho thoang -> DI ->
// XOAY... Tran cung 6 vong / 12 m roi DUNG HAN goi nguoi (nhu ban ROS).
enum class RelocExec { kOff, kSweep, kTurn, kDrive, kHalted };
RelocExec reloc_exec_ = RelocExec::kOff;
double reloc_turn_target_ = 0.0; // huong odom can quay toi (rad)
Pose2D reloc_drive_start_;
double reloc_drive_len_ = 0.0; // quang duong du dinh cua pha DI
double reloc_total_drive_ = 0.0; // cong don cho mot lan dinh vi
int reloc_exec_cycles_ = 0;
std::chrono::steady_clock::time_point reloc_phase_t0_;
std::chrono::steady_clock::time_point reloc_yield_until_; // nguoi thang -> nhuong
// Pha "dung yen roi tinh chinh" (RelocSettle). Gom luc DANG QUAY lam dam
// diem nhoe 1-2 do moi scan (odom doc tre hon luc quet) -- mo phong
// 2026-09-29: chot lech 0.12 m va RTAB-Map khong sua vi robot dung ngay.
bool reloc_settle_ = false;
Pose2D reloc_settle_T_; // T_map_odom luc chot, chua tinh chinh
double reloc_settle_ratio_ = 0.0;
std::chrono::steady_clock::time_point reloc_settle_t0_;
std::chrono::steady_clock::time_point reloc_still_since_;
bool reloc_still_ = false;
Pose2D reloc_settle_prev_odom_;
std::vector<Point> reloc_settle_pts_;
int reloc_settle_scans_ = 0;
std::string reloc_settle_src_; // "LiDAR, ty le .." | "camera+LiDAR (..)" -- log/web
// --- Camera trong dinh vi lai (--slam-reloc-vpr). CHI luong slam cham. ---
std::unique_ptr<VprEncoder> vpr_; // null = khong dung camera
std::unique_ptr<VisualVerifier> vverif_;
std::vector<int> vpr_ids_; // node ban do co mo ta
std::vector<float> vpr_desc_; // vpr_ids_.size() x dim, da chuan hoa
struct MapShot {
VisualFrame f; // ORB + depth + K + T_base_optical
cv::Matx44d T_map_base;
};
std::map<int, MapShot> vpr_shots_; // node ban do, nap khi can roi giu
bool reloc_cam_have_last_ = false;
double reloc_cam_last_theta_ = 0.0; // odom.theta lan chup gan nhat
UnixTime reloc_cam_last_stamp_;
int reloc_cam_shots_ = 0; // anh da thu trong vong gom nay
int reloc_cam_best_inl_ = 0; // inlier PnP tot nhat vong nay
// ---- Test doc tu dong (--slope-test) ----
std::mutex slope_mu_; // slope_test_ + slope_planned_
std::unique_ptr<SlopeTest> slope_test_; // null = khong bat
bool slope_planned_ = false;
std::atomic<int> slope_button_{0}; // so lan bam Y (luong tay cam ghi)
std::atomic<bool> slope_lost_{false}; // luong slam bao: mat dinh vi
std::thread slope_thread_;
// CHI luong slam.
bool slope_plan_failed_ = false;
std::chrono::steady_clock::time_point slope_meas_at_;
int slope_low_ = 0; // so lan do lien tiep scan khop kem
std::FILE* slope_csv_ = nullptr;
std::string slope_csv_path_;
std::chrono::steady_clock::time_point slope_t0_;
struct SlopeSample {
int loop;
bool down;
double speed;
bool moving;
double err_cm, dth_deg, score;
bool have_z;
double zerr_cm;
};
std::vector<SlopeSample> slope_samples_;
bool slope_summary_done_ = false;
#endif #endif
// Doc-only sau Start(), nen khong can mutex. // Doc-only sau Start(), nen khong can mutex.
@@ -319,12 +543,16 @@ class Runtime {
Pose2D prev_odom_; Pose2D prev_odom_;
UnixTime prev_odom_stamp_; UnixTime prev_odom_stamp_;
bool have_prev_odom_ = false; bool have_prev_odom_ = false;
double gyro_z_ = 0.0; // Goc quay cho EKF: gyro giu tong, encoder lap khoang gyro chua ve (xem
UnixTime gyro_stamp_; // gyro_yaw_fuser.h). Duoi `odom_mu_`.
// Tich phan gyro giua hai lan cap nhat odom, va tong thoi gian da phu. GyroYawFuser yaw_fuser_;
double gyro_dtheta_ = 0.0; // Chan doan goc quay 30 s mot lan (wiring.cc). Duoi `odom_mu_`.
double gyro_dt_ = 0.0; double yaw_diag_enc_ = 0.0;
bool have_gyro_ = false; double yaw_diag_enc_abs_ = 0.0;
double yaw_diag_fused_ = 0.0;
int yaw_diag_steps_ = 0;
int yaw_diag_gyro_ = 0;
UnixTime yaw_diag_t0_;
// Ground truth CHOT cung luc voi EKF, duoi `odom_mu_`. Doc tuoi luc chup // Ground truth CHOT cung luc voi EKF, duoi `odom_mu_`. Doc tuoi luc chup
// snapshot roi dem voi pose cu la do DO TRE chu khong phai sai so. // snapshot roi dem voi pose cu la do DO TRE chu khong phai sai so.
@@ -356,6 +584,40 @@ class Runtime {
std::atomic<double> tilt_roll_{0.0}; std::atomic<double> tilt_roll_{0.0};
std::atomic<double> tilt_pitch_{0.0}; std::atomic<double> tilt_pitch_{0.0};
std::atomic<bool> tilt_accel_ok_{false}; 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();
// Chinh meo scan (sensors.yaml `lidar.deskew`, CHI LiDAR that). Doc-only sau
// Start(); can laser_to_base_static_ o tren.
bool deskew_on_ = false;
SweepTiming sweep_;
bool have_cam_to_base_ = false;
// CHI luong slam: lan giai do thi z cuoi; da neo z lan nao chua (lan DAU
// sau khoi dong / dinh vi lai thi DAT THANG z ban do, khong qua cong).
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> estop_{false};
std::atomic<bool> stop_{false}; std::atomic<bool> stop_{false};

View File

@@ -18,10 +18,14 @@
#include "runtime.h" #include "runtime.h"
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/json_parse.h" #include "vslam/json_parse.h"
#include "vslam/log.h" #include "vslam/log.h"
#include <algorithm>
#include <cmath> #include <cmath>
#include <cstring>
#include <vector>
namespace vslam { namespace vslam {
@@ -36,8 +40,52 @@ StatusResponse Runtime::Wire() {
// rieng thi "cai nao chay truoc" la mot bay co that. // rieng thi "cai nao chay truoc" la mot bay co that.
auto copy = std::make_shared<LaserScan>(*s); auto copy = std::make_shared<LaserScan>(*s);
sanitizer_->Apply(copy.get()); sanitizer_->Apply(copy.get());
// Ban cho SLAM / dinh vi lai: CHINH MEO (LiDAR that) roi BU NGHIENG (doc).
// An toan va web giu ban tho. Tat ca hai thi hai con tro la MOT.
LaserScanPtr slam_scan = copy;
if (deskew_on_) {
// w ~ gyro 200 Hz qua EKF (lech 0.008 rad/s x 40 ms: khong dang ke),
// v theo encoder. Kep de mot mau van toc hong khong be cong scan.
double w = 0.0, v = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
w = std::max(-2.0, std::min(2.0, ekf_->vyaw()));
v = std::max(-1.0, std::min(1.0, ekf_->vx()));
}
auto dsk = std::make_shared<LaserScan>();
DeskewScan(*copy, laser_to_base_static_, sweep_, w, v, dsk.get());
slam_scan = dsk;
}
if (slope_on_ && cfg_->slope.level_scan) {
Pose2D od;
double z = 0.0;
{
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(*slam_scan, laser_to_base_static_, roll, pitch,
cfg_->robot.geometry().wheel_radius, od, z, elev_.get(), level_cfg_,
lv.get(), &level_stats_);
// Ti le tia giu lai (cong don tu luc chay) -- san phang phai ~100%.
// 07/10: nua scan bi bo tu 06/10 ma khong dong log nao bao.
const ScanLevelStats& ls = level_stats_;
VSLAM_INFO_THROTTLE(30.0, "slope/scan: giu " << ls.kept << "/" << ls.rays << " tia ("
<< (ls.rays > 0 ? 100 * ls.kept / ls.rays : 0) << "%), bo cham san "
<< ls.dropped_floor << ", duoi dat " << ls.dropped_below << ", ngoai goc "
<< ls.rays - ls.kept - ls.dropped_floor - ls.dropped_below);
}
slam_scan = lv;
}
std::lock_guard<std::mutex> lk(scan_mu_); std::lock_guard<std::mutex> lk(scan_mu_);
latest_scan_ = copy; latest_scan_ = copy;
latest_slam_scan_ = slam_scan;
}); });
} }
@@ -55,24 +103,14 @@ StatusResponse Runtime::Wire() {
tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed); tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed);
tilt_accel_ok_.store(perception_->gravity().accel_ok(), tilt_accel_ok_.store(perception_->gravity().accel_ok(),
std::memory_order_relaxed); std::memory_order_relaxed);
tilt_valid_.store(perception_->gravity().valid(), std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(odom_mu_); std::lock_guard<std::mutex> lk(odom_mu_);
wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z); wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z);
// ⚠️ TICH PHAN gyro, khong lay mot mau. // Goc gyro (EKF dung khi `ekf.gyro_yaw: true`; log odom/yaw luon dung): TICH
// // PHAN theo DAU THOI GIAN mau (hinh thang), khong theo luc mau toi -- xem
// IMU chay 200 Hz con encoder 50 Hz, nen moi khoang odom co ~4 mau. // GyroYawFuser.
// Lay MOT mau roi nhan voi ca khoang 20 ms la phep hinh chu nhat tren yaw_fuser_.AddGyro(m->header.stamp, m->angular_velocity.z);
// mot tin hieu dang doi nhanh -- da do: sai goc 150 do sau mot lan xoay.
if (have_gyro_) {
const double dti = SecondsBetween(m->header.stamp, gyro_stamp_);
if (dti > 0.0 && dti < 0.1) {
gyro_dtheta_ += 0.5 * (gyro_z_ + m->angular_velocity.z) * dti;
gyro_dt_ += dti;
}
}
gyro_z_ = m->angular_velocity.z;
gyro_stamp_ = m->header.stamp;
have_gyro_ = true;
ekf_->UpdateImuYawRate(m->header.stamp, m->angular_velocity.z, ekf_->UpdateImuYawRate(m->header.stamp, m->angular_velocity.z,
m->angular_velocity_covariance[8] > 0.0 m->angular_velocity_covariance[8] > 0.0
? m->angular_velocity_covariance[8] ? m->angular_velocity_covariance[8]
@@ -108,6 +146,8 @@ StatusResponse Runtime::Wire() {
// ---------------- Encoder ---------------- // ---------------- Encoder ----------------
if (base_ != nullptr) { if (base_ != nullptr) {
VSLAM_INFO("odom: goc quay EKF theo " << (cfg_->ekf_gyro_yaw ? "GYRO" : "ENCODER")
<< " (pipeline.yaml ekf.gyro_yaw) -- gyro van so trong log odom/yaw");
base_->SetEncoderCallback([this](const EncoderReading& e) { base_->SetEncoderCallback([this](const EncoderReading& e) {
if (!e.valid) return; if (!e.valid) return;
Odometry o; Odometry o;
@@ -137,19 +177,25 @@ StatusResponse Runtime::Wire() {
double d_theta = NormalizeAngle(now_pose.theta - prev_odom_.theta); double d_theta = NormalizeAngle(now_pose.theta - prev_odom_.theta);
const double dt = SecondsBetween(e.stamp, prev_odom_stamp_); const double dt = SecondsBetween(e.stamp, prev_odom_stamp_);
// Gyro da duoc TICH PHAN trong callback IMU. Chi nhan neu no phu // Goc gyro cho buoc nay: GyroYawFuser -- gyro giu TONG, encoder chi lap
// gan het khoang odom -- thieu mau thi tich phan khong dai dien. // khoang gyro chua ve. Cach cu tich gyro theo luc mau TOI va chi nhan
// Cua so gyro phai KHOP buoc encoder. IMU that 10 Hz (T=0.1002 s), // khi cua so dai 0.5-1.5 buoc encoder, ngoai do VUT: tren robot that
// encoder ~44 Hz: mot mau gyro mang 0.1 s goc quay do vao buoc 23 ms // mau toi theo cum (log 07/10: cua so 40 ms / buoc 22.5 ms) -> ban do
// trong khi cac buoc truoc da cong goc encoder -> goc dem HAI LAN. // real_20261007_112455 dem THIEU 9.9% moi goc quay (cac cap node dung
const bool gyro_ok = // yen hai dau van 9.6%: loi ti le, khong phai lech gio). IMU cham
dt > 0.0 && gyro_dt_ > 0.5 * dt && gyro_dt_ < 1.5 * dt; // (10 Hz) / het tuoi thi chi encoder, nhu truoc 06/10.
if (dt > 0.0 && gyro_dt_ >= 1.5 * dt) { double d_theta_gyro = d_theta;
VSLAM_WARN_THROTTLE(30.0, "odom: gyro cham hon encoder (cua so " const bool gyro_step = dt > 0.0 && yaw_fuser_.Step(e.stamp, d_theta, &d_theta_gyro);
<< gyro_dt_ << " s / buoc " << dt << " s) -- bo gyro, dung goc " // EKF chi lay goc gyro khi pipeline.yaml `ekf.gyro_yaw: true`. Mac dinh
"encoder. Tang toc do IMU len >= 100 Hz de dung duoc gyro."); // TAT: WT61PC lech MOT CHIEU khi chay -- 07/10 14:27-14:29 gyro - encoder
// = +0.11..+0.38 rad moi 30 s du quay trai hay phai (+71 do trong 2.5
// phut), dung yen thi tra 0 nen khong thay. Ban do chi encoder (28/09,
// 01/10) thi dung. GyroYawFuser van chay de log `odom/yaw` so hai nguon.
const bool gyro_ok = gyro_step && cfg_->ekf_gyro_yaw;
if (cfg_->ekf_gyro_yaw && !gyro_step && yaw_fuser_.gyro_period() > 0.03) {
VSLAM_WARN_THROTTLE(60.0, "odom: IMU cham (chu ky " << yaw_fuser_.gyro_period() * 1e3
<< " ms) -- goc quay chi theo encoder. Can IMU >= 33 Hz de dung gyro.");
} }
const double d_theta_gyro = gyro_ok ? gyro_dtheta_ : d_theta;
// Phuong sai: wheel_odom bao qua twist.covariance -- do chinh la // Phuong sai: wheel_odom bao qua twist.covariance -- do chinh la
// cho no noi "dang truot, dung tin toi". // cho no noi "dang truot, dung tin toi".
@@ -162,11 +208,54 @@ StatusResponse Runtime::Wire() {
gyro_ok ? std::max(2.4e-7 * dt, 1e-12) : 1e9; 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); 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
var_tr, var_th_enc, var_th_gyro); // 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);
}
// Tat gyro thi EKF nhan DUNG goc encoder, khong phu thuoc ti le phuong sai.
ekf_->UpdateOdomDelta(e.stamp, d_trans_ekf, d_theta, gyro_ok ? d_theta_gyro : d_theta,
var_tr, var_th_enc, var_th_gyro);
// Chan doan 30 s mot lan: goc quay RONG theo encoder va theo gyro
// (GyroYawFuser), in HIEU tuyet doi -- lech mot chieu (07/10: gyro
// +0.11..+0.38 rad moi 30 s) doc theo % se tuong la loi ti le. Encoder
// sai ~2% (ban do 28/09, 01/10).
yaw_diag_enc_ += d_theta;
yaw_diag_enc_abs_ += std::fabs(d_theta);
yaw_diag_fused_ += gyro_step ? d_theta_gyro : d_theta;
++yaw_diag_steps_;
if (gyro_step) ++yaw_diag_gyro_;
if (yaw_diag_t0_.isZero()) yaw_diag_t0_ = e.stamp;
if (SecondsBetween(e.stamp, yaw_diag_t0_) >= 30.0) {
if (yaw_diag_enc_abs_ > 0.5) { // co quay, ke ca quay qua lai
VSLAM_INFO("odom/yaw: 30 s qua: quay rong encoder " << yaw_diag_enc_
<< " rad, gyro " << yaw_diag_fused_ << " rad (gyro - encoder "
<< yaw_diag_fused_ - yaw_diag_enc_ << " rad), tong |quay| "
<< yaw_diag_enc_abs_ << " rad, " << 100 * yaw_diag_gyro_ / yaw_diag_steps_
<< "% buoc co gyro (chu ky " << yaw_fuser_.gyro_period() * 1e3
<< " ms) -- EKF theo " << (cfg_->ekf_gyro_yaw ? "GYRO" : "ENCODER"));
}
yaw_diag_enc_ = yaw_diag_enc_abs_ = yaw_diag_fused_ = 0.0;
yaw_diag_steps_ = yaw_diag_gyro_ = 0;
yaw_diag_t0_ = e.stamp;
}
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;
prev_odom_ = now_pose; prev_odom_ = now_pose;
prev_odom_stamp_ = e.stamp; prev_odom_stamp_ = e.stamp;
have_prev_odom_ = true; have_prev_odom_ = true;
@@ -234,6 +323,9 @@ StatusResponse Runtime::Wire() {
have_depth_ = true; 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 -> // Ca chuoi perception chay INLINE o day: depth -> cloud -> loc ->
// can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong // can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong
// camera. // camera.
@@ -397,4 +489,62 @@ StatusResponse Runtime::Wire() {
return StatusResponse::Ok(); 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 } // namespace vslam

View File

@@ -14,6 +14,13 @@ ekf:
# Bo qua mau cach mau truoc qua lau: ban ghi bi cat, hoac cam bien vua cam # Bo qua mau cach mau truoc qua lau: ban ghi bi cat, hoac cam bien vua cam
# lai. Tich phan qua mot lo hong 2 giay la bia them sai so. # lai. Tich phan qua mot lo hong 2 giay la bia them sai so.
max_dt: 0.5 max_dt: 0.5
# Goc quay EKF: false = theo ENCODER (nhu truoc 06/10), true = theo gyro
# WT61PC (GyroYawFuser). 07/10 tren robot that: gyro - encoder = +0.11..+0.38
# rad moi 30 s, CA khi quay trai lan quay phai (+71 do trong 2.5 phut); dung
# yen thi WT61PC tra 0 nen khong thay. Ban do chi dung encoder (28/09, 01/10)
# thi dung. Chi bat lai khi da do/bu duoc lech gyro -- log `odom/yaw` van in
# gyro - encoder du tat hay bat.
gyro_yaw: false
# ============ depth -> cloud -> loc ============ # ============ depth -> cloud -> loc ============
depth_filter: depth_filter:

View File

@@ -72,6 +72,22 @@ lidar:
# |(t_cuoi - t_dau) - scan_time| > nguong nay. # |(t_cuoi - t_dau) - scan_time| > nguong nay.
stamp_mismatch_warn: 0.005 stamp_mismatch_warn: 0.005
# --- Gio cua scan so voi odometry: DO tren ban do that ---
# Driver dong dau scan luc NHAN XONG vong quet. ICP scan luc robot dang QUAY
# voi scan gan do luc gan dung yen (ban do 28/09 + 01/10, 88 + 179 cap): scan
# tre +55..57 ms so voi odometry SAU khi chinh meo (+72..79 ms neu khong).
# Quay 0.8 rad/s ma khong bu -> moi scan lech 2.5-3.5 do, tuong dup sau moi
# lan quay. Doi phan cung / driver thi do lai.
stamp_offset_sec: -0.055
# Chinh meo: moi tia chup o mot thoi diem khac trong vong quet 40 ms (25 Hz);
# quay 0.8 rad/s thi tia dau va tia cuoi lech 1.8 do. Dua moi tia ve khung
# robot luc stamp theo w, v cua EKF. Chieu quet DO tren ban do that: goc GIAM
# theo thoi gian khi angle_flip: true (vong bat dau o angle_offset_deg, phia
# sau); chieu nguoc lai lam scan khop TE hon. Chi LiDAR that (--live,
# --replay) -- scan sim chup tuc thoi. Ban cho SLAM / dinh vi lai; an toan va
# web van dung scan tho.
deskew: true
# ============ BON BO LOC SCAN ============ # ============ BON BO LOC SCAN ============
# Chay TREN scan tho, truoc ScanSanitizer. Nguon: lakibeam.yaml cua # Chay TREN scan tho, truoc ScanSanitizer. Nguon: lakibeam.yaml cua
# base_kit -- bo tham so da duoc chinh tren chinh con robot nay. # base_kit -- bo tham so da duoc chinh tren chinh con robot nay.
@@ -167,11 +183,27 @@ camera:
# TIME_OF_ARRIVAL. Giu true van dung, duong lui da chay. # TIME_OF_ARRIVAL. Giu true van dung, duong lui da chay.
prefer_global_time: true prefer_global_time: true
# ============ MCU ============ # ============ MCU / IMU ============
mcu: mcu:
port: /dev/ttyACM0 # ============ NOI IMU VAO MAY ============
# 115200 theo firmware that (ESP32-S3 + WT61PC). Gia tri cu la 921600 -- doc # wt61pc = WT61PC noi THANG UART hoac cap USB-FTDI, khung nhi phan 0x55 cua
# sai baud cho ra RAC chu khong cho ra loi, nen no hong im lang. # cam bien (wt61pc_protocol.h). Khong con ESP32, khong co ClockSync:
# stamp lay tu dong ho HOST, tru imu_lag_sec.
# esp = ESP32-S3 + WT61PC qua USB-CDC (cach cu, firmware/imu_uart/).
# Cac muc sync_window, max_skew_warn, expect_timestamps, ticks_per_rev ben
# duoi CHI co nghia voi `esp`.
protocol: wt61pc
# 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: 115200 baud: 115200
# ClockSync khop micros() cua MCU voi dong ho host bang fit tuyen tinh. # ClockSync khop micros() cua MCU voi dong ho host bang fit tuyen tinh.
@@ -243,7 +275,17 @@ mcu:
# #
# ⚠️ Phai do lai neu doi tan so cam bien hoac baud cua day UART1 -- ca hai so # ⚠️ Phai do lai neu doi tan so cam bien hoac baud cua day UART1 -- ca hai so
# hang tren deu phu thuoc chung. # hang tren deu phu thuoc chung.
imu_lag_sec: 0.07 #
# ⚠️ 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.
#
# --- 2026-10-06: 115200 baud / 200 Hz, DO tren robot that ---
# dat 0.01 (uoc luong) -> log `tot nhat 20 ms` on dinh tu mau 1000 den
# 5000, lai ra vao cua -> 0.01 + 0.02 = 0.03. Uoc luong ~2 ms day khung +
# ~1 ms USB nen loc noi bo cua cam bien ~27 ms, khong phai 3-10 ms.
# Lan chay sau phai bao ~0 ms (bin 10 ms). Giu 0.07 o 200 Hz la lech ~40 ms.
imu_lag_sec: 0.03
# Ban ghi encoder `E,<micros>,<ticks_l>,<ticks_r>` la MO RONG moi -- giao # Ban ghi encoder `E,<micros>,<ticks_l>,<ticks_r>` la MO RONG moi -- giao
# thuc cu chi co I/B/P. # thuc cu chi co I/B/P.

View File

@@ -62,9 +62,9 @@ optimizer_strategy: "1"
# nhieu do/buoc (IMU 10 Hz dem goc hai lan), khai chac thi ICP khong nan # nhieu do/buoc (IMU 10 Hz dem goc hai lan), khai chac thi ICP khong nan
# duoc. Chay lai DB that: 0.01/0.005 van xoan; 0.1/0.1 hanh lang thang, # duoc. Chay lai DB that: 0.01/0.005 van xoan; 0.1/0.1 hanh lang thang,
# phong vuong. (Mo phong thi 0.01/0.005 tot hon ~30% -- odom mo phong gan # phong vuong. (Mo phong thi 0.01/0.005 tot hon ~30% -- odom mo phong gan
# nhu hoan hao -- nhung robot that la dich.) # nhu hoan hao.)
odom_sigma_m: 0.1 #
odom_sigma_rad: 0.1 # -> GIA TRI nam o `profiles:` cuoi file: mo phong va robot that khac nhau.
# ============ THI GIAC ============ # ============ THI GIAC ============
# Kp/MaxFeatures: -1 khi false, 400 khi true. # Kp/MaxFeatures: -1 khi false, 400 khi true.
@@ -170,6 +170,80 @@ voxel:
# Tuong va ban ghe dung yen thi nhieu node thay nen van giu. # Tuong va ban ghe dung yen thi nhieu node thay nen van giu.
min_node_hits: 3 min_node_hits: 3
# LAN NHIN MOI NHAT QUYET DINH (07/10). Truoc day lop nay CHI THEM: 3 nguoi
# dung tren duong luc quet thanh vat can vinh vien, quay lai quet van con.
# Gio: voxel ma >= bay nhieu node SAU lan thay cuoi nhin XUYEN qua (depth xa
# hon voxel + 0.10 + 0.03 z^2 m) va khong node nao trong do con thay -> XOA,
# ca khoi ban do 3D lan lop vat can 2D. Bi che (depth gan hon) thi khong tinh
# -- khong biet thi khong xoa. Ap ca luc quet lan luc mo ban do da luu.
# 0 = tat (chi them, nhu truoc).
clear_after_views: 2
# ============ VONG DONG XA (chi khi quet) ============
# Phat hien ke can cua RTAB-Map chi xet node trong 50 buoc do thi
# (RGBD/ProximityMaxGraphDepth), nen quay lai cho cu sau mot vong DAI thi
# 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. WT61PC tren robot da o 115200 baud
# / 200 Hz (06/10/2026, sensors.yaml `mcu`).
#
# ⚠️ 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.
#
# Mac dinh BAT tu 06/10/2026: robot di giua cac toa nha qua doc. San phang thi
# z kep ve 0, khong doi gi. Ban do quet truoc khi co che do doc (DB khong co z
# tung node) van mo duoc: khong co mat san -> bo loc nghieng cua dinh vi lai
# tu tat, chay nhu cu. enabled: false = moi duong cu giu nguyen.
slope:
enabled: true
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 ============ # ============ KHOI RTAB-MAP ============
# Ghi de len mac dinh cua du an (xem BuildRtabmapParams). De trong thi dung # 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. # mac dinh -- do la lua chon dung cho hau het truong hop.
@@ -187,11 +261,7 @@ rtabmap:
Icp/MaxCorrespondenceDistance: "0.15" Icp/MaxCorrespondenceDistance: "0.15"
Icp/Iterations: "30" Icp/Iterations: "30"
Icp/Epsilon: "0.001" Icp/Epsilon: "0.001"
# 0.3 (chinh tren mo phong) loai HET ICP tren LiDAR that: ti le khop that # Icp/CorrespondenceRatio -> `profiles:` cuoi file (sim va real khac nhau).
# chi 0.05-0.1, mot phan vi RTAB-Map chia cho 1440 tia khai trong header
# trong khi chi ~655 diem hop le. DB that 2026-09-25: 0.3 -> 0 lien ket,
# 0.1 -> 18, 0.05 -> 325 (ban do dung).
Icp/CorrespondenceRatio: "0.05"
Icp/MaxTranslation: "0.5" Icp/MaxTranslation: "0.5"
# --- Vong dong va lien ket lan can --- # --- Vong dong va lien ket lan can ---
@@ -239,6 +309,16 @@ rtabmap:
Grid/CellSize: "0.05" Grid/CellSize: "0.05"
Grid/RangeMax: "12.0" Grid/RangeMax: "12.0"
Grid/RayTracing: "true" Grid/RayTracing: "true"
# Luoi 2D theo LAN NHIN MOI NHAT (07/10). Moi o cong log-odds: trung +0.85,
# truot (tia di xuyen qua) -0.62, kep trong [-1.39, +1.39]. Mac dinh RTAB-Map
# kep +3.5 va truot -0.41: o da chac chiem can ~9 lan nhin xuyen qua moi xoa
# -> nguoi dung lai roi di, quay lai quet van con tren ban do. Bo nay: 3 lan
# xuyen qua -> trong, 2 lan thay vat -> chiem. Doi lai: vat rat manh (chan
# ghe) co the chap chon khi tia luot sat ben canh.
GridGlobal/ProbHit: "0.7"
GridGlobal/ProbMiss: "0.35"
GridGlobal/ProbClampingMin: "0.2"
GridGlobal/ProbClampingMax: "0.8"
Grid/3D: "false" Grid/3D: "false"
Grid/DepthDecimation: "4" Grid/DepthDecimation: "4"
@@ -254,3 +334,33 @@ rtabmap:
# ⚠️ Doi lai: DB khong con MOI khung, nen vslam_slam_bench chay lai tu no # ⚠️ Doi lai: DB khong con MOI khung, nen vslam_slam_bench chay lai tu no
# se thua hon phien goc. Quet de lam du lieu phan tich thi dat "true". # se thua hon phien goc. Quet de lam du lieu phan tich thi dat "true".
Mem/NotLinkedNodesKept: "false" Mem/NotLinkedNodesKept: "false"
# ============ THEO MOI TRUONG ============
# Mo phong va robot that can bo so KHAC nhau cho cung mot key. Chon TU DONG
# theo nguon: --sim -> sim; --live / --replay -> real (replay la du lieu
# robot that).
#
# Node TU CHOI khoi dong neu:
# - thieu mot trong hai khoi, hoac co khoi thu ba;
# - hai khoi KHONG cung tap key (sua mot ben quen ben kia);
# - mot key vua o day vua o phan chung phia tren (mot key, mot cho);
# - co key ngoai odom_sigma_m, odom_sigma_rad, rtabmap.
profiles:
sim:
# Odom mo phong gan nhu hoan hao, scan du 1440 tia. hospital_nam
# 2026-09-25 (run_N1): sai so vs ground truth 3-5 cm; cung ban do voi
# bo so `real` 2026-09-28: 8-12 cm sau 5 phut.
odom_sigma_m: 0.01
odom_sigma_rad: 0.005
rtabmap:
Icp/CorrespondenceRatio: "0.3"
real:
# 2026-09-25: 0.01/0.005 lam ban do xoan (odom that sai nhieu do/buoc);
# 0.1/0.1 hanh lang thang, phong vuong.
odom_sigma_m: 0.1
odom_sigma_rad: 0.1
rtabmap:
# Ti le khop that chi 0.05-0.1: RTAB-Map chia cho 1440 tia khai trong
# header trong khi LakiBeam chi ~655 diem hop le. DB that 2026-09-25:
# 0.3 -> 0 lien ket, 0.1 -> 18, 0.05 -> 325 (ban do dung).
Icp/CorrespondenceRatio: "0.05"

View File

@@ -161,6 +161,7 @@ gamepad:
button_zero: 1 # B -- ve 0 ngay button_zero: 1 # B -- ve 0 ngay
button_turbo: 5 # RB button_turbo: 5 # RB
button_slow: 4 # LB button_slow: 4 # LB
button_test: 3 # Y -- test doc tu dong (--slope-test): bat dau / chay tiep
# ⚠️ BAT CA HAI -- DO TREN CHINH CON ROBOT NAY. # ⚠️ BAT CA HAI -- DO TREN CHINH CON ROBOT NAY.
# #

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) if(VSLAM_BUILD_SIM)
add_subdirectory(vslam_sim) add_subdirectory(vslam_sim)
endif() 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

@@ -14,6 +14,7 @@ vslam_add_library(vslam_drivers
scan_sanitizer.h scan_sanitizer.h
clock_sync.h clock_sync.h
mcu_protocol.h mcu_protocol.h
wt61pc_protocol.h
record_format.h record_format.h
record_io.h record_io.h
replay_source.h replay_source.h

View File

@@ -115,9 +115,14 @@ struct LidarConfig {
bool inverted = true; bool inverted = true;
LidarStampMode stamp_mode = LidarStampMode::kFirstPacket; LidarStampMode stamp_mode = LidarStampMode::kFirstPacket;
// Bu do tre da do duoc, cong vao stamp. Chua do -> 0. // Bu do tre da do duoc, cong vao stamp. Chua do -> 0. sensors.yaml
// `lidar.stamp_offset_sec` (07/10: -0.055, do tren ban do that).
double stamp_offset_sec = 0.0; double stamp_offset_sec = 0.0;
// Chinh meo scan trong vong quet (runtime lam, khong phai driver -- driver
// khong biet robot dang chuyen dong the nao). sensors.yaml `lidar.deskew`.
bool deskew = true;
// Canh bao neu do dai sweep lech qua nhieu so voi scan_time du kien. Day la // Canh bao neu do dai sweep lech qua nhieu so voi scan_time du kien. Day la
// bo phat hien mat goi UDP mien phi ma driver goc khong co. // bo phat hien mat goi UDP mien phi ma driver goc khong co.
double sweep_duration_tolerance_sec = 0.005; double sweep_duration_tolerance_sec = 0.005;
@@ -175,7 +180,17 @@ struct CameraConfig {
// --- MCU: IMU + barometer -------------------------------------------------- // --- MCU: IMU + barometer --------------------------------------------------
// Cach IMU noi vao may.
enum class McuProtocol {
// ESP32-S3 + WT61PC, text qua USB-CDC (/dev/ttyACM0). Xem mcu_bridge.cc.
kEspText,
// WT61PC noi THANG UART hoac cap USB-FTDI (/dev/imu), khung nhi phan 0x55.
// Khong con ESP32, khong co ClockSync. Xem wt61pc_bridge.cc.
kWt61pc,
};
struct McuConfig { struct McuConfig {
McuProtocol protocol = McuProtocol::kEspText;
std::string port = "/dev/ttyACM0"; std::string port = "/dev/ttyACM0";
// 115200, theo firmware that (base_kit/src/imu_uart). Gia tri cu o day la // 115200, theo firmware that (base_kit/src/imu_uart). Gia tri cu o day la
// 921600 -- doc sai baud thi ra rac chu khong ra loi, nen no im lang. // 921600 -- doc sai baud thi ra rac chu khong ra loi, nen no im lang.
@@ -219,6 +234,10 @@ struct McuConfig {
double baro_variance = 9.0; double baro_variance = 9.0;
double read_timeout_sec = 1.0; double read_timeout_sec = 1.0;
// Chi cho kWt61pc: khong co khung hop le nao trong chung nay (giay) thi WARN
// kem goi y. Cam bien 10 Hz nen 2 s la mat ~20 khung, khong con la jitter.
double no_data_warn_sec = 2.0;
}; };
// --- Base: encoder + motor ------------------------------------------------- // --- Base: encoder + motor -------------------------------------------------

View File

@@ -100,6 +100,9 @@ struct GamepadConfig {
int button_zero = 1; // B -- ve 0 ngay int button_zero = 1; // B -- ve 0 ngay
int button_turbo = 5; // RB int button_turbo = 5; // RB
int button_slow = 4; // LB int button_slow = 4; // LB
// Y -- test doc tu dong (--slope-test): bat dau / chay tiep sau tam dung.
// Bat ke dang bat dieu khien hay khong.
int button_test = 3;
// Duong thoat khi bo tay cam nguoc chieu. Doi mot dong YAML thay vi sua code // Duong thoat khi bo tay cam nguoc chieu. Doi mot dong YAML thay vi sua code
// roi build lai -- chieu truc chi kiem duoc bang cach cam tay cam vao robot // roi build lai -- chieu truc chi kiem duoc bang cach cam tay cam vao robot
@@ -191,6 +194,9 @@ struct GamepadCommand {
// Chuyen trang thai, chi de LOG. Mapper khong tu log: no thuan. // Chuyen trang thai, chi de LOG. Mapper khong tu log: no thuan.
bool enabled_changed = false; bool enabled_changed = false;
bool connected_changed = false; bool connected_changed = false;
// Vua BAM nut test (canh len) -- runtime dem so lan bam.
bool test_pressed = false;
}; };
// Tho -> van toc. THUAN: khong doc dong ho, khong doc file, khong log. // Tho -> van toc. THUAN: khong doc dong ho, khong doc file, khong log.
@@ -215,6 +221,7 @@ class GamepadMapper {
bool enable_pressed_ = false; // chong dap phim, = start_pressed_ ben kia bool enable_pressed_ = false; // chong dap phim, = start_pressed_ ben kia
bool was_connected_ = false; bool was_connected_ = false;
bool have_active_ = false; // da tung co lenh chuyen dong bool have_active_ = false; // da tung co lenh chuyen dong
bool test_prev_ = false; // nut test vong truoc (bat canh len)
UnixTime last_active_; UnixTime last_active_;
}; };

View File

@@ -73,6 +73,10 @@ enum class VsrStream : uint8_t {
// bao "xanh" cho mot he da mat hai nhanh an toan. // bao "xanh" cho mot he da mat hai nhanh an toan.
kUltrasonic = 11, kUltrasonic = 11,
kBumper = 12, 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); 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); void EncodeBumperPayload(uint32_t mask, std::string* out);
bool DecodeBumperPayload(const std::string& buf, uint32_t* mask); 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); void EncodeCameraInfoPayload(const CameraInfo& info, std::string* out);
bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out); bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out);

View File

@@ -0,0 +1,81 @@
#ifndef VSLAM_WT61PC_PROTOCOL_H
#define VSLAM_WT61PC_PROTOCOL_H
// Khung nhi phan cua WT61PC (IMU 6 truc, WitMotion) khi cam THANG vao UART hoac
// cap USB-FTDI cua Jetson, khong qua ESP32.
//
// Khac mcu_protocol.h: day KHONG phai giao thuc cua du an. No la giao thuc cua
// cam bien, nen file nay GHI LAI dac ta cua nha san xuat; ben phai khop la
// cam bien, khong phai firmware.
//
// ================== KHUNG ==================
// 11 byte. Cam bien phat lien tuc, moi chu ky ba khung theo thu tu:
// 0x55 0x51 axL axH ayL ayH azL azH TL TH SUM gia toc
// 0x55 0x52 gxL gxH gyL gyH gzL gzH TL TH SUM van toc goc
// 0x55 0x53 rL rH pL pH yL yH TL TH SUM goc (roll, pitch, yaw)
// Moi truong la int16 little-endian. SUM = tong 10 byte dau, lay 8 bit thap.
//
// ================== DOI DON VI ==================
// gia toc : raw / 32768 * 16 g -> m/s^2 (g = 9.80665)
// van toc : raw / 32768 * 2000 do/s -> rad/s
// goc : raw / 32768 * 180 do -> rad
// Cung cong thuc voi firmware/imu_uart/main/main.c, nen truc va dau KHONG doi so
// voi ban ghi `I` cua ESP32: doi nguon IMU khong dong toi EKF hay gravity_align.
//
// ================== TAN SO ==================
// Mac dinh cua cam bien la 10 Hz o 9600 baud (do duoc: chu ky 0.1001 s). Moi
// chu ky 33 byte, nen 9600 baud tran o ~29 Hz. Muon cao hon phai doi baud CUA
// CAM BIEN (lenh cau hinh cua WitMotion), khong phai chi baud ben host.
#include <cstddef>
#include <cstdint>
namespace vslam {
constexpr size_t kWt61pcFrameBytes = 11;
constexpr uint8_t kWt61pcHeader = 0x55;
enum class Wt61pcType : uint8_t {
kAccel = 0x51, // m/s^2
kGyro = 0x52, // rad/s
kAngle = 0x53, // rad
};
struct Wt61pcFrame {
Wt61pcType type = Wt61pcType::kAccel;
// Da DOI DON VI theo `type`, xem tren.
double x = 0.0;
double y = 0.0;
double z = 0.0;
};
// Bo tach khung theo tung byte. Khong doc dong ho, khong goi he thong: chi la
// ham thuan tren chuoi byte, nen test duoc ma khong can cong serial.
class Wt61pcParser {
public:
// Nap mot byte. true khi byte nay hoan tat mot khung HOP LE loai
// kAccel/kGyro/kAngle (checksum dung) va *out da duoc dien.
bool Push(uint8_t byte, Wt61pcFrame* out);
void Reset();
uint64_t bad_checksum() const { return bad_checksum_; }
// Byte bi bo vi khong thuoc khung nao (rac, hoac mat dong bo).
uint64_t skipped_bytes() const { return skipped_bytes_; }
// Khung dung checksum nhung loai khac 0x51..0x53 (vd 0x54). WT61PC khong co
// tu ke nen binh thuong bang 0; dem de thay khi cam nham mot cam bien khac.
uint64_t other_frames() const { return other_frames_; }
private:
void Resync();
uint8_t buf_[kWt61pcFrameBytes] = {};
size_t n_ = 0;
uint64_t bad_checksum_ = 0;
uint64_t skipped_bytes_ = 0;
uint64_t other_frames_ = 0;
};
} // namespace vslam
#endif // VSLAM_WT61PC_PROTOCOL_H

View File

@@ -91,6 +91,7 @@ GamepadCommand GamepadMapper::Step(const GamepadState& s, UnixTime now) {
enabled_ = false; enabled_ = false;
enable_pressed_ = false; enable_pressed_ = false;
was_connected_ = false; was_connected_ = false;
test_prev_ = false;
} }
out.enabled = false; out.enabled = false;
// Van gui 0 trong cua so idle: rut day giua luc dang chay thi lenh cuoi // Van gui 0 trong cua so idle: rut day giua luc dang chay thi lenh cuoi
@@ -108,6 +109,12 @@ GamepadCommand GamepadMapper::Step(const GamepadState& s, UnixTime now) {
out.connected_changed = true; out.connected_changed = true;
} }
// --- Nut test (Y): canh len, BAT KE dang bat dieu khien hay khong ---------
// Dat TRUOC moi nhanh `return` ben duoi (nut B, coc LT, chua bat).
const bool test_now = s.Button(cfg_.button_test);
out.test_pressed = test_now && !test_prev_;
test_prev_ = test_now;
// --- Nut Start: BAT/TAT dieu khien -------------------------------------- // --- Nut Start: BAT/TAT dieu khien --------------------------------------
// joy_control_node.cpp:180-194. Chong dap phim bang co canh len. // joy_control_node.cpp:180-194. Chong dap phim bang co canh len.
if (s.Button(cfg_.button_enable)) { if (s.Button(cfg_.button_enable)) {

View File

@@ -1,5 +1,8 @@
// Cau noi toi MCU: IMU qua UART. // Cau noi toi MCU: IMU qua UART.
// //
// (Cach thu ba -- WT61PC noi THANG UART, khong ESP32 -- nam o wt61pc_bridge.cc;
// CreateMcuBridge() o cuoi file chon theo mcu.protocol.)
//
// ================== HAI NHANH, CHON BANG mcu.expect_timestamps ================== // ================== HAI NHANH, CHON BANG mcu.expect_timestamps ==================
// //
// `true` -- firmware trong firmware/imu_uart/ cua repo nay. Phat theo dung // `true` -- firmware trong firmware/imu_uart/ cua repo nay. Phat theo dung
@@ -516,8 +519,15 @@ class McuBridge : public McuInterface {
} // namespace } // namespace
// Dinh nghia o wt61pc_bridge.cc.
std::unique_ptr<McuInterface> CreateWt61pcBridge(const McuConfig& cfg,
ClockPtr clock);
std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg, std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg,
ClockPtr clock) { ClockPtr clock) {
if (cfg.protocol == McuProtocol::kWt61pc) {
return CreateWt61pcBridge(cfg, std::move(clock));
}
return std::make_unique<McuBridge>(cfg, std::move(clock)); return std::make_unique<McuBridge>(cfg, std::move(clock));
} }

View File

@@ -37,6 +37,7 @@
#include <thread> #include <thread>
#include <vector> #include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/clock.h" #include "vslam/clock.h"
#include "vslam/driver_config.h" #include "vslam/driver_config.h"
#include "vslam/driver_interfaces.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->data = static_cast<const uint8_t*>(depth.get_data());
depth_img->keep_alive = keep; // KHONG copy: giu frameset song depth_img->keep_alive = keep; // KHONG copy: giu frameset song
} else { } 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->width, &depth_img->height);
depth_img->step = depth_img->width * 2; depth_img->step = depth_img->width * 2;
depth_img->data = depth_buf_.data(); depth_img->data = buf->data();
// Bo dem cua ta: hop le toi lan goi Loop() sau. Consumer chay INLINE depth_img->keep_alive = buf;
// trong callback (xem PerceptionPipeline) nen dieu do la du.
} }
out.depth = depth_img; out.depth = depth_img;
if (cfg_.enable_infra1) { if (cfg_.enable_infra1) {
rs2::video_frame ir = fs.get_infrared_frame(1); 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) { if (cfg_.enable_infra2) {
rs2::video_frame ir = fs.get_infrared_frame(2); 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_; out.depth_info = info_;
@@ -354,8 +363,7 @@ class RealSenseDriver : public CameraInterface {
} }
ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr, ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr,
const std::shared_ptr<FrameKeepAlive>& keep, const std::shared_ptr<FrameKeepAlive>& keep) {
std::vector<uint8_t>* buf) {
auto img = std::make_shared<Image>(); auto img = std::make_shared<Image>();
img->header = hdr; img->header = hdr;
img->format = PixelFormat::kMono8; img->format = PixelFormat::kMono8;
@@ -367,10 +375,13 @@ class RealSenseDriver : public CameraInterface {
img->data = static_cast<const uint8_t*>(ir.get_data()); img->data = static_cast<const uint8_t*>(ir.get_data());
img->keep_alive = keep; img->keep_alive = keep;
} else { } 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, 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->step = img->width;
img->data = buf->data(); img->data = buf->data();
img->keep_alive = buf;
} }
return img; return img;
} }
@@ -384,7 +395,10 @@ class RealSenseDriver : public CameraInterface {
float depth_scale_ = 0.001f; float depth_scale_ = 0.001f;
CameraInfo info_; 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::atomic<bool> running_{false};
std::thread thread_; std::thread thread_;

View File

@@ -121,6 +121,7 @@ const char* VsrStreamName(VsrStream s) {
case VsrStream::kEvent: return "event"; case VsrStream::kEvent: return "event";
case VsrStream::kUltrasonic: return "ultrasonic"; case VsrStream::kUltrasonic: return "ultrasonic";
case VsrStream::kBumper: return "bumper"; case VsrStream::kBumper: return "bumper";
case VsrStream::kGroundTruth: return "ground_truth";
} }
return "?"; return "?";
} }
@@ -225,6 +226,15 @@ bool DecodeBumperPayload(const std::string& buf, uint32_t* mask) {
return r.ok; 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) { void EncodeEncoderPayload(double l, double rr, std::string* o) {
PutF64(o, l); PutF64(o, l);
PutF64(o, rr); PutF64(o, rr);

View File

@@ -7,6 +7,7 @@
#include <mutex> #include <mutex>
#include <vector> #include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/log.h" #include "vslam/log.h"
#include "vslam/record_io.h" #include "vslam/record_io.h"
#include "vslam/scan_sanitizer.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. // roi phat mot lan khi thay chunk depth ke tiep hoac khi het file.
CameraFrame pending_frame; CameraFrame pending_frame;
bool have_pending = false; bool have_pending = false;
std::vector<uint8_t> depth_storage; // Kho nho cho anh giai ma. MOI anh mot kho rieng, giu qua keep_alive:
std::vector<uint8_t> infra1_storage; // SlamLoop giu khung moi nhat qua Rtabmap::process tren luong khac, va ba
std::vector<uint8_t> infra2_storage; // 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; CameraInfo last_info;
bool have_info = false; bool have_info = false;
@@ -360,22 +372,22 @@ void ReplaySource::Run() {
case VsrStream::kDepth: { case VsrStream::kDepth: {
// Chunk depth moi = khung truoc da day du -> phat khung truoc. // Chunk depth moi = khung truoc da day du -> phat khung truoc.
impl_->FlushCameraFrame(); impl_->FlushCameraFrame();
auto img = std::make_shared<Image>(); ImagePtr img = impl_->DecodeImage(payload);
if (!DecodeImagePayload(payload, img.get(), &impl_->depth_storage)) break; if (!img) break;
impl_->pending_frame.header = img->header; impl_->pending_frame.header = img->header;
impl_->pending_frame.depth = img; impl_->pending_frame.depth = img;
impl_->have_pending = true; impl_->have_pending = true;
break; break;
} }
case VsrStream::kInfra1: { case VsrStream::kInfra1: {
auto img = std::make_shared<Image>(); ImagePtr img = impl_->DecodeImage(payload);
if (!DecodeImagePayload(payload, img.get(), &impl_->infra1_storage)) break; if (!img) break;
impl_->pending_frame.infra1 = img; impl_->pending_frame.infra1 = img;
break; break;
} }
case VsrStream::kInfra2: { case VsrStream::kInfra2: {
auto img = std::make_shared<Image>(); ImagePtr img = impl_->DecodeImage(payload);
if (!DecodeImagePayload(payload, img.get(), &impl_->infra2_storage)) break; if (!img) break;
impl_->pending_frame.infra2 = img; impl_->pending_frame.infra2 = img;
break; break;
} }
@@ -385,6 +397,10 @@ void ReplaySource::Run() {
} }
break; 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: case VsrStream::kCmdVel:
// Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra. // 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. // Replay khong tu dong ap chung: viec do do wiring quyet dinh.

View File

@@ -0,0 +1,426 @@
// Cau noi toi IMU WT61PC noi THANG vao UART (cap USB-FTDI), khong qua ESP32.
//
// Chon bang `mcu.protocol: wt61pc` trong sensors.yaml. CreateMcuBridge() trong
// mcu_bridge.cc chuyen sang day; cach cu (ESP32 + USB-CDC) van o do.
//
// ================== KHAC McuBridge O DAU ==================
//
// 1. KHONG CO ClockSync.
// ESP32 dong dau bang micros() cua chinh no roi ClockSync anh xa sang dong
// 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. 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;
// sau khi doi sang UART thang PHAI do lai (log `wheel_odom/lag`).
//
// 2. PHAT NGAY KHI CO KHUNG GYRO, khong doi khung Angle.
// Mot chu ky la Acc -> Gyro -> Angle. Doi Angle them ~11.5 ms o 9600 baud,
// ma khong ai doc imu.orientation trong libs/ va app/ (firmware ESP32 cung
// lam vay, xem firmware/imu_uart/main/main.c). Gyro khong co Acc di truoc
// trong cung chu ky thi bo mau, khong ghep voi gia toc cu.
//
// 3. DOC QUYEN CONG (TIOCEXCL).
// Hai chuong trinh cung doc mot tty thi chia nhau luong byte: da gap tren
// robot nay khi imu_ros_node cua motor_control doc chung cong, IMU chi con
// mot nua so mau (chu ky 0.2 s thay vi 0.1 s) va khong bao loi nao. Co
// TIOCEXCL thi chuong trinh thu hai (khong phai root) mo cong se loi EBUSY
// ngay. Luu y: neu chuong trinh kia mo TRUOC thi khong chan duoc -- Open()
// van thanh cong; kiem bang `sudo fuser -v /dev/imu`.
//
// 4. KHONG IM LANG.
// Khong co khung hop le nao trong `no_data_warn_sec` -> WARN kem goi y. Cap
// bi rut -> read() loi, driver tu mo lai moi giay thay vi ket vinh vien.
//
// 5. KHONG CO BARO / SIEU AM / BUMPER. Ba callback do khong bao gio duoc goi,
// giong mcu_bridge.cc muc 3.
#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>
#include <thread>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/log.h"
#include "vslam/wt61pc_protocol.h"
namespace vslam {
namespace {
speed_t BaudConstant(uint32_t 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;
case 460800: return B460800;
case 921600: return B921600;
default: return 0;
}
}
// 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)
: cfg_(cfg), clock_(std::move(clock)) {}
~Wt61pcBridge() override { Close(); }
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
// WT61PC chi co IMU. Dac biet bumper: lop safety coi mat bumper la mot duong
// doc lap, o day no khong ton tai.
void SetBaroCallback(BaroCallback) override {}
void SetUltrasonicCallback(UltrasonicCallback) override {}
void SetBumperCallback(BumperCallback) override {}
StatusResponse Open() override {
if (running_) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"imu: da mo roi");
}
if (!clock_) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"imu: thieu clock");
}
if (BaudConstant(cfg_.baud) == 0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"imu: baud " + std::to_string(cfg_.baud) + " khong ho tro");
}
byte_s_ = 10.0 / static_cast<double>(cfg_.baud); // 1 start + 8 data + 1 stop
const StatusResponse st = OpenPort();
if (!st.ok()) return st;
VSLAM_INFO("imu: WT61PC o " << cfg_.port << " @" << cfg_.baud
<< ", 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 "
"trong sensors.yaml.");
}
last_frame_ = std::chrono::steady_clock::now();
running_ = true;
thread_ = std::thread([this] { ReadLoop(); });
return StatusResponse::Ok();
}
void Close() override {
running_ = false;
// read() tra ve sau nhieu nhat 0.1 s (VTIME) nen join nhanh; dong fd SAU
// khi luong doc da thoat, khong dong duoi chan no.
if (thread_.joinable()) thread_.join();
CloseFd();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(stats_mu_);
return stats_;
}
private:
StatusResponse OpenPort() {
const int fd = ::open(cfg_.port.c_str(), O_RDWR | O_NOCTTY);
if (fd < 0) {
const int e = errno;
std::string hint;
if (e == EACCES) {
hint = " -- thieu quyen? kiem luat udev (MODE/GROUP) hoac them user vao "
"nhom dialout";
} else if (e == ENOENT) {
hint = " -- khong thay thiet bi: cap USB-UART da cam chua? luat udev "
"da cai chua (ls -l " + cfg_.port + ")?";
} else if (e == EBUSY) {
hint = " -- co chuong trinh khac dang giu cong (imu_ros_node cua "
"motor_control?): sudo fuser -v " + cfg_.port;
}
return StatusResponse::Error(
StatusCode::kUnavailable,
"imu: mo " + cfg_.port + " that bai: " + std::strerror(e) + hint);
}
termios tty{};
if (::tcgetattr(fd, &tty) != 0) {
const std::string err = std::strerror(errno);
::close(fd);
return StatusResponse::Error(StatusCode::kInternal,
"imu: tcgetattr that bai: " + err);
}
const speed_t speed = BaudConstant(cfg_.baud);
::cfsetospeed(&tty, speed);
::cfsetispeed(&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8 bit
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~(PARENB | PARODD); // khong parity
tty.c_cflag &= ~CSTOPB; // 1 stop bit
tty.c_cflag &= ~CRTSCTS; // khong flow control
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL);
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tty.c_oflag &= ~OPOST;
// VMIN=0 + VTIME=1: read() tra ve ngay khi co byte, hoac sau 0.1 s neu khong
// co. Du ngan de Close() va bo dem im lang chay deu.
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 1;
if (::tcsetattr(fd, TCSANOW, &tty) != 0) {
const std::string err = std::strerror(errno);
::close(fd);
return StatusResponse::Error(StatusCode::kInternal,
"imu: tcsetattr that bai: " + err);
}
if (::ioctl(fd, TIOCEXCL) != 0) {
VSLAM_WARN("imu: khong khoa duoc quyen doc cong " << cfg_.port << " ("
<< 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();
}
void CloseFd() {
const int fd = fd_.exchange(-1);
if (fd >= 0) ::close(fd);
}
void ReadLoop() {
uint8_t buf[512];
Wt61pcFrame frame;
while (running_) {
const ssize_t n = ::read(fd_, buf, sizeof(buf));
const UnixTime t_read = clock_->Now(); // ngay sau khi read() tra ve
if (n < 0) {
if (!running_) break;
if (errno == EAGAIN || errno == EINTR) continue;
Fail(std::string("read() that bai: ") + std::strerror(errno) +
" -- cap bi rut? driver thu mo lai moi giay");
Reopen();
continue;
}
if (n > 0) {
bytes_ += static_cast<uint64_t>(n);
for (ssize_t i = 0; i < n; ++i) {
if (!parser_.Push(buf[i], &frame)) continue;
// Byte cuoi cua khung la byte thu i. (n - 1 - i) byte da toi SAU no
// trong cung lan doc, nen khung that ra som hon luc read() mot chut.
const UnixTime t_end =
t_read - Duration::fromSec(static_cast<double>(n - 1 - i) * byte_s_);
OnFrame(frame, t_end);
}
}
CheckSilence();
}
}
void OnFrame(const Wt61pcFrame& f, UnixTime t_end) {
last_frame_ = std::chrono::steady_clock::now();
switch (f.type) {
case Wt61pcType::kAccel:
ax_ = f.x; ay_ = f.y; az_ = f.z;
have_acc_ = true;
return;
case Wt61pcType::kAngle:
return; // khong dung, xem dau file muc 2
case Wt61pcType::kGyro:
break;
}
if (!have_acc_) {
++incomplete_; // mat khung gia toc cua chu ky nay
return;
}
have_acc_ = false;
Publish(f, t_end - Duration::fromSec(cfg_.imu_lag_sec));
}
void Publish(const Wt61pcFrame& gyro, UnixTime stamp) {
// Gom byte cua cap USB-FTDI co the khien thoi diem suy nguoc cua mot khung
// som hon khung truoc vai ms. Dau thoi gian khong duoc lui: wheel_odom chi
// chiu duoc lech thu tu nho.
if (have_pub_ && stamp < last_stamp_) {
stamp = last_stamp_;
++clamped_;
}
auto imu = std::make_shared<Imu>();
imu->header.seq = seq_++;
imu->header.stamp = stamp;
imu->header.frame_id = cfg_.imu_frame_id;
imu->angular_velocity.x = gyro.x;
imu->angular_velocity.y = gyro.y;
imu->angular_velocity.z = gyro.z;
imu->linear_acceleration.x = ax_;
imu->linear_acceleration.y = ay_;
imu->linear_acceleration.z = az_;
// Khong mang orientation (khung Angle khong duoc dung). [0] < 0 la quy uoc
// "khong co orientation", giong record_format.cc va sim_source.cc.
imu->orientation_covariance[0] = -1.0;
for (int i = 0; i < 3; ++i) {
imu->angular_velocity_covariance[i * 4] = cfg_.gyro_variance;
imu->linear_acceleration_covariance[i * 4] = cfg_.accel_variance;
}
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.frames;
stats_.connected = true;
if (have_pub_) {
const double dt = (stamp - last_stamp_).toSec();
if (dt > 0.0) stats_.hz = 1.0 / dt;
}
// Khong co MCU de so dong ho -> hai so nay luon 0.
stats_.stamp_skew_ms = 0.0;
stats_.clock_skew_ppm = 0.0;
}
last_stamp_ = stamp;
have_pub_ = true;
if (imu_cb_) imu_cb_(imu);
}
// Goi sau moi lan read(), ke ca khi het thoi gian cho (n == 0).
void CheckSilence() {
const double quiet = std::chrono::duration<double>(
std::chrono::steady_clock::now() - last_frame_).count();
if (quiet < cfg_.no_data_warn_sec) return;
const std::string msg =
"khong co khung WT61PC hop le nao trong " + std::to_string(quiet) +
" s (nhan " + std::to_string(bytes_) + " byte, checksum sai " +
std::to_string(parser_.bad_checksum()) + ", byte bo " +
std::to_string(parser_.skipped_bytes()) + "). Kiem: day TX cua cam "
"bien -> RX cua cap USB-UART co long khong; cam bien co dang o baud "
"khac " + std::to_string(cfg_.baud) + " (co byte ma checksum sai "
"nhieu thi gan chac la sai baud); chuong trinh khac dang doc cong "
"(sudo fuser -v " + cfg_.port + ").";
{
std::lock_guard<std::mutex> lk(stats_mu_);
stats_.connected = false;
stats_.last_error = msg;
}
VSLAM_WARN_THROTTLE(5.0, "imu: " << msg);
}
void Fail(const std::string& msg) {
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.errors;
stats_.connected = false;
stats_.last_error = msg;
}
VSLAM_WARN_THROTTLE(5.0, "imu: " << msg);
}
// Cap bi rut roi cam lai: read() loi mai mai neu khong mo lai. Mo lai moi
// giay cho toi khi duoc hoac Close().
void Reopen() {
CloseFd();
parser_.Reset();
have_acc_ = false;
while (running_) {
for (int i = 0; i < 10 && running_; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (!running_) return;
const StatusResponse st = OpenPort();
if (st.ok()) {
VSLAM_INFO("imu: mo lai " << cfg_.port << " thanh cong");
last_frame_ = std::chrono::steady_clock::now();
return;
}
VSLAM_WARN_THROTTLE(5.0, st.message);
}
}
McuConfig cfg_;
ClockPtr clock_;
ImuCallback imu_cb_;
std::atomic<int> fd_{-1};
std::atomic<bool> running_{false};
std::thread thread_;
// Chi cham tu luong doc.
Wt61pcParser parser_;
double byte_s_ = 0.0;
uint64_t bytes_ = 0;
double ax_ = 0.0, ay_ = 0.0, az_ = 0.0;
bool have_acc_ = false;
uint64_t incomplete_ = 0; // gyro khong co acc di truoc trong chu ky
uint64_t clamped_ = 0; // stamp bi keo len de khong lui
uint32_t seq_ = 0;
UnixTime last_stamp_;
bool have_pub_ = false;
std::chrono::steady_clock::time_point last_frame_;
mutable std::mutex stats_mu_;
DriverStats stats_;
};
} // namespace
std::unique_ptr<McuInterface> CreateWt61pcBridge(const McuConfig& cfg,
ClockPtr clock) {
return std::make_unique<Wt61pcBridge>(cfg, std::move(clock));
}
} // namespace vslam

View File

@@ -0,0 +1,100 @@
#include "vslam/wt61pc_protocol.h"
#include <cmath>
namespace vslam {
namespace {
constexpr double kWt61pcG = 9.80665;
constexpr double kDeg2Rad = M_PI / 180.0;
// Loai khung cua dong WitMotion nam trong 0x50..0x5A. 0x55 bi loai ra: no
// trung voi byte dau khung, nen "0x55 0x55" nghia la byte truoc la rac va byte
// nay moi la dau khung that.
bool IsFrameType(uint8_t b) {
return b >= 0x50 && b <= 0x5A && b != kWt61pcHeader;
}
double Int16LE(const uint8_t* p) {
return static_cast<double>(
static_cast<int16_t>(static_cast<uint16_t>(p[1]) << 8 | p[0]));
}
} // namespace
void Wt61pcParser::Reset() {
n_ = 0;
}
bool Wt61pcParser::Push(uint8_t byte, Wt61pcFrame* out) {
if (n_ == 0) {
if (byte == kWt61pcHeader) {
buf_[n_++] = byte;
} else {
++skipped_bytes_;
}
return false;
}
if (n_ == 1) {
if (IsFrameType(byte)) {
buf_[n_++] = byte;
} else {
++skipped_bytes_;
if (byte != kWt61pcHeader) n_ = 0; // 0x55 0x55: giu lai, byte nay la dau khung
}
return false;
}
buf_[n_++] = byte;
if (n_ < kWt61pcFrameBytes) return false;
uint8_t sum = 0;
for (size_t i = 0; i + 1 < kWt61pcFrameBytes; ++i) {
sum = static_cast<uint8_t>(sum + buf_[i]);
}
if (sum != buf_[kWt61pcFrameBytes - 1]) {
++bad_checksum_;
Resync();
return false;
}
const uint8_t type = buf_[1];
n_ = 0;
if (type != static_cast<uint8_t>(Wt61pcType::kAccel) &&
type != static_cast<uint8_t>(Wt61pcType::kGyro) &&
type != static_cast<uint8_t>(Wt61pcType::kAngle)) {
++other_frames_;
return false;
}
out->type = static_cast<Wt61pcType>(type);
double scale = 0.0;
switch (out->type) {
case Wt61pcType::kAccel: scale = 16.0 * kWt61pcG / 32768.0; break;
case Wt61pcType::kGyro: scale = 2000.0 * kDeg2Rad / 32768.0; break;
case Wt61pcType::kAngle: scale = 180.0 * kDeg2Rad / 32768.0; break;
}
out->x = Int16LE(buf_ + 2) * scale;
out->y = Int16LE(buf_ + 4) * scale;
out->z = Int16LE(buf_ + 6) * scale;
return true;
}
// Checksum sai co the la mat dong bo: dau khung that nam NGAY TRONG 10 byte sau
// dau gia. Bo ca 11 byte se nuot luon khung dung ngay sau, va o 10 Hz do la
// mat ca mot mau. Nen truot toi 0x55 ke tiep va nap lai phan con lai.
void Wt61pcParser::Resync() {
uint8_t keep[kWt61pcFrameBytes];
size_t m = 0;
size_t j = 1;
while (j < kWt61pcFrameBytes && buf_[j] != kWt61pcHeader) ++j;
skipped_bytes_ += j;
for (; j < kWt61pcFrameBytes; ++j) keep[m++] = buf_[j];
n_ = 0;
// Toi da 10 byte nen khong the ra mot khung moi (can 11), cung khong de quy
// vao Resync lan nua.
Wt61pcFrame unused;
for (size_t i = 0; i < m; ++i) Push(keep[i], &unused);
}
} // namespace vslam

View File

@@ -273,6 +273,12 @@ void ZlacMotorDriver::telemetryLoop() {
pdo_mapped_ = true; pdo_mapped_ = true;
} catch (...) { } catch (...) {
// Fallback to SDO synchronous read if PDO is not mapped yet // Fallback to SDO synchronous read if PDO is not mapped yet
//
// [vslam] try rieng, nhu 0x6064 ben duoi: nem tu trong catch ->
// std::terminate. Da xay ra GIUA phien chay 2026-09-28 khi bus CAN
// nghen ("49 write errors"): SdoError("SubmitRead:01:606C:01:
// Resource not available: SDO connection") va node abort.
try {
auto left_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 1); auto left_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 1);
auto right_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 2); auto right_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 2);
@@ -281,6 +287,9 @@ void ZlacMotorDriver::telemetryLoop() {
cached_right_vel_raw_ = right_opt.value(); cached_right_vel_raw_ = right_opt.value();
cached_vel_valid_ = true; cached_vel_valid_ = true;
} }
} catch (...) {
// Mat mot mau van toc; 20 ms sau doc lai.
}
} }
} }

View File

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

View File

@@ -0,0 +1,87 @@
#ifndef VSLAM_GYRO_YAW_FUSER_H
#define VSLAM_GYRO_YAW_FUSER_H
// Goc quay (yaw) cho EKF: GYRO giu TONG, encoder chi lap khoang gyro chua ve.
//
// ================== VI SAO ==================
// Cach cu tich gyro THEO LUC MAU TOI giua hai buoc encoder, roi chi nhan khi do
// dai cua so gyro nam trong 0.5-1.5 lan buoc encoder, ngoai do thi VUT. Tren
// robot that mau IMU toi THEO CUM (log 07/10: cua so 40 ms = 8 mau, buoc
// encoder 22.5 ms): cua so ngan (thieu) duoc nhan, cua so dai (mang phan bu)
// bi vut -> goc DEM THIEU mot chieu. Do tren ban do real_20261007_112455: ICP
// phai cong them 9.9% moi goc quay (ban do 28/09 va 01/10 dung encoder: 0% va
// -1.8%), trong khi chinh gyro van khop encoder 0.99 luc quay. Sim khong lo vi
// IMU va encoder toi deu.
//
// ================== CACH LAM ==================
// Goc tai buoc encoder t:
// Y(t) = Theta_gyro(b) + [theta_enc(t) - theta_enc(b)]
// b = dau thoi gian mau gyro MOI NHAT (da bu tre). Moi buoc tra ve
// Y(t_i) - Y(t_{i-1}): tong cong don lai triet tieu, nen ve lau dai goc theo
// DUNG gyro (khong mau nao bi vut), con khoang (b, t] -- vai chuc ms gyro chua
// toi -- lay tu encoder nen khong tre. Truot banh lam encoder sai trong khoang
// do thi buoc sau, khi gyro toi, phan lech duoc tra lai.
//
// IMU cham (chu ky > max_gyro_period, vd WT61PC 10 Hz) hoac het tuoi thi chi
// dung encoder -- nhu truoc 06/10. Gyro dut quang (khe > max_gap) thi dat lai
// moc, khong bu qua khe.
#include <deque>
#include "vslam/unix_time.h"
namespace vslam {
struct GyroYawFuserConfig {
double max_gyro_period = 0.03; // s; IMU cham hon -> chi encoder
double stale_sec = 0.2; // s; khong co mau gyro moi -> chi encoder
double max_gap = 0.1; // s; hai mau gyro cach hon -> khong tich phan qua khe
double enc_history_sec = 2.0; // s; lich su goc encoder de noi suy tai moc gyro
};
class GyroYawFuser {
public:
explicit GyroYawFuser(GyroYawFuserConfig cfg = GyroYawFuserConfig());
// Mot mau gyro z (rad/s), dau thoi gian DA bu tre IMU. Goi theo thu tu toi.
void AddGyro(UnixTime t, double wz);
// Mot buoc encoder ket thuc tai `t` voi goc encoder `d_theta_enc` (rad).
// `*d_theta` = goc da ghep cho buoc nay. Tra true neu co dung gyro.
bool Step(UnixTime t, double d_theta_enc, double* d_theta);
void Reset();
// Chu ky gyro uoc luong (s), 0 neu chua biet. De log.
double gyro_period() const { return period_; }
private:
struct EncSample {
UnixTime t;
double theta;
};
bool EncThetaAt(UnixTime t, double* out) const;
GyroYawFuserConfig cfg_;
// Gyro: goc tich luy (hinh thang) toi mau moi nhat.
bool have_g_ = false;
UnixTime g_t_;
double g_w_ = 0.0;
double g_theta_ = 0.0;
double period_ = 0.0;
// Encoder: goc tich luy theo thoi gian.
std::deque<EncSample> enc_;
double enc_theta_ = 0.0;
// Moc cua buoc truoc: thoi gian b, goc gyro va goc encoder tai b.
bool anchored_ = false;
UnixTime b_;
double g_at_b_ = 0.0;
double e_at_b_ = 0.0;
};
} // namespace vslam
#endif // VSLAM_GYRO_YAW_FUSER_H

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,106 @@
#include "vslam/gyro_yaw_fuser.h"
#include <algorithm>
namespace vslam {
GyroYawFuser::GyroYawFuser(GyroYawFuserConfig cfg) : cfg_(cfg) {}
void GyroYawFuser::Reset() {
have_g_ = false;
g_w_ = 0.0;
g_theta_ = 0.0;
period_ = 0.0;
enc_.clear();
enc_theta_ = 0.0;
anchored_ = false;
}
void GyroYawFuser::AddGyro(UnixTime t, double wz) {
if (!have_g_) {
have_g_ = true;
g_t_ = t;
g_w_ = wz;
return;
}
const double dt = SecondsBetween(t, g_t_);
if (dt <= 0.0) {
// Dau thoi gian bang mau truoc (driver kep cho khong lui): khong co khoang
// nao de tich, mau sau se phu khoang nay. Giu toc do moi nhat.
g_w_ = wz;
return;
}
if (dt < cfg_.max_gap) {
g_theta_ += 0.5 * (g_w_ + wz) * dt;
period_ = period_ > 0.0 ? 0.9 * period_ + 0.1 * dt : dt;
} else {
// Dut quang: goc gyro khong biet trong khe -- dat lai moc, khong bu qua khe.
anchored_ = false;
}
g_t_ = t;
g_w_ = wz;
}
bool GyroYawFuser::EncThetaAt(UnixTime t, double* out) const {
if (enc_.empty()) return false;
if (SecondsBetween(t, enc_.back().t) >= 0.0) {
if (SecondsBetween(t, enc_.back().t) > 0.0) return false; // sau buoc moi nhat
*out = enc_.back().theta;
return true;
}
for (size_t k = enc_.size() - 1; k > 0; --k) {
const EncSample& hi = enc_[k];
const EncSample& lo = enc_[k - 1];
if (SecondsBetween(t, lo.t) < 0.0) continue;
const double span = SecondsBetween(hi.t, lo.t);
*out = span > 0.0 ? lo.theta + (hi.theta - lo.theta) * SecondsBetween(t, lo.t) / span
: hi.theta;
return true;
}
return false; // truoc mau encoder cu nhat
}
bool GyroYawFuser::Step(UnixTime t, double d_theta_enc, double* d_theta) {
*d_theta = d_theta_enc;
if (!enc_.empty() && SecondsBetween(t, enc_.back().t) <= 0.0) {
// Thoi gian encoder lui (reset mo phong, phat lai): bat dau lai.
Reset();
}
enc_theta_ += d_theta_enc;
enc_.push_back(EncSample{t, enc_theta_});
while (enc_.size() > 2 && SecondsBetween(t, enc_.front().t) > cfg_.enc_history_sec) {
enc_.pop_front();
}
const bool usable = have_g_ && period_ > 0.0 && period_ <= cfg_.max_gyro_period &&
SecondsBetween(t, g_t_) < cfg_.stale_sec;
if (!usable) {
anchored_ = false;
return false;
}
// Moc moi: mau gyro moi nhat, khong vuot buoc encoder nay.
const UnixTime b = SecondsBetween(g_t_, t) > 0.0 ? t : g_t_;
double e_b = 0.0;
if (!EncThetaAt(b, &e_b)) {
anchored_ = false;
return false;
}
// Gyro toi tre hon buoc encoder thi g_theta_ la goc tai g_t_; b = t chi khi
// gyro di truoc (it gap) -- khi do goc gyro tai t lay bang mau moi nhat.
if (!anchored_ || SecondsBetween(b, b_) < 0.0) {
anchored_ = true;
b_ = b;
g_at_b_ = g_theta_;
e_at_b_ = e_b;
return false;
}
// Goc tren khoang moc [b_, b]: gyro thay encoder.
const double corr = (g_theta_ - g_at_b_) - (e_b - e_at_b_);
*d_theta = d_theta_enc + corr;
b_ = b;
g_at_b_ = g_theta_;
e_at_b_ = e_b;
return true;
}
} // namespace vslam

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

View File

@@ -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,160 @@
#include "vslam/scan_leveler.h"
#include <cmath>
#include <limits>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
namespace vslam {
namespace {
// Chi so tia cua goc `a` (rad) BAT KE quy uoc goc cua scan: LakiBeam that phat
// [0, 2pi) (angle_min = 0, lidar_core scan_conversion.cpp), sim va test phat
// [-pi, pi). Lay hieu goc THEO VONG TRON roi moi chia; -1 = ngoai FOV.
//
// Truoc day NormalizeAngle(a) ve [-pi, pi) roi tru angle_min = 0: moi tia nua
// -pi..0 ra chi so AM va bi BO, khong log nao bao. Ban do robot that tu 06/10
// (doc BAT mac dinh) chi con nua scan (0..+120 do), 325 diem / scan thay vi
// 620-730 (28/09, 01/10) -- sim khong thay vi scan sim la [-135, 135] do.
long RayIndex(double a, double angle_min, double inc, size_t n) {
const double two_pi = 2.0 * M_PI;
double rel = std::fmod(a - angle_min, two_pi);
if (rel * inc < 0.0) rel += std::copysign(two_pi, inc); // cung chieu quet
long j = std::lround(rel / inc);
// Goc ~2pi: tia dau (scan tron vong) hoac ngay truoc angle_min.
if (j >= static_cast<long>(n)) j -= std::lround(two_pi / std::fabs(inc));
return (j >= 0 && j < static_cast<long>(n)) ? j : -1;
}
} // namespace
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 long j = RayIndex(std::atan2(dy, dx) - laser_yaw, in.angle_min, in.angle_increment, n);
if (j < 0 || 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++;
}
}
void DeskewScan(const LaserScan& in, const Transform& laser_to_base, const SweepTiming& tm,
double w, double v, LaserScan* out) {
*out = in;
const size_t n = in.ranges.size();
if (n == 0 || in.angle_increment == 0.0f || !(tm.period_s > 0.0)) return;
const float nan = std::numeric_limits<float>::quiet_NaN();
out->ranges.assign(n, nan);
if (!out->intensities.empty()) out->intensities.assign(n, 0.0f);
// Tia KHONG huu han va sentinel cua sector mask giu nguyen o cu (nhu LevelScan).
std::vector<char> masked(n, 0);
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (std::isnan(r)) continue;
if (std::isinf(r)) {
out->ranges[i] = r;
} else if (r > in.range_max) {
out->ranges[i] = r;
masked[i] = 1;
}
}
const Transform laser_from_base = TransformInverse(laser_to_base);
const double two_pi = 2.0 * M_PI;
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (!std::isfinite(r) || r > in.range_max) continue;
const double a = in.angle_min + static_cast<double>(i) * in.angle_increment;
// Phan vong DA quet truoc tia nay -> tia chup truoc stamp `lag` giay.
double f = std::fmod(tm.dir > 0 ? a - tm.start_rad : tm.start_rad - a, two_pi);
if (f < 0.0) f += two_pi;
const double lag = tm.period_s * (1.0 - f / two_pi);
const double dth = w * lag, dx = v * lag;
// Diem trong khung base LUC CHUP -> khung base LUC STAMP: robot da tien dx
// roi quay dth, nen diem tinh lui dx va xoay -dth.
const Point pb = TransformPoint(laser_to_base, Point{r * std::cos(a), r * std::sin(a), 0.0});
const double c = std::cos(dth), s = std::sin(dth);
const double qx = pb.x - dx, qy = pb.y;
const Point pl = TransformPoint(laser_from_base, Point{c * qx + s * qy, -s * qx + c * qy, pb.z});
const long j = RayIndex(std::atan2(pl.y, pl.x), in.angle_min, in.angle_increment, n);
if (j < 0 || masked[static_cast<size_t>(j)]) continue;
const double rr = std::hypot(pl.x, pl.y);
float& slot = out->ranges[static_cast<size_t>(j)];
if (!std::isfinite(slot) || rr < slot) {
slot = static_cast<float>(rr);
if (!out->intensities.empty() && i < in.intensities.size()) {
out->intensities[static_cast<size_t>(j)] = in.intensities[i];
}
}
}
}
} // namespace vslam

View File

@@ -210,7 +210,15 @@ SafetyOutput SafetyMonitor::Step(const SafetyInputs& in) {
if (out.us_min < cfg_.us_stop_distance) { if (out.us_min < cfg_.us_stop_distance) {
VSLAM_WARN_THROTTLE(1.0, "safety: sieu am " << out.us_min << " m (< " VSLAM_WARN_THROTTLE(1.0, "safety: sieu am " << out.us_min << " m (< "
<< cfg_.us_stop_distance << cfg_.us_stop_distance
<< ") -- co the la KINH. Dung."); << ") -- co the la KINH. Chan tien/lui, "
"xoay tai cho de thoat.");
// Chan TINH TIEN (robot that chi co ten us0..usN, khong biet huong tung
// dau do) nhung GIU angular: xoay tai cho khong dua than robot lai gan vat.
// Chan ca xoay la be tac -- mo phong 2026-09-28: sieu am 0.31 m < 0.40,
// robot dung im, khong lenh nao ra duoc.
out.cmd = Twist{};
out.cmd.angular.z = std::max(-cfg_.max_angular,
std::min(cfg_.max_angular, in.cmd->angular.z));
return finish(SafetyState::kUsBlocked, "sieu am chan -- co the la kinh"); return finish(SafetyState::kUsBlocked, "sieu am chan -- co the la kinh");
} }

View File

@@ -9,6 +9,7 @@ find_package(yaml-cpp REQUIRED)
vslam_add_library(vslam_sim vslam_add_library(vslam_sim
PUBLIC_HDRS PUBLIC_HDRS
sim_source.h sim_source.h
sim_camera_renderer.h
occupancy_map_io.h occupancy_map_io.h
gazebo_world.h gazebo_world.h
PUBLIC_DEPS 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 // `CGMClassic` mot minh ra bao loi 239 x 111 m, va ca the gioi phinh tu
// 25x51 m len 263x146 m. // 25x51 m len 263x146 m.
double sx = 1.0, sy = 1.0, sz = 1.0; 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 { struct GazeboWorld {
std::string world_path; std::string world_path;
std::vector<WorldModel> models; 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. // 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 // Chi lay tam giac nam trong dai do cao [z_min, z_max] tinh tu MAT SAN CUC BO
// ma LiDAR 2D thuc su quet. Lay het moi do cao se bien ca mat san thanh vat // cua tung o: do la dai ma LiDAR 2D thuc su quet. Lay het moi do cao se bien
// can, va lay qua cao se bo lot ban ghe. // 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. // `resolution` met/o. `pad` la vien trong them quanh bao loi, tinh bang met.
struct WorldRasterOptions { struct WorldRasterOptions {
@@ -92,10 +105,28 @@ struct WorldRasterOptions {
double pad = 1.0; 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, StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
OccupancyGrid* out); 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 // 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 // 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, // cham don gian hoa khac han mesh hien thi (do duoc: PatientWheelChair,
// nursesstation_01), va Gazebo cung hanh xu y het. // 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, StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
const OccupancyGrid& grid, const OccupancyGrid& grid,
WorldSegments* out); WorldSegments* out,
const std::vector<float>* floor_z = nullptr);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Xuat hinh hoc cho khung 3D // 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 // co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va
// toan bo duong ong du lieu. // toan bo duong ong du lieu.
#include <functional>
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
#include "vslam/clock.h" #include "vslam/clock.h"
#include "vslam/gazebo_world.h" #include "vslam/gazebo_world.h"
#include "vslam/sim_camera_renderer.h"
#include "vslam/driver_interfaces.h" #include "vslam/driver_interfaces.h"
#include "vslam/vslam_common.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". // 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 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 imu_rate_hz = 200.0;
double gyro_noise_stddev = 4.9e-4; double gyro_noise_stddev = 4.9e-4;
double accel_noise_stddev = 6.9e-3; 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 ================== // ================== NGHIENG THAN ROBOT ==================
// Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG, // 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 // 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; bool follow_terrain_slope = true;
double wheelbase_for_slope = 0.44; // khoang cach truoc-sau de do doc 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; double encoder_rate_hz = 50.0;
// ================== HAI LOAI TRUOT, RAT KHAC NHAU ================== // ================== HAI LOAI TRUOT, RAT KHAC NHAU ==================
@@ -251,6 +303,23 @@ struct SimConfig {
double speed = 1.0; 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. // So huu ca bon nguon, y het ReplaySource.
class SimSource { class SimSource {
public: public:
@@ -281,6 +350,29 @@ class SimSource {
// z am = bac hut xuong / cau thang di xuong. // z am = bac hut xuong / cau thang di xuong.
void SetFloorHeight(double x0, double y0, double x1, double y1, float z); 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. // 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 // 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; } if (uri.empty()) { skip++; continue; }
m.model_name = uri.substr(uri.rfind('/') + 1); m.model_name = uri.substr(uri.rfind('/') + 1);
m.terrain = m.model_name.rfind(kTerrainModelPrefix, 0) == 0;
std::string root; std::string root;
const std::string dir = ResolveModelUri(uri, roots, &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, StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
OccupancyGrid* out) { 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)) { if (!(opt.resolution > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument, return StatusResponse::Error(StatusCode::kInvalidArgument,
"resolution phai duong"); "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. // o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM.
out->data.assign(static_cast<size_t>(w) * h, 0); 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; size_t n_used = 0;
for (const Loaded& L : loaded) { for (const Loaded& L : loaded) {
if (L.m->terrain) continue; // dia hinh la san, khong phai vat can
for (const Tri& t : L.tris) { for (const Tri& t : L.tris) {
// Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua: // 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. // 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 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]}); 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++; n_used++;
// Bao loi cua tam giac, roi kiem tung o bang toa do trong tam. // 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; inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9;
} }
if (inside) { 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 << minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri
<< " tam giac (" << n_used << " trong dai z [" << " tam giac (" << n_used << " trong dai z ["
<< opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem"); << 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(); return StatusResponse::Ok();
} }
@@ -742,7 +822,8 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
StatusResponse BuildWorldSegments(const GazeboWorld& world, StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
const OccupancyGrid& grid, const OccupancyGrid& grid,
WorldSegments* out) { WorldSegments* out,
const std::vector<float>* floor_z) {
if (out == nullptr) { if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null"); 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 double ox = out->origin_x, oy = out->origin_y;
const int W = static_cast<int>(grid.width), H = static_cast<int>(grid.height); 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 --- // --- 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 // 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; std::map<std::string, std::vector<Tri>> cache;
for (const WorldModel& m : world.models) { for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue; 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); auto it = cache.find(m.model_name);
if (it == cache.end()) { if (it == cache.end()) {
std::vector<Tri> tris; 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 zlo = std::min({Z[0], Z[1], Z[2]});
const double zhi = std::max({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) { for (int e = 0; e < 3; ++e) {
const int a = e, b = (e + 1) % 3; const int a = e, b = (e + 1) % 3;
out->seg.push_back(static_cast<float>(X[a])); out->seg.push_back(static_cast<float>(X[a]));

View File

@@ -1,21 +1,54 @@
#include "vslam/sim_source.h" #include "vslam/sim_source.h"
#include <algorithm>
#include <atomic> #include <atomic>
#include <cmath> #include <cmath>
#include <deque>
#include <functional>
#include <mutex> #include <mutex>
#include <random> #include <random>
#include <thread> #include <thread>
#include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/log.h" #include "vslam/log.h"
#include "vslam/node_constants.h" #include "vslam/node_constants.h"
#include "vslam/occupancy_map_io.h" #include "vslam/occupancy_map_io.h"
#include "vslam/robot_model.h"
#include <limits> #include <limits>
namespace vslam { namespace vslam {
namespace { 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 // Bon lop nay la interface driver THAT, y het ReplaySource. vslam_node khong
// phan biet duoc phan cung / file .vsr / mo phong. // 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; double us_acc = 0.0, bump_acc = 0.0;
bool bumper_now = false; bool bumper_now = false;
// Bo dem anh depth, cap phat mot lan. Anh khong so huu bo nho (xem // Bo dem anh depth. Anh khong so huu bo nho (xem vslam_common.h), nen MOI
// vslam_common.h), nen bo dem nay phai song it nhat bang khung anh. // khung lay mot bo dem rieng tu pool va giu no qua keep_alive -- SlamLoop
std::vector<uint8_t> depth_buf; // giu khung moi nhat qua Rtabmap::process tren luong khac, va mot bo dem
uint32_t depth_w = 0, depth_h = 0; // 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; std::shared_ptr<ReplayClock> clock;
// Trang thai that cua robot. // 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 terrain_pitch = 0.0; // nghieng do DIA HINH, cong vao than
double last_accel = 0.0; 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}; std::atomic<bool> stop{false};
mutable std::mutex state_mu; mutable std::mutex state_mu;
Stats stats; Stats stats;
@@ -354,6 +428,82 @@ struct SimSource::Impl {
return inf; 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. // Do cao san tai mot diem the gioi. Ngoai ban do coi nhu phang.
float FloorAt(double wx, double wy) const { float FloorAt(double wx, double wy) const {
const int cx = static_cast<int>( 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, // 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. // va no la ly do nhanh US_BLOCKED cua FSM ton tai.
if (map.data[idx] >= 50 && !(idx < glass.size() && glass[idx])) { 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) || 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)) { (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, // 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 // 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. // 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) { if (gap_enter > 0.0 && gap_exit <= 0.0) {
const double frac = gap_enter / (gap_enter - gap_exit); const double frac = gap_enter / (gap_enter - gap_exit);
return (t_enter + frac * (t_exit - t_enter)) * res; return (t_enter + frac * (t_exit - t_enter)) * res;
@@ -614,8 +780,10 @@ struct SimSource::Impl {
cy >= static_cast<int>(map.height)) { cy >= static_cast<int>(map.height)) {
return true; return true;
} }
return map.data[static_cast<size_t>(cy) * map.width + const size_t idx = static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx);
static_cast<size_t>(cx)] >= 50; 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. // Kiem va cham: lay 8 diem tren vanh robot.
@@ -649,11 +817,24 @@ struct SimSource::Impl {
prev_v = v; prev_v = v;
// Tich phan pose THAT. // Tich phan pose THAT.
const double nx = x + v * std::cos(yaw) * dt; double nx, ny, nyaw;
const double ny = y + v * std::sin(yaw) * dt; if (terrain_on) {
const double nyaw = NormalizeAngle(yaw + w * dt); // 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); std::lock_guard<std::mutex> lk(state_mu);
if (terrain_on && steps_dirty) RebuildStepMask();
if (Collides(nx, ny)) { if (Collides(nx, ny)) {
// Dung tai cho. Robot that se truot va quay, nhung "dung han" la mo // 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. // hinh trung thuc hon voi mot robot dich vu co bumper cat nguon.
@@ -690,7 +871,10 @@ struct SimSource::Impl {
roll += roll_rate * dt; roll += roll_rate * dt;
// Nghieng do DIA HINH: do chenh lech do cao san giua truoc va sau robot. // 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 half = cfg.wheelbase_for_slope / 2.0;
const double fz = FloorAt(x + half * std::cos(yaw), y + half * std::sin(yaw)); 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)); 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; 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) { LaserScanPtr MakeScan(UnixTime stamp) {
auto s = std::make_shared<LaserScan>(); auto s = std::make_shared<LaserScan>();
s->header.stamp = stamp; s->header.stamp = stamp;
@@ -742,6 +965,11 @@ struct SimSource::Impl {
s->range_max = static_cast<float>(cfg.lidar_range_max); s->range_max = static_cast<float>(cfg.lidar_range_max);
s->ranges.resize(cfg.lidar_samples); s->ranges.resize(cfg.lidar_samples);
if (terrain_on) {
FillScan3D(s.get());
return s;
}
double rx, ry, ryaw; double rx, ry, ryaw;
{ {
std::lock_guard<std::mutex> lk(state_mu); 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 w = cfg.depth_width / dec;
const uint32_t h = cfg.depth_height / dec; const uint32_t h = cfg.depth_height / dec;
if (depth_w != w || depth_h != h) { // 16UC1. Vong lap ben duoi ghi MOI diem anh, nen khong can xoa truoc.
depth_w = w; auto buf = depth_pool->Acquire();
depth_h = h; buf->resize(static_cast<size_t>(w) * h * 2);
depth_buf.assign(static_cast<size_t>(w) * h * 2, 0); // 16UC1 std::vector<uint8_t>& depth_buf = *buf;
}
double rx, ry, ryaw; double rx, ry, rz, ryaw;
{ {
std::lock_guard<std::mutex> lk(state_mu); std::lock_guard<std::mutex> lk(state_mu);
rx = x; rx = x;
ry = y; ry = y;
rz = ground_z;
ryaw = yaw; ryaw = yaw;
} }
// Vi tri camera trong the gioi. // Vi tri camera trong the gioi. Dia hinh 3D tinh lai ben duoi, theo tu the
const double cx_w = rx + cfg.camera_x * std::cos(ryaw); // 6-DoF cua than.
const double cy_w = ry + cfg.camera_x * std::sin(ryaw); double cx_w = rx + cfg.camera_x * std::cos(ryaw);
const double cz_w = cfg.camera_z; 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 // 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. // 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); std::lock_guard<std::mutex> lk(state_mu);
body_roll = roll; body_roll = roll;
body_pitch = pitch + terrain_pitch; body_pitch = pitch + terrain_pitch;
if (terrain_on) body_roll += terrain_roll;
} }
const double total_pitch = cfg.camera_pitch + body_pitch; const double total_pitch = cfg.camera_pitch + body_pitch;
const double cp = std::cos(total_pitch), sp = std::sin(total_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 cr_b = std::cos(body_roll), sr_b = std::sin(body_roll);
const double cy_r = std::cos(ryaw), sy_r = std::sin(ryaw); 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 // Khong dung mot `normal_distribution` chung: sigma phu thuoc KHOANG
// CACH cua tung diem anh, nen phan phoi duoc dung ngay trong vong lap. // CACH cua tung diem anh, nen phan phoi duoc dung ngay trong vong lap.
std::uniform_real_distribution<double> uni01(0.0, 1.0); std::uniform_real_distribution<double> uni01(0.0, 1.0);
@@ -828,20 +1125,16 @@ struct SimSource::Impl {
const double oz = 1.0; const double oz = 1.0;
const double inv = 1.0 / std::sqrt(ox * ox + oy * oy + oz * oz); 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, double d;
// +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo yaw. if (use_gl) {
const double bx0 = oz * inv, by0 = -ox * inv, bz0 = -oy * inv; // GPU tra thang Z-DEPTH; 0 = khong trung gi.
// Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch). const float zg = gl_depth[static_cast<size_t>(v) * w + u];
const double by1 = by0 * cr_b - bz0 * sr_b; d = zg > 0.0f ? static_cast<double>(zg) : std::numeric_limits<double>::infinity();
const double bz1 = by0 * sr_b + bz0 * cr_b; } else {
const double px = bx0 * cp + bz1 * sp; double wx, wy, pz;
const double pz = -bx0 * sp + bz1 * cp; to_world(oz * inv, -ox * inv, -oy * inv, &wx, &wy, &pz);
const double py = by1; d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far);
}
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);
uint16_t mm = 0; // 0 = khong do duoc, dung quy uoc cua RealSense 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 // 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, // 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 // 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. // 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. // Nhieu depth theo MO HINH STEREO, khong phai hang so.
// //
@@ -928,6 +1223,22 @@ struct SimSource::Impl {
img->format = PixelFormat::kMono16; img->format = PixelFormat::kMono16;
img->depth_scale = 0.001f; img->depth_scale = 0.001f;
img->data = depth_buf.data(); 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->header = img->header;
out->depth = img; out->depth = img;
@@ -966,6 +1277,14 @@ struct SimSource::Impl {
cur_rr = roll_rate; cur_rr = roll_rate;
cur_pr = pitch_rate; cur_pr = pitch_rate;
cur_accel = last_accel; 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. // 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]; m->linear_acceleration_covariance[8] = m->linear_acceleration_covariance[0];
return m; 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. // chuoi do phai giong nhau giua hai lan ghi cung mot kich ban.
impl_->rng.seed(impl_->cfg.seed); impl_->rng.seed(impl_->cfg.seed);
WorldTerrain terr;
if (!impl_->cfg.world_path.empty()) { if (!impl_->cfg.world_path.empty()) {
const StatusResponse st = LoadGazeboWorld( const StatusResponse st = LoadGazeboWorld(
impl_->cfg.world_path, impl_->cfg.world_model_paths, &impl_->world); impl_->cfg.world_path, impl_->cfg.world_model_paths, &impl_->world);
if (!st.ok()) return st; if (!st.ok()) return st;
WorldRasterOptions wo; 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; if (!rs.ok()) return rs;
// Chi muc doan 2D, de khoang cach tra ve trung MAT TUONG chu khong trung // 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 // bien o. Khong dung duoc thi van chay -- chi la moi tia dung som toi mot
// o, y nhu truoc day. // o, y nhu truoc day.
const StatusResponse ss = const StatusResponse ss = BuildWorldSegments(
BuildWorldSegments(impl_->world, wo, impl_->map, &impl_->segments); impl_->world, wo, impl_->map, &impl_->segments,
terr.terrain_cells > 0 ? &terr.floor_z : nullptr);
if (!ss.ok()) { if (!ss.ok()) {
VSLAM_WARN("sim: khong dung duoc chi muc doan (" << ss.message VSLAM_WARN("sim: khong dung duoc chi muc doan (" << ss.message
<< ") -- raycast se luong tu hoa theo o " << ") -- raycast se luong tu hoa theo o "
@@ -1048,13 +1533,63 @@ StatusResponse SimSource::Open() {
} }
// San phang mac dinh. SetFloorHeight() tao bac hut xuong. // 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); const size_t n_cells = static_cast<size_t>(impl_->map.width) * impl_->map.height;
impl_->glass.assign(static_cast<size_t>(impl_->map.width) * impl_->map.height, 0); 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_->x = impl_->cfg.start_x;
impl_->y = impl_->cfg.start_y; impl_->y = impl_->cfg.start_y;
impl_->yaw = impl_->cfg.start_yaw; 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)) { if (impl_->Collides(impl_->x, impl_->y)) {
// Bao NGAY thay vi de robot ket ngay tu khung dau tien va nguoi dung ngoi // Bao NGAY thay vi de robot ket ngay tu khung dau tien va nguoi dung ngoi
// doan tai sao no khong nhuc nhich. // doan tai sao no khong nhuc nhich.
@@ -1093,6 +1628,10 @@ void SimSource::SetMapForTest(const OccupancyGrid& m) {
impl_->map = m; impl_->map = m;
impl_->floor_z.assign(static_cast<size_t>(m.width) * m.height, 0.0f); 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_->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; } 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; 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 VSLAM_INFO("sim: dat do cao san " << z << " m cho vung (" << x0 << ", " << y0
<< ") - (" << x1 << ", " << y1 << ")"); << ") - (" << 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 { void SimSource::true_tilt(double* roll_out, double* pitch_out) const {
std::lock_guard<std::mutex> lk(impl_->state_mu); 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; *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 { Pose2D SimSource::ground_truth() const {
std::lock_guard<std::mutex> lk(impl_->state_mu); std::lock_guard<std::mutex> lk(impl_->state_mu);
return Pose2D{impl_->x, impl_->y, impl_->yaw}; return Pose2D{impl_->x, impl_->y, impl_->yaw};
@@ -1207,13 +1832,24 @@ void SimSource::RunFor(double seconds) {
impl_->StepPhysics(dt); impl_->StepPhysics(dt);
impl_->sim_elapsed += 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); std::lock_guard<std::mutex> lk(impl_->state_mu);
impl_->stats.imu++; if (imu_out) impl_->stats.imu++;
impl_->stats.sim_time_sec += dt; 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; enc_acc += dt;
if (enc_acc >= enc_period) { if (enc_acc >= enc_period) {
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,11 @@ vslam_add_library(vslam_slam
sensor_data_builder.h sensor_data_builder.h
occupancy_export.h occupancy_export.h
voxel_export.h voxel_export.h
slope_test.h
height_map.h
global_localizer.h
vpr_encoder.h
visual_verifier.h
FIND_DEPS FIND_DEPS
vslam_common vslam_common
RTABMap RTABMap
@@ -46,3 +51,43 @@ vslam_add_library(vslam_slam
target_link_libraries(vslam_slam PUBLIC vslam_common rtabmap::core ${OpenCV_LIBS}) target_link_libraries(vslam_slam PUBLIC vslam_common rtabmap::core ${OpenCV_LIBS})
target_include_directories(vslam_slam SYSTEM PUBLIC ${OpenCV_INCLUDE_DIRS}) target_include_directories(vslam_slam SYSTEM PUBLIC ${OpenCV_INCLUDE_DIRS})
# VPR bang TensorRT -- CHI Jetson (JetPack 6: TensorRT 10 + CUDA). Giong RealSense/CANopen o
# vslam_drivers: GLOB_RECURSE gom het src/ nen phai loai vpr_tensorrt.cc khi tat, neu khong
# `#include <NvInfer.h>` lam hong build tren may khong co TensorRT. Tat thi
# CreateVprEncoder() (vpr_encoder.cc) tra Unavailable va dinh vi lai chay bang LiDAR.
option(VSLAM_WITH_TENSORRT "VPR (EigenPlaces) bang TensorRT -- chi Jetson" OFF)
get_target_property(_vslam_slam_srcs vslam_slam SOURCES)
list(FILTER _vslam_slam_srcs EXCLUDE REGEX "vpr_tensorrt\\.cc$")
set_target_properties(vslam_slam PROPERTIES SOURCES "${_vslam_slam_srcs}")
if(VSLAM_WITH_TENSORRT)
if(NOT DEFINED CUDAToolkit_ROOT AND EXISTS /usr/local/cuda)
set(CUDAToolkit_ROOT /usr/local/cuda)
endif()
# 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)
message(FATAL_ERROR "VSLAM_WITH_TENSORRT=ON nhung khong thay NvInfer.h / libnvinfer "
"(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} ${_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

@@ -0,0 +1,322 @@
#ifndef VSLAM_GLOBAL_LOCALIZER_H
#define VSLAM_GLOBAL_LOCALIZER_H
// Dinh vi TOAN CUC bang khop scan LiDAR voi luoi chiem dung -- port tu
// vSLAM_ws/src/localization_ops/scripts/global_scan_init.py (ban ROS).
//
// ============ BAI TOAN ============
// Tha robot xuong mot cho bat ky tren ban do da quet, KHONG cho biet dang o
// dau. Robot xoay tai cho gom scan. Phai suy ra pose trong ban do -- roi dua
// cho RTAB-Map lam pose ban dau (no chi bat duoc khi lech < ~0.3 m / 5 do, xem
// docs/SLAM.md).
//
// ============ VI SAO KHOP SCAN, KHONG TUI TU ============
// Ban ROS do tren hospital: 194 lan tui tu de xuat, 186 lan co DUNG 0 inlier
// (D410 chi co anh IR, hanh lang giong nhau). Khop scan tinh diem MOI gia
// thuyet (x, y, theta) cung luc nen SO SANH duoc cac ung vien -- hai hanh lang
// giong nhau cho hai diem gan bang nhau -> biet la nhap nhang va IM LANG thay
// vi chon bua.
//
// ============ ⚠️ DA DO BEN ROS, KHONG DUOC QUEN ============
// - Xac minh bang depth QUANH mot gia thuyet (GICP) bi bac: pose SAI 22.4 m
// duoc cham TOT hon pose dung. Xac minh cuc bo khong bat duoc nham lan
// toan cuc.
// - Tren phan cung that da CHOT SAI mot lan (22.5 m, lat 180 do) du qua ca
// hai cong ty le. Ty le mot lan khop KHONG tach duoc dung/sai o dai
// 1.31-1.39 -> moi co cong nhieu vong (`min_ratio_fast`, `min_cycles`).
//
// Module nay KHONG goi RTAB-Map, khong co luong, khong doc dong ho: chi la
// ham thuan tren (luoi, diem). Viec gom scan khi xoay va dat pose ban dau la
// cua ben goi.
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
// So lay NGUYEN tu ban ROS (global_scan_init.py). Doi so nao thi ghi ly do va
// so do o ben canh -- ban ROS da hai lan rut ket luan tu 2 mau roi mau thu
// ba lat nguoc.
struct GlobalLocalizerConfig {
// Do rong truong likelihood exp(-d^2 / 2 sigma^2). 0.15 m ~ 3 o luoi 0.05:
// chiu duoc sai so luoi ma khong lam nhoe het dac trung.
double sigma = 0.15;
// = Grid/RangeMax: ban do chi dung tu tia <= 12 m. Dung tia xa hon la khop
// vao vung chua tung ghi.
double max_range = 12.0;
// --- Tim tho ---
double coarse_res = 0.80; // m
double angle_step_deg = 5.0;
int top_k = 24; // dinh tho xet de gom ung vien
int max_candidates = 8; // ung vien (da khu trung) dem tinh chinh
size_t max_points = 1500; // sau khi gop diem ve o luoi
// --- Doi thu ---
// Doi thu VI TRI phai cach nguoi thang it nhat ngan nay.
double reject_radius = 2.0;
// Doi thu HUONG: CUNG cho (trong reject_radius) nhung lech it nhat ngan nay.
// Ban ROS do: dam may 360 do doi xung quay -> vi tri dung, huong sai 40-160
// do ma ty le vi tri van 1.6.
double min_angle_sep_deg = 25.0;
// --- Cong ---
double min_ratio = 1.30; // s1 / s2 (vi tri)
double min_ratio_yaw = 1.30; // s1 / s2_yaw (huong)
// Tren nguong nay chot ngay. Duoi thi phai dung dau `min_cycles` vong lien
// tiep. Ban ROS: 7 ca DUNG 1.315-1.581, 3 ca SAI 1.31-1.39.
double min_ratio_fast = 1.60;
int min_cycles = 2;
double assoc_radius = 0.8; // m, ghep gia thuyet giua hai vong
// Chi tinh mot vong vao streak khi robot DA DI it nhat ngan nay: ban sao doi
// xung 180 do cung lap lai y het khi dung yen.
double acc_min_move = 0.20;
double acc_timeout = 120.0; // s
// --- 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
// Xa hon tilt_node_radius nhung NAM GIUA hai lan cung mot mat doc (node gan nhat
// hai phia doi dien, lech gradient <= tilt_agree_deg) thi dung do doc chung do --
// xem FloorGradientBetween. Sim 06/10, doc rong 8 m quet hai lan sat tuong: giua
// doc cach node 2-2.5 m, doi thu lat 180 do o doc kia lot bo loc, 8/8 cho xien
// khong chot.
double tilt_between_radius = 4.0; // m
double tilt_agree_deg = 2.5;
// 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
// canh "da lac" -- cung mot thang do.
class LikelihoodField {
public:
// o >= 50 la tuong, o == 0 la trong (robot chi co the dung o day), -1 chua
// biet. Khoang cach bang EDT chinh xac (Felzenszwalb-Huttenlocher).
static LikelihoodField FromGrid(const OccupancyGrid& g, double sigma);
bool empty() const { return width_ == 0 || height_ == 0; }
int width() const { return width_; }
int height() const { return height_; }
double resolution() const { return res_; }
double origin_x() const { return ox_; }
double origin_y() const { return oy_; }
// Gia tri tai o (r, c); 0 ngoai luoi.
float At(int r, int c) const {
if (r < 0 || c < 0 || r >= height_ || c >= width_) return 0.0f;
return lf_[static_cast<size_t>(r) * width_ + c];
}
bool Free(int r, int c) const {
if (r < 0 || c < 0 || r >= height_ || c >= width_) return false;
return free_[static_cast<size_t>(r) * width_ + c] != 0;
}
// Diem TRUNG BINH moi diem (frame map). Diem ngoai luoi khong tinh; tra -1
// neu it hon `min_points` diem roi vao luoi.
double MeanScore(const std::vector<Point>& pts_map, size_t min_points = 50) const;
private:
int width_ = 0, height_ = 0;
double res_ = 0.05, ox_ = 0.0, oy_ = 0.0;
std::vector<float> lf_;
std::vector<uint8_t> free_;
};
struct RelocHypothesis {
Pose2D map_from_odom; // T_map_odom
double score = 0.0; // diem sau tinh chinh
};
struct RelocMatch {
bool ok = false;
Pose2D map_from_odom; // nguoi thang
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 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
// odom luc gom -- rang buoc dat tren vi tri ROBOT, khong phai tam dam diem (o
// hanh lang tam lech robot nhieu met). score = -1 neu khong khop.
//
// `yaw_center` (rad, huong ROBOT trong map) + `yaw_window`: chi xet huong
// trong cua so do. Mac dinh (NAN) = moi huong.
//
// ⚠️ VI SAO CAN GIOI HAN HUONG: robot that 2026-09-29, 113/249 lan hoi LiDAR
// NHAP NHANG HUONG (mot scan LakiBeam ~270 do). Khop cuc bo MOI huong quanh
// ung vien VPR dung cho van truot sang huong LON cung voi LiDAR toan cuc (4
// lan chot sai, lech 105-177 do) -- vi no van dung LiDAR de chon huong. Anh
// VPR biet camera nhin ve dau: de NO chon huong, LiDAR chi chinh chinh xac.
RelocHypothesis LocalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom, const Pose2D& odom_now,
const Point& center, double radius,
const GlobalLocalizerConfig& cfg,
double yaw_center = NAN, double yaw_window = M_PI);
// Tich luy gia thuyet qua nhieu vong, truyen bang ODOM (pose toan cuc chua
// biet). "Streak" = so vong LIEN TIEP mot gia thuyet dung dau.
class HypothesisTracker {
public:
explicit HypothesisTracker(const GlobalLocalizerConfig& cfg) : cfg_(cfg) {}
// `odom_now`: pose odom->base luc vong nay ket thuc. `now_s`: giay, don dieu.
void Add(const RelocMatch& m, const Pose2D& odom_now, double now_s);
// Streak cua gia thuyet gan `map_from_odom` nhat (trong assoc_radius).
int Streak(const Pose2D& map_from_odom) const;
size_t size() const { return acc_.size(); }
void Clear() { acc_.clear(); have_odom_ = false; }
private:
struct Entry {
Pose2D map_from_odom;
int streak = 0;
double t_last = 0.0;
};
GlobalLocalizerConfig cfg_;
std::vector<Entry> acc_;
Pose2D odom_mark_; // odom luc streak duoc cong lan cuoi
Pose2D last_odom_; // odom luc Add() gan nhat -- de so vi tri
bool have_odom_ = false;
double t_prev_ = 0.0;
};
enum class RelocVerdict {
kAccept, // qua het cong -> dat pose ban dau
kNeedCycles, // ty le o dai bien, chua du so vong lien tiep
kAmbiguous, // ty le vi tri < min_ratio (hanh lang lap)
kAmbiguousYaw, // vi tri co the dung, HUONG khong tin duoc
kFailed, // khong khop duoc gi
};
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,131 @@
#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 <cstddef>
#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(); }
const std::vector<FloorNode>& nodes() const { return nodes_; }
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 doc SAN GIUA HAI LAN da quet: node gan nhat va node gan nhat o PHIA DOI DIEN
// (huong lech >= 120 do), ca hai trong `max_dist`, cung mot gradient (lech <= `agree`,
// don vi tan) -> tra gradient trung binh. Doc rong quet theo vai lan thi giua hai
// lan khong co node gan (FloorGradientAt false) nhung van la mot mat doc -- NOI SUY
// thi tin duoc, NGOAI SUY (chi mot phia, vd ngoai chan doc) thi khong: false.
bool FloorGradientBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double* gx, double* gy);
// Do cao SAN giua hai lan, cung cach chon node nhu FloorGradientBetween: hai mat phang
// node cung gradient (lech <= `agree`) va du doan z tai (x, y) lech <= `agree_z` (m) ->
// trung binh. Neo z sau dinh vi lai o giua doc rong (node gan nhat xa hon 2 m).
bool FloorZBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double agree_z, double* z);
// 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);
// Goc can quay (rad, duong = trai) de mui nhin DOC theo doc -- LEN hoac XUONG, phia
// gan hon (bang nhau thi LEN) -- chi tu do nghieng than (roll, pitch -- ROS, IMU),
// khong can biet pose. `misalign`: |goc quay|. San phang: 0.
double SlopeAlignTurn(double roll, double pitch, double* misalign = nullptr);
} // namespace vslam
#endif // VSLAM_HEIGHT_MAP_H

View File

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

View File

@@ -23,6 +23,13 @@
namespace vslam { namespace vslam {
// Ghi de theo MOI TRUONG -- khoi `profiles:` cua slam.yaml. Chi chua nhung
// key KHAC nhau giua mo phong va robot that; phan con lai dung chung.
struct SlamProfile {
std::map<std::string, double> numbers; // odom_sigma_m, odom_sigma_rad
std::map<std::string, std::string> rtabmap; // key RTAB-Map
};
struct RtabmapConfig { struct RtabmapConfig {
// TAT mac dinh: tren may chua build RTAB-Map thi node van phai chay duoc // TAT mac dinh: tren may chua build RTAB-Map thi node van phai chay duoc
// day du phan con lai. // day du phan con lai.
@@ -50,6 +57,11 @@ struct RtabmapConfig {
// Cac key RTAB-Map doc tu khoi `rtabmap:` cua slam.yaml. Ghi de len mac // Cac key RTAB-Map doc tu khoi `rtabmap:` cua slam.yaml. Ghi de len mac
// dinh, va bi ghi de boi cac suy dien tu mode/visual_loop o tren. // dinh, va bi ghi de boi cac suy dien tu mode/visual_loop o tren.
std::map<std::string, std::string> overrides; std::map<std::string, std::string> overrides;
// "sim" va "real" tu khoi `profiles:`. CHUA ap: LoadRtabmapConfig chi doc
// va kiem, ben goi chon mot cai bang ApplySlamProfile() vi chi no biet dang
// chay mo phong hay robot that.
std::map<std::string, SlamProfile> profiles;
}; };
// Tra ve tap tham so day du. `unknown` nhan ten cac key khong co trong bang // Tra ve tap tham so day du. `unknown` nhan ten cac key khong co trong bang
@@ -58,9 +70,14 @@ struct RtabmapConfig {
std::map<std::string, std::string> BuildRtabmapParams( std::map<std::string, std::string> BuildRtabmapParams(
const RtabmapConfig& cfg, std::vector<std::string>* unknown); const RtabmapConfig& cfg, std::vector<std::string>* unknown);
// Doc khoi `rtabmap:` + cac key cap cao tu ConfigNode. // Doc khoi `rtabmap:` + cac key cap cao tu ConfigNode. Nem neu khoi
// `profiles:` sai luat (xem slam.yaml).
RtabmapConfig LoadRtabmapConfig(const ConfigNode& node); RtabmapConfig LoadRtabmapConfig(const ConfigNode& node);
// Ap `profiles.<name>` len cfg: sigma odom va cac key RTAB-Map cua profile.
// Loi neu khong co profile do -- KHONG lang le chay bang mac dinh cua struct.
StatusResponse ApplySlamProfile(const std::string& name, RtabmapConfig* cfg);
// Tra ve true neu RTAB-Map duoc build kem optimizer nay. // Tra ve true neu RTAB-Map duoc build kem optimizer nay.
bool OptimizerAvailable(const std::string& strategy); bool OptimizerAvailable(const std::string& strategy);

View File

@@ -19,8 +19,13 @@
// `init(params, db, loadDatabaseParameters=false)` VA assert sau do. // `init(params, db, loadDatabaseParameters=false)` VA assert sau do.
#include <memory> #include <memory>
#include <map>
#include <string> #include <string>
#include <vector>
#include <opencv2/core.hpp>
#include "vslam/height_map.h"
#include "vslam/rtabmap_params.h" #include "vslam/rtabmap_params.h"
#include "vslam/slam_types.h" #include "vslam/slam_types.h"
#include "vslam/voxel_export.h" #include "vslam/voxel_export.h"
@@ -32,6 +37,15 @@ class RtabmapSlamImpl; // o namespace scope, KHONG long trong class
// (pimpl long private khong goi duoc tu .cc -- da // (pimpl long private khong goi duoc tu .cc -- da
// mac loi nay o ConfigNode va WebServer) // mac loi nay o ConfigNode va WebServer)
// Anh cua mot node ban do, cho dinh vi lai bang camera (vslam/visual_verifier.h).
struct NodeView {
cv::Mat gray; // anh IR (kenh "rgb" luc quet), 8 bit
cv::Mat depth; // CV_16UC1 (mm); rong neu with_depth = false
cv::Matx33d K; // DA bu binning -- dung nhu luc luu
cv::Matx44d T_base_optical; // base (z tu san, gom nghieng luc chup) <- optical
cv::Matx44d T_map_base; // pose TOI UU cua node
};
class RtabmapSlam { class RtabmapSlam {
public: public:
RtabmapSlam(); RtabmapSlam();
@@ -83,6 +97,39 @@ class RtabmapSlam {
// chi ho moi biet tap truoc do la gi. // chi ho moi biet tap truoc do la gi.
StatusResponse ExportVoxels(const VoxelExportOptions& opt, VoxelGrid* out); StatusResponse ExportVoxels(const VoxelExportOptions& opt, VoxelGrid* out);
// Node co pose toi uu (ban do dang dung), va anh + hinh hoc camera cua mot node -- DUNG
// nhu RTAB-Map da luu (K da bu binning, T gom nghieng luc chup). CHI luong slam goi (cung
// luong Process()): doc thang Memory cua RTAB-Map.
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); StatusResponse Close(bool save_database);
const SlamStats& stats() const; const SlamStats& stats() const;
@@ -92,6 +139,11 @@ class RtabmapSlam {
// Rong = DB trong RAM. Chi co nghia sau Init(). // Rong = DB trong RAM. Chi co nghia sau Init().
const std::string& database_path() const; const std::string& database_path() const;
// Tham so RTAB-Map DANG CHAY (slam.yaml + mac dinh). Dung lai GridGlobal/*
// khi dung luoi tu DB (ExportOccupancyGridFromDb) cho cung cach cap nhat o
// voi ban do dang hien.
std::map<std::string, std::string> rtabmap_parameters() const;
private: private:
std::unique_ptr<RtabmapSlamImpl> impl_; std::unique_ptr<RtabmapSlamImpl> impl_;
}; };

View File

@@ -51,6 +51,13 @@ struct SlamInput {
// Than robot chuc len/xuong khi tang/giam toc. Coi camera nam ngang thi san // 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. // o 3 m bi day len ~0.2 m va thanh vat can gia trong ban do 3D.
const Transform* camera_to_base = nullptr; 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 { struct SlamOutput {

View File

@@ -0,0 +1,159 @@
#ifndef VSLAM_SLOPE_TEST_H
#define VSLAM_SLOPE_TEST_H
// Test DOC tu dong (08/10): dat robot o DINH doc, dinh vi lai xong robot tu tim
// huong doc tren ban do, quay mat xuong, roi XUONG / LEN nhieu luot -- moi luot
// MOT van toc -- de do sai so dinh vi (va z) theo van toc va theo thoi gian.
//
// Chi la LOGIC: lap duong thu tu ban do (PlanSlopePath) va may trang thai lai
// (SlopeTest). Khong cham phan cung: runtime dua pose / co / nut vao, lay lenh
// (v, w) ra va dua qua DUNG duong FSM an toan nhu moi lenh khac (tay cam, web,
// dinh vi lai tu dong).
//
// A (cho robot dung) ──XUONG, v_k──> B (chan doc da phang + 0.5 m)
// dung do, quay dau dung do, quay dau
// <──LEN, v_k── x loops luot, v_k = speeds[k]
#include <functional>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
struct SlopePathConfig {
double max_len = 15.0; // m, xa nhat tu A
double step = 0.10; // m, buoc do doc duong
double heading_step_deg = 2.0;
double min_drop = 0.20; // m, san phai xuong it nhat chung nay
double flat_tol = 0.04; // m, "phang lai": z lech z thap nhat < nguong nay ...
double flat_len = 1.0; // m, ... lien tiep chung nay
double past_bottom = 0.5; // m, B = cho bat dau phang + doan nay
double stop_margin = 0.6; // m, B cach o khong trong / khong biet san it nhat
double level_deg = 3.0; // san 'phang': do doc mat san duoi nguong nay
double level_h = 0.25; // m, buoc sai phan do do doc
};
struct SlopePath {
Pose2D a; // x, y; theta = huong A -> B (XUONG doc)
double bx = 0.0, by = 0.0;
double length = 0.0; // m
double drop = 0.0; // m, z(A) - z(B) > 0
};
// floor(x, y, &z): do cao san trong ban do; false = khong biet san o do.
// free(x, y): o TRONG va du cho than robot (nguoi goi da tinh lan).
using FloorFn = std::function<bool(double, double, double*)>;
using FreeFn = std::function<bool(double, double)>;
// Thu moi huong quanh (x, y): di thang tren ban do, buoc `step`, toi khi gap o
// khong trong hoac khong biet san. Huong hop le: san XUONG >= min_drop roi PHANG
// lai >= flat_len truoc khi het duong. Chon huong xuong het doc NGAN NHAT -- tuc
// la doc theo truc doc, khong xien. false + `why` neu khong co huong nao.
//
// A = DINH doc phang (robot dang giua doc thi di nguoc len theo truc toi cho
// phang), B = CHAN doc phang + past_bottom. `diag` (tuy chon): moi huong da
// thu, "huong:duong trong:dung vi:ket qua" -- de doc khi khong ra duong.
bool PlanSlopePath(double x, double y, const FloorFn& floor, const FreeFn& free,
const SlopePathConfig& cfg, SlopePath* out, std::string* why,
std::string* diag = nullptr);
struct SlopeTestConfig {
int loops = 10;
// Van toc MOI LUOT (xuong + len cung mot van toc), tang dan: luot dau cham,
// an toan nhat. Het danh sach thi quay vong.
std::vector<double> speeds = {0.10, 0.14, 0.18, 0.22, 0.26, 0.30, 0.34, 0.38, 0.42, 0.46};
double dwell_s = 3.0; // dung o moi dau de do
double turn_rate = 0.5; // rad/s, quay tai cho toi da
double turn_min = 0.15; // rad/s, toi thieu (vuot vung chet cua base)
double turn_tol_deg = 3.0;
double arrive_tol = 0.10; // m
double slow_zone = 0.8; // m, giam toc truoc dich
double min_speed = 0.06; // m/s
double k_heading = 1.5; // w = k * loi huong
double k_cross = 1.0; // huong dich = huong duong - atan(k * lech ngang)
double max_w = 0.6; // rad/s khi dang chay
double drive_turn_deg = 25.0; // loi huong lon hon -> dung lai quay truoc
double cross_max = 0.40; // m, lech khoi duong -> DUNG HAN
double jump_max = 0.30; // m giua hai buoc, pose nhay -> DUNG HAN
double tilt_max_deg = 20.0; // nghieng hon -> DUNG HAN
double leg_timeout_extra = 20.0; // s, cong vao 2 * L / v
// Robot khong o A (dinh vi lai tu chay ra giua doc): chay CHAM ve A truoc.
double approach_speed = 0.15; // m/s
};
enum class SlopeTestPhase {
kIdle, // chua co duong
kFace, // quay mat xuong doc (truoc khi cho nut)
kWaitStart, // da quay mat, cho nguoi bam bat dau
kTurn, // quay theo huong luot dang chay
kDrive, // dang chay tren duong
kDwell, // dung o mot dau de do
kPaused, // nguoi vua lai -- im, cho bam tiep tuc
kHalted, // vi pham an toan -- dung han
kDone, // xong moi luot
};
const char* SlopeTestPhaseName(SlopeTestPhase p);
struct SlopeTestInput {
double t = 0.0; // s, dong ho don dieu
Pose2D pose; // pose MAP
bool localized = false; // false = mat dinh vi / scan khong khop ban do
double roll = 0.0, pitch = 0.0; // rad, nghieng than
bool human = false; // nguon khac (tay cam, web) vua ra lenh
bool start = false; // vua bam nut bat dau / chay tiep
};
struct SlopeTestOutput {
bool command = false; // ghi lenh khong; false = im, nhuong nguon khac
double v = 0.0, w = 0.0;
std::string event; // dong log moi; rong = khong co gi moi
};
class SlopeTest {
public:
explicit SlopeTest(SlopeTestConfig cfg = SlopeTestConfig());
// Dat duong; vao kFace. autostart: quay mat xong thi chay luon (mo phong --
// khong co tay cam), khong thi cho `start`.
void SetPath(const SlopePath& p, bool autostart);
SlopeTestOutput Step(const SlopeTestInput& in);
SlopeTestPhase phase() const { return phase_; }
const SlopePath& path() const { return path_; }
int loops() const { return cfg_.loops; }
int loop() const { return loop_; } // 1-based; 0 = chua chay
bool down() const { return down_; } // luot hien tai dang XUONG
double speed() const; // van toc luot hien tai
bool approaching() const { return approach_; } // dang ve A (khong phai luot do)
double along() const { return along_; } // m, da di tu dau luot
double cross() const { return cross_; } // m, lech ngang (+ = ben trai)
const std::string& halt_reason() const { return halt_; }
private:
void BeginLeg(double t);
SlopeTestOutput Halt(const std::string& why);
bool Unsafe(const SlopeTestInput& in, std::string* why) const;
SlopeTestConfig cfg_;
SlopePath path_;
SlopeTestPhase phase_ = SlopeTestPhase::kIdle;
SlopeTestPhase paused_from_ = SlopeTestPhase::kIdle;
bool autostart_ = false;
bool approach_ = false; // dang chay ve A
bool approached_ = false; // da kiem can ve A chua
int loop_ = 0;
bool down_ = true;
double from_x_ = 0.0, from_y_ = 0.0, to_x_ = 0.0, to_y_ = 0.0, heading_ = 0.0, len_ = 0.0;
double leg_t0_ = 0.0, dwell_t0_ = 0.0;
double along_ = 0.0, cross_ = 0.0;
bool have_prev_ = false;
Pose2D prev_;
std::string halt_;
};
} // namespace vslam
#endif // VSLAM_SLOPE_TEST_H

View File

@@ -0,0 +1,65 @@
#ifndef VSLAM_VISUAL_VERIFIER_H
#define VSLAM_VISUAL_VERIFIER_H
// Xac minh ung vien VPR bang ANH: so khop diem dac trung (ORB) giua anh hoi va anh ban do,
// nang diem ban do len 3D bang depth cua chinh anh do, roi PnP RANSAC -> pose robot.
//
// Ban C++ cua tools/reloc_pnp_eval.py -- CUNG tham so. Do 2026-09-30 (camera + LiDAR, chot
// khi pose PnP trung khop LiDAR cuc bo quanh node anh VPR): 25/09 85 -> 159 dung, 28/09
// 29 -> 40 dung, 0 chot SAI ca hai. Diem dac trung nho (goc cua, poster) nhin NGUOC lai thi
// khac han -> pha duoc doi xung hanh lang ma LiDAR va hinh khoi depth deu bi lua.
#include <vector>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
namespace vslam {
struct VisualVerifierConfig {
int orb_features = 1500;
int fast_threshold = 7;
double clahe_clip = 3.0; // anh IR toi: CLAHE cho x2.7 diem ORB
int clahe_grid = 8;
double ratio = 0.8; // ratio test Lowe
double depth_min_m = 0.3;
double depth_max_m = 5.0;
int ransac_iters = 300;
double reproj_px = 4.0;
double confidence = 0.999;
int min_points = 8;
};
// Mot anh da trich dac trung, kem hinh hoc camera.
struct VisualFrame {
std::vector<cv::KeyPoint> kp;
cv::Mat des;
cv::Mat depth; // CV_16UC1 (mm) hoac CV_32FC1 (m); rong neu khong can
cv::Matx33d K;
cv::Matx44d T_base_optical; // base (z tinh tu san) <- optical
};
struct PnpResult {
int matches = 0; // cap qua ratio test
int inliers = 0; // inlier PnP RANSAC; 0 = khong ra nghiem
double x = 0.0, y = 0.0, yaw = 0.0; // base cua anh hoi trong map
double dz = 0.0, tilt_deg = 0.0; // robot tren san: phai ~0 (lech = nghiem suy bien)
};
class VisualVerifier {
public:
explicit VisualVerifier(const VisualVerifierConfig& cfg = VisualVerifierConfig());
// CLAHE + ORB. `depth`, `K`, `T_base_optical` nguoi goi dien sau.
VisualFrame Extract(const cv::Mat& gray) const;
// Pose base cua anh hoi `q` trong map, tu diem khop voi anh ban do `m` (can depth) co pose
// map <- base `T_map_base_m`.
PnpResult Solve(const VisualFrame& q, const VisualFrame& m, const cv::Matx44d& T_map_base_m) const;
private:
VisualVerifierConfig cfg_;
cv::Ptr<cv::ORB> orb_;
};
} // namespace vslam
#endif // VSLAM_VISUAL_VERIFIER_H

View File

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

View File

@@ -0,0 +1,52 @@
#ifndef VSLAM_VPR_ENCODER_H
#define VSLAM_VPR_ENCODER_H
// Nhan dien NOI CHON bang anh (VPR): anh IR -> mo ta 2048 chieu da chuan hoa L2.
// Hai anh chup cung mot cho co tich vo huong (cosine) cao.
//
// Mo hinh: EigenPlaces ResNet50, xuat ONNX bang tools/vpr_export_onnx.py. Chay bang
// TensorRT tren Jetson -- do 2026-09-30 (JetPack 6.1): fp16 6.5 ms/anh, OpenCV CPU
// 299 ms/anh. Build khong co -DVSLAM_WITH_TENSORRT=ON thi CreateVprEncoder() tra
// Unavailable: dinh vi lai van chay bang LiDAR nhu cu.
//
// Engine TensorRT (.plan) RIENG tung may + phien ban TensorRT. Dung MOT lan tren may do
// (lenh viet tren MOT dong):
// /usr/src/tensorrt/bin/trtexec --onnx=resources/vpr/eigenplaces_r50_2048_384x512.onnx
// --fp16 --saveEngine=resources/vpr/eigenplaces_r50_fp16.plan
#include <memory>
#include <string>
#include <vector>
#include <opencv2/core.hpp>
#include "vslam/vslam_common.h"
namespace vslam {
// Tien xu ly PHAI giong tools/vpr_export_onnx.py (noi da do 88-89% top-1 tren anh IR).
struct VprConfig {
std::string engine_path; // .plan cua TensorRT
int width = 512;
int height = 384;
double clahe_clip = 2.0;
int clahe_grid = 8;
};
class VprEncoder {
public:
virtual ~VprEncoder() = default;
// Anh IR xam 8 bit, kich thuoc bat ky -> mo ta dim() so, da chuan hoa L2.
virtual StatusResponse Describe(const cv::Mat& gray, std::vector<float>* desc) = 0;
virtual int dim() const = 0;
};
StatusResponse CreateVprEncoder(const VprConfig& cfg, std::unique_ptr<VprEncoder>* out);
// Anh xam -> tensor (3, height, width) float32 hang CHW: CLAHE -> resize INTER_LINEAR ->
// /255 -> lap 3 kenh -> chuan hoa ImageNet. Tach rieng de dung/test khong can TensorRT.
void VprPreprocess(const cv::Mat& gray, const VprConfig& cfg, std::vector<float>* chw);
} // namespace vslam
#endif // VSLAM_VPR_ENCODER_H

View File

@@ -0,0 +1,832 @@
#include "vslam/global_localizer.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <limits>
#include <unordered_set>
#include "vslam/geometry.h"
namespace vslam {
namespace {
constexpr double kDegToRad = M_PI / 180.0;
// EDT 1D (Felzenszwalb-Huttenlocher): d[i] = min_j (f[j] + (i-j)^2).
// Phan tu f = inf (khong co tuong) KHONG BAO GIO nam tren duong bao duoi, nen
// bo qua han -- de nguyen trong cong thuc giao diem thi ra inf - inf = NaN.
void Edt1d(const std::vector<float>& f, std::vector<float>* d,
std::vector<int>* v, std::vector<double>* z) {
const int n = static_cast<int>(f.size());
const float inf = std::numeric_limits<float>::infinity();
int k = -1;
for (int q = 0; q < n; ++q) {
if (f[q] == inf) continue;
if (k < 0) {
k = 0;
(*v)[0] = q;
(*z)[0] = -std::numeric_limits<double>::infinity();
(*z)[1] = std::numeric_limits<double>::infinity();
continue;
}
double s;
while (true) {
const int p = (*v)[k];
s = ((f[q] + static_cast<double>(q) * q) - (f[p] + static_cast<double>(p) * p)) /
(2.0 * (q - p));
// z[0] = -inf nen k khong bao gio xuong duoi 0.
if (s <= (*z)[k]) { --k; continue; }
break;
}
++k;
(*v)[k] = q;
(*z)[k] = s;
(*z)[k + 1] = std::numeric_limits<double>::infinity();
}
if (k < 0) { // ca hang/cot khong co tuong
for (int q = 0; q < n; ++q) (*d)[q] = inf;
return;
}
k = 0;
for (int q = 0; q < n; ++q) {
while ((*z)[k + 1] < q) ++k;
const int p = (*v)[k];
(*d)[q] = static_cast<float>((q - p) * static_cast<double>(q - p) + f[p]);
}
}
struct Refined {
double score = -1.0;
double x = 0.0, y = 0.0, th = 0.0; // (x, y) tuong doi goc luoi, met
};
// Mot luot luoi (x, y, theta) quanh (x0, y0, th0): x, y trong +-n_xy buoc
// dxy, theta trong +-n_a buoc da. Tinh truc tiep, khong FFT.
Refined SearchGrid(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, int n_xy, double dxy,
int n_a, double da) {
const double res = f.resolution();
Refined best;
std::vector<double> qx(P.size()), qy(P.size());
for (int ia = -n_a; ia <= n_a; ++ia) {
const double th = th0 + ia * da;
const double ct = std::cos(th), st = std::sin(th);
for (size_t i = 0; i < P.size(); ++i) {
qx[i] = ct * P[i].x - st * P[i].y;
qy[i] = st * P[i].x + ct * P[i].y;
}
for (int ix = -n_xy; ix <= n_xy; ++ix) {
const double x = x0 + ix * dxy;
for (int iy = -n_xy; iy <= n_xy; ++iy) {
const double y = y0 + iy * dxy;
double s = 0.0;
for (size_t i = 0; i < P.size(); ++i) {
const int c = static_cast<int>(std::lround((qx[i] + x) / res));
const int r = static_cast<int>(std::lround((qy[i] + y) / res));
s += f.At(r, c);
}
if (s > best.score) best = Refined{s, x, y, th};
}
}
}
return best;
}
// Tinh chinh mot ung vien o do phan giai ban do.
Refined Refine(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, double rc,
const GlobalLocalizerConfig& cfg) {
const double res = f.resolution();
const double step = cfg.angle_step_deg * kDegToRad;
// Luot 1 = ban ROS: +-nua o tho buoc 2*res, +-mot buoc goc buoc (buoc / 5).
const int n_xy = std::max(1, static_cast<int>(std::lround((rc / 2.0) / (2.0 * res))));
const Refined r1 = SearchGrid(f, P, x0, y0, th0, n_xy, 2.0 * res, 5, step / 5.0);
if (r1.score < 0.0) return r1;
// [vslam] Luot 2 min hon: +-0.1 m buoc res/2, +-(buoc / 5) buoc (buoc / 25).
// Lech 1.5 do o 7 m la 0.19 m ~ 1.3 sigma -- keo diem pose DUNG xuong va lam
// ty le kem tach bach (test tong hop 2026-09-29: sai 1.57 do). Ap cho MOI
// ung vien -- ca doi thu -- de so diem cong bang.
return SearchGrid(f, P, r1.x, r1.y, r1.th, 4, res / 2.0, 5, step / 25.0);
}
} // namespace
// ---------------------------------------------------------------------------
// LikelihoodField
// ---------------------------------------------------------------------------
LikelihoodField LikelihoodField::FromGrid(const OccupancyGrid& g, double sigma) {
LikelihoodField out;
out.width_ = static_cast<int>(g.width);
out.height_ = static_cast<int>(g.height);
out.res_ = g.resolution;
out.ox_ = g.origin.position.x;
out.oy_ = g.origin.position.y;
const size_t n = static_cast<size_t>(out.width_) * out.height_;
out.lf_.assign(n, 0.0f);
out.free_.assign(n, 0);
if (n == 0 || g.data.size() != n) return out;
const float inf = std::numeric_limits<float>::infinity();
std::vector<float> d2(n, inf);
bool any_occ = false;
for (size_t i = 0; i < n; ++i) {
if (g.data[i] >= 50) { d2[i] = 0.0f; any_occ = true; }
out.free_[i] = (g.data[i] == 0) ? 1 : 0;
}
if (!any_occ) return out;
// EDT tach duoc: cot roi hang, don vi o^2.
const int W = out.width_, H = out.height_;
const int m = std::max(W, H);
std::vector<float> f(m), d(m);
std::vector<double> z(m + 1);
std::vector<int> v(m);
for (int c = 0; c < W; ++c) {
f.resize(H); d.resize(H);
for (int r = 0; r < H; ++r) f[r] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int r = 0; r < H; ++r) d2[static_cast<size_t>(r) * W + c] = d[r];
}
for (int r = 0; r < H; ++r) {
f.resize(W); d.resize(W);
for (int c = 0; c < W; ++c) f[c] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int c = 0; c < W; ++c) d2[static_cast<size_t>(r) * W + c] = d[c];
}
const double k = (out.res_ * out.res_) / (2.0 * sigma * sigma);
for (size_t i = 0; i < n; ++i) {
out.lf_[i] = static_cast<float>(std::exp(-d2[i] * k));
}
return out;
}
double LikelihoodField::MeanScore(const std::vector<Point>& pts_map,
size_t min_points) const {
double s = 0.0;
size_t cnt = 0;
for (const Point& p : pts_map) {
const int c = static_cast<int>(std::lround((p.x - ox_) / res_));
const int r = static_cast<int>(std::lround((p.y - oy_) / res_));
if (r < 0 || c < 0 || r >= height_ || c >= width_) continue;
s += lf_[static_cast<size_t>(r) * width_ + c];
++cnt;
}
if (cnt < min_points || cnt == 0) return -1.0;
return s / static_cast<double>(cnt);
}
// ---------------------------------------------------------------------------
// Khop toan cuc
// ---------------------------------------------------------------------------
std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
size_t max_points) {
// Nhieu tia roi vao mot o thi khong them thong tin, chi lam cham.
std::vector<Point> out;
out.reserve(pts.size());
std::unordered_set<uint64_t> seen;
seen.reserve(pts.size() * 2);
for (const Point& p : pts) {
const int64_t kx = static_cast<int64_t>(std::llround(p.x / res));
const int64_t ky = static_cast<int64_t>(std::llround(p.y / res));
const uint64_t key = (static_cast<uint64_t>(kx) << 32) ^
static_cast<uint32_t>(ky);
if (seen.insert(key).second) out.push_back(p);
}
if (max_points > 0 && out.size() > max_points) {
const size_t step = (out.size() + max_points - 1) / max_points;
std::vector<Point> thin;
thin.reserve(out.size() / step + 1);
for (size_t i = 0; i < out.size(); i += step) thin.push_back(out[i]);
out.swap(thin);
}
return out;
}
namespace {
// Luoi tho + dam diem da can tam -- dung chung cho GlobalMatch va LocalMatch.
struct Coarse {
double res = 0.05;
int k = 1; // o tho = k x k o min
double rc = 0.8; // canh o tho, met
int Wc = 0, Hc = 0;
std::vector<float> Lc; // max-pool truong likelihood
std::vector<uint8_t> Fc; // o tho co it nhat mot o min TRONG
Point cen; // tam dam diem (frame odom)
std::vector<Point> P; // diem da tru tam
double step = 0.0; // buoc goc, rad
int n_ang = 0;
int R = 0; // ban kinh histogram do lech, o tho
// Tam cua khoi tho b, met tuong doi goc luoi. O min i co tam i*res.
double BlockCenter(int b) const { return (b * k + (k - 1) / 2.0) * res; }
bool FreeCell(int r, int c) const { return Fc[static_cast<size_t>(r) * Wc + c] != 0; }
};
Coarse PrepareCoarse(const LikelihoodField& field, const std::vector<Point>& pts,
const GlobalLocalizerConfig& cfg) {
Coarse cz;
cz.res = field.resolution();
// Phai la MAX chu khong phai trung binh: muc tho de SANG LOC, bo sot mot
// dinh that o day thi khong con co hoi tinh chinh no nua.
cz.k = std::max(1, static_cast<int>(std::lround(cfg.coarse_res / cz.res)));
cz.rc = cz.res * cz.k;
const int W = field.width(), H = field.height();
cz.Wc = (W + cz.k - 1) / cz.k;
cz.Hc = (H + cz.k - 1) / cz.k;
cz.Lc.assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0.0f);
cz.Fc.assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0);
for (int r = 0; r < H; ++r) {
for (int c = 0; c < W; ++c) {
const size_t ci = static_cast<size_t>(r / cz.k) * cz.Wc + (c / cz.k);
cz.Lc[ci] = std::max(cz.Lc[ci], field.At(r, c));
if (field.Free(r, c)) cz.Fc[ci] = 1;
}
}
// Xoay quanh TAM dam diem cho on dinh so hoc.
for (const Point& p : pts) { cz.cen.x += p.x; cz.cen.y += p.y; }
cz.cen.x /= static_cast<double>(pts.size());
cz.cen.y /= static_cast<double>(pts.size());
cz.P.resize(pts.size());
double maxn = 0.0;
for (size_t i = 0; i < pts.size(); ++i) {
cz.P[i].x = pts[i].x - cz.cen.x;
cz.P[i].y = pts[i].y - cz.cen.y;
maxn = std::max(maxn, std::hypot(cz.P[i].x, cz.P[i].y));
}
cz.step = cfg.angle_step_deg * kDegToRad;
cz.n_ang = std::max(1, static_cast<int>(std::lround(2.0 * M_PI / cz.step)));
cz.R = static_cast<int>(std::ceil(maxn / cz.rc)) + 1;
return cz;
}
struct AnglePeak { double score; int r, c; double th; };
// Diem THO cua goc thu `ia` tai moi o `allowed(r, c)` (o khac = 0).
//
// Ban ROS dung FFT; o day cong truc tiep tren cac do lech DA GOP (histogram do
// lech o tho) -- cung ket qua (khong cuon vong), khong can FFT.
template <class Allowed>
AnglePeak ScoreAngle(const Coarse& cz, int ia, Allowed allowed, std::vector<float>* sc) {
struct Off { int dr, dc; float n; };
const double th = ia * cz.step;
const double ct = std::cos(th), st = std::sin(th);
const int HW = 2 * cz.R + 1;
std::vector<float> hist(static_cast<size_t>(HW) * HW, 0.0f);
for (const Point& p : cz.P) {
const int dc = static_cast<int>(std::lround((ct * p.x - st * p.y) / cz.rc));
const int dr = static_cast<int>(std::lround((st * p.x + ct * p.y) / cz.rc));
hist[static_cast<size_t>(dr + cz.R) * HW + (dc + cz.R)] += 1.0f;
}
std::vector<Off> offs;
for (int dr = -cz.R; dr <= cz.R; ++dr) {
for (int dc = -cz.R; dc <= cz.R; ++dc) {
const float n = hist[static_cast<size_t>(dr + cz.R) * HW + (dc + cz.R)];
if (n > 0.0f) offs.push_back({dr, dc, n});
}
}
sc->assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0.0f);
AnglePeak pk{-1.0, 0, 0, th};
for (int r = 0; r < cz.Hc; ++r) {
for (int c = 0; c < cz.Wc; ++c) {
if (!allowed(r, c)) continue;
double s = 0.0;
for (const Off& o : offs) {
const int rr = r + o.dr, cc = c + o.dc;
if (rr < 0 || cc < 0 || rr >= cz.Hc || cc >= cz.Wc) continue;
s += o.n * cz.Lc[static_cast<size_t>(rr) * cz.Wc + cc];
}
(*sc)[static_cast<size_t>(r) * cz.Wc + c] = static_cast<float>(s);
if (s > pk.score) pk = AnglePeak{s, r, c, th};
}
}
return pk;
}
// (x, y, th) dat TAM dam diem vao cho nao tren luoi. Doi sang T_map_odom:
// p_map = R(th) * p_odom + t, t = (x, y) + goc_luoi - R(th) * tam
Pose2D ToMap(const Refined& rf, const Point& cen, const LikelihoodField& f) {
const double ct = std::cos(rf.th), st = std::sin(rf.th);
return Pose2D{rf.x + f.origin_x() - (ct * cen.x - st * cen.y),
rf.y + f.origin_y() - (st * cen.x + ct * cen.y),
NormalizeAngle(rf.th)};
}
} // namespace
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg,
const RelocAdmit& admit) {
RelocMatch out;
if (field.empty() || pts_odom.empty()) return out;
const double res = field.resolution();
const std::vector<Point> pts = DownsamplePoints(pts_odom, res, cfg.max_points);
out.points = pts.size();
if (pts.empty()) return out;
const Coarse cz = PrepareCoarse(field, pts, cfg);
const int k = cz.k;
const double rc = cz.rc;
const int Wc = cz.Wc, Hc = cz.Hc;
const std::vector<Point>& P = cz.P;
const double step = cz.step;
const int n_ang = cz.n_ang;
auto block_center = [&](int b) { return cz.BlockCenter(b); };
// --- Quet tho: MOI goc x MOI o trong ---
// ⚠️ Rang buoc "o trong" dat tren TAM dam diem, dung nhu ban ROS
// (`sc[~Fc] = 0` tren luoi dat tam). Dam may 300 do quanh robot co tam gan
// robot nen gan nhu tuong duong.
std::vector<std::vector<float>> scores(n_ang);
std::vector<AnglePeak> peaks;
peaks.reserve(n_ang);
for (int ia = 0; ia < n_ang; ++ia) {
peaks.push_back(ScoreAngle(cz, ia, [&](int r, int c) { return cz.FreeCell(r, c); },
&scores[ia]));
}
std::sort(peaks.begin(), peaks.end(),
[](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.
const double rad_c = cfg.reject_radius / rc;
std::vector<AnglePeak> cand;
for (int i = 0; i < std::min<int>(cfg.top_k, static_cast<int>(peaks.size())); ++i) {
const AnglePeak& p = peaks[i];
bool dup = false;
for (const AnglePeak& q : cand) {
const double dr = p.r - q.r, dc = p.c - q.c;
if (dr * dr + dc * dc <= rad_c * rad_c) { dup = true; break; }
}
if (!dup) cand.push_back(p);
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;
refine_all(cand, &refined);
if (refined.empty()) return out;
// --- 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 ---
// ⚠️ Phai LUON tim duoc, ke ca ngoai top-K. Ban ROS: tren ban do nho ca 8
// ung vien nam gon trong 2 m cua nhau -> s2 = 0 -> ty le len vo cuc va node
// 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 &&
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;
const int cw = static_cast<int>(std::lround(best.x / res)) / k;
auto is_far = [&](int r, int c) {
const double dr = r - rw, dc = c - cw;
return dr * dr + dc * dc > rad_c * rad_c;
};
{
double fv = -1.0;
int fr = -1, fc = -1;
double fth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const std::vector<float>& sc = scores[ia];
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) && 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);
if (alt.score > s2) {
s2 = alt.score;
out.s2_from_odom = ToMap(alt, cz.cen, field);
}
}
}
// --- Doi thu HUONG: CUNG cho, KHAC huong ---
double s2_yaw = 0.0;
{
const double min_sep = cfg.min_angle_sep_deg * kDegToRad;
double gv = -1.0;
int gr = -1, gc = -1;
double gth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const double th = ia * step;
if (std::fabs(AngleDiff(th, best.th)) < min_sep) continue;
const std::vector<float>& sc = scores[ia];
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) && rival_ok(r, c, th)) { gv = v; gr = r; gc = c; gth = th; }
}
}
}
if (gr >= 0 && gv > 0.0) {
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;
out.s2 = s2;
out.s2_yaw = s2_yaw;
out.ok = true;
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,
const GlobalLocalizerConfig& cfg,
double yaw_center, double yaw_window) {
RelocHypothesis out;
out.score = -1.0;
if (field.empty() || pts_odom.empty()) return out;
const std::vector<Point> pts =
DownsamplePoints(pts_odom, field.resolution(), cfg.max_points);
if (pts.empty()) return out;
const Coarse cz = PrepareCoarse(field, pts, cfg);
// Rang buoc dat tren vi tri ROBOT, khong phai tam dam diem: o hanh lang tam
// lech robot nhieu met. Voi goc th, robot roi dung `center` khi tam dat tai
// center - R(th) * (robot_odom - tam)
// (met tuong doi goc luoi). Nua o tho cong them de khong cat hut o bien.
const double bx = odom_now.x - cz.cen.x, by = odom_now.y - cz.cen.y;
const double cx = center.x - field.origin_x(), cy = center.y - field.origin_y();
const double r2 = (radius + 0.5 * cz.rc) * (radius + 0.5 * cz.rc);
std::vector<AnglePeak> peaks;
std::vector<float> sc;
for (int ia = 0; ia < cz.n_ang; ++ia) {
const double th = ia * cz.step;
// Huong ROBOT trong map ung voi goc th: th + odom_now.theta. Cong mot buoc
// goc de khong cat hut goc tho sat bien cua so (tinh chinh +-1 buoc).
if (std::isfinite(yaw_center) &&
std::fabs(AngleDiff(th + odom_now.theta, yaw_center)) > yaw_window + cz.step) {
continue;
}
const double ct = std::cos(th), st = std::sin(th);
const double px = cx - (ct * bx - st * by), py = cy - (st * bx + ct * by);
const AnglePeak pk = ScoreAngle(
cz, ia,
[&](int r, int c) {
if (!cz.FreeCell(r, c)) return false;
const double dx = cz.BlockCenter(c) - px, dy = cz.BlockCenter(r) - py;
return dx * dx + dy * dy <= r2;
},
&sc);
if (pk.score > 0.0) peaks.push_back(pk);
}
if (peaks.empty()) return out;
std::sort(peaks.begin(), peaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
// Tinh chinh vai dinh dau (cung ly do nhu GlobalMatch: so o muc tho la sai).
Refined best;
for (size_t i = 0; i < peaks.size() && i < 3; ++i) {
const Refined rf = Refine(field, cz.P, cz.BlockCenter(peaks[i].c),
cz.BlockCenter(peaks[i].r), peaks[i].th, cz.rc, cfg);
if (rf.score > best.score) best = rf;
}
if (best.score < 0.0) return out;
out.map_from_odom = ToMap(best, cz.cen, field);
out.score = best.score;
return out;
}
// ---------------------------------------------------------------------------
// Tich luy qua nhieu vong
// ---------------------------------------------------------------------------
//
// Luu T_map_odom chu khong luu pose robot: T_map_odom KHONG doi khi robot di
// (frame odom co dinh), nen khong phai truyen tung gia thuyet theo delta odom
// nhu ban ROS -- chi can ghep voi odom HIEN TAI khi so sanh vi tri.
//
// ⚠️ Khac ban ROS mot cho, co chu y: ban ROS dat lai moc odom MOI vong, ke ca
// vong chua du `acc_min_move` -- nen di cham (moi vong < 0.2 m) thi KHONG bao
// gio cong duoc streak. O day moc chi dat lai khi DA cong: quang duong duoc
// cong don cho toi khi du.
void HypothesisTracker::Add(const RelocMatch& m, const Pose2D& odom_now, double now_s) {
if (!m.ok || m.hyps.empty()) return;
if (!acc_.empty() && now_s - t_prev_ > cfg_.acc_timeout) acc_.clear();
t_prev_ = now_s;
last_odom_ = odom_now;
if (acc_.empty() || !have_odom_) {
acc_.clear();
for (size_t i = 0; i < m.hyps.size(); ++i) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
}
odom_mark_ = odom_now;
have_odom_ = true;
return;
}
// Cung cho -> streak KHONG duoc cong: ban sao doi xung cung lap lai y het.
if (std::hypot(odom_now.x - odom_mark_.x, odom_now.y - odom_mark_.y) < cfg_.acc_min_move) {
for (Entry& e : acc_) e.t_last = now_s;
return;
}
odom_mark_ = odom_now;
const double r2 = cfg_.assoc_radius * cfg_.assoc_radius;
for (size_t i = 0; i < m.hyps.size(); ++i) {
const Pose2D ph = Pose2DCompose(m.hyps[i].map_from_odom, odom_now);
Entry* hit = nullptr;
double bd = r2;
for (Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, odom_now);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; hit = &e; }
}
if (hit == nullptr) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
continue;
}
hit->map_from_odom = m.hyps[i].map_from_odom; // bam theo do do moi nhat
hit->t_last = now_s;
hit->streak = (i == 0) ? hit->streak + 1 : 0;
}
// Bo gia thuyet khong xuat hien lai o vong nay.
acc_.erase(std::remove_if(acc_.begin(), acc_.end(),
[&](const Entry& e) { return e.t_last < now_s; }),
acc_.end());
}
int HypothesisTracker::Streak(const Pose2D& map_from_odom) const {
const Pose2D ph = Pose2DCompose(map_from_odom, last_odom_);
int best = 0;
double bd = cfg_.assoc_radius * cfg_.assoc_radius;
for (const Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, last_odom_);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; best = e.streak; }
}
return best;
}
// ---------------------------------------------------------------------------
// Cong
// ---------------------------------------------------------------------------
const char* RelocVerdictName(RelocVerdict v) {
switch (v) {
case RelocVerdict::kAccept: return "CHOT";
case RelocVerdict::kNeedCycles: return "DAI_BIEN_CHO_VONG";
case RelocVerdict::kAmbiguous: return "NHAP_NHANG";
case RelocVerdict::kAmbiguousYaw: return "NHAP_NHANG_HUONG";
case RelocVerdict::kFailed: return "THAT_BAI";
}
return "?";
}
RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg) {
if (!m.ok) return RelocVerdict::kFailed;
// Huong truoc: khong co cong nay thi vi tri dung, huong sai 40-160 do ma ty
// le vi tri van 1.6 (ban ROS).
if (m.ratio_yaw() < cfg.min_ratio_yaw) return RelocVerdict::kAmbiguousYaw;
// Hanh lang lap: tra loi sai tu tin te hon nhieu so voi im lang.
if (m.ratio() < cfg.min_ratio) return RelocVerdict::kAmbiguous;
// Dai bien: ty le mot lan khop khong tach duoc dung/sai o day.
if (m.ratio() < cfg.min_ratio_fast && streak < cfg.min_cycles) {
return RelocVerdict::kNeedCycles;
}
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,256 @@
#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;
}
namespace {
// Dao ham cua PlaneZ: z = z_n - fwd * tan(pitch) + left * tan(roll).
void NodeGradient(const FloorNode& n, double* gx, double* gy) {
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;
}
} // namespace
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;
NodeGradient(n, gx, gy);
return true;
}
namespace {
// Node gan nhat va node gan nhat o PHIA DOI DIEN (huong lech >= 120 do), ca hai trong
// max_dist. false neu thieu mot trong hai.
bool OppositePair(const FloorModel& fm, double x, double y, double max_dist, FloorNode* a,
FloorNode* b) {
const std::vector<FloorNode>& nodes = fm.nodes();
int i1 = -1;
double d1 = max_dist;
for (size_t i = 0; i < nodes.size(); ++i) {
const double d = std::hypot(nodes[i].x - x, nodes[i].y - y);
if (d <= d1) {
d1 = d;
i1 = static_cast<int>(i);
}
}
if (i1 < 0 || d1 < 1e-6) return false;
const double ux = (nodes[i1].x - x) / d1, uy = (nodes[i1].y - y) / d1;
constexpr double kOpposite = -0.5; // cos(120 do)
int i2 = -1;
double d2 = max_dist;
for (size_t i = 0; i < nodes.size(); ++i) {
const double dx = nodes[i].x - x, dy = nodes[i].y - y;
const double d = std::hypot(dx, dy);
if (d > d2 || d < 1e-6 || (dx * ux + dy * uy) / d > kOpposite) continue;
d2 = d;
i2 = static_cast<int>(i);
}
if (i2 < 0) return false;
*a = nodes[static_cast<size_t>(i1)];
*b = nodes[static_cast<size_t>(i2)];
return true;
}
} // namespace
bool FloorGradientBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double* gx, double* gy) {
FloorNode a, b;
if (!OppositePair(fm, x, y, max_dist, &a, &b)) return false;
double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
NodeGradient(a, &ax, &ay);
NodeGradient(b, &bx, &by);
if (std::hypot(ax - bx, ay - by) > agree) return false;
*gx = 0.5 * (ax + bx);
*gy = 0.5 * (ay + by);
return true;
}
bool FloorZBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double agree_z, double* z) {
FloorNode a, b;
if (!OppositePair(fm, x, y, max_dist, &a, &b)) return false;
double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
NodeGradient(a, &ax, &ay);
NodeGradient(b, &bx, &by);
const double za = PlaneZ(a, x, y), zb = PlaneZ(b, x, y);
if (std::hypot(ax - bx, ay - by) > agree || std::fabs(za - zb) > agree_z) return false;
*z = 0.5 * (za + zb);
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);
}
double SlopeAlignTurn(double roll, double pitch, double* misalign) {
// Huong LEN doc trong frame than, cung quy uoc TiltResidual: mf doc theo mui,
// ml doc sang trai.
const double mf = -std::tan(pitch);
const double ml = std::tan(roll) / std::max(1e-6, std::cos(pitch));
const double up = std::atan2(ml, mf);
const double down = up > 0.0 ? up - M_PI : up + M_PI;
const double turn = std::fabs(up) <= std::fabs(down) ? up : down;
if (misalign != nullptr) *misalign = std::fabs(turn);
return turn;
}
} // namespace vslam

View File

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

View File

@@ -3,10 +3,82 @@
#include <rtabmap/core/Optimizer.h> #include <rtabmap/core/Optimizer.h>
#include <rtabmap/core/Parameters.h> #include <rtabmap/core/Parameters.h>
#include <set>
#include "vslam/log.h" #include "vslam/log.h"
namespace vslam { namespace vslam {
namespace {
const char* const kProfileNames[] = {"sim", "real"};
// Doc va KIEM khoi `profiles:`. Ba luat de hai moi truong khong bao gio dung
// nhau hay lech nhau:
// 1. Dung hai khoi `sim` va `real`, du ca hai.
// 2. Hai khoi CUNG tap key -- sua mot ben quen ben kia la loi khoi dong,
// khong phai mot lan chay sai tren robot.
// 3. Key trong profiles KHONG nam o phan chung -- mot key, mot cho. Neu
// khong, doc file se khong biet gia tri nao dang chay.
void LoadProfiles(const ConfigNode& node, const ConfigNode& block, RtabmapConfig* cfg) {
for (const std::string& k : block.Keys()) {
if (k != "sim" && k != "real") {
throw ConfigError("profiles: khoi la '" + k + "' -- chi co sim va real");
}
}
std::set<std::string> keys[2];
for (int i = 0; i < 2; ++i) {
const std::string name = kProfileNames[i];
const ConfigNode p = block[name];
if (p.IsNull()) {
throw ConfigError("profiles: thieu khoi '" + name + "' -- can ca sim va real");
}
SlamProfile sp;
for (const std::string& k : p.Keys()) {
if (k == "odom_sigma_m" || k == "odom_sigma_rad") {
if (!node[k].IsNull()) {
throw ConfigError(k + " vua o phan chung vua o profiles." + name +
" -- mot key chi duoc o mot cho");
}
const double v = p.get<double>(k, 0.0);
if (!(v > 0.0)) {
throw ConfigError("profiles." + name + "." + k + " phai > 0");
}
sp.numbers[k] = v;
keys[i].insert(k);
} else if (k == "rtabmap") {
for (const auto& kv : p["rtabmap"].AsStringMap()) {
if (cfg->overrides.count(kv.first) != 0) {
throw ConfigError("rtabmap " + kv.first + " vua o khoi rtabmap chung vua o "
"profiles." + name + " -- mot key chi duoc o mot cho");
}
sp.rtabmap[kv.first] = kv.second;
keys[i].insert("rtabmap." + kv.first);
}
} else {
throw ConfigError("profiles." + name + ": khoa la '" + k +
"' -- chi co odom_sigma_m, odom_sigma_rad, rtabmap");
}
}
cfg->profiles[name] = sp;
}
if (keys[0] != keys[1]) {
std::string diff;
for (int i = 0; i < 2; ++i) {
for (const std::string& k : keys[i]) {
if (keys[1 - i].count(k) == 0) {
diff += " " + k + " (chi co o " + kProfileNames[i] + ")";
}
}
}
throw ConfigError("profiles: sim va real phai co CUNG tap key, lech:" + diff);
}
}
} // namespace
const char* SlamModeName(SlamMode m) { const char* SlamModeName(SlamMode m) {
switch (m) { switch (m) {
case SlamMode::kMapping: return "mapping"; case SlamMode::kMapping: return "mapping";
@@ -166,7 +238,29 @@ RtabmapConfig LoadRtabmapConfig(const ConfigNode& node) {
if (!block.IsNull()) { if (!block.IsNull()) {
for (const auto& kv : block.AsStringMap()) cfg.overrides[kv.first] = kv.second; for (const auto& kv : block.AsStringMap()) cfg.overrides[kv.first] = kv.second;
} }
// SAU khoi rtabmap chung: luat "mot key, mot cho" can biet phan chung co gi.
const ConfigNode profiles = node["profiles"];
if (!profiles.IsNull()) LoadProfiles(node, profiles, &cfg);
return cfg; return cfg;
} }
StatusResponse ApplySlamProfile(const std::string& name, RtabmapConfig* cfg) {
const auto it = cfg->profiles.find(name);
if (it == cfg->profiles.end()) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml: khong co profiles." + name + " -- can khoi `profiles:` voi ca sim "
"va real, neu khong sigma odom va ICP chay bang mac dinh cua code");
}
for (const auto& kv : it->second.numbers) {
if (kv.first == "odom_sigma_m") cfg->odom_sigma_m = kv.second;
else if (kv.first == "odom_sigma_rad") cfg->odom_sigma_rad = kv.second;
}
// Ten key RTAB-Map duoc kiem o BuildRtabmapParams, nhu moi key trong
// overrides.
for (const auto& kv : it->second.rtabmap) cfg->overrides[kv.first] = kv.second;
return StatusResponse::Ok();
}
} // namespace vslam } // namespace vslam

View File

@@ -1,14 +1,19 @@
#include "vslam/rtabmap_slam.h" #include "vslam/rtabmap_slam.h"
#include <rtabmap/core/Memory.h>
#include <rtabmap/core/Optimizer.h> #include <rtabmap/core/Optimizer.h>
#include <rtabmap/core/Parameters.h> #include <rtabmap/core/Parameters.h>
#include <rtabmap/core/RegistrationIcp.h>
#include <rtabmap/core/Rtabmap.h> #include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/Statistics.h> #include <rtabmap/core/Statistics.h>
#include <rtabmap/utilite/ULogger.h> #include <rtabmap/utilite/ULogger.h>
#include <algorithm> #include <algorithm>
#include <cmath>
#include <chrono> #include <chrono>
#include <mutex> #include <mutex>
#include <set>
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/log.h" #include "vslam/log.h"
@@ -43,6 +48,14 @@ class RtabmapSlamImpl {
// Diem depth theo node cho ban do voxel. Chi ExportVoxels (luong slam) cham. // Diem depth theo node cho ban do voxel. Chi ExportVoxels (luong slam) cham.
VoxelNodeCache voxel_cache; 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) { void RecordMs(double ms) {
stats.last_ms = ms; stats.last_ms = ms;
stats.max_ms = std::max(stats.max_ms, ms); stats.max_ms = std::max(stats.max_ms, ms);
@@ -77,6 +90,10 @@ const std::string& RtabmapSlam::database_path() const {
return impl_->cfg.database_path; return impl_->cfg.database_path;
} }
std::map<std::string, std::string> RtabmapSlam::rtabmap_parameters() const {
return impl_->rtabmap.getParameters();
}
Pose2D RtabmapSlam::map_correction() const { Pose2D RtabmapSlam::map_correction() const {
std::lock_guard<std::mutex> lk(impl_->out_mu); std::lock_guard<std::mutex> lk(impl_->out_mu);
return impl_->map_correction; return impl_->map_correction;
@@ -280,6 +297,15 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
in.camera_to_base != nullptr ? *in.camera_to_base in.camera_to_base != nullptr ? *in.camera_to_base
: impl_->camera_to_base, : impl_->camera_to_base,
impl_->next_id++); 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. // Phuong sai odom: nguoi goi dat thi dung, khong thi lay tu slam.yaml.
const double lin_var = in.odom_linear_var > 0.0 const double lin_var = in.odom_linear_var > 0.0
@@ -317,6 +343,12 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
} }
impl_->stats.frames_processed++; 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(); out.loop_closure_id = impl_->rtabmap.getLoopClosureId();
const rtabmap::Statistics& st = impl_->rtabmap.getStatistics(); const rtabmap::Statistics& st = impl_->rtabmap.getStatistics();
auto stat = [&](const std::string& k, double dflt) { auto stat = [&](const std::string& k, double dflt) {
@@ -375,9 +407,237 @@ StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt,
if (!impl_->inited) { if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init"); 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); 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(),
t.r31(), t.r32(), t.r33(), t.z(), 0, 0, 0, 1);
}
} // namespace
std::vector<int> RtabmapSlam::MapNodeIds() const {
std::vector<int> out;
if (!impl_->inited) return out;
for (const auto& kv : impl_->rtabmap.getLocalOptimizedPoses()) out.push_back(kv.first);
return out;
}
StatusResponse RtabmapSlam::GetNodeView(int id, bool with_depth, NodeView* out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
const std::map<int, rtabmap::Transform>& poses = impl_->rtabmap.getLocalOptimizedPoses();
const auto it = poses.find(id);
if (it == poses.end() || it->second.isNull()) {
return StatusResponse::Error(StatusCode::kNotFound, "node khong co pose toi uu");
}
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
if (mem == nullptr) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "rtabmap chua co Memory");
}
rtabmap::SensorData d = mem->getNodeData(id, true, false, false, false);
cv::Mat img, depth;
d.uncompressData(&img, with_depth ? &depth : nullptr); // du lieu trong DB la du lieu NEN
if (img.empty() || d.cameraModels().empty()) {
return StatusResponse::Error(StatusCode::kNotFound, "node khong co anh");
}
const rtabmap::CameraModel& cm = d.cameraModels()[0];
out->gray = img;
out->depth = depth;
out->K = cv::Matx33d(cm.fx(), 0, cm.cx(), 0, cm.fy(), cm.cy(), 0, 0, 1);
out->T_base_optical = ToMatx44(cm.localTransform());
out->T_map_base = ToMatx44(it->second);
return StatusResponse::Ok();
}
StatusResponse RtabmapSlam::Close(bool save_database) { StatusResponse RtabmapSlam::Close(bool save_database) {
if (!impl_->inited) return StatusResponse::Ok(); if (!impl_->inited) return StatusResponse::Ok();
impl_->inited = false; impl_->inited = false;

View File

@@ -0,0 +1,480 @@
#include "vslam/slope_test.h"
#include <algorithm>
#include <cmath>
#include <sstream>
#include "vslam/geometry.h"
namespace vslam {
const char* SlopeTestPhaseName(SlopeTestPhase p) {
switch (p) {
case SlopeTestPhase::kIdle: return "chua co duong";
case SlopeTestPhase::kFace: return "quay mat xuong doc";
case SlopeTestPhase::kWaitStart: return "cho bam bat dau";
case SlopeTestPhase::kTurn: return "quay theo luot";
case SlopeTestPhase::kDrive: return "dang chay";
case SlopeTestPhase::kDwell: return "dung do";
case SlopeTestPhase::kPaused: return "tam dung";
case SlopeTestPhase::kHalted: return "dung han";
case SlopeTestPhase::kDone: return "xong";
}
return "?";
}
// ---------------------------------------------------------------------------
// Lap duong
// ---------------------------------------------------------------------------
bool PlanSlopePath(double x, double y, const FloorFn& floor, const FreeFn& free,
const SlopePathConfig& cfg, SlopePath* out, std::string* why,
std::string* diag) {
double z0 = 0.0;
if (!floor(x, y, &z0)) {
*why = "khong biet do cao san cho robot dung (ban do khong co z node? slope.enabled?)";
return false;
}
// San PHANG tai (px, py): do doc bang sai phan +-level_h theo x va y. Chi nhin
// z doc theo tia la khong du: di CHEO tren doc 10 do thi z doi cham, trong
// nhu phang (sim 08/10: chon duong ngang doc, xuong 0.2 m).
const double level_tan = std::tan(cfg.level_deg * M_PI / 180.0);
auto level = [&](double px, double py) {
double zx0 = 0.0, zx1 = 0.0, zy0 = 0.0, zy1 = 0.0;
const double h = cfg.level_h;
if (!floor(px - h, py, &zx0) || !floor(px + h, py, &zx1) || !floor(px, py - h, &zy0) ||
!floor(px, py + h, &zy1)) {
return false;
}
return std::hypot(zx1 - zx0, zy1 - zy0) / (2.0 * h) < level_tan;
};
struct Cand {
double th, len, drop;
};
std::vector<Cand> ok;
std::ostringstream fan;
double best_drop_seen = 0.0;
const int nh = std::max(8, static_cast<int>(std::lround(360.0 / cfg.heading_step_deg)));
for (int k = 0; k < nh; ++k) {
const double th = NormalizeAngle(2.0 * M_PI * k / nh);
const double c = std::cos(th), s = std::sin(th);
std::vector<double> ss, zs;
const char* stop = "max";
for (double d = cfg.step; d <= cfg.max_len + 1e-9; d += cfg.step) {
const double px = x + c * d, py = y + s * d;
if (!free(px, py)) {
stop = "vc";
break;
}
double z = 0.0;
if (!floor(px, py, &z)) {
stop = "ks";
break;
}
ss.push_back(d);
zs.push_back(z);
}
if (ss.empty()) continue;
const double s_end = ss.back();
double drop_here = 0.0;
for (const double z : zs) drop_here = std::max(drop_here, z0 - z);
best_drop_seen = std::max(best_drop_seen, drop_here);
if (drop_here < cfg.min_drop) continue;
// Chan doc: diem DAU TIEN da xuong >= min_drop ma flat_len tiep theo PHANG.
const char* res = "khong phang";
for (size_t i = 0; i < ss.size(); ++i) {
if (z0 - zs[i] < cfg.min_drop) continue;
if (ss[i] + cfg.flat_len > s_end) {
res = "het duong";
break;
}
bool flat = true;
for (size_t j = i; j < ss.size() && ss[j] <= ss[i] + cfg.flat_len + 1e-9; ++j) {
if (!level(x + c * ss[j], y + s * ss[j])) {
flat = false;
break;
}
}
if (!flat) continue;
const double len = ss[i] + cfg.past_bottom;
if (len > s_end - cfg.stop_margin) {
res = "B sat vat can";
break;
}
double zb = zs[i];
floor(x + c * len, y + s * len, &zb);
ok.push_back(Cand{th, len, z0 - zb});
res = "OK";
break;
}
fan << " " << std::lround(th * 180.0 / M_PI) << "d:" << s_end << "m:" << stop << ":" << res;
}
if (diag != nullptr) *diag = fan.str();
if (ok.empty()) {
std::ostringstream os;
os << "khong thay doc tu cho robot dung (xuong toi da " << best_drop_seen << " m, can >= "
<< cfg.min_drop << " m roi PHANG " << cfg.flat_len << " m truoc vat can) -- dat robot gan "
<< "dinh doc hon. Huong:duong trong:dung vi (vc vat can, ks khong biet san):ket qua --"
<< fan.str();
*why = os.str();
return false;
}
// Uu tien xuong HET doc (>= 80% do sut lon nhat) -- loai duong cheo / ngang chi
// cat qua mep doc; roi NGAN NHAT = truc doc. Doc rong: mot dai huong gan truc
// ngan bang nhau (luong tu 10 cm) -- lay huong GIUA cua dai do.
double max_drop = 0.0;
for (const Cand& c : ok) max_drop = std::max(max_drop, c.drop);
double min_len = 1e9;
for (const Cand& c : ok) {
if (c.drop >= 0.8 * max_drop) min_len = std::min(min_len, c.len);
}
double sx = 0.0, sy = 0.0;
for (const Cand& c : ok) {
if (c.drop < 0.8 * max_drop || c.len > min_len + 0.05) continue;
sx += std::cos(c.th);
sy += std::sin(c.th);
}
const double th = std::atan2(sy, sx);
const double ux = std::cos(th), uy = std::sin(th);
// Day doc B: di lai theo HUONG DA CHON (huong trung binh co the lech vai do).
double b_len = -1.0;
{
std::vector<double> ss, zs;
for (double d = cfg.step; d <= cfg.max_len + 1e-9; d += cfg.step) {
double z = 0.0;
if (!free(x + ux * d, y + uy * d) || !floor(x + ux * d, y + uy * d, &z)) break;
ss.push_back(d);
zs.push_back(z);
}
for (size_t i = 0; i < ss.size() && b_len < 0.0; ++i) {
if (z0 - zs[i] < cfg.min_drop || ss[i] + cfg.flat_len > ss.back()) continue;
bool flat = true;
for (size_t j = i; j < ss.size() && ss[j] <= ss[i] + cfg.flat_len + 1e-9; ++j) {
if (!level(x + ux * ss[j], y + uy * ss[j])) {
flat = false;
break;
}
}
if (flat && ss[i] + cfg.past_bottom <= ss.back() - cfg.stop_margin) {
b_len = ss[i] + cfg.past_bottom;
}
}
}
if (b_len < 0.0) {
*why = "huong trung binh cua truc doc khong toi duoc chan doc phang -- dat robot thang truc doc hon";
return false;
}
// Dinh doc A: robot co the DANG o giua doc (dinh vi lai tu chay toi 1 m moi
// lan, sim 08/10: 3.5 m). Di NGUOC len theo truc toi cho phang flat_len, roi
// them past_bottom. Robot da o cho phang thi A = cho robot.
double a_back = 0.0;
bool at_top = true;
for (double d = 0.0; d <= cfg.flat_len + 1e-9; d += cfg.step) {
if (!level(x - ux * d, y - uy * d)) {
at_top = false;
break;
}
}
if (!at_top) {
bool found = false;
for (double d = cfg.step; d <= cfg.max_len + 1e-9 && !found; d += cfg.step) {
if (!free(x - ux * d, y - uy * d)) break;
bool flat = true;
for (double e = d; e <= d + cfg.flat_len + 1e-9; e += cfg.step) {
if (!level(x - ux * e, y - uy * e)) {
flat = false;
break;
}
}
if (flat) {
a_back = d + cfg.past_bottom;
found = true;
}
}
if (!found) {
*why = "dang o giua doc ma khong tim thay dinh doc phang phia tren -- dat robot o dinh doc";
return false;
}
for (double d = cfg.step; d <= a_back + 1e-9; d += cfg.step) {
if (!free(x - ux * d, y - uy * d)) {
*why = "duong len dinh doc vuong vat can -- dat robot o dinh doc";
return false;
}
}
}
out->a = Pose2D{x - ux * a_back, y - uy * a_back, th};
out->bx = x + ux * b_len;
out->by = y + uy * b_len;
out->length = a_back + b_len;
double za = z0, zb = z0;
floor(out->a.x, out->a.y, &za);
floor(out->bx, out->by, &zb);
out->drop = za - zb;
return true;
}
// ---------------------------------------------------------------------------
// May trang thai
// ---------------------------------------------------------------------------
SlopeTest::SlopeTest(SlopeTestConfig cfg) : cfg_(std::move(cfg)) {
if (cfg_.speeds.empty()) cfg_.speeds.push_back(0.2);
if (cfg_.loops < 1) cfg_.loops = 1;
}
void SlopeTest::SetPath(const SlopePath& p, bool autostart) {
path_ = p;
autostart_ = autostart;
phase_ = SlopeTestPhase::kFace;
loop_ = 0;
down_ = true;
have_prev_ = false;
approach_ = false;
approached_ = false;
leg_t0_ = 0.0;
halt_.clear();
}
double SlopeTest::speed() const {
if (approach_) return cfg_.approach_speed;
const size_t i = loop_ > 0 ? static_cast<size_t>(loop_ - 1) % cfg_.speeds.size() : 0;
return cfg_.speeds[i];
}
void SlopeTest::BeginLeg(double t) {
if (down_) {
from_x_ = path_.a.x;
from_y_ = path_.a.y;
to_x_ = path_.bx;
to_y_ = path_.by;
} else {
from_x_ = path_.bx;
from_y_ = path_.by;
to_x_ = path_.a.x;
to_y_ = path_.a.y;
}
heading_ = std::atan2(to_y_ - from_y_, to_x_ - from_x_);
len_ = std::hypot(to_x_ - from_x_, to_y_ - from_y_);
along_ = 0.0;
cross_ = 0.0;
phase_ = SlopeTestPhase::kTurn;
leg_t0_ = t;
}
SlopeTestOutput SlopeTest::Halt(const std::string& why) {
phase_ = SlopeTestPhase::kHalted;
halt_ = why;
SlopeTestOutput o;
o.command = true; // MOT lenh dung, roi im
o.event = "DUNG HAN -- " + why;
return o;
}
bool SlopeTest::Unsafe(const SlopeTestInput& in, std::string* why) const {
if (!in.localized) {
*why = "mat dinh vi / scan khong khop ban do";
return true;
}
const double tilt = cfg_.tilt_max_deg * M_PI / 180.0;
if (std::fabs(in.roll) > tilt || std::fabs(in.pitch) > tilt) {
std::ostringstream os;
os << "nghieng qua " << cfg_.tilt_max_deg << " do (roll " << in.roll * 180.0 / M_PI
<< ", pitch " << in.pitch * 180.0 / M_PI << ")";
*why = os.str();
return true;
}
if (have_prev_) {
const double j = std::hypot(in.pose.x - prev_.x, in.pose.y - prev_.y);
if (j > cfg_.jump_max) {
std::ostringstream os;
os << "pose nhay " << j << " m trong mot buoc (dinh vi sai?)";
*why = os.str();
return true;
}
}
return false;
}
SlopeTestOutput SlopeTest::Step(const SlopeTestInput& in) {
SlopeTestOutput o;
const double tol = cfg_.turn_tol_deg * M_PI / 180.0;
auto turn = [&](double err) {
double w = std::max(-cfg_.turn_rate, std::min(cfg_.turn_rate, cfg_.k_heading * err));
if (std::fabs(w) < cfg_.turn_min) w = std::copysign(cfg_.turn_min, err);
return w;
};
auto leg_name = [&]() {
std::ostringstream os;
if (approach_) {
os << "ve dinh doc (A) " << speed() << " m/s";
return os.str();
}
os << "luot " << loop_ << "/" << cfg_.loops << " " << (down_ ? "XUONG" : "LEN") << " "
<< speed() << " m/s";
return os.str();
};
switch (phase_) {
case SlopeTestPhase::kIdle:
case SlopeTestPhase::kHalted:
case SlopeTestPhase::kDone:
return o; // im
case SlopeTestPhase::kPaused:
if (in.start) {
// Chay tiep: dang chay / quay thi quay lai theo huong luot roi chay tiep.
phase_ = paused_from_ == SlopeTestPhase::kDrive ? SlopeTestPhase::kTurn : paused_from_;
if (phase_ == SlopeTestPhase::kDwell) dwell_t0_ = in.t;
leg_t0_ = in.t;
have_prev_ = false;
o.event = "chay tiep (" + std::string(SlopeTestPhaseName(phase_)) + ").";
}
return o;
case SlopeTestPhase::kWaitStart:
if (in.start) {
loop_ = 1;
down_ = true;
BeginLeg(in.t);
have_prev_ = false;
o.event = "BAT DAU " + leg_name();
}
return o;
default:
break;
}
// Cac pha DANG ra lenh: nguoi lai thi nhuong ngay, im cho toi khi bam tiep.
if (in.human) {
paused_from_ = phase_;
phase_ = SlopeTestPhase::kPaused;
o.event = "nguoi dang lai -- TAM DUNG. Bam Y de chay tiep.";
return o;
}
std::string why;
if (Unsafe(in, &why)) return Halt(why);
prev_ = in.pose;
have_prev_ = true;
o.command = true; // tu day: luon ghi lenh (ke ca 0 = giu dung)
switch (phase_) {
case SlopeTestPhase::kFace: {
// Lan dau: robot khong o A (dinh vi lai tu chay ra giua doc) -> ve A truoc.
if (!approached_) {
approached_ = true;
const double d = std::hypot(path_.a.x - in.pose.x, path_.a.y - in.pose.y);
if (d > 1.5 * cfg_.arrive_tol) {
approach_ = true;
from_x_ = in.pose.x;
from_y_ = in.pose.y;
to_x_ = path_.a.x;
to_y_ = path_.a.y;
heading_ = std::atan2(to_y_ - from_y_, to_x_ - from_x_);
len_ = d;
along_ = cross_ = 0.0;
phase_ = SlopeTestPhase::kTurn;
leg_t0_ = in.t;
std::ostringstream os;
os << "robot cach dinh doc (A) " << d << " m -- chay CHAM ve A truoc.";
o.event = os.str();
return o;
}
}
const double err = NormalizeAngle(path_.a.theta - in.pose.theta);
if (std::fabs(err) < tol) {
std::ostringstream os;
os << "da quay mat xuong doc (xuong " << path_.drop << " m, dai " << path_.length << " m). ";
if (autostart_) {
loop_ = 1;
down_ = true;
BeginLeg(in.t);
os << "Tu chay (mo phong): " << leg_name();
} else {
phase_ = SlopeTestPhase::kWaitStart;
os << "Bam Y de chay " << cfg_.loops << " luot.";
}
o.event = os.str();
return o;
}
if (in.t - leg_t0_ > 30.0 && leg_t0_ > 0.0) return Halt("quay mat xuong doc qua 30 s");
if (leg_t0_ <= 0.0) leg_t0_ = in.t;
o.w = turn(err);
return o;
}
case SlopeTestPhase::kTurn: {
const double err = NormalizeAngle(heading_ - in.pose.theta);
if (std::fabs(err) < tol) {
phase_ = SlopeTestPhase::kDrive;
leg_t0_ = in.t;
return o;
}
if (in.t - leg_t0_ > 30.0) return Halt("quay dau qua 30 s (vat can chan quay?)");
o.w = turn(err);
return o;
}
case SlopeTestPhase::kDrive: {
const double ux = std::cos(heading_), uy = std::sin(heading_);
const double rx = in.pose.x - from_x_, ry = in.pose.y - from_y_;
along_ = rx * ux + ry * uy;
cross_ = ux * ry - uy * rx;
if (std::fabs(cross_) > cfg_.cross_max) {
std::ostringstream os;
os << "lech khoi duong " << cross_ << " m (" << leg_name() << ")";
return Halt(os.str());
}
const double timeout = 2.0 * len_ / std::max(speed(), 0.05) + cfg_.leg_timeout_extra;
if (in.t - leg_t0_ > timeout) {
std::ostringstream os;
os << "qua " << timeout << " s ma chua toi dau doc (" << leg_name() << ")";
return Halt(os.str());
}
const double d = len_ - along_;
if (d <= cfg_.arrive_tol && approach_) {
approach_ = false;
phase_ = SlopeTestPhase::kFace;
leg_t0_ = in.t;
o.event = "da ve dinh doc (A).";
return o;
}
if (d <= cfg_.arrive_tol) {
phase_ = SlopeTestPhase::kDwell;
dwell_t0_ = in.t;
std::ostringstream os;
os << leg_name() << ": toi " << (down_ ? "CHAN" : "DINH") << " doc sau " << in.t - leg_t0_
<< " s, lech ngang " << cross_ * 100.0 << " cm";
o.event = os.str();
return o;
}
const double psi_d = heading_ - std::atan(cfg_.k_cross * cross_);
const double err = NormalizeAngle(psi_d - in.pose.theta);
o.w = std::max(-cfg_.max_w, std::min(cfg_.max_w, cfg_.k_heading * err));
if (std::fabs(err) < cfg_.drive_turn_deg * M_PI / 180.0) {
o.v = std::max(cfg_.min_speed, speed() * std::min(1.0, d / cfg_.slow_zone));
}
return o;
}
case SlopeTestPhase::kDwell: {
if (in.t - dwell_t0_ < cfg_.dwell_s) return o; // dung yen
if (down_) {
down_ = false;
} else if (loop_ >= cfg_.loops) {
phase_ = SlopeTestPhase::kDone;
std::ostringstream os;
os << "XONG " << cfg_.loops << " luot.";
o.event = os.str();
return o;
} else {
++loop_;
down_ = true;
}
BeginLeg(in.t);
o.event = "bat dau " + leg_name();
return o;
}
default:
return o;
}
}
} // namespace vslam

View File

@@ -0,0 +1,75 @@
#include "vslam/visual_verifier.h"
#include <algorithm>
#include <cmath>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc.hpp>
namespace vslam {
VisualVerifier::VisualVerifier(const VisualVerifierConfig& cfg)
: cfg_(cfg),
orb_(cv::ORB::create(cfg.orb_features, 1.2f, 8, 31, 0, 2, cv::ORB::HARRIS_SCORE, 31,
cfg.fast_threshold)) {}
VisualFrame VisualVerifier::Extract(const cv::Mat& gray) const {
VisualFrame f;
cv::Mat g = gray, eq;
if (g.channels() == 3) cv::cvtColor(gray, g, cv::COLOR_BGR2GRAY);
cv::createCLAHE(cfg_.clahe_clip, cv::Size(cfg_.clahe_grid, cfg_.clahe_grid))->apply(g, eq);
orb_->detectAndCompute(eq, cv::noArray(), f.kp, f.des);
return f;
}
PnpResult VisualVerifier::Solve(const VisualFrame& q, const VisualFrame& m,
const cv::Matx44d& T_map_base_m) const {
PnpResult r;
if (q.des.empty() || m.des.empty() || q.kp.size() < 8 || m.kp.size() < 8 || m.depth.empty()) {
return r;
}
std::vector<std::vector<cv::DMatch>> knn;
cv::BFMatcher(cv::NORM_HAMMING).knnMatch(q.des, m.des, knn, 2);
const cv::Matx44d Twm = T_map_base_m * m.T_base_optical; // map <- optical cua anh ban do
const double fx = m.K(0, 0), fy = m.K(1, 1), cx = m.K(0, 2), cy = m.K(1, 2);
std::vector<cv::Point3d> obj;
std::vector<cv::Point2d> img;
for (const auto& p : knn) {
if (p.size() < 2 || p[0].distance >= cfg_.ratio * p[1].distance) continue;
++r.matches;
const cv::Point2f uv = m.kp[p[0].trainIdx].pt;
const int row = static_cast<int>(std::lround(uv.y)), col = static_cast<int>(std::lround(uv.x));
if (row < 0 || col < 0 || row >= m.depth.rows || col >= m.depth.cols) continue;
const double z = m.depth.type() == CV_16UC1 ? m.depth.at<uint16_t>(row, col) * 0.001
: static_cast<double>(m.depth.at<float>(row, col));
if (!(z > cfg_.depth_min_m && z < cfg_.depth_max_m)) continue;
const cv::Vec4d pc((uv.x - cx) * z / fx, (uv.y - cy) * z / fy, z, 1.0);
const cv::Vec4d pw = Twm * pc;
obj.emplace_back(pw[0], pw[1], pw[2]);
img.emplace_back(q.kp[p[0].queryIdx].pt);
}
if (static_cast<int>(obj.size()) < cfg_.min_points) return r;
cv::Mat rvec, tvec;
std::vector<int> inl;
const bool ok = cv::solvePnPRansac(obj, img, cv::Mat(q.K), cv::noArray(), rvec, tvec, false,
cfg_.ransac_iters, static_cast<float>(cfg_.reproj_px),
cfg_.confidence, inl, cv::SOLVEPNP_EPNP);
if (!ok || inl.empty()) return r;
cv::Mat R;
cv::Rodrigues(rvec, R);
cv::Matx44d Tcw = cv::Matx44d::eye(); // optical <- map
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) Tcw(i, j) = R.at<double>(i, j);
Tcw(i, 3) = tvec.at<double>(i);
}
const cv::Matx44d Twb = Tcw.inv() * q.T_base_optical.inv(); // map <- base cua anh hoi
r.inliers = static_cast<int>(inl.size());
r.x = Twb(0, 3);
r.y = Twb(1, 3);
r.yaw = std::atan2(Twb(1, 0), Twb(0, 0));
r.dz = Twb(2, 3);
r.tilt_deg = std::acos(std::max(-1.0, std::min(1.0, Twb(2, 2)))) * 180.0 / M_PI;
return r;
}
} // namespace vslam

View File

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

View File

@@ -0,0 +1,36 @@
#include "vslam/vpr_encoder.h"
#include <opencv2/imgproc.hpp>
namespace vslam {
void VprPreprocess(const cv::Mat& gray, const VprConfig& cfg, std::vector<float>* chw) {
static const float kMean[3] = {0.485f, 0.456f, 0.406f};
static const float kStd[3] = {0.229f, 0.224f, 0.225f};
cv::Mat g = gray;
if (g.channels() == 3) cv::cvtColor(gray, g, cv::COLOR_BGR2GRAY);
cv::Mat eq, rs;
cv::createCLAHE(cfg.clahe_clip, cv::Size(cfg.clahe_grid, cfg.clahe_grid))->apply(g, eq);
cv::resize(eq, rs, cv::Size(cfg.width, cfg.height), 0, 0, cv::INTER_LINEAR);
const size_t plane = static_cast<size_t>(cfg.width) * static_cast<size_t>(cfg.height);
chw->resize(3 * plane);
for (int c = 0; c < 3; ++c) {
float* dst = chw->data() + c * plane;
for (int y = 0; y < cfg.height; ++y) {
const uint8_t* src = rs.ptr<uint8_t>(y);
for (int x = 0; x < cfg.width; ++x) {
dst[static_cast<size_t>(y) * cfg.width + x] = (src[x] / 255.0f - kMean[c]) / kStd[c];
}
}
}
}
#ifndef VSLAM_HAVE_TENSORRT
StatusResponse CreateVprEncoder(const VprConfig&, std::unique_ptr<VprEncoder>* out) {
out->reset();
return StatusResponse::Error(StatusCode::kUnavailable,
"VPR can build voi -DVSLAM_WITH_TENSORRT=ON (chi Jetson)");
}
#endif
} // namespace vslam

View File

@@ -0,0 +1,150 @@
// CHI bien dich voi -DVSLAM_WITH_TENSORRT=ON (xem CMakeLists.txt).
#include "vslam/vpr_encoder.h"
#include <NvInfer.h>
#include <cuda_runtime_api.h>
#include <cmath>
#include <fstream>
#include <iterator>
#include <mutex>
#include "vslam/log.h"
namespace vslam {
namespace {
class TrtLogger : public nvinfer1::ILogger {
public:
void log(Severity s, const char* msg) noexcept override {
if (s <= Severity::kWARNING) VSLAM_WARN("tensorrt: " << msg);
}
};
// IRuntime giu tham chieu toi logger suot doi -> logger tinh.
TrtLogger& Logger() {
static TrtLogger l;
return l;
}
size_t Volume(const nvinfer1::Dims& d) {
size_t v = 1;
for (int i = 0; i < d.nbDims; ++i) v *= static_cast<size_t>(d.d[i]);
return v;
}
class TrtVprEncoder : public VprEncoder {
public:
~TrtVprEncoder() override {
if (d_in_ != nullptr) cudaFree(d_in_);
if (d_out_ != nullptr) cudaFree(d_out_);
if (stream_ != nullptr) cudaStreamDestroy(stream_);
// ctx_ -> engine_ -> runtime_ huy theo thu tu nguoc khai bao: dung thu tu TensorRT can.
}
StatusResponse Init(const VprConfig& cfg) {
cfg_ = cfg;
std::ifstream f(cfg.engine_path, std::ios::binary);
if (!f) {
return StatusResponse::Error(StatusCode::kNotFound,
"vpr: khong mo duoc engine " + cfg.engine_path +
" -- dung bang trtexec (xem vpr_encoder.h)");
}
const std::vector<char> blob((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
runtime_.reset(nvinfer1::createInferRuntime(Logger()));
if (!runtime_) return Err("createInferRuntime");
engine_.reset(runtime_->deserializeCudaEngine(blob.data(), blob.size()));
if (!engine_) return Err("deserializeCudaEngine -- engine dung cho may/TensorRT khac?");
ctx_.reset(engine_->createExecutionContext());
if (!ctx_) return Err("createExecutionContext");
for (int i = 0; i < engine_->getNbIOTensors(); ++i) {
const char* name = engine_->getIOTensorName(i);
if (engine_->getTensorDataType(name) != nvinfer1::DataType::kFLOAT) {
return Err(std::string("tensor ") + name + " khong phai float32");
}
const size_t n = Volume(engine_->getTensorShape(name));
if (engine_->getTensorIOMode(name) == nvinfer1::TensorIOMode::kINPUT) {
in_name_ = name;
in_elems_ = n;
} else {
out_name_ = name;
out_elems_ = n;
}
}
const size_t want = 3u * static_cast<size_t>(cfg.width) * static_cast<size_t>(cfg.height);
if (in_name_.empty() || out_name_.empty() || in_elems_ != want) {
return Err("engine co dau vao " + std::to_string(in_elems_) + " so, can " +
std::to_string(want) + " (3x" + std::to_string(cfg.height) + "x" +
std::to_string(cfg.width) + ")");
}
if (cudaStreamCreate(&stream_) != cudaSuccess ||
cudaMalloc(&d_in_, in_elems_ * sizeof(float)) != cudaSuccess ||
cudaMalloc(&d_out_, out_elems_ * sizeof(float)) != cudaSuccess) {
return Err("cap phat bo nho GPU");
}
if (!ctx_->setTensorAddress(in_name_.c_str(), d_in_) ||
!ctx_->setTensorAddress(out_name_.c_str(), d_out_)) {
return Err("setTensorAddress");
}
VSLAM_INFO("vpr: TensorRT engine " << cfg.engine_path << " -- vao " << in_name_ << " ("
<< in_elems_ << " so), ra " << out_name_ << " (" << out_elems_ << " chieu)");
return StatusResponse::Ok();
}
StatusResponse Describe(const cv::Mat& gray, std::vector<float>* desc) override {
if (gray.empty()) return StatusResponse::Error(StatusCode::kInvalidArgument, "vpr: anh rong");
std::lock_guard<std::mutex> lk(mu_);
VprPreprocess(gray, cfg_, &host_in_);
desc->resize(out_elems_);
if (cudaMemcpyAsync(d_in_, host_in_.data(), in_elems_ * sizeof(float),
cudaMemcpyHostToDevice, stream_) != cudaSuccess ||
!ctx_->enqueueV3(stream_) ||
cudaMemcpyAsync(desc->data(), d_out_, out_elems_ * sizeof(float),
cudaMemcpyDeviceToHost, stream_) != cudaSuccess ||
cudaStreamSynchronize(stream_) != cudaSuccess) {
return StatusResponse::Error(StatusCode::kInternal, "vpr: suy luan TensorRT loi");
}
// Mo hinh da L2 o lop cuoi, nhung fp16 lam lech chuan chut it -> chuan hoa lai.
double n2 = 0.0;
for (float v : *desc) n2 += static_cast<double>(v) * v;
const float inv = n2 > 0.0 ? static_cast<float>(1.0 / std::sqrt(n2)) : 0.0f;
for (float& v : *desc) v *= inv;
return StatusResponse::Ok();
}
int dim() const override { return static_cast<int>(out_elems_); }
private:
static StatusResponse Err(const std::string& m) {
return StatusResponse::Error(StatusCode::kInternal, "vpr: " + m);
}
VprConfig cfg_;
std::unique_ptr<nvinfer1::IRuntime> runtime_;
std::unique_ptr<nvinfer1::ICudaEngine> engine_;
std::unique_ptr<nvinfer1::IExecutionContext> ctx_;
std::string in_name_, out_name_;
size_t in_elems_ = 0, out_elems_ = 0;
void* d_in_ = nullptr;
void* d_out_ = nullptr;
cudaStream_t stream_ = nullptr;
std::vector<float> host_in_;
std::mutex mu_;
};
} // namespace
StatusResponse CreateVprEncoder(const VprConfig& cfg, std::unique_ptr<VprEncoder>* out) {
std::unique_ptr<TrtVprEncoder> e(new TrtVprEncoder);
const StatusResponse st = e->Init(cfg);
if (!st.ok()) {
out->reset();
return st;
}
*out = std::move(e);
return StatusResponse::Ok();
}
} // namespace vslam

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, void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
float quant_m, const Pose2D& delta, std::string* out); 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. // RLE hang-chinh. Xem rle.h.
// `type` cho phep dung chung bo ma hoa cho ban do SLAM (kMapFull) va ban do // `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 // 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. // 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, 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 // (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 // 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 DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out);
bool DecodeScan(const std::string& buf, LaserScan* 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 // 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 // goi lien tiep. `total`/`chunk_index`/`chunk_count`/`epoch` tra qua con tro

View File

@@ -13,6 +13,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "vslam/binary_codec.h"
#include "vslam/stats.h" #include "vslam/stats.h"
#include "vslam/vslam_common.h" #include "vslam/vslam_common.h"
@@ -52,6 +53,13 @@ struct SlamSnapshot {
std::string voxels_source = "off"; std::string voxels_source = "off";
uint32_t voxel_cells = 0; uint32_t voxel_cells = 0;
uint32_t voxel_epoch = 0; uint32_t voxel_epoch = 0;
// Trang thai dinh vi lai tu dong (--slam-reloc): "XOAY TAI CHO 120/300 do",
// "NHAP NHANG ... di chuyen roi xoay tiep", "DA DINH VI ...". Rong = khong bat.
std::string reloc;
// CHUA dinh vi xong: `pose` chi la vi tri DOAN (ung vien so 1 cua vong khop
// gan nhat, hoac odom tu 0 truoc vong dau) -> web ve robot MO + dong chu.
bool reloc_pending = false;
}; };
struct TeleopSnapshot { struct TeleopSnapshot {
@@ -131,6 +139,13 @@ struct WebSnapshot {
double pitch = 0.0; double pitch = 0.0;
bool accel_ok = true; 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 ============ // ============ GROUND TRUTH ============
// CHI co khi chay mo phong. Day la tuong duong cua /ground_truth/odom trong // 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". // repo cu, noi ghi ro "khong estimator nao duoc subscribe".
@@ -144,6 +159,7 @@ struct WebSnapshot {
Pose2D ground_truth; Pose2D ground_truth;
double gt_roll = 0.0; // nghieng THAT, de doi chung gravity_align double gt_roll = 0.0; // nghieng THAT, de doi chung gravity_align
double gt_pitch = 0.0; double gt_pitch = 0.0;
double gt_z = 0.0; // do cao san THAT duoi robot (world co doc)
SafetySnapshot safety; SafetySnapshot safety;
SlamSnapshot slam; SlamSnapshot slam;
@@ -166,6 +182,8 @@ struct WebSnapshot {
Pose2D cloud_delta; Pose2D cloud_delta;
bool have_cloud_delta = false; bool have_cloud_delta = false;
OccupancyGridPtr map; // ban do SLAM dung 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 // 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. // that -- luc do khong co su that nao de doi chieu.
OccupancyGridPtr world_map; 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, void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
BinaryType type) { BinaryType type, const MapFloorGrid* floor_grid) {
PutHeader(out, type, stamp); PutHeader(out, type, stamp);
PutF32(out, map.resolution); PutF32(out, map.resolution);
PutI32(out, static_cast<int32_t>(map.width)); 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)] = (*out)[run_count_off + static_cast<size_t>(i)] =
static_cast<char>((r32 >> (8 * i)) & 0xFF); 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 ------------------------------------------------------- // --- Ban do voxel 3D -------------------------------------------------------
@@ -333,9 +346,10 @@ bool DecodeScan(const std::string& buf, LaserScan* out) {
return true; return true;
} }
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) { bool DecodeMapFull(const std::string& buf, OccupancyGrid* out, MapFloorGrid* floor_grid) {
BinaryHeader h; BinaryHeader h;
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false; if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false;
if (floor_grid != nullptr) *floor_grid = MapFloorGrid{};
size_t o = kBinaryHeaderSize; size_t o = kBinaryHeaderSize;
if (buf.size() < o + 28) return false; 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; const size_t expected = static_cast<size_t>(out->width) * out->height;
if (!RleDecode(buf, o, runs, expected, &out->data)) return false; 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)); out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
return true; 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("x", s.pose_map.x, 3, out); Comma(out);
Num("y", s.pose_map.y, 3, out); Comma(out); Num("y", s.pose_map.y, 3, out); Comma(out);
Num("yaw", s.pose_map.theta, 4, 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); out->push_back('}'); Comma(out);
// Bu do tre cua scan: quy tia tu pose HIEN TAI ve pose LUC QUET. Cloud // 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("yaw", s.ground_truth.theta, 4, out); Comma(out);
Num("roll", s.gt_roll, 4, out); Comma(out); Num("roll", s.gt_roll, 4, out); Comma(out);
Num("pitch", s.gt_pitch, 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 // 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 // client tu tru: neu sau nay map va gt khac goc toa do thi phep tru
// ngay tren client se sai am tham. // ngay tren client se sai am tham.
@@ -192,6 +202,8 @@ void WriteStateJson(const WebSnapshot& s, std::string* out) {
// Ban do 3D: nguon va so o. Mot ban do voxel RONG phai doc duoc tu day, chu // Ban do 3D: nguon va so o. Mot ban do voxel RONG phai doc duoc tu day, chu
// khong phai bang cach mo khung 3D len roi doan. // khong phai bang cach mo khung 3D len roi doan.
Str("voxels_source", s.slam.voxels_source, out); Comma(out); Str("voxels_source", s.slam.voxels_source, out); Comma(out);
Str("reloc", s.slam.reloc, out); Comma(out);
Bool("reloc_pending", s.slam.reloc_pending, out); Comma(out);
Int("voxel_cells", static_cast<int>(s.slam.voxel_cells), out); Comma(out); Int("voxel_cells", static_cast<int>(s.slam.voxel_cells), out); Comma(out);
Int("voxel_epoch", static_cast<int>(s.slam.voxel_epoch), out); Int("voxel_epoch", static_cast<int>(s.slam.voxel_epoch), out);
out->push_back('}'); Comma(out); out->push_back('}'); Comma(out);

View File

@@ -830,7 +830,8 @@ void WebServer::Publish(const WebSnapshot& snap) {
if (s->acked_map_version() == snap.slam.map_version) continue; if (s->acked_map_version() == snap.slam.map_version) continue;
if (!buf) { if (!buf) {
buf = std::make_shared<std::string>(); 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->Send(buf, true, /*is_map=*/true);
s->set_acked_map_version(snap.slam.map_version); 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. // 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 // Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con
// cache ban cu". // cache ban cu".
const UI_VERSION = '2026-09-23d'; const UI_VERSION = '2026-10-07b';
// ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau. // ⚠️ 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; const T_WORLD_MAP = 6;
// Ban do voxel 3D: tap day du (chia manh) va phan them/bot. // Ban do voxel 3D: tap day du (chia manh) va phan them/bot.
const T_VOXEL_FULL = 7, T_VOXEL_DELTA = 8; 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. // 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) const R_NAN = 0xFFFF; // khong do duoc (duoi range_min)
@@ -229,7 +231,21 @@ function onBinary(dv) {
cells.fill(val, p, p + len); cells.fill(val, p, p + len);
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) { if (type === T_WORLD_MAP) {
// Ban do THE GIOI: su that, de lai cho chuan. KHONG lan vao state.map. // Ban do THE GIOI: su that, de lai cho chuan. KHONG lan vao state.map.
state.worldMap = grid; state.worldMap = grid;
@@ -377,6 +393,7 @@ function rasterize(map, pal) {
function onState(s) { function onState(s) {
state.pose = s.pose; state.pose = s.pose;
noteStatePose(s);
// Khong co truong nay = server khong bu duoc do tre scan. Dat null chu // Khong co truong nay = server khong bu duoc do tre scan. Dat null chu
// khong dat {0,0,0}: mot delta 0 gia mao la "da bu", con null thi lop ve // khong dat {0,0,0}: mot delta 0 gia mao la "da bu", con null thi lop ve
// biet la chua co gi va dung pose hien tai nhu truoc. // biet la chua co gi va dung pose hien tai nhu truoc.
@@ -394,9 +411,26 @@ function onState(s) {
// khong phan biet duoc "dung o goc" voi "khong biet". // khong phan biet duoc "dung o goc" voi "khong biet".
state.gt = s.gt || null; state.gt = s.gt || null;
txt('gtErr', s.gt ? fmt(s.gt.err, 3) + ' m' : '--'); 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; state.slamMode = s.slam.mode;
txt('mode', s.slam.mode); txt('mode', s.slam.mode);
state.relocPending = !!s.slam.reloc_pending;
state.relocText = s.slam.reloc || '';
// Dong chu DE LEN ca khung 2D lan 3D: robot MO ma khong co chu thi trong
// nhu loi (da xay ra 2026-09-29).
const bn = document.getElementById('relocBanner');
if (bn) {
bn.style.display = state.relocPending ? 'block' : 'none';
bn.textContent = 'CHUA DINH VI -- robot tam ve o CHO BAT DAU QUET, scan chua khop tuong -- ' +
(state.relocText || 'dang tu tim vi tri');
}
const st = s.safety.state; const st = s.safety.state;
const sv = document.getElementById('safeState'); const sv = document.getElementById('safeState');
@@ -432,10 +466,21 @@ function onState(s) {
txt('tAccel', s.tilt.accel_ok ? 'neo trong luc' : 'gyro thuan (troi)'); txt('tAccel', s.tilt.accel_ok ? 'neo trong luc' : 'gyro thuan (troi)');
} }
txt('loc', s.slam.localized ? 'co' : 'khong'); // Dinh vi lai tu dong (--slam-reloc) dang chay/vua chot thi hien trang thai
// cua no -- "co/khong" cua RTAB-Map vo nghia khi chua co pose ban dau.
txt('loc', s.slam.reloc ? s.slam.reloc : (s.slam.localized ? 'co' : 'khong'));
txt('score', fmt(s.slam.score, 2)); txt('score', fmt(s.slam.score, 2));
txt('pms', fmt(s.slam.process_ms, 0) + ' ms'); txt('pms', fmt(s.slam.process_ms, 0) + ' ms');
txt('mapver', String(s.slam.map_version)); txt('mapver', String(s.slam.map_version));
txt('vox', s.slam.voxels_source + ', ' + s.slam.voxel_cells + ' o');
// Lan DAU co voxel thi TU BAT lop "cloud da quet". Tat mac dinh la de khong
// ai tuong hong khi camera_3d tat; co du lieu roi ma van an moi la hong.
// Nguoi dung da tu bam o do thi khong dung vao.
if (s.slam.voxel_cells > 0 && !state.mapCloudAuto) {
state.mapCloudAuto = true;
const cb = document.getElementById('lyMapCloud');
if (cb && !state.mapCloudTouched) cb.checked = true;
}
txt('hzLidar', fmt(s.health.lidar_hz, 1)); txt('hzLidar', fmt(s.health.lidar_hz, 1));
txt('hzCam', fmt(s.health.camera_hz, 1)); txt('hzCam', fmt(s.health.camera_hz, 1));
@@ -571,6 +616,63 @@ function composePose(a, d) {
}; };
} }
// --- Pose HIEN THI: robot troi muot giua cac khung state ---------------------
//
// Server gui pose 10 Hz (system.yaml status_rate_hz) con trang ve ~60 Hz. Dat
// thang pose moi nhat thi robot NHAY tung buoc 100 ms -- 5 cm / 4.6 do o
// 0.5 m/s, 0.8 rad/s -- va nhay them moi lan SLAM chinh map_correction. O day:
// du doan theo van toc odom toi da DISP_LEAD_MAX giay, roi TRUOT ve dich voi
// hang so DISP_TAU. Xa hon DISP_SNAP (vua chot dinh vi lai) thi dat thang.
//
// CHI la hien thi: so lieu (px/py/pyaw, gap voi ground truth) van doc
// `state.pose` THAT.
const DISP_TAU = 0.05; // s
// KHONG du doan theo van toc (07/10): du doan 0.15 s lam robot VUOT qua roi giat
// lai moi lan dung quay (0.8 rad/s x 0.15 s = 7 do) -- roi mat.
const DISP_LEAD_MAX = 0.0; // s
const DISP_SNAP_M = 1.0, DISP_SNAP_RAD = 0.8;
const disp = { pose: null, t: 0, rx: 0, vx: 0, vyaw: 0 };
function wrapPi(a) { return Math.atan2(Math.sin(a), Math.cos(a)); }
// Giay, don dieu. `performance` co o moi trinh duyet, nhung KHONG co trong
// sandbox vm cua test/www -- lui ve Date.now().
function nowSec() {
return (typeof performance !== 'undefined' ? performance.now() : Date.now()) / 1000;
}
// Goi moi khung state: luc toi + van toc odom (he than robot).
function noteStatePose(s) {
disp.rx = nowSec();
const o = s.odom || {};
disp.vx = Math.max(-1.5, Math.min(1.5, Number(o.vx) || 0));
disp.vyaw = Math.max(-2.0, Math.min(2.0, Number(o.vyaw) || 0));
}
// Goi MOT lan moi khung ve (draw()).
function displayPose() {
const p = state.pose;
if (!p) return null;
const now = nowSec();
const lead = Math.min(Math.max(now - disp.rx, 0), DISP_LEAD_MAX);
const yaw = p.yaw + disp.vyaw * lead;
const mid = p.yaw + 0.5 * disp.vyaw * lead;
const tx = p.x + disp.vx * lead * Math.cos(mid);
const ty = p.y + disp.vx * lead * Math.sin(mid);
const d = disp.pose;
if (!d || Math.hypot(tx - d.x, ty - d.y) > DISP_SNAP_M ||
Math.abs(wrapPi(yaw - d.yaw)) > DISP_SNAP_RAD) {
disp.pose = { x: tx, y: ty, yaw: wrapPi(yaw) };
} else {
const a = 1 - Math.exp(-Math.max(now - disp.t, 0) / DISP_TAU);
d.x += a * (tx - d.x);
d.y += a * (ty - d.y);
d.yaw = wrapPi(d.yaw + a * wrapPi(yaw - d.yaw));
}
disp.t = now;
// z / nghieng / sigma: theo pose that, chi x-y-yaw duoc lam muot.
return { ...p, x: disp.pose.x, y: disp.pose.y, yaw: disp.pose.yaw };
}
// Pose de ve MOT LOP DU LIEU, khong phai pose robot. // Pose de ve MOT LOP DU LIEU, khong phai pose robot.
// //
// Moi lop toi theo nhip rieng (cloud 2 Hz, scan 10 Hz) con trang ve lai moi // Moi lop toi theo nhip rieng (cloud 2 Hz, scan 10 Hz) con trang ve lai moi
@@ -592,6 +694,11 @@ function anchorPose(robotPose, anchoredAt) {
x: robotPose.x + c * lx - s * ly, x: robotPose.x + c * lx - s * ly,
y: robotPose.y + s * lx + c * ly, y: robotPose.y + s * lx + c * ly,
yaw: robotPose.yaw + (anchoredAt.yaw - state.pose.yaw), 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,
}; };
} }
@@ -655,6 +762,9 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
// scan va cloud o frame robot -> xoay theo pose truoc khi ve. Nhung KHONG // scan va cloud o frame robot -> xoay theo pose truoc khi ve. Nhung KHONG
// phai pose hien tai: moi lop neo vao pose no thuoc ve, xem anchorPose(). // phai pose hien tai: moi lop neo vao pose no thuoc ve, xem anchorPose().
const p = robotPose; const p = robotPose;
// Scan / cloud neo theo pose THAT -- dinh vao tuong cua ban do. Neo theo pose
// lam muot (displayPose) thi chung lac quanh tuong moi khi quay (07/10: roi mat).
const anchor = robotPose === state.dispPose ? state.pose : robotPose;
if (p) { if (p) {
// Ground truth ve TRUOC pose uoc luong, de pose ve de len tren: cai ta // Ground truth ve TRUOC pose uoc luong, de pose ve de len tren: cai ta
@@ -665,7 +775,7 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
if (state.cloud && on('lyCloud')) { if (state.cloud && on('lyCloud')) {
// Cloud KHONG dung `p` -- xem anchorPose(). // Cloud KHONG dung `p` -- xem anchorPose().
const cp = anchorPose(p, state.cloudPose); const cp = anchorPose(anchor, state.cloudPose);
const cc = Math.cos(cp.yaw), cs = Math.sin(cp.yaw); const cc = Math.cos(cp.yaw), cs = Math.sin(cp.yaw);
const pts = state.cloud; const pts = state.cloud;
for (let i = 0; i < pts.length; i += 3) { for (let i = 0; i < pts.length; i += 3) {
@@ -690,7 +800,7 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
const ly = (state.robot && state.robot.laser_y) || 0; const ly = (state.robot && state.robot.laser_y) || 0;
// Neo vao pose LUC QUET, khong phai `p` -- xem anchorPose(). Khi quay // Neo vao pose LUC QUET, khong phai `p` -- xem anchorPose(). Khi quay
// 50 do/s thi 100 ms giu giua hai khung la 5 do, o 3 m la 26 cm. // 50 do/s thi 100 ms giu giua hai khung la 5 do, o 3 m la 26 cm.
const sp = anchorPose(p, state.scanPose); const sp = anchorPose(anchor, state.scanPose);
const sc = Math.cos(sp.yaw), ss = Math.sin(sp.yaw); const sc = Math.cos(sp.yaw), ss = Math.sin(sp.yaw);
for (let i = 0; i < pts.length; i += 2) { for (let i = 0; i < pts.length; i += 2) {
const bx = pts[i] + lx, by = pts[i + 1] + ly; const bx = pts[i] + lx, by = pts[i + 1] + ly;
@@ -700,7 +810,10 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
} }
} }
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, pal.robot, 1.0, pal); // Dang DINH VI LAI (--slam-reloc): robot TAM o goc map (odom tu 0) -> ve MO.
// Chot xong moi nhay ve cho that. Dong chu trang thai nam o #relocBanner.
const faded = state.relocPending && robotPose === state.dispPose;
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, pal.robot, faded ? 0.35 : 1.0, pal);
} }
} }
@@ -740,6 +853,9 @@ function updateSlamLabel() {
} }
function draw() { function draw() {
// Pose HIEN THI cho MOI khung ve duoi day -- tinh MOT lan moi khung hinh, vi
// displayPose() truot theo thoi gian giua hai lan goi.
state.dispPose = displayPose();
// Goi o DAY chu khong trong draw3d(): o so sanh uoc luong voi ground truth // Goi o DAY chu khong trong draw3d(): o so sanh uoc luong voi ground truth
// phai chay ca khi dang xem khung 2D. // phai chay ca khi dang xem khung 2D.
updateGapChip(); updateGapChip();
@@ -755,7 +871,7 @@ function draw() {
// Khung phai VAN phai chay khi dang chia doi. // Khung phai VAN phai chay khi dang chia doi.
if (split) { if (split) {
updateSlamLabel(); updateSlamLabel();
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap', drawScene(cvR, ctxR, state.map, state.mapImage, state.dispPose, true, 'lyMap',
PALETTE.slam); PALETTE.slam);
} else if (split3d) { } else if (split3d) {
// Khong co canvas thu hai o che do nay: draw3d() da ve ca hai nua. Chi // Khong co canvas thu hai o che do nay: draw3d() da ve ca hai nua. Chi
@@ -769,10 +885,10 @@ function draw() {
updateSlamLabel(); updateSlamLabel();
// TRAI = THE GIOI: ban do that + pose THAT. Day la khung de LAI. // TRAI = THE GIOI: ban do that + pose THAT. Day la khung de LAI.
drawScene(cv, ctx, state.worldMap, state.worldMapImage, drawScene(cv, ctx, state.worldMap, state.worldMapImage,
state.gt || state.pose, false, 'lyWorld', PALETTE.world); state.gt || state.dispPose, false, 'lyWorld', PALETTE.world);
// PHAI = SLAM: ban do dang dung + pose UOC LUONG. Khung de xem quet toi // PHAI = SLAM: ban do dang dung + pose UOC LUONG. Khung de xem quet toi
// dau, va lech bao nhieu so voi khung trai. // dau, va lech bao nhieu so voi khung trai.
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap', drawScene(cvR, ctxR, state.map, state.mapImage, state.dispPose, true, 'lyMap',
PALETTE.slam); PALETTE.slam);
} else { } else {
// Mot khung: uu tien ban do SLAM neu co, khong thi ban do the gioi. // Mot khung: uu tien ban do SLAM neu co, khong thi ban do the gioi.
@@ -780,7 +896,7 @@ function draw() {
drawScene(cv, ctx, drawScene(cv, ctx,
haveSlam ? state.map : state.worldMap, haveSlam ? state.map : state.worldMap,
haveSlam ? state.mapImage : state.worldMapImage, haveSlam ? state.mapImage : state.worldMapImage,
state.pose, true, haveSlam ? 'lyMap' : 'lyWorld', state.dispPose, true, haveSlam ? 'lyMap' : 'lyWorld',
haveSlam ? PALETTE.slam : PALETTE.world); haveSlam ? PALETTE.slam : PALETTE.world);
} }
requestAnimationFrame(draw); requestAnimationFrame(draw);
@@ -1015,10 +1131,24 @@ function sendCmd() {
ws.send(JSON.stringify({ t: 'cmd', vx: stick.vx, wz: stick.wz })); ws.send(JSON.stringify({ t: 'cmd', vx: stick.vx, wz: stick.wz }));
} }
// Chi gui khi DANG LAI; buong ra thi gui 0 them 1.5 s roi IM -- giong tay cam
// (gamepad.idle_publish_sec). Ban truoc gui 0 LIEN TUC ke ca khi dung yen, va
// vi web va tay cam cung ghi MOT `raw_cmd_` (ai ghi sau thang), mot tab web mo
// la tay cam khong bao gio lai duoc (robot that 2026-09-28: gamepad bao
// w=1 rad/s ma banh dung yen).
//
// Deadman van con: dang lai thi van gui deu 20 Hz, mat ket noi = base tu dung
// sau 300 ms. Im khi dung yen thi robot van dung yen (NO_CMD -> dung).
//
// -Infinity, KHONG phai 0: performance.now() bat dau tu 0 luc mo trang, nen 0 lam trang gui
// lenh 0 suot 1.5 s dau -- node tuong co NGUOI lai va dinh vi lai tu dong NHUONG 5 s (mo
// phong 2026-09-30, logs/sim_reloc_step4.log: nhuong 0.5 s sau khi bat dau, vong 1 chi quet
// duoc 272 do trong 30 s).
let lastMove = -Infinity;
setInterval(() => { setInterval(() => {
// Gui LIEN TUC ke ca khi dung yen: deadman o base can nhan duoc lenh deu const now = performance.now();
// dan de biet nguoi lai van con day. Ngung gui = base tu dung sau 300 ms. if (stick.vx !== 0 || stick.wz !== 0) lastMove = now;
sendCmd(); if (now - lastMove < 1500) sendCmd();
}, 50); }, 50);
// --- Do bang thong --------------------------------------------------------- // --- Do bang thong ---------------------------------------------------------
@@ -1096,6 +1226,9 @@ btnSplit.addEventListener('click', () => {
if (el) el.textContent = 'ui ' + UI_VERSION; if (el) el.textContent = 'ui ' + UI_VERSION;
console.log('vslam ui ' + UI_VERSION); console.log('vslam ui ' + UI_VERSION);
} }
document.getElementById('lyMapCloud').addEventListener('change', () => {
state.mapCloudTouched = true;
});
const cv3d = document.getElementById('main3d'); const cv3d = document.getElementById('main3d');
const btn3d = document.getElementById('btn3d'); const btn3d = document.getElementById('btn3d');
@@ -1188,7 +1321,12 @@ function updateGapChip() {
// Sai so du lieu va khoang cach ve la HAI so. Bang nhau nghia la hinh ve // Sai so du lieu va khoang cach ve la HAI so. Bang nhau nghia la hinh ve
// trung thuc va cai nhin thay la sai so that. Khac nhau nghia la con loi o // trung thuc va cai nhin thay la sai so that. Khac nhau nghia la con loi o
// tang hien thi -- da xay ra hai lan (thieu lop boc, va quen laser_x). // tang hien thi -- da xay ra hai lan (thieu lop boc, va quen laser_x).
const drift = dDraw !== null && Math.abs(dDraw - dData) > 0.01; //
// So voi pose DA DUA DI VE (displayPose() lam muot co chu dich, lech pose
// that vai cm khi dang chay) -- van bat duoc loi lop boc / laser_x.
const drawn = state.drawnPose || state.pose;
const dRef = state.gt ? Math.hypot(drawn.x - state.gt.x, drawn.y - state.gt.y) : dData;
const drift = dDraw !== null && Math.abs(dDraw - dRef) > 0.01;
el.textContent = 'gap ' + dData.toFixed(3) + ' m' + el.textContent = 'gap ' + dData.toFixed(3) + ' m' +
(drift ? ' / ve ' + dDraw.toFixed(3) : ''); (drift ? ' / ve ' + dDraw.toFixed(3) : '');
el.title = drift el.title = drift
@@ -1206,7 +1344,33 @@ for (const b of document.querySelectorAll('.vbtn')) {
function draw3d() { function draw3d() {
if (state.robot) v3dSetShape(state.robot); if (state.robot) v3dSetShape(state.robot);
if (state.pose) v3dSetPose(V3D.robotGroup, state.pose); if (state.dispPose) {
v3dSetPose(V3D.robotGroup, state.dispPose);
state.drawnPose = state.dispPose; // updateGapChip() so voi pose NAY
}
// Chua dinh vi xong: robot TAM o goc map -> ve MO. Nho do mo goc cua tung
// vat lieu (vai overlay von trong suot) de tra lai dung khi da chot. Chay moi
// khung vi v3dSetShape() co the tao vat lieu moi.
if (V3D.robotGroup) {
const fade = !!state.relocPending;
V3D.robotGroup.traverse((o) => {
if (!o.material) return;
const mats = Array.isArray(o.material) ? o.material : [o.material];
for (const m of mats) {
if (m.userData.op0 === undefined) {
m.userData.op0 = m.opacity;
m.userData.tr0 = m.transparent;
}
const op = fade ? m.userData.op0 * 0.35 : m.userData.op0;
const tr = fade ? true : m.userData.tr0;
if (m.opacity !== op || m.transparent !== tr) {
m.opacity = op;
m.transparent = tr;
m.needsUpdate = true;
}
}
});
}
if (state.gt && on('lyGt')) { if (state.gt && on('lyGt')) {
if (V3D.gtGroup) V3D.gtGroup.visible = true; if (V3D.gtGroup) V3D.gtGroup.visible = true;
v3dSetPose(V3D.gtGroup, state.gt); v3dSetPose(V3D.gtGroup, state.gt);
@@ -1243,7 +1407,7 @@ function draw3d() {
v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion }); v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion });
} }
if (V3D.mapMesh) V3D.mapMesh.visible = on('lyMap') && !!state.map; 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; else if (V3D.pathLine) V3D.pathLine.visible = false;
v3dRender(cv3d, on('lyFollow'), split3d); v3dRender(cv3d, on('lyFollow'), split3d);

View File

@@ -425,6 +425,19 @@ function v3dSetPose(group, p) {
group.position.x = p.x; group.position.x = p.x;
group.position.z = -p.y; group.position.z = -p.y;
group.rotation.y = p.yaw; 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). // 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 n = arr.length / 2;
const pos = new Float32Array(n * 3); const pos = new Float32Array(n * 3);
// Scan nam o do cao cua LiDAR, khong phai o san. Ve o san se lam nguoi xem // 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. // tuong LiDAR thay duoc vat thap -- no KHONG thay. Cong cao do san duoi
const z = r.laser_z + r.wheel_radius; // 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. // ⚠️ Scan den trong frame LASER, khong phai frame BASE.
// //
// `laser_link` cach `base_link` 0.24 m ve phia truoc (robot.yaml). Dat thang // `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; const lx = r.laser_x || 0, ly = r.laser_y || 0;
for (let i = 0; i < n; ++i) { for (let i = 0; i < n; ++i) {
const x = arr[i * 2] + lx, y = arr[i * 2 + 1] + ly; const x = arr[i * 2] + lx, y = arr[i * 2 + 1] + ly;
pos[i * 3] = pose.x + c * x - s * y; // Rx(roll) roi Ry(pitch), trong he footprint (truoc khi quay yaw).
pos[i * 3 + 1] = z; const y1 = y * cr - zl * sr, z1 = y * sr + zl * cr;
pos[i * 3 + 2] = -(pose.y + s * x + c * y); 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.dispose();
V3D.scanPts.geometry = new THREE.BufferGeometry(); 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 c = Math.cos(pose.yaw), s = Math.sin(pose.yaw);
const n = arr.length / 3; const n = arr.length / 3;
const pos = new Float32Array(n * 3), col = new Float32Array(n * 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) { for (let i = 0; i < n; ++i) {
const x = arr[i * 3], y = arr[i * 3 + 1], z = arr[i * 3 + 2]; 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] = 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); pos[i * 3 + 2] = -(pose.y + s * x + c * y);
// To mau theo do cao, cung bang mau voi khung 2D. // To mau theo do cao, cung bang mau voi khung 2D.
const t = Math.max(0, Math.min(1, z / 1.2)); 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 // 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 // bay "sàn troi theo robot": robot dung yen giua man hinh con ca the gioi
// truot qua, trong y het loi dinh vi. // 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) { function v3dSetGround(grid) {
if (!V3D.ready || !grid) return; 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; const r = grid.res;
if (V3D.floorMesh) { if (V3D.floorMesh) {
V3D.root.remove(V3D.floorMesh); V3D.root.remove(V3D.floorMesh);
V3D.floorMesh.geometry.dispose(); V3D.floorMesh.geometry.dispose();
V3D.floorMesh.material.dispose();
} }
const fw = grid.w * r, fh = grid.h * r; const fw = grid.w * r, fh = grid.h * r;
V3D.floorMesh = new THREE.Mesh( V3D.floorMesh = new THREE.Mesh(
@@ -627,7 +662,11 @@ function v3dSetGround(grid) {
const span = Math.max(fw, fh); const span = Math.max(fw, fh);
V3D.scene.fog.near = span * 0.35; V3D.scene.fog.near = span * 0.35;
V3D.scene.fog.far = span * 1.4; 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), V3D.gridHelper = new THREE.GridHelper(Math.ceil(span), Math.ceil(span),
0x93a2b0, 0xa6b3c0); 0x93a2b0, 0xa6b3c0);
V3D.root.add(V3D.gridHelper); V3D.root.add(V3D.gridHelper);
@@ -831,11 +870,69 @@ function v3dSetWorld(grid, wallHeight) {
v3dSetGround(grid); 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) { function v3dSetMap(map) {
if (!V3D.ready || !map || !map.w || !map.h) return; if (!V3D.ready || !map || !map.w || !map.h) return;
if (V3D.mapKey === map.version) return; // Khoa theo MANG O, khong theo so phien ban: khung JSON mang phien ban moi
V3D.mapKey = map.version; // 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'); const cv = document.createElement('canvas');
cv.width = map.w; cv.height = map.h; cv.width = map.w; cv.height = map.h;
@@ -843,6 +940,11 @@ function v3dSetMap(map) {
const img = g.createImageData(map.w, map.h); const img = g.createImageData(map.w, map.h);
for (let i = 0; i < map.w * map.h; ++i) { for (let i = 0; i < map.w * map.h; ++i) {
const v = map.data[i]; const v = map.data[i];
// Hang 0 cua occupancy grid la o DUOI cung (y = oy), hang 0 cua ImageData
// la o TREN cung -> lat theo y khi ghi, nhu rasterize() ben app.js. Thieu
// buoc nay ban do da quet bi LAT GUONG quanh tam cua no: lech khoi voxel va
// quy dao, va "troi" moi lan ban do no rong (tam doi).
const j = ((map.h - 1 - Math.floor(i / map.w)) * map.w + (i % map.w)) * 4;
// -1 = CHUA BIET. Ve no khac han o trong: "chua di toi" va "da di toi, // -1 = CHUA BIET. Ve no khac han o trong: "chua di toi" va "da di toi,
// khong co gi" la hai chuyen khac nhau, va gop lai se lam ban do trong // khong co gi" la hai chuyen khac nhau, va gop lai se lam ban do trong
// day du hon thuc te. // day du hon thuc te.
@@ -853,8 +955,8 @@ function v3dSetMap(map) {
if (v < 0) { r = gg = b = 0; a = 0; } // chua quet -> trong suot if (v < 0) { r = gg = b = 0; a = 0; } // chua quet -> trong suot
else if (v >= 50) { r = 90; gg = 200; b = 255; a = 230; } // tuong da quet else if (v >= 50) { r = 90; gg = 200; b = 255; a = 230; } // tuong da quet
else { r = 40; gg = 90; b = 130; a = 120; } // san da quet else { r = 40; gg = 90; b = 130; a = 120; } // san da quet
img.data[i * 4] = r; img.data[i * 4 + 1] = gg; img.data[j] = r; img.data[j + 1] = gg;
img.data[i * 4 + 2] = b; img.data[i * 4 + 3] = a; img.data[j + 2] = b; img.data[j + 3] = a;
} }
g.putImageData(img, 0, 0); g.putImageData(img, 0, 0);
@@ -862,23 +964,57 @@ function v3dSetMap(map) {
tex.magFilter = THREE.NearestFilter; tex.magFilter = THREE.NearestFilter;
tex.minFilter = THREE.LinearMipmapLinearFilter; 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 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( V3D.mapMesh = new THREE.Mesh(
new THREE.PlaneGeometry(wM, hM), geom,
new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false })); new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false }));
V3D.mapMesh.rotation.x = -Math.PI / 2; V3D.mapMesh.rotation.x = -Math.PI / 2;
// Hoi thap hon san mot chut de khong z-fight voi luoi va vanh cliff. // Phang: 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)); // 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); 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.ready) return;
if (V3D.pathLine) { V3D.root.remove(V3D.pathLine); V3D.pathLine.geometry.dispose(); } if (V3D.pathLine) { V3D.root.remove(V3D.pathLine); V3D.pathLine.geometry.dispose(); }
if (!pts || pts.length < 4) return; 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 = []; 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( V3D.pathLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(v), new THREE.BufferGeometry().setFromPoints(v),
new THREE.LineBasicMaterial({ color: 0xffb300 })); new THREE.LineBasicMaterial({ color: 0xffb300 }));
@@ -894,6 +1030,10 @@ function v3dSetPath(pts) {
function v3dSetWorldVisible(on) { function v3dSetWorldVisible(on) {
if (V3D.meshWorld) V3D.meshWorld.visible = on; if (V3D.meshWorld) V3D.meshWorld.visible = on;
if (V3D.worldMesh) V3D.worldMesh.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. // Dat khung nhin ve mot goc chuan.
@@ -971,17 +1111,21 @@ function v3dRender(canvas, follow, splitSlam) {
} }
// Tam quay: bam theo robot neu bat, khong thi theo diem pan cua nguoi dung. // 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) { if (follow && V3D.robotGroup) {
cx = V3D.robotGroup.position.x + V3D.orbit.tx; cx = V3D.robotGroup.position.x + V3D.orbit.tx;
cz = V3D.robotGroup.position.z + V3D.orbit.ty; cz = V3D.robotGroup.position.z + V3D.orbit.ty;
cy = V3D.robotGroup.position.y;
} }
const o = V3D.orbit; const o = V3D.orbit;
V3D.camera.position.set( V3D.camera.position.set(
cx + o.dist * Math.cos(o.el) * Math.cos(o.az), 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)); 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; const r = V3D.renderer;
if (!splitSlam) { if (!splitSlam) {
@@ -1020,7 +1164,10 @@ function v3dRender(canvas, follow, splitSlam) {
show(hid); show(hid);
// --- Nua PHAI: chi SLAM, khong co the gioi --- // --- 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.setViewport(half, 0, w - half, h);
r.setScissor(half, 0, w - half, h); r.setScissor(half, 0, w - half, h);
r.render(V3D.scene, V3D.camera); r.render(V3D.scene, V3D.camera);

View File

@@ -58,6 +58,8 @@
<canvas id="mainR"></canvas> <canvas id="mainR"></canvas>
<div id="labL" class="pane-label" style="display:none">THE GIOI (su that)</div> <div id="labL" class="pane-label" style="display:none">THE GIOI (su that)</div>
<div id="labR" class="pane-label" style="display:none">SLAM dang dung</div> <div id="labR" class="pane-label" style="display:none">SLAM dang dung</div>
<!-- Dinh vi lai (--slam-reloc) chua xong: de len ca 2D lan 3D. -->
<div id="relocBanner" class="reloc-banner" style="display:none"></div>
<div id="hint">keo de di chuyen &middot; cuon de phong to &middot; nhan dup de ve giua</div> <div id="hint">keo de di chuyen &middot; cuon de phong to &middot; nhan dup de ve giua</div>
</div> </div>
@@ -71,6 +73,9 @@
<!-- Ground truth chi co khi mo phong. Sai so la thuoc do duy nhat <!-- Ground truth chi co khi mo phong. Sai so la thuoc do duy nhat
cho biet uoc luong dang tot hay te. --> cho biet uoc luong dang tot hay te. -->
<tr><td>sai so</td><td id="gtErr">--</td></tr> <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> </table>
</section> </section>
@@ -106,6 +111,9 @@
<tr><td>diem</td><td id="score">--</td></tr> <tr><td>diem</td><td id="score">--</td></tr>
<tr><td>process</td><td id="pms">--</td></tr> <tr><td>process</td><td id="pms">--</td></tr>
<tr><td>map ver</td><td id="mapver">--</td></tr> <tr><td>map ver</td><td id="mapver">--</td></tr>
<!-- Nguon + so o cua ban do 3D. "0 o" = chua dung duoc; "thieu depth"
= camera khong ra khung. -->
<tr><td>ban do 3D</td><td id="vox">--</td></tr>
</table> </table>
</section> </section>

View File

@@ -181,6 +181,13 @@ button.danger:hover { background: var(--bad); color: #fff; }
color: #8fa3bf; background: rgba(18,21,26,.82); color: #8fa3bf; background: rgba(18,21,26,.82);
padding: 2px 7px; border-radius: 3px; pointer-events: none; padding: 2px 7px; border-radius: 3px; pointer-events: none;
} }
.reloc-banner {
position: absolute; top: 34px; left: 50%; transform: translateX(-50%);
max-width: 90%; z-index: 5;
font: 12px/1.4 ui-monospace, monospace;
color: #1b1405; background: rgba(245,166,35,.92);
padding: 4px 10px; border-radius: 3px; pointer-events: none;
}
#labL { left: 8px; } #labL { left: 8px; }
#labR { left: 50%; margin-left: 8px; } #labR { left: 50%; margin-left: 8px; }

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,52 @@
# Dia hinh world hai doc: sanh z=0, hai tang z=1.50, doc 10 / 15 do.
# Z-UP, met. Sinh boi tools/gen_two_ramp_world.py -- dung sua tay.
v 0.0000 0.0000 1.5000
vt 0.0000 0.0000
v 6.0000 0.0000 1.5000
vt 6.0000 0.0000
v 6.0000 8.0000 1.5000
vt 6.0000 8.0000
v 0.0000 8.0000 1.5000
vt 0.0000 8.0000
f 1/1 2/2 3/3
f 1/1 3/3 4/4
v 6.0000 0.0000 1.5000
vt 6.0000 0.0000
v 14.5069 0.0000 0.0000
vt 14.5069 0.0000
v 14.5069 8.0000 0.0000
vt 14.5069 8.0000
v 6.0000 8.0000 1.5000
vt 6.0000 8.0000
f 5/5 6/6 7/7
f 5/5 7/7 8/8
v 14.5069 0.0000 0.0000
vt 14.5069 0.0000
v 24.5069 0.0000 0.0000
vt 24.5069 0.0000
v 24.5069 8.0000 0.0000
vt 24.5069 8.0000
v 14.5069 8.0000 0.0000
vt 14.5069 8.0000
f 9/9 10/10 11/11
f 9/9 11/11 12/12
v 24.5069 0.0000 0.0000
vt 24.5069 0.0000
v 30.1050 0.0000 1.5000
vt 30.1050 0.0000
v 30.1050 8.0000 1.5000
vt 30.1050 8.0000
v 24.5069 8.0000 0.0000
vt 24.5069 8.0000
f 13/13 14/14 15/15
f 13/13 15/15 16/16
v 30.1050 0.0000 1.5000
vt 30.1050 0.0000
v 36.1050 0.0000 1.5000
vt 36.1050 0.0000
v 36.1050 8.0000 1.5000
vt 36.1050 8.0000
v 30.1050 8.0000 1.5000
vt 30.1050 8.0000
f 17/17 18/18 19/19
f 17/17 19/19 20/20

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" ?>
<model>
<name>vslam_terrain_two_ramps</name>
<version>1.0</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>vslam_cpp</name>
<email></email>
</author>
<description>
Sanh, hai doc va hai tang (dia hinh).
Sinh boi tools/gen_two_ramp_world.py.
</description>
</model>

View File

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

View File

@@ -0,0 +1,602 @@
# Tuong bao va cot cua world hai doc. Z-UP, met.
# Sinh boi tools/gen_two_ramp_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 8.2000 4.0000
vt 0.0000 8.2000
v -0.2000 8.2000 4.0000
vt -0.2000 8.2000
f 1/1 2/2 3/3
f 1/1 3/3 4/4
v -0.2000 8.2000 0.0000
vt -0.2000 8.2000
v 0.0000 8.2000 0.0000
vt 0.0000 8.2000
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 8.2000 0.0000
vt 0.0000 0.0000
v -0.2000 8.2000 0.0000
vt -0.2000 0.0000
v -0.2000 8.2000 4.0000
vt -0.2000 4.0000
v 0.0000 8.2000 4.0000
vt 0.0000 4.0000
f 13/13 14/14 15/15
f 13/13 15/15 16/16
v -0.2000 8.2000 0.0000
vt 8.2000 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 8.2000 4.0000
vt 8.2000 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 8.2000 0.0000
vt 8.2000 0.0000
v 0.0000 8.2000 4.0000
vt 8.2000 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 36.1050 -0.2000 4.0000
vt 36.1050 -0.2000
v 36.3050 -0.2000 4.0000
vt 36.3050 -0.2000
v 36.3050 8.2000 4.0000
vt 36.3050 8.2000
v 36.1050 8.2000 4.0000
vt 36.1050 8.2000
f 25/25 26/26 27/27
f 25/25 27/27 28/28
v 36.1050 8.2000 0.0000
vt 36.1050 8.2000
v 36.3050 8.2000 0.0000
vt 36.3050 8.2000
v 36.3050 -0.2000 0.0000
vt 36.3050 -0.2000
v 36.1050 -0.2000 0.0000
vt 36.1050 -0.2000
f 29/29 30/30 31/31
f 29/29 31/31 32/32
v 36.1050 -0.2000 0.0000
vt 36.1050 0.0000
v 36.3050 -0.2000 0.0000
vt 36.3050 0.0000
v 36.3050 -0.2000 4.0000
vt 36.3050 4.0000
v 36.1050 -0.2000 4.0000
vt 36.1050 4.0000
f 33/33 34/34 35/35
f 33/33 35/35 36/36
v 36.3050 8.2000 0.0000
vt 36.3050 0.0000
v 36.1050 8.2000 0.0000
vt 36.1050 0.0000
v 36.1050 8.2000 4.0000
vt 36.1050 4.0000
v 36.3050 8.2000 4.0000
vt 36.3050 4.0000
f 37/37 38/38 39/39
f 37/37 39/39 40/40
v 36.1050 8.2000 0.0000
vt 8.2000 0.0000
v 36.1050 -0.2000 0.0000
vt -0.2000 0.0000
v 36.1050 -0.2000 4.0000
vt -0.2000 4.0000
v 36.1050 8.2000 4.0000
vt 8.2000 4.0000
f 41/41 42/42 43/43
f 41/41 43/43 44/44
v 36.3050 -0.2000 0.0000
vt -0.2000 0.0000
v 36.3050 8.2000 0.0000
vt 8.2000 0.0000
v 36.3050 8.2000 4.0000
vt 8.2000 4.0000
v 36.3050 -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 36.3050 -0.2000 4.0000
vt 36.3050 -0.2000
v 36.3050 0.0000 4.0000
vt 36.3050 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 36.3050 0.0000 0.0000
vt 36.3050 0.0000
v 36.3050 -0.2000 0.0000
vt 36.3050 -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 36.3050 -0.2000 0.0000
vt 36.3050 0.0000
v 36.3050 -0.2000 4.0000
vt 36.3050 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 36.3050 0.0000 0.0000
vt 36.3050 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 36.3050 0.0000 4.0000
vt 36.3050 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 36.3050 -0.2000 0.0000
vt -0.2000 0.0000
v 36.3050 0.0000 0.0000
vt 0.0000 0.0000
v 36.3050 0.0000 4.0000
vt 0.0000 4.0000
v 36.3050 -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 8.0000 4.0000
vt -0.2000 8.0000
v 36.3050 8.0000 4.0000
vt 36.3050 8.0000
v 36.3050 8.2000 4.0000
vt 36.3050 8.2000
v -0.2000 8.2000 4.0000
vt -0.2000 8.2000
f 73/73 74/74 75/75
f 73/73 75/75 76/76
v -0.2000 8.2000 0.0000
vt -0.2000 8.2000
v 36.3050 8.2000 0.0000
vt 36.3050 8.2000
v 36.3050 8.0000 0.0000
vt 36.3050 8.0000
v -0.2000 8.0000 0.0000
vt -0.2000 8.0000
f 77/77 78/78 79/79
f 77/77 79/79 80/80
v -0.2000 8.0000 0.0000
vt -0.2000 0.0000
v 36.3050 8.0000 0.0000
vt 36.3050 0.0000
v 36.3050 8.0000 4.0000
vt 36.3050 4.0000
v -0.2000 8.0000 4.0000
vt -0.2000 4.0000
f 81/81 82/82 83/83
f 81/81 83/83 84/84
v 36.3050 8.2000 0.0000
vt 36.3050 0.0000
v -0.2000 8.2000 0.0000
vt -0.2000 0.0000
v -0.2000 8.2000 4.0000
vt -0.2000 4.0000
v 36.3050 8.2000 4.0000
vt 36.3050 4.0000
f 85/85 86/86 87/87
f 85/85 87/87 88/88
v -0.2000 8.2000 0.0000
vt 8.2000 0.0000
v -0.2000 8.0000 0.0000
vt 8.0000 0.0000
v -0.2000 8.0000 4.0000
vt 8.0000 4.0000
v -0.2000 8.2000 4.0000
vt 8.2000 4.0000
f 89/89 90/90 91/91
f 89/89 91/91 92/92
v 36.3050 8.0000 0.0000
vt 8.0000 0.0000
v 36.3050 8.2000 0.0000
vt 8.2000 0.0000
v 36.3050 8.2000 4.0000
vt 8.2000 4.0000
v 36.3050 8.0000 4.0000
vt 8.0000 4.0000
f 93/93 94/94 95/95
f 93/93 95/95 96/96
v 8.7774 7.8500 4.0000
vt 8.7774 7.8500
v 9.1774 7.8500 4.0000
vt 9.1774 7.8500
v 9.1774 8.0000 4.0000
vt 9.1774 8.0000
v 8.7774 8.0000 4.0000
vt 8.7774 8.0000
f 97/97 98/98 99/99
f 97/97 99/99 100/100
v 8.7774 8.0000 0.0000
vt 8.7774 8.0000
v 9.1774 8.0000 0.0000
vt 9.1774 8.0000
v 9.1774 7.8500 0.0000
vt 9.1774 7.8500
v 8.7774 7.8500 0.0000
vt 8.7774 7.8500
f 101/101 102/102 103/103
f 101/101 103/103 104/104
v 8.7774 7.8500 0.0000
vt 8.7774 0.0000
v 9.1774 7.8500 0.0000
vt 9.1774 0.0000
v 9.1774 7.8500 4.0000
vt 9.1774 4.0000
v 8.7774 7.8500 4.0000
vt 8.7774 4.0000
f 105/105 106/106 107/107
f 105/105 107/107 108/108
v 9.1774 8.0000 0.0000
vt 9.1774 0.0000
v 8.7774 8.0000 0.0000
vt 8.7774 0.0000
v 8.7774 8.0000 4.0000
vt 8.7774 4.0000
v 9.1774 8.0000 4.0000
vt 9.1774 4.0000
f 109/109 110/110 111/111
f 109/109 111/111 112/112
v 8.7774 8.0000 0.0000
vt 8.0000 0.0000
v 8.7774 7.8500 0.0000
vt 7.8500 0.0000
v 8.7774 7.8500 4.0000
vt 7.8500 4.0000
v 8.7774 8.0000 4.0000
vt 8.0000 4.0000
f 113/113 114/114 115/115
f 113/113 115/115 116/116
v 9.1774 7.8500 0.0000
vt 7.8500 0.0000
v 9.1774 8.0000 0.0000
vt 8.0000 0.0000
v 9.1774 8.0000 4.0000
vt 8.0000 4.0000
v 9.1774 7.8500 4.0000
vt 7.8500 4.0000
f 117/117 118/118 119/119
f 117/117 119/119 120/120
v 11.7548 7.8500 4.0000
vt 11.7548 7.8500
v 12.1548 7.8500 4.0000
vt 12.1548 7.8500
v 12.1548 8.0000 4.0000
vt 12.1548 8.0000
v 11.7548 8.0000 4.0000
vt 11.7548 8.0000
f 121/121 122/122 123/123
f 121/121 123/123 124/124
v 11.7548 8.0000 0.0000
vt 11.7548 8.0000
v 12.1548 8.0000 0.0000
vt 12.1548 8.0000
v 12.1548 7.8500 0.0000
vt 12.1548 7.8500
v 11.7548 7.8500 0.0000
vt 11.7548 7.8500
f 125/125 126/126 127/127
f 125/125 127/127 128/128
v 11.7548 7.8500 0.0000
vt 11.7548 0.0000
v 12.1548 7.8500 0.0000
vt 12.1548 0.0000
v 12.1548 7.8500 4.0000
vt 12.1548 4.0000
v 11.7548 7.8500 4.0000
vt 11.7548 4.0000
f 129/129 130/130 131/131
f 129/129 131/131 132/132
v 12.1548 8.0000 0.0000
vt 12.1548 0.0000
v 11.7548 8.0000 0.0000
vt 11.7548 0.0000
v 11.7548 8.0000 4.0000
vt 11.7548 4.0000
v 12.1548 8.0000 4.0000
vt 12.1548 4.0000
f 133/133 134/134 135/135
f 133/133 135/135 136/136
v 11.7548 8.0000 0.0000
vt 8.0000 0.0000
v 11.7548 7.8500 0.0000
vt 7.8500 0.0000
v 11.7548 7.8500 4.0000
vt 7.8500 4.0000
v 11.7548 8.0000 4.0000
vt 8.0000 4.0000
f 137/137 138/138 139/139
f 137/137 139/139 140/140
v 12.1548 7.8500 0.0000
vt 7.8500 0.0000
v 12.1548 8.0000 0.0000
vt 8.0000 0.0000
v 12.1548 8.0000 4.0000
vt 8.0000 4.0000
v 12.1548 7.8500 4.0000
vt 7.8500 4.0000
f 141/141 142/142 143/143
f 141/141 143/143 144/144
v 17.8069 5.8000 4.0000
vt 17.8069 5.8000
v 18.2069 5.8000 4.0000
vt 18.2069 5.8000
v 18.2069 6.2000 4.0000
vt 18.2069 6.2000
v 17.8069 6.2000 4.0000
vt 17.8069 6.2000
f 145/145 146/146 147/147
f 145/145 147/147 148/148
v 17.8069 6.2000 0.0000
vt 17.8069 6.2000
v 18.2069 6.2000 0.0000
vt 18.2069 6.2000
v 18.2069 5.8000 0.0000
vt 18.2069 5.8000
v 17.8069 5.8000 0.0000
vt 17.8069 5.8000
f 149/149 150/150 151/151
f 149/149 151/151 152/152
v 17.8069 5.8000 0.0000
vt 17.8069 0.0000
v 18.2069 5.8000 0.0000
vt 18.2069 0.0000
v 18.2069 5.8000 4.0000
vt 18.2069 4.0000
v 17.8069 5.8000 4.0000
vt 17.8069 4.0000
f 153/153 154/154 155/155
f 153/153 155/155 156/156
v 18.2069 6.2000 0.0000
vt 18.2069 0.0000
v 17.8069 6.2000 0.0000
vt 17.8069 0.0000
v 17.8069 6.2000 4.0000
vt 17.8069 4.0000
v 18.2069 6.2000 4.0000
vt 18.2069 4.0000
f 157/157 158/158 159/159
f 157/157 159/159 160/160
v 17.8069 6.2000 0.0000
vt 6.2000 0.0000
v 17.8069 5.8000 0.0000
vt 5.8000 0.0000
v 17.8069 5.8000 4.0000
vt 5.8000 4.0000
v 17.8069 6.2000 4.0000
vt 6.2000 4.0000
f 161/161 162/162 163/163
f 161/161 163/163 164/164
v 18.2069 5.8000 0.0000
vt 5.8000 0.0000
v 18.2069 6.2000 0.0000
vt 6.2000 0.0000
v 18.2069 6.2000 4.0000
vt 6.2000 4.0000
v 18.2069 5.8000 4.0000
vt 5.8000 4.0000
f 165/165 166/166 167/167
f 165/165 167/167 168/168
v 21.3069 2.3000 4.0000
vt 21.3069 2.3000
v 21.7069 2.3000 4.0000
vt 21.7069 2.3000
v 21.7069 2.7000 4.0000
vt 21.7069 2.7000
v 21.3069 2.7000 4.0000
vt 21.3069 2.7000
f 169/169 170/170 171/171
f 169/169 171/171 172/172
v 21.3069 2.7000 0.0000
vt 21.3069 2.7000
v 21.7069 2.7000 0.0000
vt 21.7069 2.7000
v 21.7069 2.3000 0.0000
vt 21.7069 2.3000
v 21.3069 2.3000 0.0000
vt 21.3069 2.3000
f 173/173 174/174 175/175
f 173/173 175/175 176/176
v 21.3069 2.3000 0.0000
vt 21.3069 0.0000
v 21.7069 2.3000 0.0000
vt 21.7069 0.0000
v 21.7069 2.3000 4.0000
vt 21.7069 4.0000
v 21.3069 2.3000 4.0000
vt 21.3069 4.0000
f 177/177 178/178 179/179
f 177/177 179/179 180/180
v 21.7069 2.7000 0.0000
vt 21.7069 0.0000
v 21.3069 2.7000 0.0000
vt 21.3069 0.0000
v 21.3069 2.7000 4.0000
vt 21.3069 4.0000
v 21.7069 2.7000 4.0000
vt 21.7069 4.0000
f 181/181 182/182 183/183
f 181/181 183/183 184/184
v 21.3069 2.7000 0.0000
vt 2.7000 0.0000
v 21.3069 2.3000 0.0000
vt 2.3000 0.0000
v 21.3069 2.3000 4.0000
vt 2.3000 4.0000
v 21.3069 2.7000 4.0000
vt 2.7000 4.0000
f 185/185 186/186 187/187
f 185/185 187/187 188/188
v 21.7069 2.3000 0.0000
vt 2.3000 0.0000
v 21.7069 2.7000 0.0000
vt 2.7000 0.0000
v 21.7069 2.7000 4.0000
vt 2.7000 4.0000
v 21.7069 2.3000 4.0000
vt 2.3000 4.0000
f 189/189 190/190 191/191
f 189/189 191/191 192/192
v 2.8000 4.8000 4.0000
vt 2.8000 4.8000
v 3.2000 4.8000 4.0000
vt 3.2000 4.8000
v 3.2000 5.2000 4.0000
vt 3.2000 5.2000
v 2.8000 5.2000 4.0000
vt 2.8000 5.2000
f 193/193 194/194 195/195
f 193/193 195/195 196/196
v 2.8000 5.2000 1.5000
vt 2.8000 5.2000
v 3.2000 5.2000 1.5000
vt 3.2000 5.2000
v 3.2000 4.8000 1.5000
vt 3.2000 4.8000
v 2.8000 4.8000 1.5000
vt 2.8000 4.8000
f 197/197 198/198 199/199
f 197/197 199/199 200/200
v 2.8000 4.8000 1.5000
vt 2.8000 1.5000
v 3.2000 4.8000 1.5000
vt 3.2000 1.5000
v 3.2000 4.8000 4.0000
vt 3.2000 4.0000
v 2.8000 4.8000 4.0000
vt 2.8000 4.0000
f 201/201 202/202 203/203
f 201/201 203/203 204/204
v 3.2000 5.2000 1.5000
vt 3.2000 1.5000
v 2.8000 5.2000 1.5000
vt 2.8000 1.5000
v 2.8000 5.2000 4.0000
vt 2.8000 4.0000
v 3.2000 5.2000 4.0000
vt 3.2000 4.0000
f 205/205 206/206 207/207
f 205/205 207/207 208/208
v 2.8000 5.2000 1.5000
vt 5.2000 1.5000
v 2.8000 4.8000 1.5000
vt 4.8000 1.5000
v 2.8000 4.8000 4.0000
vt 4.8000 4.0000
v 2.8000 5.2000 4.0000
vt 5.2000 4.0000
f 209/209 210/210 211/211
f 209/209 211/211 212/212
v 3.2000 4.8000 1.5000
vt 4.8000 1.5000
v 3.2000 5.2000 1.5000
vt 5.2000 1.5000
v 3.2000 5.2000 4.0000
vt 5.2000 4.0000
v 3.2000 4.8000 4.0000
vt 4.8000 4.0000
f 213/213 214/214 215/215
f 213/213 215/215 216/216
v 33.3050 3.3000 4.0000
vt 33.3050 3.3000
v 33.7050 3.3000 4.0000
vt 33.7050 3.3000
v 33.7050 3.7000 4.0000
vt 33.7050 3.7000
v 33.3050 3.7000 4.0000
vt 33.3050 3.7000
f 217/217 218/218 219/219
f 217/217 219/219 220/220
v 33.3050 3.7000 1.5000
vt 33.3050 3.7000
v 33.7050 3.7000 1.5000
vt 33.7050 3.7000
v 33.7050 3.3000 1.5000
vt 33.7050 3.3000
v 33.3050 3.3000 1.5000
vt 33.3050 3.3000
f 221/221 222/222 223/223
f 221/221 223/223 224/224
v 33.3050 3.3000 1.5000
vt 33.3050 1.5000
v 33.7050 3.3000 1.5000
vt 33.7050 1.5000
v 33.7050 3.3000 4.0000
vt 33.7050 4.0000
v 33.3050 3.3000 4.0000
vt 33.3050 4.0000
f 225/225 226/226 227/227
f 225/225 227/227 228/228
v 33.7050 3.7000 1.5000
vt 33.7050 1.5000
v 33.3050 3.7000 1.5000
vt 33.3050 1.5000
v 33.3050 3.7000 4.0000
vt 33.3050 4.0000
v 33.7050 3.7000 4.0000
vt 33.7050 4.0000
f 229/229 230/230 231/231
f 229/229 231/231 232/232
v 33.3050 3.7000 1.5000
vt 3.7000 1.5000
v 33.3050 3.3000 1.5000
vt 3.3000 1.5000
v 33.3050 3.3000 4.0000
vt 3.3000 4.0000
v 33.3050 3.7000 4.0000
vt 3.7000 4.0000
f 233/233 234/234 235/235
f 233/233 235/235 236/236
v 33.7050 3.3000 1.5000
vt 3.3000 1.5000
v 33.7050 3.7000 1.5000
vt 3.7000 1.5000
v 33.7050 3.7000 4.0000
vt 3.7000 4.0000
v 33.7050 3.3000 4.0000
vt 3.3000 4.0000
f 237/237 238/238 239/239
f 237/237 239/239 240/240

View File

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

View File

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

0
resources/vpr/.keep Normal file
View File

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

@@ -0,0 +1,102 @@
<?xml version="1.0" ?>
<!-- World HAI DOC. Sinh boi tools/gen_two_ramp_world.py -- dung sua tay.
Sanh giua z = 0 (x 14.5-24.5); doc trai 10 do (y 0.0-8.0) len tang trai,
doc phai 15 do (y 0.0-8.0) len tang phai, hai tang z = 1.5.
Xuat phat goi y: --x 19.5 --y 4.0 --yaw 3.1416 (giua sanh, nhin ve doc trai). -->
<sdf version="1.6">
<world name="slope_two_ramps">
<include><uri>model://ground_plane</uri></include>
<include><uri>model://sun</uri></include>
<model name="vslam_terrain_two_ramps_1">
<include>
<uri>model://vslam_terrain_two_ramps</uri>
<static>true</static>
<pose>0.000 0.000 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="vslam_two_ramps_walls_1">
<include>
<uri>model://vslam_two_ramps_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>15.107 7.400 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="IVStand_1">
<include>
<uri>model://IVStand</uri>
<static>true</static>
<pose>17.007 0.800 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="VendingMachine_1">
<include>
<uri>model://VendingMachine</uri>
<static>true</static>
<pose>19.507 7.500 0.000 0 0 -1.5708</pose>
</include>
</model>
<model name="StorageRack_1">
<include>
<uri>model://StorageRack</uri>
<static>true</static>
<pose>21.007 0.600 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="PatientWheelChair_1">
<include>
<uri>model://PatientWheelChair</uri>
<static>true</static>
<pose>23.807 1.000 0.000 0 0 0.0000</pose>
</include>
</model>
<model name="MetalCabinet_2">
<include>
<uri>model://MetalCabinet</uri>
<static>true</static>
<pose>0.600 7.000 1.500 0 0 0.0000</pose>
</include>
</model>
<model name="BedTable_1">
<include>
<uri>model://BedTable</uri>
<static>true</static>
<pose>2.500 0.800 1.500 0 0 0.0000</pose>
</include>
</model>
<model name="IVStand_2">
<include>
<uri>model://IVStand</uri>
<static>true</static>
<pose>4.500 7.200 1.500 0 0 0.0000</pose>
</include>
</model>
<model name="StorageRack_2">
<include>
<uri>model://StorageRack</uri>
<static>true</static>
<pose>33.005 0.600 1.500 0 0 0.0000</pose>
</include>
</model>
<model name="BedTable_2">
<include>
<uri>model://BedTable</uri>
<static>true</static>
<pose>34.505 7.400 1.500 0 0 0.0000</pose>
</include>
</model>
<model name="VendingMachine_2">
<include>
<uri>model://VendingMachine</uri>
<static>true</static>
<pose>35.505 2.000 1.500 0 0 3.1416</pose>
</include>
</model>
</world>
</sdf>

View File

@@ -52,6 +52,8 @@ endif()
if(VSLAM_BUILD_ODOMETRY) if(VSLAM_BUILD_ODOMETRY)
vslam_add_test(test_wheel_odometry LIBS vslam_odometry vslam_common) 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_ekf_se2 LIBS vslam_odometry vslam_common)
vslam_add_test(test_height_estimator LIBS vslam_odometry vslam_common)
vslam_add_test(test_gyro_yaw_fuser LIBS vslam_odometry vslam_common)
endif() endif()
if(VSLAM_BUILD_SAFETY) if(VSLAM_BUILD_SAFETY)
@@ -62,6 +64,8 @@ if(VSLAM_BUILD_DRIVERS)
vslam_add_test(test_scan_sanitizer LIBS vslam_drivers vslam_common) vslam_add_test(test_scan_sanitizer LIBS vslam_drivers vslam_common)
vslam_add_test(test_clock_sync LIBS vslam_drivers vslam_common) vslam_add_test(test_clock_sync LIBS vslam_drivers vslam_common)
vslam_add_test(test_mcu_protocol LIBS vslam_drivers vslam_common) vslam_add_test(test_mcu_protocol LIBS vslam_drivers vslam_common)
vslam_add_test(test_wt61pc_protocol LIBS vslam_drivers vslam_common)
vslam_add_test(test_wt61pc_bridge LIBS vslam_drivers vslam_common)
vslam_add_test(test_record_io LIBS vslam_drivers vslam_common) vslam_add_test(test_record_io LIBS vslam_drivers vslam_common)
# Tay cam: khoa CAM GIAC LAI port tu base_kit (he so turbo/slow, deadzone, # Tay cam: khoa CAM GIAC LAI port tu base_kit (he so turbo/slow, deadzone,
# cu kich thang ma sat tinh, luat nhuong quyen 1.5 s). Khong can tay cam. # cu kich thang ma sat tinh, luat nhuong quyen 1.5 s). Khong can tay cam.
@@ -71,6 +75,7 @@ endif()
if(VSLAM_BUILD_PERCEPTION) if(VSLAM_BUILD_PERCEPTION)
vslam_add_test(test_perception LIBS vslam_perception vslam_common) 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) if(VSLAM_BUILD_SIM)
# Test TICH HOP sim -> perception. Khoa quy uoc Z-depth cua anh mo phong # 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 # va bai "san phang thi khong duoc bao vuc" -- thu ma ban ROS chi kiem
@@ -85,6 +90,15 @@ if(VSLAM_BUILD_SIM)
# Doc `.world` cua Gazebo. Fixture rieng trong test/data/world -- KHONG can # 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. # 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) 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) if(VSLAM_BUILD_ODOMETRY)
# Test TICH HOP: sim -> encoder -> wheel_odom -> EKF, do sai so so voi # 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. # ground truth. Day la bai L2 cua repo cu viet lai khong ROS.
@@ -96,6 +110,9 @@ endif()
if(VSLAM_BUILD_SLAM) if(VSLAM_BUILD_SLAM)
vslam_add_test(test_slam LIBS vslam_slam vslam_common) 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_voxel_export LIBS vslam_slam vslam_common)
vslam_add_test(test_height_map LIBS vslam_slam vslam_common)
vslam_add_test(test_slope_test LIBS vslam_slam vslam_common)
vslam_add_test(test_global_localizer LIBS vslam_slam vslam_common)
endif() endif()
if(VSLAM_BUILD_WEB) if(VSLAM_BUILD_WEB)
@@ -245,6 +262,15 @@ if(VSLAM_NODE_EXE AND TARGET vslam_world_export)
${CMAKE_CURRENT_SOURCE_DIR}/www/test_orbit_camera.js) ${CMAKE_CURRENT_SOURCE_DIR}/www/test_orbit_camera.js)
set_tests_properties(www_orbit_camera PROPERTIES set_tests_properties(www_orbit_camera PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT") 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() else()
message(STATUS "vslam: khong tim thay `node` -- bo qua bai kiem frontend") message(STATUS "vslam: khong tim thay `node` -- bo qua bai kiem frontend")
endif() 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

Some files were not shown because too many files have changed in this diff Show More