Compare commits

..

14 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
48 changed files with 4740 additions and 161 deletions

220
README.md
View File

@@ -1,16 +1,21 @@
# vslam_cpp
SLAM va dinh vi cho robot dich vu trong nha, viet bang **C++ thuan, khong ROS**.
Mot tien trinh duy nhat `vslam_node` chay tren Jetson AGX (Ubuntu 22.04 arm64):
doc cam bien, uoc luong odometry, giu lop an toan, quet ban do 2D/3D bang
RTAB-Map, **tu dinh vi lai** tren ban do da quet, va hien tat ca len web UI.
SLAM va dinh vi cho robot dich vu di trong nha va **giua cac toa nha qua doc**, viet bang
**C++ thuan, khong ROS**. Mot tien trinh duy nhat `vslam_node` chay tren Jetson AGX (Ubuntu
22.04 arm64): doc cam bien, uoc luong odometry, giu lop an toan, quet ban do 2D/3D bang
RTAB-Map, **tu dinh vi lai** tren ban do da quet (ca khi dang dung tren doc), va hien tat ca
len web UI.
Pose SLAM la 2D (x, y, yaw). Tren doc them **do cao z** tinh tu IMU va luu vao tung node ban
do, nen ban do 3D va lop vat can di theo mat san -- doc khong bi coi la tuong. Nhieu tang chong
len nhau tai cung (x, y) KHONG ho tro.
Ba nguon du lieu, chung mot duong ong xu ly:
| Co | Nguon |
|---|---|
| `--live` | robot that |
| `--sim` | bo mo phong tich hop, doc thang file `.world` cua Gazebo |
| `--sim` | bo mo phong tich hop, doc thang file `.world` cua Gazebo (co dia hinh doc) |
| `--replay FILE.vsr` | phat lai ban ghi |
Tai lieu chi tiet: [RUNTIME](docs/RUNTIME.md) · [SLAM](docs/SLAM.md) ·
@@ -21,13 +26,14 @@ Tai lieu chi tiet: [RUNTIME](docs/RUNTIME.md) · [SLAM](docs/SLAM.md) ·
| Phan | Dung gi |
|---|---|
| Ngon ngu, build, test | C++17, CMake, GoogleTest |
| SLAM | RTAB-Map (ICP tren LiDAR, toi uu do thi g2o), OpenCV. Luoi 2D tu LiDAR, ban do 3D tu depth camera |
| Dinh vi lai | Khop scan LiDAR voi likelihood field cua toan ban do (`libs/vslam_slam/global_localizer`). Tuy chon camera: VPR EigenPlaces (TensorRT) + PnP bang depth anh ban do, chi chot khi trung LiDAR |
| SLAM | RTAB-Map (ICP tren LiDAR, toi uu do thi g2o), OpenCV. Luoi 2D tu LiDAR, ban do 3D tu depth camera, do cao san theo tung node |
| Di tren doc | IMU 200 Hz: z robot = tich -ds*sin(pitch) neo vao ban do; odometry tinh quang duong NGANG; scan LiDAR cho SLAM / dinh vi lai duoc bu nghieng va bo tia cham san / mat doc (ban do do cao tu depth). Lop an toan van dung scan tho |
| Dinh vi lai | Khop scan LiDAR voi likelihood field cua toan ban do (`libs/vslam_slam/global_localizer`), loai gia thuyet ma do doc ban do khong khop do nghieng IMU; tren doc khop tai cho, khong xoay robot. Tuy chon camera: VPR EigenPlaces (TensorRT) + PnP bang depth anh ban do -- san phang chot khi trung LiDAR, tren doc chot bang pose camera khi >= 2 anh trung nhau |
| Odometry | EKF: encoder banh + gyro, Eigen3 |
| An toan | FSM 20 Hz tren luong rieng: LiDAR, sieu am, bumper, e-stop |
| Web UI | Boost.Beast (HTTP + WebSocket), JavaScript + three.js |
| Cau hinh | yaml-cpp, 6 file trong `configuration_files/` |
| Phan cung | LiDAR LakiBeam 1L (UDP) · RealSense D410 (librealsense2) · IMU WT61PC (UART, cap USB-FTDI `/dev/imu`) · base ZLAC8015D (CANopen, lely-core) · tay cam Logitech F710 |
| An toan | FSM 20 Hz tren luong rieng: LiDAR, e-stop. Co dau vao sieu am / bumper nhung phan cung hien tai KHONG gui (xem `mcu_bridge.cc` muc 3) |
| Web UI | Boost.Beast (HTTP + WebSocket), JavaScript + three.js (khung 3D theo do cao san) |
| Cau hinh | yaml-cpp, 6 file trong `configuration_files/`, luat udev IMU trong `configuration_files/udev/` |
| Phan cung | LiDAR LakiBeam 1L (UDP) · RealSense D410 (librealsense2) · IMU WT61PC (UART 115200 / 200 Hz, cap USB-FTDI `/dev/imu`) · base ZLAC8015D (CANopen, lely-core) · tay cam Logitech F710 |
| Cong cu Python | `tools/render_map.py` (anh bao cao ban do), `tools/vpr_eval.py` (danh gia VPR), `tools/vpr_export_onnx.py` (xuat model VPR sang ONNX) |
## Build
@@ -46,7 +52,9 @@ cmake --build build -j
```
Tuy chon: `-DVSLAM_BUILD_SLAM=OFF` (chua co RTAB-Map, phan con lai van chay),
`-DVSLAM_WITH_REALSENSE=ON` (camera), `-DVSLAM_WITH_CANOPEN=ON` (base, bat buoc cho `--live`).
`-DVSLAM_WITH_REALSENSE=ON` (camera), `-DVSLAM_WITH_CANOPEN=ON` (base, bat buoc cho `--live`),
`-DVSLAM_SIM_WITH_GL=ON` (camera mo phong ve bang GPU, can cho `--sim-gl`),
`-DVSLAM_WITH_TENSORRT=ON` (camera dinh vi lai `--slam-reloc-vpr`, can TensorRT + CUDA).
### Jetson (arm64, Ubuntu 22.04)
@@ -54,11 +62,15 @@ Dependency build san trong `/opt/vslam` (RTAB-Map 0.23); g2o lay tu `ros-humble-
```sh
cd vslam_cpp
git fetch origin && git reset --keep origin/master # lay code moi (Jetson khong phan giai duoc remote `company`)
git log --oneline -1 # phai la commit vua push
cmake --preset jetson -DVSLAM_BUILD_SLAM=ON -DVSLAM_WITH_REALSENSE=ON -DVSLAM_WITH_CANOPEN=ON # chi lan dau
cmake --build --preset jetson
cmake --build --preset jetson 2>&1 | tee logs/build_jetson.log # dat: [100%] Built target vslam_node
(cd build/jetson && ctest -j4 | grep -E "tests passed|tests failed")
```
Binary: `build/jetson/app/vslam_node`.
Binary: `build/jetson/app/vslam_node`. `reset --keep` bao `Cannot merge` = Jetson dang co sua trong
repo: xem `git status` / `git diff` truoc. KHONG chay `git stash pop` khi chua biet stash dang giu gi.
Dinh vi lai bang camera (`--slam-reloc-vpr`) can them `-DVSLAM_WITH_TENSORRT=ON` luc
`cmake --preset jetson`, va mot engine TensorRT cho model VPR. Engine rieng tung may, tao MOT lan:
@@ -77,7 +89,8 @@ scp resources/vpr/eigenplaces_r50_2048_384x512.onnx <jetson>:<repo>/resources/vp
Chung cho moi lan chay, tu goc repo:
```sh
export VSLAM_CONFIG_DIR=$PWD/configuration_files # thieu thi node tu choi khoi dong
source tools/dev_env.sh # CHI may dev: thieu thi loi libusb_set_option (libpcl_io)
export VSLAM_CONFIG_DIR=$PWD/configuration_files # thieu thi node tu choi khoi dong
export VSLAM_RESOURCE_DIR=$PWD/resources
```
@@ -86,6 +99,10 @@ export VSLAM_RESOURCE_DIR=$PWD/resources
- DB ban do nam o `resources/maps/`. `{stamp}` trong ten file -> thoi diem khoi dong.
- Moi lan quet phai ra **file DB moi**. Node tu choi quet tiep vao DB da co.
- Tham so SLAM tu chon profile theo nguon: `--sim` -> `sim`, `--live` -> `real` (`slam.yaml`).
- Che do doc (`slope.enabled` trong `slam.yaml`) **mac dinh bat**, ca mo phong lan robot that.
San phang thi khong doi gi. Ban do quet truoc khi co che do doc van dung duoc, chi khong co do cao.
- Quet ban do co doc: di moi doc **ca len lan xuong**, lai them mot doan phang o hai dau doc.
Camera chi nhan ra cho da thay tu CUNG huong.
### Mo phong (may dev)
@@ -115,68 +132,177 @@ Dinh vi lai tu dong: dat robot o cho khac, **khong** cho pose ban dau.
--slam-reloc --slam-reloc-auto 2>&1 | tee logs/sim_reloc.log
```
Di tren doc: bat `slope.enabled: true` trong `slam.yaml` (xem ghi chu khoi `slope:`).
World thu `slope_test.world` co 5 lan doc 5/10/15/20/30 do noi hai mat bang chenh 1.5 m.
`--sim-imu-hz 100` cho IMU mo phong giong WT61PC sau khi doi 115200 baud.
**Doc:** world `slope_test.world` co 5 lan doc 5/10/15/20/30 do (tam lan x = 1.2 / 3.8 / 6.4 /
9.0 / 11.6, doc tu y = 8) noi hai mat bang chenh 1.5 m. `--sim-gl` ve camera bang GPU: anh IR co
texture (lay tu `~/gazebo_models/aws_hospital`), can build `-DVSLAM_SIM_WITH_GL=ON`. Khong co co nay
thi camera mo phong chi co depth, khong co anh -- dinh vi lai bang camera khong chay. IMU mo phong
mac dinh 200 Hz giong IMU that.
```sh
./build/app/vslam_node --sim --sim-gl --sim-imu-hz 100 --world resources/worlds/slope_test.world \
./build/app/vslam_node --sim --sim-gl --world resources/worlds/slope_test.world \
--x 6.4 --y 4.0 --yaw 1.5708 --max-speed 0.3 --token t \
--slam --slam-db "slope_{stamp}.db" --slam-mode mapping 2>&1 | tee logs/sim_slope.log
```
Web hien `z uoc luong` canh `z that`. Robot that: **doi WT61PC sang 115200 baud / 100 Hz
va dat `mcu.baud: 115200` truoc khi bat** -- IMU 10 Hz cho sai ~19 cm moi doc 1.5 m (sim).
Dinh vi lai ngay tren doc, co camera (vi du giua lan 10 do, nhin len doc):
```sh
./build/app/vslam_node --sim --sim-gl --world resources/worlds/slope_test.world \
--x 3.8 --y 12.0 --yaw 1.5708 --max-speed 0.3 --token t \
--slam --slam-db slope_YYYYMMDD_HHMMSS.db --slam-mode localization \
--slam-reloc --slam-reloc-auto --slam-reloc-vpr 2>&1 | tee logs/sim_reloc_slope.log
```
**World gon:** `slope_two_ramps.world` (`tools/gen_two_ramp_world.py`) -- sanh giua z = 0 (x 14.5-24.5),
hai doc RONG HET NHA (8 m): doc trai 10 do len tang trai, doc phai 15 do len tang phai, hai tang
z = 1.5 m. Quet mot vong (~85 m, ~5 phut): len doc trai -> vong tang trai -> xuong -> qua sanh ->
len doc phai -> vong tang phai -> xuong; moi doc di ca len lan xuong. Doc rong: di doc theo vai
lan (giua va sat hai tuong) de camera xoa het tuong gia o chan doc.
```sh
./build/app/vslam_node --sim --sim-gl --world resources/worlds/slope_two_ramps.world \
--x 19.5 --y 4.0 --yaw 3.1416 --max-speed 0.3 --token t \
--slam --slam-db "tworamps_{stamp}.db" --slam-mode mapping 2>&1 | tee logs/sim_tworamps_map.log
```
Dinh vi lai tren doc: giua doc trai `--x 10.25 --y 4.0` (`--yaw 3.1416` nhin len, `--yaw 0` nhin
xuong); giua doc phai `--x 27.31 --y 4.0` (`--yaw 0` nhin len, `--yaw 3.1416` nhin xuong); sat
tuong: `--y 0.8` hoac `--y 7.2`.
Web hien `z uoc luong` canh `z that`. Che do doc can IMU >= 100 Hz -- IMU 10 Hz cho sai ~19 cm
moi doc 1.5 m (sim).
### Robot that (Jetson)
**Cai mot lan** (Jetson moi hoac cai lai): luat udev cho IMU -- tao `/dev/imu` va dat do tre cap
FTDI 1 ms (mac dinh 16 ms gom ~3 mau 200 Hz mot lan, stamp IMU giat).
```sh
sudo cp configuration_files/udev/99-imu.rules /etc/udev/rules.d/
sudo udevadm control --reload-rules && sudo udevadm trigger && sudo udevadm settle
ls -l /dev/imu # -> ttyUSBn
cat /sys/bus/usb-serial/devices/ttyUSB*/latency_timer # 1
```
**Truoc moi lan chay**:
```sh
cd vslam_cpp
sudo systemctl stop xlocd motor_control && sudo systemctl mask --runtime xlocd motor_control # chiem LiDAR (UDP 2368), IMU va motor; mat khi khoi dong lai may
source /opt/ros/humble/setup.bash # chi de nap lib g2o
source /opt/ros/humble/setup.bash # chi de nap lib g2o
export LD_LIBRARY_PATH=/opt/vslam/lib:$LD_LIBRARY_PATH
export VSLAM_CONFIG_DIR=$PWD/configuration_files VSLAM_RESOURCE_DIR=$PWD/resources
export VSLAM_TOKEN=robot123 # doi chuoi nay; web: http://<jetson>:8080/?token=robot123
```
Quet ban do: bam **Start** tren tay cam de bat dieu khien, lai het khu vuc, **Ctrl-C de luu**.
Kiem IMU (tuy chon; cong phai ranh: sau khi tat dich vu, truoc khi chay node). Khong co
`--baud` / `--rate-hz` thi tool chi DO, khong ghi gi vao cam bien:
```sh
./build/jetson/app/vslam_node --live --gamepad --token <TOKEN> \
--slam --slam-db "real_{stamp}.db" --slam-mode mapping 2>&1 | tee -i logs/real_mapping.log
./build/jetson/tools/vslam_imu_config --port /dev/imu --guess 115200 # dat: 115200 baud, gyro ~200 Hz
```
Dinh vi lai tu dong: dat robot trong vung da quet, cach vat can >= 0.6 m, **luon co nguoi cam e-stop**.
Vai giay dau log phai co:
| Dong log | Nghia |
|---|---|
| `imu: WT61PC o /dev/imu @115200` va `imu: latency_timer cap FTDI = 1 ms` | IMU tot |
| `imu: khong co khung WT61PC hop le ...` | IMU im: kiem day, baud, hoac chuong trinh khac giu cong (`sudo fuser -v /dev/imu`) |
| `realsense: ... @ 30 Hz ...` | camera tot |
| `camera khong mo duoc, chay TIEP khong co camera` | kiem cap USB camera (`lsusb \| grep 8086`); camera dinh vi lai se KHONG chay |
| `slope: BAT -- ...` | che do doc dang bat (mac dinh) |
**Quet ban do**: bam **Start** tren tay cam de bat dieu khien, lai het khu vuc (doc: ca len lan
xuong), **Ctrl-C MOT lan** roi cho log in `slam: da luu ban do.` va `da dung.`.
```sh
./build/jetson/app/vslam_node --live --gamepad --token <TOKEN> \
--slam --slam-db real_YYYYMMDD_HHMMSS.db --slam-mode localization \
--slam-reloc --slam-reloc-auto 2>&1 | tee -i logs/real_reloc.log
./build/jetson/app/vslam_node --live --gamepad --token "$VSLAM_TOKEN" \
--slam --slam-db "real_{stamp}.db" --slam-mode mapping 2>&1 | tee -i logs/real_mapping_$(date +%m%d_%H%M).log
```
- Robot tu xoay ~300 do. Chua chot thi tu di toi da 1 m roi xoay lai
(0.12 m/s, 0.4 rad/s, toi da 6 vong / 12 m). Cham tay cam/web la no nhuong ngay.
- Tren web: robot **mo o goc map** toi khi chot, roi nhay ve dung cho. Chot
dung thi scan do khit tuong; log in `slam: DA DINH VI (x, y, yaw rad)`. Yaw tren web va log deu la radian.
- Bo `--slam-reloc-auto` thi nguoi tu xoay robot tai cho.
**Sao luu ban do NGAY** sau khi quet (02/10: mot ban do 811 node thanh 0 byte sau mot lan mat dien):
```sh
sync # Jetson
scp '<jetson>:<repo>/resources/maps/real_YYYYMMDD_HHMMSS.db' resources/maps/ # may dev; so kich thuoc hai ben
```
Tat may bang `sudo shutdown now`, khong rut nguon.
**Dinh vi lai tu dong**: dat robot trong vung da quet -- ca tren doc -- cach vat can >= 0.6 m,
**luon co nguoi cam e-stop**.
```sh
MAP=real_YYYYMMDD_HHMMSS.db # ten DB da quet: ls -lt resources/maps | head
./build/jetson/app/vslam_node --live --gamepad --token "$VSLAM_TOKEN" \
--slam --slam-db $MAP --slam-mode localization \
--slam-reloc --slam-reloc-auto --slam-reloc-vpr 2>&1 | tee -i logs/real_reloc_$(date +%m%d_%H%M).log
```
Bo `--slam-reloc-vpr` thi chi dung LiDAR (chua co engine TensorRT, hoac camera hong).
- San phang: robot tu xoay ~300 do; cu 30 do chup mot anh, chot SOM khi anh va LiDAR cung chi
mot cho. Chua chot thi tu di toi da 1 m roi xoay lai (0.12 m/s, 0.4 rad/s, toi da 6 vong / 12 m).
Log `bang camera+LiDAR` hoac `bang LiDAR`. Vi du 02/10 (mot cho): camera+LiDAR ~3 s, LiDAR ~13 s.
- Tren doc (nghieng > 3 do): **khong xoay**. Cho do nghieng IMU on dinh (~1 s), khop scan tai cho
moi 3 s, chup anh o giay cuoi moi vong. Camera chot khi >= 2 anh ban do cung chi mot cho, khop do
nghieng IMU va LiDAR khong phan doi -- log `bang camera tren doc`; chi nhan ra cho ma ban do co
anh chup **cung huong** (sim 06/10: dung 1.4-2.9 cm, huong nguoc thi khong chot). Tu chay: chua
chot thi bo thang 0.5 m (cho mu doc truc 1.5 m), khong lui, tong toi da 12 m.
- Dung **XIEN** tren doc (lech > 20 do so voi chieu doc): anh ban do chup doc theo doc nen camera
khong nhan ra. Tu chay (co camera): vong dau chua chot thi robot **QUAY mat theo chieu doc** (len
hoac xuong, phia gan hon -- huong doc lay tu IMU) roi khop lai -- log `QUAY ... de camera nhin doc
theo doc`. Khong tu chay thi web nhac nguoi xoay robot. Sim 06/10 doc rong: 8/8 cho xien chot dung
0.5-2.9 cm (11-100 s). Doc rong thi quet ca lan GIUA doc: ban do chi co hai lan sat tuong thi
camera khong nhan ra o giua doc, phai cho LiDAR.
- ⚠️ Dang nhin XUONG doc thi tu chay co the bao `phia truoc khong thoang` roi quay ngang tren doc
(thay trong sim, chua sua): cam e-stop, hoac bo `--slam-reloc-auto` -- tren doc robot van tu
khop tai cho, khong can nguoi xoay.
- Cham tay cam/web la tu chay nhuong ngay. Bo `--slam-reloc-auto` tren san phang thi nguoi tu xoay
robot tai cho.
- Tren web: robot **mo o cho bat dau quet** toi khi chot, roi nhay ve dung cho. Chot dung thi scan do khit
tuong; log in `slam: DA DINH VI (x, y, yaw rad)`. Yaw tren web va log deu la radian.
- Camera can: build `-DVSLAM_WITH_TENSORRT=ON`, file `resources/vpr/eigenplaces_r50_fp16.plan`,
`camera_3d: true` trong `slam.yaml` (mac dinh), DB quet co camera, va camera mo duoc (bang log o
tren). Khoi dong lau hon (tinh mo ta VPR cho moi anh ban do: 1362 anh mat ~7 s); log phai co
`camera cho dinh vi lai -- mo ta VPR N anh ban do`, thay `... CHI bang LiDAR` la camera chua bat.
Dong nay in TRUOC khi mo camera nen camera hong van thay -- chi tin dong chot.
- DB quet tren Jetson (RTAB-Map 0.23) khong mo duoc bang RTAB-Map 0.21 cua may dev.
Dinh vi lai co **camera** (VPR + PnP, chot khi trung LiDAR): them `--slam-reloc-vpr`.
**Test doc tu dong** (`--slope-test`): dat robot o DINH doc (cho phang, gan dau doc), chay dinh vi
lai kem `--slope-test`. Chot xong robot TU tim truc doc tren ban do (do cao san cua node), ve dinh
doc neu dinh vi lai da tu chay ra giua doc, quay mat XUONG doc, roi **cho bam Y** tren tay cam (mo
phong: tu chay). Moi luot: xuong toi chan doc (phang + 0.5 m), dung 3 s, quay dau, len lai dinh,
dung 3 s. Mac dinh 10 luot, van toc moi luot 0.10, 0.14, ..., 0.46 m/s (`--slope-test-loops N`,
`--slope-test-speeds 0.1,0.2,...` hoac `0.3:1.0` = chia deu cho so luot; toi da = tran an toan
0.5 m/s, sim nang bang `--max-speed V`; robot that bi base kep o `robot.yaml base.max_linear`).
```sh
./build/jetson/app/vslam_node --live --gamepad --token <TOKEN> \
--slam --slam-db real_YYYYMMDD_HHMMSS.db --slam-mode localization \
--slam-reloc --slam-reloc-auto --slam-reloc-vpr 2>&1 | tee -i logs/real_reloc_vpr.log
./build/jetson/app/vslam_node --live --gamepad --token "$VSLAM_TOKEN" \
--slam --slam-db $MAP --slam-mode localization \
--slam-reloc --slam-reloc-auto --slope-test 2>&1 | tee -i logs/real_slope_test_$(date +%m%d_%H%M).log
```
- Can: build `-DVSLAM_WITH_TENSORRT=ON`, file `resources/vpr/eigenplaces_r50_fp16.plan` (hoac
duong dan ngay sau co), `camera_3d: true` trong `slam.yaml`, va DB quet co camera.
- Khoi dong lau hon (tinh mo ta VPR cho moi anh ban do: 1362 anh mat ~7 s). Log phai co
`camera cho dinh vi lai -- mo ta VPR N anh ban do`; thay `... CHI bang LiDAR` la camera chua bat.
- Luc xoay, cu 30 do chup mot anh; chot SOM khi anh va LiDAR cung chi mot cho. Log ghi
`bang camera+LiDAR` hoac `bang LiDAR`. Vi du do 02/10 (mot cho, mot ban do): camera+LiDAR
chot sau ~3 s, LiDAR-only sau ~13 s.
- Trong mo phong: build them `-DVSLAM_SIM_WITH_GL=ON` (may co GPU) va chay `--sim --sim-gl` -- camera ve
bang GPU co anh IR (texture lay tu `~/gazebo_models/aws_hospital`). Khong co co nay thi chi co depth.
- Doi dong `slope_test: da quay mat xuong doc ... Bam Y` va NHIN robot: mat phai huong xuong doc.
Sai huong (vd quay vao tuong -- dinh vi lai chot nham cho) thi KHONG bam Y, Ctrl-C.
- Gat can tay cam / web / e-stop luc nao = **TAM DUNG**; bam Y de chay tiep.
- Tu **DUNG HAN** khi: lech khoi duong > 0.4 m, scan khong khop ban do 1.5 s, pose nhay > 0.3 m,
nghieng > 20 do, mot luot qua thoi gian. Lenh van qua lop an toan nhu moi lenh khac.
- ⚠️ `cliff_detect` dang TAT: luon co nguoi cam e-stop canh doc; chan doc can ~1 m phang de quay
dau. Khong chay lui (sau lung la quat mu LiDAR).
- Ket qua: 2 lan / giay ghi `logs/slope_test_<gio>.csv` -- lech dinh vi (doi pose de scan KHOP luoi
ban do nhat, doc lap voi RTAB-Map), goc, sai z so voi san ban do, do khop. Xong du luot thi in
**BANG TONG** theo luot / chieu + xu huong lech luot dau -> luot cuoi, ghi ra
`logs/slope_test_<gio>_tong.txt`, roi node **TU THOAT**. Ctrl-C giua chung cung in bang. Dung han
thi node CHAY TIEP de lai tay ra khoi doc, Ctrl-C de thoat. Sim 08/10: phep do bao du
~1-2 cm so voi ground truth (lech that 0.6-1.3 cm) va co diem vot khi scan it rang buoc doc truc
doc (doc dai giua hai tuong song song) -- dung de SO giua van toc / luot, khong phai thuoc tuyet doi.
**Lay log ve may dev:**
```sh
scp '<jetson>:<repo>/logs/real_*.log' logs/
```
Xong thi tra lai hai dich vu:

View File

@@ -69,7 +69,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
Reject(l, "sensors.yaml lidar",
{"host", "port", "expected_rate_hz", "range_min", "range_max",
"stamp_mismatch_warn", "sector_masks",
"angle_offset_deg", "angle_flip", "filters"});
"angle_offset_deg", "angle_flip", "filters",
"stamp_offset_sec", "deskew"});
if (!r.ok()) return r;
}
out->sanitizer.range_min = l.get<double>("range_min", 0.05);
@@ -94,6 +95,11 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
l.get<double>("angle_offset_deg", out->lidar_driver.angle_offset_deg);
out->lidar_driver.inverted =
l.get<bool>("angle_flip", out->lidar_driver.inverted);
// Gio scan so voi odometry va chinh meo -- do tren ban do that, xem
// sensors.yaml.
out->lidar_driver.stamp_offset_sec =
l.get<double>("stamp_offset_sec", out->lidar_driver.stamp_offset_sec);
out->lidar_driver.deskew = l.get<bool>("deskew", out->lidar_driver.deskew);
// --- Bon bo loc scan ---
const ConfigNode ft = l["filters"];
@@ -306,7 +312,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
{
const StatusResponse r =
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;
}
out->ekf.q_x = e.get<double>("q_x", out->ekf.q_x);
@@ -315,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_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_gyro_yaw = e.get<bool>("gyro_yaw", out->ekf_gyro_yaw);
const ConfigNode d = root["depth_filter"];
{
@@ -583,7 +590,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
const StatusResponse r =
Reject(v, "slam.yaml voxel",
{"emit_size_m", "z_min", "z_max", "max_cells", "delta_max_ratio",
"obstacle_z_min", "obstacle_z_max", "min_node_hits"});
"obstacle_z_min", "obstacle_z_max", "min_node_hits",
"clear_after_views"});
if (!r.ok()) return r;
out->voxel.emit_size_m = v.get<double>("emit_size_m", out->voxel.emit_size_m);
@@ -604,6 +612,13 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"slam.yaml voxel.min_node_hits phai >= 1");
}
out->voxel.min_node_hits = static_cast<size_t>(hits);
const int clear = v.get<int>("clear_after_views",
static_cast<int>(out->voxel.clear_after_views));
if (clear < 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml voxel.clear_after_views phai >= 0 (0 = tat)");
}
out->voxel.clear_after_views = static_cast<size_t>(clear);
if (out->voxel.emit_size_m <= 0.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
@@ -750,7 +765,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"min_angular_kick", "idle_publish_sec", "reopen_period_sec",
"turbo_linear", "turbo_angular", "slow_linear", "slow_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",
"invert_angular", "lt_stop", "axis_lt", "lt_press_above"});
if (!r.ok()) return r;
@@ -790,6 +805,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
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_test = gp.get<int>("button_test", out->gamepad.button_test);
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);

View File

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

View File

@@ -84,6 +84,15 @@ void Usage(const char* argv0) {
" 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",
argv0, vslam::ConfigDir().c_str());
}
@@ -189,6 +198,27 @@ int main(int argc, char** argv) {
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 == "--help" || a == "-h") { Usage(argv[0]); return 0; }
else {

View File

@@ -2,14 +2,17 @@
#include <pthread.h>
#include <sched.h>
#include <sys/stat.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <deque>
#include <limits>
#include <sstream>
#include "vslam/binary_codec.h"
#include "vslam/clock.h"
@@ -551,8 +554,10 @@ StatusResponse Runtime::Start() {
if (opts_.slam_reloc) {
const auto t0 = std::chrono::steady_clock::now();
OccupancyGrid g;
const StatusResponse gst =
ExportOccupancyGridFromDb(slam_->database_path(), 0.05, reloc_cfg_.max_range, &g);
// Cung cach cap nhat o (GridGlobal/*) voi ban do dang hien.
const std::map<std::string, std::string> gp = slam_->rtabmap_parameters();
const StatusResponse gst = ExportOccupancyGridFromDb(
slam_->database_path(), 0.05, reloc_cfg_.max_range, &g, nullptr, &gp);
if (!gst.ok()) {
return StatusResponse::Error(gst.code, "--slam-reloc: dung luoi tu DB: " + gst.message);
}
@@ -627,6 +632,7 @@ StatusResponse Runtime::Start() {
vo.z_max = cfg_->voxel.z_max;
vo.max_cells = cfg_->voxel.max_cells;
vo.min_node_hits = cfg_->voxel.min_node_hits;
vo.clear_after_views = cfg_->voxel.clear_after_views;
// Nap depth CUA MOI node (mac dinh 40 node/lan xuat): o day chi xuat
// MOT lan truoc khi chot -> 40/971 node chi la mot manh quanh goc map,
// trong nhu PCL cua phien dinh vi. Doi vai giay luc khoi dong; cache
@@ -659,6 +665,17 @@ StatusResponse Runtime::Start() {
}
reloc_active_ = true;
reloc_epoch_ = std::chrono::steady_clock::now();
// Cho ve robot truoc khi chot: node dau tien (xem reloc_view_origin_).
const std::vector<int> ids = slam_->MapNodeIds();
NodeView nv0;
if (!ids.empty() &&
slam_->GetNodeView(*std::min_element(ids.begin(), ids.end()), false, &nv0).ok()) {
reloc_view_origin_.x = nv0.T_map_base(0, 3);
reloc_view_origin_.y = nv0.T_map_base(1, 3);
reloc_view_origin_.theta = std::atan2(nv0.T_map_base(1, 0), nv0.T_map_base(0, 0));
VSLAM_INFO("slam: chua chot thi web ve robot tu cho bat dau quet (" << reloc_view_origin_.x
<< ", " << reloc_view_origin_.y << ", " << reloc_view_origin_.theta << " rad).");
}
const double dt = std::chrono::duration<double>(reloc_epoch_ - t0).count();
VSLAM_INFO("slam: DINH VI LAI TU DONG -- ban do " << g.width << "x" << g.height
<< " o (dung trong " << dt << " s). "
@@ -716,6 +733,24 @@ StatusResponse Runtime::Start() {
<< "Can IMU >= 100 Hz -- 10 Hz cho sai ~19 cm moi doc 1.5 m (sim G3).");
}
// Chinh meo scan: CHI LiDAR that (--live, --replay ban ghi that). Scan sim
// chup tuc thoi -- chinh meo o do la LAM meo.
deskew_on_ = cfg_->lidar_driver.deskew && opts_.source != SourceKind::kSim;
if (deskew_on_) {
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &laser_to_base_static_)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"deskew: robot.yaml khong co duong laser -> base_link");
}
const LidarConfig& lc = cfg_->lidar_driver;
sweep_.start_rad = lc.angle_offset_deg * M_PI / 180.0;
sweep_.dir = lc.inverted ? -1 : +1;
sweep_.period_s = lc.scan_freq_hz > 0.0 ? 1.0 / lc.scan_freq_hz : 0.04;
VSLAM_INFO("lidar: chinh meo scan BAT -- vong " << sweep_.period_s * 1e3 << " ms, bat dau "
<< lc.angle_offset_deg << " do, goc " << (sweep_.dir < 0 ? "GIAM" : "TANG")
<< " theo thoi gian; stamp_offset " << lc.stamp_offset_sec * 1e3
<< " ms. Ban cho SLAM / dinh vi lai, an toan + web giu scan tho.");
}
{
const StatusResponse st = Wire();
if (!st.ok()) return st;
@@ -803,12 +838,58 @@ StatusResponse Runtime::Start() {
safety_thread_ = std::thread([this] { SafetyLoop(); });
ApplyThreadPriority(&safety_thread_, cfg_->threads.safety_priority, "safety");
#ifdef VSLAM_HAVE_SLAM
// --- Test doc tu dong (--slope-test) ---
if (opts_.slope_test) {
if (!slam_enabled_ || !opts_.slam_reloc || !reloc_field_) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"--slope-test can --slam --slam-mode localization --slam-reloc: dung luoi ban do de "
"tim doc va do sai so");
}
SlopeTestConfig sc;
sc.loops = std::max(1, opts_.slope_test_loops);
if (!opts_.slope_test_speeds.empty()) sc.speeds = opts_.slope_test_speeds;
if (opts_.slope_test_vmax > 0.0) {
// A:B -> chia deu cho so luot (1 luot = A).
sc.speeds.clear();
for (int k = 0; k < sc.loops; ++k) {
const double u = sc.loops > 1 ? static_cast<double>(k) / (sc.loops - 1) : 0.0;
sc.speeds.push_back(opts_.slope_test_vmin + u * (opts_.slope_test_vmax - opts_.slope_test_vmin));
}
}
// Tran = tran cua lop an toan: 0.5 m/s (safety.yaml); sim --max-speed V nang
// ca ba tang (teleop, safety, base sim). Robot that: base ZLAC con tu kep o
// robot.yaml base.max_linear -- nang tran that la quyet dinh AN TOAN rieng.
const double vcap = cfg_->safety.max_linear;
std::string sp;
for (const double v : sc.speeds) {
if (!(v > 0.0) || v > vcap + 1e-9) {
std::ostringstream os;
os << "--slope-test-speeds: moi van toc phai trong (0, " << vcap
<< "] m/s (tran an toan" << (opts_.source == SourceKind::kSim ? "; sim: them --max-speed V" : "")
<< ")";
return StatusResponse::Error(StatusCode::kInvalidArgument, os.str());
}
sp += (sp.empty() ? "" : " / ") + std::to_string(v).substr(0, 4);
}
slope_test_.reset(new SlopeTest(sc));
VSLAM_INFO("slope_test: BAT -- " << sc.loops << " luot (xuong + len), van toc moi luot " << sp
<< " m/s. Dinh vi lai xong se tu tim doc tren ban do va quay mat xuong, roi "
<< (opts_.source == SourceKind::kSim ? "TU CHAY (mo phong)." : "cho bam Y."));
}
#endif
if (slam_enabled_) {
slam_thread_ = std::thread([this] { SlamLoop(); });
// CFS, KHONG realtime. Luong nay chan hang tram ms; cho no uu tien cao la
// cach chac chan nhat de treo vong an toan.
}
#ifdef VSLAM_HAVE_SLAM
if (slope_test_) slope_thread_ = std::thread([this] { SlopeLoop(); });
#endif
web_thread_ = std::thread([this] { WebLoop(); });
// web_tx chay CFS: no khong o trong vong an toan, va nang no len se lay mat
// CPU cua luong dang giu robot khong dam vao tuong.
@@ -840,11 +921,26 @@ void Runtime::Join() {
// `raw_cmd_` con duoc ghi ma khong con ai don no ve 0.
if (gamepad_thread_.joinable()) gamepad_thread_.join();
if (gamepad_) gamepad_->Close();
#ifdef VSLAM_HAVE_SLAM
// Test doc cung la NGUON LENH: tat truoc vong safety, cung ly do voi tay cam.
if (slope_thread_.joinable()) slope_thread_.join();
#endif
if (safety_thread_.joinable()) safety_thread_.join();
if (web_thread_.joinable()) web_thread_.join();
if (slam_thread_.joinable()) slam_thread_.join();
if (source_thread_.joinable()) source_thread_.join();
#ifdef VSLAM_HAVE_SLAM
// Ctrl-C giua chung: van in bang tong phan da do (luong slam da dung).
if (slope_test_ && !slope_summary_done_) {
SlopeTestPhase ph;
{
std::lock_guard<std::mutex> lk(slope_mu_);
ph = slope_test_->phase();
}
SlopeTestSummary(ph);
}
#endif
// Dung base TRUOC khi dong web: neu dong web truoc thi trong khoang giua,
// khong con ai gui lenh nhung robot van con van toc cuoi cung.
@@ -1088,6 +1184,12 @@ void Runtime::GamepadLoop() {
while (!stop_.load()) {
const GamepadState s = gamepad_->Snapshot();
GamepadCommand c = gamepad_map_->Step(s, clock_->Now());
#ifdef VSLAM_HAVE_SLAM
if (c.test_pressed) {
slope_button_.fetch_add(1);
if (slope_test_) VSLAM_INFO("gamepad: bam Y (test doc)");
}
#endif
if (c.connected_changed && s.connected) {
VSLAM_INFO("gamepad: da ket noi (" << gamepad_->DeviceInfo()
@@ -1236,6 +1338,11 @@ void Runtime::SlamLoop() {
// sai 1 m (docs/SLAM.md). Chot roi thi pose ban dau tinh tu CHINH odom
// nay -- khong tre, khong phai cho robot dung nhu ban ROS.
if (reloc_active_) {
if (slope_test_) {
// Dinh vi lai chay LAI sau khi test da co duong = mat dinh vi giua chung.
std::lock_guard<std::mutex> lk(slope_mu_);
if (slope_planned_) slope_lost_.store(true);
}
RelocStep(*scan, odom);
if (reloc_active_) continue;
}
@@ -1352,6 +1459,9 @@ void Runtime::SlamLoop() {
}
}
// --- Test doc tu dong: lap duong sau khi chot, do 2 Hz ---
if (slope_test_) SlopeTestSlamStep(out, *scan);
bool need_map = false;
{
std::lock_guard<std::mutex> lk(slam_mu_);
@@ -1463,6 +1573,7 @@ void Runtime::SlamLoop() {
vo.z_max = cfg_->voxel.z_max;
vo.max_cells = cfg_->voxel.max_cells;
vo.min_node_hits = cfg_->voxel.min_node_hits;
vo.clear_after_views = cfg_->voxel.clear_after_views;
VoxelGrid vg;
const auto t_vox = std::chrono::steady_clock::now();
@@ -1608,6 +1719,9 @@ constexpr double kRelocCreepBlind = 1.5; // m
// duoi chan doc truoc khi toi tuong xa -> mu toi khi ra gan chan doc.
constexpr double kRelocSlopeCreepMax = kRelocMaxDrive; // m
constexpr double kRelocCreepMargin = 0.6; // m chua truoc vat can (lop an toan dung 0.45)
// Tu chay tren doc co camera: dung XIEN qua goc nay so voi chieu doc thi quay mat
// theo doc (xem cho goi SlopeAlignTurn).
constexpr double kRelocSlopeAlignRad = 20.0 * M_PI / 180.0;
} // namespace
double Runtime::RelocFrontClear(const LaserScan& scan) const {
@@ -1640,7 +1754,10 @@ bool Runtime::RelocPoseAdmissible(const Pose2D& p, double tilt_r, double tilt_p)
const int r = static_cast<int>(std::lround((p.y - lf->origin_y()) / lf->resolution()));
if (!lf->Free(r, c)) return false;
double gx = 0.0, gy = 0.0;
if (!FloorGradientAt(slam_->floor_model(), p.x, p.y, reloc_cfg_.tilt_node_radius, &gx, &gy)) {
const FloorModel& fm = slam_->floor_model();
if (!FloorGradientAt(fm, p.x, p.y, reloc_cfg_.tilt_node_radius, &gx, &gy) &&
!FloorGradientBetween(fm, p.x, p.y, reloc_cfg_.tilt_between_radius,
std::tan(reloc_cfg_.tilt_agree_deg * M_PI / 180.0), &gx, &gy)) {
return true; // khong biet san o do -- khong loai
}
return TiltResidual(tilt_r, tilt_p, p.theta, gx, gy) <=
@@ -1811,16 +1928,18 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
const double err = AngleDiff(reloc_turn_target_, odom.theta);
const double t = std::chrono::duration<double>(now - reloc_phase_t0_).count();
if (std::fabs(err) < 5.0 * M_PI / 180.0 || t > kRelocPhaseTimeout) {
// Quay theo chieu doc: reloc_drive_len_ = 0 nen pha DI xong ngay, sang vong gom moi.
reloc_exec_ = RelocExec::kDrive;
reloc_drive_start_ = odom;
reloc_phase_t0_ = now;
reloc_aligning_ = false;
if (!yielding) RelocCommand(0.0, 0.0);
return;
}
if (!yielding) RelocCommand(0.0, err > 0.0 ? kRelocTurnRate : -kRelocTurnRate);
SetRelocStatus("TU QUAY ve huong thoang (con " +
std::to_string(static_cast<int>(std::fabs(err) * 180.0 / M_PI)) + " do)" +
(yielding ? " -- NHUONG NGUOI" : ""),
SetRelocStatus(std::string(reloc_aligning_ ? "QUAY THEO CHIEU DOC" : "TU QUAY ve huong thoang") +
" (con " + std::to_string(static_cast<int>(std::fabs(err) * 180.0 / M_PI)) +
" do)" + (yielding ? " -- NHUONG NGUOI" : ""),
true);
return;
}
@@ -2055,8 +2174,16 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
py.y, py.theta * 180.0 / M_PI);
}
VSLAM_WARN("slam: reloc chua chot -- " << buf << who);
// Dung XIEN tren doc: anh ban do chup DOC doc (luc quet robot di len / xuong) nen camera
// khong nhan ra goc xien (sim 06/10, doc rong: 8/8 cho xien khong chot, PnP 0-6 diem).
// Huong doc lay tu IMU, khong can biet pose.
double misalign = 0.0;
const double align = SlopeAlignTurn(tilt_r, tilt_p, &misalign);
const bool askew = vpr_ && reloc_static_round_ && misalign > kRelocSlopeAlignRad;
if (!running) {
SetRelocStatus(buf, true);
SetRelocStatus(std::string(buf) +
(askew ? " -- xoay robot DOC theo doc (len/xuong) de camera nhan ra" : ""),
true);
return;
}
// Tu chay: sang cho khac roi xoay tiep -- doi xung cuc bo thuong vo khi
@@ -2075,6 +2202,25 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
// < min_ratio thi DecideStatic tra truoc khi kiem doc truc (sim: giua lan
// dich 1 m giu 100% ma van bo tung 0.5 m sau 3 lan).
const bool blind = admit && shift_ratio >= reloc_cfg_.tilt_max_shift_ratio;
// Dung xien va LiDAR chua chac sau vong dau o cho nay -> quay mat theo chieu doc
// (len / xuong, phia gan hon) roi khop lai tai cho: anh camera moi giong anh ban
// do. Moi cho mot lan. Khong camera thi khong quay -- LiDAR khong loi gi ma them
// truot banh.
const bool lidar_sure = m.ok && m.ratio() >= reloc_cfg_.static_min_ratio && !blind;
if (askew && !reloc_aligned_here_ && !lidar_sure) {
reloc_aligned_here_ = true;
reloc_aligning_ = true;
reloc_static_here_ = 0;
reloc_static_hist_.clear();
reloc_turn_target_ = NormalizeAngle(odom.theta + align);
reloc_drive_len_ = 0.0;
reloc_exec_ = RelocExec::kTurn;
reloc_phase_t0_ = now;
VSLAM_INFO("reloc_exec: dung xien " << misalign * 180.0 / M_PI << " do so voi chieu doc -- QUAY "
<< align * 180.0 / M_PI << " do de camera nhin doc theo doc, roi khop lai tai cho.");
SetRelocStatus(std::string(buf) + " -- QUAY THEO CHIEU DOC", true);
return;
}
if (!blind && reloc_static_here_ < kRelocStaticBeforeCreep) {
RelocStartSweep();
VSLAM_INFO("reloc_exec: vong " << reloc_cycle_ << " chua chot -- tren doc: khop lai tai cho ("
@@ -2093,6 +2239,7 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
return;
}
reloc_static_here_ = 0;
reloc_aligned_here_ = false; // cho moi
reloc_creeping_ = true;
// Chot CHO nay truoc khi bo: chot "hai cho" so cho moi voi no.
if (!reloc_static_hist_.empty()) {
@@ -2134,6 +2281,7 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) {
return;
}
reloc_static_here_ = 0;
reloc_aligned_here_ = false;
if (reloc_exec_cycles_ >= kRelocMaxCycles || reloc_total_drive_ >= kRelocMaxDrive) {
RelocHalt("het tran " + std::to_string(kRelocMaxCycles) + " vong / " +
std::to_string(static_cast<int>(kRelocMaxDrive)) + " m");
@@ -2547,7 +2695,13 @@ void Runtime::RelocFinish(const Pose2D& map_from_odom, const Pose2D& odom,
slam_->UpdateHeights(zc);
}
double z_ref = 0.0;
if (slam_->HeightAt(pose.x, pose.y, 2.0, &z_ref)) {
// Giua doc rong (node gan nhat xa hon 2 m -- sim 06/10: z lech 0.75 m sau khi chot)
// thi noi suy giua hai lan cung mat doc. 0.3 m: z ban do hai lan da lech nhau 13 cm
// (sim 06/10); hai MAT khac nhau thi do doc da loai, nguong z chi chan hai san song
// song khac do cao (sanh 0 m / tang 1.5 m).
if (slam_->HeightAt(pose.x, pose.y, 2.0, &z_ref) ||
FloorZBetween(slam_->floor_model(), pose.x, pose.y, reloc_cfg_.tilt_between_radius,
std::tan(reloc_cfg_.tilt_agree_deg * M_PI / 180.0), 0.30, &z_ref)) {
std::lock_guard<std::mutex> lk(odom_mu_);
height_->Reset(z_ref, cfg_->slope.sigma_anchor);
height_anchored_ = true;
@@ -2613,6 +2767,8 @@ void Runtime::RelocWatch(const LaserScan& scan, const Pose2D& pose_map) {
reloc_static_hist_.clear();
reloc_static_places_.clear();
reloc_static_here_ = 0;
reloc_aligned_here_ = false;
reloc_aligning_ = false;
reloc_slope_creep_ = 0.0;
reloc_creeping_ = false;
if (opts_.slam_reloc_auto) {
@@ -2835,6 +2991,9 @@ void Runtime::WebLoop() {
: slam_enabled_ ? "dang cho"
: "off";
#ifdef VSLAM_HAVE_SLAM
// Dang dinh vi lai: ve robot tu cho bat dau quet, khong tu goc map (xem
// reloc_view_origin_). Chi la hien thi -- dinh vi lai van tinh trong frame odom.
if (!snap.slam.reloc.empty()) snap.pose_map = Pose2DCompose(reloc_view_origin_, ekf_pose);
// Dang dinh vi lai: ban do DB dung san luc Init.
if (slam_map_) {
snap.map = slam_map_;
@@ -3045,4 +3204,368 @@ void Runtime::WebLoop() {
}
}
#ifdef VSLAM_HAVE_SLAM
// ============================================================================
// Test doc tu dong (--slope-test). Logic lai o vslam/slope_test.h; o day chi
// noi day: lap duong tu ban do, lai 20 Hz, do 2 Hz, ghi CSV, bang tong.
// ============================================================================
void Runtime::SlopeLoop() {
const auto t0 = std::chrono::steady_clock::now();
auto next = t0;
int seen = slope_button_.load();
while (!stop_.load()) {
next += std::chrono::milliseconds(50);
bool planned = false;
{
std::lock_guard<std::mutex> lk(slope_mu_);
planned = slope_planned_;
}
const int b = slope_button_.load();
if (planned) {
SlopeTestInput in;
in.t = 1.0 + std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
Pose2D corr;
bool loc = false;
{
std::lock_guard<std::mutex> lk(slam_mu_);
corr = map_correction_;
loc = slam_localized_;
}
Pose2D od;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
}
// Pose MAP 20 Hz: phep nan cua RTAB-Map (3 Hz) x EKF (44 Hz).
in.pose = Pose2DCompose(corr, od);
// Chi tin DO DOC LAP: dinh vi lai chay lai / scan khop kem lien tiep
// (SlopeTestSlamStep). `slam_localized_` cua RTAB-Map khong dung duoc o day:
// localization chi bat no sau khi robot da chay.
(void)loc;
in.localized = !slope_lost_.load();
in.roll = tilt_roll_.load(std::memory_order_relaxed);
in.pitch = tilt_pitch_.load(std::memory_order_relaxed);
// Tay cam / web vua ra lenh, hoac e-stop: nhuong NGAY, cho bam Y.
in.human = RelocHumanCommanding() || estop_.load();
in.start = b != seen;
SlopeTestOutput o;
{
std::lock_guard<std::mutex> lk(slope_mu_);
o = slope_test_->Step(in);
}
// CUNG duong voi dinh vi lai tu dong: raw_cmd_ -> FSM an toan -> base.
if (o.command) RelocCommand(o.v, o.w);
if (!o.event.empty()) VSLAM_INFO("slope_test: " << o.event);
}
seen = b;
std::this_thread::sleep_until(next);
}
}
void Runtime::SlopeTestSlamStep(const SlamOutput& out, const LaserScan& scan) {
if (!reloc_field_) return;
const LikelihoodField& lf = *reloc_field_;
bool planned = false;
bool approaching = false;
SlopeTestPhase ph = SlopeTestPhase::kIdle;
int loop = 0;
bool down = true;
double speed = 0.0, along = 0.0, cross = 0.0;
{
std::lock_guard<std::mutex> lk(slope_mu_);
planned = slope_planned_;
ph = slope_test_->phase();
approaching = slope_test_->approaching();
loop = slope_test_->loop();
down = slope_test_->down();
speed = slope_test_->speed();
along = slope_test_->along();
cross = slope_test_->cross();
}
if (!planned) {
// ---- Lap duong, MOT lan, ngay sau khi chot ----
// Toi duoc day nghia la dinh vi lai DA CHOT (vong slam `continue` khi chua).
// KHONG cho `out.localized`: o localization no chi bat khi RTAB-Map tu khop
// duoc -- can robot DA CHAY, ma robot dang dung cho chinh test nay.
if (slope_plan_failed_) return;
const FloorModel& fm = slam_->floor_model();
if (fm.empty()) {
VSLAM_WARN("slope_test: ban do khong co do cao node (slam.yaml slope.enabled? ban do quet "
"truoc khi co che do doc?) -- KHONG chay.");
slope_plan_failed_ = true;
return;
}
// O trong VA du cho than robot: ban kinh than + 10 cm, tren luoi ban do.
const double clear = cfg_->robot.geometry().robot_radius + 0.10;
const double res = lf.resolution();
const int rr = static_cast<int>(std::ceil(clear / res));
auto free = [&](double x, double y) {
// Robot DA di qua cho nay luc quet -> di duoc. Luoi dinh vi lai (dung thang
// tu DB) con TUONG GIA o chan doc (tia LiDAR cham mat doc tu xa) -- lop
// camera chi xoa chung tren ban do hien thi. Sim 08/10: chan het moi huong
// xuong doc ngay chan doc.
FloorNode n;
double dn = 0.0;
if (fm.NearestNode(x, y, &n, &dn) && dn <= 0.35) return true;
// Goc luoi RTAB-Map la GOC o (0, 0) (xep o bang phep cat): tra bang floor.
const int c0 = static_cast<int>(std::floor((x - lf.origin_x()) / res));
const int r0 = static_cast<int>(std::floor((y - lf.origin_y()) / res));
for (int dr = -rr; dr <= rr; ++dr) {
for (int dc = -rr; dc <= rr; ++dc) {
if ((dr * dr + dc * dc) * res * res > clear * clear) continue;
if (!lf.Free(r0 + dr, c0 + dc)) return false;
}
}
return true;
};
// Chi tin mat san gan node da quet (doc rong quet theo lan: giua hai lan ~1.5 m).
auto floor = [&](double x, double y, double* z) {
double d = 0.0;
return fm.FloorAt(x, y, z, &d) && d <= 2.0;
};
SlopePath p;
std::string why, fan;
if (!PlanSlopePath(out.pose_map.x, out.pose_map.y, floor, free, SlopePathConfig{}, &p, &why,
&fan)) {
VSLAM_WARN("slope_test: " << why << " -- KHONG chay.");
slope_plan_failed_ = true;
return;
}
{
std::lock_guard<std::mutex> lk(slope_mu_);
slope_test_->SetPath(p, opts_.source == SourceKind::kSim);
slope_planned_ = true;
}
slope_t0_ = std::chrono::steady_clock::now();
VSLAM_INFO("slope_test: duong thu A (" << p.a.x << ", " << p.a.y << ") -> B (" << p.bx << ", "
<< p.by << "): dai " << p.length << " m, xuong " << p.drop << " m, huong "
<< p.a.theta * 180.0 / M_PI << " do. Dang quay mat xuong doc...");
VSLAM_INFO("slope_test: cac huong da thu (huong:duong trong:dung vi:ket qua):" << fan);
// CSV: logs/ o thu muc chay (goc repo).
::mkdir("logs", 0755);
char stamp[32];
const std::time_t tt = std::time(nullptr);
std::tm tmv{};
localtime_r(&tt, &tmv);
std::strftime(stamp, sizeof(stamp), "%Y%m%d_%H%M%S", &tmv);
slope_csv_path_ = std::string("logs/slope_test_") + stamp + ".csv";
slope_csv_ = std::fopen(slope_csv_path_.c_str(), "w");
if (slope_csv_ != nullptr) {
std::fprintf(slope_csv_,
"t_s,luot,chieu,van_toc,pha,doc_duong_m,lech_ngang_cm,x,y,yaw_deg,khop,"
"khop_tot_nhat,dx_cm,dy_cm,dyaw_deg,lech_cm,z_uoc_luong,z_ban_do,z_sai_cm\n");
} else {
VSLAM_WARN("slope_test: khong mo duoc " << slope_csv_path_ << " -- chi log.");
}
return;
}
if (ph == SlopeTestPhase::kDone || ph == SlopeTestPhase::kHalted) {
if (!slope_summary_done_) {
SlopeTestSummary(ph);
if (ph == SlopeTestPhase::kDone) {
// Xong du luot: TU THOAT (cung duong voi Ctrl-C: dung base, dong DB).
// Truoc day node chay tiep va log khac day troi mat bang tong.
VSLAM_INFO("slope_test: xong -- node tu thoat.");
RequestStop();
} else {
// Dung han (vi pham an toan): robot co the dang GIUA doc -- giu node de
// nguoi lai tay ra khoi doc.
VSLAM_WARN("slope_test: DUNG HAN -- node van chay de lai tay ra khoi doc; "
"Ctrl-C de thoat. Bang tong o tren.");
}
}
return;
}
if (ph != SlopeTestPhase::kDrive && ph != SlopeTestPhase::kDwell) return;
if (approaching) return; // dang ve A: chua phai luot do
const auto now = std::chrono::steady_clock::now();
if (now - slope_meas_at_ < std::chrono::milliseconds(500)) return;
slope_meas_at_ = now;
// ---- Do: lech dinh vi = phep doi pose lam scan KHOP ban do nhat ----
// Do doc lap voi RTAB-Map: chi scan hien tai + luoi ban do. Tho (+-20 cm,
// +-3 do) roi tinh (1 cm, 0.25 do).
const Pose2D pose = out.pose_map;
std::vector<Point> pts = ScanToFrame(scan, pose);
if (pts.size() > 400) {
std::vector<Point> sub;
const size_t stride = (pts.size() + 399) / 400;
for (size_t i = 0; i < pts.size(); i += stride) sub.push_back(pts[i]);
pts.swap(sub);
}
if (pts.size() < 50) return;
const double res = lf.resolution(), ox = lf.origin_x(), oy = lf.origin_y();
auto score = [&](double dx, double dy, double dth) {
const double c = std::cos(dth), s = std::sin(dth);
double sum = 0.0;
for (const Point& q : pts) {
const double rx = q.x - pose.x, ry = q.y - pose.y;
const double qx = pose.x + c * rx - s * ry + dx;
const double qy = pose.y + s * rx + c * ry + dy;
// floor, KHONG lround: goc luoi la GOC o (0, 0). lround lech nua o (2.5 cm
// moi truc) -- sim 08/10: lech gia -4 / -4 cm khi dinh vi that sai 1 cm.
sum += lf.At(static_cast<int>(std::floor((qy - oy) / res)),
static_cast<int>(std::floor((qx - ox) / res)));
}
return sum / static_cast<double>(pts.size());
};
const double deg = M_PI / 180.0;
const double s0 = score(0.0, 0.0, 0.0);
double bx = 0.0, by = 0.0, bth = 0.0, bs = s0;
for (int it = -3; it <= 3; ++it) {
for (int ix = -5; ix <= 5; ++ix) {
for (int iy = -5; iy <= 5; ++iy) {
const double v = score(ix * 0.04, iy * 0.04, it * deg);
if (v > bs) {
bs = v;
bx = ix * 0.04;
by = iy * 0.04;
bth = it * deg;
}
}
}
}
const double cx = bx, cy = by, cth = bth;
for (int it = -3; it <= 3; ++it) {
for (int ix = -4; ix <= 4; ++ix) {
for (int iy = -4; iy <= 4; ++iy) {
const double dx = cx + ix * 0.01, dy = cy + iy * 0.01, dth = cth + it * 0.25 * deg;
const double v = score(dx, dy, dth);
if (v > bs) {
bs = v;
bx = dx;
by = dy;
bth = dth;
}
}
}
}
// Mat dinh vi: scan khop KEM 3 lan do lien tiep (1.5 s) -> luong lai dung han.
if (s0 < 0.15) {
if (++slope_low_ >= 3) slope_lost_.store(true);
} else {
slope_low_ = 0;
}
bool have_z = false;
double z_est = 0.0, z_map = 0.0;
if (slope_on_) {
{
std::lock_guard<std::mutex> lk(odom_mu_);
z_est = height_->z();
}
have_z = slam_->HeightAt(pose.x, pose.y, 1.0, &z_map);
}
SlopeSample smp;
smp.loop = loop;
smp.down = down;
smp.speed = speed;
smp.moving = ph == SlopeTestPhase::kDrive;
smp.err_cm = std::hypot(bx, by) * 100.0;
smp.dth_deg = bth / deg;
smp.score = s0;
smp.have_z = have_z;
smp.zerr_cm = have_z ? (z_est - z_map) * 100.0 : 0.0;
slope_samples_.push_back(smp);
if (slope_csv_ != nullptr) {
const double t = std::chrono::duration<double>(now - slope_t0_).count();
std::fprintf(slope_csv_,
"%.2f,%d,%s,%.2f,%s,%.2f,%.1f,%.3f,%.3f,%.2f,%.3f,%.3f,%.1f,%.1f,%.2f,%.1f,%s,%s,%s\n",
t, loop, down ? "xuong" : "len", speed, smp.moving ? "chay" : "dung", along,
cross * 100.0, pose.x, pose.y, pose.theta / deg, s0, bs, bx * 100.0, by * 100.0,
smp.dth_deg, smp.err_cm, have_z ? std::to_string(z_est).c_str() : "",
have_z ? std::to_string(z_map).c_str() : "",
have_z ? std::to_string(smp.zerr_cm).c_str() : "");
std::fflush(slope_csv_);
}
}
void Runtime::SlopeTestSummary(SlopeTestPhase end) {
slope_summary_done_ = true;
if (slope_csv_ != nullptr) {
std::fclose(slope_csv_);
slope_csv_ = nullptr;
}
// Moi dong vua log vua ghi ra logs/slope_test_<gio>_tong.txt: terminal con in
// log khac sau do (node chay tiep khi dung han) va bang troi mat.
std::FILE* tong = nullptr;
std::string tong_path;
if (!slope_csv_path_.empty()) {
tong_path = slope_csv_path_.substr(0, slope_csv_path_.size() - 4) + "_tong.txt";
tong = std::fopen(tong_path.c_str(), "w");
}
auto out = [&](const std::string& line) {
VSLAM_INFO("slope_test: " << line);
if (tong != nullptr) std::fprintf(tong, "%s\n", line.c_str());
};
if (slope_samples_.empty()) {
out(std::string("khong co mau do nao (") + SlopeTestPhaseName(end) + ").");
if (tong != nullptr) std::fclose(tong);
return;
}
// "trung vi / 95% / lon nhat" cua |x|.
auto stats = [](std::vector<double> v) {
for (double& x : v) x = std::fabs(x);
std::sort(v.begin(), v.end());
char buf[64];
if (v.empty()) return std::string("--");
const double med = v[v.size() / 2];
const double p95 = v[std::min(v.size() - 1, static_cast<size_t>(0.95 * (v.size() - 1) + 0.5))];
std::snprintf(buf, sizeof(buf), "%5.1f /%5.1f /%5.1f", med, p95, v.back());
return std::string(buf);
};
out("===== BANG TONG (" + std::string(SlopeTestPhaseName(end)) + ", " +
std::to_string(slope_samples_.size()) + " lan do, 2 Hz) =====");
out(" luot chieu v m/s n | lech cm tv / 95% / max | goc do tv / 95% / max"
" | z sai cm tv / 95% / max | khop tb");
int max_loop = 0;
for (const SlopeSample& s : slope_samples_) max_loop = std::max(max_loop, s.loop);
std::vector<double> first_err, last_err;
for (int l = 1; l <= max_loop; ++l) {
for (const bool dn : {true, false}) {
std::vector<double> e, a, z;
double sc = 0.0, v = 0.0;
for (const SlopeSample& s : slope_samples_) {
if (s.loop != l || s.down != dn) continue;
e.push_back(s.err_cm);
a.push_back(s.dth_deg);
if (s.have_z) z.push_back(s.zerr_cm);
sc += s.score;
v = s.speed;
}
if (e.empty()) continue;
if (l == 1) first_err.insert(first_err.end(), e.begin(), e.end());
if (l == max_loop) last_err.insert(last_err.end(), e.begin(), e.end());
char head[64];
std::snprintf(head, sizeof(head), "%4d %-5s %.2f %3zu", l, dn ? "xuong" : "len", v, e.size());
char sc_buf[16];
std::snprintf(sc_buf, sizeof(sc_buf), "%.3f", sc / e.size());
out(std::string(head) + " | " + stats(e) + " | " + stats(a) + " | " + stats(z) + " | " +
sc_buf);
}
}
std::vector<double> all_e, all_a, all_z;
for (const SlopeSample& s : slope_samples_) {
all_e.push_back(s.err_cm);
all_a.push_back(s.dth_deg);
if (s.have_z) all_z.push_back(s.zerr_cm);
}
out(" TONG | " + stats(all_e) + " | " + stats(all_a) + " | " + stats(all_z) + " |");
if (max_loop > 1) {
out("xu huong lech (trung vi) luot 1 -> luot " + std::to_string(max_loop) + ": " +
stats(first_err).substr(0, 5) + " -> " + stats(last_err).substr(0, 5) +
" cm (tang deu = ban do / dinh vi troi dan)");
}
if (!slope_csv_path_.empty()) out("CSV: " + slope_csv_path_);
if (tong != nullptr) {
std::fclose(tong);
VSLAM_INFO("slope_test: bang tong da ghi ra " << tong_path);
}
}
#endif
} // namespace vslam

View File

@@ -28,6 +28,7 @@
#include <atomic>
#include <chrono>
#include <cstdio>
#include <deque>
#include <functional>
#include <memory>
@@ -40,6 +41,7 @@
#include "app_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/ekf_se2.h"
#include "vslam/gyro_yaw_fuser.h"
#include "vslam/elevation_map.h"
#include "vslam/gamepad.h"
#include "vslam/geometry.h"
@@ -56,6 +58,7 @@
#include "vslam/global_localizer.h"
#include "vslam/rtabmap_slam.h"
#include "vslam/visual_verifier.h"
#include "vslam/slope_test.h"
#include "vslam/voxel_export.h"
#include "vslam/vpr_encoder.h"
#endif
@@ -118,6 +121,14 @@ struct RuntimeOptions {
// 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 {
@@ -205,6 +216,13 @@ class Runtime {
// 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);
@@ -410,8 +428,17 @@ class Runtime {
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;
@@ -462,6 +489,32 @@ class Runtime {
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
// Doc-only sau Start(), nen khong can mutex.
@@ -490,12 +543,16 @@ class Runtime {
Pose2D prev_odom_;
UnixTime prev_odom_stamp_;
bool have_prev_odom_ = false;
double gyro_z_ = 0.0;
UnixTime gyro_stamp_;
// Tich phan gyro giua hai lan cap nhat odom, va tong thoi gian da phu.
double gyro_dtheta_ = 0.0;
double gyro_dt_ = 0.0;
bool have_gyro_ = false;
// Goc quay cho EKF: gyro giu tong, encoder lap khoang gyro chua ve (xem
// gyro_yaw_fuser.h). Duoi `odom_mu_`.
GyroYawFuser yaw_fuser_;
// Chan doan goc quay 30 s mot lan (wiring.cc). Duoi `odom_mu_`.
double yaw_diag_enc_ = 0.0;
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
// snapshot roi dem voi pose cu la do DO TRE chu khong phai sai so.
@@ -547,6 +604,10 @@ class Runtime {
// Tinh, doc-only sau Start(): base_link <- laser_link / camera optical.
Transform laser_to_base_static_ = TransformIdentity();
Transform cam_to_base_static_ = TransformIdentity();
// Chinh meo scan (sensors.yaml `lidar.deskew`, CHI LiDAR that). Doc-only sau
// Start(); can laser_to_base_static_ o tren.
bool deskew_on_ = false;
SweepTiming sweep_;
bool have_cam_to_base_ = false;
// CHI luong slam: lan giai do thi z cuoi; da neo z lan nao chua (lan DAU
// sau khoi dong / dinh vi lai thi DAT THANG z ban do, khong qua cong).

View File

@@ -41,9 +41,22 @@ StatusResponse Runtime::Wire() {
auto copy = std::make_shared<LaserScan>(*s);
sanitizer_->Apply(copy.get());
// Di tren doc: ban BU NGHIENG + bo tia cham san cho SLAM / dinh vi lai.
// An toan va web giu ban tho. Tat thi hai con tro la MOT.
// Ban cho SLAM / dinh vi lai: CHINH MEO (LiDAR that) roi BU NGHIENG (doc).
// An toan va web giu ban tho. Tat ca hai thi hai con tro la MOT.
LaserScanPtr slam_scan = copy;
if (deskew_on_) {
// w ~ gyro 200 Hz qua EKF (lech 0.008 rad/s x 40 ms: khong dang ke),
// v theo encoder. Kep de mot mau van toc hong khong be cong scan.
double w = 0.0, v = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
w = std::max(-2.0, std::min(2.0, ekf_->vyaw()));
v = std::max(-1.0, std::min(1.0, ekf_->vx()));
}
auto dsk = std::make_shared<LaserScan>();
DeskewScan(*copy, laser_to_base_static_, sweep_, w, v, dsk.get());
slam_scan = dsk;
}
if (slope_on_ && cfg_->slope.level_scan) {
Pose2D od;
double z = 0.0;
@@ -57,9 +70,16 @@ StatusResponse Runtime::Wire() {
auto lv = std::make_shared<LaserScan>();
{
std::lock_guard<std::mutex> lk(elev_mu_);
LevelScan(*copy, laser_to_base_static_, roll, pitch,
LevelScan(*slam_scan, laser_to_base_static_, roll, pitch,
cfg_->robot.geometry().wheel_radius, od, z, elev_.get(), level_cfg_,
lv.get(), &level_stats_);
// Ti le tia giu lai (cong don tu luc chay) -- san phang phai ~100%.
// 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;
}
@@ -87,21 +107,10 @@ StatusResponse Runtime::Wire() {
std::lock_guard<std::mutex> lk(odom_mu_);
wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z);
// ⚠️ TICH PHAN gyro, khong lay mot mau.
//
// IMU chay 200 Hz con encoder 50 Hz, nen moi khoang odom co ~4 mau.
// Lay MOT mau roi nhan voi ca khoang 20 ms la phep hinh chu nhat tren
// 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;
// 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
// GyroYawFuser.
yaw_fuser_.AddGyro(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]
@@ -137,6 +146,8 @@ StatusResponse Runtime::Wire() {
// ---------------- Encoder ----------------
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) {
if (!e.valid) return;
Odometry o;
@@ -166,19 +177,25 @@ StatusResponse Runtime::Wire() {
double d_theta = NormalizeAngle(now_pose.theta - prev_odom_.theta);
const double dt = SecondsBetween(e.stamp, prev_odom_stamp_);
// Gyro da duoc TICH PHAN trong callback IMU. Chi nhan neu no phu
// gan het khoang odom -- thieu mau thi tich phan khong dai dien.
// Cua so gyro phai KHOP buoc encoder. IMU that 10 Hz (T=0.1002 s),
// encoder ~44 Hz: mot mau gyro mang 0.1 s goc quay do vao buoc 23 ms
// trong khi cac buoc truoc da cong goc encoder -> goc dem HAI LAN.
const bool gyro_ok =
dt > 0.0 && gyro_dt_ > 0.5 * dt && gyro_dt_ < 1.5 * dt;
if (dt > 0.0 && gyro_dt_ >= 1.5 * dt) {
VSLAM_WARN_THROTTLE(30.0, "odom: gyro cham hon encoder (cua so "
<< gyro_dt_ << " s / buoc " << dt << " s) -- bo gyro, dung goc "
"encoder. Tang toc do IMU len >= 100 Hz de dung duoc gyro.");
// Goc gyro cho buoc nay: GyroYawFuser -- gyro giu TONG, encoder chi lap
// khoang gyro chua ve. Cach cu tich gyro theo luc mau TOI va chi nhan
// khi cua so dai 0.5-1.5 buoc encoder, ngoai do VUT: tren robot that
// mau toi theo cum (log 07/10: cua so 40 ms / buoc 22.5 ms) -> ban do
// real_20261007_112455 dem THIEU 9.9% moi goc quay (cac cap node dung
// yen hai dau van 9.6%: loi ti le, khong phai lech gio). IMU cham
// (10 Hz) / het tuoi thi chi encoder, nhu truoc 06/10.
double d_theta_gyro = d_theta;
const bool gyro_step = dt > 0.0 && yaw_fuser_.Step(e.stamp, d_theta, &d_theta_gyro);
// EKF chi lay goc gyro khi pipeline.yaml `ekf.gyro_yaw: true`. Mac dinh
// 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
// cho no noi "dang truot, dung tin toi".
@@ -199,8 +216,32 @@ StatusResponse Runtime::Wire() {
height_->OnWheelStep(d_trans, pitch);
if (cfg_->slope.horizontal_odom) d_trans_ekf = d_trans * std::cos(pitch);
}
ekf_->UpdateOdomDelta(e.stamp, d_trans_ekf, d_theta, d_theta_gyro,
// 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).
@@ -215,8 +256,6 @@ StatusResponse Runtime::Wire() {
odom_hist_.pop_front();
}
}
gyro_dtheta_ = 0.0;
gyro_dt_ = 0.0;
prev_odom_ = now_pose;
prev_odom_stamp_ = e.stamp;
have_prev_odom_ = true;

View File

@@ -14,6 +14,13 @@ ekf:
# 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.
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_filter:

View File

@@ -72,6 +72,22 @@ lidar:
# |(t_cuoi - t_dau) - scan_time| > nguong nay.
stamp_mismatch_warn: 0.005
# --- Gio cua scan so voi odometry: DO tren ban do that ---
# Driver dong dau scan luc NHAN XONG vong quet. ICP scan luc robot dang QUAY
# voi scan gan do luc gan dung yen (ban do 28/09 + 01/10, 88 + 179 cap): scan
# tre +55..57 ms so voi odometry SAU khi chinh meo (+72..79 ms neu khong).
# Quay 0.8 rad/s ma khong bu -> moi scan lech 2.5-3.5 do, tuong dup sau moi
# lan quay. Doi phan cung / driver thi do lai.
stamp_offset_sec: -0.055
# Chinh meo: moi tia chup o mot thoi diem khac trong vong quet 40 ms (25 Hz);
# quay 0.8 rad/s thi tia dau va tia cuoi lech 1.8 do. Dua moi tia ve khung
# robot luc stamp theo w, v cua EKF. Chieu quet DO tren ban do that: goc GIAM
# theo thoi gian khi angle_flip: true (vong bat dau o angle_offset_deg, phia
# sau); chieu nguoc lai lam scan khop TE hon. Chi LiDAR that (--live,
# --replay) -- scan sim chup tuc thoi. Ban cho SLAM / dinh vi lai; an toan va
# web van dung scan tho.
deskew: true
# ============ BON BO LOC SCAN ============
# Chay TREN scan tho, truoc ScanSanitizer. Nguon: lakibeam.yaml cua
# base_kit -- bo tham so da duoc chinh tren chinh con robot nay.
@@ -264,13 +280,12 @@ mcu:
# 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 -> 0.01 la UOC LUONG, CHUA DO ---
# ~2 ms day 2 khung Acc+Gyro qua day 115200 baud
# ~3-10 ms loc / trung binh noi bo o che do 200 Hz (o 10 Hz la ~50 ms)
# ~1 ms USB (latency_timer 1 ms, xem luat udev)
# Giu 0.07 o 200 Hz la lech gyro ~60 ms. Do lai theo quy trinh tren: may do
# co bin 10 ms, nen lan chay sau bao ~0 ms la dat.
imu_lag_sec: 0.01
# --- 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
# thuc cu chi co I/B/P.

View File

@@ -170,6 +170,15 @@ voxel:
# Tuong va ban ghe dung yen thi nhieu node thay nen van giu.
min_node_hits: 3
# LAN NHIN MOI NHAT QUYET DINH (07/10). Truoc day lop nay CHI THEM: 3 nguoi
# dung tren duong luc quet thanh vat can vinh vien, quay lai quet van con.
# Gio: voxel ma >= bay nhieu node SAU lan thay cuoi nhin XUYEN qua (depth xa
# hon voxel + 0.10 + 0.03 z^2 m) va khong node nao trong do con thay -> XOA,
# ca khoi ban do 3D lan lop vat can 2D. Bi che (depth gan hon) thi khong tinh
# -- khong biet thi khong xoa. Ap ca luc quet lan luc mo ban do da luu.
# 0 = tat (chi them, nhu truoc).
clear_after_views: 2
# ============ VONG DONG XA (chi khi quet) ============
# Phat hien ke can cua RTAB-Map chi xet node trong 50 buoc do thi
# (RGBD/ProximityMaxGraphDepth), nen quay lai cho cu sau mot vong DAI thi
@@ -208,16 +217,19 @@ far_loops:
#
# ⚠️ CAN IMU >= 100 Hz. Do trong sim (G3, 03/10): IMU 100 Hz -> sai dz qua doc
# 1.5 m trung vi 1.8 cm, max 8 cm; IMU 10 Hz (WT61PC mac dinh, 9600 baud) ->
# 19 cm, va khong chinh bo loc nao cuu duoc. Doi cam bien sang 115200 baud /
# 100 Hz va dat `mcu.baud: 115200` trong sensors.yaml TRUOC khi bat.
# 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.
#
# enabled: false = moi duong cu giu nguyen.
# 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: false
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)
@@ -297,6 +309,16 @@ rtabmap:
Grid/CellSize: "0.05"
Grid/RangeMax: "12.0"
Grid/RayTracing: "true"
# Luoi 2D theo LAN NHIN MOI NHAT (07/10). Moi o cong log-odds: trung +0.85,
# truot (tia di xuyen qua) -0.62, kep trong [-1.39, +1.39]. Mac dinh RTAB-Map
# kep +3.5 va truot -0.41: o da chac chiem can ~9 lan nhin xuyen qua moi xoa
# -> nguoi dung lai roi di, quay lai quet van con tren ban do. Bo nay: 3 lan
# xuyen qua -> trong, 2 lan thay vat -> chiem. Doi lai: vat rat manh (chan
# ghe) co the chap chon khi tia luot sat ben canh.
GridGlobal/ProbHit: "0.7"
GridGlobal/ProbMiss: "0.35"
GridGlobal/ProbClampingMin: "0.2"
GridGlobal/ProbClampingMax: "0.8"
Grid/3D: "false"
Grid/DepthDecimation: "4"

View File

@@ -161,6 +161,7 @@ gamepad:
button_zero: 1 # B -- ve 0 ngay
button_turbo: 5 # RB
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.
#

View File

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

View File

@@ -100,6 +100,9 @@ struct GamepadConfig {
int button_zero = 1; // B -- ve 0 ngay
int button_turbo = 5; // RB
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
// 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.
bool enabled_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.
@@ -215,6 +221,7 @@ class GamepadMapper {
bool enable_pressed_ = false; // chong dap phim, = start_pressed_ ben kia
bool was_connected_ = false;
bool have_active_ = false; // da tung co lenh chuyen dong
bool test_prev_ = false; // nut test vong truoc (bat canh len)
UnixTime last_active_;
};

View File

@@ -91,6 +91,7 @@ GamepadCommand GamepadMapper::Step(const GamepadState& s, UnixTime now) {
enabled_ = false;
enable_pressed_ = false;
was_connected_ = false;
test_prev_ = false;
}
out.enabled = false;
// 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;
}
// --- 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 --------------------------------------
// joy_control_node.cpp:180-194. Chong dap phim bang co canh len.
if (s.Button(cfg_.button_enable)) {

View File

@@ -8,6 +8,7 @@ vslam_add_library(vslam_odometry
wheel_odometry.h
ekf_se2.h
height_estimator.h
gyro_yaw_fuser.h
PUBLIC_DEPS
vslam_common
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,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

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

View File

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

View File

@@ -38,6 +38,7 @@ vslam_add_library(vslam_slam
sensor_data_builder.h
occupancy_export.h
voxel_export.h
slope_test.h
height_map.h
global_localizer.h
vpr_encoder.h

View File

@@ -92,6 +92,13 @@ struct GlobalLocalizerConfig {
// 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 ->

View File

@@ -30,6 +30,7 @@
//
// Khong phu thuoc RTAB-Map -- test duoc rieng.
#include <cstddef>
#include <map>
#include <vector>
@@ -82,6 +83,7 @@ class FloorModel {
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_;
@@ -98,6 +100,20 @@ double PlaneZ(const FloorNode& n, double x, double y);
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
@@ -105,6 +121,11 @@ bool FloorGradientAt(const FloorModel& fm, double x, double y, double max_dist,
// 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,7 @@
// canh bao -- cho toi khi goi `uncompressDataConst()`. Do dung la ly do
// `tools/probe_rtabmap` lan dau chay ra "1990 node, 0 o".
#include <map>
#include <set>
#include <string>
@@ -44,10 +45,13 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out);
// `only_ids`: chi dung cac node co id trong tap nay (nullptr = moi node). De
// do relocalization CONG BANG tren mot phien: ban do tu nua dau, hoi bang nua
// sau -- scan dung de hoi khong duoc gop vao ban do.
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max,
OccupancyGrid* out,
const std::set<int>* only_ids = nullptr);
//
// `grid_params`: tham so RTAB-Map dang chay -- lay GridGlobal/* (cach cap nhat
// o) tu day. nullptr = theo tham so DB da luu luc quet.
StatusResponse ExportOccupancyGridFromDb(
const std::string& db_path, double cell_size, double range_max, OccupancyGrid* out,
const std::set<int>* only_ids = nullptr,
const std::map<std::string, std::string>* grid_params = nullptr);
} // namespace vslam

View File

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

View File

@@ -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

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

View File

@@ -147,16 +147,86 @@ bool FloorModel::FloorAt(double x, double y, double* z, double* dist) const {
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;
// Dao ham cua PlaneZ: z = z_n - fwd * tan(pitch) + left * tan(roll).
const double c = std::cos(n.theta), s = std::sin(n.theta);
const double tp = std::tan(n.pitch), tr = std::tan(n.roll);
*gx = -tp * c - tr * s;
*gy = -tp * s + tr * c;
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;
}
@@ -171,4 +241,16 @@ double TiltResidual(double roll, double pitch, double yaw, double gx, double gy)
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,
const std::map<int, rtabmap::Transform>& poses,
double cell_size, double range_max,
const rtabmap::ParametersMap& slam_params,
OccupancyGrid* out) {
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"khong co pose nao de dung grid");
}
rtabmap::ParametersMap params;
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridCellSize(),
std::to_string(cell_size)));
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGrid3D(), "false"));
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridRangeMax(),
std::to_string(range_max)));
// Cach cap nhat o (GridGlobal/*: xac suat trung / truot / kep) THEO RTAB-Map
// dang chay (slam.yaml). Truoc 07/10 khong truyen -> luon mac dinh RTAB-Map:
// o da chac chiem can ~9 lan nhin xuyen qua moi xoa, nen nguoi dung lai roi
// di van nam tren ban do sau khi quay lai quet.
for (const auto& kv : slam_params) {
if (kv.first.rfind("GridGlobal/", 0) == 0) params.insert(kv);
}
params[rtabmap::Parameters::kGridCellSize()] = std::to_string(cell_size);
params[rtabmap::Parameters::kGrid3D()] = "false";
params[rtabmap::Parameters::kGridRangeMax()] = std::to_string(range_max);
rtabmap::OccupancyGrid grid(&cache, params);
grid.update(poses);
@@ -135,13 +141,14 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out) {
cache.add(kv.first, data.gridGroundCellsRaw(), data.gridObstacleCellsRaw(),
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
}
return BuildFromCache(cache, poses, 0.05, 12.0, out);
return BuildFromCache(cache, poses, 0.05, 12.0, slam.getParameters(), out);
}
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max,
OccupancyGrid* out,
const std::set<int>* only_ids) {
const std::set<int>* only_ids,
const std::map<std::string, std::string>* grid_params) {
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
bool opened = false;
try {
@@ -175,6 +182,10 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
with_grid++;
}
// Cach cap nhat o: theo nguoi goi (tham so dang chay), khong thi theo tham
// so DB da luu luc quet.
const rtabmap::ParametersMap slam_params =
grid_params != nullptr ? *grid_params : driver->getLastParameters();
driver->closeConnection(false);
if (with_grid == 0) {
@@ -182,7 +193,7 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
StatusCode::kFailedPrecondition,
"khong node nao co local grid -- ban do quet voi Grid/FromDepth sai?");
}
return BuildFromCache(cache, poses, cell_size, range_max, out);
return BuildFromCache(cache, poses, cell_size, range_max, slam_params, out);
}
} // namespace vslam

View File

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

View File

@@ -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

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

View File

@@ -12,7 +12,7 @@ const MAGIC = 0x314C5356; // 'VSL1' little-endian
// Phien ban ma nguon giao dien. TANG khi doi app.js / app3d.js / style.css.
// Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con
// cache ban cu".
const UI_VERSION = '2026-10-05c';
const UI_VERSION = '2026-10-07b';
// ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau.
//
@@ -393,6 +393,7 @@ function rasterize(map, pal) {
function onState(s) {
state.pose = s.pose;
noteStatePose(s);
// Khong co truong nay = server khong bu duoc do tre scan. Dat null chu
// khong dat {0,0,0}: mot delta 0 gia mao la "da bu", con null thi lop ve
// biet la chua co gi va dung pose hien tai nhu truoc.
@@ -427,7 +428,7 @@ function onState(s) {
const bn = document.getElementById('relocBanner');
if (bn) {
bn.style.display = state.relocPending ? 'block' : 'none';
bn.textContent = 'CHUA DINH VI -- robot tam o GOC map, scan chua khop tuong -- ' +
bn.textContent = 'CHUA DINH VI -- robot tam ve o CHO BAT DAU QUET, scan chua khop tuong -- ' +
(state.relocText || 'dang tu tim vi tri');
}
@@ -615,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.
//
// Moi lop toi theo nhip rieng (cloud 2 Hz, scan 10 Hz) con trang ve lai moi
@@ -704,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
// phai pose hien tai: moi lop neo vao pose no thuoc ve, xem anchorPose().
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) {
// Ground truth ve TRUOC pose uoc luong, de pose ve de len tren: cai ta
@@ -714,7 +775,7 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
if (state.cloud && on('lyCloud')) {
// 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 pts = state.cloud;
for (let i = 0; i < pts.length; i += 3) {
@@ -739,7 +800,7 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
const ly = (state.robot && state.robot.laser_y) || 0;
// 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.
const sp = anchorPose(p, state.scanPose);
const sp = anchorPose(anchor, state.scanPose);
const sc = Math.cos(sp.yaw), ss = Math.sin(sp.yaw);
for (let i = 0; i < pts.length; i += 2) {
const bx = pts[i] + lx, by = pts[i + 1] + ly;
@@ -751,7 +812,7 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
// Dang DINH VI LAI (--slam-reloc): robot TAM o goc map (odom tu 0) -> ve MO.
// Chot xong moi nhay ve cho that. Dong chu trang thai nam o #relocBanner.
const faded = state.relocPending && robotPose === state.pose;
const faded = state.relocPending && robotPose === state.dispPose;
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, pal.robot, faded ? 0.35 : 1.0, pal);
}
}
@@ -792,6 +853,9 @@ function updateSlamLabel() {
}
function draw() {
// Pose HIEN THI cho MOI khung ve duoi day -- tinh MOT lan moi khung hinh, vi
// displayPose() truot theo thoi gian giua hai lan goi.
state.dispPose = displayPose();
// Goi o DAY chu khong trong draw3d(): o so sanh uoc luong voi ground truth
// phai chay ca khi dang xem khung 2D.
updateGapChip();
@@ -807,7 +871,7 @@ function draw() {
// Khung phai VAN phai chay khi dang chia doi.
if (split) {
updateSlamLabel();
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap',
drawScene(cvR, ctxR, state.map, state.mapImage, state.dispPose, true, 'lyMap',
PALETTE.slam);
} else if (split3d) {
// Khong co canvas thu hai o che do nay: draw3d() da ve ca hai nua. Chi
@@ -821,10 +885,10 @@ function draw() {
updateSlamLabel();
// TRAI = THE GIOI: ban do that + pose THAT. Day la khung de LAI.
drawScene(cv, ctx, state.worldMap, state.worldMapImage,
state.gt || state.pose, false, 'lyWorld', PALETTE.world);
state.gt || state.dispPose, false, 'lyWorld', PALETTE.world);
// PHAI = SLAM: ban do dang dung + pose UOC LUONG. Khung de xem quet toi
// dau, va lech bao nhieu so voi khung trai.
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap',
drawScene(cvR, ctxR, state.map, state.mapImage, state.dispPose, true, 'lyMap',
PALETTE.slam);
} else {
// Mot khung: uu tien ban do SLAM neu co, khong thi ban do the gioi.
@@ -832,7 +896,7 @@ function draw() {
drawScene(cv, ctx,
haveSlam ? state.map : state.worldMap,
haveSlam ? state.mapImage : state.worldMapImage,
state.pose, true, haveSlam ? 'lyMap' : 'lyWorld',
state.dispPose, true, haveSlam ? 'lyMap' : 'lyWorld',
haveSlam ? PALETTE.slam : PALETTE.world);
}
requestAnimationFrame(draw);
@@ -1257,7 +1321,12 @@ function updateGapChip() {
// Sai so du lieu va khoang cach ve la HAI so. Bang nhau nghia la hinh ve
// trung thuc va cai nhin thay la sai so that. Khac nhau nghia la con loi o
// tang hien thi -- da xay ra hai lan (thieu lop boc, va quen laser_x).
const drift = dDraw !== null && Math.abs(dDraw - dData) > 0.01;
//
// So voi pose DA DUA DI VE (displayPose() lam muot co chu dich, lech pose
// that vai cm khi dang chay) -- van bat duoc loi lop boc / laser_x.
const drawn = state.drawnPose || state.pose;
const dRef = state.gt ? Math.hypot(drawn.x - state.gt.x, drawn.y - state.gt.y) : dData;
const drift = dDraw !== null && Math.abs(dDraw - dRef) > 0.01;
el.textContent = 'gap ' + dData.toFixed(3) + ' m' +
(drift ? ' / ve ' + dDraw.toFixed(3) : '');
el.title = drift
@@ -1275,7 +1344,10 @@ for (const b of document.querySelectorAll('.vbtn')) {
function draw3d() {
if (state.robot) v3dSetShape(state.robot);
if (state.pose) v3dSetPose(V3D.robotGroup, state.pose);
if (state.dispPose) {
v3dSetPose(V3D.robotGroup, state.dispPose);
state.drawnPose = state.dispPose; // updateGapChip() so voi pose NAY
}
// Chua dinh vi xong: robot TAM o goc map -> ve MO. Nho do mo goc cua tung
// vat lieu (vai overlay von trong suot) de tra lai dung khi da chot. Chay moi
// khung vi v3dSetShape() co the tao vat lieu moi.

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>

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

@@ -53,6 +53,7 @@ if(VSLAM_BUILD_ODOMETRY)
vslam_add_test(test_wheel_odometry LIBS vslam_odometry vslam_common)
vslam_add_test(test_ekf_se2 LIBS vslam_odometry vslam_common)
vslam_add_test(test_height_estimator LIBS vslam_odometry vslam_common)
vslam_add_test(test_gyro_yaw_fuser LIBS vslam_odometry vslam_common)
endif()
if(VSLAM_BUILD_SAFETY)
@@ -110,6 +111,7 @@ if(VSLAM_BUILD_SLAM)
vslam_add_test(test_slam LIBS vslam_slam vslam_common)
vslam_add_test(test_voxel_export LIBS vslam_slam vslam_common)
vslam_add_test(test_height_map LIBS vslam_slam vslam_common)
vslam_add_test(test_slope_test LIBS vslam_slam vslam_common)
vslam_add_test(test_global_localizer LIBS vslam_slam vslam_common)
endif()

168
test/test_gyro_yaw_fuser.cc Normal file
View File

@@ -0,0 +1,168 @@
// GyroYawFuser: goc quay EKF ghep gyro + encoder theo THOI GIAN. Xem
// vslam/gyro_yaw_fuser.h -- lop nay ra doi vi cach cu dem thieu ~10% goc quay
// tren robot that (07/10) khi mau IMU toi theo cum.
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <random>
#include <vector>
#include "vslam/gyro_yaw_fuser.h"
namespace vslam {
namespace {
// Toc do quay that theo thoi gian: dung, quay trai 0.6 rad/s 5 s, dung, quay
// phai 0.4 rad/s 5 s, dung. Tong |quay| 5 rad, quay rong 1 rad.
double TrueRate(double t) {
if (t >= 1.0 && t < 6.0) return 0.6;
if (t >= 7.0 && t < 12.0) return -0.4;
return 0.0;
}
double TrueTheta(double t) {
const double a = std::min(std::max(t - 1.0, 0.0), 5.0) * 0.6;
const double b = std::min(std::max(t - 7.0, 0.0), 5.0) * -0.4;
return a + b;
}
UnixTime At(double s) { return UnixTime::fromSec(1000.0 + s); }
struct Scenario {
double imu_period = 0.005; // 200 Hz
double latency = 0.03; // mau toi tre hon dau thoi gian (da bu tre)
double batch = 0.04; // mau duoc nha theo CUM moi `batch` giay; 0 = khong cum
double arrive_jitter = 0.0; // xo lech luc toi (s)
double enc_step = 0.0225; // buoc encoder (robot 07/10)
double cb_delay_max = 0.0; // callback encoder tre ngau nhien toi chung nay (s)
double enc_err = 0.0; // encoder bao them ti le nay (truot / sai ban kinh)
double gyro_off_from = 1e9; // gyro im lang trong [from, to)
double gyro_off_to = 1e9;
int dup_every = 0; // moi n mau gyro lap lai dau thoi gian truoc (driver kep)
double t_end = 13.0;
unsigned seed = 1;
};
struct Result {
double fused = 0.0; // tong goc da ghep
int used_gyro = 0;
int steps = 0;
};
Result Simulate(const Scenario& sc) {
GyroYawFuser f;
Result r;
std::mt19937 rng(sc.seed);
std::uniform_real_distribution<double> u01(0.0, 1.0);
// Mau gyro: dau thoi gian = luc do; toi tre `latency`, co the theo cum / xo lech.
struct G { double stamp, arrive, w; };
std::vector<G> gs;
int n = 0;
for (double s = 0.0; s < sc.t_end; s += sc.imu_period, ++n) {
if (s >= sc.gyro_off_from && s < sc.gyro_off_to) continue;
double stamp = s;
if (sc.dup_every > 0 && n % sc.dup_every == 0 && !gs.empty()) stamp = gs.back().stamp;
double arrive = s + sc.latency + sc.arrive_jitter * u01(rng);
if (sc.batch > 0.0) arrive = std::ceil(arrive / sc.batch) * sc.batch;
gs.push_back(G{stamp, arrive, TrueRate(s)});
}
// Mau toi theo THU TU toi; driver giu dau thoi gian khong lui.
std::stable_sort(gs.begin(), gs.end(), [](const G& a, const G& b) { return a.arrive < b.arrive; });
for (size_t i = 1; i < gs.size(); ++i) gs[i].stamp = std::max(gs[i].stamp, gs[i - 1].stamp);
size_t gi = 0;
double prev = 0.0, cb_last = 0.0;
for (double t = sc.enc_step; t < sc.t_end; t += sc.enc_step) {
const double cb = std::max(cb_last, t + sc.cb_delay_max * u01(rng));
cb_last = cb;
while (gi < gs.size() && gs[gi].arrive <= cb) {
f.AddGyro(At(gs[gi].stamp), gs[gi].w);
++gi;
}
const double d_enc = (TrueTheta(t) - TrueTheta(prev)) * (1.0 + sc.enc_err);
double d = 0.0;
if (f.Step(At(t), d_enc, &d)) ++r.used_gyro;
r.fused += d;
prev = t;
++r.steps;
}
return r;
}
// Sai lech cho phep: 0.5% cua tong |quay| (5 rad).
constexpr double kTol = 0.005 * 5.0;
TEST(GyroYawFuser, CumMauKhongDemThieu) {
const Scenario sc; // cum 40 ms, buoc encoder 22.5 ms -- nhu log robot 07/10
const Result r = Simulate(sc);
EXPECT_NEAR(r.fused, TrueTheta(sc.t_end), kTol);
EXPECT_GT(r.used_gyro, r.steps * 9 / 10);
}
TEST(GyroYawFuser, NhipNgauNhienKhongDemThieu) {
// Cach cu lech o nhung nhip nay (mo phong 07/10: cum 16 ms + xo lech, callback
// encoder tre 0-20 ms). Cach moi phai dung o MOI nhip.
for (unsigned seed = 1; seed <= 5; ++seed) {
Scenario sc;
sc.seed = seed;
sc.batch = 0.016;
sc.arrive_jitter = 0.004;
sc.cb_delay_max = 0.02;
const Result r = Simulate(sc);
EXPECT_NEAR(r.fused, TrueTheta(sc.t_end), kTol) << "seed " << seed;
Scenario sc2 = sc;
sc2.batch = 0.0;
const Result r2 = Simulate(sc2);
EXPECT_NEAR(r2.fused, TrueTheta(sc2.t_end), kTol) << "khong cum, seed " << seed;
}
}
TEST(GyroYawFuser, EncoderSaiThiGyroSua) {
Scenario sc;
sc.enc_err = 0.05; // banh bao them 5%
const Result r = Simulate(sc);
EXPECT_NEAR(r.fused, TrueTheta(sc.t_end), kTol);
}
TEST(GyroYawFuser, GyroMatThiDungEncoderRoiNoiLai) {
Scenario sc;
sc.enc_err = 0.05;
sc.gyro_off_from = 3.0; // mat gyro giua luc dang quay trai
sc.gyro_off_to = 8.0;
const Result r = Simulate(sc);
// Trong khoang mat gyro chi co encoder (sai 5% cua 3 s quay 0.6 rad/s =
// 0.09 rad, cong ~0.4 s quay phai luc gyro chua noi lai), ngoai khoang do gyro.
const double enc_part = (TrueTheta(8.2) - TrueTheta(3.0)) * 0.05;
EXPECT_NEAR(r.fused, TrueTheta(sc.t_end) + enc_part, 0.02);
}
TEST(GyroYawFuser, ImuChamThiChiEncoder) {
Scenario sc;
sc.imu_period = 0.1; // WT61PC mac dinh 10 Hz
sc.enc_err = 0.02;
const Result r = Simulate(sc);
EXPECT_EQ(r.used_gyro, 0);
EXPECT_NEAR(r.fused, TrueTheta(sc.t_end) * 1.02, 1e-9);
}
TEST(GyroYawFuser, DauThoiGianLapLai) {
Scenario sc;
sc.dup_every = 7; // driver kep dau thoi gian bang mau truoc
const Result r = Simulate(sc);
EXPECT_NEAR(r.fused, TrueTheta(sc.t_end), kTol);
}
TEST(GyroYawFuser, ThoiGianLuiThiBatDauLai) {
GyroYawFuser f;
double d = 0.0;
for (int i = 0; i < 50; ++i) {
f.AddGyro(At(0.005 * i), 0.5);
if (i % 4 == 3) f.Step(At(0.005 * i + 0.01), 0.01, &d);
}
// Encoder lui ve truoc (reset mo phong): khong dung gyro, tra dung goc encoder.
EXPECT_FALSE(f.Step(At(0.0), 0.02, &d));
EXPECT_DOUBLE_EQ(d, 0.02);
}
} // namespace
} // namespace vslam

View File

@@ -131,3 +131,69 @@ TEST(FloorModel, DoDocVaDoLechNghieng) {
const double p = -std::atan(sf), r = std::atan(sl * std::cos(p));
EXPECT_NEAR(TiltResidual(r, p, M_PI / 4, 0.0, g), 0.0, 1e-9);
}
TEST(FloorModel, DocRongGiuaHaiLanNoiSuy) {
// Doc 10 do len ve -x (node mui -x, mui ngoc = pitch am), quet hai lan sat tuong
// y = 1.5 va y = 6.5 -- nhu world slope_two_ramps doc rong (sim 06/10).
std::vector<FloorNode> nodes;
for (int i = 0; i <= 80; ++i) {
for (double y : {1.5, 6.5}) {
FloorNode n;
n.x = 6.0 + 0.1 * i;
n.y = y;
n.theta = M_PI;
n.pitch = -10 * kDeg;
n.z = (14.0 - n.x) * std::tan(10 * kDeg); // z = 0 o x = 14, len ve -x
nodes.push_back(n);
}
}
FloorModel fm;
fm.Build(nodes);
const double agree = std::tan(2.5 * kDeg);
double gx = 0, gy = 0, z = 0;
// Giua hai lan cach node gan nhat 2.5 m: node gan nhat khong du gan.
EXPECT_FALSE(FloorGradientAt(fm, 10.0, 4.0, 1.5, &gx, &gy));
ASSERT_TRUE(FloorGradientBetween(fm, 10.0, 4.0, 4.0, agree, &gx, &gy));
EXPECT_NEAR(gx, -std::tan(10 * kDeg), 1e-9); // len doc ve -x
EXPECT_NEAR(gy, 0.0, 1e-9);
// Do cao cung noi suy duoc (neo z sau dinh vi lai).
ASSERT_TRUE(FloorZBetween(fm, 10.0, 4.0, 4.0, agree, 0.1, &z));
EXPECT_NEAR(z, 4.0 * std::tan(10 * kDeg), 1e-9);
EXPECT_FALSE(FloorZBetween(fm, 10.0, 8.5, 4.0, agree, 0.1, &z));
// Chi mot phia (ngoai lan y = 6.5): ngoai suy -> khong tin.
EXPECT_FALSE(FloorGradientBetween(fm, 10.0, 8.5, 4.0, agree, &gx, &gy));
// Xa hon max_dist: khong tin.
EXPECT_FALSE(FloorGradientBetween(fm, 10.0, 4.0, 2.0, agree, &gx, &gy));
// Hai phia KHAC mat (lan duoi phang, vd chan doc): khong dong y -> khong tin.
for (FloorNode& n : nodes) {
if (n.y < 4.0) n.pitch = 0.0;
}
fm.Build(nodes);
EXPECT_FALSE(FloorGradientBetween(fm, 10.0, 4.0, 4.0, agree, &gx, &gy));
}
TEST(FloorModel, QuayTheoChieuDoc) {
double mis = 1.0;
// Mui LEN doc (pitch am) hoac XUONG doc (pitch duong): da doc theo doc.
EXPECT_NEAR(SlopeAlignTurn(0.0, -10 * kDeg, &mis), 0.0, 1e-9);
EXPECT_NEAR(mis, 0.0, 1e-9);
EXPECT_NEAR(SlopeAlignTurn(0.0, 10 * kDeg, &mis), 0.0, 1e-9);
// Ngang doc, ben TRAI cao (roll duong): xa nhu nhau -> quay TRAI 90 do nhin LEN.
EXPECT_NEAR(SlopeAlignTurn(10 * kDeg, 0.0, &mis), M_PI / 2, 1e-9);
EXPECT_NEAR(mis, M_PI / 2, 1e-9);
// Ben PHAI cao (roll am): quay PHAI.
EXPECT_NEAR(SlopeAlignTurn(-10 * kDeg, 0.0), -M_PI / 2, 1e-9);
// Mui len doc lech TRAI 45 do (sim 06/10: doc 15 do, IMU roll -10.7 / pitch -10.7):
// quay PHAI 45 do.
const double g = std::tan(15 * kDeg);
const double sf = g * std::cos(M_PI / 4), sl = -g * std::sin(M_PI / 4);
const double p = -std::atan(sf), r = std::atan(sl * std::cos(p));
EXPECT_NEAR(SlopeAlignTurn(r, p, &mis), -M_PI / 4, 1e-9);
// Mui XUONG doc lech 30 do: quay 30 do ve phia xuong, khong quay 150 do de nhin len.
const double sf2 = -g * std::cos(M_PI / 6), sl2 = g * std::sin(M_PI / 6);
const double p2 = -std::atan(sf2), r2 = std::atan(sl2 * std::cos(p2));
EXPECT_NEAR(std::fabs(SlopeAlignTurn(r2, p2, &mis)), M_PI / 6, 1e-9);
// San phang: khong quay.
EXPECT_NEAR(SlopeAlignTurn(0.0, 0.0, &mis), 0.0, 1e-12);
EXPECT_NEAR(mis, 0.0, 1e-12);
}

View File

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

View File

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

260
test/test_slope_test.cc Normal file
View File

@@ -0,0 +1,260 @@
// Test doc tu dong (08/10): lap duong tu ban do + may trang thai lai.
// Robot gia lap: mo hinh xe hai banh, tich phan lenh (v, w) cua chinh SlopeTest.
#include <gtest/gtest.h>
#include <cmath>
#include <string>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/slope_test.h"
using namespace vslam;
namespace {
// Doc gia doc truc x: tang tren z 1.2 (x < 2), doc xuong toi z 0 o x = 8, san
// duoi phang. Nha |y| < 3, x trong (-1, 11); tinh lan 0.3 m cho than robot.
bool Floor(double x, double y, double* z) {
if (x < -1.0 || x > 11.0 || std::fabs(y) > 3.0) return false;
if (x < 2.0) *z = 1.2;
else if (x < 8.0) *z = 1.2 * (8.0 - x) / 6.0;
else *z = 0.0;
return true;
}
bool Free(double x, double y) { return x > -0.7 && x < 10.7 && std::fabs(y) < 2.7; }
struct Sim {
SlopeTest t;
Pose2D p;
double now = 1.0;
std::vector<std::string> events;
double vmax_leg = 0.0;
explicit Sim(SlopeTestConfig c) : t(std::move(c)) {}
// Mot buoc 50 ms. Tra output de test kiem tra.
SlopeTestOutput Step(bool start = false, bool human = false, bool localized = true) {
SlopeTestInput in;
in.t = now;
in.pose = p;
in.localized = localized;
in.start = start;
in.human = human;
const SlopeTestOutput o = t.Step(in);
if (!o.event.empty()) events.push_back(o.event);
if (o.command) {
const double dt = 0.05;
p.theta = NormalizeAngle(p.theta + o.w * dt);
p.x += o.v * std::cos(p.theta) * dt;
p.y += o.v * std::sin(p.theta) * dt;
vmax_leg = std::max(vmax_leg, o.v);
}
now += 0.05;
return o;
}
// Chay toi khi gap pha `ph` (hoac het so buoc).
bool RunUntil(SlopeTestPhase ph, int max_steps = 20000) {
for (int i = 0; i < max_steps; ++i) {
if (t.phase() == ph) return true;
Step();
}
return t.phase() == ph;
}
};
SlopeTestConfig Cfg() {
SlopeTestConfig c;
c.loops = 3;
c.speeds = {0.10, 0.30, 0.45};
c.dwell_s = 1.0;
return c;
}
bool Has(const std::vector<std::string>& ev, const std::string& s) {
for (const auto& e : ev) {
if (e.find(s) != std::string::npos) return true;
}
return false;
}
} // namespace
TEST(PlanSlopePath, TimDungTrucDocVaChanDoc) {
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why)) << why;
EXPECT_NEAR(p.a.theta, 0.0, 3.0 * M_PI / 180.0); // xuong doc theo +x
EXPECT_NEAR(p.drop, 1.2, 0.05);
// Chan doc: mat san PHANG (do doc < 3 do, sai phan +-0.25 m) tu x = 8.25, + 0.5 m.
EXPECT_NEAR(p.bx, 8.75, 0.2);
EXPECT_NEAR(p.by, 0.2, 0.2);
// Robot da o dinh phang: A = cho robot.
EXPECT_NEAR(p.a.x, 0.5, 1e-9);
}
TEST(PlanSlopePath, GiuaDocThiADatODinhDoc) {
// Dinh vi lai tu chay ra GIUA doc (sim 08/10: 3.5 m). A phai la DINH phang,
// KHONG phai cho robot dung.
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(4.0, 0.2, Floor, Free, SlopePathConfig{}, &p, &why)) << why;
EXPECT_NEAR(p.a.theta, 0.0, 3.0 * M_PI / 180.0);
EXPECT_NEAR(p.a.x, 1.25, 0.15); // phang tu x = 1.75 (+-0.25) lui 1 m, + 0.5 m
EXPECT_NEAR(p.bx, 8.75, 0.2);
EXPECT_NEAR(p.drop, 1.2, 0.05);
}
TEST(PlanSlopePath, KhongChonDuongCheoNgangDoc) {
// Doc rong (|y| < 3) dung SAT tuong y = 2.5: huong cheo cat qua doc ngan hon
// nhung khong xuong het -- phai chon truc doc (xuong 1.2 m).
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(3.0, 2.3, Floor, Free, SlopePathConfig{}, &p, &why)) << why;
EXPECT_NEAR(p.drop, 1.2, 0.05);
EXPECT_NEAR(p.a.theta, 0.0, 6.0 * M_PI / 180.0);
}
TEST(PlanSlopePath, KhongCoDocThiBaoLoi) {
SlopePath p;
std::string why;
// San phang toan bo: khong huong nao xuong.
auto flat = [](double x, double y, double* z) {
*z = 0.0;
return std::fabs(x) < 5.0 && std::fabs(y) < 5.0;
};
auto free = [](double x, double y) { return std::fabs(x) < 4.7 && std::fabs(y) < 4.7; };
EXPECT_FALSE(PlanSlopePath(0.0, 0.0, flat, free, SlopePathConfig{}, &p, &why));
EXPECT_NE(why.find("khong thay doc"), std::string::npos);
}
TEST(SlopeTest, QuayMatXuongDocRoiChoNut) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 2.0}; // dang nhin xien sau reloc
s.t.SetPath(p, false);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kWaitStart, 2000));
EXPECT_NEAR(NormalizeAngle(s.p.theta - p.a.theta), 0.0, 4.0 * M_PI / 180.0);
// Cho nut: KHONG ra lenh, robot dung yen.
const Pose2D before = s.p;
for (int i = 0; i < 100; ++i) EXPECT_FALSE(s.Step().command);
EXPECT_DOUBLE_EQ(s.p.x, before.x);
}
TEST(SlopeTest, GiuaDocThiVeDinhTruoc) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(4.0, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{4.0, 0.2, 2.0};
s.t.SetPath(p, false);
s.Step();
EXPECT_TRUE(s.t.approaching());
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kWaitStart, 4000));
EXPECT_LT(std::hypot(s.p.x - p.a.x, s.p.y - p.a.y), 0.15);
EXPECT_NEAR(NormalizeAngle(s.p.theta - p.a.theta), 0.0, 4.0 * M_PI / 180.0);
EXPECT_TRUE(Has(s.events, "chay CHAM ve A"));
EXPECT_LE(s.vmax_leg, 0.15 + 1e-9); // ve A cham
}
TEST(SlopeTest, DuLuotDungThuTuVaVanToc) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, false);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kWaitStart, 2000));
s.Step(true); // bam Y
const double speeds[] = {0.10, 0.30, 0.45};
for (int k = 0; k < 3; ++k) {
for (bool down : {true, false}) {
s.vmax_leg = 0.0;
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDwell)) << "luot " << k + 1 << (down ? " xuong" : " len");
EXPECT_EQ(s.t.loop(), k + 1);
EXPECT_EQ(s.t.down(), down);
// Van toc luot nay: dat toi, khong vuot.
EXPECT_NEAR(s.vmax_leg, speeds[k], 1e-9);
// Toi dung dau doc.
const double tx = down ? p.bx : p.a.x, ty = down ? p.by : p.a.y;
EXPECT_LT(std::hypot(s.p.x - tx, s.p.y - ty), 0.15);
// Roi pha dung do.
for (int i = 0; i < 40 && s.t.phase() == SlopeTestPhase::kDwell; ++i) s.Step();
}
}
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDone, 200));
EXPECT_TRUE(Has(s.events, "XONG 3 luot"));
EXPECT_TRUE(Has(s.events, "luot 2/3 XUONG 0.3 m/s"));
EXPECT_TRUE(Has(s.events, "luot 3/3 LEN 0.45 m/s"));
// Xong thi im.
EXPECT_FALSE(s.Step().command);
}
TEST(SlopeTest, NguoiLaiThiTamDungRoiChayTiep) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true); // tu chay
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
for (int i = 0; i < 40; ++i) s.Step();
// Nguoi gat can: tam dung, IM ngay.
EXPECT_FALSE(s.Step(false, true).command);
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kPaused);
for (int i = 0; i < 50; ++i) EXPECT_FALSE(s.Step().command);
// Bam Y: chay tiep toi chan doc.
s.Step(true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDwell));
EXPECT_LT(std::hypot(s.p.x - p.bx, s.p.y - p.by), 0.15);
}
TEST(SlopeTest, LechDuongThiDungHan) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
for (int i = 0; i < 20; ++i) s.Step();
s.p.y += 0.25; // truot ngang (khong nhay qua jump_max)
s.Step();
s.p.y += 0.25;
const SlopeTestOutput o = s.Step();
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kHalted);
EXPECT_TRUE(o.command); // MOT lenh dung
EXPECT_DOUBLE_EQ(o.v, 0.0);
EXPECT_NE(s.t.halt_reason().find("lech khoi duong"), std::string::npos);
EXPECT_FALSE(s.Step().command); // roi im
}
TEST(SlopeTest, MatDinhViThiDungHan) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
s.Step(false, false, false);
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kHalted);
EXPECT_NE(s.t.halt_reason().find("mat dinh vi"), std::string::npos);
}
TEST(SlopeTest, PoseNhayThiDungHan) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
s.Step();
s.p.x += 0.5; // dinh vi nhay 0.5 m
s.Step();
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kHalted);
EXPECT_NE(s.t.halt_reason().find("pose nhay"), std::string::npos);
}

View File

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

170
tools/gen_two_ramp_world.py Normal file
View File

@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Sinh world mo phong HAI DOC: resources/worlds/slope_two_ramps.world + hai model.
Gon hon slope_test (5 lan doc): mot sanh phang o giua, moi ben mot doc len mot
tang. Quet het mot vong (len doc trai, vong tang trai, xuong, qua sanh, len doc
phai, vong tang phai, xuong) ~85 m, ~5 phut o 0.3 m/s, va moi doc deu da di CA
LEN LAN XUONG -- camera dinh vi lai nhan ra ca hai huong.
Bo cuc (nhin tu tren xuong, x sang phai, y len tren; met):
y=8 +---------+--#------#---+-------------------+-----------+---------+
| | | | | |
| TANG | doc 10 do | | doc 15 | TANG |
| TRAI | rong 8 m | SANH GIUA | do, rong | PHAI |
| z=1.5 | | z = 0 | 8 m | z=1.5 |
| | | | | |
y=0 +---------+-------------+-------------------+-----------+---------+
x=0 6.0 14.5 24.5 30.1 36.1
Hai doc RONG HET NHA (8 m, giua hai tuong bao) -- doc ngoai troi giua cac toa
nha thuong rong. Goc, do dac va cot KHAC NHAU de world KHONG doi xung -- doi
xung thi dinh vi lai nhap nhang (lat 180 do), nhu sanh tren cua slope_test.
Doc trai co hai cot nho o tuong y = 8 (#, LiDAR co cho bam doc theo doc); doc
phai tuong tron (LiDAR mu doc truc -- truong hop can camera).
Doc rong thi tuong gia o chan doc (tia LiDAR cham mat doc) cung rong het nha,
ma camera chi thay ~3 m be ngang o 4 m: muon xoa het thi di doc theo vai lan
(giua va sat hai tuong), khong chi mot duong giua.
Cung quy uoc voi tools/gen_slope_world.py (dung lai Obj, SDF, CONFIG,
include, write cua no): model `vslam_terrain_*` la DIA HINH, mesh co toa do
texture theo met, do dac lay tu ~/gazebo_models/aws_hospital_fuel.
Chay tu goc repo:
python3 tools/gen_two_ramp_world.py
export GAZEBO_MODEL_PATH=$PWD/resources/models
./build/app/vslam_node --sim --sim-gl --world resources/worlds/slope_two_ramps.world \\
--x 19.5 --y 4.0 --yaw 3.1416 --max-speed 0.3 --token t
"""
import argparse
import math
import os
import gen_slope_world as base
H = 1.5 # do cao hai tang, m
DEG_L, DEG_R = 10.0, 15.0 # goc doc trai / phai
WALL_T = 0.2
WALL_H = H + 2.5
DEPTH = 8.0 # be rong toan nha theo y
FLOOR_L = 6.0 # chieu dai tang trai / phai theo x
HALL_L = 10.0
Y_RL0, Y_RL1 = 0.0, DEPTH # hai doc rong het nha
Y_RR0, Y_RR1 = 0.0, DEPTH
LEN_L = H / math.tan(math.radians(DEG_L))
LEN_R = H / math.tan(math.radians(DEG_R))
X_L1 = FLOOR_L # het tang trai = dinh doc trai
X_H0 = X_L1 + LEN_L # chan doc trai = dau sanh
X_H1 = X_H0 + HALL_L # cuoi sanh = chan doc phai
X_R0 = X_H1 + LEN_R # dinh doc phai = dau tang phai
X_END = X_R0 + FLOOR_L
TERRAIN = 'vslam_terrain_two_ramps'
WALLS = 'vslam_two_ramps_walls'
# Do dac: (model, x, y, z, yaw). Sat tuong bao, de trong long doc va giua hai
# chan / dinh doc -- chan duong len doc la lop an toan dung xe truoc doc.
FURNITURE = [
('MetalCabinet', X_H0 + 0.6, 7.4, 0.0, 0.0),
('IVStand', X_H0 + 2.5, 0.8, 0.0, 0.0),
('VendingMachine', X_H0 + 5.0, 7.5, 0.0, -math.pi / 2),
('StorageRack', X_H0 + 6.5, 0.6, 0.0, 0.0),
('PatientWheelChair', X_H1 - 0.7, 1.0, 0.0, 0.0),
('MetalCabinet', 0.6, 7.0, H, 0.0),
('BedTable', 2.5, 0.8, H, 0.0),
('IVStand', 4.5, 7.2, H, 0.0),
('StorageRack', X_R0 + 2.9, 0.6, H, 0.0),
('BedTable', X_R0 + 4.4, 7.4, H, 0.0),
('VendingMachine', X_END - 0.6, 2.0, H, math.pi),
]
def terrain_mesh():
m = base.Obj('Dia hinh world hai doc: sanh z=0, hai tang z=%.2f, doc %g / %g do.\n'
'Z-UP, met. Sinh boi tools/gen_two_ramp_world.py -- dung sua tay.'
% (H, DEG_L, DEG_R))
m.quad([(0, 0, H), (X_L1, 0, H), (X_L1, DEPTH, H), (0, DEPTH, H)]) # tang trai
m.quad([(X_L1, Y_RL0, H), (X_H0, Y_RL0, 0), (X_H0, Y_RL1, 0), (X_L1, Y_RL1, H)]) # doc trai
m.quad([(X_H0, 0, 0), (X_H1, 0, 0), (X_H1, DEPTH, 0), (X_H0, DEPTH, 0)]) # sanh
m.quad([(X_H1, Y_RR0, 0), (X_R0, Y_RR0, H), (X_R0, Y_RR1, H), (X_H1, Y_RR1, 0)]) # doc phai
m.quad([(X_R0, 0, H), (X_END, 0, H), (X_END, DEPTH, H), (X_R0, DEPTH, H)]) # tang phai
return m.text()
def walls_mesh():
m = base.Obj('Tuong bao va cot cua world hai doc. Z-UP, met.\n'
'Sinh boi tools/gen_two_ramp_world.py -- dung sua tay.')
t = WALL_T
# Vong ngoai. Hai doc rong het nha nen khong co tuong rieng cho doc.
m.box(-t, -t, 0, 0, DEPTH + t, WALL_H)
m.box(X_END, -t, 0, X_END + t, DEPTH + t, WALL_H)
m.box(-t, -t, 0, X_END + t, 0, WALL_H)
m.box(-t, DEPTH, 0, X_END + t, DEPTH + t, WALL_H)
# Doc trai: hai cot nho nho ra 0.15 m o tuong y lon -- LiDAR co moc doc theo doc.
for xc in (X_L1 + 0.35 * LEN_L, X_L1 + 0.7 * LEN_L):
m.box(xc - 0.2, Y_RL1 - 0.15, 0, xc + 0.2, Y_RL1, WALL_H)
# Cot trong sanh va hai tang (lech nhau, khong doi xung), tranh duong vao doc.
m.box(X_H0 + 3.3, 5.8, 0, X_H0 + 3.7, 6.2, WALL_H)
m.box(X_H0 + 6.8, 2.3, 0, X_H0 + 7.2, 2.7, WALL_H)
m.box(2.8, 4.8, H, 3.2, 5.2, WALL_H)
m.box(X_R0 + 3.2, 3.3, H, X_R0 + 3.6, 3.7, WALL_H)
return m.text()
def world_text():
parts = ['<?xml version="1.0" ?>\n',
'<!-- World HAI DOC. Sinh boi tools/gen_two_ramp_world.py -- dung sua tay.\n'
' Sanh giua z = 0 (x %.1f-%.1f); doc trai %g do (y %.1f-%.1f) len tang trai,\n'
' doc phai %g do (y %.1f-%.1f) len tang phai, hai tang z = %.1f.\n'
' Xuat phat goi y: --x %.1f --y 4.0 --yaw 3.1416 (giua sanh, nhin ve doc trai). -->\n'
% (X_H0, X_H1, DEG_L, Y_RL0, Y_RL1, DEG_R, Y_RR0, Y_RR1, H, (X_H0 + X_H1) / 2),
'<sdf version="1.6">\n <world name="slope_two_ramps">\n',
' <include><uri>model://ground_plane</uri></include>\n',
' <include><uri>model://sun</uri></include>\n',
base.include(TERRAIN + '_1', TERRAIN, 0, 0, 0, 0),
base.include(WALLS + '_1', WALLS, 0, 0, 0, 0)]
count = {}
for name, x, y, z, yaw in FURNITURE:
count[name] = count.get(name, 0) + 1
parts.append(base.include('%s_%d' % (name, count[name]), name, x, y, z, yaw))
parts.append(' </world>\n</sdf>\n')
return ''.join(parts)
def main():
here = os.path.dirname(os.path.abspath(__file__))
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--root', default=os.path.dirname(here),
help='goc repo (mac dinh: thu muc cha cua tools/)')
a = ap.parse_args()
models = os.path.join(a.root, 'resources', 'models')
base.write(os.path.join(models, TERRAIN, 'meshes', 'terrain.obj'), terrain_mesh())
base.write(os.path.join(models, TERRAIN, 'model.sdf'),
base.SDF.format(name=TERRAIN, mesh='terrain.obj'))
base.write(os.path.join(models, TERRAIN, 'model.config'),
base.CONFIG.format(name=TERRAIN, desc='Sanh, hai doc va hai tang (dia hinh).')
.replace('gen_slope_world.py', 'gen_two_ramp_world.py'))
base.write(os.path.join(models, WALLS, 'meshes', 'walls.obj'), walls_mesh())
base.write(os.path.join(models, WALLS, 'model.sdf'),
base.SDF.format(name=WALLS, mesh='walls.obj'))
base.write(os.path.join(models, WALLS, 'model.config'),
base.CONFIG.format(name=WALLS, desc='Tuong bao va cot.')
.replace('gen_slope_world.py', 'gen_two_ramp_world.py'))
base.write(os.path.join(a.root, 'resources', 'worlds', 'slope_two_ramps.world'), world_text())
print('sanh giua x %.2f-%.2f (z 0); tang trai x 0-%.2f, tang phai x %.2f-%.2f (z %.1f)'
% (X_H0, X_H1, X_L1, X_R0, X_END, H))
for name, deg, x0, x1, y0, y1 in (('trai', DEG_L, X_L1, X_H0, Y_RL0, Y_RL1),
('phai', DEG_R, X_H1, X_R0, Y_RR0, Y_RR1)):
print('doc %s %g do: x %.2f-%.2f, y %.1f-%.1f, dai %.2f m, tam (%.2f, %.2f), '
'tuong gia o chan doc cach %.2f m'
% (name, deg, x0, x1, y0, y1, x1 - x0, (x0 + x1) / 2, (y0 + y1) / 2,
0.2165 / math.tan(math.radians(deg))))
if __name__ == '__main__':
main()

507
tools/gen_world_from_db.py Normal file
View File

@@ -0,0 +1,507 @@
#!/usr/bin/env python3
"""World mo phong tu MOT ban do that (DB RTAB-Map cua vslam_cpp): tuong + mat dat.
De chay lai test doc (--slope-test) tren chinh con doc that khi khong dua duoc
robot ra hien truong. Moi thu lay tu DB:
* mat dat = z do cua tung node (userData, ghi khi slope.enabled), noi suy
Gauss quanh node (SIGMA, xa node thi rong dan) thanh luoi tam giac TRES
phu CA khung ban do -- o sim khong co dia hinh la san z = 0, de ho thi
mep vung da biet thanh mot bac dung;
* tuong = o BI CHIEM cua luoi 2D (log-odds tu luoi cuc bo tung node + pose
toi uu, cung GridGlobal/* voi slam.yaml), dung cao WALL_H tu mat dat. Bo
hai loai tuong GIA:
- tia LiDAR cham MAT DAT: o ma mat dat nho cao hon mat phang duoi robot
(cua node nhin thay o do) qua LIDAR_H - GROUND_TOL -- chan doc nhin tu
duoi, chan doc nhin tu tren khi dang xuong;
- o trong vong ROBOT_R + 5 cm quanh duong robot DA DI (chac chan trong);
* goi y diem dat robot: dinh doan doc lon nhat, theo pose node that.
Frame world = frame ban do, nen sai so so voi ground truth cua sim co nghia.
Sim chay tren BAN SAO cua DB trong thu muc ra (localization co the ghi DB).
Gioi han: anh camera sim khong giong anh that -> dinh vi lai bang LiDAR (KHONG
--slam-reloc-vpr); khong co nguoi / do vat di dong; vat thap duoi tam LiDAR
khong co; mat dat chi dung doc theo duong robot da di (ngang ra thi keo dai).
Chay tu goc repo (in ra lenh sim day du):
python3 tools/gen_world_from_db.py resources/maps/real_YYYYMMDD_HHMMSS.db \\
--preview logs/real_YYYYMMDD_HHMMSS_world.png
"""
import argparse
import math
import os
import re
import shutil
import sqlite3
import struct
import zlib
import numpy as np
import gen_slope_world as base
RES = 0.05 # o luoi 2D, bang Grid/CellSize
TRES = 0.20 # o luoi mat dat
SIGMA = 0.5 # noi suy z: do rong Gauss quanh node gan nhat, m
WALL_H = 2.0 # tuong cao bao nhieu tren mat dat
LIDAR_H = 0.2165 # tam LiDAR tren san: robot.yaml laser_link z 0.13 + wheel_radius 0.0865
GROUND_TOL = 0.08 # dat nho hon mat phang robot >= LIDAR_H - cai nay: tia cham DAT
ROBOT_R = 0.24 # robot.yaml robot_radius
SLOPE_DEG = 3.0 # mat dat doc hon cai nay la doc
PAD = 1.0 # le quanh khung ban do, m
MAX_GAP = 1.0 # hai node lien tiep xa hon (RGBD/LinearUpdate 0.1) = dut duong
def mat(blob):
"""Blob nen cua RTAB-Map: zlib + 12 byte (rows, cols, type) -> (bytes, so kenh)."""
typ = struct.unpack('3i', blob[-12:])[2]
return zlib.decompress(blob[:-12]), (typ >> 3) + 1
def grid_params(root):
"""GridGlobal/* cua slam.yaml (thieu thi mac dinh RTAB-Map)."""
p = {'ProbHit': 0.7, 'ProbMiss': 0.4, 'ProbClampingMin': 0.1192, 'ProbClampingMax': 0.971}
path = os.path.join(root, 'configuration_files', 'slam.yaml')
text = open(path).read() if os.path.exists(path) else ''
for k in p:
m = re.search(r'GridGlobal/%s:\s*"?([0-9.]+)' % k, text)
if m:
p[k] = float(m.group(1))
return p
def logit(p):
return math.log(p / (1.0 - p))
def connect(db):
return sqlite3.connect('file:%s?mode=ro' % db, uri=True).cursor()
def load(db):
"""-> ids tang dan, pose {id: 3x4}, do {id: (z, roll, pitch)}, nguon pose."""
c = connect(db)
row = c.execute('select opt_ids, opt_poses from Admin').fetchone()
if row is not None and row[0] is not None and row[1] is not None:
ids = np.frombuffer(mat(row[0])[0], dtype=np.int32)
P = np.frombuffer(mat(row[1])[0], dtype=np.float32).reshape(-1, 3, 4)
pose = {int(i): P[k].astype(np.float64) for k, i in enumerate(ids)}
src = 'pose toi uu (Admin)'
else:
pose = {int(i): np.frombuffer(b, dtype=np.float32).reshape(3, 4).astype(np.float64)
for i, b in c.execute('select id, pose from Node where pose is not null')}
src = 'pose ODOM (bang Node) -- DB chua co pose toi uu: node bi tat ngang?'
tilt = {}
for nid, ud in c.execute('select id, user_data from Data where user_data is not null'):
if nid not in pose:
continue
try:
raw, _ = mat(ud)
except (zlib.error, struct.error):
continue
if len(raw) >= 24:
tilt[nid] = struct.unpack_from('3d', raw)
return sorted(pose), pose, tilt, src
def cells(db, pose):
"""Luoi cuc bo tung node, theo id (= theo thoi gian, nhu RTAB-Map ghep):
-> (id, o trong xy, o chiem xy) trong frame ban do. Doc dan, khong giu
het trong RAM -- ban do lon co hang chuc trieu o trong."""
for nid, em, ob in connect(db).execute(
'select id, empty_cells, obstacle_cells from Data order by id'):
if nid not in pose or (em is None and ob is None):
continue
T = pose[nid]
out = []
for blob in (em, ob):
if blob is None:
out.append(np.zeros((0, 2)))
continue
raw, ch = mat(blob)
q = np.frombuffer(raw, dtype=np.float32).reshape(-1, ch)[:, :2].astype(np.float64)
out.append(q @ T[:2, :2].T + T[:2, 3])
yield nid, out[0], out[1]
def bilinear(G, x0, y0, step):
"""Ham lay mau song tuyen luoi G (goc (x0, y0), buoc step) tai (x, y)."""
TH, TW = G.shape
def f(x, y):
fx = np.clip((np.asarray(x, float) - x0) / step, 0, TW - 1 - 1e-9)
fy = np.clip((np.asarray(y, float) - y0) / step, 0, TH - 1 - 1e-9)
i, j = fx.astype(int), fy.astype(int)
ax, ay = fx - i, fy - j
return ((1 - ay) * ((1 - ax) * G[j, i] + ax * G[j, i + 1])
+ ay * ((1 - ax) * G[j + 1, i] + ax * G[j + 1, i + 1]))
return f
def dilate(mask, r):
"""O True lan thanh hinh tron ban kinh r o (khong vong qua mep nhu np.roll)."""
H, W = mask.shape
out = mask.copy()
for dy in range(-r, r + 1):
for dx in range(-r, r + 1):
if dx * dx + dy * dy > r * r:
continue
out[max(dy, 0):H + min(dy, 0), max(dx, 0):W + min(dx, 0)] |= \
mask[max(-dy, 0):H - max(dy, 0), max(-dx, 0):W - max(dx, 0)]
return out
def path_mask(xy, keep, x0, y0, H, W):
"""O luoi duong robot di qua: noi cac node lien tiep cung `keep`, cach < MAX_GAP."""
pts = [xy[keep]]
for k in range(len(xy) - 1):
if not (keep[k] and keep[k + 1]):
continue
a, b = xy[k], xy[k + 1]
d = math.hypot(*(b - a))
if RES / 2 < d < MAX_GAP:
t = np.linspace(0.0, 1.0, int(d / (RES / 2)) + 2)[1:-1, None]
pts.append(a + t * (b - a))
p = np.concatenate(pts)
m = np.zeros((H, W), bool)
m[((p[:, 1] - y0) / RES).astype(int).clip(0, H - 1),
((p[:, 0] - x0) / RES).astype(int).clip(0, W - 1)] = True
return m
def terrain_obj(header, gx, gy, Z):
"""Luoi do cao -> OBJ dung chung dinh (nho hon nhieu so voi Obj.quad)."""
TH, TW = Z.shape
lines = ['# ' + l for l in header.splitlines()]
for j in range(TH):
lines.extend('v %.3f %.3f %.4f' % (gx[i], gy[j], Z[j, i]) for i in range(TW))
for j in range(TH - 1):
for i in range(TW - 1):
a = j * TW + i + 1 # nguoc kim dong ho nhin tu tren: mat huong LEN
lines.append('f %d %d %d' % (a, a + 1, a + TW + 1))
lines.append('f %d %d %d' % (a, a + TW + 1, a + TW))
return '\n'.join(lines) + '\n'
def fill_gaps(occ):
"""Lap khe <= 2 o (10 cm) giua hai doan tuong thang hang (ngang, doc, cheo).
Luoi 'lan nhin moi nhat thang' xoa o tuong ma tia sau suot qua, nen tuong
that thanh net dut -- trong sim tia LiDAR lot qua khe. Chi lap o nam GIUA
hai o chiem, khong noi rong dam (nguoi da roi di khong quay lai)."""
H, W = occ.shape
def shift(m, dy, dx): # out[y, x] = m[y - dy, x - dx], ngoai mep = False
out = np.zeros_like(m)
out[max(dy, 0):H + min(dy, 0), max(dx, 0):W + min(dx, 0)] = \
m[max(-dy, 0):H - max(dy, 0), max(-dx, 0):W - max(dx, 0)]
return out
fill = np.zeros_like(occ)
for dy, dx in ((0, 1), (1, 0), (1, 1), (1, -1)):
a1, a2 = shift(occ, dy, dx), shift(occ, 2 * dy, 2 * dx)
b1, b2 = shift(occ, -dy, -dx), shift(occ, -2 * dy, -2 * dx)
fill |= (a1 & b1) | (a1 & b2) | (a2 & b1)
return occ | fill
def local_rtabmap_version(root):
"""Ban RTAB-Map ma build may nay link: build/CMakeCache.txt -> RTABMapConfigVersion.cmake."""
try:
cache = open(os.path.join(root, 'build', 'CMakeCache.txt')).read()
d = re.search(r'^RTABMap_DIR:PATH=(.+)$', cache, re.M).group(1).strip()
cfg = open(os.path.join(d, 'RTABMapConfigVersion.cmake')).read()
return re.search(r'set\(PACKAGE_VERSION "([0-9.]+)"\)', cfg).group(1)
except (OSError, AttributeError):
return None
def vtuple(v):
return tuple(int(x) for x in re.findall(r'\d+', v))
def wall_rects(occ):
"""Gop o chiem thanh hinh chu nhat: doan lien tiep tren hang, keo dai xuong
cac hang co dung doan do. -> [(i0, j0, i1, j1)] (bao gom hai dau)."""
H = occ.shape[0]
rects, opened = [], {}
for j in range(H + 1):
cur = set()
if j < H:
d = np.diff(np.concatenate(([0], occ[j].astype(np.int8), [0])))
cur = set(zip(np.nonzero(d == 1)[0].tolist(), (np.nonzero(d == -1)[0] - 1).tolist()))
for key in [k for k in opened if k not in cur]:
rects.append((key[0], opened.pop(key), key[1], j - 1))
for key in cur:
opened.setdefault(key, j)
return rects
def slope_runs(xy, zz, steep):
"""Doan doc tren quy dao: node lien tiep cung doc, chenh z >= 0.2 m.
-> [(k dau, k cuoi, chenh z, dai)]."""
runs, k = [], 0
while k < len(xy):
if not steep[k]:
k += 1
continue
e = k
while e + 1 < len(xy) and steep[e + 1] and math.hypot(*(xy[e + 1] - xy[e])) < MAX_GAP:
e += 1
dz = float(zz[k:e + 1].max() - zz[k:e + 1].min())
length = float(np.hypot(*np.diff(xy[k:e + 1], axis=0).T).sum()) if e > k else 0.0
if dz >= 0.2:
runs.append((k, e, dz, length))
k = e + 1
return runs
def walk_out(xy, k, step, dist):
"""Tu node k di theo quy dao (step = +1 / -1) toi khi duoc `dist` m hoac dut."""
s = 0.0
while 0 <= k + step < len(xy):
d = math.hypot(*(xy[k + step] - xy[k]))
if d >= MAX_GAP:
break
s += d
k += step
if s >= dist:
break
return k
def preview(path, occ, seen, ground, cleared, xy, zz, runs, spawn, x0, y0):
import cv2
H, W = occ.shape
img = np.full((H, W, 3), 128, np.uint8)
img[seen] = (255, 255, 255)
img[ground] = (0, 140, 255) # cam: tia cham dat (bo)
img[cleared] = (255, 200, 0) # xanh: tren duong da di (bo)
img[occ] = (0, 0, 0)
span = max(float(zz.max() - zz.min()), 1e-3)
col = cv2.applyColorMap(((zz - zz.min()) / span * 255).astype(np.uint8).reshape(-1, 1),
cv2.COLORMAP_JET).reshape(-1, 3)
px = ((xy - (x0, y0)) / RES).astype(int)
for (u, v), c in zip(px, col):
cv2.circle(img, (int(u), int(v)), 2, tuple(int(t) for t in c), -1)
for k, e, _, _ in runs:
cv2.polylines(img, [px[k:e + 1].reshape(-1, 1, 2).astype(np.int32)], False, (0, 0, 255), 1)
if spawn is not None:
sx, sy, syaw = spawn
u, v = int((sx - x0) / RES), int((sy - y0) / RES)
cv2.circle(img, (u, v), 8, (0, 200, 0), 2)
cv2.line(img, (u, v), (int(u + 16 * math.cos(syaw)), int(v + 16 * math.sin(syaw))), (0, 200, 0), 2)
cv2.imwrite(path, img[::-1]) # y len tren
print('anh xem truoc:', path, '(den = tuong, cam = tia cham dat da bo, xanh = bo tren duong '
'da di, cham = node theo z xanh->do, do = doan doc, vong xanh la = diem dat)')
def main():
here = os.path.dirname(os.path.abspath(__file__))
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('db', help='DB ban do that, vd resources/maps/real_YYYYMMDD_HHMMSS.db')
ap.add_argument('--name', help='ten world (mac dinh: ten DB)')
ap.add_argument('--out', help='thu muc ra (mac dinh: <thu muc DB>/sim_<ten> -- da gitignore)')
ap.add_argument('--root', default=os.path.dirname(here), help='goc repo (doc slam.yaml)')
ap.add_argument('--preview', help='ghi anh PNG xem truoc tuong / mat dat / doc')
a = ap.parse_args()
name = a.name or os.path.splitext(os.path.basename(a.db))[0]
out = os.path.abspath(a.out or os.path.join(os.path.dirname(os.path.abspath(a.db)), 'sim_' + name))
terrain, walls = 'vslam_terrain_' + name, 'vslam_walls_' + name
ids, pose, tilt, src = load(a.db)
if not ids:
raise SystemExit('DB khong co node nao')
xy = np.array([pose[i][:2, 3] for i in ids])
yaw = np.array([math.atan2(pose[i][1, 0], pose[i][0, 0]) for i in ids])
zz = np.array([tilt[i][0] if i in tilt else 0.0 for i in ids])
print('%d node, %s; %d node co z do (userData), z %.2f .. %.2f m'
% (len(ids), src, len(tilt), zz.min(), zz.max()))
if not tilt:
print(' !! khong node nao co z (slope.enabled tat luc quet?) -> mat dat PHANG')
# z hai LUOT qua cung mot cho (cach >= 30 node): lech = troi z cua ban do.
lech = []
idx = np.arange(len(ids))
for k in range(len(ids)):
m = (np.hypot(xy[:, 0] - xy[k, 0], xy[:, 1] - xy[k, 1]) < 0.3) & (np.abs(idx - k) > 30)
if m.any():
lech.append(float(np.abs(zz[m] - zz[k]).max()))
if lech:
print(' z giua cac luot qua cung cho (%d node): trung vi %.1f cm, 95%% %.1f cm, max %.1f cm'
% (len(lech), 100 * np.median(lech), 100 * np.percentile(lech, 95), 100 * max(lech)))
# Luot 1 qua DB: khung ban do (node + moi o da thay).
lo_xy, hi_xy = xy.min(0), xy.max(0)
n_grids = 0
for _, em, ob in cells(a.db, pose):
n_grids += 1
for p in (em, ob):
if len(p):
lo_xy, hi_xy = np.minimum(lo_xy, p.min(0)), np.maximum(hi_xy, p.max(0))
if not n_grids:
raise SystemExit('DB khong co luoi cuc bo nao (obstacle_cells / empty_cells)')
x0, y0 = lo_xy - PAD
x1, y1 = hi_xy + PAD
# ---------------- Mat dat: Gauss quanh node, phu ca khung ----------------
TW = int(math.ceil((x1 - x0) / TRES)) + 1
TH = int(math.ceil((y1 - y0) / TRES)) + 1
gx = x0 + np.arange(TW) * TRES
gy = y0 + np.arange(TH) * TRES
Z = np.empty((TH, TW))
for j in range(TH): # tung hang: (TW x so node) -- vua bo nho
d2 = (gx[:, None] - xy[None, :, 0]) ** 2 + (gy[j] - xy[None, :, 1]) ** 2
dmin = d2.min(1, keepdims=True)
# Rong SIGMA sat node, rong dan khi xa (sigma^2 + (d/2)^2): xa duong di
# khong thanh bac o duong chia giua hai node khac z.
w = np.exp(-(d2 - dmin) / (2.0 * SIGMA ** 2 + 0.5 * dmin))
Z[j] = (w @ zz) / w.sum(1)
zt = bilinear(Z, x0, y0, TRES)
dzy, dzx = np.gradient(Z, TRES)
zn = zt(xy[:, 0], xy[:, 1])
gxn = bilinear(dzx, x0, y0, TRES)(xy[:, 0], xy[:, 1])
gyn = bilinear(dzy, x0, y0, TRES)(xy[:, 0], xy[:, 1])
steep = np.degrees(np.arctan(np.hypot(gxn, gyn))) > SLOPE_DEG
print('mat dat %dx%d o %.1f m, z %.2f .. %.2f m; %d node tren doc > %.0f do'
% (TW, TH, TRES, Z.min(), Z.max(), int(steep.sum()), SLOPE_DEG))
# ---------------- Luoi 2D: log-odds nhu slam.yaml, bo tia cham dat ----------------
gp = grid_params(a.root)
lh, lm = logit(gp['ProbHit']), logit(gp['ProbMiss'])
lo, hi = logit(gp['ProbClampingMin']), logit(gp['ProbClampingMax'])
W = int(math.ceil((x1 - x0) / RES))
H = int(math.ceil((y1 - y0) / RES))
L = np.zeros((H, W))
seen = np.zeros((H, W), bool)
ground = np.zeros((H, W), bool)
k_of = {nid: k for k, nid in enumerate(ids)}
n_obs = n_ground = 0
for nid, em, ob in cells(a.db, pose): # luot 2 qua DB
k = k_of[nid]
if len(ob):
# Tia ngang song song mat dat duoi robot, cao LIDAR_H: o nao mat dat
# nho len gan toi do la tia cham DAT, khong phai tuong.
plane = zn[k] + gxn[k] * (ob[:, 0] - xy[k, 0]) + gyn[k] * (ob[:, 1] - xy[k, 1])
g = zt(ob[:, 0], ob[:, 1]) - plane > LIDAR_H - GROUND_TOL
n_obs += len(ob)
if g.any():
n_ground += int(g.sum())
ground[((ob[g, 1] - y0) / RES).astype(int).clip(0, H - 1),
((ob[g, 0] - x0) / RES).astype(int).clip(0, W - 1)] = True
ob = ob[~g]
for pts, d in ((em, lm), (ob, lh)):
if not len(pts):
continue
flat = np.unique(((pts[:, 1] - y0) / RES).astype(int).clip(0, H - 1) * W
+ ((pts[:, 0] - x0) / RES).astype(int).clip(0, W - 1))
L.flat[flat] = np.clip(L.flat[flat] + d, lo, hi)
seen.flat[flat] = True
occ = seen & (L > 0)
ground &= ~occ # o con chiem nho node khac nhin thay that
n_log = int(occ.sum())
occ |= fill_gaps(occ) & ~ground
near = dilate(path_mask(xy, np.ones(len(xy), bool), x0, y0, H, W),
int(math.ceil((ROBOT_R + 0.05) / RES)))
cleared = occ & near
occ &= ~near
print('luoi %dx%d o %.2f m: %d o tuong (log-odds %d + lap khe %d - tren duong da di %d); '
'bo %d/%d lan thay la tia cham dat'
% (W, H, RES, int(occ.sum()), n_log, int((occ | cleared).sum()) - n_log,
int(cleared.sum()), n_ground, n_obs))
if steep.any():
sl = dilate(path_mask(xy, steep, x0, y0, H, W), int(round(0.6 / RES)))
print(' con %d o tuong cach duong DOC <= 0.6 m (tuong / lan can that, hoac tuong gia sot)'
% int((occ & sl).sum()))
# ---------------- Doan doc + diem dat robot ----------------
runs = slope_runs(xy, zz, steep)
for n, (k, e, dz, length) in enumerate(runs):
print('doc #%d: node %d..%d, dai %.1f m, z %.2f -> %.2f (chenh %.2f m, ~%.1f do)'
% (n, ids[k], ids[e], length, zz[k], zz[e], dz,
math.degrees(math.atan2(dz, max(length, 1e-6)))))
spawn = None
if runs:
k, e, _, _ = max(runs, key=lambda r: r[2])
top, step = (e, +1) if zz[e] > zz[k] else (k, -1)
s = walk_out(xy, top, step, 1.0) # lui ~1 m ra mat bang tren
spawn = (float(xy[s, 0]), float(xy[s, 1]), float(yaw[s]))
print('dat robot o DINH doc lon nhat (node %d, z %.2f m): --x %.2f --y %.2f --yaw %.3f'
% (ids[s], zz[s], spawn[0], spawn[1], spawn[2]))
else:
print('!! khong thay doan doc nao (chenh >= 0.2 m) -- --slope-test se bao khong co doc')
# ---------------- Ghi model + world + ban sao DB ----------------
tag = 'tu %s. Sinh boi tools/gen_world_from_db.py -- dung sua tay.' % os.path.basename(a.db)
w = base.Obj('Tuong (o chiem luoi 2D), cao %.1f m tren mat dat, %s Z-UP, met.' % (WALL_H, tag))
rects = wall_rects(occ)
for i0, j0, i1, j1 in rects:
bx0, bx1 = x0 + i0 * RES, x0 + (i1 + 1) * RES
by0, by1 = y0 + j0 * RES, y0 + (j1 + 1) * RES
f = zt(*np.meshgrid(np.linspace(bx0, bx1, max(2, int((bx1 - bx0) / TRES) + 2)),
np.linspace(by0, by1, max(2, int((by1 - by0) / TRES) + 2))))
w.box(bx0, by0, float(f.min()) - 0.05, bx1, by1, float(f.max()) + WALL_H)
print('tuong: %d hop' % len(rects))
models = os.path.join(out, 'models')
for mname, mesh, text, desc in (
(terrain, 'terrain.obj', terrain_obj('Mat dat (z node) %s Z-UP, met.' % tag, gx, gy, Z),
'Mat dat tu z node ban do that.'),
(walls, 'walls.obj', w.text(), 'Tuong tu luoi 2D ban do that.')):
base.write(os.path.join(models, mname, 'meshes', mesh), text)
base.write(os.path.join(models, mname, 'model.sdf'), base.SDF.format(name=mname, mesh=mesh))
base.write(os.path.join(models, mname, 'model.config'),
base.CONFIG.format(name=mname, desc=desc).replace('gen_slope_world', 'gen_world_from_db'))
hint = ('--x %.2f --y %.2f --yaw %.3f' % spawn) if spawn else '(khong co doc)'
world_path = os.path.join(out, name + '.world')
base.write(world_path, ''.join([
'<?xml version="1.0" ?>\n',
'<!-- World %s\n Frame world = frame ban do. Dinh doc lon nhat: %s -->\n' % (tag, hint),
'<sdf version="1.6">\n <world name="%s">\n' % name,
' <include><uri>model://ground_plane</uri></include>\n',
' <include><uri>model://sun</uri></include>\n',
base.include(terrain + '_1', terrain, 0, 0, 0, 0),
base.include(walls + '_1', walls, 0, 0, 0, 0),
' </world>\n</sdf>\n']))
# Ban sao DB: localization co the ghi vao DB, giu ban that nguyen ven. Chep
# lai moi khi ban sao khac ban goc (ca sau mot lan sim da ghi vao no).
db_copy = os.path.join(out, name + '.db')
st = os.stat(a.db)
if (not os.path.exists(db_copy) or os.stat(db_copy).st_size != st.st_size
or int(os.stat(db_copy).st_mtime) != int(st.st_mtime)):
shutil.copy2(a.db, db_copy)
print('chep DB ->', db_copy)
# DB tu Jetson (RTAB-Map 0.23) ma may nay link ban cu hon (0.21) thi RTAB-Map
# tu choi mo ("Opened database version ... is more recent"). Schema 0.23 =
# 0.21 + hai cot 0.21 khong doc (Admin.dictionary_index, Data.depth_confidence),
# nen ha chuoi version cua BAN SAO la du -- 08/10: rtabmap-info + vslam_node
# 0.21.13 nap va dinh vi lai binh thuong tren DB 0.23.12.
local = local_rtabmap_version(a.root)
con = sqlite3.connect(db_copy)
ver = con.execute('select version from Admin').fetchone()[0]
if local and vtuple(ver) > vtuple(local):
con.execute('update Admin set version = ?', (local,))
con.commit()
print('ban sao DB: version %s -> %s (RTAB-Map cua build nay)' % (ver, local))
con.close()
if a.preview:
preview(a.preview, occ, seen, ground, cleared, xy, zz, runs, spawn, x0, y0)
root = os.path.abspath(a.root)
rel = lambda p: os.path.relpath(p, root) if p.startswith(root + os.sep) else p
maps = os.path.join(root, 'resources', 'maps')
db_arg = os.path.relpath(db_copy, maps) if db_copy.startswith(maps + os.sep) else db_copy
mp = rel(models) if os.path.isabs(rel(models)) else '$PWD/' + rel(models)
print('\nChay sim (tu goc repo; dinh vi lai CHI bang LiDAR -- anh sim khac anh that):\n'
' export GAZEBO_MODEL_PATH=$PWD/resources/models:%s\n'
' ./build/app/vslam_node --sim --sim-gl --world %s %s --token t --port 8092 \\\n'
' --slam --slam-db %s --slam-mode localization --slam-reloc --slam-reloc-auto \\\n'
' --slope-test 2>&1 | tee logs/sim_%s.log'
% (mp, rel(world_path), hint, db_arg, name))
if __name__ == '__main__':
main()