diff --git a/app/src/runtime.cc b/app/src/runtime.cc index 7962a47..6f43421 100644 --- a/app/src/runtime.cc +++ b/app/src/runtime.cc @@ -69,13 +69,9 @@ StatusResponse Runtime::OpenSource() { sc.start_yaw = opts_.sim_start_yaw; // Hinh hoc lay tu robot.yaml, KHONG go tay. Neu sim dung mot bo so va - // duong ong dung bo khac thi moi phep do deu do nham. - const RobotGeometry& g = cfg_->robot.geometry(); - sc.wheel_radius = g.wheel_radius; - sc.wheel_separation = g.wheel_separation; - sc.robot_radius = g.robot_radius; - sc.camera_z = cfg_->robot.camera_height_above_floor(); - sc.camera_pitch = cfg_->robot.camera_pitch(); + // duong ong dung bo khac thi moi phep do deu do nham. Ham dung CHUNG voi + // vslam_record. + SimConfigFromRobot(cfg_->robot, &sc); sc.max_linear = speed_limit_; sc.max_angular = cfg_->robot.base().max_angular; sc.accel_limit = accel_limit_; @@ -84,17 +80,6 @@ StatusResponse Runtime::OpenSource() { sc.imu_rate_hz = cfg_->sensors.imu_hz; sc.enable_depth_camera = cfg_->sensors.camera_enable; - Transform t; - if (cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) { - sc.lidar_x = t.translation.x; - // Do cao LiDAR tren TAM TRUC. Duong 2D cu khong dung; dia hinh 3D thi - // can de tia o dung 0.2165 m tren san. - sc.lidar_z = t.translation.z; - } - if (cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) { - sc.camera_x = t.translation.x; - } - source_->sim.reset(new SimSource(sc)); const StatusResponse st = source_->sim->Open(); if (!st.ok()) return st; diff --git a/libs/vslam_drivers/include/vslam/record_format.h b/libs/vslam_drivers/include/vslam/record_format.h index 1f6fc87..20c56e0 100644 --- a/libs/vslam_drivers/include/vslam/record_format.h +++ b/libs/vslam_drivers/include/vslam/record_format.h @@ -73,6 +73,10 @@ enum class VsrStream : uint8_t { // bao "xanh" cho mot he da mat hai nhanh an toan. kUltrasonic = 11, kBumper = 12, + // MO RONG: tu the THAT 6-DoF, CHI ban ghi tu bo mo phong. De cham diem + // offline (VO/VIO, z tren doc). Replay khong dua no vao duong ong nao -- + // khong stage nao duoc doc su that. + kGroundTruth = 13, }; const char* VsrStreamName(VsrStream s); @@ -109,6 +113,11 @@ bool DecodeUltrasonicPayload(const std::string& buf, double* range, size_t* coun void EncodeBumperPayload(uint32_t mask, std::string* out); bool DecodeBumperPayload(const std::string& buf, uint32_t* mask); +// Ground truth 6-DoF: sau double x, y, z, roll, pitch, yaw cua base_footprint +// trong frame world (z = do cao san duoi robot; pitch duong = mui chuc xuong). +void EncodeGroundTruthPayload(const double pose6[6], std::string* out); +bool DecodeGroundTruthPayload(const std::string& buf, double pose6[6]); + void EncodeCameraInfoPayload(const CameraInfo& info, std::string* out); bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out); diff --git a/libs/vslam_drivers/src/realsense_driver.cc b/libs/vslam_drivers/src/realsense_driver.cc index 8740667..0d9c2f5 100644 --- a/libs/vslam_drivers/src/realsense_driver.cc +++ b/libs/vslam_drivers/src/realsense_driver.cc @@ -37,6 +37,7 @@ #include #include +#include "vslam/buffer_pool.h" #include "vslam/clock.h" #include "vslam/driver_config.h" #include "vslam/driver_interfaces.h" @@ -323,22 +324,30 @@ class RealSenseDriver : public CameraInterface { depth_img->data = static_cast(depth.get_data()); depth_img->keep_alive = keep; // KHONG copy: giu frameset song } else { - Decimate16(praw, sw, sh, static_cast(cfg_.decimate), &depth_buf_, + // MOI khung mot bo dem RIENG tu pool, anh giu no qua keep_alive. + // + // ⚠️ Truoc day la MOT bo dem dung chung, "hop le toi lan goi Loop() + // sau" -- du cho perception chay INLINE trong callback, nhung SlamLoop + // giu khung depth/IR moi nhat qua Rtabmap::process (100-600 ms) tren + // luong KHAC, va `BuildSensorData` boc cv::Mat quanh bo dem ma khong + // copy. Khung sau (33 ms) ghi de giua chung: anh luu vao DB co the la + // nua khung nay nua khung kia. + auto buf = buf_pool_->Acquire(); + Decimate16(praw, sw, sh, static_cast(cfg_.decimate), buf.get(), &depth_img->width, &depth_img->height); depth_img->step = depth_img->width * 2; - depth_img->data = depth_buf_.data(); - // Bo dem cua ta: hop le toi lan goi Loop() sau. Consumer chay INLINE - // trong callback (xem PerceptionPipeline) nen dieu do la du. + depth_img->data = buf->data(); + depth_img->keep_alive = buf; } out.depth = depth_img; if (cfg_.enable_infra1) { rs2::video_frame ir = fs.get_infrared_frame(1); - if (ir) out.infra1 = WrapIr(ir, out.header, keep, &ir1_buf_); + if (ir) out.infra1 = WrapIr(ir, out.header, keep); } if (cfg_.enable_infra2) { rs2::video_frame ir = fs.get_infrared_frame(2); - if (ir) out.infra2 = WrapIr(ir, out.header, keep, &ir2_buf_); + if (ir) out.infra2 = WrapIr(ir, out.header, keep); } out.depth_info = info_; @@ -354,8 +363,7 @@ class RealSenseDriver : public CameraInterface { } ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr, - const std::shared_ptr& keep, - std::vector* buf) { + const std::shared_ptr& keep) { auto img = std::make_shared(); img->header = hdr; img->format = PixelFormat::kMono8; @@ -367,10 +375,13 @@ class RealSenseDriver : public CameraInterface { img->data = static_cast(ir.get_data()); img->keep_alive = keep; } else { + // Bo dem rieng moi khung, nhu depth o tren. + auto buf = buf_pool_->Acquire(); Decimate8(static_cast(ir.get_data()), w, h, - static_cast(cfg_.decimate), buf, &img->width, &img->height); + static_cast(cfg_.decimate), buf.get(), &img->width, &img->height); img->step = img->width; img->data = buf->data(); + img->keep_alive = buf; } return img; } @@ -384,7 +395,10 @@ class RealSenseDriver : public CameraInterface { float depth_scale_ = 0.001f; CameraInfo info_; - std::vector depth_buf_, ir1_buf_, ir2_buf_; + // Bo dem anh da decimate (depth + IR). Moi khung lay bo dem rieng va tra + // ve pool khi KHONG CON AI giu anh -- 0 malloc o trang thai on dinh. + std::shared_ptr>> buf_pool_ = + BufferPool>::Create(12); std::atomic running_{false}; std::thread thread_; diff --git a/libs/vslam_drivers/src/record_format.cc b/libs/vslam_drivers/src/record_format.cc index f61b4b8..7b394f6 100644 --- a/libs/vslam_drivers/src/record_format.cc +++ b/libs/vslam_drivers/src/record_format.cc @@ -121,6 +121,7 @@ const char* VsrStreamName(VsrStream s) { case VsrStream::kEvent: return "event"; case VsrStream::kUltrasonic: return "ultrasonic"; case VsrStream::kBumper: return "bumper"; + case VsrStream::kGroundTruth: return "ground_truth"; } return "?"; } @@ -225,6 +226,15 @@ bool DecodeBumperPayload(const std::string& buf, uint32_t* mask) { return r.ok; } +void EncodeGroundTruthPayload(const double pose6[6], std::string* o) { + for (int i = 0; i < 6; ++i) PutF64(o, pose6[i]); +} +bool DecodeGroundTruthPayload(const std::string& buf, double pose6[6]) { + Reader r(buf); + for (int i = 0; i < 6; ++i) pose6[i] = r.F64(); + return r.ok; +} + void EncodeEncoderPayload(double l, double rr, std::string* o) { PutF64(o, l); PutF64(o, rr); diff --git a/libs/vslam_drivers/src/replay_source.cc b/libs/vslam_drivers/src/replay_source.cc index 67bc3f3..41a7e04 100644 --- a/libs/vslam_drivers/src/replay_source.cc +++ b/libs/vslam_drivers/src/replay_source.cc @@ -7,6 +7,7 @@ #include #include +#include "vslam/buffer_pool.h" #include "vslam/log.h" #include "vslam/record_io.h" #include "vslam/scan_sanitizer.h" @@ -163,9 +164,20 @@ struct ReplaySource::Impl { // roi phat mot lan khi thay chunk depth ke tiep hoac khi het file. CameraFrame pending_frame; bool have_pending = false; - std::vector depth_storage; - std::vector infra1_storage; - std::vector infra2_storage; + // Kho nho cho anh giai ma. MOI anh mot kho rieng, giu qua keep_alive: + // SlamLoop giu khung moi nhat qua Rtabmap::process tren luong khac, va ba + // kho dung chung (nhu truoc day) bi khung sau ghi de giua chung. + std::shared_ptr>> img_pool = + BufferPool>::Create(12); + + // Giai ma mot anh vao kho rieng. null neu payload hong. + ImagePtr DecodeImage(const std::string& payload) { + auto img = std::make_shared(); + auto storage = img_pool->Acquire(); + if (!DecodeImagePayload(payload, img.get(), storage.get())) return nullptr; + img->keep_alive = storage; + return img; + } CameraInfo last_info; bool have_info = false; @@ -360,22 +372,22 @@ void ReplaySource::Run() { case VsrStream::kDepth: { // Chunk depth moi = khung truoc da day du -> phat khung truoc. impl_->FlushCameraFrame(); - auto img = std::make_shared(); - if (!DecodeImagePayload(payload, img.get(), &impl_->depth_storage)) break; + ImagePtr img = impl_->DecodeImage(payload); + if (!img) break; impl_->pending_frame.header = img->header; impl_->pending_frame.depth = img; impl_->have_pending = true; break; } case VsrStream::kInfra1: { - auto img = std::make_shared(); - if (!DecodeImagePayload(payload, img.get(), &impl_->infra1_storage)) break; + ImagePtr img = impl_->DecodeImage(payload); + if (!img) break; impl_->pending_frame.infra1 = img; break; } case VsrStream::kInfra2: { - auto img = std::make_shared(); - if (!DecodeImagePayload(payload, img.get(), &impl_->infra2_storage)) break; + ImagePtr img = impl_->DecodeImage(payload); + if (!img) break; impl_->pending_frame.infra2 = img; break; } @@ -385,6 +397,10 @@ void ReplaySource::Run() { } break; } + case VsrStream::kGroundTruth: + // Su that tu bo mo phong: chi de cham diem offline. KHONG dua vao + // duong ong -- khong stage nao duoc doc no. + break; case VsrStream::kCmdVel: // Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra. // Replay khong tu dong ap chung: viec do do wiring quyet dinh. diff --git a/libs/vslam_sim/include/vslam/sim_source.h b/libs/vslam_sim/include/vslam/sim_source.h index 0faddc8..95791c7 100644 --- a/libs/vslam_sim/include/vslam/sim_source.h +++ b/libs/vslam_sim/include/vslam/sim_source.h @@ -35,6 +35,7 @@ // co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va // toan bo duong ong du lieu. +#include #include #include #include @@ -184,10 +185,37 @@ struct SimConfig { // docs/SIM_VS_REAL.md cu phai ghi "kinh phai kiem bang du lieu that". double glass_lidar_pass_rate = 1.0; // 1.0 = xuyen hoan toan + // Buoc VAT LY cua bo mo phong, va (mac dinh) tan so phat IMU. double imu_rate_hz = 200.0; double gyro_noise_stddev = 4.9e-4; double accel_noise_stddev = 6.9e-3; + // ================== MO HINH IMU ================== + // kLegacy: cong thuc cu -- gia toc doc than + huong tam, gyro tu lo xo (va + // toc do doi nghieng do dia hinh). Giu nguyen tung byte ban ghi cu. + // kKinematic: gyro va gia toc ke tinh TU quy dao 6-DoF that cua DIEM DAT + // IMU (dao ham tu the, dao ham bac hai vi tri, cong trong luc). Tich phan + // IMU khop dung quy dao -- dieu kien toi thieu de thu VIO tren doc. + // kAuto: kKinematic khi dia hinh 3D bat, kLegacy khi khong. + enum class ImuModel { kAuto, kLegacy, kKinematic }; + ImuModel imu_model = ImuModel::kAuto; + // Tan so PHAT IMU, Hz. 0 = moi buoc vat ly, nhu cu. Buoc vat ly van theo + // `imu_rate_hz`: ha tan so phat de giong WT61PC (10 Hz) khong keo ca dong + // hoc, LiDAR va camera xuong theo. + double imu_output_hz = 0.0; + // Mau phat ra la so do CU hon stamp bao nhieu giay (loc trong cam bien + + // truyen). Driver that tru `imu_lag_sec`; phan lech con lai la sai so dong + // bo camera-IMU ma VIO phai chiu. + double imu_delay_sec = 0.0; + // --- Chi mo hinh kKinematic (dung RNG RIENG, khong xao chuoi nhieu cu) --- + double gyro_bias_sigma = 0.0; // rad/s, sigma bias DAU moi truc + double accel_bias_sigma = 0.0; // m/s^2 + double gyro_bias_rw = 0.0; // rad/s/sqrt(s), bias troi ngau nhien + double accel_bias_rw = 0.0; // m/s^2/sqrt(s) + double imu_lpf_hz = 0.0; // loc thong thap bac 1 trong cam bien; 0 = tat + // Vi tri diem dat IMU so voi base_link (robot.yaml: imu_link). + double imu_x = 0.0, imu_y = 0.0, imu_z = 0.06; + // ================== NGHIENG THAN ROBOT ================== // Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG, // quay gap lam no NGHIENG ra ngoai. Gazebo mo phong dieu nay qua vat ly @@ -284,6 +312,13 @@ struct SimPose3 { double roll = 0.0, pitch = 0.0, yaw = 0.0; }; +class RobotModel; + +// Dien hinh hoc robot THAT (robot.yaml) vao cau hinh mo phong: banh, ban kinh +// than, vi tri LiDAR / camera / IMU. vslam_node va moi tool dung CHUNG ham +// nay -- sim va duong ong dung hai bo so khac nhau thi moi phep do deu do nham. +void SimConfigFromRobot(const RobotModel& robot, SimConfig* cfg); + // So huu ca bon nguon, y het ReplaySource. class SimSource { public: @@ -325,6 +360,12 @@ class SimSource { // Tu the that 6-DoF. CHI de danh gia, nhu `ground_truth()`. SimPose3 ground_truth_3d() const; + // Goi lai voi tu the that moi `1 / rate_hz` giay mo phong (0 = moi buoc vat + // ly), tren luong chay Run()/RunFor(). Cho tool GHI su that vao ban ghi de + // cham diem offline -- KHONG duoc noi vao duong ong uoc luong. + using GroundTruthCallback = std::function; + void SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz = 0.0); + // 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 diff --git a/libs/vslam_sim/src/sim_source.cc b/libs/vslam_sim/src/sim_source.cc index 401cc89..efe8285 100644 --- a/libs/vslam_sim/src/sim_source.cc +++ b/libs/vslam_sim/src/sim_source.cc @@ -3,15 +3,19 @@ #include #include #include +#include +#include #include #include #include #include +#include "vslam/buffer_pool.h" #include "vslam/geometry.h" #include "vslam/log.h" #include "vslam/node_constants.h" #include "vslam/occupancy_map_io.h" +#include "vslam/robot_model.h" #include @@ -214,10 +218,12 @@ struct SimSource::Impl { double us_acc = 0.0, bump_acc = 0.0; bool bumper_now = false; - // Bo dem anh depth, cap phat mot lan. Anh khong so huu bo nho (xem - // vslam_common.h), nen bo dem nay phai song it nhat bang khung anh. - std::vector depth_buf; - uint32_t depth_w = 0, depth_h = 0; + // Bo dem anh depth. Anh khong so huu bo nho (xem vslam_common.h), nen MOI + // khung lay mot bo dem rieng tu pool va giu no qua keep_alive -- SlamLoop + // giu khung moi nhat qua Rtabmap::process tren luong khac, va mot bo dem + // dung chung se bi khung sau ghi de giua chung. + std::shared_ptr>> depth_pool = + BufferPool>::Create(8); std::shared_ptr clock; // Trang thai that cua robot. @@ -248,6 +254,24 @@ struct SimSource::Impl { // `wall_height` nhu cu. std::vector wall_top; + // --- IMU dong hoc (SimConfig::imu_model) va phat thua / tre --- + bool imu_kinematic = false; // chot o Open() + // RNG RIENG cho IMU dong hoc: dung chung `rng` se xao toan bo chuoi nhieu + // cua LiDAR/camera va moi ban ghi cu doi theo. + std::mt19937 imu_rng{1234}; + Rot3 imu_R_prev{}; // tu the buoc truoc + double imu_p[3][3] = {}; // vi tri diem dat IMU: k-2, k-1, k + int imu_hist = 0; // so buoc da co lich su (toi da 3) + double imu_bg[3] = {0.0, 0.0, 0.0}, imu_ba[3] = {0.0, 0.0, 0.0}; + bool imu_lpf_init = false; + double imu_lpf_w[3] = {0.0, 0.0, 0.0}, imu_lpf_f[3] = {0.0, 0.0, 0.0}; + double imu_out_acc = 0.0; + std::deque> imu_fifo; // (thoi diem DO, mau) + + // --- Ground truth cho tool ghi --- + SimSource::GroundTruthCallback gt_cb; + double gt_period = 0.0, gt_acc = 0.0; + std::atomic stop{false}; mutable std::mutex state_mu; Stats stats; @@ -974,11 +998,10 @@ struct SimSource::Impl { const uint32_t w = cfg.depth_width / dec; const uint32_t h = cfg.depth_height / dec; - if (depth_w != w || depth_h != h) { - depth_w = w; - depth_h = h; - depth_buf.assign(static_cast(w) * h * 2, 0); // 16UC1 - } + // 16UC1. Vong lap ben duoi ghi MOI diem anh, nen khong can xoa truoc. + auto buf = depth_pool->Acquire(); + buf->resize(static_cast(w) * h * 2); + std::vector& depth_buf = *buf; double rx, ry, rz, ryaw; { @@ -1149,6 +1172,7 @@ struct SimSource::Impl { img->format = PixelFormat::kMono16; img->depth_scale = 0.001f; img->data = depth_buf.data(); + img->keep_alive = buf; out->header = img->header; out->depth = img; @@ -1234,6 +1258,169 @@ struct SimSource::Impl { m->linear_acceleration_covariance[8] = m->linear_acceleration_covariance[0]; return m; } + + // IMU tinh TU quy dao that (SimConfig::ImuModel::kKinematic). Goi sau + // StepPhysics, MOI buoc vat ly -- lich su vi tri can deu buoc. + // + // gyro = Log(R_truoc^T R) / dt (van toc goc trong he THAN) + // accel = R^T (a + (0, 0, g)), a = sai phan lui bac hai vi tri diem dat IMU + // + // Tich phan nguoc (xoay gia toc ve the gioi bang tu the that, tru trong + // luc, tich phan hai lan) ra DUNG quy dao, sai so chi o muc lam tron. Mo + // hinh cu chi xap xi: thieu gia toc theo phuong dung khi len doc, thieu + // canh tay don cua diem dat IMU khi than nghieng. + // Tu the THAT va vi tri diem dat IMU o trang thai hien tai: + // base_footprint + R * (imu_x, imu_y, r_banh + imu_z). + void ImuTruth(Rot3* R, double p[3]) { + double rx, ry, rz, ryaw, rroll, rpitch; + { + std::lock_guard lk(state_mu); + rx = x; ry = y; ryaw = yaw; + rz = terrain_on ? ground_z : 0.0; + rroll = roll + (terrain_on ? terrain_roll : 0.0); + rpitch = pitch + terrain_pitch; + } + *R = Rot3::FromRPY(rroll, rpitch, ryaw); + R->Apply(cfg.imu_x, cfg.imu_y, cfg.wheel_radius + cfg.imu_z, &p[0], &p[1], &p[2]); + p[0] += rx; p[1] += ry; p[2] += rz; + } + + // Gieo lich su IMU tai tu the hien tai, robot coi nhu dang dung yen. Goi + // o Open(): mau dau tien phai mang CA chuyen dong cua buoc vat ly dau tien, + // khong thi tich phan IMU lech su that ngay tu dau. + void SeedImuHistory() { + double p[3]; + ImuTruth(&imu_R_prev, p); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) imu_p[i][j] = p[j]; + } + imu_hist = 1; + } + + ImuPtr MakeImuKinematic(UnixTime stamp, double dt) { + Rot3 R; + double pnow[3]; + ImuTruth(&R, pnow); + if (imu_hist == 0) SeedImuHistory(); + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 3; ++j) imu_p[i][j] = imu_p[i + 1][j]; + } + for (int j = 0; j < 3; ++j) imu_p[2][j] = pnow[j]; + imu_hist = std::min(imu_hist + 1, 3); + + double w[3] = {0.0, 0.0, 0.0}; + if (dt > 0.0) { + // Rr = R_truoc^T * R, roi Log() ve vector quay. + double Rr[9]; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + Rr[i * 3 + j] = imu_R_prev.m[0 * 3 + i] * R.m[0 * 3 + j] + + imu_R_prev.m[1 * 3 + i] * R.m[1 * 3 + j] + + imu_R_prev.m[2 * 3 + i] * R.m[2 * 3 + j]; + } + } + const double c = std::max(-1.0, std::min(1.0, (Rr[0] + Rr[4] + Rr[8] - 1.0) / 2.0)); + const double th = std::acos(c); + const double k = th < 1e-9 ? 0.5 : th / (2.0 * std::sin(th)); + w[0] = k * (Rr[7] - Rr[5]) / dt; + w[1] = k * (Rr[2] - Rr[6]) / dt; + w[2] = k * (Rr[3] - Rr[1]) / dt; + } + imu_R_prev = R; + + double a[3] = {0.0, 0.0, 0.0}; + if (dt > 0.0) { + for (int j = 0; j < 3; ++j) { + a[j] = (imu_p[2][j] - 2.0 * imu_p[1][j] + imu_p[0][j]) / (dt * dt); + } + } + const double aw[3] = {a[0], a[1], a[2] + kGravity}; + double f[3]; + for (int i = 0; i < 3; ++i) { + f[i] = R.m[0 * 3 + i] * aw[0] + R.m[1 * 3 + i] * aw[1] + R.m[2 * 3 + i] * aw[2]; + } + + // Bias troi + nhieu trang. + std::normal_distribution n01(0.0, 1.0); + const double sq = std::sqrt(std::max(dt, 0.0)); + for (int i = 0; i < 3; ++i) { + if (cfg.gyro_bias_rw > 0.0) imu_bg[i] += cfg.gyro_bias_rw * sq * n01(imu_rng); + if (cfg.accel_bias_rw > 0.0) imu_ba[i] += cfg.accel_bias_rw * sq * n01(imu_rng); + w[i] += imu_bg[i]; + f[i] += imu_ba[i]; + if (cfg.gyro_noise_stddev > 0.0) w[i] += cfg.gyro_noise_stddev * n01(imu_rng); + if (cfg.accel_noise_stddev > 0.0) f[i] += cfg.accel_noise_stddev * n01(imu_rng); + } + // Loc trong cam bien (WT61PC co loc noi): lam tre va lam mem tin hieu. + if (cfg.imu_lpf_hz > 0.0 && dt > 0.0) { + const double al = dt / (dt + 1.0 / (2.0 * M_PI * cfg.imu_lpf_hz)); + if (!imu_lpf_init) { + for (int i = 0; i < 3; ++i) { imu_lpf_w[i] = w[i]; imu_lpf_f[i] = f[i]; } + imu_lpf_init = true; + } + for (int i = 0; i < 3; ++i) { + imu_lpf_w[i] += al * (w[i] - imu_lpf_w[i]); + imu_lpf_f[i] += al * (f[i] - imu_lpf_f[i]); + w[i] = imu_lpf_w[i]; + f[i] = imu_lpf_f[i]; + } + } + + auto m = std::make_shared(); + m->header.stamp = stamp; + m->header.frame_id = kImuFrame; + m->angular_velocity.x = w[0]; + m->angular_velocity.y = w[1]; + m->angular_velocity.z = w[2]; + m->linear_acceleration.x = f[0]; + m->linear_acceleration.y = f[1]; + m->linear_acceleration.z = f[2]; + m->orientation_covariance[0] = -1.0; // khong co orientation + const double gv = cfg.gyro_noise_stddev * cfg.gyro_noise_stddev; + const double av = cfg.accel_noise_stddev * cfg.accel_noise_stddev; + m->angular_velocity_covariance[0] = gv; + m->angular_velocity_covariance[4] = gv; + m->angular_velocity_covariance[8] = gv; + m->linear_acceleration_covariance[0] = av; + m->linear_acceleration_covariance[4] = av; + m->linear_acceleration_covariance[8] = av; + return m; + } + + // Phat mau IMU theo tan so phat va do tre. Tra true neu da phat. + // + // Mac dinh (imu_output_hz = 0, imu_delay_sec = 0): phat MOI mau ngay khi do, + // y het truoc. Co tre: mau phat luc `now` la mau DO tai `now - delay`, mang + // stamp `now` -- dung cai driver that thay khi dong dau bang gio nhan. + bool EmitImu(UnixTime now, ImuPtr meas, double dt) { + if (cfg.imu_output_hz <= 0.0 && cfg.imu_delay_sec <= 0.0) { + mcu.PushImu(std::move(meas)); + return true; + } + const double t = sim_elapsed; + imu_fifo.emplace_back(t, std::move(meas)); + imu_out_acc += dt; + const double period = cfg.imu_output_hz > 0.0 ? 1.0 / cfg.imu_output_hz : dt; + if (imu_out_acc + 1e-9 < period) { + // Khong de hang doi phinh khi tan so phat thap: giu toi da 2 s. + while (imu_fifo.size() > 1 && imu_fifo.front().first < t - cfg.imu_delay_sec - 2.0) { + imu_fifo.pop_front(); + } + return false; + } + imu_out_acc -= period; + ImuPtr pick; + const double want = t - cfg.imu_delay_sec; + while (!imu_fifo.empty() && imu_fifo.front().first <= want + 1e-9) { + pick = imu_fifo.front().second; + imu_fifo.pop_front(); + } + if (!pick) return false; // vua khoi dong, chua du tre + auto out = std::make_shared(*pick); + out->header.stamp = now; + mcu.PushImu(std::move(out)); + return true; + } }; // --------------------------------------------------------------------------- @@ -1311,6 +1498,32 @@ StatusResponse SimSource::Open() { impl_->UpdateTerrainPose(0.0); } + // Mo hinh IMU. RNG rieng, gieo tu seed: cung kich ban => cung chuoi nhieu. + const SimConfig::ImuModel im = impl_->cfg.imu_model; + impl_->imu_kinematic = im == SimConfig::ImuModel::kKinematic || + (im == SimConfig::ImuModel::kAuto && impl_->terrain_on); + impl_->imu_rng.seed(impl_->cfg.seed + 101u); + impl_->imu_hist = 0; + if (impl_->imu_kinematic) impl_->SeedImuHistory(); + impl_->imu_lpf_init = false; + impl_->imu_fifo.clear(); + impl_->imu_out_acc = 0.0; + for (int i = 0; i < 3; ++i) { impl_->imu_bg[i] = 0.0; impl_->imu_ba[i] = 0.0; } + if (impl_->imu_kinematic) { + std::normal_distribution n01(0.0, 1.0); + for (int i = 0; i < 3; ++i) { + impl_->imu_bg[i] = impl_->cfg.gyro_bias_sigma * n01(impl_->imu_rng); + impl_->imu_ba[i] = impl_->cfg.accel_bias_sigma * n01(impl_->imu_rng); + } + VSLAM_INFO("sim: IMU dong hoc -- tinh tu quy dao 6-DoF that" + << (impl_->cfg.imu_output_hz > 0.0 + ? ", phat " + std::to_string(impl_->cfg.imu_output_hz) + " Hz" + : std::string("")) + << (impl_->cfg.imu_delay_sec > 0.0 + ? ", tre " + std::to_string(impl_->cfg.imu_delay_sec) + " s" + : std::string(""))); + } + if (impl_->Collides(impl_->x, impl_->y)) { // Bao NGAY thay vi de robot ket ngay tu khung dau tien va nguoi dung ngoi // doan tai sao no khong nhuc nhich. @@ -1443,6 +1656,36 @@ void SimSource::SetFloorRamp(double x0, double y0, double x1, double y1, bool SimSource::terrain_active() const { return impl_->terrain_on; } +void SimSource::SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz) { + impl_->gt_cb = std::move(cb); + impl_->gt_period = rate_hz > 0.0 ? 1.0 / rate_hz : 0.0; + impl_->gt_acc = 0.0; +} + +void SimConfigFromRobot(const RobotModel& robot, SimConfig* c) { + const RobotGeometry& g = robot.geometry(); + c->wheel_radius = g.wheel_radius; + c->wheel_separation = g.wheel_separation; + c->robot_radius = g.robot_radius; + c->camera_z = robot.camera_height_above_floor(); + c->camera_pitch = robot.camera_pitch(); + Transform t; + if (robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) { + c->lidar_x = t.translation.x; + // Do cao LiDAR tren TAM TRUC. Duong 2D cu khong dung; dia hinh 3D thi + // can de tia o dung 0.2165 m tren san. + c->lidar_z = t.translation.z; + } + if (robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) { + c->camera_x = t.translation.x; + } + if (robot.StaticTransform(kBaseLinkFrame, kImuFrame, &t)) { + c->imu_x = t.translation.x; + c->imu_y = t.translation.y; + c->imu_z = t.translation.z; + } +} + void SimSource::true_tilt(double* roll_out, double* pitch_out) const { std::lock_guard lk(impl_->state_mu); // Tat dia hinh 3D thi KHONG cong (ke ca 0.0): giu dung tung bit nhu cu. @@ -1518,13 +1761,24 @@ void SimSource::RunFor(double seconds) { impl_->StepPhysics(dt); impl_->sim_elapsed += dt; - impl_->mcu.PushImu(impl_->MakeImu(now)); + ImuPtr meas = impl_->imu_kinematic ? impl_->MakeImuKinematic(now, dt) + : impl_->MakeImu(now); + const bool imu_out = impl_->EmitImu(now, std::move(meas), dt); { std::lock_guard lk(impl_->state_mu); - impl_->stats.imu++; + if (imu_out) impl_->stats.imu++; impl_->stats.sim_time_sec += dt; } + // Su that cho tool ghi (SetGroundTruthCallback). Khong stage nao doc no. + if (impl_->gt_cb) { + impl_->gt_acc += dt; + if (impl_->gt_period <= 0.0 || impl_->gt_acc + 1e-9 >= impl_->gt_period) { + if (impl_->gt_period > 0.0) impl_->gt_acc -= impl_->gt_period; + impl_->gt_cb(now, ground_truth_3d()); + } + } + enc_acc += dt; if (enc_acc >= enc_period) { enc_acc -= enc_period; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index c9af098..1acacb0 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -90,6 +90,8 @@ if(VSLAM_BUILD_SIM) # Dia hinh 3D: doc, san cao, robot di tren mat san, LiDAR tia 3D. Fixture # test/data/world/ramp.world (mot doc 10 do). vslam_add_test(test_sim_terrain LIBS vslam_sim vslam_drivers vslam_common) + # IMU mo phong (mo hinh dong hoc, phat thua, tre, bias) va su that 6-DoF. + vslam_add_test(test_sim_imu LIBS vslam_sim vslam_drivers vslam_common) if(VSLAM_BUILD_ODOMETRY) # Test TICH HOP: sim -> encoder -> wheel_odom -> EKF, do sai so so voi # ground truth. Day la bai L2 cua repo cu viet lai khong ROS. diff --git a/test/test_record_io.cc b/test/test_record_io.cc index 79d8e3a..b142bf9 100644 --- a/test/test_record_io.cc +++ b/test/test_record_io.cc @@ -149,6 +149,35 @@ TEST(RecordIo, RoundTripImuVaEncoder) { std::remove(path.c_str()); } +TEST(RecordIo, RoundTripGroundTruth) { + // Stream MO RONG cua ban ghi mo phong: tu the THAT 6-DoF de cham diem + // offline. Ten stream phai co, khong thi log replay in "?". + const std::string path = TempPath("gt"); + const double pose[6] = {1.5, -2.25, 0.4363, 0.01, -0.1745, 1.5708}; + { + RecordWriterConfig c; + c.path = path; + RecordWriter w(c); + ASSERT_TRUE(w.Open().ok()); + std::string p; + EncodeGroundTruthPayload(pose, &p); + w.Write(VsrStream::kGroundTruth, UnixTime::fromSec(200.0), p); + w.Close(); + } + RecordReader r; + ASSERT_TRUE(r.Open(path).ok()); + VsrChunkHeader h; + std::string payload; + ASSERT_TRUE(r.Next(&h, &payload)); + EXPECT_EQ(h.stream, VsrStream::kGroundTruth); + EXPECT_STREQ(VsrStreamName(h.stream), "ground_truth"); + double back[6] = {}; + ASSERT_TRUE(DecodeGroundTruthPayload(payload, back)); + for (int i = 0; i < 6; ++i) EXPECT_DOUBLE_EQ(back[i], pose[i]) << "truong " << i; + r.Close(); + std::remove(path.c_str()); +} + TEST(RecordIo, RoundTripImage) { const std::string path = TempPath("img"); std::vector pixels(320 * 240 * 2); diff --git a/test/test_replay_source.cc b/test/test_replay_source.cc index 0685df1..c9e199b 100644 --- a/test/test_replay_source.cc +++ b/test/test_replay_source.cc @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -320,6 +321,66 @@ TEST(ReplaySource, LenhMotorKhiReplayDiVaoHuKhong) { std::remove(path.c_str()); } +TEST(ReplaySource, AnhCuKhongBiKhungSauGhiDe) { + // Nhu bo mo phong va driver RealSense: anh da phat ra phai giu nguyen noi + // dung du nguon da giai ma them nhieu khung -- SlamLoop giu khung moi nhat + // qua Rtabmap::process tren luong khac. Truoc day ba kho giai ma dung chung. + const std::string path = TempPath("img_hold"); + { + RecordWriterConfig c; + c.path = path; + RecordWriter w(c); + ASSERT_TRUE(w.Open().ok()); + for (int k = 0; k < 6; ++k) { + const UnixTime stamp = UnixTime::fromSec(1737000000.0 + 0.1 * k); + std::vector depth(4 * 2 * 2), ir(4 * 2); + for (size_t i = 0; i < depth.size(); ++i) depth[i] = static_cast(10 * k + i); + for (size_t i = 0; i < ir.size(); ++i) ir[i] = static_cast(100 + 10 * k + i); + Image d; + d.header.stamp = stamp; + d.width = 4; d.height = 2; d.step = 8; + d.format = PixelFormat::kMono16; + d.depth_scale = 0.001f; + d.data = depth.data(); + Image r = d; + r.step = 4; + r.format = PixelFormat::kMono8; + r.data = ir.data(); + std::string pd, pr; + EncodeImagePayload(d, &pd); + EncodeImagePayload(r, &pr); + w.Write(VsrStream::kDepth, stamp, pd); + w.Write(VsrStream::kInfra1, stamp, pr); + } + w.Close(); + } + + ReplayConfig cfg; + cfg.path = path; + cfg.deterministic = true; + ReplaySource rs(cfg); + ASSERT_TRUE(rs.Open().ok()); + std::vector frames; + std::vector> depth_copy, ir_copy; + rs.camera()->SetCallback([&](const CameraFrame& f) { + frames.push_back(f); + depth_copy.emplace_back(f.depth->data, f.depth->data + 16); + ir_copy.emplace_back(f.infra1->data, f.infra1->data + 8); + }); + rs.camera()->Open(); + rs.Run(); + + ASSERT_EQ(frames.size(), 6u); + for (size_t k = 0; k < frames.size(); ++k) { + EXPECT_EQ(std::memcmp(frames[k].depth->data, depth_copy[k].data(), 16), 0) + << "depth khung " << k << " bi ghi de"; + EXPECT_EQ(std::memcmp(frames[k].infra1->data, ir_copy[k].data(), 8), 0) + << "IR khung " << k << " bi ghi de"; + EXPECT_EQ(frames[k].depth->data[0], static_cast(10 * k)); + } + std::remove(path.c_str()); +} + TEST(ReplaySource, FileKhongTonTaiThiBaoLoi) { ReplayConfig cfg; cfg.path = "/khong/ton/tai/abc.vsr"; diff --git a/test/test_sim_imu.cc b/test/test_sim_imu.cc new file mode 100644 index 0000000..98e1aab --- /dev/null +++ b/test/test_sim_imu.cc @@ -0,0 +1,308 @@ +// IMU mo phong va su that 6-DoF. +// +// ================== VI SAO BAI KIEM NAY TON TAI ================== +// VIO (DM-VIO, F2M co IMU) tin rang tich phan gyro ra dung tu the va tich +// phan gia toc ke (tru trong luc) ra dung quy dao. Mot IMU mo phong noi doi +// mot chut la VIO trong sim "tot" vi ly do sai, hoac "te" vi ly do sai. Mo +// hinh cu chi xap xi (bo gia toc theo phuong dung khi len doc, bo canh tay +// don cua diem dat IMU) -- du cho gravity_align, khong du cho VIO. +// +// Bai nay khoa: +// * tich phan gyro ra DUNG tu the that, ke ca khi quay tren doc; +// * tich phan gia toc ke ra DUNG vi tri that cua diem dat IMU; +// * tan so phat thap (WT61PC 10 Hz) khong keo buoc vat ly theo; +// * do tre: mau phat ra la mau cu, dung bang so buoc; +// * bias dau lam lech gyro nhu cau hinh; +// * su that phat dung tan so; hinh hoc lay dung tu robot.yaml. + +#include + +#include +#include +#include +#include + +#include "vslam/node_constants.h" +#include "vslam/robot_model.h" +#include "vslam/sim_source.h" + +using namespace vslam; + +namespace { + +constexpr double kDeg = M_PI / 180.0; + +std::string DataDir() { + const char* e = std::getenv("VSLAM_TEST_DATA_DIR"); + return e != nullptr ? std::string(e) : std::string("test/data"); +} + +std::string ConfigSrcDir() { + const char* e = std::getenv("VSLAM_CONFIG_SRC_DIR"); + return e != nullptr ? std::string(e) : std::string("configuration_files"); +} + +// Doc 10 do cua test/data/world/ramp.world, khong nhieu, IMU dong hoc. +SimConfig RampCfg() { + SimConfig c; + c.speed = 0.0; + c.enable_depth_camera = false; + c.world_path = DataDir() + "/world/ramp.world"; + c.world_model_paths = {DataDir() + "/world/models"}; + c.wheel_radius = 0.0865; + c.wheel_separation = 0.40; + c.lidar_x = 0.0; + c.lidar_z = 0.13; + c.lidar_noise_stddev = 0.0; + c.gyro_noise_stddev = 0.0; + c.accel_noise_stddev = 0.0; + c.imu_model = SimConfig::ImuModel::kKinematic; + c.start_x = -2.0; + return c; +} + +SimConfig FlatCfg() { + SimConfig c; + c.speed = 0.0; + c.enable_depth_camera = false; + c.gyro_noise_stddev = 0.0; + c.accel_noise_stddev = 0.0; + return c; +} + +// --- Ma tran 3x3 hang-chinh, chi cho bai kiem --- +struct M3 { + double m[9]; +}; + +M3 FromRPY(double r, double p, double y) { + const double cr = std::cos(r), sr = std::sin(r); + const double cp = std::cos(p), sp = std::sin(p); + const double cy = std::cos(y), sy = std::sin(y); + return M3{{cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr, + sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr, + -sp, cp * sr, cp * cr}}; +} + +M3 Mul(const M3& a, const M3& b) { + M3 o{}; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + double s = 0.0; + for (int k = 0; k < 3; ++k) s += a.m[i * 3 + k] * b.m[k * 3 + j]; + o.m[i * 3 + j] = s; + } + } + return o; +} + +// Exp(w) theo Rodrigues. +M3 Exp(double wx, double wy, double wz) { + const double th = std::sqrt(wx * wx + wy * wy + wz * wz); + const M3 K{{0, -wz, wy, wz, 0, -wx, -wy, wx, 0}}; + const M3 K2 = Mul(K, K); + const double a = th < 1e-12 ? 1.0 : std::sin(th) / th; + const double b = th < 1e-12 ? 0.5 : (1.0 - std::cos(th)) / (th * th); + M3 o{{1, 0, 0, 0, 1, 0, 0, 0, 1}}; + for (int i = 0; i < 9; ++i) o.m[i] += a * K.m[i] + b * K2.m[i]; + return o; +} + +double AngleBetween(const M3& a, const M3& b) { + double tr = 0.0; // trace(a^T b) + for (int i = 0; i < 3; ++i) { + for (int k = 0; k < 3; ++k) tr += a.m[k * 3 + i] * b.m[k * 3 + i]; + } + return std::acos(std::max(-1.0, std::min(1.0, (tr - 1.0) / 2.0))); +} + +// Vi tri diem dat IMU theo tu the that, cung quy uoc voi bo mo phong. +void ImuPoint(const SimConfig& c, const SimPose3& p, double out[3]) { + const M3 R = FromRPY(p.roll, p.pitch, p.yaw); + const double v[3] = {c.imu_x, c.imu_y, c.wheel_radius + c.imu_z}; + const double base[3] = {p.x, p.y, p.z}; + for (int i = 0; i < 3; ++i) { + out[i] = base[i] + R.m[i * 3 + 0] * v[0] + R.m[i * 3 + 1] * v[1] + R.m[i * 3 + 2] * v[2]; + } +} + +// Lai: tu x = -2 thang len doc (~1.8 m vao doc, z ~0.3 m), roi re trai nhe +// NGAY TREN doc -- doi ca roll lan pitch. +void DriveRampAndTurn(SimSource* sim) { + for (int i = 0; i < 260; ++i) { sim->base()->SetVelocity(0.30, 0.0); sim->RunFor(0.05); } + for (int i = 0; i < 60; ++i) { sim->base()->SetVelocity(0.25, 0.25); sim->RunFor(0.05); } +} + +} // namespace + +TEST(SimImu, TichPhanGyroRaDungTuThe) { + SimSource sim(RampCfg()); + ASSERT_TRUE(sim.Open().ok()); + const double dt = 1.0 / RampCfg().imu_rate_hz; + const SimPose3 p0 = sim.ground_truth_3d(); + M3 R = FromRPY(p0.roll, p0.pitch, p0.yaw); + sim.mcu()->SetImuCallback([&](ImuPtr m) { + R = Mul(R, Exp(m->angular_velocity.x * dt, m->angular_velocity.y * dt, + m->angular_velocity.z * dt)); + }); + sim.mcu()->Open(); + sim.base()->Open(); + + DriveRampAndTurn(&sim); + const SimPose3 p1 = sim.ground_truth_3d(); + ASSERT_GT(p1.z, 0.2) << "chua len doc"; + ASSERT_GT(std::fabs(p1.roll), 0.5 * kDeg) << "chua quay tren doc -- roll khong doi"; + EXPECT_LT(AngleBetween(R, FromRPY(p1.roll, p1.pitch, p1.yaw)), 1e-6); +} + +TEST(SimImu, TichPhanGiaTocRaDungQuyDao) { + const SimConfig c = RampCfg(); + SimSource sim(c); + ASSERT_TRUE(sim.Open().ok()); + const double dt = 1.0 / c.imu_rate_hz; + const SimPose3 p0 = sim.ground_truth_3d(); + M3 R = FromRPY(p0.roll, p0.pitch, p0.yaw); + double pos[3]; + ImuPoint(c, p0, pos); + double vel[3] = {0.0, 0.0, 0.0}; + sim.mcu()->SetImuCallback([&](ImuPtr m) { + // Tu the lay tu tich phan gyro (da kiem o bai tren la dung). + R = Mul(R, Exp(m->angular_velocity.x * dt, m->angular_velocity.y * dt, + m->angular_velocity.z * dt)); + const double f[3] = {m->linear_acceleration.x, m->linear_acceleration.y, + m->linear_acceleration.z}; + for (int i = 0; i < 3; ++i) { + double a = R.m[i * 3 + 0] * f[0] + R.m[i * 3 + 1] * f[1] + R.m[i * 3 + 2] * f[2]; + if (i == 2) a -= kGravity; + vel[i] += a * dt; + pos[i] += vel[i] * dt; + } + }); + sim.mcu()->Open(); + sim.base()->Open(); + + DriveRampAndTurn(&sim); + double truth[3]; + ImuPoint(c, sim.ground_truth_3d(), truth); + const double err = std::hypot(std::hypot(pos[0] - truth[0], pos[1] - truth[1]), + pos[2] - truth[2]); + EXPECT_LT(err, 1e-3) << "tich phan IMU lech quy dao that " << err << " m"; + EXPECT_GT(truth[2], 0.3) << "phai len doc thi bai nay moi kiem gia toc dung"; +} + +TEST(SimImu, TanSoPhatThapKhongKeoTheoVatLy) { + // WT61PC that phat 10 Hz. Ha tan so PHAT khong duoc keo LiDAR, encoder va + // buoc vat ly xuong theo. + SimConfig c = FlatCfg(); + c.imu_output_hz = 10.0; + SimSource sim(c); + ASSERT_TRUE(sim.Open().ok()); + int imu = 0, scans = 0, enc = 0; + sim.mcu()->SetImuCallback([&](ImuPtr) { imu++; }); + sim.lidar()->SetCallback([&](LaserScanPtr) { scans++; }); + sim.base()->SetEncoderCallback([&](const EncoderReading&) { enc++; }); + sim.mcu()->Open(); + sim.lidar()->Open(); + sim.base()->Open(); + sim.RunFor(2.0); + EXPECT_EQ(imu, 20); + EXPECT_EQ(scans, 50); + EXPECT_EQ(enc, 100); +} + +TEST(SimImu, DoTreLaMauCuDungSoBuoc) { + // Tre 0.05 s o buoc 5 ms: mau phat thu j la mau do o buoc j, phat muon 10 + // buoc. Hai lan chay giong het nhau (khong nhieu) nen so duoc tung gia tri. + auto run = [](double delay, std::vector* gz) { + SimConfig c = FlatCfg(); + c.imu_delay_sec = delay; + SimSource sim(c); + ASSERT_TRUE(sim.Open().ok()); + sim.mcu()->SetImuCallback([gz](ImuPtr m) { gz->push_back(m->angular_velocity.z); }); + sim.mcu()->Open(); + sim.base()->Open(); + for (int i = 0; i < 20; ++i) { sim.base()->SetVelocity(0.2, 0.6); sim.RunFor(0.05); } + }; + std::vector a, b; + run(0.0, &a); + run(0.05, &b); + ASSERT_EQ(a.size() - b.size(), 10u); + for (size_t j = 0; j < b.size(); ++j) { + ASSERT_EQ(b[j], a[j]) << "mau " << j; + } +} + +TEST(SimImu, BiasDauLamLechGyroKhiDungYen) { + SimConfig c = FlatCfg(); + c.imu_model = SimConfig::ImuModel::kKinematic; + c.gyro_bias_sigma = 0.01; + SimSource sim(c); + ASSERT_TRUE(sim.Open().ok()); + std::vector gz; + sim.mcu()->SetImuCallback([&](ImuPtr m) { gz.push_back(m->angular_velocity.z); }); + sim.mcu()->Open(); + sim.RunFor(1.0); + ASSERT_FALSE(gz.empty()); + // Dung yen, khong nhieu: gyro bang dung bias, va bias khac 0. + EXPECT_GT(std::fabs(gz.back()), 1e-5); + for (double v : gz) EXPECT_EQ(v, gz.back()); +} + +TEST(SimImu, MacDinhWorldPhangGiuMoHinhCu) { + // kAuto khong co dia hinh = mo hinh cu. Hai lan chay (kAuto, kLegacy) phai + // ra cung tung mau -- dieu kien de ban ghi hoi quy khong doi. + auto run = [](SimConfig::ImuModel model, std::vector* v) { + SimConfig c; + c.speed = 0.0; + c.enable_depth_camera = false; + c.imu_model = model; + SimSource sim(c); + ASSERT_TRUE(sim.Open().ok()); + sim.mcu()->SetImuCallback([v](ImuPtr m) { + v->push_back(m->linear_acceleration.x); + v->push_back(m->angular_velocity.z); + }); + sim.mcu()->Open(); + sim.base()->Open(); + for (int i = 0; i < 20; ++i) { sim.base()->SetVelocity(0.3, 0.4); sim.RunFor(0.05); } + }; + std::vector a, b; + run(SimConfig::ImuModel::kAuto, &a); + run(SimConfig::ImuModel::kLegacy, &b); + EXPECT_EQ(a, b); +} + +TEST(SimGroundTruth, PhatDungTanSoVaKhopTuThe) { + SimSource sim(RampCfg()); + ASSERT_TRUE(sim.Open().ok()); + int every = 0; + SimPose3 last; + sim.SetGroundTruthCallback([&](UnixTime, const SimPose3& p) { every++; last = p; }); + sim.RunFor(1.0); + EXPECT_EQ(every, 200); // moi buoc vat ly + const SimPose3 now = sim.ground_truth_3d(); + EXPECT_EQ(last.x, now.x); + EXPECT_EQ(last.z, now.z); + + int at25 = 0; + sim.SetGroundTruthCallback([&](UnixTime, const SimPose3&) { at25++; }, 25.0); + sim.RunFor(2.0); + EXPECT_EQ(at25, 50); +} + +TEST(SimConfigRobot, LayHinhHocRobotThat) { + RobotModel robot; + ASSERT_TRUE(robot.LoadFile(ConfigSrcDir() + "/robot.yaml").ok()); + SimConfig c; + SimConfigFromRobot(robot, &c); + EXPECT_NEAR(c.wheel_radius, robot.geometry().wheel_radius, 1e-12); + EXPECT_NEAR(c.wheel_separation, robot.geometry().wheel_separation, 1e-12); + EXPECT_NEAR(c.camera_z, robot.camera_height_above_floor(), 1e-12); + // LiDAR o 0.2165 m tren SAN: tam truc (r banh) + laser_link z. + EXPECT_NEAR(c.wheel_radius + c.lidar_z, 0.2165, 1e-6); + Transform t; + ASSERT_TRUE(robot.StaticTransform(kBaseLinkFrame, kImuFrame, &t)); + EXPECT_NEAR(c.imu_z, t.translation.z, 1e-12); + ASSERT_TRUE(robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)); + EXPECT_NEAR(c.camera_x, t.translation.x, 1e-12); +} diff --git a/test/test_sim_source.cc b/test/test_sim_source.cc index 49e42ab..0caa4f0 100644 --- a/test/test_sim_source.cc +++ b/test/test_sim_source.cc @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -743,6 +744,37 @@ TEST(SimTilt, TatFollowTerrainThiKhongNghiengTheoDoc) { EXPECT_NEAR(p, 0.0, 0.02); } +TEST(SimCamera, KhungCuKhongBiKhungSauGhiDe) { + // SlamLoop giu khung depth moi nhat qua Rtabmap::process (100-600 ms) tren + // luong khac, va BuildSensorData boc cv::Mat quanh bo dem ma khong copy. + // Mot bo dem dung chung thi khung sau ghi de len anh DANG duoc doc -- anh + // luu vao DB la nua khung nay nua khung kia. Moi khung phai co bo dem rieng. + SimSource sim(CamCfg()); + ASSERT_TRUE(sim.Open().ok()); + sim.base()->Open(); + std::vector frames; + std::vector> copies; + sim.camera()->SetCallback([&](const CameraFrame& f) { + frames.push_back(f); + const size_t n = static_cast(f.depth->step) * f.depth->height; + copies.emplace_back(f.depth->data, f.depth->data + n); + }); + sim.camera()->Open(); + // Quay tai cho: moi khung nhin mot huong khac. + for (int i = 0; i < 10; ++i) { sim.base()->SetVelocity(0.0, 0.8); sim.RunFor(0.1); } + ASSERT_GE(frames.size(), 10u); + size_t overwritten = 0; + for (size_t i = 0; i < frames.size(); ++i) { + if (std::memcmp(frames[i].depth->data, copies[i].data(), copies[i].size()) != 0) { + overwritten++; + } + } + EXPECT_EQ(overwritten, 0u) << "anh da phat ra bi khung sau ghi de"; + // Cac khung phai khac nhau that (robot dang quay), khong thi bai nay khong + // kiem duoc gi. + EXPECT_NE(copies.front(), copies.back()); +} + TEST(SimCamera, CAMERA_NGHIENG_THEO_THAN) { // Camera gan cung vao than. Than ngoc len thi camera nhin xa hon tren san. // Day la thu lam `cliff_detect` kho: mat phang san ky vong dich theo tung diff --git a/tools/vslam_record.cc b/tools/vslam_record.cc index 7658431..c00527e 100644 --- a/tools/vslam_record.cc +++ b/tools/vslam_record.cc @@ -22,6 +22,7 @@ #include "vslam/driver_interfaces.h" #include "vslam/record_format.h" #include "vslam/record_io.h" +#include "vslam/robot_model.h" #include "vslam/sim_source.h" namespace { @@ -137,6 +138,10 @@ std::vector Scenarios() { int main(int argc, char** argv) { std::string name, out_dir = "."; bool list = false; + // Mac dinh GIU hinh hoc cu cua SimConfig va KHONG ghi su that: bo hoi quy + // (tools/regress.sh) so voi ban ghi dung bang cach do. + std::string robot_yaml; + bool write_gt = false; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -144,10 +149,17 @@ int main(int argc, char** argv) { if (a == "--scenario") name = next(); else if (a == "--out-dir") out_dir = next(); else if (a == "--list") list = true; + else if (a == "--robot") robot_yaml = next(); + else if (a == "--gt") write_gt = true; else if (a == "--help") { - std::printf("cach dung: %s --scenario TEN --out-dir D\n" + std::printf("cach dung: %s --scenario TEN --out-dir D [--robot robot.yaml] [--gt]\n" " %s --list\n" - " %s --scenario all --out-dir D\n", argv[0], argv[0], argv[0]); + " %s --scenario all --out-dir D\n" + " --robot F hinh hoc robot THAT (banh, LiDAR, camera, IMU) tu robot.yaml\n" + " thay vi so mac dinh cu cua SimConfig\n" + " --gt ghi them tu the THAT 6-DoF (stream ground_truth) moi\n" + " buoc vat ly, de cham diem offline\n", + argv[0], argv[0], argv[0]); return 0; } } @@ -159,6 +171,15 @@ int main(int argc, char** argv) { return name.empty() && !list ? 2 : 0; } + vslam::RobotModel robot; + if (!robot_yaml.empty()) { + const vslam::StatusResponse rs = robot.LoadFile(robot_yaml); + if (!rs.ok()) { + std::fprintf(stderr, "%s: %s\n", robot_yaml.c_str(), rs.message.c_str()); + return 1; + } + } + int written = 0; for (const Scenario& s : all) { if (name != "all" && name != s.name) continue; @@ -176,6 +197,7 @@ int main(int argc, char** argv) { cfg.lidar_cut_at = s.lidar_cut_at; cfg.lidar_cut_for = s.lidar_cut_for; cfg.camera_rate_hz = s.camera_hz; + if (!robot_yaml.empty()) vslam::SimConfigFromRobot(robot, &cfg); vslam::SimSource sim(cfg); if (!sim.Open().ok()) { @@ -206,7 +228,9 @@ int main(int argc, char** argv) { vslam::RecordWriterConfig wc; wc.path = path; wc.compress = false; // nen = khong tat dinh giua cac phien ban zstd - wc.config_json = std::string("{\"scenario\":\"") + s.name + "\",\"seed\":1234}"; + wc.config_json = std::string("{\"scenario\":\"") + s.name + "\",\"seed\":1234" + + (robot_yaml.empty() ? "" : ",\"robot\":\"" + robot_yaml + "\"") + + (write_gt ? ",\"ground_truth\":true" : "") + "}"; vslam::RecordWriter w(wc); const vslam::StatusResponse st = w.Open(); @@ -251,6 +275,15 @@ int main(int argc, char** argv) { vslam::EncodeEncoderPayload(e.left_rad, e.right_rad, &b_enc); w.Write(vslam::VsrStream::kEncoder, e.stamp, b_enc); }); + std::string b_gt; + if (write_gt) { + sim.SetGroundTruthCallback([&](vslam::UnixTime t, const vslam::SimPose3& p) { + const double v[6] = {p.x, p.y, p.z, p.roll, p.pitch, p.yaw}; + b_gt.clear(); + vslam::EncodeGroundTruthPayload(v, &b_gt); + w.Write(vslam::VsrStream::kGroundTruth, t, b_gt); + }); + } if (sim.camera() != nullptr) { sim.camera()->SetCallback([&](const vslam::CameraFrame& f) { if (!f.depth) return;