drivers,sim: moi khung anh mot bo dem rieng (sua tranh chap voi SlamLoop o RealSense/sim/replay); sim: IMU dong hoc tu quy dao 6-DoF, tan so phat/tre/bias, ground truth vao .vsr, vslam_record --robot --gt

This commit is contained in:
trung09122002
2026-10-03 18:55:55 +07:00
parent 26ee1a3b72
commit 0dd2546ab1
13 changed files with 845 additions and 51 deletions

View File

@@ -3,15 +3,19 @@
#include <algorithm>
#include <atomic>
#include <cmath>
#include <deque>
#include <functional>
#include <mutex>
#include <random>
#include <thread>
#include <vector>
#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 <limits>
@@ -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<uint8_t> 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<BufferPool<std::vector<uint8_t>>> depth_pool =
BufferPool<std::vector<uint8_t>>::Create(8);
std::shared_ptr<ReplayClock> clock;
// Trang thai that cua robot.
@@ -248,6 +254,24 @@ struct SimSource::Impl {
// `wall_height` nhu cu.
std::vector<float> wall_top;
// --- IMU dong hoc (SimConfig::imu_model) va phat thua / tre ---
bool imu_kinematic = false; // chot o Open()
// RNG RIENG cho IMU dong hoc: dung chung `rng` se xao toan bo chuoi nhieu
// cua LiDAR/camera va moi ban ghi cu doi theo.
std::mt19937 imu_rng{1234};
Rot3 imu_R_prev{}; // tu the buoc truoc
double imu_p[3][3] = {}; // vi tri diem dat IMU: k-2, k-1, k
int imu_hist = 0; // so buoc da co lich su (toi da 3)
double imu_bg[3] = {0.0, 0.0, 0.0}, imu_ba[3] = {0.0, 0.0, 0.0};
bool imu_lpf_init = false;
double imu_lpf_w[3] = {0.0, 0.0, 0.0}, imu_lpf_f[3] = {0.0, 0.0, 0.0};
double imu_out_acc = 0.0;
std::deque<std::pair<double, ImuPtr>> imu_fifo; // (thoi diem DO, mau)
// --- Ground truth cho tool ghi ---
SimSource::GroundTruthCallback gt_cb;
double gt_period = 0.0, gt_acc = 0.0;
std::atomic<bool> stop{false};
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<size_t>(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<size_t>(w) * h * 2);
std::vector<uint8_t>& 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<std::mutex> lk(state_mu);
rx = x; ry = y; ryaw = yaw;
rz = terrain_on ? ground_z : 0.0;
rroll = roll + (terrain_on ? terrain_roll : 0.0);
rpitch = pitch + terrain_pitch;
}
*R = Rot3::FromRPY(rroll, rpitch, ryaw);
R->Apply(cfg.imu_x, cfg.imu_y, cfg.wheel_radius + cfg.imu_z, &p[0], &p[1], &p[2]);
p[0] += rx; p[1] += ry; p[2] += rz;
}
// Gieo lich su IMU tai tu the hien tai, robot coi nhu dang dung yen. Goi
// o Open(): mau dau tien phai mang CA chuyen dong cua buoc vat ly dau tien,
// khong thi tich phan IMU lech su that ngay tu dau.
void SeedImuHistory() {
double p[3];
ImuTruth(&imu_R_prev, p);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) imu_p[i][j] = p[j];
}
imu_hist = 1;
}
ImuPtr MakeImuKinematic(UnixTime stamp, double dt) {
Rot3 R;
double pnow[3];
ImuTruth(&R, pnow);
if (imu_hist == 0) SeedImuHistory();
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) imu_p[i][j] = imu_p[i + 1][j];
}
for (int j = 0; j < 3; ++j) imu_p[2][j] = pnow[j];
imu_hist = std::min(imu_hist + 1, 3);
double w[3] = {0.0, 0.0, 0.0};
if (dt > 0.0) {
// Rr = R_truoc^T * R, roi Log() ve vector quay.
double Rr[9];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
Rr[i * 3 + j] = imu_R_prev.m[0 * 3 + i] * R.m[0 * 3 + j] +
imu_R_prev.m[1 * 3 + i] * R.m[1 * 3 + j] +
imu_R_prev.m[2 * 3 + i] * R.m[2 * 3 + j];
}
}
const double c = std::max(-1.0, std::min(1.0, (Rr[0] + Rr[4] + Rr[8] - 1.0) / 2.0));
const double th = std::acos(c);
const double k = th < 1e-9 ? 0.5 : th / (2.0 * std::sin(th));
w[0] = k * (Rr[7] - Rr[5]) / dt;
w[1] = k * (Rr[2] - Rr[6]) / dt;
w[2] = k * (Rr[3] - Rr[1]) / dt;
}
imu_R_prev = R;
double a[3] = {0.0, 0.0, 0.0};
if (dt > 0.0) {
for (int j = 0; j < 3; ++j) {
a[j] = (imu_p[2][j] - 2.0 * imu_p[1][j] + imu_p[0][j]) / (dt * dt);
}
}
const double aw[3] = {a[0], a[1], a[2] + kGravity};
double f[3];
for (int i = 0; i < 3; ++i) {
f[i] = R.m[0 * 3 + i] * aw[0] + R.m[1 * 3 + i] * aw[1] + R.m[2 * 3 + i] * aw[2];
}
// Bias troi + nhieu trang.
std::normal_distribution<double> n01(0.0, 1.0);
const double sq = std::sqrt(std::max(dt, 0.0));
for (int i = 0; i < 3; ++i) {
if (cfg.gyro_bias_rw > 0.0) imu_bg[i] += cfg.gyro_bias_rw * sq * n01(imu_rng);
if (cfg.accel_bias_rw > 0.0) imu_ba[i] += cfg.accel_bias_rw * sq * n01(imu_rng);
w[i] += imu_bg[i];
f[i] += imu_ba[i];
if (cfg.gyro_noise_stddev > 0.0) w[i] += cfg.gyro_noise_stddev * n01(imu_rng);
if (cfg.accel_noise_stddev > 0.0) f[i] += cfg.accel_noise_stddev * n01(imu_rng);
}
// Loc trong cam bien (WT61PC co loc noi): lam tre va lam mem tin hieu.
if (cfg.imu_lpf_hz > 0.0 && dt > 0.0) {
const double al = dt / (dt + 1.0 / (2.0 * M_PI * cfg.imu_lpf_hz));
if (!imu_lpf_init) {
for (int i = 0; i < 3; ++i) { imu_lpf_w[i] = w[i]; imu_lpf_f[i] = f[i]; }
imu_lpf_init = true;
}
for (int i = 0; i < 3; ++i) {
imu_lpf_w[i] += al * (w[i] - imu_lpf_w[i]);
imu_lpf_f[i] += al * (f[i] - imu_lpf_f[i]);
w[i] = imu_lpf_w[i];
f[i] = imu_lpf_f[i];
}
}
auto m = std::make_shared<Imu>();
m->header.stamp = stamp;
m->header.frame_id = kImuFrame;
m->angular_velocity.x = w[0];
m->angular_velocity.y = w[1];
m->angular_velocity.z = w[2];
m->linear_acceleration.x = f[0];
m->linear_acceleration.y = f[1];
m->linear_acceleration.z = f[2];
m->orientation_covariance[0] = -1.0; // khong co orientation
const double gv = cfg.gyro_noise_stddev * cfg.gyro_noise_stddev;
const double av = cfg.accel_noise_stddev * cfg.accel_noise_stddev;
m->angular_velocity_covariance[0] = gv;
m->angular_velocity_covariance[4] = gv;
m->angular_velocity_covariance[8] = gv;
m->linear_acceleration_covariance[0] = av;
m->linear_acceleration_covariance[4] = av;
m->linear_acceleration_covariance[8] = av;
return m;
}
// Phat mau IMU theo tan so phat va do tre. Tra true neu da phat.
//
// Mac dinh (imu_output_hz = 0, imu_delay_sec = 0): phat MOI mau ngay khi do,
// y het truoc. Co tre: mau phat luc `now` la mau DO tai `now - delay`, mang
// stamp `now` -- dung cai driver that thay khi dong dau bang gio nhan.
bool EmitImu(UnixTime now, ImuPtr meas, double dt) {
if (cfg.imu_output_hz <= 0.0 && cfg.imu_delay_sec <= 0.0) {
mcu.PushImu(std::move(meas));
return true;
}
const double t = sim_elapsed;
imu_fifo.emplace_back(t, std::move(meas));
imu_out_acc += dt;
const double period = cfg.imu_output_hz > 0.0 ? 1.0 / cfg.imu_output_hz : dt;
if (imu_out_acc + 1e-9 < period) {
// Khong de hang doi phinh khi tan so phat thap: giu toi da 2 s.
while (imu_fifo.size() > 1 && imu_fifo.front().first < t - cfg.imu_delay_sec - 2.0) {
imu_fifo.pop_front();
}
return false;
}
imu_out_acc -= period;
ImuPtr pick;
const double want = t - cfg.imu_delay_sec;
while (!imu_fifo.empty() && imu_fifo.front().first <= want + 1e-9) {
pick = imu_fifo.front().second;
imu_fifo.pop_front();
}
if (!pick) return false; // vua khoi dong, chua du tre
auto out = std::make_shared<Imu>(*pick);
out->header.stamp = now;
mcu.PushImu(std::move(out));
return true;
}
};
// ---------------------------------------------------------------------------
@@ -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<double> n01(0.0, 1.0);
for (int i = 0; i < 3; ++i) {
impl_->imu_bg[i] = impl_->cfg.gyro_bias_sigma * n01(impl_->imu_rng);
impl_->imu_ba[i] = impl_->cfg.accel_bias_sigma * n01(impl_->imu_rng);
}
VSLAM_INFO("sim: IMU dong hoc -- tinh tu quy dao 6-DoF that"
<< (impl_->cfg.imu_output_hz > 0.0
? ", phat " + std::to_string(impl_->cfg.imu_output_hz) + " Hz"
: std::string(""))
<< (impl_->cfg.imu_delay_sec > 0.0
? ", tre " + std::to_string(impl_->cfg.imu_delay_sec) + " s"
: std::string("")));
}
if (impl_->Collides(impl_->x, impl_->y)) {
// 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<std::mutex> 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<std::mutex> 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;