slam,odometry,perception: di tren doc (G4, slam.yaml slope.enabled, mac dinh tat) -- z robot = tich -ds*sin(pitch IMU) kep phang < 1.5 do va neo vao ban do (HeightEstimator), odometry ngang, scan cho SLAM bu nghieng + bo tia cham san/doc theo ban do do cao tu depth (ScanLeveler, ElevationMap), z/roll/pitch luu vao node + do thi z 1-D + mat san theo node (height_map), voxel dat o z that va vat can tinh tu san cuc bo, xoa tuong gia LiDAR tren doc noi camera da thay mat san, web z uoc luong, --sim-imu-hz

This commit is contained in:
trung09122002
2026-10-04 00:03:02 +07:00
parent 6735b53423
commit f064dcf3ec
32 changed files with 1799 additions and 10 deletions

View File

@@ -0,0 +1,150 @@
#include "vslam/height_map.h"
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include <algorithm>
#include <cmath>
#include <limits>
namespace vslam {
std::map<int, double> SolveZGraph(const std::map<int, NodeHeight>& meas,
const std::vector<ZGraphLink>& links,
const ZGraphConfig& cfg) {
std::map<int, double> out;
if (meas.empty()) return out;
std::map<int, int> index;
for (const auto& kv : meas) {
const int k = static_cast<int>(index.size());
index[kv.first] = k;
}
const int n = static_cast<int>(index.size());
// Phuong trinh chuan H z = g, H = sum w a a^T.
std::vector<Eigen::Triplet<double>> trip;
Eigen::VectorXd g = Eigen::VectorXd::Zero(n);
auto add_rel = [&](int i, int j, double dz, double sigma) {
// z_j - z_i = dz
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
trip.emplace_back(j, j, w);
trip.emplace_back(i, j, -w);
trip.emplace_back(j, i, -w);
g(i) -= w * dz;
g(j) += w * dz;
};
auto add_abs = [&](int i, double z, double sigma) {
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
g(i) += w * z;
};
for (const auto& kv : meas) add_abs(index[kv.first], kv.second.z, cfg.sigma_prior);
add_abs(index[meas.begin()->first], meas.begin()->second.z, cfg.sigma_first);
for (const ZGraphLink& l : links) {
auto a = meas.find(l.from), b = meas.find(l.to);
if (a == meas.end() || b == meas.end() || l.from == l.to) continue;
const int i = index[l.from], j = index[l.to];
if (l.neighbor) {
const double dz = b->second.z - a->second.z;
add_rel(i, j, dz, cfg.sigma_neighbor + cfg.sigma_rel * std::fabs(dz));
continue;
}
const bool flat_a = std::fabs(a->second.pitch) < cfg.clamp_rad;
const bool flat_b = std::fabs(b->second.pitch) < cfg.clamp_rad;
if (flat_a && flat_b) {
add_rel(i, j, 0.0, cfg.sigma_loop_flat);
} else {
// Mat phang doc cua node `from`, keo toi `to`.
FloorNode fa;
fa.roll = a->second.roll;
fa.pitch = a->second.pitch;
const double dz = PlaneZ(fa, l.dx, l.dy);
add_rel(i, j, dz, cfg.sigma_loop_slope + cfg.sigma_rel * std::fabs(dz));
}
}
Eigen::SparseMatrix<double> H(n, n);
H.setFromTriplets(trip.begin(), trip.end());
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(H);
if (solver.info() != Eigen::Success) {
for (const auto& kv : meas) out[kv.first] = kv.second.z;
return out;
}
const Eigen::VectorXd z = solver.solve(g);
for (const auto& kv : index) out[kv.first] = z(kv.second);
return out;
}
double PlaneZ(const FloorNode& n, double x, double y) {
const double dx = x - n.x, dy = y - n.y;
const double c = std::cos(n.theta), s = std::sin(n.theta);
const double fwd = c * dx + s * dy;
const double left = -s * dx + c * dy;
// Ry(pitch): +x chuc xuong khi pitch duong; Rx(roll): +y len khi roll duong.
return n.z - fwd * std::tan(n.pitch) + left * std::tan(n.roll);
}
void FloorModel::Build(const std::vector<FloorNode>& nodes, double radius, double cell) {
nodes_ = nodes;
radius_ = radius;
cell_ = cell;
nearest_.clear();
w_ = h_ = 0;
if (nodes_.empty()) return;
double xmin = std::numeric_limits<double>::max(), ymin = xmin;
double xmax = std::numeric_limits<double>::lowest(), ymax = xmax;
for (const FloorNode& f : nodes_) {
xmin = std::min(xmin, f.x);
xmax = std::max(xmax, f.x);
ymin = std::min(ymin, f.y);
ymax = std::max(ymax, f.y);
}
x0_ = xmin - radius - cell;
y0_ = ymin - radius - cell;
w_ = static_cast<int>(std::ceil((xmax - xmin + 2 * radius + 2 * cell) / cell));
h_ = static_cast<int>(std::ceil((ymax - ymin + 2 * radius + 2 * cell) / cell));
nearest_.assign(static_cast<size_t>(w_) * h_, -1);
std::vector<float> best(nearest_.size(), std::numeric_limits<float>::max());
const int rc = static_cast<int>(std::ceil(radius / cell));
const double r2 = radius * radius;
for (size_t k = 0; k < nodes_.size(); ++k) {
const FloorNode& f = nodes_[k];
const int cx = static_cast<int>((f.x - x0_) / cell), cy = static_cast<int>((f.y - y0_) / cell);
for (int iy = std::max(0, cy - rc); iy <= std::min(h_ - 1, cy + rc); ++iy) {
for (int ix = std::max(0, cx - rc); ix <= std::min(w_ - 1, cx + rc); ++ix) {
const double px = x0_ + (ix + 0.5) * cell, py = y0_ + (iy + 0.5) * cell;
const double d2 = (px - f.x) * (px - f.x) + (py - f.y) * (py - f.y);
if (d2 > r2) continue;
const size_t i = static_cast<size_t>(iy) * w_ + ix;
if (d2 < best[i]) {
best[i] = static_cast<float>(d2);
nearest_[i] = static_cast<int>(k);
}
}
}
}
}
bool FloorModel::NearestNode(double x, double y, FloorNode* node, double* dist) const {
if (nodes_.empty()) return false;
const int ix = static_cast<int>(std::floor((x - x0_) / cell_));
const int iy = static_cast<int>(std::floor((y - y0_) / cell_));
if (ix < 0 || iy < 0 || ix >= w_ || iy >= h_) return false;
const int k = nearest_[static_cast<size_t>(iy) * w_ + ix];
if (k < 0) return false;
*node = nodes_[static_cast<size_t>(k)];
if (dist != nullptr) *dist = std::hypot(x - node->x, y - node->y);
return true;
}
bool FloorModel::FloorAt(double x, double y, double* z, double* dist) const {
FloorNode f;
if (!NearestNode(x, y, &f, dist)) return false;
*z = PlaneZ(f, x, y);
return true;
}
} // namespace vslam

