upload
This commit is contained in:
25
libs/vslam_slam/CMakeLists.txt
Normal file
25
libs/vslam_slam/CMakeLists.txt
Normal file
@@ -0,0 +1,25 @@
|
||||
# Lib kho build nhat tren arm64. Tat bang -DVSLAM_BUILD_SLAM=OFF thi sau lib
|
||||
# kia van build -- do la ca ly do tach lib theo tap dependency thay vi theo
|
||||
# chuc nang.
|
||||
#
|
||||
# OpenCV: tren Jetson PHAI dung ban cua JetPack, KHONG cai libopencv-dev.
|
||||
# Hai ban OpenCV cung luc la nguon loi link/runtime kinh dien. Pin OpenCV_DIR.
|
||||
|
||||
find_package(RTABMap REQUIRED)
|
||||
find_package(OpenCV REQUIRED)
|
||||
|
||||
vslam_add_library(vslam_slam
|
||||
PUBLIC_HDRS
|
||||
slam_types.h
|
||||
rtabmap_params.h
|
||||
rtabmap_slam.h
|
||||
sensor_data_builder.h
|
||||
occupancy_export.h
|
||||
FIND_DEPS
|
||||
vslam_common
|
||||
RTABMap
|
||||
OpenCV
|
||||
)
|
||||
|
||||
target_link_libraries(vslam_slam PUBLIC vslam_common rtabmap::core ${OpenCV_LIBS})
|
||||
target_include_directories(vslam_slam SYSTEM PUBLIC ${OpenCV_INCLUDE_DIRS})
|
||||
43
libs/vslam_slam/include/vslam/occupancy_export.h
Normal file
43
libs/vslam_slam/include/vslam/occupancy_export.h
Normal file
@@ -0,0 +1,43 @@
|
||||
#ifndef VSLAM_OCCUPANCY_EXPORT_H
|
||||
#define VSLAM_OCCUPANCY_EXPORT_H
|
||||
|
||||
// Dung occupancy grid 2D tu do thi RTAB-Map, xuat ra struct POD.
|
||||
//
|
||||
// ================== BAY DA MAC MOT LAN ==================
|
||||
// RTAB-Map luu du lieu NEN trong SensorData. `gridGroundCellsRaw()` va
|
||||
// `gridObstacleCellsRaw()` tra ve ma tran RONG -- im lang, khong loi, khong
|
||||
// canh bao -- cho toi khi goi `uncompressDataConst()`. Do dung la ly do
|
||||
// `tools/probe_rtabmap` lan dau chay ra "1990 node, 0 o".
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace rtabmap {
|
||||
class Rtabmap;
|
||||
}
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Nhung gi doc duoc tu DB TRUOC khi init. Dung de kiem dieu kien tien quyet
|
||||
// ma khong phai mo ca do thi.
|
||||
struct DbFacts {
|
||||
bool exists = false;
|
||||
int nodes = 0;
|
||||
int words = 0; // 0 = ban do quet KHONG co tu vung
|
||||
std::string optimizer_strategy; // tham so DB nho, co the khac cai ta ep
|
||||
};
|
||||
|
||||
DbFacts InspectDatabase(const std::string& path);
|
||||
|
||||
StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out);
|
||||
|
||||
// Doc thang tu DB, khong can Rtabmap dang chay. Dung cho
|
||||
// `tools/vslam_slam_bench` va cho viec doi DB cu sang PGM.
|
||||
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
|
||||
double cell_size, double range_max,
|
||||
OccupancyGrid* out);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_OCCUPANCY_EXPORT_H
|
||||
64
libs/vslam_slam/include/vslam/rtabmap_params.h
Normal file
64
libs/vslam_slam/include/vslam/rtabmap_params.h
Normal file
@@ -0,0 +1,64 @@
|
||||
#ifndef VSLAM_RTABMAP_PARAMS_H
|
||||
#define VSLAM_RTABMAP_PARAMS_H
|
||||
|
||||
// 26 key cua RTAB-Map tro thanh DU LIEU YAML thay vi <param> rai rac trong
|
||||
// rtabmap.launch.
|
||||
//
|
||||
// ================== VI SAO PHAI KIEM TEN KEY ==================
|
||||
// Go sai ten mot key RTAB-Map hien tai KHONG bao loi gi -- no bi bo qua im
|
||||
// lang va he chay bang gia tri mac dinh. `Reg/Force3DoF` go thanh
|
||||
// `Reg/Force3Dof` nghia la pose thanh 6-DoF ma khong ai biet, cho toi khi
|
||||
// ban do bat dau nghieng.
|
||||
//
|
||||
// `BuildRtabmapParams` doi chieu MOI key voi
|
||||
// `rtabmap::Parameters::getDefaultParameters()` va tra loi neu co key la.
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/config.h"
|
||||
#include "vslam/slam_types.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct RtabmapConfig {
|
||||
// TAT mac dinh: tren may chua build RTAB-Map thi node van phai chay duoc
|
||||
// day du phan con lai.
|
||||
bool enabled = false;
|
||||
|
||||
SlamMode mode = SlamMode::kMapping;
|
||||
std::string database_path;
|
||||
|
||||
// Bat tui tu thi giac. Keo theo yeu cau co anh -- xem ghi chu trong
|
||||
// rtabmap.launch: Kp/MaxFeatures dieu khien viec PHAT HIEN, con
|
||||
// Reg/Strategy=1 (ICP tren LiDAR) van la thu TINH phep bien doi. Nen bat
|
||||
// thi giac khong danh doi do chinh xac.
|
||||
bool visual_loop = false;
|
||||
bool camera_3d = false;
|
||||
|
||||
// Optimizer. "1" = g2o. KHONG dung "2" (GTSAM): apt jammy arm64 khong co
|
||||
// GTSAM va PPA borglab khong publish arm64.
|
||||
std::string optimizer_strategy = "1";
|
||||
|
||||
// Cac key RTAB-Map doc tu khoi `rtabmap:` cua slam.yaml. Ghi de len mac
|
||||
// dinh, va bi ghi de boi cac suy dien tu mode/visual_loop o tren.
|
||||
std::map<std::string, std::string> overrides;
|
||||
};
|
||||
|
||||
// Tra ve tap tham so day du. `unknown` nhan ten cac key khong co trong bang
|
||||
// mac dinh cua RTAB-Map -- nguoi goi PHAI coi do la loi khoi dong, khong
|
||||
// duoc chi log.
|
||||
std::map<std::string, std::string> BuildRtabmapParams(
|
||||
const RtabmapConfig& cfg, std::vector<std::string>* unknown);
|
||||
|
||||
// Doc khoi `rtabmap:` + cac key cap cao tu ConfigNode.
|
||||
RtabmapConfig LoadRtabmapConfig(const ConfigNode& node);
|
||||
|
||||
// Tra ve true neu RTAB-Map duoc build kem optimizer nay.
|
||||
bool OptimizerAvailable(const std::string& strategy);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_RTABMAP_PARAMS_H
|
||||
89
libs/vslam_slam/include/vslam/rtabmap_slam.h
Normal file
89
libs/vslam_slam/include/vslam/rtabmap_slam.h
Normal file
@@ -0,0 +1,89 @@
|
||||
#ifndef VSLAM_RTABMAP_SLAM_H
|
||||
#define VSLAM_RTABMAP_SLAM_H
|
||||
|
||||
// Boc `rtabmap::Rtabmap`.
|
||||
//
|
||||
// ================== BA DIEU PHAI NHO ==================
|
||||
//
|
||||
// 1. `Process()` CHAN 100-600 ms. Luong goi no KHONG duoc chia se mutex nao
|
||||
// voi luong safety. Trong ban ROS dieu nay duoc bao dam mien phi boi tien
|
||||
// trinh rieng + respawn="true"; o day no la quy tac review.
|
||||
//
|
||||
// 2. RTAB-Map luu du lieu NEN. `gridGroundCellsRaw()` tra ma tran RONG, im
|
||||
// lang, cho toi khi goi `uncompressDataConst()`. Da mac loi nay mot lan
|
||||
// khi do `tools/probe_rtabmap` tren map_hospital.db.
|
||||
//
|
||||
// 3. DB hien co luu `Optimizer/Strategy=2` (GTSAM). Tren Jetson build voi
|
||||
// -DWITH_GTSAM=OFF ma de RTAB-Map doc tham so tu DB thi no chon lai GTSAM
|
||||
// va crash thieu symbol. `Init()` luon goi
|
||||
// `init(params, db, loadDatabaseParameters=false)` VA assert sau do.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "vslam/rtabmap_params.h"
|
||||
#include "vslam/slam_types.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
class RtabmapSlamImpl; // o namespace scope, KHONG long trong class
|
||||
// (pimpl long private khong goi duoc tu .cc -- da
|
||||
// mac loi nay o ConfigNode va WebServer)
|
||||
|
||||
class RtabmapSlam {
|
||||
public:
|
||||
RtabmapSlam();
|
||||
~RtabmapSlam();
|
||||
|
||||
RtabmapSlam(const RtabmapSlam&) = delete;
|
||||
RtabmapSlam& operator=(const RtabmapSlam&) = delete;
|
||||
|
||||
// Mo DB va khoi tao. Tra loi (khong nem) de nguoi goi quyet dinh chay tiep
|
||||
// o che do khong-SLAM hay dung han.
|
||||
//
|
||||
// Kiem truoc khi chay, KHONG phai sau:
|
||||
// - optimizer da yeu cau co duoc build vao khong;
|
||||
// - visual_loop=true ma DB khong co tu vung (SELECT COUNT(*) FROM Word
|
||||
// = 0) -> tra FAILED_PRECONDITION thay vi am tham ton CPU ma khong bao
|
||||
// gio dong duoc vong nao;
|
||||
// - localization ma DB rong -> khong co gi de dinh vi vao.
|
||||
StatusResponse Init(const RtabmapConfig& cfg);
|
||||
|
||||
// Phep bien doi TINH tu cam bien ve base_footprint, doc tu robot.yaml.
|
||||
//
|
||||
// PHAI goi truoc Process(). Mac dinh la dong nhat, va dong nhat la SAI:
|
||||
// laser tren robot nay o xyz = (0.24, 0, 0.20). Bo qua no thi moi scan bi
|
||||
// dat lech 24 cm so voi pose, ICP van hoi tu (no chi thay ca the gioi dich
|
||||
// di) nhung do thi tich luy sai so -- da do: ATE 0.2378 m thay vi 0.0074 m
|
||||
// tren map_house.db. Khong co gi bao loi.
|
||||
void SetExtrinsics(const Transform& laser_to_base, const Transform& camera_to_base);
|
||||
|
||||
// Mot khung. Tra `processed=false` neu RTAB-Map bo qua (chua du chuyen dong
|
||||
// theo RGBD/LinearUpdate) -- do KHONG phai loi.
|
||||
SlamOutput Process(const SlamInput& in);
|
||||
|
||||
// map -> odom gan nhat. An toan goi tu luong khac (doc duoi mutex rieng,
|
||||
// khong phai mutex ma Process() giu).
|
||||
Pose2D map_correction() const;
|
||||
bool localized() const;
|
||||
uint64_t map_version() const;
|
||||
|
||||
// Dat lai pose (thay cho /initialpose). Chi co nghia o che do localization.
|
||||
StatusResponse SetInitialPose(const Pose2D& pose);
|
||||
|
||||
// Xuat occupancy grid hien tai. Dat, goi khi map_version doi.
|
||||
StatusResponse ExportMap(OccupancyGrid* out);
|
||||
|
||||
StatusResponse Close(bool save_database);
|
||||
|
||||
const SlamStats& stats() const;
|
||||
SlamMode mode() const;
|
||||
|
||||
private:
|
||||
std::unique_ptr<RtabmapSlamImpl> impl_;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_RTABMAP_SLAM_H
|
||||
45
libs/vslam_slam/include/vslam/sensor_data_builder.h
Normal file
45
libs/vslam_slam/include/vslam/sensor_data_builder.h
Normal file
@@ -0,0 +1,45 @@
|
||||
#ifndef VSLAM_SENSOR_DATA_BUILDER_H
|
||||
#define VSLAM_SENSOR_DATA_BUILDER_H
|
||||
|
||||
// Doi struct POD cua ta thanh `rtabmap::SensorData`.
|
||||
//
|
||||
// Tach rieng khoi rtabmap_slam.cc vi day la cho DE SAI NHAT va de test nhat:
|
||||
// don vi, thu tu kenh, frame cuc bo, va y nghia cua tia khong do duoc deu
|
||||
// phai dung, ma sai thi khong co gi bao -- chi la ICP kem hoi tu hon mot
|
||||
// chut.
|
||||
|
||||
#include <rtabmap/core/SensorData.h>
|
||||
#include <rtabmap/core/Transform.h>
|
||||
|
||||
#include "vslam/slam_types.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Doi Pose2D <-> rtabmap::Transform. SE(2) nhung RTAB-Map luon dung SE(3);
|
||||
// `Reg/Force3DoF=true` ep no ve mat phang o phia trong.
|
||||
rtabmap::Transform ToRtabmap(const Pose2D& p);
|
||||
Pose2D FromRtabmap(const rtabmap::Transform& t);
|
||||
rtabmap::Transform ToRtabmap(const Transform& t);
|
||||
Transform TransformFromRtabmap(const rtabmap::Transform& t);
|
||||
|
||||
// LaserScan POD -> rtabmap::LaserScan (kXY, CV_32FC2).
|
||||
//
|
||||
// BA NGU NGHIA CUA TIA phai giu dung -- xem scan_sanitizer.h:
|
||||
// NaN = khong do duoc -> BO
|
||||
// inf = khong co phan xa -> BO (khong phai diem o vo cuc)
|
||||
// range_max + 1.0 = sentinel bi sector mask cat -> BO
|
||||
// Bien inf thanh mot diem o range_max se dung mot buc tuong ao quanh robot va
|
||||
// ICP se khop vao no.
|
||||
rtabmap::LaserScan BuildLaserScan(const LaserScan& scan,
|
||||
const Transform& laser_to_base);
|
||||
|
||||
// Dung SensorData day du. `depth`/`infra1` co the null.
|
||||
rtabmap::SensorData BuildSensorData(const SlamInput& in,
|
||||
const Transform& laser_to_base,
|
||||
const Transform& camera_to_base,
|
||||
int id);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_SENSOR_DATA_BUILDER_H
|
||||
79
libs/vslam_slam/include/vslam/slam_types.h
Normal file
79
libs/vslam_slam/include/vslam/slam_types.h
Normal file
@@ -0,0 +1,79 @@
|
||||
#ifndef VSLAM_SLAM_TYPES_H
|
||||
#define VSLAM_SLAM_TYPES_H
|
||||
|
||||
// Kieu du lieu o bien gioi cua vslam_slam.
|
||||
//
|
||||
// KHONG co kieu nao cua RTAB-Map o day. Do la dieu kien de `app/` va
|
||||
// `vslam_web` khong phai bien voi RTAB-Map, va de doi sang backend khac (hoac
|
||||
// tat han bang -DVSLAM_BUILD_SLAM=OFF) chi la thay mot thu vien.
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/unix_time.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
enum class SlamMode : uint8_t {
|
||||
kMapping = 0, // Mem/IncrementalMemory = true
|
||||
kLocalization = 1, // Mem/IncrementalMemory = false
|
||||
};
|
||||
|
||||
const char* SlamModeName(SlamMode m);
|
||||
|
||||
struct SlamInput {
|
||||
UnixTime stamp;
|
||||
|
||||
// odom -> base_footprint. Day la dau vao BAT BUOC: RTAB-Map o che do nay
|
||||
// khong tu tinh odometry, no chinh odometry cua ta.
|
||||
Pose2D odom;
|
||||
double odom_linear_var = 0.01;
|
||||
double odom_angular_var = 0.01;
|
||||
|
||||
// Scan DA VE SINH (qua ScanSanitizer), trong frame laser.
|
||||
const LaserScan* scan = nullptr;
|
||||
|
||||
// Tuy chon, chi dung khi camera_3d hoac visual_loop bat.
|
||||
const Image* depth = nullptr;
|
||||
const CameraInfo* depth_info = nullptr;
|
||||
const Image* infra1 = nullptr; // D410 KHONG co RGB -> dung IR trai lam "rgb"
|
||||
};
|
||||
|
||||
struct SlamOutput {
|
||||
bool processed = false; // false = bi bo qua do chua du chuyen dong
|
||||
UnixTime stamp;
|
||||
|
||||
// map -> odom. Day la thu duy nhat SLAM ghi vao TransformTree.
|
||||
Pose2D map_correction;
|
||||
// map -> base_footprint, tien cho nguoi goi.
|
||||
Pose2D pose_map;
|
||||
|
||||
bool localized = false;
|
||||
int loop_closure_id = 0; // 0 = khong co vong dong o khung nay
|
||||
int proximity_id = 0;
|
||||
double score = 0.0; // do tin cay cua gia thuyet vong dong
|
||||
|
||||
double process_ms = 0.0;
|
||||
uint64_t map_version = 0; // tang khi do thi doi -> web moi gui lai map
|
||||
int nodes_wm = 0; // so node trong working memory
|
||||
};
|
||||
|
||||
struct SlamStats {
|
||||
uint64_t frames_in = 0;
|
||||
uint64_t frames_processed = 0;
|
||||
uint64_t loop_closures = 0;
|
||||
uint64_t proximity_links = 0;
|
||||
double last_ms = 0.0;
|
||||
double max_ms = 0.0;
|
||||
// p95 cua process_ms. Chi tieu tren Jetson la < 700 ms -- gia tri trung
|
||||
// binh vo nghia o day vi phan phoi co duoi rat dai (khung co vong dong dat
|
||||
// gap 10 lan khung thuong).
|
||||
double p95_ms = 0.0;
|
||||
std::vector<double> samples; // giu de tinh p95; gioi han kich thuoc
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_SLAM_TYPES_H
|
||||
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