upload
This commit is contained in:
29
libs/vslam_sim/CMakeLists.txt
Normal file
29
libs/vslam_sim/CMakeLists.txt
Normal file
@@ -0,0 +1,29 @@
|
||||
# Bo mo phong -- thay Gazebo.
|
||||
#
|
||||
# Dep ngoai: chi yaml-cpp (doc map.yaml). Khong OpenGL, khong vat ly 3D,
|
||||
# khong model database. Do la ca diem: Jetson AGX khong co gi de chay Gazebo,
|
||||
# ma thu can kiem chung cho duong ong 2.5D chi la ban do 2D + raycast.
|
||||
|
||||
find_package(yaml-cpp REQUIRED)
|
||||
|
||||
vslam_add_library(vslam_sim
|
||||
PUBLIC_HDRS
|
||||
sim_source.h
|
||||
occupancy_map_io.h
|
||||
gazebo_world.h
|
||||
PUBLIC_DEPS
|
||||
vslam_common
|
||||
vslam_drivers
|
||||
FIND_DEPS
|
||||
vslam_common
|
||||
vslam_drivers
|
||||
)
|
||||
|
||||
if(TARGET yaml-cpp::yaml-cpp)
|
||||
target_link_libraries(vslam_sim PRIVATE yaml-cpp::yaml-cpp)
|
||||
elseif(TARGET yaml-cpp)
|
||||
target_link_libraries(vslam_sim PRIVATE yaml-cpp)
|
||||
else()
|
||||
target_include_directories(vslam_sim SYSTEM PRIVATE ${YAML_CPP_INCLUDE_DIR})
|
||||
target_link_libraries(vslam_sim PRIVATE ${YAML_CPP_LIBRARIES})
|
||||
endif()
|
||||
152
libs/vslam_sim/include/vslam/gazebo_world.h
Normal file
152
libs/vslam_sim/include/vslam/gazebo_world.h
Normal file
@@ -0,0 +1,152 @@
|
||||
#ifndef VSLAM_GAZEBO_WORLD_H
|
||||
#define VSLAM_GAZEBO_WORLD_H
|
||||
|
||||
// Doc file `.world` cua Gazebo va dung the gioi mo phong tu no.
|
||||
//
|
||||
// ================== VI SAO DOC WORLD CHU KHONG DOC .db ==================
|
||||
// Luoi chiem dung xuat tu `map_hospital.db` co goc o cho robot BAT DAU phien
|
||||
// quet, con file world o he toa do RIENG cua Gazebo. Do duoc: world trai rong
|
||||
// x -12.4..12.4, y -31.9..19.5; luoi tu .db la x -17.1..9.2, y -49.6..8.5 --
|
||||
// lech ~18 m theo y.
|
||||
//
|
||||
// Nen khong the "dan do dac cua world len luoi tu .db". Doc THANG world lam
|
||||
// nguon su that thi ca ba thu -- luoi cho sim, mesh cho khung 3D, va tu the
|
||||
// do dac -- deu o MOT he toa do, va khong can mot phep can chinh nao.
|
||||
//
|
||||
// ================== KHONG CAN PARSER XML DAY DU ==================
|
||||
// Cau truc `.world` cua Gazebo rat deu:
|
||||
//
|
||||
// <model name="X">
|
||||
// <include>
|
||||
// <uri>model://Ten</uri>
|
||||
// <static>true</static>
|
||||
// <pose>x y z roll pitch yaw</pose>
|
||||
// </include>
|
||||
// </model>
|
||||
//
|
||||
// va `model.sdf` cua tung model chi tro toi mot file `.obj`. Mot bo quet the
|
||||
// ~100 dong doc duoc ca hai, va tranh keo them mot dep XML vao `vslam_sim` --
|
||||
// lib nay hien chi phu thuoc `vslam_common`.
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Mot the hien model trong world.
|
||||
struct WorldModel {
|
||||
std::string name; // ten the hien, vd "MetalCabinet_3"
|
||||
std::string model_name; // ten model, vd "MetalCabinet"
|
||||
// Duong dan tuyet doi toi mesh va chat lieu; rong neu khong tim thay.
|
||||
std::string visual_obj;
|
||||
std::string collision_obj;
|
||||
// Tu the trong he toa do WORLD.
|
||||
double x = 0.0, y = 0.0, z = 0.0;
|
||||
double roll = 0.0, pitch = 0.0, yaw = 0.0;
|
||||
|
||||
// ⚠️ He so ti le cua `<mesh><scale>` trong model.sdf.
|
||||
//
|
||||
// File OBJ khong khai don vi, nen Gazebo lay ti le TU SDF. Trong bo model
|
||||
// nay 27 model dung `<scale>`, phan lon la 0.01 (mesh ve bang CENTIMET) va
|
||||
// co ca 0.00817 va `1 1 0.95`.
|
||||
//
|
||||
// Bo qua the nay lam mot chiec xe day 2.4 m thanh 236 m -- da do:
|
||||
// `CGMClassic` mot minh ra bao loi 239 x 111 m, va ca the gioi phinh tu
|
||||
// 25x51 m len 263x146 m.
|
||||
double sx = 1.0, sy = 1.0, sz = 1.0;
|
||||
};
|
||||
|
||||
struct GazeboWorld {
|
||||
std::string world_path;
|
||||
std::vector<WorldModel> models;
|
||||
// Thu muc goc chua cac model da phan giai, de web phuc vu file tinh.
|
||||
std::vector<std::string> model_roots;
|
||||
};
|
||||
|
||||
// Doc `.world` va phan giai `model://` qua `model_paths`.
|
||||
//
|
||||
// `model_paths`: danh sach thu muc, moi cai chua cac thu muc model con (giong
|
||||
// GAZEBO_MODEL_PATH). Rong thi thu $GAZEBO_MODEL_PATH roi ~/.gazebo/models.
|
||||
//
|
||||
// Model khong phan giai duoc KHONG lam ham that bai -- `ground_plane` va `sun`
|
||||
// la built-in cua Gazebo, khong co tren dia, va mot the gioi thieu hai cai do
|
||||
// van dung duoc. Chung duoc bo qua va dem vao `skipped`.
|
||||
StatusResponse LoadGazeboWorld(const std::string& world_path,
|
||||
const std::vector<std::string>& model_paths,
|
||||
GazeboWorld* out, size_t* skipped = nullptr);
|
||||
|
||||
// Raster hoa mesh VA CHAM cua world thanh luoi chiem dung 2D.
|
||||
//
|
||||
// Chi lay tam giac nam trong dai do cao [z_min, z_max] so voi SAN: do la dai
|
||||
// ma LiDAR 2D thuc su quet. Lay het moi do cao se bien ca mat san thanh vat
|
||||
// can, va lay qua cao se bo lot ban ghe.
|
||||
//
|
||||
// `resolution` met/o. `pad` la vien trong them quanh bao loi, tinh bang met.
|
||||
struct WorldRasterOptions {
|
||||
double resolution = 0.05;
|
||||
double z_min = 0.05; // tren mat san mot chut, de khong quet trung san
|
||||
double z_max = 1.20; // duoi tran, tren dinh phan lon do dac
|
||||
double pad = 1.0;
|
||||
};
|
||||
|
||||
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
|
||||
const WorldRasterOptions& opt,
|
||||
OccupancyGrid* out);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Xuat hinh hoc cho khung 3D
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// Khung 3D khong tai duoc file mesh goc: trinh duyet khong co bo doc COLLADA
|
||||
// offline, va 149 texture PNG cua bo model nay tong cong 74 MB -- gui tung ay
|
||||
// moi lan mo trang la khong chap nhan duoc.
|
||||
//
|
||||
// Nen phia C++ (von DA co bo doc) gui thang TAM GIAC. Hinh hoc duoc gop theo
|
||||
// TEN MODEL chu khong theo the hien: world co 181 the hien nhung chi ~69 model
|
||||
// khac nhau, nen 42 chiec ghe chi ton mot ban hinh hoc.
|
||||
|
||||
struct WorldMeshGeom {
|
||||
std::string model_name;
|
||||
// Mau than vat the, lay tu TEXTURE cua chinh model (xem
|
||||
// tools/gen_model_colors.py). Mac dinh la xam men su -- dung cho
|
||||
// KitchenSink va Toilet, hai model duy nhat trong world khong co texture.
|
||||
uint8_t r = 214, g = 214, b = 210;
|
||||
// 9 float moi tam giac (x,y,z) x 3, trong he MODEL: da ap `<scale>` nhung
|
||||
// CHUA ap yaw/tinh tien cua the hien -- do la viec cua instance.
|
||||
std::vector<float> tri;
|
||||
};
|
||||
|
||||
struct WorldMeshInstance {
|
||||
uint32_t geom = 0;
|
||||
float x = 0, y = 0, z = 0, yaw = 0;
|
||||
};
|
||||
|
||||
struct WorldMeshes {
|
||||
std::vector<WorldMeshGeom> geoms;
|
||||
std::vector<WorldMeshInstance> instances;
|
||||
};
|
||||
|
||||
// `visual = true` lay mesh HIEN THI (nhieu tam giac, dep hon); false lay mesh
|
||||
// VA CHAM, von it tam giac va khop chinh xac voi luoi chiem dung.
|
||||
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
|
||||
WorldMeshes* out);
|
||||
|
||||
// Gan mau cho tung hinh hoc tu bang `model_colors.json`.
|
||||
//
|
||||
// Thieu file hoac thieu model trong file KHONG phai loi: vat the do giu mau
|
||||
// mac dinh. Tra ve so hinh hoc da duoc gan mau.
|
||||
size_t ApplyModelColors(const std::string& json_path, WorldMeshes* io);
|
||||
|
||||
// Dong goi `WorldMeshes` thanh khoi nhi phan cho trinh duyet.
|
||||
//
|
||||
// "VSLW" | u32 version | u32 n_geom | u32 n_inst
|
||||
// moi geom : u32 name_len | name | u8 r,g,b | u32 n_tri | n_tri*9 f32
|
||||
// moi inst : u32 geom | f32 x,y,z,yaw
|
||||
void EncodeWorldMeshes(const WorldMeshes& in, std::string* out);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_GAZEBO_WORLD_H
|
||||
49
libs/vslam_sim/include/vslam/occupancy_map_io.h
Normal file
49
libs/vslam_sim/include/vslam/occupancy_map_io.h
Normal file
@@ -0,0 +1,49 @@
|
||||
#ifndef VSLAM_OCCUPANCY_MAP_IO_H
|
||||
#define VSLAM_OCCUPANCY_MAP_IO_H
|
||||
|
||||
// Doc/ghi occupancy grid dang PGM + YAML -- dung dinh dang cua map_server ROS.
|
||||
//
|
||||
// Giu dinh dang cu co y: nguoi dung da quen no, `rtabmap-export` sinh ra no,
|
||||
// va moi map cu trong vSLAM_ws/maps/ deu o dang nay. Bo ROS khong co nghia la
|
||||
// phai bo moi thu ROS cham vao.
|
||||
//
|
||||
// map.yaml:
|
||||
// image: map.pgm
|
||||
// resolution: 0.05
|
||||
// origin: [-5.0, -13.0, 0.0]
|
||||
// negate: 0
|
||||
// occupied_thresh: 0.65
|
||||
// free_thresh: 0.196
|
||||
//
|
||||
// PGM P5 (nhi phan, 8 bit): 0 = den = bi chiem, 255 = trang = trong.
|
||||
// Quy uoc nay NGUOC voi truc quan, va dao nguoc no la mot trong nhung loi
|
||||
// hay gap nhat khi doc map -- ket qua la robot coi tuong la duong di.
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct MapLoadResult {
|
||||
OccupancyGrid grid;
|
||||
std::string image_path;
|
||||
double occupied_thresh = 0.65;
|
||||
double free_thresh = 0.196;
|
||||
};
|
||||
|
||||
// Doc map.yaml va file PGM di kem. Duong dan anh trong YAML duoc hieu la
|
||||
// tuong doi so voi thu muc chua YAML.
|
||||
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out);
|
||||
|
||||
// Ghi ra PGM + YAML. Dung cho tools/vslam_map_export.
|
||||
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
|
||||
const std::string& yaml_path);
|
||||
|
||||
// Sinh mot the gioi tong hop: hanh lang chinh + phong hai ben.
|
||||
// Dung khi chua co map that, de chay thu duong ong ngay lap tuc.
|
||||
OccupancyGrid MakeSyntheticWorld(uint32_t width, uint32_t height, float resolution);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_OCCUPANCY_MAP_IO_H
|
||||
339
libs/vslam_sim/include/vslam/sim_source.h
Normal file
339
libs/vslam_sim/include/vslam/sim_source.h
Normal file
@@ -0,0 +1,339 @@
|
||||
#ifndef VSLAM_SIM_SOURCE_H
|
||||
#define VSLAM_SIM_SOURCE_H
|
||||
|
||||
// Bo mo phong -- thay Gazebo.
|
||||
//
|
||||
// ================== VI SAO KHONG PHAI GAZEBO ==================
|
||||
// Bo ROS la mat gazebo_ros. Nhung ke ca con ROS thi Gazebo cung khong hop:
|
||||
// world `hospital_three_floors.world` co 541 instance model, va `gpu_ray`
|
||||
// 1081 tia @25 Hz duoc chon vi may dev co RTX 4060 -- Jetson AGX khong co thu
|
||||
// do de tieu.
|
||||
//
|
||||
// Cai thuc su can de kiem chung duong ong 2.5D chi la: mot ban do 2D, mot
|
||||
// robot vi sai, va phep raycast. Do la vai tram dong, chay duoc tren CPU, va
|
||||
// KHONG can card do hoa.
|
||||
//
|
||||
// ================== VI SAO NO VUA VAN VAO KIEN TRUC ==================
|
||||
// SimSource implement CHINH cac interface driver, y het ReplaySource. Nen
|
||||
// vslam_node khong phan biet duoc ba nguon: phan cung that, file .vsr, hay mo
|
||||
// phong. Khong co mot nhanh `if (sim)` nao trong logic -- day dung la dieu ma
|
||||
// docs/ARCHITECTURE.md cua repo cu goi la "nguyen tac parity sim <-> real",
|
||||
// nhung lan nay no duoc bao dam boi kieu du lieu chu khong boi ky luat.
|
||||
//
|
||||
// ================== CAI GI KHONG DUOC MO PHONG ==================
|
||||
// docs/SIM_VS_REAL.md cua repo cu liet ke chinh xac nhung cho Gazebo "noi
|
||||
// doi". Bo mo phong nay con noi doi NHIEU HON, va phai noi ro:
|
||||
// * Khong co IR speckle, khong rolling shutter. Depth dropout CO mo phong
|
||||
// nhung bang xac suat deu, tho hon nhieu so voi that (that thi tap trung
|
||||
// o be mat toi, be mat bong va mep vat the).
|
||||
// * Khong co anh infra1/infra2 -- stereo_odometry khong kiem duoc o day.
|
||||
// * LiDAR khong bi nhieu boi be mat den hay guong. Khong co o kinh/guong
|
||||
// (trong suot voi LiDAR VA voi depth), khong co vat can nho ra (mep ban).
|
||||
// * Bien dang anh (distortion) khong mo phong: K la pinhole hoan hao.
|
||||
// Nhung gi mo phong duoc KIEM CHUNG: dong hoc vi sai, tich phan odometry,
|
||||
// EKF, SLAM 2D, lop an toan theo scan, camera depth (raycast 2.5D, Z-depth,
|
||||
// co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va
|
||||
// toan bo duong ong du lieu.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/clock.h"
|
||||
#include "vslam/gazebo_world.h"
|
||||
#include "vslam/driver_interfaces.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct SimConfig {
|
||||
// Ban do. Rong = dung MakeSyntheticWorld().
|
||||
std::string map_yaml;
|
||||
// File `.world` cua Gazebo. Uu tien hon `map_yaml`: luoi duoc raster hoa
|
||||
// THANG tu mesh va cham, nen luoi cua sim, mesh cua khung 3D va tu the do
|
||||
// dac deu o MOT he toa do -- xem `vslam/gazebo_world.h`.
|
||||
std::string world_path;
|
||||
std::vector<std::string> world_model_paths;
|
||||
uint32_t synthetic_width = 600;
|
||||
uint32_t synthetic_height = 400;
|
||||
float synthetic_resolution = 0.05f;
|
||||
|
||||
// Vi tri xuat phat trong frame map.
|
||||
double start_x = 0.0;
|
||||
double start_y = 0.0;
|
||||
double start_yaw = 0.0;
|
||||
|
||||
// Hat giong RNG. Co dinh => cung mot kich ban cho cung mot file .vsr, byte
|
||||
// giong byte. Do la dieu kien de `tools/regress.sh` so ket qua duoc: neu
|
||||
// ban ghi doi moi lan sinh thi moi khac biet deu la nhieu.
|
||||
uint32_t seed = 1234;
|
||||
|
||||
// Hinh hoc robot. PHAI khop robot.yaml.
|
||||
double wheel_radius = 0.075;
|
||||
double wheel_separation = 0.36;
|
||||
|
||||
// LiDAR -- khop cau hinh LakiBeam 1L that.
|
||||
double lidar_rate_hz = 25.0;
|
||||
uint32_t lidar_samples = 1081;
|
||||
double lidar_fov_rad = 4.712389; // 270 do
|
||||
double lidar_range_min = 0.05;
|
||||
double lidar_range_max = 40.0;
|
||||
double lidar_x = 0.24; // vi tri tren robot, khop laser_joint
|
||||
double lidar_z = 0.125;
|
||||
double lidar_noise_stddev = 0.01;
|
||||
|
||||
// ================== CAMERA DEPTH ==================
|
||||
// Gazebo mo phong depth bang libgazebo_ros_openni_kinect. Bo mo phong nay
|
||||
// lam dieu tuong duong bang raycast 2.5D: ban do chiem dung duoc DUNG THANH
|
||||
// tuong cao `wall_height`, va moi o co mot DO CAO SAN rieng.
|
||||
//
|
||||
// Do cao san la thu cho phep kiem `cliff_detect` -- o nao co floor_height
|
||||
// AM la mot bac hut xuong. Khong co lop nay thi san tuyet doi phang va
|
||||
// cliff_detect khong co gi de phat hien.
|
||||
bool enable_depth_camera = true;
|
||||
double camera_rate_hz = 30.0;
|
||||
uint32_t depth_width = 640;
|
||||
uint32_t depth_height = 480;
|
||||
double depth_hfov_rad = 1.204; // 69 do, khop D410 that
|
||||
double depth_near = 0.22; // Min-Z: vung mu truoc mui robot
|
||||
double depth_far = 10.0;
|
||||
|
||||
// ============ NHIEU DEPTH: MO HINH STEREO ============
|
||||
// sigma_d = sqrt(floor^2 + (d^2 * sigma_disp / (f*B))^2)
|
||||
//
|
||||
// Sai so tang theo BINH PHUONG khoang cach, vi depth stereo suy tu DO LECH
|
||||
// PIXEL chu khong do truc tiep. Mot hang so (ban cu: 7 mm) sai o DANG chu
|
||||
// khong chi o tri -- gan thi bi quan, xa thi lac quan gap 10 lan.
|
||||
//
|
||||
// `f` KHONG khai o day: no suy ra tu `depth_hfov_rad` va `depth_width`, de
|
||||
// khong co hai nguon cho cung mot so.
|
||||
//
|
||||
// ⚠️ CA HAI so duoi CHUA XAC MINH tren thiet bi that:
|
||||
// * `depth_baseline` 50 mm la UOC LUONG, khong co trong ban ghi datasheet
|
||||
// nao. Sai 20% thi moi con so nhieu sai 20%.
|
||||
// * `depth_disparity_noise_px` 0.1 px la gia tri DIEN HINH cua stereo
|
||||
// block-matching, khong phai thong so do duoc cua D410.
|
||||
// Do bang `rs-enumerate-devices -c` khi cam camera roi sua o day.
|
||||
double depth_disparity_noise_px = 0.1;
|
||||
double depth_baseline = 0.050; // m, khoang cach hai mat IR
|
||||
// San nhieu gan: dien tu cam bien va luong tu hoa, khong mat khi d -> 0.
|
||||
double depth_noise_floor = 0.002;
|
||||
|
||||
// Ty le diem anh KHONG co gia tri tra ve, mo phong depth dropout cua D410.
|
||||
// Camera that mat diem o be mat toi, be mat bong, va o mep vat the.
|
||||
double depth_dropout_rate = 0.0;
|
||||
|
||||
// Mo phong RUT DAY LiDAR: ngung phat scan tu giay `lidar_cut_at` trong
|
||||
// bao lau. 0 = khong cat.
|
||||
//
|
||||
// Day la cach duy nhat chay duoc nhanh SCAN_TIMEOUT end-to-end. Tieu chi
|
||||
// P4 ghi "rut day LiDAR -> SCAN_TIMEOUT < 1.1 s" nhung truoc kich ban nay
|
||||
// khong co cach nao DO duoc no ngoai viec rut day that.
|
||||
double lidar_cut_at = 0.0;
|
||||
double lidar_cut_for = 0.0;
|
||||
uint32_t depth_decimate = 2; // 640x480 -> 320x240, nhu crop_decimate
|
||||
|
||||
// Vi tri camera tren robot. Khop camera_joint cua robot.urdf.xacro.
|
||||
double camera_x = 0.19;
|
||||
double camera_z = 0.80;
|
||||
double camera_pitch = 0.2618; // 15 do chuc xuong
|
||||
|
||||
double wall_height = 2.0; // tuong cao bao nhieu, tinh tu san
|
||||
|
||||
// ============ SIEU AM ============
|
||||
// Dan cam bien phia truoc, goc tinh tu +X cua than (rad).
|
||||
//
|
||||
// ⚠️ Sieu am ton tai CHI vi mot ly do: KINH. Kinh vo hinh voi LiDAR (tia
|
||||
// xuyen qua) va voi depth camera (IR xuyen qua), nhung phan xa am rat tot.
|
||||
// Khong mo phong kinh thi nhanh US_BLOCKED cua FSM khong bao gio chay, va
|
||||
// ca cam bien do tro thanh do trang tri.
|
||||
bool enable_ultrasonic = true;
|
||||
double us_rate_hz = 20.0;
|
||||
double us_max_range = 2.0; // HC-SR04 thuc te ~4 m, nhung nhieu
|
||||
double us_min_range = 0.03;
|
||||
double us_beam_half_angle = 0.26; // ~15 do nua goc -- chum RAT rong
|
||||
double us_noise_stddev = 0.005;
|
||||
double us_z = 0.12; // cao bao nhieu so voi tam truc
|
||||
// Goc cua tung dau do, rad, 0 = thang truoc.
|
||||
std::vector<double> us_angles = {-0.35, 0.0, 0.35};
|
||||
|
||||
// Ti le mot lan doc bi mat (cam bien khong tra loi) -> NaN -> US_TIMEOUT.
|
||||
double us_dropout_rate = 0.0;
|
||||
|
||||
// ============ BUMPER ============
|
||||
// Cong tac va cham, chot cung. Kich khi than robot cham vat can.
|
||||
bool enable_bumper = true;
|
||||
double bumper_rate_hz = 50.0;
|
||||
|
||||
// Cong tac bumper NHO RA ngoai vo bao nhieu (m).
|
||||
//
|
||||
// ⚠️ PHAI > 0. Phep va cham cua bo mo phong TU CHOI chuyen dong khi vanh
|
||||
// robot (ban kinh `robot_radius`) cham vat can, nen robot khong bao gio
|
||||
// vao duoc vi tri ma mot bumper dat DUNG `robot_radius` nhin thay. Ket qua:
|
||||
// nhanh BUMPER cua FSM khong bao gio chay.
|
||||
//
|
||||
// Bumper that cung nho ra that: no la mot cong tac gan tren vanh nhua, kich
|
||||
// khi CHAM chu khong khi da lun vao. 3 cm la kich thuoc dien hinh.
|
||||
double bumper_reach = 0.03;
|
||||
|
||||
// ============ KINH / GUONG ============
|
||||
// O danh dau la kinh: LiDAR va depth XUYEN QUA (nhu khong co gi), sieu am
|
||||
// THAY binh thuong. Dat bang SetGlass().
|
||||
//
|
||||
// Day la thu Gazebo cua repo cu KHONG mo phong duoc, va la ly do
|
||||
// docs/SIM_VS_REAL.md cu phai ghi "kinh phai kiem bang du lieu that".
|
||||
double glass_lidar_pass_rate = 1.0; // 1.0 = xuyen hoan toan
|
||||
|
||||
double imu_rate_hz = 200.0;
|
||||
double gyro_noise_stddev = 4.9e-4;
|
||||
double accel_noise_stddev = 6.9e-3;
|
||||
|
||||
// ================== NGHIENG THAN ROBOT ==================
|
||||
// Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG,
|
||||
// quay gap lam no NGHIENG ra ngoai. Gazebo mo phong dieu nay qua vat ly
|
||||
// tiep xuc; o day mo phong bang mot he lo xo - giam chan bac hai.
|
||||
//
|
||||
// KHONG CO NGHIENG THI KHONG THU THACH DUOC `gravity_align`. Logic cot loi
|
||||
// cua no la TRU gia toc rieng cua robot truoc khi coi phan con lai la trong
|
||||
// luc (axc = ax - a_lin, ayc = ay - v*w). San phang va robot cung nhac thi
|
||||
// ca hai so hang do bang 0 va bo loc khong bao gio bi kiem tra.
|
||||
//
|
||||
// Gia tri mac dinh chon de dat ~2 do khi tang toc 0.3 m/s^2 -- do la muc
|
||||
// docs/SIM_VS_REAL.md cua repo cu goi la "mon no chua tra ve tilt trong TF".
|
||||
double tilt_pitch_per_accel = 0.12; // rad tren (m/s^2)
|
||||
double tilt_roll_per_centrip = 0.08; // rad tren (m/s^2)
|
||||
double tilt_natural_freq = 4.0; // rad/s, lo xo giam xoc
|
||||
double tilt_damping = 0.7; // he so giam chan
|
||||
|
||||
// San doc: robot NGHIENG THEO dia hinh. Do cao san da co trong ban do do
|
||||
// cao; do doc tinh tu chenh lech giua truoc va sau robot.
|
||||
bool follow_terrain_slope = true;
|
||||
double wheelbase_for_slope = 0.44; // khoang cach truoc-sau de do doc
|
||||
|
||||
double encoder_rate_hz = 50.0;
|
||||
|
||||
// ================== HAI LOAI TRUOT, RAT KHAC NHAU ==================
|
||||
//
|
||||
// slip_factor -- truot DOI XUNG: ca hai banh truot bang nhau.
|
||||
// Encoder bao di xa hon thuc te, nhung KHONG sinh chenh lech quay.
|
||||
// => slip_metric = |omega_encoder - gyro_z| KHONG PHAT HIEN DUOC.
|
||||
// Day la mot gioi han THAT cua phuong phap so gyro, khong phai thieu sot
|
||||
// cai dat. Muon bat loai nay can nguon thu hai (vd visual odometry).
|
||||
//
|
||||
// slip_differential -- truot VI SAI: mot banh truot nhieu hon banh kia.
|
||||
// Sinh mot phep quay GIA ma gyro khong thay => slip_metric bat duoc.
|
||||
// Day la loai ma wheel_odom duoc thiet ke de phat hien, va la loai da do
|
||||
// duoc tren robot that o bai L6 (slip_metric 0.170 > nguong 0.15).
|
||||
//
|
||||
// San nha hang co nuoc va dau mo thi thuong la truot vi sai: mot banh vao
|
||||
// vet dau truoc banh kia.
|
||||
double slip_factor = 0.0;
|
||||
double slip_differential = 0.0;
|
||||
double slip_accel_threshold = 0.3; // m/s^2
|
||||
|
||||
// Gioi han dong hoc, khop diff_drive_controller cu.
|
||||
double max_linear = 0.35;
|
||||
double max_angular = 0.8;
|
||||
double accel_limit = 0.3;
|
||||
|
||||
// DEADMAN: khong nhan lenh trong bao lau thi tu dung.
|
||||
//
|
||||
// Phai NGAN hon deadman phia JS (500 ms), de base dung truoc khi lop tren
|
||||
// kip phan ung. Tab trinh duyet dong giua luc dang lai, hoac wifi rot, deu
|
||||
// dan toi cung mot chuyen: khong con ai gui lenh nua.
|
||||
double cmd_timeout_sec = 0.3;
|
||||
|
||||
// Va cham: robot dung lai khi cham tuong.
|
||||
bool enable_collision = true;
|
||||
double robot_radius = 0.24;
|
||||
|
||||
// 1.0 = thoi gian that. 0 = chay nhanh nhat co the (cho bai regression).
|
||||
double speed = 1.0;
|
||||
};
|
||||
|
||||
// So huu ca bon nguon, y het ReplaySource.
|
||||
class SimSource {
|
||||
public:
|
||||
explicit SimSource(SimConfig cfg);
|
||||
~SimSource();
|
||||
|
||||
SimSource(const SimSource&) = delete;
|
||||
SimSource& operator=(const SimSource&) = delete;
|
||||
|
||||
StatusResponse Open();
|
||||
|
||||
ClockPtr clock() const;
|
||||
|
||||
LidarInterface* lidar();
|
||||
McuInterface* mcu();
|
||||
BaseInterface* base();
|
||||
// Camera depth mo phong bang raycast 2.5D. Tra nullptr khi tat
|
||||
// (enable_depth_camera = false) chu khong tra mot camera khong co anh.
|
||||
CameraInterface* camera();
|
||||
|
||||
// Ban do do cao san, cung kich thuoc voi map(). Gia tri AM la mot bac hut
|
||||
// xuong -- do la thu cliff_detect phai phat hien.
|
||||
//
|
||||
// Mac dinh phang (toan 0). Dung AddCliff() de tao bac.
|
||||
const std::vector<float>& floor_height() const;
|
||||
|
||||
// Dat mot vung hinh chu nhat (toa do THE GIOI, met) thanh do cao `z`.
|
||||
// z am = bac hut xuong / cau thang di xuong.
|
||||
void SetFloorHeight(double x0, double y0, double x1, double y1, float z);
|
||||
|
||||
// Danh dau mot vung hinh chu nhat (toa do THE GIOI, met) la KINH.
|
||||
//
|
||||
// O kinh phai la o BI CHIEM trong ban do (data >= 50) -- kinh la vat can
|
||||
// that, chi la vat can ma hai cam bien kia khong thay. Danh dau mot o
|
||||
// trong la kinh khong co y nghia gi va bi bo qua.
|
||||
void SetGlass(double x0, double y0, double x1, double y1, bool is_glass);
|
||||
|
||||
// Thay ban do sau khi Open(). CHI dung de dung kich ban thu nghiem -- no
|
||||
// khong dong bo voi bat ky thu gi dang chay, nen goi truoc khi Run().
|
||||
void SetMapForTest(const OccupancyGrid& m);
|
||||
|
||||
// Model doc duoc tu `.world`; rong neu khong chay tu world. Khung 3D dung
|
||||
// no de ve do dac that thay vi khoi hop dung tu luoi.
|
||||
const GazeboWorld& world() const;
|
||||
const std::vector<uint8_t>& glass_mask() const;
|
||||
|
||||
// Cham vao vat can chua (bumper THAT dang bi nhan).
|
||||
bool true_bumper() const;
|
||||
|
||||
// Ban do dung de raycast. Cung la ban do "that" ma SLAM se phai dung lai.
|
||||
const OccupancyGrid& map() const;
|
||||
|
||||
// Do nghieng THAT cua than robot (rad). CHI dung de danh gia -- khong
|
||||
// estimator nao duoc doc. `gravity_align` phai TU uoc luong hai so nay tu
|
||||
// IMU, va day la dap an de cham diem.
|
||||
void true_tilt(double* roll, double* pitch) const;
|
||||
|
||||
// Pose that cua robot. CHI dung de danh gia -- khong estimator nao duoc
|
||||
// doc ham nay. Day la tuong duong cua /ground_truth/odom trong repo cu.
|
||||
Pose2D ground_truth() const;
|
||||
|
||||
// Chay mo phong. Chan cho toi khi RequestStop().
|
||||
void Run();
|
||||
// Chay dung `seconds` thoi gian mo phong roi dung. Dung cho test.
|
||||
void RunFor(double seconds);
|
||||
void RequestStop();
|
||||
|
||||
struct Stats {
|
||||
uint64_t scans = 0;
|
||||
uint64_t imu = 0;
|
||||
uint64_t encoder = 0;
|
||||
uint64_t camera_frames = 0;
|
||||
uint64_t collisions = 0;
|
||||
double sim_time_sec = 0.0;
|
||||
double distance_travelled = 0.0;
|
||||
};
|
||||
Stats stats() const;
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_SIM_SOURCE_H
|
||||
863
libs/vslam_sim/src/gazebo_world.cc
Normal file
863
libs/vslam_sim/src/gazebo_world.cc
Normal file
@@ -0,0 +1,863 @@
|
||||
#include "vslam/gazebo_world.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include "vslam/log.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
bool FileExists(const std::string& p) {
|
||||
struct stat st;
|
||||
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISREG(st.st_mode);
|
||||
}
|
||||
|
||||
bool DirExists(const std::string& p) {
|
||||
struct stat st;
|
||||
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
|
||||
}
|
||||
|
||||
std::string ReadFile(const std::string& p) {
|
||||
std::ifstream f(p);
|
||||
if (!f) return "";
|
||||
std::ostringstream o;
|
||||
o << f.rdbuf();
|
||||
return o.str();
|
||||
}
|
||||
|
||||
// Lay noi dung cua the <tag> DAU TIEN tu vi tri `from`. Tra chuoi rong neu
|
||||
// khong co. `end_out` nhan vi tri ngay sau the dong.
|
||||
//
|
||||
// Du cho cau truc rat deu cua SDF; khong nham lam mot parser XML tong quat.
|
||||
std::string Tag(const std::string& s, const std::string& tag, size_t from,
|
||||
size_t* end_out = nullptr) {
|
||||
const std::string open = "<" + tag + ">";
|
||||
const std::string close = "</" + tag + ">";
|
||||
const size_t a = s.find(open, from);
|
||||
if (a == std::string::npos) return "";
|
||||
const size_t b = s.find(close, a);
|
||||
if (b == std::string::npos) return "";
|
||||
if (end_out) *end_out = b + close.size();
|
||||
return s.substr(a + open.size(), b - a - open.size());
|
||||
}
|
||||
|
||||
std::string Trim(const std::string& s) {
|
||||
const size_t a = s.find_first_not_of(" \t\r\n");
|
||||
if (a == std::string::npos) return "";
|
||||
const size_t b = s.find_last_not_of(" \t\r\n");
|
||||
return s.substr(a, b - a + 1);
|
||||
}
|
||||
|
||||
// "x y z roll pitch yaw" -> sau so. Thieu thi de 0.
|
||||
void ParsePose(const std::string& s, WorldModel* m) {
|
||||
std::istringstream in(s);
|
||||
double v[6] = {0, 0, 0, 0, 0, 0};
|
||||
for (int i = 0; i < 6 && (in >> v[i]); ++i) {}
|
||||
m->x = v[0]; m->y = v[1]; m->z = v[2];
|
||||
m->roll = v[3]; m->pitch = v[4]; m->yaw = v[5];
|
||||
}
|
||||
|
||||
std::vector<std::string> DefaultModelPaths() {
|
||||
std::vector<std::string> out;
|
||||
if (const char* env = std::getenv("GAZEBO_MODEL_PATH")) {
|
||||
std::string s(env), cur;
|
||||
std::istringstream in(s);
|
||||
while (std::getline(in, cur, ':')) if (!cur.empty()) out.push_back(cur);
|
||||
}
|
||||
if (const char* home = std::getenv("HOME")) {
|
||||
// Cho mac dinh cua Gazebo, va cho ma repo nay that su de model.
|
||||
out.push_back(std::string(home) + "/.gazebo/models");
|
||||
out.push_back(std::string(home) + "/gazebo_models/aws_hospital_fuel");
|
||||
out.push_back(std::string(home) + "/gazebo_models/aws_hospital");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// `model://Ten` hoac `model://Ten/meshes/x.obj` -> duong dan tuyet doi.
|
||||
std::string ResolveModelUri(const std::string& uri,
|
||||
const std::vector<std::string>& roots,
|
||||
std::string* root_used) {
|
||||
const std::string prefix = "model://";
|
||||
if (uri.compare(0, prefix.size(), prefix) != 0) return "";
|
||||
const std::string rel = uri.substr(prefix.size());
|
||||
for (const std::string& r : roots) {
|
||||
const std::string p = r + "/" + rel;
|
||||
if (FileExists(p) || DirExists(p)) {
|
||||
if (root_used) *root_used = r;
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
StatusResponse LoadGazeboWorld(const std::string& world_path,
|
||||
const std::vector<std::string>& model_paths,
|
||||
GazeboWorld* out, size_t* skipped) {
|
||||
const std::string src = ReadFile(world_path);
|
||||
if (src.empty()) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kNotFound,
|
||||
"khong doc duoc file world: " + world_path);
|
||||
}
|
||||
|
||||
std::vector<std::string> roots = model_paths;
|
||||
if (roots.empty()) roots = DefaultModelPaths();
|
||||
// Bo cac thu muc khong ton tai -- de thong bao loi ben duoi khong liet ke
|
||||
// mot dong duong dan vo nghia.
|
||||
roots.erase(std::remove_if(roots.begin(), roots.end(),
|
||||
[](const std::string& p) { return !DirExists(p); }),
|
||||
roots.end());
|
||||
if (roots.empty()) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kNotFound,
|
||||
"khong tim thay thu muc model nao. Dat GAZEBO_MODEL_PATH, hoac de "
|
||||
"model o ~/.gazebo/models.");
|
||||
}
|
||||
|
||||
out->world_path = world_path;
|
||||
out->models.clear();
|
||||
size_t skip = 0;
|
||||
|
||||
// Quet tung the <model name="...">.
|
||||
size_t pos = 0;
|
||||
const std::string kModelOpen = "<model name=";
|
||||
while ((pos = src.find(kModelOpen, pos)) != std::string::npos) {
|
||||
const size_t name_a = src.find('"', pos);
|
||||
const size_t name_b = name_a == std::string::npos
|
||||
? std::string::npos : src.find('"', name_a + 1);
|
||||
if (name_b == std::string::npos) break;
|
||||
|
||||
WorldModel m;
|
||||
m.name = src.substr(name_a + 1, name_b - name_a - 1);
|
||||
|
||||
// Khoi cua model nay ket thuc o </model> gan nhat.
|
||||
const size_t block_end = src.find("</model>", name_b);
|
||||
if (block_end == std::string::npos) break;
|
||||
const std::string block = src.substr(name_b, block_end - name_b);
|
||||
|
||||
const std::string uri = Trim(Tag(block, "uri", 0));
|
||||
ParsePose(Tag(block, "pose", 0), &m);
|
||||
pos = block_end + 8;
|
||||
|
||||
if (uri.empty()) { skip++; continue; }
|
||||
m.model_name = uri.substr(uri.rfind('/') + 1);
|
||||
|
||||
std::string root;
|
||||
const std::string dir = ResolveModelUri(uri, roots, &root);
|
||||
if (dir.empty()) {
|
||||
// `ground_plane` va `sun` la built-in cua Gazebo, khong co tren dia.
|
||||
// Bo qua chung la DUNG, khong phai loi.
|
||||
skip++;
|
||||
continue;
|
||||
}
|
||||
if (std::find(out->model_roots.begin(), out->model_roots.end(), root) ==
|
||||
out->model_roots.end()) {
|
||||
out->model_roots.push_back(root);
|
||||
}
|
||||
|
||||
// model.sdf tro toi mesh. Lay ca visual lan collision: chung thuong la
|
||||
// cung mot file, nhung khi khac nhau thi collision la ban da giam da
|
||||
// giac -- dung cai do de raster hoa se nhanh hon nhieu.
|
||||
const std::string sdf = ReadFile(dir + "/model.sdf");
|
||||
if (!sdf.empty()) {
|
||||
size_t vp = sdf.find("<visual");
|
||||
if (vp != std::string::npos) {
|
||||
const std::string u = Trim(Tag(sdf, "uri", vp));
|
||||
m.visual_obj = ResolveModelUri(u, roots, nullptr);
|
||||
}
|
||||
size_t cp = sdf.find("<collision");
|
||||
if (cp != std::string::npos) {
|
||||
const std::string u = Trim(Tag(sdf, "uri", cp));
|
||||
m.collision_obj = ResolveModelUri(u, roots, nullptr);
|
||||
}
|
||||
// `<scale>` nam trong khoi <mesh>. Lay cua collision truoc, khong co
|
||||
// thi cua visual -- hai cai hau nhu luon giong nhau.
|
||||
{
|
||||
size_t sp = (cp != std::string::npos) ? cp : vp;
|
||||
if (sp != std::string::npos) {
|
||||
const std::string sc = Trim(Tag(sdf, "scale", sp));
|
||||
std::istringstream in(sc);
|
||||
double v[3] = {1, 1, 1};
|
||||
int n = 0;
|
||||
while (n < 3 && (in >> v[n])) n++;
|
||||
if (n == 3) { m.sx = v[0]; m.sy = v[1]; m.sz = v[2]; }
|
||||
else if (n == 1) { m.sx = m.sy = m.sz = v[0]; }
|
||||
}
|
||||
}
|
||||
}
|
||||
// Khong co collision rieng thi dung visual -- van tot hon la bo qua han
|
||||
// mot buc tuong.
|
||||
if (m.collision_obj.empty()) m.collision_obj = m.visual_obj;
|
||||
if (m.visual_obj.empty()) m.visual_obj = m.collision_obj;
|
||||
// ⚠️ File world nay co san pose HONG.
|
||||
//
|
||||
// `StorageRack_1` mang `<pose>9.07 -10.36 -7.57769e+08 ...>`: mot vat da
|
||||
// roi xuyen san trong mot phien Gazebo nao do roi world duoc luu lai.
|
||||
// Gazebo cung khong hien chung -- chung o cach mat dat 757 nghin km.
|
||||
//
|
||||
// Khong loc thi luoi van dung (tam giac roi ngoai dai z) nhung khung 3D
|
||||
// cap phat instance cho vat khong bao gio thay duoc, va moi phep tinh bao
|
||||
// loi deu vo nghia.
|
||||
if (std::fabs(m.x) > 1000.0 || std::fabs(m.y) > 1000.0 ||
|
||||
std::fabs(m.z) > 1000.0) {
|
||||
VSLAM_WARN("world: bo model " << m.name << " -- pose vo ly ("
|
||||
<< m.x << ", " << m.y << ", " << m.z << ")");
|
||||
skip++;
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
out->models.push_back(std::move(m));
|
||||
}
|
||||
|
||||
if (skipped) *skipped = skip;
|
||||
VSLAM_INFO("world " << world_path << ": " << out->models.size()
|
||||
<< " model phan giai duoc"
|
||||
<< (skip ? ", bo qua " + std::to_string(skip) +
|
||||
" (ground_plane/sun la built-in)"
|
||||
: ""));
|
||||
if (out->models.empty()) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
world_path + ": khong phan giai duoc model nao");
|
||||
}
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Raster hoa
|
||||
// ---------------------------------------------------------------------------
|
||||
namespace {
|
||||
|
||||
struct Tri { double x[3], y[3], z[3]; };
|
||||
|
||||
// Ma tran 4x4 hang-chinh, chi dung cho phep bien doi affine cua COLLADA.
|
||||
struct Mat4 {
|
||||
double m[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
|
||||
};
|
||||
|
||||
Mat4 MatMul(const Mat4& a, const Mat4& b) {
|
||||
Mat4 r;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
double s = 0;
|
||||
for (int k = 0; k < 4; ++k) s += a.m[i * 4 + k] * b.m[k * 4 + j];
|
||||
r.m[i * 4 + j] = s;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
void MatApply(const Mat4& t, double* x, double* y, double* z) {
|
||||
const double px = *x, py = *y, pz = *z;
|
||||
*x = t.m[0] * px + t.m[1] * py + t.m[2] * pz + t.m[3];
|
||||
*y = t.m[4] * px + t.m[5] * py + t.m[6] * pz + t.m[7];
|
||||
*z = t.m[8] * px + t.m[9] * py + t.m[10] * pz + t.m[11];
|
||||
}
|
||||
|
||||
Mat4 MakeTranslate(double x, double y, double z) {
|
||||
Mat4 t;
|
||||
t.m[3] = x; t.m[7] = y; t.m[11] = z;
|
||||
return t;
|
||||
}
|
||||
|
||||
// Quay quanh truc (ax,ay,az) mot goc `deg` DO -- COLLADA dung do, khong radian.
|
||||
Mat4 MakeRotate(double ax, double ay, double az, double deg) {
|
||||
const double n = std::sqrt(ax * ax + ay * ay + az * az);
|
||||
Mat4 t;
|
||||
if (n < 1e-12) return t;
|
||||
ax /= n; ay /= n; az /= n;
|
||||
const double a = deg * M_PI / 180.0, c = std::cos(a), s = std::sin(a), k = 1 - c;
|
||||
t.m[0] = c + ax*ax*k; t.m[1] = ax*ay*k - az*s; t.m[2] = ax*az*k + ay*s;
|
||||
t.m[4] = ay*ax*k + az*s; t.m[5] = c + ay*ay*k; t.m[6] = ay*az*k - ax*s;
|
||||
t.m[8] = az*ax*k - ay*s; t.m[9] = az*ay*k + ax*s; t.m[10] = c + az*az*k;
|
||||
return t;
|
||||
}
|
||||
|
||||
Mat4 MakeScale(double x, double y, double z) {
|
||||
Mat4 t;
|
||||
t.m[0] = x; t.m[5] = y; t.m[10] = z;
|
||||
return t;
|
||||
}
|
||||
|
||||
std::vector<double> ParseFloats(const std::string& s) {
|
||||
std::vector<double> v;
|
||||
std::istringstream in(s);
|
||||
double d;
|
||||
while (in >> d) v.push_back(d);
|
||||
return v;
|
||||
}
|
||||
|
||||
// Lay gia tri thuoc tinh `attr` cua the bat dau tai `tag_pos`.
|
||||
std::string Attr(const std::string& s, size_t tag_pos, const std::string& attr) {
|
||||
const size_t end = s.find('>', tag_pos);
|
||||
if (end == std::string::npos) return "";
|
||||
const size_t a = s.find(attr + "=\"", tag_pos);
|
||||
if (a == std::string::npos || a > end) return "";
|
||||
const size_t b = a + attr.size() + 2;
|
||||
const size_t c = s.find('"', b);
|
||||
if (c == std::string::npos) return "";
|
||||
return s.substr(b, c - b);
|
||||
}
|
||||
|
||||
// Doc tam giac tu file COLLADA (.dae).
|
||||
//
|
||||
// ⚠️ QUY UOC NAM TRONG TUNG FILE, KHONG PHAI TOAN CUC.
|
||||
//
|
||||
// Cac mesh `.obj` cua bo model nay la Z-UP, don vi MET. Nhung `.dae` cua
|
||||
// tuong/san lai la:
|
||||
// <unit meter="0.01" name="centimeter"/>
|
||||
// <up_axis>Y_UP</up_axis>
|
||||
// Ap mot quy uoc chung cho ca hai lam luoi ra la RAC ma van "trong nhu co du
|
||||
// lieu": da do mot lan ra luoi 5235x5942 o (262 x 297 m) cho mot toa nha chi
|
||||
// rong 25 x 51 m.
|
||||
//
|
||||
// Ho tro tap con thuc su xuat hien trong bo model AWS: <polylist> va
|
||||
// <triangles>, input co offset, va phep bien doi cua <node> (translate /
|
||||
// rotate truc-goc theo DO / scale).
|
||||
// So duoi file KHONG phan biet hoa thuong.
|
||||
//
|
||||
// ⚠️ Bo model nay tron ca `.dae` lan `.DAE`: 15 model `aws_robomaker_
|
||||
// residential_*` va `warehouse_*` dung chu hoa. So phan biet hoa thuong lam
|
||||
// chung roi vao bo doc OBJ va HONG IM LANG -- khong loi, khong canh bao, chi
|
||||
// la sofa/tu lanh/tranh tuong bien mat khoi ca khung 3D LAN luoi chiem dung.
|
||||
bool IsDae(const std::string& p) {
|
||||
if (p.size() < 4) return false;
|
||||
const std::string e = p.substr(p.size() - 4);
|
||||
return (e[0] == '.') && (e[1] == 'd' || e[1] == 'D') &&
|
||||
(e[2] == 'a' || e[2] == 'A') && (e[3] == 'e' || e[3] == 'E');
|
||||
}
|
||||
|
||||
bool ReadDaeTriangles(const std::string& path, std::vector<Tri>* out) {
|
||||
const std::string s = ReadFile(path);
|
||||
if (s.empty()) return false;
|
||||
|
||||
// --- don vi va truc len ---
|
||||
double unit = 1.0;
|
||||
{
|
||||
const size_t u = s.find("<unit");
|
||||
if (u != std::string::npos) {
|
||||
const std::string v = Attr(s, u, "meter");
|
||||
if (!v.empty()) unit = std::atof(v.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// --- source id -> mang float ---
|
||||
std::map<std::string, std::vector<double>> sources;
|
||||
for (size_t p = 0; (p = s.find("<source", p)) != std::string::npos;) {
|
||||
const std::string id = Attr(s, p, "id");
|
||||
size_t fa = s.find("<float_array", p);
|
||||
const size_t next_src = s.find("<source", p + 1);
|
||||
if (fa != std::string::npos && (next_src == std::string::npos || fa < next_src)) {
|
||||
const size_t open_end = s.find('>', fa);
|
||||
const size_t close = s.find("</float_array>", open_end);
|
||||
if (open_end != std::string::npos && close != std::string::npos && !id.empty()) {
|
||||
sources[id] = ParseFloats(s.substr(open_end + 1, close - open_end - 1));
|
||||
}
|
||||
}
|
||||
p += 7;
|
||||
}
|
||||
|
||||
// --- vertices id -> source id cua POSITION ---
|
||||
std::map<std::string, std::string> vert_to_src;
|
||||
for (size_t p = 0; (p = s.find("<vertices", p)) != std::string::npos;) {
|
||||
const std::string id = Attr(s, p, "id");
|
||||
const size_t in = s.find("<input", p);
|
||||
const size_t close = s.find("</vertices>", p);
|
||||
if (in != std::string::npos && close != std::string::npos && in < close) {
|
||||
std::string src = Attr(s, in, "source");
|
||||
if (!src.empty() && src[0] == '#') src.erase(0, 1);
|
||||
if (!id.empty()) vert_to_src[id] = src;
|
||||
}
|
||||
p += 9;
|
||||
}
|
||||
|
||||
// --- phep bien doi cua node, theo id geometry duoc instance ben trong ---
|
||||
std::map<std::string, Mat4> geom_xform;
|
||||
for (size_t p = 0; (p = s.find("<node", p)) != std::string::npos;) {
|
||||
const size_t node_end = s.find("</node>", p);
|
||||
const size_t limit = node_end == std::string::npos ? s.size() : node_end;
|
||||
Mat4 t;
|
||||
// Thu tu ap la thu tu XUAT HIEN trong file -- COLLADA quy dinh vay.
|
||||
//
|
||||
// ⚠️ `<matrix>` KHONG the bo qua. Bo model nay co hai ho file: ho xuat tu
|
||||
// Blender dung translate/rotate/scale, ho xuat tu 3ds Max dung MOT the
|
||||
// `<matrix>`. Bo qua the do lam ti le sai tu 10x den 100x ma khong mot
|
||||
// canh bao nao -- da do sofa ra 24.4 m va buc tranh ra 5 cm, ca hai trong
|
||||
// file khai `<unit meter="0.01">` y het cac file dung.
|
||||
for (size_t q = p; q < limit;) {
|
||||
const size_t tr = s.find("<translate", q), ro = s.find("<rotate", q),
|
||||
sc = s.find("<scale", q), mx = s.find("<matrix", q);
|
||||
size_t nxt = std::min({tr == std::string::npos ? limit : tr,
|
||||
ro == std::string::npos ? limit : ro,
|
||||
sc == std::string::npos ? limit : sc,
|
||||
mx == std::string::npos ? limit : mx});
|
||||
if (nxt >= limit) break;
|
||||
const size_t oe = s.find('>', nxt), ce = s.find('<', oe + 1);
|
||||
const std::vector<double> v = ParseFloats(s.substr(oe + 1, ce - oe - 1));
|
||||
if (nxt == tr && v.size() >= 3) t = MatMul(t, MakeTranslate(v[0], v[1], v[2]));
|
||||
else if (nxt == ro && v.size() >= 4) t = MatMul(t, MakeRotate(v[0], v[1], v[2], v[3]));
|
||||
else if (nxt == sc && v.size() >= 3) t = MatMul(t, MakeScale(v[0], v[1], v[2]));
|
||||
else if (nxt == mx && v.size() >= 16) {
|
||||
// COLLADA ghi ma tran theo HANG, cung quy uoc voi Mat4 o day.
|
||||
Mat4 mm;
|
||||
for (int i = 0; i < 16; ++i) mm.m[i] = v[static_cast<size_t>(i)];
|
||||
t = MatMul(t, mm);
|
||||
}
|
||||
q = ce;
|
||||
}
|
||||
for (size_t g = p; (g = s.find("<instance_geometry", g)) != std::string::npos &&
|
||||
g < limit;) {
|
||||
std::string url = Attr(s, g, "url");
|
||||
if (!url.empty() && url[0] == '#') url.erase(0, 1);
|
||||
if (!url.empty()) geom_xform[url] = t;
|
||||
g += 18;
|
||||
}
|
||||
p += 5;
|
||||
}
|
||||
|
||||
// --- geometry -> tam giac ---
|
||||
size_t before = out->size();
|
||||
for (size_t p = 0; (p = s.find("<geometry", p)) != std::string::npos;) {
|
||||
const std::string gid = Attr(s, p, "id");
|
||||
const size_t gend = s.find("</geometry>", p);
|
||||
const size_t limit = gend == std::string::npos ? s.size() : gend;
|
||||
|
||||
Mat4 xf;
|
||||
auto it = geom_xform.find(gid);
|
||||
if (it != geom_xform.end()) xf = it->second;
|
||||
|
||||
// ⚠️ `<up_axis>` cua bo model nay PHAI BI BO QUA.
|
||||
//
|
||||
// Moi file deu khai `<up_axis>Y_UP`, nhung do la noi ve he toa do cua bo
|
||||
// XUAT, khong phai cua du lieu trong file. Bo xuat nay da nuong phep doi
|
||||
// truc vao node goc, va chi nuong KHI CAN:
|
||||
//
|
||||
// walls_collision ID3 : dinh (56.12, 3.00, 25.12) -- Y-up that
|
||||
// node co `0 1 0 90` + `0 0 1 -270` de doi truc
|
||||
// walls_visual ID43: dinh (25.12, 56.12, 3.00) -- DA la Z-up
|
||||
// node RONG, khong can doi gi
|
||||
//
|
||||
// Cung mot buc tuong, hai file, hai cach. Ap them `<up_axis>` lam cai thu
|
||||
// hai bi lat: buc tuong 3 m thanh mot thanh DUNG DUNG cao 56 m giua san.
|
||||
//
|
||||
// Tung thu doan theo ma tran node ("node don vi thi lat") -- sai chinh o
|
||||
// ID43. Node don vi o day nghia la "khong can doi", khong phai "chua doi".
|
||||
|
||||
|
||||
for (size_t q = p; q < limit;) {
|
||||
const size_t pl = s.find("<polylist", q), trg = s.find("<triangles", q);
|
||||
size_t prim = std::min(pl == std::string::npos ? limit : pl,
|
||||
trg == std::string::npos ? limit : trg);
|
||||
if (prim >= limit) break;
|
||||
const bool is_poly = (prim == pl);
|
||||
const size_t pend = s.find(is_poly ? "</polylist>" : "</triangles>", prim);
|
||||
if (pend == std::string::npos) break;
|
||||
|
||||
// Tim input VERTEX va stride (offset lon nhat + 1).
|
||||
int vert_off = -1, stride = 1;
|
||||
std::string vsrc;
|
||||
for (size_t i = prim; (i = s.find("<input", i)) != std::string::npos && i < pend;) {
|
||||
const std::string off = Attr(s, i, "offset");
|
||||
if (!off.empty()) stride = std::max(stride, std::atoi(off.c_str()) + 1);
|
||||
if (Attr(s, i, "semantic") == "VERTEX") {
|
||||
vert_off = off.empty() ? 0 : std::atoi(off.c_str());
|
||||
vsrc = Attr(s, i, "source");
|
||||
if (!vsrc.empty() && vsrc[0] == '#') vsrc.erase(0, 1);
|
||||
}
|
||||
i += 6;
|
||||
}
|
||||
if (vert_off < 0) { q = pend; continue; }
|
||||
|
||||
auto vt = vert_to_src.find(vsrc);
|
||||
const std::string psrc = vt != vert_to_src.end() ? vt->second : vsrc;
|
||||
auto ps = sources.find(psrc);
|
||||
if (ps == sources.end()) { q = pend; continue; }
|
||||
const std::vector<double>& pos = ps->second;
|
||||
|
||||
std::vector<double> vcount;
|
||||
if (is_poly) {
|
||||
const size_t vc = s.find("<vcount>", prim);
|
||||
if (vc != std::string::npos && vc < pend) {
|
||||
const size_t e = s.find("</vcount>", vc);
|
||||
vcount = ParseFloats(s.substr(vc + 8, e - vc - 8));
|
||||
}
|
||||
}
|
||||
const size_t pp = s.find("<p>", prim);
|
||||
if (pp == std::string::npos || pp > pend) { q = pend; continue; }
|
||||
const size_t pe = s.find("</p>", pp);
|
||||
const std::vector<double> idx = ParseFloats(s.substr(pp + 3, pe - pp - 3));
|
||||
|
||||
auto vertex = [&](size_t n, double* x, double* y, double* z) {
|
||||
const size_t vi = static_cast<size_t>(idx[n * stride + vert_off]) * 3;
|
||||
if (vi + 2 >= pos.size()) return false;
|
||||
// ⚠️ THU TU: ap ma tran node TRUOC, roi moi doi don vi.
|
||||
//
|
||||
// `<translate>` cua node nam trong CUNG don vi cua file (o day la
|
||||
// centimet). Nhan `unit` vao dinh truoc roi ap mot translate tinh
|
||||
// bang cm se coi 5000 cm thanh 5000 MET -- da do mot lan ra luoi
|
||||
// 263 x 146 m cho mot toa nha 25 x 51 m.
|
||||
double px = pos[vi], py = pos[vi + 1], pz = pos[vi + 2];
|
||||
MatApply(xf, &px, &py, &pz);
|
||||
px *= unit; py *= unit; pz *= unit;
|
||||
// Y_UP -> Z_UP cua ROS: (x, y, z)_dae -> (x, -z, y)
|
||||
*x = px; *y = py; *z = pz;
|
||||
return true;
|
||||
};
|
||||
|
||||
const size_t nvert = stride > 0 ? idx.size() / stride : 0;
|
||||
if (is_poly && !vcount.empty()) {
|
||||
size_t base = 0;
|
||||
for (double cd : vcount) {
|
||||
const size_t c = static_cast<size_t>(cd);
|
||||
for (size_t k = 2; k < c && base + k < nvert; ++k) {
|
||||
Tri t;
|
||||
bool ok = vertex(base, &t.x[0], &t.y[0], &t.z[0]) &&
|
||||
vertex(base + k - 1, &t.x[1], &t.y[1], &t.z[1]) &&
|
||||
vertex(base + k, &t.x[2], &t.y[2], &t.z[2]);
|
||||
if (ok) out->push_back(t);
|
||||
}
|
||||
base += c;
|
||||
}
|
||||
} else {
|
||||
for (size_t k = 0; k + 2 < nvert; k += 3) {
|
||||
Tri t;
|
||||
bool ok = vertex(k, &t.x[0], &t.y[0], &t.z[0]) &&
|
||||
vertex(k + 1, &t.x[1], &t.y[1], &t.z[1]) &&
|
||||
vertex(k + 2, &t.x[2], &t.y[2], &t.z[2]);
|
||||
if (ok) out->push_back(t);
|
||||
}
|
||||
}
|
||||
q = pend;
|
||||
}
|
||||
p = limit;
|
||||
}
|
||||
return out->size() > before;
|
||||
}
|
||||
|
||||
// Doc tam giac tu file OBJ. Chi can `v` va `f`; bo qua vt/vn/usemtl.
|
||||
//
|
||||
// OBJ danh chi so tu 1 va cho phep chi so AM (tinh nguoc tu cuoi). Bo qua
|
||||
// chi so am se lam mot so mesh mat mat -- xu ly ca hai.
|
||||
bool ReadObjTriangles(const std::string& path, std::vector<Tri>* out) {
|
||||
std::ifstream f(path);
|
||||
if (!f) return false;
|
||||
std::vector<std::array<double, 3>> v;
|
||||
std::string line;
|
||||
while (std::getline(f, line)) {
|
||||
if (line.size() < 2) continue;
|
||||
if (line[0] == 'v' && line[1] == ' ') {
|
||||
std::istringstream in(line.substr(2));
|
||||
std::array<double, 3> p{0, 0, 0};
|
||||
in >> p[0] >> p[1] >> p[2];
|
||||
v.push_back(p);
|
||||
} else if (line[0] == 'f' && line[1] == ' ') {
|
||||
std::istringstream in(line.substr(2));
|
||||
std::string tok;
|
||||
std::vector<int> idx;
|
||||
while (in >> tok) {
|
||||
// "a", "a/b", "a//c", "a/b/c" -- chi lay phan truoc dau '/'.
|
||||
const size_t slash = tok.find('/');
|
||||
const std::string num = slash == std::string::npos ? tok : tok.substr(0, slash);
|
||||
if (num.empty()) continue;
|
||||
int i = std::atoi(num.c_str());
|
||||
if (i > 0) i -= 1;
|
||||
else if (i < 0) i = static_cast<int>(v.size()) + i;
|
||||
else continue;
|
||||
if (i >= 0 && i < static_cast<int>(v.size())) idx.push_back(i);
|
||||
}
|
||||
// Quat va n-giac: chia thanh quat tam giac.
|
||||
for (size_t k = 2; k < idx.size(); ++k) {
|
||||
Tri t;
|
||||
const int a = idx[0], b = idx[k - 1], c = idx[k];
|
||||
t.x[0] = v[a][0]; t.y[0] = v[a][1]; t.z[0] = v[a][2];
|
||||
t.x[1] = v[b][0]; t.y[1] = v[b][1]; t.z[1] = v[b][2];
|
||||
t.x[2] = v[c][0]; t.y[2] = v[c][1]; t.z[2] = v[c][2];
|
||||
out->push_back(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
|
||||
const WorldRasterOptions& opt,
|
||||
OccupancyGrid* out) {
|
||||
if (!(opt.resolution > 0.0)) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"resolution phai duong");
|
||||
}
|
||||
|
||||
|
||||
// --- Luot 1: bao loi ---
|
||||
double minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;
|
||||
size_t n_tri = 0, n_mesh = 0;
|
||||
|
||||
struct Loaded { const WorldModel* m; std::vector<Tri> tris; };
|
||||
std::vector<Loaded> loaded;
|
||||
loaded.reserve(world.models.size());
|
||||
|
||||
for (const WorldModel& m : world.models) {
|
||||
if (m.collision_obj.empty()) continue;
|
||||
Loaded L;
|
||||
L.m = &m;
|
||||
// Chon bo doc theo DUOI FILE: bo model nay tron ca .obj lan .dae, va moi
|
||||
// dinh dang mang quy uoc rieng (xem ghi chu o ReadDaeTriangles).
|
||||
const std::string& cp = m.collision_obj;
|
||||
const bool ok = IsDae(cp) ? ReadDaeTriangles(cp, &L.tris)
|
||||
: ReadObjTriangles(cp, &L.tris);
|
||||
if (!ok) {
|
||||
VSLAM_WARN("world: khong doc duoc mesh " << cp << " cua model "
|
||||
<< m.model_name << " -- vat the nay VANG MAT khoi luoi");
|
||||
continue;
|
||||
}
|
||||
if (L.tris.empty()) continue;
|
||||
n_mesh++;
|
||||
n_tri += L.tris.size();
|
||||
|
||||
const double cy = std::cos(m.yaw), sny = std::sin(m.yaw);
|
||||
for (Tri& t : L.tris) {
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
// Ti le TRUOC khi quay va tinh tien -- `<scale>` la cua mesh, khong
|
||||
// phai cua the gioi.
|
||||
t.x[k] *= m.sx; t.y[k] *= m.sy; t.z[k] *= m.sz;
|
||||
// Bo doc da tra ve he ROS (Z-len, met) roi -- KHONG doi truc them o
|
||||
// day. Quy uoc nam trong TUNG FILE (.obj Z-up met, .dae Y-up cm), va
|
||||
// ap them mot phep doi chung se lam hong dung mot nua so mesh.
|
||||
const double wx = t.x[k], wy = t.y[k], wz = t.z[k];
|
||||
// Chi xet yaw: roll/pitch cua do dac dat tren san gan nhu luon 0, va
|
||||
// xoay day du se lam ham nay dai gap doi ma khong doi ket qua.
|
||||
const double rx = wx * cy - wy * sny;
|
||||
const double ry = wx * sny + wy * cy;
|
||||
t.x[k] = rx + m.x;
|
||||
t.y[k] = ry + m.y;
|
||||
t.z[k] = wz + m.z;
|
||||
minx = std::min(minx, t.x[k]); maxx = std::max(maxx, t.x[k]);
|
||||
miny = std::min(miny, t.y[k]); maxy = std::max(maxy, t.y[k]);
|
||||
}
|
||||
}
|
||||
loaded.push_back(std::move(L));
|
||||
}
|
||||
|
||||
if (loaded.empty()) {
|
||||
return StatusResponse::Error(StatusCode::kNotFound,
|
||||
"khong doc duoc mesh va cham nao tu world");
|
||||
}
|
||||
|
||||
minx -= opt.pad; maxx += opt.pad;
|
||||
miny -= opt.pad; maxy += opt.pad;
|
||||
|
||||
const double res = opt.resolution;
|
||||
const uint32_t w = static_cast<uint32_t>(std::ceil((maxx - minx) / res));
|
||||
const uint32_t h = static_cast<uint32_t>(std::ceil((maxy - miny) / res));
|
||||
|
||||
out->resolution = static_cast<float>(res);
|
||||
out->width = w;
|
||||
out->height = h;
|
||||
out->origin = Pose{};
|
||||
out->origin.position.x = minx;
|
||||
out->origin.position.y = miny;
|
||||
// Bat dau la TRONG, khong phai chua biet: the gioi nay do ta dung nen moi
|
||||
// o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM.
|
||||
out->data.assign(static_cast<size_t>(w) * h, 0);
|
||||
|
||||
// --- Luot 2: to tam giac trong dai do cao ---
|
||||
size_t n_used = 0;
|
||||
for (const Loaded& L : loaded) {
|
||||
for (const Tri& t : L.tris) {
|
||||
// Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua:
|
||||
// mesh day dac nen mot tam giac bien bi bo van con hang xom phu.
|
||||
const double tz0 = std::min({t.z[0], t.z[1], t.z[2]});
|
||||
const double tz1 = std::max({t.z[0], t.z[1], t.z[2]});
|
||||
if (tz1 < opt.z_min || tz0 > opt.z_max) continue;
|
||||
n_used++;
|
||||
|
||||
// Bao loi cua tam giac, roi kiem tung o bang toa do trong tam.
|
||||
const double bx0 = std::min({t.x[0], t.x[1], t.x[2]});
|
||||
const double bx1 = std::max({t.x[0], t.x[1], t.x[2]});
|
||||
const double by0 = std::min({t.y[0], t.y[1], t.y[2]});
|
||||
const double by1 = std::max({t.y[0], t.y[1], t.y[2]});
|
||||
|
||||
const int cx0 = std::max(0, static_cast<int>((bx0 - minx) / res));
|
||||
const int cx1 = std::min(static_cast<int>(w) - 1,
|
||||
static_cast<int>((bx1 - minx) / res));
|
||||
const int cy0 = std::max(0, static_cast<int>((by0 - miny) / res));
|
||||
const int cy1 = std::min(static_cast<int>(h) - 1,
|
||||
static_cast<int>((by1 - miny) / res));
|
||||
|
||||
const double ax = t.x[0], ay = t.y[0];
|
||||
const double bx = t.x[1], by = t.y[1];
|
||||
const double cx = t.x[2], cy = t.y[2];
|
||||
const double den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
|
||||
const bool degenerate = std::fabs(den) < 1e-12;
|
||||
|
||||
for (int gy = cy0; gy <= cy1; ++gy) {
|
||||
for (int gx = cx0; gx <= cx1; ++gx) {
|
||||
const double px = minx + (gx + 0.5) * res;
|
||||
const double py = miny + (gy + 0.5) * res;
|
||||
bool inside;
|
||||
if (degenerate) {
|
||||
// Tam giac suy bien (canh rat mong) van phai to, neu khong mot
|
||||
// buc tuong mong se thung lo.
|
||||
inside = true;
|
||||
} else {
|
||||
const double l1 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / den;
|
||||
const double l2 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / den;
|
||||
const double l3 = 1.0 - l1 - l2;
|
||||
inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9;
|
||||
}
|
||||
if (inside) {
|
||||
out->data[static_cast<size_t>(gy) * w + gx] = 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t occ = 0;
|
||||
for (int8_t v : out->data) if (v >= 50) occ++;
|
||||
VSLAM_INFO("world -> luoi: " << w << "x" << h << " @ " << res << " m/o, goc ("
|
||||
<< minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri
|
||||
<< " tam giac (" << n_used << " trong dai z ["
|
||||
<< opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem");
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
|
||||
WorldMeshes* out) {
|
||||
if (out == nullptr) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
|
||||
}
|
||||
out->geoms.clear();
|
||||
out->instances.clear();
|
||||
|
||||
std::map<std::string, uint32_t> by_model;
|
||||
|
||||
for (const WorldModel& m : world.models) {
|
||||
const std::string& path = visual && !m.visual_obj.empty() ? m.visual_obj
|
||||
: m.collision_obj;
|
||||
if (path.empty()) continue;
|
||||
|
||||
// Gop theo TEN MODEL, khong theo duong dan mesh: `<scale>` den tu
|
||||
// model.sdf nen hai model dung chung mot file mesh van co the khac ti le.
|
||||
uint32_t gid = 0;
|
||||
auto it = by_model.find(m.model_name);
|
||||
if (it != by_model.end()) {
|
||||
gid = it->second;
|
||||
} else {
|
||||
std::vector<Tri> tris;
|
||||
const bool ok = IsDae(path) ? ReadDaeTriangles(path, &tris)
|
||||
: ReadObjTriangles(path, &tris);
|
||||
if (!ok || tris.empty()) {
|
||||
VSLAM_WARN("world: khong doc duoc mesh " << path << " cua model "
|
||||
<< m.model_name << " -- vat the nay VANG MAT khoi khung 3D");
|
||||
continue;
|
||||
}
|
||||
|
||||
WorldMeshGeom g;
|
||||
g.model_name = m.model_name;
|
||||
g.tri.reserve(tris.size() * 9);
|
||||
for (const Tri& t : tris) {
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
g.tri.push_back(static_cast<float>(t.x[k] * m.sx));
|
||||
g.tri.push_back(static_cast<float>(t.y[k] * m.sy));
|
||||
g.tri.push_back(static_cast<float>(t.z[k] * m.sz));
|
||||
}
|
||||
}
|
||||
gid = static_cast<uint32_t>(out->geoms.size());
|
||||
by_model[m.model_name] = gid;
|
||||
out->geoms.push_back(std::move(g));
|
||||
}
|
||||
|
||||
WorldMeshInstance inst;
|
||||
inst.geom = gid;
|
||||
inst.x = static_cast<float>(m.x);
|
||||
inst.y = static_cast<float>(m.y);
|
||||
inst.z = static_cast<float>(m.z);
|
||||
inst.yaw = static_cast<float>(m.yaw);
|
||||
out->instances.push_back(inst);
|
||||
}
|
||||
|
||||
if (out->geoms.empty()) {
|
||||
return StatusResponse::Error(StatusCode::kNotFound,
|
||||
"khong doc duoc mesh nao tu world");
|
||||
}
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
size_t ApplyModelColors(const std::string& json_path, WorldMeshes* io) {
|
||||
if (io == nullptr) return 0;
|
||||
// JSON la tap con cua YAML, nen yaml-cpp doc duoc thang -- khong keo them
|
||||
// mot bo doc JSON vao `vslam_sim` chi vi mot bang 69 dong.
|
||||
YAML::Node root;
|
||||
try {
|
||||
root = YAML::LoadFile(json_path);
|
||||
} catch (const std::exception& e) {
|
||||
VSLAM_WARN("world: khong doc duoc bang mau " << json_path << " (" << e.what()
|
||||
<< ") -- moi vat the se mang mau mac dinh");
|
||||
return 0;
|
||||
}
|
||||
size_t n = 0;
|
||||
for (WorldMeshGeom& g : io->geoms) {
|
||||
const YAML::Node c = root[g.model_name];
|
||||
if (!c || !c.IsSequence() || c.size() < 3) continue;
|
||||
g.r = static_cast<uint8_t>(c[0].as<int>());
|
||||
g.g = static_cast<uint8_t>(c[1].as<int>());
|
||||
g.b = static_cast<uint8_t>(c[2].as<int>());
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
namespace {
|
||||
void PutU32(std::string* o, uint32_t v) {
|
||||
// Little-endian tuong minh: trinh duyet doc bang DataView voi littleEndian
|
||||
// = true, nen khong duoc phu thuoc endianness cua may chu.
|
||||
o->push_back(static_cast<char>(v & 0xFF));
|
||||
o->push_back(static_cast<char>((v >> 8) & 0xFF));
|
||||
o->push_back(static_cast<char>((v >> 16) & 0xFF));
|
||||
o->push_back(static_cast<char>((v >> 24) & 0xFF));
|
||||
}
|
||||
void PutF32(std::string* o, float f) {
|
||||
uint32_t u = 0;
|
||||
std::memcpy(&u, &f, 4);
|
||||
PutU32(o, u);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void EncodeWorldMeshes(const WorldMeshes& in, std::string* out) {
|
||||
if (out == nullptr) return;
|
||||
out->clear(); // ⚠️ ghi de, KHONG noi them -- xem EncodeScanPayload
|
||||
out->append("VSLW");
|
||||
PutU32(out, 1);
|
||||
PutU32(out, static_cast<uint32_t>(in.geoms.size()));
|
||||
PutU32(out, static_cast<uint32_t>(in.instances.size()));
|
||||
for (const WorldMeshGeom& g : in.geoms) {
|
||||
PutU32(out, static_cast<uint32_t>(g.model_name.size()));
|
||||
out->append(g.model_name);
|
||||
out->push_back(static_cast<char>(g.r));
|
||||
out->push_back(static_cast<char>(g.g));
|
||||
out->push_back(static_cast<char>(g.b));
|
||||
PutU32(out, static_cast<uint32_t>(g.tri.size() / 9));
|
||||
for (float v : g.tri) PutF32(out, v);
|
||||
}
|
||||
for (const WorldMeshInstance& i : in.instances) {
|
||||
PutU32(out, i.geom);
|
||||
PutF32(out, i.x); PutF32(out, i.y); PutF32(out, i.z); PutF32(out, i.yaw);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
248
libs/vslam_sim/src/occupancy_map_io.cc
Normal file
248
libs/vslam_sim/src/occupancy_map_io.cc
Normal file
@@ -0,0 +1,248 @@
|
||||
#include "vslam/occupancy_map_io.h"
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/log.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
std::string DirName(const std::string& path) {
|
||||
const size_t slash = path.find_last_of('/');
|
||||
return slash == std::string::npos ? std::string(".") : path.substr(0, slash);
|
||||
}
|
||||
|
||||
// Doc PGM P5 (nhi phan 8 bit). Bo qua comment bat dau bang '#'.
|
||||
bool ReadPgm(const std::string& path, uint32_t* w, uint32_t* h,
|
||||
std::vector<uint8_t>* pixels, std::string* err) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
if (!f) {
|
||||
*err = "khong mo duoc " + path;
|
||||
return false;
|
||||
}
|
||||
|
||||
auto next_token = [&f]() -> std::string {
|
||||
std::string tok;
|
||||
while (f) {
|
||||
const int c = f.get();
|
||||
if (c == EOF) break;
|
||||
if (c == '#') {
|
||||
while (f && f.get() != '\n') {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (std::isspace(c)) {
|
||||
if (!tok.empty()) break;
|
||||
continue;
|
||||
}
|
||||
tok.push_back(static_cast<char>(c));
|
||||
}
|
||||
return tok;
|
||||
};
|
||||
|
||||
if (next_token() != "P5") {
|
||||
*err = path + ": chi ho tro PGM P5 (nhi phan)";
|
||||
return false;
|
||||
}
|
||||
*w = static_cast<uint32_t>(std::stoul(next_token()));
|
||||
*h = static_cast<uint32_t>(std::stoul(next_token()));
|
||||
const unsigned long maxval = std::stoul(next_token());
|
||||
if (maxval > 255) {
|
||||
*err = path + ": chi ho tro PGM 8 bit";
|
||||
return false;
|
||||
}
|
||||
|
||||
pixels->resize(static_cast<size_t>(*w) * (*h));
|
||||
f.read(reinterpret_cast<char*>(pixels->data()),
|
||||
static_cast<std::streamsize>(pixels->size()));
|
||||
if (static_cast<size_t>(f.gcount()) != pixels->size()) {
|
||||
*err = path + ": file anh cut";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out) {
|
||||
// Kiem TON TAI truoc khi giao cho yaml-cpp.
|
||||
//
|
||||
// `YAML::LoadFile` tren mot file khong co nem `BadFile`, va `what()` cua no
|
||||
// dung la chuoi "bad file" -- khong noi file nao, khong phan biet thieu voi
|
||||
// hong, khong goi y gi. Nguoi dung go sai duong dan chi nhan duoc
|
||||
// "hospital.yaml: bad file" roi dung do.
|
||||
{
|
||||
std::ifstream probe(yaml_path);
|
||||
if (!probe) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kNotFound,
|
||||
"khong mo duoc ban do: " + yaml_path +
|
||||
" (khong ton tai hoac khong co quyen doc). Xuat mot ban do tu DB "
|
||||
"RTAB-Map bang: vslam_slam_bench --db X.db --localize "
|
||||
"--export-only --export-map out.pgm");
|
||||
}
|
||||
}
|
||||
|
||||
YAML::Node node;
|
||||
try {
|
||||
node = YAML::LoadFile(yaml_path);
|
||||
} catch (const YAML::Exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
yaml_path + ": YAML hong: " + e.what());
|
||||
}
|
||||
|
||||
if (!node["image"] || !node["resolution"]) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
yaml_path + ": thieu 'image' hoac 'resolution'");
|
||||
}
|
||||
|
||||
std::string image = node["image"].as<std::string>();
|
||||
if (!image.empty() && image[0] != '/') image = DirName(yaml_path) + "/" + image;
|
||||
out->image_path = image;
|
||||
|
||||
const double resolution = node["resolution"].as<double>();
|
||||
double ox = 0.0, oy = 0.0;
|
||||
if (node["origin"] && node["origin"].size() >= 2) {
|
||||
ox = node["origin"][0].as<double>();
|
||||
oy = node["origin"][1].as<double>();
|
||||
}
|
||||
const bool negate = node["negate"] ? node["negate"].as<int>() != 0 : false;
|
||||
out->occupied_thresh =
|
||||
node["occupied_thresh"] ? node["occupied_thresh"].as<double>() : 0.65;
|
||||
out->free_thresh = node["free_thresh"] ? node["free_thresh"].as<double>() : 0.196;
|
||||
|
||||
uint32_t w = 0, h = 0;
|
||||
std::vector<uint8_t> pixels;
|
||||
std::string err;
|
||||
if (!ReadPgm(image, &w, &h, &pixels, &err)) {
|
||||
return StatusResponse::Error(StatusCode::kNotFound, err);
|
||||
}
|
||||
|
||||
out->grid.width = w;
|
||||
out->grid.height = h;
|
||||
out->grid.resolution = static_cast<float>(resolution);
|
||||
out->grid.origin.position.x = ox;
|
||||
out->grid.origin.position.y = oy;
|
||||
out->grid.data.resize(static_cast<size_t>(w) * h);
|
||||
|
||||
for (uint32_t y = 0; y < h; ++y) {
|
||||
for (uint32_t x = 0; x < w; ++x) {
|
||||
// PGM hang 0 o TREN CUNG; occupancy grid hang 0 o DUOI CUNG (goc o
|
||||
// origin). Quen lat truc y la loi kinh dien khi doc map, va hau qua la
|
||||
// ban do bi lat nguoc ma van "trong nhu that".
|
||||
const uint8_t px = pixels[static_cast<size_t>(h - 1 - y) * w + x];
|
||||
double occ = (255.0 - static_cast<double>(px)) / 255.0;
|
||||
if (negate) occ = 1.0 - occ;
|
||||
|
||||
int8_t v;
|
||||
if (occ > out->occupied_thresh) {
|
||||
v = 100;
|
||||
} else if (occ < out->free_thresh) {
|
||||
v = 0;
|
||||
} else {
|
||||
v = -1; // chua biet
|
||||
}
|
||||
out->grid.data[static_cast<size_t>(y) * w + x] = v;
|
||||
}
|
||||
}
|
||||
|
||||
VSLAM_INFO("map: nap " << image << " -- " << w << "x" << h << " @ "
|
||||
<< resolution << " m/o, goc (" << ox << ", " << oy << ")");
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
|
||||
const std::string& yaml_path) {
|
||||
std::string base = yaml_path;
|
||||
const size_t dot = base.find_last_of('.');
|
||||
if (dot != std::string::npos) base = base.substr(0, dot);
|
||||
const std::string pgm_path = base + ".pgm";
|
||||
|
||||
std::ofstream img(pgm_path, std::ios::binary);
|
||||
if (!img) {
|
||||
return StatusResponse::Error(StatusCode::kUnavailable,
|
||||
"khong ghi duoc " + pgm_path);
|
||||
}
|
||||
img << "P5\n# sinh boi vslam\n" << grid.width << " " << grid.height << "\n255\n";
|
||||
for (uint32_t y = 0; y < grid.height; ++y) {
|
||||
for (uint32_t x = 0; x < grid.width; ++x) {
|
||||
const int8_t v = grid.data[static_cast<size_t>(grid.height - 1 - y) * grid.width + x];
|
||||
const uint8_t px = v < 0 ? 205 : (v >= 50 ? 0 : 254);
|
||||
img.put(static_cast<char>(px));
|
||||
}
|
||||
}
|
||||
img.close();
|
||||
|
||||
std::ofstream y(yaml_path);
|
||||
if (!y) {
|
||||
return StatusResponse::Error(StatusCode::kUnavailable,
|
||||
"khong ghi duoc " + yaml_path);
|
||||
}
|
||||
const size_t slash = pgm_path.find_last_of('/');
|
||||
y << "image: " << (slash == std::string::npos ? pgm_path : pgm_path.substr(slash + 1))
|
||||
<< "\nresolution: " << grid.resolution << "\norigin: [" << grid.origin.position.x
|
||||
<< ", " << grid.origin.position.y << ", 0.0]\nnegate: 0\n"
|
||||
<< "occupied_thresh: 0.65\nfree_thresh: 0.196\n";
|
||||
|
||||
VSLAM_INFO("map: da ghi " << yaml_path << " va " << pgm_path);
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
OccupancyGrid MakeSyntheticWorld(uint32_t w, uint32_t h, float res) {
|
||||
OccupancyGrid m;
|
||||
m.width = w;
|
||||
m.height = h;
|
||||
m.resolution = res;
|
||||
m.origin.position.x = -static_cast<double>(w) * res / 2.0;
|
||||
m.origin.position.y = -static_cast<double>(h) * res / 2.0;
|
||||
m.data.assign(static_cast<size_t>(w) * h, -1);
|
||||
|
||||
auto put = [&](uint32_t x, uint32_t y, int8_t v) {
|
||||
if (x < w && y < h) m.data[static_cast<size_t>(y) * w + x] = v;
|
||||
};
|
||||
|
||||
const uint32_t cy = h / 2;
|
||||
const uint32_t half = std::max<uint32_t>(6, h / 24);
|
||||
|
||||
for (uint32_t x = w / 10; x < w - w / 10; ++x) {
|
||||
for (uint32_t y = cy - half; y <= cy + half; ++y) put(x, y, 0);
|
||||
put(x, cy - half - 1, 100);
|
||||
put(x, cy + half + 1, 100);
|
||||
}
|
||||
// Bit hai dau hanh lang, neu khong thi raycast chay ra vo tan.
|
||||
for (uint32_t y = cy - half - 1; y <= cy + half + 1; ++y) {
|
||||
put(w / 10, y, 100);
|
||||
put(w - w / 10 - 1, y, 100);
|
||||
}
|
||||
|
||||
const uint32_t room = half * 3;
|
||||
for (uint32_t rx = w / 6; rx + room < w - w / 10; rx += room + room / 2) {
|
||||
for (int side = 0; side < 2; ++side) {
|
||||
const uint32_t y0 = side == 0 ? cy + half + 2 : cy - half - 2 - room;
|
||||
for (uint32_t x = rx; x < rx + room; ++x) {
|
||||
for (uint32_t y = y0; y < y0 + room; ++y) put(x, y, 0);
|
||||
}
|
||||
for (uint32_t x = rx - 1; x <= rx + room; ++x) {
|
||||
put(x, y0 - 1, 100);
|
||||
put(x, y0 + room, 100);
|
||||
}
|
||||
for (uint32_t y = y0 - 1; y <= y0 + room; ++y) {
|
||||
put(rx - 1, y, 100);
|
||||
put(rx + room, y, 100);
|
||||
}
|
||||
const uint32_t door = rx + room / 2;
|
||||
for (uint32_t x = door - 2; x <= door + 2; ++x) {
|
||||
put(x, side == 0 ? y0 - 1 : y0 + room, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
1186
libs/vslam_sim/src/sim_source.cc
Normal file
1186
libs/vslam_sim/src/sim_source.cc
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user