View File

@@ -11,6 +11,7 @@
#include <algorithm>
#include <chrono>
#include <mutex>
#include <set>
#include "vslam/geometry.h"
#include "vslam/log.h"
@@ -45,6 +46,14 @@ class RtabmapSlamImpl {
// Diem depth theo node cho ban do voxel. Chi ExportVoxels (luong slam) cham.
VoxelNodeCache voxel_cache;
// ---- z ban do (di tren doc). CHI luong slam cham. ----
std::map<int, NodeHeight> node_meas; // z DO luc tao node
std::set<int> node_no_height; // node DB khong co userData z
std::map<int, double> node_z; // z sau do thi z
FloorModel floor;
bool use_heights = false;
std::vector<uint64_t> floor_cells;
void RecordMs(double ms) {
stats.last_ms = ms;
stats.max_ms = std::max(stats.max_ms, ms);
@@ -282,6 +291,15 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
in.camera_to_base != nullptr ? *in.camera_to_base
: impl_->camera_to_base,
impl_->next_id++);
if (in.has_height) {
// z / roll / pitch DO cua node -> DB (userData). Ban do quet xong mo lai
// o localization van co z.
cv::Mat ud(1, 3, CV_64FC1);
ud.at<double>(0) = in.z;
ud.at<double>(1) = in.roll;
ud.at<double>(2) = in.pitch;
data.setUserData(ud);
}
// Phuong sai odom: nguoi goi dat thi dung, khong thi lay tu slam.yaml.
const double lin_var = in.odom_linear_var > 0.0
@@ -319,6 +337,12 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
}
impl_->stats.frames_processed++;
if (in.has_height && impl_->cfg.mode == SlamMode::kMapping) {
// RTAB-Map tu sinh id node (Mem/GenerateIds) -- id cua SensorData chi la
// goi y. Node vua them la node cuoi cua bo nho.
const int id = impl_->rtabmap.getLastLocationId();
if (id > 0) impl_->node_meas[id] = NodeHeight{in.z, in.roll, in.pitch};
}
out.loop_closure_id = impl_->rtabmap.getLoopClosureId();
const rtabmap::Statistics& st = impl_->rtabmap.getStatistics();
auto stat = [&](const std::string& k, double dflt) {
@@ -377,9 +401,109 @@ StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt,
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
if (impl_->use_heights && !impl_->node_z.empty()) {
VoxelExportOptions o = opt;
o.node_z = &impl_->node_z;
o.floor = &impl_->floor;
impl_->floor_cells.clear();
o.floor_cells = &impl_->floor_cells;
return ExportVoxelGrid(impl_->rtabmap, o, &impl_->voxel_cache, out);
}
return ExportVoxelGrid(impl_->rtabmap, opt, &impl_->voxel_cache, out);
}
void RtabmapSlam::SetUseHeights(bool on) { impl_->use_heights = on; }
const std::vector<uint64_t>& RtabmapSlam::floor_cells() const { return impl_->floor_cells; }
const FloorModel& RtabmapSlam::floor_model() const { return impl_->floor; }
StatusResponse RtabmapSlam::UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
std::map<int, rtabmap::Transform> poses;
std::multimap<int, rtabmap::Link> links;
impl_->rtabmap.getGraph(poses, links, /*optimized=*/true, /*global=*/false);
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "do thi rong");
}
// Node chua co z do: nap userData tu DB (ban do quet o phien truoc). Node
// DB khong co (quet truoc khi co che do doc) thi nho lai, khong hoi mai.
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
for (const auto& kv : poses) {
const int id = kv.first;
if (id <= 0 || impl_->node_meas.count(id) || impl_->node_no_height.count(id)) continue;
if (mem == nullptr) break;
const rtabmap::SensorData d = mem->getNodeData(id, false, false, true, false);
cv::Mat ud;
d.uncompressDataConst(nullptr, nullptr, nullptr, &ud);
if (ud.type() == CV_64FC1 && ud.total() == 3) {
impl_->node_meas[id] = NodeHeight{ud.at<double>(0), ud.at<double>(1), ud.at<double>(2)};
} else {
impl_->node_no_height.insert(id);
}
}
std::map<int, NodeHeight> meas;
for (const auto& kv : poses) {
auto it = impl_->node_meas.find(kv.first);
if (it != impl_->node_meas.end()) meas[kv.first] = it->second;
}
std::vector<ZGraphLink> zl;
for (const auto& kv : links) {
const rtabmap::Link& l = kv.second;
ZGraphLink z;
z.from = l.from();
z.to = l.to();
switch (l.type()) {
case rtabmap::Link::kNeighbor:
case rtabmap::Link::kNeighborMerged:
z.neighbor = true;
break;
case rtabmap::Link::kGlobalClosure:
case rtabmap::Link::kLocalSpaceClosure:
case rtabmap::Link::kLocalTimeClosure:
case rtabmap::Link::kUserClosure:
z.neighbor = false;
break;
default:
continue;
}
if (l.transform().isNull()) continue;
z.dx = l.transform().x();
z.dy = l.transform().y();
zl.push_back(z);
}
impl_->node_z = SolveZGraph(meas, zl, cfg);
std::vector<FloorNode> fn;
fn.reserve(impl_->node_z.size());
for (const auto& kv : impl_->node_z) {
const auto p = poses.find(kv.first);
if (p == poses.end() || p->second.isNull()) continue;
const NodeHeight& m = meas[kv.first];
FloorNode f;
f.x = p->second.x();
f.y = p->second.y();
f.theta = p->second.theta();
f.z = kv.second;
f.roll = m.roll;
f.pitch = m.pitch;
fn.push_back(f);
}
impl_->floor.Build(fn);
if (nodes_out != nullptr) *nodes_out = impl_->node_z.size();
return StatusResponse::Ok();
}
bool RtabmapSlam::HeightAt(double x, double y, double radius, double* z) const {
double d = 0.0;
if (!impl_->floor.FloorAt(x, y, z, &d)) return false;
return d <= radius;
}
namespace {
cv::Matx44d ToMatx44(const rtabmap::Transform& t) {
return cv::Matx44d(t.r11(), t.r12(), t.r13(), t.x(), t.r21(), t.r22(), t.r23(), t.y(),

View File

@@ -230,13 +230,17 @@ void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
}
size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
OccupancyGrid* grid) {
OccupancyGrid* grid, const FloorModel* floor) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f) return 0;
const double r = vg.resolution;
const double inv = 1.0 / grid->resolution;
size_t marked = 0;
for (const VoxelIndex& k : vg.cells) {
const double z = vg.origin_z + (k.z + 0.5) * r;
double z = vg.origin_z + (k.z + 0.5) * r;
if (floor != nullptr) {
double f = 0.0;
if (floor->FloorAt(vg.origin_x + (k.x + 0.5) * r, vg.origin_y + (k.y + 0.5) * r, &f)) z -= f;
}
if (z < z_min || z > z_max) continue;
// Luoi 2D khong xoay (occupancy_export dat orientation = dong nhat), va
// hang 0 la ymin -- cung quy uoc voi RTAB-Map/map_server.
@@ -255,6 +259,38 @@ size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
return marked;
}
size_t ClearLidarOnSeenRamps(OccupancyGrid* grid, const std::vector<uint64_t>& floor_cells,
double cell_size, const FloorModel& floor, double clamp_rad,
double max_node_dist) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f || floor_cells.empty()) {
return 0;
}
std::vector<uint64_t> seen(floor_cells);
std::sort(seen.begin(), seen.end());
seen.erase(std::unique(seen.begin(), seen.end()), seen.end());
const double res = grid->resolution;
const double inv = 1.0 / cell_size;
size_t cleared = 0;
for (uint32_t r = 0; r < grid->height; ++r) {
for (uint32_t c = 0; c < grid->width; ++c) {
int8_t& v = grid->data[static_cast<size_t>(r) * grid->width + c];
if (v < 50) continue;
const double x = grid->origin.position.x + (c + 0.5) * res;
const double y = grid->origin.position.y + (r + 0.5) * res;
FloorNode n;
double d = 0.0;
if (!floor.NearestNode(x, y, &n, &d) || d > max_node_dist) continue;
if (std::fabs(n.pitch) < clamp_rad) continue;
const uint64_t k = PackFloorCell(static_cast<int32_t>(std::floor(x * inv)),
static_cast<int32_t>(std::floor(y * inv)));
if (!std::binary_search(seen.begin(), seen.end(), k)) continue;
v = 0;
++cleared;
}
}
return cleared;
}
void NodeCloudFromSensorData(const rtabmap::SensorData& data,
const VoxelExportOptions& opt,
std::vector<float>* out) {
@@ -298,11 +334,30 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
it = poses.count(it->first) ? std::next(it) : cache->nodes.erase(it);
}
// Di tren doc: diem dat o z THAT, va dai z cat theo SAN tai cho diem -- ca
// hai viec lam O DAY, nen bo gom nhan moi z. Cache diem cua node giu dai
// rong hon (mat doc xuong phia truoc o z am so voi node).
const bool use_floor = opt.node_z != nullptr && opt.floor != nullptr;
VoxelExportOptions acc_opt = opt;
if (use_floor) {
acc_opt.z_min = -1e9;
acc_opt.z_max = 1e9;
}
VoxelExportOptions node_opt = opt;
if (use_floor) {
node_opt.z_min = opt.z_min - 3.0;
node_opt.z_max = opt.z_max + 3.0;
}
if (cache->wide != use_floor) {
cache->nodes.clear();
cache->wide = use_floor;
}
// min_node_hits > 1: dem so node thay moi voxel (loc diem bay, nguoi di
// ngang). = 1: duong cu, re hon.
const bool count_hits = opt.min_node_hits > 1;
VoxelAccumulator acc(opt);
VoxelHitCounter hits(opt);
VoxelAccumulator acc(acc_opt);
VoxelHitCounter hits(acc_opt);
size_t nodes_used = 0, fetched = 0, pending = 0, no_points = 0;
for (const auto& kv : poses) {
@@ -320,7 +375,7 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
// moi node va ban do 3D im lang rong khong.
data.uncompressData();
std::vector<float> pts;
NodeCloudFromSensorData(data, opt, &pts);
NodeCloudFromSensorData(data, node_opt, &pts);
it = cache->nodes.emplace(kv.first, std::move(pts)).first;
}
const std::vector<float>& pts = it->second;
@@ -336,12 +391,31 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
const float r10 = T.r21(), r11 = T.r22(), r12 = T.r23(), ty = T.y();
const float r20 = T.r31(), r21 = T.r32(), r22 = T.r33(), tz = T.z();
double z_off = 0.0;
if (use_floor) {
const auto zi = opt.node_z->find(kv.first);
if (zi != opt.node_z->end()) z_off = zi->second;
}
if (count_hits) hits.BeginNode();
for (size_t i = 0; i + 2 < pts.size(); i += 3) {
const float px = pts[i], py = pts[i + 1], pz = pts[i + 2];
const double wx = r00 * px + r01 * py + r02 * pz + tx;
const double wy = r10 * px + r11 * py + r12 * pz + ty;
const double wz = r20 * px + r21 * py + r22 * pz + tz;
double wz = r20 * px + r21 * py + r22 * pz + tz;
if (use_floor) {
wz += z_off;
double f = z_off;
opt.floor->FloorAt(wx, wy, &f);
const double h = wz - f;
if (opt.floor_cells != nullptr && std::fabs(h) <= opt.floor_band) {
const double inv = 1.0 / opt.emit_size_m;
opt.floor_cells->push_back(
PackFloorCell(static_cast<int32_t>(std::floor(wx * inv)),
static_cast<int32_t>(std::floor(wy * inv))));
}
if (h < opt.z_min || h > opt.z_max) continue;
}
if (count_hits) hits.AddPoint(wx, wy, wz);
else acc.AddPoint(wx, wy, wz);
}