From 213b5f23a629593a65d0464e7798637dd2174f8e Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Sat, 3 Oct 2026 19:37:29 +0700 Subject: [PATCH] tools: vslam_record kich ban doc (slope_loop, slope_lane5..30) lai theo waypoint khong qua FSM, --gl, --cam-decimate, nhieu IMU vao header; vslam_vsr_export doi .vsr sang dataset DM-VIO (mau IMU dung gio anh, T_cam_imu tu robot.yaml, su that IMU/camera/base, ha tan so/lech gio/nhieu IMU luc xuat) --- tools/CMakeLists.txt | 15 ++ tools/vslam_record.cc | 234 ++++++++++++++++++++++- tools/vslam_vsr_export.cc | 385 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 628 insertions(+), 6 deletions(-) create mode 100644 tools/vslam_vsr_export.cc diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index fbf93ce..58c64f0 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -73,6 +73,21 @@ endif() if(VSLAM_BUILD_SIM AND VSLAM_BUILD_DRIVERS) add_executable(vslam_record vslam_record.cc) target_link_libraries(vslam_record PRIVATE vslam_sim vslam_drivers vslam_common) + # --gl: ve camera bang GPU khi co lib tuy chon. + if(TARGET vslam_sim_gl) + target_link_libraries(vslam_record PRIVATE vslam_sim_gl) + target_compile_definitions(vslam_record PRIVATE VSLAM_HAVE_SIM_GL=1) + endif() + + # vslam_vsr_export: .vsr (anh IR + IMU + su that) -> thu muc dataset cho + # DM-VIO. Lam xau IMU (ha tan so, lech gio, nhieu) o buoc nay, khong ghi lai. + # Can OpenCV de ghi PNG; build khong co OpenCV thi bo qua tool nay. + find_package(OpenCV QUIET COMPONENTS core imgcodecs) + if(OpenCV_FOUND) + add_executable(vslam_vsr_export vslam_vsr_export.cc) + target_include_directories(vslam_vsr_export SYSTEM PRIVATE ${OpenCV_INCLUDE_DIRS}) + target_link_libraries(vslam_vsr_export PRIVATE vslam_drivers vslam_common ${OpenCV_LIBS}) + endif() endif() # vslam_replay: phat lai .vsr qua TOAN BO duong ong roi xuat JSON phang. diff --git a/tools/vslam_record.cc b/tools/vslam_record.cc index c00527e..268419d 100644 --- a/tools/vslam_record.cc +++ b/tools/vslam_record.cc @@ -13,10 +13,15 @@ // vat can cua cliff_detect. #include +#include #include #include +#include #include +#include #include +#include +#include #include #include "vslam/driver_interfaces.h" @@ -24,6 +29,9 @@ #include "vslam/record_io.h" #include "vslam/robot_model.h" #include "vslam/sim_source.h" +#ifdef VSLAM_HAVE_SIM_GL +#include "vslam/sim_gl_renderer.h" +#endif namespace { @@ -53,8 +61,125 @@ struct Scenario { double start_x = 0.0, start_y = 0.0, start_yaw = 0.0; }; +// --- Kich ban DOC --- +// Chay trong file .world (tuong doi VSLAM_RESOURCE_DIR), lai theo WAYPOINT +// bang bo bam duong -- KHONG qua lop an toan, nen doc 30 do van co du lieu. +// Luon dung hinh hoc robot THAT, luon ghi su that 6-DoF, anh IR neu --gl. +// KHONG nam trong `--scenario all`: bo hoi quy chi dung kich ban phang. +// +// Tach rieng khoi `Scenario` (tra theo ten): them truong vao `Scenario` lam +// moi dong khoi tao cu thieu truong va -Wextra canh bao. +struct SlopeInfo { + const char* world = nullptr; + std::vector> waypoints; + double cruise = 0.30; // m/s doc mat san +}; + +std::vector>& SlopeTable() { + static std::vector> t; + return t; +} + +const SlopeInfo* FindSlope(const char* name) { + for (const auto& e : SlopeTable()) { + if (e.first == name) return &e.second; + } + return nullptr; +} + +// Kich ban DOC trong worlds/slope_test.world (tools/gen_slope_world.py): tam +// lan x = 1.2 / 3.8 / 6.4 / 9.0 / 11.6 cho doc 5 / 10 / 15 / 20 / 30 do, chan +// doc y = 8, san cao 1.5 m tu y = 25.5. +void AddSlopeScenarios(std::vector* v) { + const char* kWorld = "worlds/slope_test.world"; + SlopeTable().clear(); + { + Scenario s{}; + s.name = "slope_loop"; + s.what = "doc: len lan 15 do, qua san tren, xuong lan 20 do, ve cho cu"; + s.camera = true; + s.camera_hz = 20.0; + s.start_x = 6.4; + s.start_y = 4.0; + s.start_yaw = M_PI / 2.0; + v->push_back(s); + SlopeInfo si; + si.world = kWorld; + si.waypoints = {{6.4, 7.0}, {6.4, 24.5}, {6.4, 27.6}, {9.0, 27.6}, + {9.0, 24.5}, {9.0, 6.6}, {6.4, 6.0}, {6.4, 4.0}}; + SlopeTable().emplace_back(s.name, si); + } + // Quay dau o y = 27.5 (san tren, 2 m qua dinh lan): doc 5 do dai 17.15 m, + // dinh o y = 25.15, nen quay som hon (24.5) la con tren doc -- thieu doan + // dinh doc, cho kho nhat cua VO. San tren trong tu y 25.5 toi cot o 29.3. + const struct { const char* name; const char* what; double x; } lanes[] = { + {"slope_lane5", "doc 5 do: len het lan, qua dinh, quay xuong", 1.2}, + {"slope_lane10", "doc 10 do: len het lan, qua dinh, quay xuong", 3.8}, + {"slope_lane15", "doc 15 do: len het lan, qua dinh, quay xuong", 6.4}, + {"slope_lane20", "doc 20 do: len het lan, qua dinh, quay xuong", 9.0}, + {"slope_lane30", "doc 30 do: len het lan, qua dinh, quay xuong", 11.6}, + }; + for (const auto& l : lanes) { + Scenario s{}; + s.name = l.name; + s.what = l.what; + s.camera = true; + s.camera_hz = 20.0; + s.start_x = l.x; + s.start_y = 5.0; + s.start_yaw = M_PI / 2.0; + v->push_back(s); + SlopeInfo si; + si.world = kWorld; + si.waypoints = {{l.x, 27.5}, {l.x, 5.5}}; + SlopeTable().emplace_back(s.name, si); + } +} + +// Bam waypoint bang SU THAT (nhu nguoi lai nhin thay robot): quay ve phia +// diem ke, tien khi da gan dung huong. Lenh phat lai moi lat 50 ms (watchdog +// cua base), `after_slice` chay sau moi lat (ham hang doi ghi). +bool DriveWaypoints(vslam::SimSource* sim, const std::vector>& wps, + double cruise, const std::function& after_slice, + double* sim_s) { + constexpr double kSlice = 0.05; + constexpr double kMaxS = 900.0; + size_t k = 0; + double t = 0.0; + while (k < wps.size() && t < kMaxS) { + const vslam::SimPose3 p = sim->ground_truth_3d(); + const double dx = wps[k].first - p.x, dy = wps[k].second - p.y; + if (std::hypot(dx, dy) < 0.25) { + ++k; + continue; + } + double err = std::atan2(dy, dx) - p.yaw; + err = std::atan2(std::sin(err), std::cos(err)); + const double wz = std::max(-0.6, std::min(0.6, 1.5 * err)); + const double vx = std::fabs(err) < 0.2 ? cruise : (std::fabs(err) < 0.6 ? 0.3 * cruise : 0.0); + sim->base()->SetVelocity(vx, wz); + sim->RunFor(kSlice); + t += kSlice; + after_slice(); + } + // Dung han nua giay: khung cuoi co robot dung yen. + for (int i = 0; i < 10; ++i) { + sim->base()->SetVelocity(0.0, 0.0); + sim->RunFor(kSlice); + t += kSlice; + after_slice(); + } + *sim_s = t; + return k == wps.size(); +} + +std::string ResourceDir() { + const char* e = std::getenv("VSLAM_RESOURCE_DIR"); + return e != nullptr && *e != '\0' ? std::string(e) : std::string("resources"); +} + std::vector Scenarios() { - return { + std::vector v = { {"straight", "tich phan odometry, EKF, ScanSanitizer", {{0.35, 0.0, 8.0}, {0.0, 0.0, 1.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0}, @@ -131,6 +256,8 @@ std::vector Scenarios() { {"spin", "cong vat can cua cliff_detect trong hanh lang hep", {{0.0, 1.0, 7.0}}, 0.0, 0.0, false, -0.40f, true, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0}, }; + AddSlopeScenarios(&v); + return v; } } // namespace @@ -142,6 +269,8 @@ int main(int argc, char** argv) { // (tools/regress.sh) so voi ban ghi dung bang cach do. std::string robot_yaml; bool write_gt = false; + bool use_gl = false; // ve camera bang GPU (anh IR) -- chi kich ban doc + uint32_t cam_decimate = 2; // anh 640x480 / N, nhu crop_decimate cua robot for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -151,6 +280,8 @@ int main(int argc, char** argv) { else if (a == "--list") list = true; else if (a == "--robot") robot_yaml = next(); else if (a == "--gt") write_gt = true; + else if (a == "--gl") use_gl = true; + else if (a == "--cam-decimate") cam_decimate = static_cast(std::atoi(next().c_str())); else if (a == "--help") { std::printf("cach dung: %s --scenario TEN --out-dir D [--robot robot.yaml] [--gt]\n" " %s --list\n" @@ -158,7 +289,12 @@ int main(int argc, char** argv) { " --robot F hinh hoc robot THAT (banh, LiDAR, camera, IMU) tu robot.yaml\n" " thay vi so mac dinh cu cua SimConfig\n" " --gt ghi them tu the THAT 6-DoF (stream ground_truth) moi\n" - " buoc vat ly, de cham diem offline\n", + " buoc vat ly, de cham diem offline\n" + " kich ban doc (slope_*, hoac slope_all): chay worlds/slope_test.world,\n" + " hinh hoc robot that, luon ghi su that. Can\n" + " GAZEBO_MODEL_PATH=$PWD/resources/models.\n" + " --gl ve camera bang GPU: ghi them anh IR (build VSLAM_SIM_WITH_GL)\n" + " --cam-decimate N anh 640x480 / N (mac dinh 2 = 320x240 nhu robot)\n", argv[0], argv[0], argv[0]); return 0; } @@ -180,9 +316,38 @@ int main(int argc, char** argv) { } } + // Kich ban doc LUON dung hinh hoc robot that: --robot, hoac robot.yaml cua + // VSLAM_CONFIG_DIR / configuration_files. + vslam::RobotModel slope_robot; + bool slope_robot_ok = false; + auto load_slope_robot = [&]() -> bool { + if (slope_robot_ok) return true; + std::string p = robot_yaml; + if (p.empty()) { + const char* cd = std::getenv("VSLAM_CONFIG_DIR"); + p = (cd != nullptr && *cd != '\0' ? std::string(cd) : std::string("configuration_files")) + + "/robot.yaml"; + } + const vslam::StatusResponse rs = slope_robot.LoadFile(p); + if (!rs.ok()) { + std::fprintf(stderr, "kich ban doc can robot.yaml: %s: %s\n", p.c_str(), rs.message.c_str()); + return false; + } + slope_robot_ok = true; + return true; + }; + int written = 0; for (const Scenario& s : all) { - if (name != "all" && name != s.name) continue; + const SlopeInfo* si = FindSlope(s.name); + const bool slope = si != nullptr; + // `all` = bo hoi quy (chi kich ban phang). `slope_all` = moi kich ban doc. + const bool pick = (name == "all" && !slope) || (name == "slope_all" && slope) || name == s.name; + if (!pick) continue; + if (use_gl && !slope) { + std::fprintf(stderr, "%s: --gl chi cho kich ban doc (can mesh cua world)\n", s.name); + return 2; + } vslam::SimConfig cfg; cfg.seed = 1234; // co dinh: cung kich ban => cung file @@ -198,12 +363,36 @@ int main(int argc, char** argv) { cfg.lidar_cut_for = s.lidar_cut_for; cfg.camera_rate_hz = s.camera_hz; if (!robot_yaml.empty()) vslam::SimConfigFromRobot(robot, &cfg); + if (slope) { + if (!load_slope_robot()) return 1; + vslam::SimConfigFromRobot(slope_robot, &cfg); + cfg.world_path = ResourceDir() + "/" + si->world; + // Nhanh nhat co the; ham theo hang doi ghi ben duoi nen khong rot chunk. + cfg.speed = 0.0; + cfg.depth_decimate = std::max(1, cam_decimate); + // Noi suy D410 THAT o 640x480: fx = 595.914 -> HFOV 56.5 do (mac dinh sim 69). + cfg.depth_hfov_rad = 2.0 * std::atan(320.0 / 595.914); + } vslam::SimSource sim(cfg); if (!sim.Open().ok()) { std::fprintf(stderr, "%s: sim khong mo duoc\n", s.name); return 1; } + if (use_gl) { +#ifdef VSLAM_HAVE_SIM_GL + std::string gerr; + auto r = vslam::CreateGlCameraRenderer(sim.world(), vslam::DefaultGlRendererConfig(), &gerr); + if (!r) { + std::fprintf(stderr, "%s: --gl: %s\n", s.name, gerr.c_str()); + return 1; + } + sim.SetCameraRenderer(r); +#else + std::fprintf(stderr, "--gl: tool build KHONG co -DVSLAM_SIM_WITH_GL=ON\n"); + return 2; +#endif + } if (s.glass_at != 0.0) { // Kinh phai la o BI CHIEM: no la vat can THAT, chi la vat can ma // LiDAR va depth khong thay. @@ -225,12 +414,24 @@ int main(int argc, char** argv) { } const std::string path = out_dir + "/" + s.name + ".vsr"; + // Kich ban doc: ghi nhieu IMU vao header de bo xuat DM-VIO lay dung mat do + // nhieu, khong doan. + char imu_note[160] = ""; + if (slope) { + std::snprintf(imu_note, sizeof(imu_note), + ",\"gyro_noise_stddev\":%.6g,\"accel_noise_stddev\":%.6g", + cfg.gyro_noise_stddev, cfg.accel_noise_stddev); + } vslam::RecordWriterConfig wc; wc.path = path; wc.compress = false; // nen = khong tat dinh giua cac phien ban zstd wc.config_json = std::string("{\"scenario\":\"") + s.name + "\",\"seed\":1234" + (robot_yaml.empty() ? "" : ",\"robot\":\"" + robot_yaml + "\"") + - (write_gt ? ",\"ground_truth\":true" : "") + "}"; + (write_gt || slope ? ",\"ground_truth\":true" : "") + + (slope ? std::string(",\"world\":\"") + si->world + "\",\"gl\":" + + (use_gl ? "true" : "false") + imu_note + : std::string("")) + + "}"; vslam::RecordWriter w(wc); const vslam::StatusResponse st = w.Open(); @@ -275,8 +476,8 @@ int main(int argc, char** argv) { vslam::EncodeEncoderPayload(e.left_rad, e.right_rad, &b_enc); w.Write(vslam::VsrStream::kEncoder, e.stamp, b_enc); }); - std::string b_gt; - if (write_gt) { + std::string b_gt, b_ir; + if (write_gt || slope) { sim.SetGroundTruthCallback([&](vslam::UnixTime t, const vslam::SimPose3& p) { const double v[6] = {p.x, p.y, p.z, p.roll, p.pitch, p.yaw}; b_gt.clear(); @@ -293,6 +494,13 @@ int main(int argc, char** argv) { b_depth.clear(); vslam::EncodeImagePayload(*f.depth, &b_depth); w.Write(vslam::VsrStream::kDepth, f.header.stamp, b_depth); + // Anh IR (chi khi ve bang GPU). SAU depth: replay rap khung theo thu + // tu camera_info -> depth -> infra1. + if (f.infra1) { + b_ir.clear(); + vslam::EncodeImagePayload(*f.infra1, &b_ir); + w.Write(vslam::VsrStream::kInfra1, f.header.stamp, b_ir); + } }); sim.camera()->Open(); } @@ -311,6 +519,20 @@ int main(int argc, char** argv) { // Phat lai o 20 Hz cung la dung cai ma luong safety lam tren robot that. constexpr double kSlice = 0.05; double total = 0.0; + if (slope) { + // Ham: writer chay luong rieng va DROP khi hang doi day -- cho no ghi + // bot truoc khi mo phong chay tiep (sim chay nhanh hon thoi gian thuc). + auto throttle = [&w]() { + while (w.Stats().queue_bytes > (48u << 20)) { + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + }; + if (!DriveWaypoints(&sim, si->waypoints, si->cruise, throttle, &total)) { + std::fprintf(stderr, "%s: KHONG toi het waypoint trong thoi gian cho phep\n", s.name); + w.Close(); + return 1; + } + } for (const Leg& leg : s.legs) { double left = leg.seconds; while (left > 1e-9) { diff --git a/tools/vslam_vsr_export.cc b/tools/vslam_vsr_export.cc new file mode 100644 index 0000000..0c51951 --- /dev/null +++ b/tools/vslam_vsr_export.cc @@ -0,0 +1,385 @@ +// vslam_vsr_export -- doi ban ghi .vsr cua bo mo phong (anh IR + IMU + su +// that) sang thu muc dataset cho DM-VIO, dinh dang TUM-VI "dso". +// +// vslam_vsr_export --in X.vsr --out DIR [--robot robot.yaml] +// [--imu-hz 0] [--imu-offset-ms 0] +// [--gyro-noise 0] [--accel-noise 0] [--seed 1] +// +// Ra (DM-VIO doc theo src/dso/util/DatasetReader.h): +// DIR/cam0/images/.png anh IR 8 bit. DM-VIO ghep anh voi times.txt +// theo THU TU ten file da sap -- ten 19 chu so. +// DIR/cam0/times.txt "ns giay" moi anh. +// DIR/imu.txt "#..." roi "ns wx wy wz ax ay az". CO mau dung +// gio MOI anh: DM-VIO bo khung thieu mau trung gio. +// DIR/camera.txt pinhole kieu DSO, khong meo. +// DIR/camchain.yaml cam0/T_cam_imu (Kalibr) + noi suy. +// DIR/imu_noise.yaml mat do nhieu / bias (Kalibr imu.yaml). +// DIR/gt_imu.csv su that diem dat IMU, "ns,px,py,pz,qw,qx,qy,qz" +// (TUM-VI) -- dung cho gtFile cua DM-VIO. +// DIR/gt_cam_tum.txt su that camera (frame quang hoc), TUM. +// DIR/gt_base_tum.txt su that base_footprint, TUM. +// DIR/export.json thong so da dung. +// +// ================== LAM XAU DU LIEU O DAY, KHONG GHI LAI ================== +// Ban ghi mang IMU SACH 200 Hz. Muon thu "giong robot that" (WT61PC 10 Hz, +// lech gio camera-IMU, nhieu lon hon) thi lam o buoc xuat nay -- khong phai +// render lai anh: +// --imu-hz N giu moi k mau de con ~N Hz (0 = giu nguyen) +// --imu-offset-ms D CONG D ms vao stamp IMU: lech dong ho camera-IMU ma +// DM-VIO khong tu uoc luong +// --gyro-noise S, --accel-noise S them nhieu trang (sigma moi mau) + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "vslam/geometry.h" +#include "vslam/node_constants.h" +#include "vslam/record_format.h" +#include "vslam/record_io.h" +#include "vslam/robot_model.h" + +namespace { + +using vslam::Transform; + +struct ImuS { + int64_t t = 0; + double w[3] = {0, 0, 0}; + double a[3] = {0, 0, 0}; +}; + +struct GtS { + int64_t t = 0; + double p[6] = {0, 0, 0, 0, 0, 0}; // x y z roll pitch yaw (base_footprint) +}; + +struct Frame { + int64_t t = 0; + int w = 0, h = 0; + std::vector px; +}; + +bool MakeDir(const std::string& p) { + std::string cur; + for (size_t i = 0; i <= p.size(); ++i) { + if (i == p.size() || p[i] == '/') { + if (!cur.empty() && ::mkdir(cur.c_str(), 0775) != 0 && errno != EEXIST) return false; + } + if (i < p.size()) cur.push_back(p[i]); + } + return true; +} + +Transform PoseOf(const GtS& g) { + Transform t; + t.translation.x = g.p[0]; + t.translation.y = g.p[1]; + t.translation.z = g.p[2]; + t.rotation = vslam::QuaternionFromRPY(g.p[3], g.p[4], g.p[5]); + return t; +} + +void WriteTum(FILE* f, int64_t t, const Transform& T) { + std::fprintf(f, "%.9f %.6f %.6f %.6f %.9f %.9f %.9f %.9f\n", t * 1e-9, T.translation.x, + T.translation.y, T.translation.z, T.rotation.x, T.rotation.y, T.rotation.z, + T.rotation.w); +} + +// So theo khoa trong JSON phang cua header ("key":so). Khong co thi `def`. +double JsonNumber(const std::string& json, const std::string& key, double def) { + const std::string k = "\"" + key + "\":"; + const size_t p = json.find(k); + if (p == std::string::npos) return def; + return std::strtod(json.c_str() + p + k.size(), nullptr); +} + +ImuS Lerp(const ImuS& a, const ImuS& b, int64_t t) { + const double u = static_cast(t - a.t) / static_cast(b.t - a.t); + ImuS o; + o.t = t; + for (int i = 0; i < 3; ++i) { + o.w[i] = a.w[i] + u * (b.w[i] - a.w[i]); + o.a[i] = a.a[i] + u * (b.a[i] - a.a[i]); + } + return o; +} + +} // namespace + +int main(int argc, char** argv) { + std::string in, out, robot_yaml; + double imu_hz = 0.0, offset_ms = 0.0, gyro_noise = 0.0, accel_noise = 0.0; + // Nhieu SAN co trong ban ghi (sigma moi mau) -- de ghi mat do nhieu dung vao + // imu_noise.yaml. vslam_record ghi chung vao header cua kich ban doc; am = + // chua biet, lay tu header. + double sim_gyro_sigma = -1.0, sim_accel_sigma = -1.0; + uint32_t seed = 1; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; }; + if (a == "--in") in = next(); + else if (a == "--out") out = next(); + else if (a == "--robot") robot_yaml = next(); + else if (a == "--imu-hz") imu_hz = std::atof(next().c_str()); + else if (a == "--imu-offset-ms") offset_ms = std::atof(next().c_str()); + else if (a == "--gyro-noise") gyro_noise = std::atof(next().c_str()); + else if (a == "--accel-noise") accel_noise = std::atof(next().c_str()); + else if (a == "--sim-gyro-sigma") sim_gyro_sigma = std::atof(next().c_str()); + else if (a == "--sim-accel-sigma") sim_accel_sigma = std::atof(next().c_str()); + else if (a == "--seed") seed = static_cast(std::atoi(next().c_str())); + else { + std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str()); + return 2; + } + } + if (in.empty() || out.empty()) { + std::fprintf(stderr, "can --in va --out\n"); + return 2; + } + if (robot_yaml.empty()) { + const char* cd = std::getenv("VSLAM_CONFIG_DIR"); + robot_yaml = (cd != nullptr && *cd != '\0' ? std::string(cd) : std::string("configuration_files")) + + "/robot.yaml"; + } + + // --- Ngoai suy cam bien tu robot.yaml (CUNG nguon voi bo mo phong) --- + vslam::RobotModel robot; + const vslam::StatusResponse rs = robot.LoadFile(robot_yaml); + if (!rs.ok()) { + std::fprintf(stderr, "%s: %s\n", robot_yaml.c_str(), rs.message.c_str()); + return 1; + } + Transform T_cam_imu, T_bl_cam, T_bl_imu; + if (!robot.StaticTransform(vslam::kCameraDepthOpticalFrame, vslam::kImuFrame, &T_cam_imu) || + !robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kCameraDepthOpticalFrame, &T_bl_cam) || + !robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kImuFrame, &T_bl_imu)) { + std::fprintf(stderr, "robot.yaml thieu frame camera/IMU\n"); + return 1; + } + Transform T_fp_bl = vslam::TransformIdentity(); + T_fp_bl.translation.z = robot.geometry().wheel_radius; + + // --- Doc ban ghi --- + vslam::RecordReader r; + vslam::StatusResponse st = r.Open(in); + if (!st.ok()) { + std::fprintf(stderr, "%s: %s\n", in.c_str(), st.message.c_str()); + return 1; + } + const std::string& cj = r.info().config_json; + if (sim_gyro_sigma < 0.0) sim_gyro_sigma = JsonNumber(cj, "gyro_noise_stddev", 0.0); + if (sim_accel_sigma < 0.0) sim_accel_sigma = JsonNumber(cj, "accel_noise_stddev", 0.0); + if (sim_gyro_sigma <= 0.0 || sim_accel_sigma <= 0.0) { + std::fprintf(stderr, "canh bao: header khong ghi nhieu IMU -- imu_noise.yaml chi tinh nhieu " + "them luc xuat (dung --sim-gyro-sigma / --sim-accel-sigma)\n"); + } + std::vector imu; + std::vector gt; + std::vector frames; + vslam::CameraInfo info; + bool have_info = false; + vslam::VsrChunkHeader h; + std::string payload; + std::vector storage; + while (r.Next(&h, &payload)) { + const int64_t t = static_cast(h.stamp_ns); + switch (h.stream) { + case vslam::VsrStream::kImu: { + vslam::Imu m; + if (!vslam::DecodeImuPayload(payload, &m)) break; + ImuS s; + s.t = t; + s.w[0] = m.angular_velocity.x; s.w[1] = m.angular_velocity.y; s.w[2] = m.angular_velocity.z; + s.a[0] = m.linear_acceleration.x; s.a[1] = m.linear_acceleration.y; + s.a[2] = m.linear_acceleration.z; + imu.push_back(s); + break; + } + case vslam::VsrStream::kGroundTruth: { + GtS g; + g.t = t; + if (vslam::DecodeGroundTruthPayload(payload, g.p)) gt.push_back(g); + break; + } + case vslam::VsrStream::kCameraInfo: + if (vslam::DecodeCameraInfoPayload(payload, &info)) have_info = true; + break; + case vslam::VsrStream::kInfra1: { + vslam::Image img; + if (!vslam::DecodeImagePayload(payload, &img, &storage)) break; + if (img.format != vslam::PixelFormat::kMono8) break; + Frame f; + f.t = t; + f.w = static_cast(img.width); + f.h = static_cast(img.height); + f.px.resize(static_cast(f.w) * f.h); + for (int y = 0; y < f.h; ++y) { + std::copy(img.data + static_cast(y) * img.step, + img.data + static_cast(y) * img.step + f.w, + f.px.begin() + static_cast(y) * f.w); + } + frames.push_back(std::move(f)); + break; + } + default: + break; + } + } + if (imu.size() < 10 || frames.empty() || !have_info) { + std::fprintf(stderr, "ban ghi thieu IMU (%zu), anh IR (%zu) hoac camera_info -- ghi bang " + "vslam_record --gl va kich ban doc\n", imu.size(), frames.size()); + return 1; + } + + // --- Lam xau IMU: ha tan so, lech gio, them nhieu --- + std::vector dts; + for (size_t i = 1; i < imu.size(); ++i) dts.push_back(imu[i].t - imu[i - 1].t); + std::nth_element(dts.begin(), dts.begin() + dts.size() / 2, dts.end()); + const double src_hz = 1e9 / static_cast(dts[dts.size() / 2]); + const int keep_every = imu_hz > 0.0 ? std::max(1, static_cast(std::lround(src_hz / imu_hz))) : 1; + const int64_t offset_ns = static_cast(std::llround(offset_ms * 1e6)); + std::mt19937 rng(seed); + std::normal_distribution n01(0.0, 1.0); + std::vector q; + for (size_t i = 0; i < imu.size(); i += static_cast(keep_every)) { + ImuS s = imu[i]; + s.t += offset_ns; + for (int k = 0; k < 3; ++k) { + if (gyro_noise > 0.0) s.w[k] += gyro_noise * n01(rng); + if (accel_noise > 0.0) s.a[k] += accel_noise * n01(rng); + } + q.push_back(s); + } + const double out_hz = src_hz / keep_every; + + // --- Mau IMU dung gio MOI anh (noi suy tuyen tinh) --- + std::vector used; + std::vector merged = q; + for (Frame& f : frames) { + if (f.t < q.front().t || f.t > q.back().t) continue; // ngoai khoang IMU + used.push_back(&f); + auto it = std::lower_bound(q.begin(), q.end(), f.t, + [](const ImuS& s, int64_t t) { return s.t < t; }); + if (it != q.end() && it->t == f.t) continue; // da co mau trung gio + merged.push_back(Lerp(*(it - 1), *it, f.t)); + } + std::sort(merged.begin(), merged.end(), [](const ImuS& a, const ImuS& b) { return a.t < b.t; }); + + // --- Ghi --- + if (!MakeDir(out + "/cam0/images")) { + std::fprintf(stderr, "khong tao duoc %s\n", out.c_str()); + return 1; + } + FILE* ft = std::fopen((out + "/cam0/times.txt").c_str(), "w"); + for (const Frame* f : used) { + char name[64]; + std::snprintf(name, sizeof(name), "/cam0/images/%019lld.png", static_cast(f->t)); + const cv::Mat m(f->h, f->w, CV_8UC1, const_cast(f->px.data())); + cv::imwrite(out + name, m); + std::fprintf(ft, "%lld %.9f\n", static_cast(f->t), f->t * 1e-9); + } + std::fclose(ft); + + FILE* fi = std::fopen((out + "/imu.txt").c_str(), "w"); + std::fprintf(fi, "#timestamp [ns] w_x w_y w_z [rad/s] a_x a_y a_z [m/s^2]\n"); + for (const ImuS& s : merged) { + std::fprintf(fi, "%lld %.9f %.9f %.9f %.9f %.9f %.9f\n", static_cast(s.t), s.w[0], + s.w[1], s.w[2], s.a[0], s.a[1], s.a[2]); + } + std::fclose(fi); + + // Noi suy o DO PHAN GIAI ANH: K cua camera_info la anh goc, binning bao da + // decimate bao nhieu (giong image_proc/crop_decimate). + const double bx = std::max(1, info.binning_x), by = std::max(1, info.binning_y); + const double fx = info.k[0] / bx, fy = info.k[4] / by, cx = info.k[2] / bx, cy = info.k[5] / by; + const int W = used.front()->w, H = used.front()->h; + FILE* fc = std::fopen((out + "/camera.txt").c_str(), "w"); + std::fprintf(fc, "Pinhole %.6f %.6f %.6f %.6f 0\n%d %d\nnone\n%d %d\n", fx, fy, cx, cy, W, H, W, H); + std::fclose(fc); + + // T_cam_imu dang ma tran 4x4 (Kalibr). + const vslam::Vector3 ex = vslam::RotateVector(T_cam_imu.rotation, vslam::Vector3{1, 0, 0}); + const vslam::Vector3 ey = vslam::RotateVector(T_cam_imu.rotation, vslam::Vector3{0, 1, 0}); + const vslam::Vector3 ez = vslam::RotateVector(T_cam_imu.rotation, vslam::Vector3{0, 0, 1}); + FILE* fk = std::fopen((out + "/camchain.yaml").c_str(), "w"); + std::fprintf(fk, + "# Sinh boi vslam_vsr_export tu robot.yaml (%s): camera = " + "camera_depth_optical_frame, imu = imu_link.\n" + "cam0:\n T_cam_imu:\n" + " - [%.9f, %.9f, %.9f, %.9f]\n - [%.9f, %.9f, %.9f, %.9f]\n" + " - [%.9f, %.9f, %.9f, %.9f]\n - [0.0, 0.0, 0.0, 1.0]\n" + " camera_model: pinhole\n intrinsics: [%.6f, %.6f, %.6f, %.6f]\n" + " distortion_model: radtan\n distortion_coeffs: [0.0, 0.0, 0.0, 0.0]\n" + " resolution: [%d, %d]\n timeshift_cam_imu: 0.0\n", + robot_yaml.c_str(), ex.x, ey.x, ez.x, T_cam_imu.translation.x, ex.y, ey.y, ez.y, + T_cam_imu.translation.y, ex.z, ey.z, ez.z, T_cam_imu.translation.z, fx, fy, cx, cy, + W, H); + std::fclose(fk); + + // Mat do nhieu = sigma moi mau / sqrt(tan so RA): ha tan so bang cach bo mau + // (khong lay trung binh) giu nguyen sigma moi mau, nen mat do TANG. Bias: sim + // khong troi bias, ghi gia tri NHO nhung khac 0 -- bo loc can no de khong tin + // IMU tuyet doi. + const double g_sig = std::sqrt(sim_gyro_sigma * sim_gyro_sigma + gyro_noise * gyro_noise); + const double a_sig = std::sqrt(sim_accel_sigma * sim_accel_sigma + accel_noise * accel_noise); + FILE* fn = std::fopen((out + "/imu_noise.yaml").c_str(), "w"); + std::fprintf(fn, + "# Kalibr imu.yaml. Nhieu tu bo mo phong (sigma moi mau %.3g rad/s, %.3g m/s^2 o " + "%.0f Hz)%s.\n" + "gyroscope_noise_density: %.6e\naccelerometer_noise_density: %.6e\n" + "gyroscope_random_walk: 1.0e-05\naccelerometer_random_walk: 1.0e-04\n" + "update_rate: %.1f\n", + sim_gyro_sigma, sim_accel_sigma, src_hz, + (gyro_noise > 0 || accel_noise > 0) ? " + nhieu them luc xuat" : "", + g_sig / std::sqrt(out_hz), a_sig / std::sqrt(out_hz), out_hz); + std::fclose(fn); + + // Su that: IMU (TUM-VI csv, cho DM-VIO), camera va base (TUM, cho cham diem). + FILE* fg = std::fopen((out + "/gt_imu.csv").c_str(), "w"); + FILE* fgc = std::fopen((out + "/gt_cam_tum.txt").c_str(), "w"); + FILE* fgb = std::fopen((out + "/gt_base_tum.txt").c_str(), "w"); + std::fprintf(fg, "#timestamp [ns],p_x,p_y,p_z,q_w,q_x,q_y,q_z\n"); + std::fprintf(fgc, "# timestamp x y z qx qy qz qw -- camera_depth_optical_frame trong world\n"); + std::fprintf(fgb, "# timestamp x y z qx qy qz qw -- base_footprint trong world\n"); + for (const GtS& g : gt) { + const Transform T_w_fp = PoseOf(g); + const Transform T_w_bl = vslam::TransformCompose(T_w_fp, T_fp_bl); + const Transform T_w_imu = vslam::TransformCompose(T_w_bl, T_bl_imu); + const Transform T_w_cam = vslam::TransformCompose(T_w_bl, T_bl_cam); + std::fprintf(fg, "%lld,%.6f,%.6f,%.6f,%.9f,%.9f,%.9f,%.9f\n", static_cast(g.t), + T_w_imu.translation.x, T_w_imu.translation.y, T_w_imu.translation.z, + T_w_imu.rotation.w, T_w_imu.rotation.x, T_w_imu.rotation.y, T_w_imu.rotation.z); + WriteTum(fgc, g.t, T_w_cam); + WriteTum(fgb, g.t, T_w_fp); + } + std::fclose(fg); + std::fclose(fgc); + std::fclose(fgb); + + FILE* fj = std::fopen((out + "/export.json").c_str(), "w"); + std::fprintf(fj, + "{\"in\":\"%s\",\"robot\":\"%s\",\"images\":%zu,\"imu_src_hz\":%.3f," + "\"imu_out_hz\":%.3f,\"imu_offset_ms\":%.3f,\"gyro_noise\":%.3g," + "\"accel_noise\":%.3g,\"seed\":%u,\"fx\":%.4f,\"fy\":%.4f,\"cx\":%.4f," + "\"cy\":%.4f,\"width\":%d,\"height\":%d}\n", + in.c_str(), robot_yaml.c_str(), used.size(), src_hz, out_hz, offset_ms, + gyro_noise, accel_noise, seed, fx, fy, cx, cy, W, H); + std::fclose(fj); + + std::printf("xuat %zu anh %dx%d, %zu mau IMU (%.1f Hz -> %.1f Hz, lech %.1f ms), %zu su that " + "-> %s\n", + used.size(), W, H, merged.size(), src_hz, out_hz, offset_ms, gt.size(), out.c_str()); + return 0; +}