upload
This commit is contained in:
175
libs/vslam_slam/src/occupancy_export.cc
Normal file
175
libs/vslam_slam/src/occupancy_export.cc
Normal file
@@ -0,0 +1,175 @@
|
||||
#include "vslam/occupancy_export.h"
|
||||
|
||||
#include <rtabmap/core/DBDriver.h>
|
||||
#include <rtabmap/core/Memory.h>
|
||||
#include <rtabmap/core/LocalGrid.h>
|
||||
#include <rtabmap/core/Parameters.h>
|
||||
#include <rtabmap/core/Rtabmap.h>
|
||||
#include <rtabmap/core/SensorData.h>
|
||||
#include <rtabmap/core/global_map/OccupancyGrid.h>
|
||||
|
||||
#include <opencv2/core/core.hpp>
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/node_constants.h"
|
||||
#include "vslam/sensor_data_builder.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
// cv::Mat 8SC1 cua RTAB-Map -> vector<int8_t> theo quy uoc map_server:
|
||||
// -1 chua biet, 0 trong, 100 bi chiem
|
||||
// RTAB-Map dung 0=trong, 100=chiem, -1=chua biet o ma tran 8S, nen chi phai
|
||||
// lat truc y (RTAB-Map goc o duoi trai, giong ROS -- KHONG lat).
|
||||
void CopyGrid(const cv::Mat& m, OccupancyGrid* out) {
|
||||
out->width = static_cast<uint32_t>(m.cols);
|
||||
out->height = static_cast<uint32_t>(m.rows);
|
||||
out->data.resize(static_cast<size_t>(m.cols) * m.rows);
|
||||
for (int y = 0; y < m.rows; ++y) {
|
||||
const int8_t* row = m.ptr<int8_t>(y);
|
||||
std::copy(row, row + m.cols,
|
||||
out->data.begin() + static_cast<size_t>(y) * m.cols);
|
||||
}
|
||||
}
|
||||
|
||||
StatusResponse BuildFromCache(rtabmap::LocalGridCache& cache,
|
||||
const std::map<int, rtabmap::Transform>& poses,
|
||||
double cell_size, double range_max,
|
||||
OccupancyGrid* out) {
|
||||
if (poses.empty()) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition,
|
||||
"khong co pose nao de dung grid");
|
||||
}
|
||||
rtabmap::ParametersMap params;
|
||||
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridCellSize(),
|
||||
std::to_string(cell_size)));
|
||||
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGrid3D(), "false"));
|
||||
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridRangeMax(),
|
||||
std::to_string(range_max)));
|
||||
|
||||
rtabmap::OccupancyGrid grid(&cache, params);
|
||||
grid.update(poses);
|
||||
|
||||
float xmin = 0.0f, ymin = 0.0f;
|
||||
const cv::Mat m = grid.getMap(xmin, ymin);
|
||||
if (m.empty()) {
|
||||
return StatusResponse::Error(StatusCode::kInternal, "grid rong sau update()");
|
||||
}
|
||||
|
||||
CopyGrid(m, out);
|
||||
out->resolution = static_cast<float>(cell_size);
|
||||
out->origin = Pose{};
|
||||
out->origin.position.x = xmin;
|
||||
out->origin.position.y = ymin;
|
||||
out->origin.orientation.w = 1.0;
|
||||
out->header.frame_id = kMapFrame;
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
DbFacts InspectDatabase(const std::string& path) {
|
||||
DbFacts f;
|
||||
// Duong dan rong = DB trong RAM, chua ton tai gi. `openConnection("")` van
|
||||
// THANH CONG (no tao DB tam), nen khong chan o day thi moi kiem dieu kien
|
||||
// tien quyet deu chay tren mot DB rong va bao nham.
|
||||
if (path.empty()) return f;
|
||||
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
|
||||
if (driver == nullptr) return f;
|
||||
|
||||
// openConnection() NEM UException (qua UFATAL) khi duong dan khong mo duoc,
|
||||
// chu khong tra false. Khong bat o day thi mot duong dan go sai trong
|
||||
// slam.yaml lam SAP ca tien trinh thay vi tra ve mot thong bao doc duoc.
|
||||
try {
|
||||
if (!driver->openConnection(path, false)) return f;
|
||||
} catch (const std::exception&) {
|
||||
return f; // khong mo duoc = coi nhu chua ton tai; Init() se tao moi
|
||||
}
|
||||
f.exists = true;
|
||||
|
||||
std::set<int> ids;
|
||||
driver->getAllNodeIds(ids);
|
||||
f.nodes = static_cast<int>(ids.size());
|
||||
|
||||
// So tu vung. 0 nghia la ban do nay duoc quet voi visual_loop=false.
|
||||
// Dung id tu vung CUOI lam so dem: DBDriver khong cho dem truc tiep, va
|
||||
// cai ta can chi la phan biet "co tu vung" voi "khong co".
|
||||
int last_word = 0;
|
||||
driver->getLastWordId(last_word);
|
||||
f.words = last_word;
|
||||
|
||||
const rtabmap::ParametersMap db_params = driver->getLastParameters();
|
||||
auto it = db_params.find(rtabmap::Parameters::kOptimizerStrategy());
|
||||
if (it != db_params.end()) f.optimizer_strategy = it->second;
|
||||
|
||||
driver->closeConnection(false);
|
||||
return f;
|
||||
}
|
||||
|
||||
StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out) {
|
||||
const std::map<int, rtabmap::Transform> poses = slam.getLocalOptimizedPoses();
|
||||
if (poses.empty()) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition,
|
||||
"do thi chua co pose toi uu nao");
|
||||
}
|
||||
|
||||
rtabmap::LocalGridCache cache;
|
||||
for (const auto& kv : poses) {
|
||||
const rtabmap::Memory* mem = slam.getMemory();
|
||||
if (mem == nullptr) break;
|
||||
rtabmap::SensorData data = mem->getNodeData(kv.first, false, false, false, true);
|
||||
// BAT BUOC: du lieu trong DB la du lieu NEN. Khong goi cai nay thi
|
||||
// gridGroundCellsRaw() tra ma tran rong, im lang.
|
||||
data.uncompressData();
|
||||
if (data.gridCellSize() <= 0.0f) continue;
|
||||
cache.add(kv.first, data.gridGroundCellsRaw(), data.gridObstacleCellsRaw(),
|
||||
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
|
||||
}
|
||||
return BuildFromCache(cache, poses, 0.05, 12.0, out);
|
||||
}
|
||||
|
||||
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
|
||||
double cell_size, double range_max,
|
||||
OccupancyGrid* out) {
|
||||
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
|
||||
bool opened = false;
|
||||
try {
|
||||
opened = driver != nullptr && driver->openConnection(db_path, false);
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kNotFound,
|
||||
"khong mo duoc DB " + db_path + ": " + e.what());
|
||||
}
|
||||
if (!opened) {
|
||||
return StatusResponse::Error(StatusCode::kNotFound, "khong mo duoc DB: " + db_path);
|
||||
}
|
||||
|
||||
const std::map<int, rtabmap::Transform> poses = driver->loadOptimizedPoses();
|
||||
rtabmap::LocalGridCache cache;
|
||||
int with_grid = 0;
|
||||
|
||||
for (const auto& kv : poses) {
|
||||
rtabmap::SensorData data;
|
||||
driver->getNodeData(kv.first, data, false, false, false, true);
|
||||
// Xem ghi chu o dau file: KHONG co dong nay thi cache rong va grid ra
|
||||
// 0x0, khong loi nao duoc bao.
|
||||
data.uncompressData();
|
||||
if (data.gridCellSize() <= 0.0f) continue;
|
||||
cache.add(kv.first, data.gridGroundCellsRaw(), data.gridObstacleCellsRaw(),
|
||||
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
|
||||
with_grid++;
|
||||
}
|
||||
driver->closeConnection(false);
|
||||
|
||||
if (with_grid == 0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"khong node nao co local grid -- ban do quet voi Grid/FromDepth sai?");
|
||||
}
|
||||
return BuildFromCache(cache, poses, cell_size, range_max, out);
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
159
libs/vslam_slam/src/rtabmap_params.cc
Normal file
159
libs/vslam_slam/src/rtabmap_params.cc
Normal file
@@ -0,0 +1,159 @@
|
||||
#include "vslam/rtabmap_params.h"
|
||||
|
||||
#include <rtabmap/core/Optimizer.h>
|
||||
#include <rtabmap/core/Parameters.h>
|
||||
|
||||
#include "vslam/log.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
const char* SlamModeName(SlamMode m) {
|
||||
switch (m) {
|
||||
case SlamMode::kMapping: return "mapping";
|
||||
case SlamMode::kLocalization: return "localization";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
bool OptimizerAvailable(const std::string& strategy) {
|
||||
int s = 1;
|
||||
try {
|
||||
s = std::stoi(strategy);
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
switch (s) {
|
||||
case 0: return rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeTORO);
|
||||
case 1: return rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeG2O);
|
||||
case 2: return rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeGTSAM);
|
||||
case 3: return rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeCeres);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> BuildRtabmapParams(
|
||||
const RtabmapConfig& cfg, std::vector<std::string>* unknown) {
|
||||
const rtabmap::ParametersMap defaults = rtabmap::Parameters::getDefaultParameters();
|
||||
|
||||
std::map<std::string, std::string> out(defaults.begin(), defaults.end());
|
||||
|
||||
// --- 1. Mac dinh cua DU AN NAY, tren mac dinh cua RTAB-Map ---
|
||||
// Day la 26 key trong rtabmap.launch. Chung o day chu khong o YAML vi
|
||||
// chung la HE QUA cua kien truc (2.5D, LiDAR la trong tai) chu khong phai
|
||||
// lua chon van hanh. YAML chi de tinh chinh.
|
||||
const std::pair<const char*, const char*> project_defaults[] = {
|
||||
// 2.5D: pose la SE(2), khong uoc luong 6-DoF.
|
||||
// 0.21 gop Optimizer/Slam2D vao Reg/Force3DoF -- dat ca hai thi no
|
||||
// canh bao va bo qua cai cu, nen chi giu mot.
|
||||
{"Reg/Force3DoF", "true"},
|
||||
// 1 = ICP. LiDAR la trong tai, ke ca khi tui tu thi giac bat.
|
||||
{"Reg/Strategy", "1"},
|
||||
{"Icp/PointToPlane", "false"}, // scan 2D, khong co phap tuyen
|
||||
{"Icp/VoxelSize", "0.05"},
|
||||
{"Icp/MaxCorrespondenceDistance", "0.15"},
|
||||
{"Icp/Iterations", "30"},
|
||||
{"Icp/Epsilon", "0.001"},
|
||||
{"Icp/CorrespondenceRatio", "0.3"},
|
||||
{"Icp/MaxTranslation", "0.5"},
|
||||
{"RGBD/NeighborLinkRefining", "true"},
|
||||
{"RGBD/ProximityBySpace", "true"},
|
||||
{"RGBD/ProximityPathMaxNeighbors", "10"},
|
||||
{"RGBD/OptimizeFromGraphEnd", "false"},
|
||||
{"RGBD/LinearUpdate", "0.1"},
|
||||
{"RGBD/AngularUpdate", "0.1"},
|
||||
|
||||
// ⚠️ BAT BUOC. Mac dinh cua RTAB-Map la `false`.
|
||||
//
|
||||
// Khong co dong nay, RTAB-Map KHONG dung luoi occupancy cho tung node.
|
||||
// Do thi van lon, vong dong van chay, `map_version` van tang -- nhung
|
||||
// `ExportMap()` tra ve mot luoi TOAN O CHUA BIET. Do duoc: quet 25 giay
|
||||
// roi xuat ra 94x21 o voi 0 bi chiem, 0 trong, 1974 chua biet.
|
||||
//
|
||||
// Trieu chung o web UI la mot tam xam dac lon dan ma khong bao gio co
|
||||
// noi dung -- trong het nhu "khung SLAM khong realtime", va do la huong
|
||||
// da di sai mot luc truoc khi tim ra cho nay.
|
||||
//
|
||||
// `map_hospital.db` co luoi vi rtabmap_ros dat tham so nay; wrapper cua
|
||||
// ta phai tu dat.
|
||||
{"RGBD/CreateOccupancyGrid", "true"},
|
||||
|
||||
// Grid/Sensor la INT: 0 = laser scan, 1 = depth, 2 = ca hai.
|
||||
// (`"false"` cung ra 0 qua atoi, nhung viet "0" cho dung kieu.)
|
||||
{"Grid/Sensor", "0"},
|
||||
{"Grid/CellSize", "0.05"},
|
||||
{"Grid/RangeMax", "12.0"},
|
||||
{"Grid/RayTracing", "true"},
|
||||
{"Grid/3D", "false"},
|
||||
{"Grid/DepthDecimation", "4"},
|
||||
{"Rtabmap/TimeThr", "0"},
|
||||
{"Rtabmap/MemoryThr", "0"},
|
||||
{"Rtabmap/DetectionRate", "1"},
|
||||
};
|
||||
for (const auto& kv : project_defaults) out[kv.first] = kv.second;
|
||||
|
||||
// --- 2. Ghi de tu YAML ---
|
||||
// Kiem TRUOC khi ap: go sai ten key RTAB-Map hien tai khong bao loi gi, no
|
||||
// bi bo qua im lang va he chay bang mac dinh.
|
||||
for (const auto& kv : cfg.overrides) {
|
||||
if (defaults.find(kv.first) == defaults.end()) {
|
||||
if (unknown != nullptr) unknown->push_back(kv.first);
|
||||
continue;
|
||||
}
|
||||
out[kv.first] = kv.second;
|
||||
}
|
||||
|
||||
// --- 3. Suy dien tu mode va co, GHI DE LEN CA YAML ---
|
||||
// Cac gia tri nay khong duoc phep bi YAML ghi de: chung la he qua truc tiep
|
||||
// cua mode. Mot file YAML dat Mem/IncrementalMemory=true trong khi goi
|
||||
// chay o che do localization se lam hong ban do da quet.
|
||||
out["Mem/IncrementalMemory"] =
|
||||
(cfg.mode == SlamMode::kMapping) ? "true" : "false";
|
||||
// Localization: nap toan bo node vao working memory ngay tu dau, neu khong
|
||||
// thi vung chua tung den se khong duoc xet toi khi dinh vi lai.
|
||||
out["Mem/InitWMWithAllNodes"] =
|
||||
(cfg.mode == SlamMode::kLocalization) ? "true" : "false";
|
||||
|
||||
// Kp/MaxFeatures: -1 = tat han tui tu. >0 = so dac trung moi anh.
|
||||
out["Kp/MaxFeatures"] = cfg.visual_loop ? "400" : "-1";
|
||||
|
||||
// Optimizer: dat TUONG MINH, luon luon.
|
||||
//
|
||||
// DB hien co (`map_house.db`) luu Optimizer/Strategy=2 (GTSAM). Tren Jetson
|
||||
// build voi -DWITH_GTSAM=OFF thi neu de RTAB-Map doc lai tham so tu DB no
|
||||
// se chon GTSAM va crash thieu symbol. Vi the:
|
||||
// - init(..., loadDatabaseParameters = FALSE), va
|
||||
// - ghi de Optimizer/Strategy o day, va
|
||||
// - assert sau init (xem RtabmapSlam::Init).
|
||||
// Ba lop, vi mot lop khong du: chinh ham init() la cho de lot.
|
||||
out["Optimizer/Strategy"] = cfg.optimizer_strategy;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
RtabmapConfig LoadRtabmapConfig(const ConfigNode& node) {
|
||||
RtabmapConfig cfg;
|
||||
|
||||
cfg.enabled = node.get<bool>("enabled", false);
|
||||
|
||||
const std::string mode = node.get<std::string>("mode", "mapping");
|
||||
cfg.mode = (mode == "localization") ? SlamMode::kLocalization : SlamMode::kMapping;
|
||||
|
||||
// database_path la require<>: khong co duong dan DB thi khong co gi de
|
||||
// lam, va mot mac dinh im lang se ghi ban do vao cho khong ai tim thay.
|
||||
cfg.database_path = node.require<std::string>("database_path");
|
||||
|
||||
cfg.visual_loop = node.get<bool>("visual_loop", false);
|
||||
cfg.camera_3d = node.get<bool>("camera_3d", false);
|
||||
cfg.optimizer_strategy = node.get<std::string>("optimizer_strategy", "1");
|
||||
|
||||
// Khoi `rtabmap:` di thang vao ParametersMap, giu nguyen van. Khong kiem
|
||||
// kieu o day -- RTAB-Map nhan moi thu la chuoi. Cai PHAI kiem la TEN key,
|
||||
// va viec do lam trong BuildRtabmapParams().
|
||||
const ConfigNode block = node["rtabmap"];
|
||||
if (!block.IsNull()) {
|
||||
for (const auto& kv : block.AsStringMap()) cfg.overrides[kv.first] = kv.second;
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
322
libs/vslam_slam/src/rtabmap_slam.cc
Normal file
322
libs/vslam_slam/src/rtabmap_slam.cc
Normal file
@@ -0,0 +1,322 @@
|
||||
#include "vslam/rtabmap_slam.h"
|
||||
|
||||
#include <rtabmap/core/Optimizer.h>
|
||||
#include <rtabmap/core/Parameters.h>
|
||||
#include <rtabmap/core/Rtabmap.h>
|
||||
#include <rtabmap/core/Statistics.h>
|
||||
#include <rtabmap/utilite/ULogger.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
|
||||
#include "vslam/geometry.h"
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/occupancy_export.h"
|
||||
#include "vslam/sensor_data_builder.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
class RtabmapSlamImpl {
|
||||
public:
|
||||
RtabmapConfig cfg;
|
||||
rtabmap::Rtabmap rtabmap;
|
||||
bool inited = false;
|
||||
int next_id = 1;
|
||||
|
||||
Transform laser_to_base = TransformIdentity();
|
||||
Transform camera_to_base = TransformIdentity();
|
||||
|
||||
// ===== Bien duoc doc TU LUONG KHAC =====
|
||||
// Chi mutex NAY duoc chia se ra ngoai, va no chi bao ve bon so o duoi.
|
||||
// `rtabmap` KHONG nam duoi no: Process() chan 100-600 ms, va mot luong
|
||||
// khac doi mutex do la du lam ke cho luong safety bi treo theo. Xem
|
||||
// ghi chu dau rtabmap_slam.h.
|
||||
mutable std::mutex out_mu;
|
||||
Pose2D map_correction;
|
||||
bool localized = false;
|
||||
uint64_t map_version = 0;
|
||||
|
||||
SlamStats stats;
|
||||
|
||||
void RecordMs(double ms) {
|
||||
stats.last_ms = ms;
|
||||
stats.max_ms = std::max(stats.max_ms, ms);
|
||||
// Giu mau de tinh p95. Trung binh vo nghia o day: phan phoi co duoi rat
|
||||
// dai (khung co vong dong dat gap 10 lan khung thuong), va chi tieu tren
|
||||
// Jetson la p95 < 700 ms chu khong phai trung binh.
|
||||
stats.samples.push_back(ms);
|
||||
if (stats.samples.size() > 4096) {
|
||||
stats.samples.erase(stats.samples.begin(),
|
||||
stats.samples.begin() + 2048);
|
||||
}
|
||||
std::vector<double> sorted = stats.samples;
|
||||
const size_t k = static_cast<size_t>(0.95 * (sorted.size() - 1));
|
||||
std::nth_element(sorted.begin(), sorted.begin() + static_cast<long>(k), sorted.end());
|
||||
stats.p95_ms = sorted[k];
|
||||
}
|
||||
};
|
||||
|
||||
RtabmapSlam::RtabmapSlam() : impl_(new RtabmapSlamImpl) {}
|
||||
RtabmapSlam::~RtabmapSlam() { Close(false); }
|
||||
|
||||
void RtabmapSlam::SetExtrinsics(const Transform& laser_to_base,
|
||||
const Transform& camera_to_base) {
|
||||
impl_->laser_to_base = laser_to_base;
|
||||
impl_->camera_to_base = camera_to_base;
|
||||
}
|
||||
|
||||
SlamMode RtabmapSlam::mode() const { return impl_->cfg.mode; }
|
||||
const SlamStats& RtabmapSlam::stats() const { return impl_->stats; }
|
||||
|
||||
Pose2D RtabmapSlam::map_correction() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->out_mu);
|
||||
return impl_->map_correction;
|
||||
}
|
||||
bool RtabmapSlam::localized() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->out_mu);
|
||||
return impl_->localized;
|
||||
}
|
||||
uint64_t RtabmapSlam::map_version() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->out_mu);
|
||||
return impl_->map_version;
|
||||
}
|
||||
|
||||
StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
if (impl_->inited) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da init roi");
|
||||
}
|
||||
impl_->cfg = cfg;
|
||||
|
||||
// ULogger cua RTAB-Map mac dinh in thang ra stdout va rat on. Day ve ERROR;
|
||||
// thong tin can thiet da co trong SlamOutput va stats.
|
||||
ULogger::setType(ULogger::kTypeNoLog);
|
||||
ULogger::setLevel(ULogger::kError);
|
||||
|
||||
// --- Kiem TRUOC khi chay, khong phai sau ---
|
||||
if (!OptimizerAvailable(cfg.optimizer_strategy)) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"Optimizer/Strategy=" + cfg.optimizer_strategy +
|
||||
" khong duoc build vao librtabmap_core. Tren Jetson build voi "
|
||||
"-DWITH_GTSAM=OFF thi chi co \"1\" (g2o).");
|
||||
}
|
||||
|
||||
std::vector<std::string> unknown;
|
||||
std::map<std::string, std::string> params = BuildRtabmapParams(cfg, &unknown);
|
||||
if (!unknown.empty()) {
|
||||
// Key la la LOI KHOI DONG, khong phai canh bao. Go sai ten key RTAB-Map
|
||||
// bi bo qua im lang va he chay bang mac dinh -- `Reg/Force3DoF` go thanh
|
||||
// `Reg/Force3Dof` nghia la pose thanh 6-DoF ma khong ai biet.
|
||||
std::string msg = "key RTAB-Map khong ton tai:";
|
||||
for (const std::string& k : unknown) msg += " " + k;
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, msg);
|
||||
}
|
||||
|
||||
const DbFacts facts = InspectDatabase(cfg.database_path);
|
||||
if (cfg.mode == SlamMode::kLocalization) {
|
||||
// Localization can mot ban do DA CO. Khong co thi no chay im lang ma
|
||||
// khong bao gio dinh vi duoc vao dau -- da do: process_ms 0.3-2.4 ms va
|
||||
// map->odom luon bang 0, trong nhu "SLAM dang chay tot".
|
||||
//
|
||||
// Duong dan rong = DB trong RAM = chac chan khong co ban do.
|
||||
if (cfg.database_path.empty()) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"che do localization nhung database_path de rong (DB trong RAM). "
|
||||
"Localization can mot ban do da quet; dung mode: mapping de quet moi.");
|
||||
}
|
||||
if (!facts.exists || facts.nodes == 0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"che do localization nhung DB khong co node nao: " + cfg.database_path);
|
||||
}
|
||||
}
|
||||
if (cfg.visual_loop && facts.exists && facts.words == 0) {
|
||||
// Co `visual_loop` phai KHOP voi luc quet map. Bat thi giac tren mot DB
|
||||
// quet khong co tu vung se ton CPU trich dac trung ma khong bao gio dong
|
||||
// duoc vong nao -- im lang va tot tien.
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"visual_loop=true nhung DB khong co tu vung (Word = 0). Ban do nay "
|
||||
"duoc quet voi visual_loop=false; hai co phai khop nhau.");
|
||||
}
|
||||
if (facts.exists && facts.optimizer_strategy != cfg.optimizer_strategy) {
|
||||
VSLAM_WARN("slam: DB luu Optimizer/Strategy=" << facts.optimizer_strategy
|
||||
<< ", dang ep ve " << cfg.optimizer_strategy
|
||||
<< " (loadDatabaseParameters=false)");
|
||||
}
|
||||
|
||||
// ⚠️ QUET TIEP vao mot DB DA CO node thi RTAB-Map 0.21.13 HONG.
|
||||
//
|
||||
// Moi lan `process()` deu nem:
|
||||
// DBDriverSqlite3.cpp:4854::addStatisticsQuery() Condition (rc ==
|
||||
// SQLITE_DONE) not met! [UNIQUE constraint failed: Statistics.id]
|
||||
//
|
||||
// Da do: 60 giay lai, `map_version` dung yen o 0, khong mot khung ban do
|
||||
// nao duoc dung. Tien trinh KHONG chet (moi loi goi vao RTAB-Map deu boc
|
||||
// try/catch), nen tu ngoai nhin vao SLAM "dang chay" -- dung kieu hong tệ
|
||||
// nhat: nguoi van hanh lai het ca tang roi moi biet khong co gi duoc luu.
|
||||
//
|
||||
// Localization tren CHINH DB do thi chay sach: 0 ngoai le, map_version len
|
||||
// deu, sai so 0.004 m. Nen day khong phai loi cua DB.
|
||||
//
|
||||
// Chan tai day, khong de no chay roi hong.
|
||||
if (cfg.mode == SlamMode::kMapping && facts.exists && facts.nodes > 0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"mapping vao DB da co " + std::to_string(facts.nodes) +
|
||||
" node: RTAB-Map 0.21.13 nem 'UNIQUE constraint failed: "
|
||||
"Statistics.id' o MOI khung va khong dung duoc ban do nao.\n"
|
||||
" - Quet lai tu dau : --slam-db <duong dan MOI>\n"
|
||||
" - Dung ban do nay : --slam-mode localization "
|
||||
"--slam-init-pose x,y,yaw");
|
||||
}
|
||||
|
||||
rtabmap::ParametersMap pm(params.begin(), params.end());
|
||||
try {
|
||||
// loadDatabaseParameters = FALSE, luon luon.
|
||||
//
|
||||
// map_house.db luu Optimizer/Strategy=2 (GTSAM). Neu de RTAB-Map doc lai
|
||||
// tham so tu DB thi tren Jetson build -DWITH_GTSAM=OFF no se chon GTSAM
|
||||
// va crash thieu symbol.
|
||||
impl_->rtabmap.init(pm, cfg.database_path, /*loadDatabaseParameters=*/false);
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInternal,
|
||||
std::string("rtabmap init: ") + e.what());
|
||||
}
|
||||
|
||||
// --- Assert SAU init ---
|
||||
// Lop thu ba. init() la chinh cho de lot: no co the tu sua tham so khi nap
|
||||
// DB, va khi do hai lop tren deu vo nghia.
|
||||
const rtabmap::ParametersMap& actual = impl_->rtabmap.getParameters();
|
||||
auto it = actual.find(rtabmap::Parameters::kOptimizerStrategy());
|
||||
if (it != actual.end() && it->second != cfg.optimizer_strategy) {
|
||||
impl_->rtabmap.close(false);
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInternal,
|
||||
"sau init, Optimizer/Strategy = " + it->second + " chu khong phai " +
|
||||
cfg.optimizer_strategy + " -- init() da doc tham so tu DB");
|
||||
}
|
||||
|
||||
impl_->inited = true;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->out_mu);
|
||||
impl_->map_version = 1;
|
||||
}
|
||||
VSLAM_INFO("slam: " << SlamModeName(cfg.mode) << ", DB "
|
||||
<< (cfg.database_path.empty() ? "(RAM)" : cfg.database_path)
|
||||
<< " (" << facts.nodes << " node, " << facts.words
|
||||
<< " tu vung), optimizer " << cfg.optimizer_strategy);
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
SlamOutput RtabmapSlam::Process(const SlamInput& in) {
|
||||
SlamOutput out;
|
||||
out.stamp = in.stamp;
|
||||
impl_->stats.frames_in++;
|
||||
|
||||
if (!impl_->inited) return out;
|
||||
if (in.scan == nullptr || in.scan->ranges.empty()) return out;
|
||||
|
||||
// steady_clock cho do thoi luong -- KHONG UnixTime. Mot buoc NTP giua hai
|
||||
// moc se cho ra "khung xu ly het -3 giay".
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
|
||||
rtabmap::SensorData data =
|
||||
BuildSensorData(in, impl_->laser_to_base, impl_->camera_to_base, impl_->next_id++);
|
||||
|
||||
bool ok = false;
|
||||
try {
|
||||
ok = impl_->rtabmap.process(data, ToRtabmap(in.odom),
|
||||
static_cast<float>(in.odom_linear_var),
|
||||
static_cast<float>(in.odom_angular_var));
|
||||
} catch (const std::exception& e) {
|
||||
VSLAM_ERROR("slam: process nem: " << e.what());
|
||||
return out;
|
||||
}
|
||||
|
||||
out.process_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
|
||||
.count();
|
||||
impl_->RecordMs(out.process_ms);
|
||||
|
||||
// ok=false nghia la RTAB-Map BO QUA khung nay (chua du chuyen dong theo
|
||||
// RGBD/LinearUpdate). Do KHONG phai loi, va map_correction cu van dung.
|
||||
out.processed = ok;
|
||||
if (!ok) {
|
||||
std::lock_guard<std::mutex> lk(impl_->out_mu);
|
||||
out.map_correction = impl_->map_correction;
|
||||
out.pose_map = Pose2DCompose(out.map_correction, in.odom);
|
||||
out.localized = impl_->localized;
|
||||
out.map_version = impl_->map_version;
|
||||
return out;
|
||||
}
|
||||
|
||||
impl_->stats.frames_processed++;
|
||||
out.loop_closure_id = impl_->rtabmap.getLoopClosureId();
|
||||
const rtabmap::Statistics& st = impl_->rtabmap.getStatistics();
|
||||
auto stat = [&](const std::string& k, double dflt) {
|
||||
auto i = st.data().find(k);
|
||||
return i == st.data().end() ? dflt : static_cast<double>(i->second);
|
||||
};
|
||||
out.proximity_id = static_cast<int>(
|
||||
stat(rtabmap::Statistics::kProximitySpace_last_detection_id(), 0.0));
|
||||
out.score = impl_->rtabmap.getHighestHypothesisValue();
|
||||
out.nodes_wm = static_cast<int>(impl_->rtabmap.getWMSize());
|
||||
|
||||
if (out.loop_closure_id > 0) impl_->stats.loop_closures++;
|
||||
if (out.proximity_id > 0) impl_->stats.proximity_links++;
|
||||
|
||||
const Pose2D corr = FromRtabmap(impl_->rtabmap.getMapCorrection());
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->out_mu);
|
||||
impl_->map_correction = corr;
|
||||
// "Da dinh vi" o che do localization = da co it nhat mot lien ket toi
|
||||
// ban do cu. `getLastLocalizationPose()` rong nghia la chua bao gio.
|
||||
impl_->localized =
|
||||
(impl_->cfg.mode == SlamMode::kMapping) ||
|
||||
!impl_->rtabmap.getLastLocalizationPose().isNull();
|
||||
// Do thi doi -> web phai gui lai map. Chi tang khi CO li do: moi khung
|
||||
// deu tang thi client tai lai map do 2000x2000 moi giay.
|
||||
if (out.loop_closure_id > 0 || out.proximity_id > 0 ||
|
||||
impl_->cfg.mode == SlamMode::kMapping) {
|
||||
impl_->map_version++;
|
||||
}
|
||||
out.map_correction = impl_->map_correction;
|
||||
out.localized = impl_->localized;
|
||||
out.map_version = impl_->map_version;
|
||||
}
|
||||
out.pose_map = Pose2DCompose(out.map_correction, in.odom);
|
||||
return out;
|
||||
}
|
||||
|
||||
StatusResponse RtabmapSlam::SetInitialPose(const Pose2D& pose) {
|
||||
if (!impl_->inited) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
|
||||
}
|
||||
impl_->rtabmap.setInitialPose(ToRtabmap(pose));
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
StatusResponse RtabmapSlam::ExportMap(OccupancyGrid* out) {
|
||||
if (!impl_->inited) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
|
||||
}
|
||||
return ExportOccupancyGrid(impl_->rtabmap, out);
|
||||
}
|
||||
|
||||
StatusResponse RtabmapSlam::Close(bool save_database) {
|
||||
if (!impl_->inited) return StatusResponse::Ok();
|
||||
impl_->inited = false;
|
||||
try {
|
||||
impl_->rtabmap.close(save_database);
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInternal,
|
||||
std::string("rtabmap close: ") + e.what());
|
||||
}
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
143
libs/vslam_slam/src/sensor_data_builder.cc
Normal file
143
libs/vslam_slam/src/sensor_data_builder.cc
Normal file
@@ -0,0 +1,143 @@
|
||||
#include "vslam/sensor_data_builder.h"
|
||||
|
||||
#include <opencv2/core/core.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/geometry.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
rtabmap::Transform ToRtabmap(const Pose2D& p) {
|
||||
return rtabmap::Transform(static_cast<float>(p.x), static_cast<float>(p.y), 0.0f,
|
||||
0.0f, 0.0f, static_cast<float>(p.theta));
|
||||
}
|
||||
|
||||
Pose2D FromRtabmap(const rtabmap::Transform& t) {
|
||||
Pose2D p;
|
||||
if (t.isNull()) return p;
|
||||
p.x = t.x();
|
||||
p.y = t.y();
|
||||
float roll, pitch, yaw;
|
||||
t.getEulerAngles(roll, pitch, yaw);
|
||||
p.theta = yaw;
|
||||
return p;
|
||||
}
|
||||
|
||||
rtabmap::Transform ToRtabmap(const Transform& t) {
|
||||
double roll, pitch, yaw;
|
||||
RPYFromQuaternion(t.rotation, &roll, &pitch, &yaw);
|
||||
return rtabmap::Transform(
|
||||
static_cast<float>(t.translation.x), static_cast<float>(t.translation.y),
|
||||
static_cast<float>(t.translation.z), static_cast<float>(roll),
|
||||
static_cast<float>(pitch), static_cast<float>(yaw));
|
||||
}
|
||||
|
||||
Transform TransformFromRtabmap(const rtabmap::Transform& t) {
|
||||
Transform out = TransformIdentity();
|
||||
if (t.isNull()) return out;
|
||||
out.translation = Vector3{t.x(), t.y(), t.z()};
|
||||
float roll, pitch, yaw;
|
||||
t.getEulerAngles(roll, pitch, yaw);
|
||||
out.rotation = QuaternionFromRPY(roll, pitch, yaw);
|
||||
return out;
|
||||
}
|
||||
|
||||
rtabmap::LaserScan BuildLaserScan(const LaserScan& scan,
|
||||
const Transform& laser_to_base) {
|
||||
// rtabmap::LaserScan::init() NEM UException khi hinh hoc goc suy bien
|
||||
// (angleIncrement <= 0, hoac angleMax <= angleMin). Mot scan hong tu driver
|
||||
// -- header toan 0, hoac mot sweep thieu goi lam angle_max bang angle_min --
|
||||
// se lam SAP luong SLAM. Chan o day va tra scan rong: RTAB-Map bo qua khung
|
||||
// khong co scan, con tien trinh thi song.
|
||||
if (!(scan.angle_increment > 0.0) || !(scan.angle_max > scan.angle_min) ||
|
||||
!(scan.range_max > scan.range_min)) {
|
||||
return rtabmap::LaserScan();
|
||||
}
|
||||
|
||||
const size_t n = scan.ranges.size();
|
||||
std::vector<cv::Vec2f> pts;
|
||||
pts.reserve(n);
|
||||
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const float r = scan.ranges[i];
|
||||
|
||||
// BA NGU NGHIA, bo het ca ba:
|
||||
// NaN = khong do duoc
|
||||
// inf = khong co phan xa (hanh lang rong) -- KHONG phai diem o xa
|
||||
// >= range_max = sentinel do sector mask cat
|
||||
// Bien `inf` thanh mot diem o range_max se dung mot buc tuong ao quanh
|
||||
// robot, va ICP se khop vao buc tuong ao do thay vi vao tuong that.
|
||||
if (!std::isfinite(r)) continue;
|
||||
if (r < scan.range_min || r >= scan.range_max) continue;
|
||||
|
||||
const double a = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
|
||||
pts.emplace_back(static_cast<float>(r * std::cos(a)),
|
||||
static_cast<float>(r * std::sin(a)));
|
||||
}
|
||||
|
||||
if (pts.empty()) return rtabmap::LaserScan();
|
||||
|
||||
// CV_32FC2, mot HANG -- RTAB-Map mong doi 1xN, khong phai Nx1.
|
||||
cv::Mat data(1, static_cast<int>(pts.size()), CV_32FC2);
|
||||
std::memcpy(data.data, pts.data(), pts.size() * sizeof(cv::Vec2f));
|
||||
|
||||
return rtabmap::LaserScan(data, rtabmap::LaserScan::kXY,
|
||||
static_cast<float>(scan.range_min),
|
||||
static_cast<float>(scan.range_max),
|
||||
static_cast<float>(scan.angle_min),
|
||||
static_cast<float>(scan.angle_max),
|
||||
static_cast<float>(scan.angle_increment),
|
||||
ToRtabmap(laser_to_base));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Image POD -> cv::Mat. KHONG copy du lieu: cv::Mat bao boc con tro san co,
|
||||
// nen `img` phai song qua het loi goi Process().
|
||||
cv::Mat WrapImage(const Image& img) {
|
||||
int type = CV_8UC1;
|
||||
if (img.format == PixelFormat::kMono16) type = CV_16UC1;
|
||||
else if (img.format == PixelFormat::kFloat32) type = CV_32FC1;
|
||||
return cv::Mat(static_cast<int>(img.height), static_cast<int>(img.width), type,
|
||||
const_cast<uint8_t*>(img.data), static_cast<size_t>(img.step));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
rtabmap::SensorData BuildSensorData(const SlamInput& in,
|
||||
const Transform& laser_to_base,
|
||||
const Transform& camera_to_base, int id) {
|
||||
const rtabmap::LaserScan scan =
|
||||
in.scan != nullptr ? BuildLaserScan(*in.scan, laser_to_base) : rtabmap::LaserScan();
|
||||
|
||||
cv::Mat rgb, depth;
|
||||
std::vector<rtabmap::CameraModel> models;
|
||||
|
||||
if (in.depth != nullptr && in.depth_info != nullptr && in.depth->data != nullptr) {
|
||||
depth = WrapImage(*in.depth);
|
||||
// D410 KHONG CO RGB -> dung anh IR trai lam kenh "rgb" (mono8), y het
|
||||
// ban ROS remap /camera/infra1/image_rect_raw -> rgb/image.
|
||||
if (in.infra1 != nullptr && in.infra1->data != nullptr) {
|
||||
rgb = WrapImage(*in.infra1);
|
||||
} else {
|
||||
// Khong co anh -> anh xam rong cung kich thuoc. RTAB-Map can rgb va
|
||||
// depth CUNG kich thuoc; dua anh rong thi no bo qua ca cap.
|
||||
rgb = cv::Mat::zeros(depth.rows, depth.cols, CV_8UC1);
|
||||
}
|
||||
// fx/fy/cx/cy DA BU BINNING -- crop_decimate cap nhat binning chu khong
|
||||
// chia lai K. Quen bu la moi diem lech theo he so decimate.
|
||||
models.emplace_back(in.depth_info->fx_binned(), in.depth_info->fy_binned(),
|
||||
in.depth_info->cx_binned(), in.depth_info->cy_binned(),
|
||||
ToRtabmap(camera_to_base), 0.0,
|
||||
cv::Size(static_cast<int>(in.depth->width),
|
||||
static_cast<int>(in.depth->height)));
|
||||
}
|
||||
|
||||
rtabmap::SensorData data(scan, rgb, depth, models, id, in.stamp.toSec());
|
||||
return data;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
Reference in New Issue
Block a user