This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

47
libs/CMakeLists.txt Normal file
View File

@@ -0,0 +1,47 @@
# Thu tu o day phan anh dung do thi phu thuoc:
#
# vslam_common
# |-- vslam_odometry (khong them dep ngoai)
# |-- vslam_safety (khong them dep ngoai)
# |-- vslam_drivers (+ librealsense2)
# |-- vslam_perception (+ PCL)
# |-- vslam_web (+ Boost.Beast, header-only)
# `-- vslam_slam (+ RTAB-Map, g2o, OpenCV, PCL)
#
# vslam_slam dung cuoi vi no la cai kho build nhat tren arm64. Tat no bang
# -DVSLAM_BUILD_SLAM=OFF thi sau lib con lai van build -- do la ca ly do de
# tach lib theo tap dependency thay vi theo chuc nang.
if(VSLAM_BUILD_COMMON)
add_subdirectory(vslam_common)
endif()
if(VSLAM_BUILD_ODOMETRY)
add_subdirectory(vslam_odometry)
endif()
if(VSLAM_BUILD_SAFETY)
add_subdirectory(vslam_safety)
endif()
if(VSLAM_BUILD_DRIVERS)
add_subdirectory(vslam_drivers)
endif()
if(VSLAM_BUILD_PERCEPTION)
add_subdirectory(vslam_perception)
endif()
if(VSLAM_BUILD_WEB)
add_subdirectory(vslam_web)
endif()
if(VSLAM_BUILD_SLAM)
add_subdirectory(vslam_slam)
endif()
# Thay Gazebo. Phu thuoc vslam_drivers vi no implement chinh cac interface
# driver -- y het ReplaySource.
if(VSLAM_BUILD_SIM)
add_subdirectory(vslam_sim)
endif()

View File

@@ -0,0 +1,67 @@
# Nen tang cua ca he. Dep ngoai: Eigen3 (chi header, dung trong geometry) va
# yaml-cpp (config). Khong gi khac -- moi lib kia phu thuoc lib nay nen giu no
# nhe la dieu kien de P0 build duoc truoc khi co RTAB-Map hay PCL.
find_package(Eigen3 REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(Threads REQUIRED)
vslam_add_library(vslam_common
PUBLIC_HDRS
vslam_common.h
unix_time.h
clock.h
log.h
config.h
node_constants.h
geometry.h
stats.h
json_parse.h
robot_model.h
teleop_model.h
channel.h
approx_sync.h
buffer_pool.h
transform_tree.h
# FIND_DEPS chi liet ke dep PUBLIC -- tuc la dep co mat trong
# INTERFACE_LINK_LIBRARIES cua target da cai, nen nguoi dung thu vien PHAI
# co chung. yaml-cpp link PRIVATE nen khong nam trong do: dua no vao day se
# bat nguoi dung phai cai yaml-cpp mot cach vo co.
#
# Nguoc lai, thieu mot dep PUBLIC o day thi find_package() that bai voi thong
# bao "links to target Threads::Threads but the target was not found" --
# dung loai loi ma file Config.cmake nay sinh ra de chan.
FIND_DEPS
Eigen3
Threads
)
# yaml-cpp: ten target khac nhau theo phien ban va theo cach cai.
# 0.6 (focal, apt) -> bien yaml-cpp_LIBRARIES, doi khi target `yaml-cpp`
# 0.7 (jammy, apt) -> target `yaml-cpp`
# >=0.8 / vcpkg -> target `yaml-cpp::yaml-cpp`
# Dung sai ten o day la loi link kho doc tren Jetson, nen do het truong hop.
if(TARGET yaml-cpp::yaml-cpp)
target_link_libraries(vslam_common PRIVATE yaml-cpp::yaml-cpp)
elseif(TARGET yaml-cpp)
target_link_libraries(vslam_common PRIVATE yaml-cpp)
else()
target_include_directories(vslam_common SYSTEM PRIVATE ${YAML_CPP_INCLUDE_DIR})
target_link_libraries(vslam_common PRIVATE ${YAML_CPP_LIBRARIES})
endif()
if(TARGET Eigen3::Eigen)
target_link_libraries(vslam_common PUBLIC Eigen3::Eigen)
else()
target_include_directories(vslam_common SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR})
endif()
# Moi target trong cay phai cung mot EIGEN_MAX_ALIGN_BYTES. Dat PUBLIC o day
# de no lan sang moi lib phu thuoc vslam_common -- do la toan bo cay.
# Xem ke hoach, muc "Bay arm64": hai phia compile voi gia tri khac nhau sinh
# loi alignment chi hien ra luc chay, tren arm64, khong tai lap on dinh.
target_compile_definitions(vslam_common
PUBLIC EIGEN_MAX_ALIGN_BYTES=${VSLAM_EIGEN_MAX_ALIGN_BYTES})
# PUBLIC: Channel va TransformTree deu co std::mutex trong header cong khai.
target_link_libraries(vslam_common PUBLIC Threads::Threads)

View File

@@ -0,0 +1,345 @@
#ifndef VSLAM_APPROX_SYNC_H
#define VSLAM_APPROX_SYNC_H
// Thay message_filters::Synchronizer<ApproximateTime<...>>.
//
// Cau hinh hien tai can khop lai: rtabmap.launch:235-237 dat approx_sync=true,
// sync_queue_size=30, dong bo scan + odom + depth + rgb.
// cliff_detect_nodelet.cpp:101-102 dong bo depth + camera_info.
//
// Thuat toan o day DON GIAN VA DE DOAN HON ApproximateTime cua ROS. ROS dung
// mot thuat toan toi uu cua so co the giu ban tin lai kha lau va rat kho suy
// luan khi mot nguon tut. O day:
//
// 1. Moi ban tin moi o stream PIVOT (scan, 25 Hz -- cham nhat) tao mot moc.
// 2. Voi moi stream khac, chon ban tin co |stamp - pivot| nho nhat, yeu cau
// <= max_slop_sec.
// 3. Phat khi:
// (a) du moi stream REQUIRED, va moi stream TUY CHON hoac da co hoac ban
// tin moi nhat cua no DA VUOT pivot (khong the khop hon duoc nua); hoac
// (b) now - pivot > wait_timeout_sec -- phat voi stream tuy chon de trong.
// 4. Pivot cu hon queue_size bi bo, dem vao dropped_queue.
//
// Nhanh (b) khong lam mat tin hieu: RTAB-Map chay duoc voi scan + odom ma
// khong can depth (subscribe_depth la tuy chon), chi mat visual word.
//
// SyncStats dem RIENG ba loai drop -- slop, timeout, queue -- vi ba nguyen
// nhan nay can ba cach sua khac han nhau:
// slop -> lech dong ho giua hai nguon, hoac max_slop_sec qua chat
// timeout -> mot nguon cham hon du kien hoac da chet
// queue -> consumer khong theo kip producer
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <tuple>
#include <utility>
#include <vector>
#include "vslam/stats.h"
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
template <typename... Ts>
class ApproxTimeSync {
public:
static constexpr size_t kN = sizeof...(Ts);
using Tuple = std::tuple<std::shared_ptr<const Ts>...>;
using Callback = std::function<void(UnixTime pivot_stamp, const Tuple&)>;
struct Options {
size_t queue_size = 30; // khop sync_queue_size=30 hien tai
double max_slop_sec = 0.05; // ~1.5 khung camera o 30 Hz
double wait_timeout_sec = 0.20; // het han cho input tuy chon
size_t pivot_index = 0; // stream cham nhat lam moc (scan)
std::array<bool, kN> required{}; // scan+odom = true; depth+infra = false
};
ApproxTimeSync(Options opt, Callback cb)
: opt_(std::move(opt)), cb_(std::move(cb)) {
if (opt_.queue_size == 0) opt_.queue_size = 1;
if (opt_.pivot_index >= kN) opt_.pivot_index = 0;
}
// Them ban tin vao stream thu I.
template <size_t I>
void Add(UnixTime stamp,
std::shared_ptr<const std::tuple_element_t<I, std::tuple<Ts...>>> msg) {
static_assert(I < kN, "chi so stream vuot so stream");
std::vector<std::pair<UnixTime, Tuple>> emit;
{
std::lock_guard<std::mutex> lk(mu_);
auto& q = queues_[I];
if (!q.empty() && stamp < q.back().stamp) {
// Stamp lui: ban ghi bi xao tron hoac hai nguon ghi cung stream.
stats_.dropped_queue++;
return;
}
q.push_back(Slot{stamp, std::static_pointer_cast<const void>(std::move(msg))});
while (q.size() > opt_.queue_size) {
q.pop_front();
if (I == opt_.pivot_index) stats_.dropped_queue++;
}
CollectLocked(kTimeZero, false, &emit);
}
Fire(emit);
}
// Lai nhanh wait_timeout. Goi tu vong lap cua luong so huu sync.
void Tick(UnixTime now) {
std::vector<std::pair<UnixTime, Tuple>> emit;
{
std::lock_guard<std::mutex> lk(mu_);
CollectLocked(now, true, &emit);
}
Fire(emit);
}
SyncStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
void Reset() {
std::lock_guard<std::mutex> lk(mu_);
for (auto& q : queues_) q.clear();
stats_ = SyncStats{};
}
private:
struct Slot {
UnixTime stamp;
std::shared_ptr<const void> msg;
};
// Goi khi da giu mu_. Khong goi callback o day -- chi gom vao `emit`.
void CollectLocked(UnixTime now, bool allow_timeout,
std::vector<std::pair<UnixTime, Tuple>>* emit) {
auto& pivot_q = queues_[opt_.pivot_index];
while (!pivot_q.empty()) {
const UnixTime pivot = pivot_q.front().stamp;
std::array<size_t, kN> pick{};
std::array<bool, kN> have{};
bool all_required = true;
bool all_settled = true;
double worst_slop = 0.0;
for (size_t s = 0; s < kN; ++s) {
if (s == opt_.pivot_index) {
pick[s] = 0;
have[s] = true;
continue;
}
const auto& q = queues_[s];
if (q.empty()) {
all_settled = false;
if (opt_.required[s]) all_required = false;
continue;
}
size_t best = 0;
double best_d = std::abs(SecondsBetween(q[0].stamp, pivot));
for (size_t i = 1; i < q.size(); ++i) {
const double d = std::abs(SecondsBetween(q[i].stamp, pivot));
if (d < best_d) { best_d = d; best = i; }
}
if (best_d <= opt_.max_slop_sec) {
pick[s] = best;
have[s] = true;
worst_slop = std::max(worst_slop, best_d);
} else {
if (opt_.required[s]) all_required = false;
// Ban tin moi nhat cua stream nay DA VUOT pivot: khong the khop hon
// duoc nua, nen stream coi nhu da chot (du la chot rong).
if (q.back().stamp <= pivot) all_settled = false;
}
}
const bool timed_out =
allow_timeout && !now.isZero() &&
SecondsBetween(now, pivot) > opt_.wait_timeout_sec;
if (!all_required) {
if (!timed_out) break; // con co the cho them
// Het gio ma van thieu stream bat buoc -> bo pivot nay.
stats_.dropped_timeout++;
pivot_q.pop_front();
continue;
}
if (!all_settled && !timed_out) break; // cho stream tuy chon
Tuple t;
FillTuple(t, pick, have, std::index_sequence_for<Ts...>{});
emit->emplace_back(pivot, std::move(t));
stats_.matched++;
stats_.last_slop_sec = worst_slop;
if (timed_out && !all_settled) stats_.dropped_timeout++;
// Bo moi ban tin da dung va moi ban tin cu hon no.
for (size_t s = 0; s < kN; ++s) {
if (s == opt_.pivot_index || !have[s]) continue;
auto& q = queues_[s];
q.erase(q.begin(), q.begin() + static_cast<long>(pick[s]) + 1);
}
pivot_q.pop_front();
}
}
template <size_t... Is>
void FillTuple(Tuple& t, const std::array<size_t, kN>& pick,
const std::array<bool, kN>& have, std::index_sequence<Is...>) {
(void)std::initializer_list<int>{
(std::get<Is>(t) =
have[Is] ? std::static_pointer_cast<
const std::tuple_element_t<Is, std::tuple<Ts...>>>(
queues_[Is][pick[Is]].msg)
: nullptr,
0)...};
}
// Goi callback NGOAI khoa. Callback cua SLAM chan 100-600 ms; giu khoa
// trong do se chan luong lidar_rx.
void Fire(const std::vector<std::pair<UnixTime, Tuple>>& emit) {
for (const auto& e : emit) cb_(e.first, e.second);
}
Options opt_;
Callback cb_;
mutable std::mutex mu_;
std::array<std::deque<Slot>, kN> queues_;
SyncStats stats_;
};
// --- Bien the hai luong ----------------------------------------------------
// Truong hop hai nguon pho bien den muc dang co ban rieng: de doc hon, compile
// nhanh hon, va khong phai dien std::array<bool,2> cho moi lan dung.
// Dung boi cliff_detect (depth + camera_info).
//
// HEADER-ONLY, khong pimpl. Ban dau viet pimpl + khoi tao tuong minh cho
// PairSync<Image, CameraInfo>, nhung nhu the thi khong ai dung duoc no voi
// kieu khac -- ke ca unit test voi struct gia. Voi mot lop nho nhu nay thi
// cai gia cua pimpl (mot ban khoi tao tuong minh cho moi cap kieu) lon hon
// cai loi.
template <typename A, typename B>
class PairSync {
public:
using Callback = std::function<void(UnixTime, std::shared_ptr<const A>,
std::shared_ptr<const B>)>;
PairSync(size_t queue_size, double max_slop_sec, Callback cb)
: queue_size_(queue_size == 0 ? 1 : queue_size),
max_slop_sec_(max_slop_sec),
cb_(std::move(cb)) {}
void AddFirst(UnixTime stamp, std::shared_ptr<const A> msg) {
std::vector<Emit> emit;
{
std::lock_guard<std::mutex> lk(mu_);
qa_.push_back(SlotA{stamp, std::move(msg)});
TrimLocked();
MatchLocked(&emit);
}
Fire(emit);
}
void AddSecond(UnixTime stamp, std::shared_ptr<const B> msg) {
std::vector<Emit> emit;
{
std::lock_guard<std::mutex> lk(mu_);
qb_.push_back(SlotB{stamp, std::move(msg)});
TrimLocked();
MatchLocked(&emit);
}
Fire(emit);
}
SyncStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
void Reset() {
std::lock_guard<std::mutex> lk(mu_);
qa_.clear();
qb_.clear();
stats_ = SyncStats{};
}
private:
struct SlotA { UnixTime stamp; std::shared_ptr<const A> msg; };
struct SlotB { UnixTime stamp; std::shared_ptr<const B> msg; };
struct Emit {
UnixTime stamp;
std::shared_ptr<const A> a;
std::shared_ptr<const B> b;
};
// Goi khi da giu mu_. Chi gom vao `emit`, khong goi callback o day.
void MatchLocked(std::vector<Emit>* emit) {
while (!qa_.empty() && !qb_.empty()) {
const SlotA& a = qa_.front();
size_t best = 0;
double best_d = std::abs(SecondsBetween(qb_[0].stamp, a.stamp));
for (size_t i = 1; i < qb_.size(); ++i) {
const double d = std::abs(SecondsBetween(qb_[i].stamp, a.stamp));
if (d < best_d) { best_d = d; best = i; }
}
if (best_d <= max_slop_sec_) {
emit->push_back(Emit{a.stamp, a.msg, qb_[best].msg});
stats_.matched++;
stats_.last_slop_sec = best_d;
// Bo moi phan tu b cu hon phan tu vua khop: chung khong con co hoi
// khop voi bat ky a nao ve sau (a chi tien len).
qb_.erase(qb_.begin(), qb_.begin() + static_cast<long>(best) + 1);
qa_.pop_front();
continue;
}
// Chua khop duoc. Neu a da cu hon MOI phan tu b thi no khong bao gio
// khop nua -> bo. Nguoc lai thi cho them b.
if (a.stamp < qb_.back().stamp) {
stats_.dropped_slop++;
qa_.pop_front();
continue;
}
break;
}
}
void TrimLocked() {
while (qa_.size() > queue_size_) { qa_.pop_front(); stats_.dropped_queue++; }
while (qb_.size() > queue_size_) { qb_.pop_front(); stats_.dropped_queue++; }
}
// Goi callback NGOAI khoa. Callback cua cliff_detect lam viec nang
// (ray-cast toan anh depth); giu khoa trong do se chan luong camera.
void Fire(const std::vector<Emit>& emit) {
for (const auto& e : emit) cb_(e.stamp, e.a, e.b);
}
size_t queue_size_;
double max_slop_sec_;
Callback cb_;
mutable std::mutex mu_;
std::deque<SlotA> qa_;
std::deque<SlotB> qb_;
SyncStats stats_;
};
} // namespace vslam
#endif // VSLAM_APPROX_SYNC_H

View File

@@ -0,0 +1,92 @@
#ifndef VSLAM_BUFFER_POOL_H
#define VSLAM_BUFFER_POOL_H
// Pool tai su dung buffer, de chuoi perception khong cap phat gi o trang thai
// on dinh.
//
// Chuoi hien tai moi khung sinh: cloud_raw (320x240 = 76800 diem) ->
// cloud_filtered -> cloud_aligned. Neu moi buoc malloc mot vector moi thi o
// 10 Hz la ~9 MB/s di qua allocator, va tren Jetson dieu do the hien thanh
// jitter chu khong phai thong luong.
//
// Cach dung: hai buffer luan phien, 0 malloc o trang thai on dinh.
// Acquire() tra shared_ptr co deleter tu tra ve pool. Neu pool da bi huy
// truoc object thi deleter xoa that -- an toan khi tat may.
//
// allocated() ra /api/status: con so nay khong duoc tang sau khi he chay on
// dinh. Tang nghia la co cho giu shared_ptr lau hon can (ro ri thuc su, hoac
// mot Channel capacity qua lon).
#include <atomic>
#include <cstddef>
#include <memory>
#include <mutex>
#include <vector>
namespace vslam {
template <typename T>
class BufferPool : public std::enable_shared_from_this<BufferPool<T>> {
public:
// max_idle: giu toi da bao nhieu buffer roi. Vuot qua thi tra buffer se xoa
// that thay vi giu -- tranh pool phinh vinh vien sau mot dot tai cao.
static std::shared_ptr<BufferPool<T>> Create(size_t max_idle = 4) {
return std::shared_ptr<BufferPool<T>>(new BufferPool<T>(max_idle));
}
std::shared_ptr<T> Acquire() {
std::unique_ptr<T> obj;
{
std::lock_guard<std::mutex> lk(mu_);
if (!idle_.empty()) {
obj = std::move(idle_.back());
idle_.pop_back();
}
}
if (!obj) {
obj = std::make_unique<T>();
allocated_.fetch_add(1, std::memory_order_relaxed);
}
// weak_ptr: neu pool chet truoc object thi deleter xoa that.
std::weak_ptr<BufferPool<T>> weak = this->shared_from_this();
T* raw = obj.release();
return std::shared_ptr<T>(raw, [weak](T* p) {
if (auto pool = weak.lock()) {
pool->Release(std::unique_ptr<T>(p));
} else {
delete p;
}
});
}
size_t idle() const {
std::lock_guard<std::mutex> lk(mu_);
return idle_.size();
}
size_t allocated() const { return allocated_.load(std::memory_order_relaxed); }
void Clear() {
std::lock_guard<std::mutex> lk(mu_);
idle_.clear();
}
private:
explicit BufferPool(size_t max_idle) : max_idle_(max_idle) {}
void Release(std::unique_ptr<T> obj) {
std::lock_guard<std::mutex> lk(mu_);
if (idle_.size() >= max_idle_) return; // xoa that
idle_.push_back(std::move(obj));
}
const size_t max_idle_;
mutable std::mutex mu_;
std::vector<std::unique_ptr<T>> idle_;
std::atomic<size_t> allocated_{0};
};
} // namespace vslam
#endif // VSLAM_BUFFER_POOL_H

View File

@@ -0,0 +1,247 @@
#ifndef VSLAM_CHANNEL_H
#define VSLAM_CHANNEL_H
// Thay pub/sub cua ROS.
//
// QUY TAC RANH GIOI -- doc truoc khi dung:
//
// Channel<T> CHI dung khi du lieu di QUA BIEN LUONG.
// Trong cung mot luong: goi ham truc tiep.
//
// Day la cach giu nguyen loi the "3 nodelet chung 1 manager" cua ban ROS.
// Chuoi depth_to_cloud -> depth_filter -> gravity_align -> cliff_detect chay
// inline tren chinh luong camera trong mot loi goi PerceptionPipeline::Process().
// Tot hon nodelet manager: khong intrusive_ptr, khong dispatch theo topic,
// khong nodelet loader.
//
// Don vi du lieu duy nhat la std::shared_ptr<const T>. Publish() copy mot
// con tro (mot atomic increment), khong bao gio copy cloud/anh/scan.
//
// KHAC BIET QUAN TRONG SO VOI QUEUE CUA ROS: so ban tin bi bo duoc DEM va bao
// cao ra /api/status. Queue cua ROS drop im lang, va do la ly do repo cu phai
// doan mo ve viec costmap co nhan du cloud hay khong.
//
// AN TOAN LUONG:
// * Publish() khong bao gio chan. Day la bat buoc: luong lidar_rx hay
// camera_rx khong duoc phep dung cho luong slam (Rtabmap::process() chan
// 100-600 ms).
// * Latest() la duong doc cua luong safety: mot lan copy shared_ptr duoi
// khoa, khong bao gio giu khoa khi goi code nguoi dung.
// * Tap Reader co dinh truoc khi chay. MakeReader() phai goi xong trong
// giai doan wiring, khong duoc goi khi he dang chay.
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "vslam/stats.h"
#include "vslam/unix_time.h"
namespace vslam {
template <typename T>
class Channel {
public:
using Ptr = std::shared_ptr<const T>;
struct Item {
Ptr msg;
UnixTime stamp;
uint64_t seq = 0;
};
Channel(size_t capacity, std::string name)
: capacity_(capacity), name_(std::move(name)), ring_(capacity) {
assert(capacity > 0 && "Channel capacity phai > 0");
}
Channel(const Channel&) = delete;
Channel& operator=(const Channel&) = delete;
// Khong bao gio chan. Tra ve false neu phai ghi de mot phan tu ma con reader
// chua doc toi -- goi co the dung gia tri nay de dem hoac de canh bao.
bool Publish(Ptr msg, UnixTime stamp) {
bool overwrote = false;
{
std::lock_guard<std::mutex> lk(mu_);
const uint64_t seq = head_++;
// Ghi de o cu nhat neu vong da day.
if (seq >= capacity_) {
const uint64_t evicted = seq - capacity_;
for (const auto& r : readers_) {
if (r->cursor.load(std::memory_order_relaxed) <= evicted) {
overwrote = true;
break;
}
}
}
Item& slot = ring_[seq % capacity_];
slot.msg = std::move(msg);
slot.stamp = stamp;
slot.seq = seq;
latest_ = slot;
published_++;
if (overwrote) overwritten_++;
}
rate_.Tick();
cv_.notify_all();
return !overwrote;
}
// Con tro doc rieng cua tung consumer. Khong sao chep duoc -- moi consumer
// giu mot Reader va chi minh no dung.
class Reader {
public:
// Chan toi khi co ban tin moi hoac het `timeout`. Tra false neu het gio
// hoac channel da dong.
bool Read(Ptr* out, UnixTime* stamp, std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lk(ch_->mu_);
const bool got = ch_->cv_.wait_for(lk, timeout, [this] {
return ch_->closed_ || state_->cursor.load(std::memory_order_relaxed) < ch_->head_;
});
if (!got || ch_->closed_) return false;
return PopLocked(out, stamp);
}
// Khong chan.
bool TryRead(Ptr* out, UnixTime* stamp) {
std::lock_guard<std::mutex> lk(ch_->mu_);
if (state_->cursor.load(std::memory_order_relaxed) >= ch_->head_) return false;
return PopLocked(out, stamp);
}
// So ban tin reader nay KHONG BAO GIO nhin thay vi bi ghi de.
uint64_t dropped() const { return state_->dropped.load(std::memory_order_relaxed); }
// So ban tin dang cho doc.
uint64_t lag() const {
std::lock_guard<std::mutex> lk(ch_->mu_);
const uint64_t c = state_->cursor.load(std::memory_order_relaxed);
return ch_->head_ > c ? ch_->head_ - c : 0;
}
const std::string& name() const { return state_->name; }
private:
friend class Channel<T>;
struct State {
std::atomic<uint64_t> cursor{0};
std::atomic<uint64_t> dropped{0};
std::string name;
};
Reader(Channel<T>* ch, State* st) : ch_(ch), state_(st) {}
// Goi khi da giu mu_.
bool PopLocked(Ptr* out, UnixTime* stamp) {
uint64_t c = state_->cursor.load(std::memory_order_relaxed);
const uint64_t oldest = ch_->head_ > ch_->capacity_ ? ch_->head_ - ch_->capacity_ : 0;
if (c < oldest) {
// Reader da bi nhay qua. Dem phan mat roi tua toi o cu nhat con song.
state_->dropped.fetch_add(oldest - c, std::memory_order_relaxed);
c = oldest;
}
const Item& slot = ch_->ring_[c % ch_->capacity_];
*out = slot.msg;
if (stamp) *stamp = slot.stamp;
state_->cursor.store(c + 1, std::memory_order_relaxed);
return true;
}
Channel<T>* ch_ = nullptr;
State* state_ = nullptr;
};
// Phai goi xong trong giai doan wiring, truoc khi bat ky luong nao chay.
// `name` chi de bao cao so lieu.
Reader MakeReader(std::string name) {
std::lock_guard<std::mutex> lk(mu_);
assert(!started_ && "MakeReader() sau khi he da chay");
auto st = std::make_unique<typename Reader::State>();
st->name = std::move(name);
st->cursor.store(head_, std::memory_order_relaxed); // bat dau tu hien tai
auto* raw = st.get();
readers_.push_back(std::move(st));
return Reader(this, raw);
}
// Danh dau ket thuc wiring. Sau loi goi nay MakeReader() se assert.
void Freeze() {
std::lock_guard<std::mutex> lk(mu_);
started_ = true;
}
// O(1), khong dung cursor. Day la duong doc cua luong safety va web_tx:
// chung khong quan tam lich su, chi can ban moi nhat.
bool Latest(Ptr* out, UnixTime* stamp = nullptr) const {
std::lock_guard<std::mutex> lk(mu_);
if (!latest_.msg) return false;
*out = latest_.msg;
if (stamp) *stamp = latest_.stamp;
return true;
}
// Danh thuc moi reader dang cho.
void Close() {
{
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
}
cv_.notify_all();
}
bool closed() const {
std::lock_guard<std::mutex> lk(mu_);
return closed_;
}
ChannelStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
ChannelStats s;
s.name = name_;
s.capacity = capacity_;
s.published = published_;
s.overwritten = overwritten_;
s.readers = readers_.size();
s.hz = rate_.hz();
for (const auto& r : readers_) {
const uint64_t c = r->cursor.load(std::memory_order_relaxed);
const uint64_t lag = head_ > c ? head_ - c : 0;
if (lag > s.max_reader_lag) s.max_reader_lag = lag;
s.total_reader_drops += r->dropped.load(std::memory_order_relaxed);
}
return s;
}
const std::string& name() const { return name_; }
size_t capacity() const { return capacity_; }
private:
mutable std::mutex mu_;
std::condition_variable cv_;
const size_t capacity_;
const std::string name_;
std::vector<Item> ring_;
uint64_t head_ = 0; // seq se cap cho lan Publish ke tiep
Item latest_;
bool closed_ = false;
bool started_ = false;
uint64_t published_ = 0;
uint64_t overwritten_ = 0;
mutable RateMonitor rate_{2.0};
std::vector<std::unique_ptr<typename Reader::State>> readers_;
};
} // namespace vslam
#endif // VSLAM_CHANNEL_H

View File

@@ -0,0 +1,92 @@
#ifndef VSLAM_CLOCK_H
#define VSLAM_CLOCK_H
// QUY TAC TU NGAY DAU, KHONG RETROFIT DUOC SAU:
//
// Khong stage nao duoc goi UnixTime::now() hay steady_clock::now() truc tiep.
// Moi stage nhan mot `std::shared_ptr<Clock>` qua constructor.
//
// Ly do: replay tat dinh. Neu mot stage doc dong ho that thi chay lai cung mot
// file .vsr se cho ket qua khac, va toan bo tang 2 cua chien luoc kiem chung
// (regress.sh so JSON voi expected/) sup do. Bo qua quy tac nay bay gio nghia
// la khong bao gio lam duoc replay tat dinh sau.
//
// Clock tach LAM HAI ham khong phai ngau nhien -- day la quy tac hai dong ho
// noi o unix_time.h:
//
// Now() -> UnixTime, tu system_clock. Dung DONG DAU du lieu. Co the nhay
// khi NTP dieu chinh.
// Steady() -> steady_clock. Dung do THOI LUONG va tinh TIMEOUT. Khong bao gio
// nhay, khong bao gio lui.
//
// safety_monitor_node.cpp hien dung ros::Time::now() cho ca hai. Mot buoc NTP
// sau khi Jetson bat WiFi lam (now - last_cmd_time_) nhay vot -> NO_CMD dung
// robot dot ngot; hoac nhay lui -> watchdog khong bao gio kich. Day la bug that
// dang nam trong repo, va viec tach hai ham o day la cach sua no.
#include <chrono>
#include <memory>
#include "vslam/unix_time.h"
namespace vslam {
class Clock {
public:
using SteadyPoint = std::chrono::steady_clock::time_point;
virtual ~Clock() = default;
// Dong dau du lieu.
virtual UnixTime Now() const = 0;
// Do thoi luong va tinh timeout.
virtual SteadyPoint Steady() const = 0;
// Ngu toi mot moc steady. Ban replay khong ngu that.
virtual void SleepUntil(SteadyPoint tp) = 0;
// true neu day la dong ho ao (replay). Chi dung de log, khong duoc dung de
// re nhanh logic -- neu can re nhanh thi thiet ke da sai.
virtual bool is_virtual() const = 0;
void SleepFor(std::chrono::nanoseconds d) { SleepUntil(Steady() + d); }
};
using ClockPtr = std::shared_ptr<Clock>;
// Dong ho that: system_clock cho Now(), steady_clock cho Steady().
ClockPtr MakeSystemClock();
// Dong ho ao cho replay. Thoi gian chi tien khi co nguoi goi Advance() hoac
// SleepUntil(). Trong che do --deterministic thi replay source lai no theo
// dung thu tu stamp cua ban ghi.
class ReplayClock : public Clock {
public:
explicit ReplayClock(UnixTime start);
~ReplayClock() override;
UnixTime Now() const override;
SteadyPoint Steady() const override;
void SleepUntil(SteadyPoint tp) override;
bool is_virtual() const override { return true; }
// Dat thoi gian ao. Chi lui neu `allow_backward` -- lui thoi gian la dau
// hieu ban ghi bi xao tron thu tu, mac dinh phai bao loi.
void SetNow(UnixTime t, bool allow_backward = false);
void Advance(Duration d);
// He so toc do doi voi thoi gian tuong that khi SleepUntil() thuc su ngu.
// 0 = chay nhanh nhat co the (khong ngu). 1 = thoi gian that.
void SetSpeed(double speed);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
std::shared_ptr<ReplayClock> MakeReplayClock(UnixTime start);
} // namespace vslam
#endif // VSLAM_CLOCK_H

View File

@@ -0,0 +1,134 @@
#ifndef VSLAM_CONFIG_H
#define VSLAM_CONFIG_H
// Doc cau hinh YAML. Bao yaml-cpp de khong ro kieu cua no ra API cong khai.
//
// HAI THU MA BAN ROS THIEU, va ca hai deu da gay ton that that:
//
// 1. require<T>() -- nem loi kem TEN KEY DAY DU khi thieu.
// Hien tai pnh_.param("stop_distance", stop_distance_, 0.35) khien mot key
// go sai AM THAM roi ve default C++ va khong ai biet. Voi tham so an toan
// (stop_distance, min_front_rays) hay hinh hoc (wheel_separation) thi day
// la kieu loi im lang nguy hiem nhat: he van chay, chi la chay sai.
//
// 2. UnknownKeys() -- liet ke key CO trong file nhung KHONG co trong danh
// sach biet truoc. Bat duoc "stop_distence". Kiem o startup, log ERROR.
//
// Quy tac: dung require() cho moi thu lien quan an toan, hinh hoc, va duong
// dan. Dung get(key, fallback) chi cho tuy chon thuc su co default hop ly.
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace vslam {
class ConfigError : public std::runtime_error {
public:
explicit ConfigError(const std::string& msg) : std::runtime_error(msg) {}
};
class ConfigNode {
public:
ConfigNode();
ConfigNode(const ConfigNode&);
ConfigNode(ConfigNode&&) noexcept;
ConfigNode& operator=(const ConfigNode&);
ConfigNode& operator=(ConfigNode&&) noexcept;
~ConfigNode();
// Nem ConfigError neu file khong doc duoc hoac YAML sai cu phap.
static ConfigNode LoadFile(const std::string& path);
static ConfigNode LoadString(const std::string& yaml, std::string origin = "<string>");
// Key thieu tra ve node Null thay vi nem -- de chuoi a["b"]["c"] khong no
// giua chung. Cho phep kiem IsNull() o cuoi.
ConfigNode operator[](const std::string& key) const;
ConfigNode at(size_t index) const; // cho chuoi (sequence)
bool IsNull() const;
bool IsMap() const;
bool IsSequence() const;
bool IsScalar() const;
size_t size() const;
// Duong dan day du toi node nay, vd "safety.scan.stop_distance".
// Dung trong moi thong bao loi.
const std::string& path() const;
// Ten file goc, de thong bao loi noi ro key nam o dau.
const std::string& origin() const;
// --- Doc gia tri --------------------------------------------------------
// Thieu key -> tra `fallback`. Sai kieu -> nem ConfigError (khac han voi
// thieu key: sai kieu luon la loi cua nguoi viet config).
template <typename T>
T get(const std::string& key, const T& fallback) const;
// Thieu key hoac sai kieu -> nem ConfigError kem duong dan day du.
template <typename T>
T require(const std::string& key) const;
// Doc chinh node nay (khi da di toi la).
template <typename T>
T as() const;
template <typename T>
T as(const T& fallback) const;
// --- Kiem key la ---------------------------------------------------------
// Tra ve cac key CO trong node nay nhung KHONG nam trong `known`.
// Rong nghia la khong co typo.
std::vector<std::string> UnknownKeys(const std::vector<std::string>& known) const;
// Tien loi: goi UnknownKeys() roi log ERROR cho tung key la.
// Tra ve false neu co key la.
bool WarnUnknownKeys(const std::vector<std::string>& known) const;
// Danh sach moi key cua node map nay.
std::vector<std::string> Keys() const;
// Cac cap key/value dang chuoi, giu nguyen van. Dung cho khoi `rtabmap:`
// trong slam.yaml -- 26 key cua RTAB-Map di thang vao ParametersMap ma
// khong qua kiem kieu nao o day.
std::vector<std::pair<std::string, std::string>> AsStringMap() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
explicit ConfigNode(std::unique_ptr<Impl> impl);
};
// Khai bao tuong minh cac kieu duoc ho tro. Dinh nghia o config.cc.
// Them kieu moi thi phai them ca o day va o .cc -- co y, de khong ai vo tinh
// doc mot kieu ma yaml-cpp chuyen doi theo cach bat ngo.
#define VSLAM_CONFIG_DECLARE(T) \
extern template T ConfigNode::get<T>(const std::string&, const T&) const; \
extern template T ConfigNode::require<T>(const std::string&) const; \
extern template T ConfigNode::as<T>() const; \
extern template T ConfigNode::as<T>(const T&) const;
VSLAM_CONFIG_DECLARE(bool)
VSLAM_CONFIG_DECLARE(int)
VSLAM_CONFIG_DECLARE(unsigned int)
VSLAM_CONFIG_DECLARE(float)
VSLAM_CONFIG_DECLARE(double)
VSLAM_CONFIG_DECLARE(std::string)
#undef VSLAM_CONFIG_DECLARE
// Chuoi thi khai bao rieng vi khong dung duoc trong macro (co dau phay).
extern template std::vector<double> ConfigNode::get<std::vector<double>>(
const std::string&, const std::vector<double>&) const;
extern template std::vector<double> ConfigNode::require<std::vector<double>>(
const std::string&) const;
extern template std::vector<std::string> ConfigNode::get<std::vector<std::string>>(
const std::string&, const std::vector<std::string>&) const;
extern template std::vector<std::string> ConfigNode::require<std::vector<std::string>>(
const std::string&) const;
} // namespace vslam
#endif // VSLAM_CONFIG_H

View File

@@ -0,0 +1,108 @@
#ifndef VSLAM_GEOMETRY_H
#define VSLAM_GEOMETRY_H
// Phep bien doi hinh hoc tren cac kieu POD cua vslam_common.h.
//
// Eigen chi xuat hien trong PHAN CAI DAT (.cc), khong o chu ky ham. Ly do o
// vslam_common.h: kieu Eigen fixed-size di qua bien .so la nguon loi alignment
// tren arm64. Ai can Eigen thi tu chuyen o phia minh bang ToEigen()/FromEigen()
// khai bao trong geometry_eigen.h (header noi bo, khong phat hanh).
#include <cmath>
#include "vslam/vslam_common.h"
namespace vslam {
// --- Goc -------------------------------------------------------------------
// Dua goc ve [-pi, pi). Port tu wheel_odom_node.cpp:45-50 va
// slam_core_node.cpp:39-44 (hai ban giong het nhau trong repo cu).
double NormalizeAngle(double a);
// Hieu hai goc, da chuan hoa.
inline double AngleDiff(double a, double b) { return NormalizeAngle(a - b); }
// --- Quaternion <-> Euler --------------------------------------------------
Quaternion QuaternionFromYaw(double yaw);
Quaternion QuaternionFromRPY(double roll, double pitch, double yaw);
double YawFromQuaternion(const Quaternion& q);
void RPYFromQuaternion(const Quaternion& q, double* roll, double* pitch, double* yaw);
Quaternion QuaternionNormalized(const Quaternion& q);
Quaternion QuaternionInverse(const Quaternion& q);
Quaternion QuaternionMultiply(const Quaternion& a, const Quaternion& b);
// Noi suy cau. t kep ve [0,1]. Tu dong lat dau de di duong ngan.
Quaternion QuaternionSlerp(const Quaternion& a, const Quaternion& b, double t);
// --- Vector ----------------------------------------------------------------
inline Vector3 operator+(const Vector3& a, const Vector3& b) {
return Vector3{a.x + b.x, a.y + b.y, a.z + b.z};
}
inline Vector3 operator-(const Vector3& a, const Vector3& b) {
return Vector3{a.x - b.x, a.y - b.y, a.z - b.z};
}
inline Vector3 operator*(const Vector3& v, double s) {
return Vector3{v.x * s, v.y * s, v.z * s};
}
inline double Norm(const Vector3& v) {
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
inline Vector3 Lerp(const Vector3& a, const Vector3& b, double t) {
return Vector3{a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t};
}
// Xoay vector bang quaternion.
Vector3 RotateVector(const Quaternion& q, const Vector3& v);
// --- Transform -------------------------------------------------------------
Transform TransformIdentity();
// Ghep: ket qua bien doi tu frame cua `b` sang frame cua `a`.
// Tuong duong phep nhan ma tran a * b.
Transform TransformCompose(const Transform& a, const Transform& b);
Transform TransformInverse(const Transform& t);
// Ap bien doi len mot diem.
Point TransformPoint(const Transform& t, const Point& p);
Vector3 TransformVector(const Transform& t, const Vector3& v);
// Noi suy giua hai transform: LERP tinh tien + SLERP quay.
// Day la phep TransformTree dung khi lookup o mot stamp nam giua hai mau.
Transform TransformInterpolate(const Transform& a, const Transform& b, double t);
// --- SE(2) -----------------------------------------------------------------
// Pose cua he nay la SE(2): x, y, yaw. Roll/pitch duoc DO tu IMU chu khong
// bao gio uoc luong, va z gia dinh bang 0. Xem docs/ARCHITECTURE.md cua repo cu.
Pose2D Pose2DFromPose(const Pose& p);
Pose PoseFromPose2D(const Pose2D& p, double z = 0.0);
Pose2D Pose2DCompose(const Pose2D& a, const Pose2D& b);
Pose2D Pose2DInverse(const Pose2D& p);
// b trong he toa do cua a: a^-1 * b. Dung khi tinh delta giua hai keyframe.
Pose2D Pose2DBetween(const Pose2D& a, const Pose2D& b);
Transform TransformFromPose2D(const Pose2D& p, double z = 0.0);
Pose2D Pose2DFromTransform(const Transform& t);
inline double Distance2D(const Pose2D& a, const Pose2D& b) {
const double dx = a.x - b.x, dy = a.y - b.y;
return std::sqrt(dx * dx + dy * dy);
}
// --- Chuyen doi tien loi --------------------------------------------------
Transform TransformFromPose(const Pose& p);
Pose PoseFromTransform(const Transform& t);
} // namespace vslam
#endif // VSLAM_GEOMETRY_H

View File

@@ -0,0 +1,40 @@
#ifndef VSLAM_JSON_PARSE_H
#define VSLAM_JSON_PARSE_H
// Trich truong tu body JSON cua POST /api/*.
//
// PHAT HANH co y: ai viet mot WebServer::CommandHandler deu PHAI dung chinh
// cac ham nay de doc body. Neu handler doc body theo mot cach khac voi lop
// xac thuc thi khoang cach giua hai cach doc la mot lo hong -- da tung nhu
// vay o ban dau, khi handler tim chuoi "true" con lop xac thuc goi
// JsonGetBool, va mot body hong lam hai ben hieu nguoc nhau.
//
// CO Y KHONG phai mot parser JSON day du. Body ma server nhan chi co dang
// {"on":true} hoac {"x":1.0,"y":2.0,"yaw":0.5} -- vai truong phang, khong
// long nhau, khong mang.
//
// Viet mot parser day du o day nghia la them mot be mat tan cong tren mot
// endpoint khong xac thuc. Ham trich truong theo ten thi khong co trang thai
// de pha hong.
#include <string>
// Nam o vslam_common chu khong o vslam_web: lop XAC THUC cua web va cac
// handler PHAI dung CHUNG mot ham parse (khoang cach giua hai cach doc cung
// mot body tung la lo hong fail-open cho e-stop), va `tools/vslam_replay`
// cung can doc lai JSON ky vong ma khong duoc phep keo theo Boost.
namespace vslam {
// Tim "key": <so> va tra ve gia tri. false neu khong thay hoac khong parse duoc.
bool JsonGetNumber(const std::string& body, const std::string& key, double* out);
// Tim "key": true|false.
bool JsonGetBool(const std::string& body, const std::string& key, bool* out);
// Tim "key": "<chuoi>". Xu ly escape \" va \\.
bool JsonGetString(const std::string& body, const std::string& key, std::string* out);
} // namespace vslam
#endif // VSLAM_JSON_PARSE_H

View File

@@ -0,0 +1,98 @@
#ifndef VSLAM_LOG_H
#define VSLAM_LOG_H
// Thay ROS_DEBUG / ROS_INFO / ROS_WARN / ROS_ERROR va cac bien the _THROTTLE.
//
// Yeu cau tu hien trang:
// * _THROTTLE la bat buoc, khong phai tien nghi. Nhieu cho trong repo hien
// tai log o tan so cam bien (200 Hz IMU, 30 Hz camera); khong bop lai thi
// journald tren Jetson day o va I/O tro thanh nut co chai that.
// * Throttle phai dung steady_clock, khong phai stamp du lieu. Neu dung
// stamp thi khi replay nhanh (speed=0) moi dong se bi bop nham.
// * Ghi log tuyet doi khong duoc chan vong an toan. Sink mac dinh ghi
// thang ra stderr co khoa; neu sau nay can sink ton kem (file, mang) thi
// phai la sink bat dong bo co hang doi va DROP chu khong block.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <sstream>
#include <string>
namespace vslam {
enum class LogLevel : int { kDebug = 0, kInfo = 1, kWarn = 2, kError = 3, kOff = 4 };
const char* LogLevelName(LogLevel l);
bool ParseLogLevel(const std::string& s, LogLevel* out);
// Sink nhan dong da dinh dang san (khong co newline).
using LogSink = std::function<void(LogLevel, const char* file, int line,
const std::string& msg)>;
void SetLogLevel(LogLevel l);
LogLevel GetLogLevel();
void SetLogSink(LogSink sink);
// Bat/tat mau ANSI. Mac dinh: tu dong theo isatty(stderr).
void SetLogColor(bool on);
namespace detail {
void EmitLog(LogLevel level, const char* file, int line, const std::string& msg);
// Tra ve true neu da du `period_sec` ke tu lan cuoi cho diem goi nay.
// `state` la bien tinh rieng cua tung diem goi.
bool ThrottlePass(std::atomic<int64_t>* state, double period_sec);
} // namespace detail
#define VSLAM_LOG_AT(level, ...) \
do { \
if (static_cast<int>(level) >= static_cast<int>(::vslam::GetLogLevel())) { \
std::ostringstream _vslam_oss; \
_vslam_oss << __VA_ARGS__; \
::vslam::detail::EmitLog((level), __FILE__, __LINE__, _vslam_oss.str()); \
} \
} while (0)
#define VSLAM_DEBUG(...) VSLAM_LOG_AT(::vslam::LogLevel::kDebug, __VA_ARGS__)
#define VSLAM_INFO(...) VSLAM_LOG_AT(::vslam::LogLevel::kInfo, __VA_ARGS__)
#define VSLAM_WARN(...) VSLAM_LOG_AT(::vslam::LogLevel::kWarn, __VA_ARGS__)
#define VSLAM_ERROR(...) VSLAM_LOG_AT(::vslam::LogLevel::kError, __VA_ARGS__)
// Bien the throttle. `period` tinh bang giay, theo steady_clock.
#define VSLAM_LOG_THROTTLE_AT(level, period, ...) \
do { \
static std::atomic<int64_t> _vslam_throttle_state{0}; \
if (::vslam::detail::ThrottlePass(&_vslam_throttle_state, (period))) { \
VSLAM_LOG_AT(level, __VA_ARGS__); \
} \
} while (0)
#define VSLAM_DEBUG_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kDebug, period, __VA_ARGS__)
#define VSLAM_INFO_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kInfo, period, __VA_ARGS__)
#define VSLAM_WARN_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kWarn, period, __VA_ARGS__)
#define VSLAM_ERROR_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kError, period, __VA_ARGS__)
// Chi log mot lan duy nhat cho diem goi nay.
#define VSLAM_LOG_ONCE_AT(level, ...) \
do { \
static std::atomic<bool> _vslam_once{false}; \
bool _vslam_expected = false; \
if (_vslam_once.compare_exchange_strong(_vslam_expected, true)) { \
VSLAM_LOG_AT(level, __VA_ARGS__); \
} \
} while (0)
#define VSLAM_INFO_ONCE(...) VSLAM_LOG_ONCE_AT(::vslam::LogLevel::kInfo, __VA_ARGS__)
#define VSLAM_WARN_ONCE(...) VSLAM_LOG_ONCE_AT(::vslam::LogLevel::kWarn, __VA_ARGS__)
} // namespace vslam
#endif // VSLAM_LOG_H

View File

@@ -0,0 +1,98 @@
#ifndef VSLAM_NODE_CONSTANTS_H
#define VSLAM_NODE_CONSTANTS_H
// Duong dan va hang so toan he, tap trung mot cho.
// Khuon mau: xloc_cpp/include/node_constants.h, voi mot sua loi quan trong.
//
// xloc_cpp/include/node_constants.h:30-31 hardcode
// kMapDirectory = "/home/robotics/.local/share/xloc/resources/maps/"
// kPoseDirectory = "/home/robotics/.local/share/xloc/resources/poses/"
// nen goi .deb cua no khong chay duoc tren may co username khac, va lech han
// voi dich install() o CMakeLists.txt:269-273 (/var/lib/xloc/resources).
//
// O day: mac dinh theo FHS, va co the ghi de bang bien moi truong -- can cho
// viec chay tu build tree khi phat trien va cho test chay song song.
#include <string>
namespace vslam {
// --- Duong dan mac dinh ----------------------------------------------------
constexpr char kConfigurationDirectory[] = "/etc/vslam/configuration_files";
constexpr char kResourceDirectory[] = "/var/lib/vslam/resources";
constexpr char kMapDirectory[] = "/var/lib/vslam/resources/maps";
constexpr char kRecordDirectory[] = "/var/lib/vslam/resources/records";
constexpr char kWebAssetDirectory[] = "/var/lib/vslam/www";
// --- Bien moi truong ghi de ------------------------------------------------
constexpr char kConfigDirEnv[] = "VSLAM_CONFIG_DIR";
constexpr char kResourceDirEnv[] = "VSLAM_RESOURCE_DIR";
constexpr char kCorpusDirEnv[] = "VSLAM_CORPUS_DIR"; // ../vSLAM_ws/maps khi test
// --- Ten file cau hinh -----------------------------------------------------
// Mot file cho mot lib, cong robot.yaml. 14 file YAML cua ban ROS gop lai
// thanh sau file nay.
constexpr char kRobotConfigFile[] = "robot.yaml";
constexpr char kSensorsConfigFile[] = "sensors.yaml";
constexpr char kPipelineConfigFile[] = "pipeline.yaml";
constexpr char kSlamConfigFile[] = "slam.yaml";
constexpr char kSafetyConfigFile[] = "safety.yaml";
constexpr char kSystemConfigFile[] = "system.yaml";
// --- Ten frame -------------------------------------------------------------
// Cay TF: map -> odom -> base_footprint -> base_link -> {laser, camera, imu}
// va camera_link -> camera_depth_optical_frame -> camera_infra1/2.
// Chi BA canh la dong (xem transform_tree.h); con lai tinh, nap tu robot.yaml.
constexpr char kMapFrame[] = "map";
constexpr char kOdomFrame[] = "odom";
constexpr char kBaseFootprintFrame[] = "base_footprint";
constexpr char kBaseLinkFrame[] = "base_link";
constexpr char kLaserFrame[] = "laser_link";
constexpr char kImuFrame[] = "imu_link";
constexpr char kCameraFrame[] = "camera_link";
constexpr char kCameraDepthOpticalFrame[] = "camera_depth_optical_frame";
constexpr char kCameraInfra1OpticalFrame[] = "camera_infra1_optical_frame";
constexpr char kCameraInfra2OpticalFrame[] = "camera_infra2_optical_frame";
// --- Tan so danh dinh ------------------------------------------------------
// Gia tri that nam trong config; nhung hang so nay la mac dinh va la moc de
// RateMonitor canh bao khi lech.
constexpr double kLidarRateHz = 25.0;
constexpr double kCameraRateHz = 30.0;
constexpr double kImuRateHz = 200.0;
constexpr double kEkfRateHz = 50.0;
constexpr double kBaseIoRateHz = 50.0;
constexpr double kSafetyRateHz = 20.0;
constexpr double kWebStateRateHz = 10.0;
// --- Hang so vat ly --------------------------------------------------------
constexpr double kGravity = 9.80665; // m/s^2, khop voi gravity_align_nodelet
// --- Ham tra ve duong dan (co ghi de bang env) -----------------------------
// Thu muc cau hinh: $VSLAM_CONFIG_DIR neu co, khong thi kConfigurationDirectory.
std::string ConfigDir();
// Thu muc tai nguyen: $VSLAM_RESOURCE_DIR neu co, khong thi kResourceDirectory.
std::string ResourceDir();
// ConfigDir() + "/" + file_name
std::string ConfigPath(const std::string& file_name);
// ResourceDir() + "/" + rel
std::string ResourcePath(const std::string& rel);
// Thu muc ban do: ResourceDir() + "/maps"
std::string MapDir();
// Thu muc ban ghi .vsr: ResourceDir() + "/records"
std::string RecordDir();
// Corpus .db de test: $VSLAM_CORPUS_DIR neu co, khong thi MapDir().
// Trong luc port, tro sang ../vSLAM_ws/maps de dung lai map_house.db va
// map_hospital.db ma khong phai copy 3.8 GB.
std::string CorpusDir();
} // namespace vslam
#endif // VSLAM_NODE_CONSTANTS_H

View File

@@ -0,0 +1,112 @@
#ifndef VSLAM_ROBOT_MODEL_H
#define VSLAM_ROBOT_MODEL_H
// Hinh hoc robot + cay frame, nap tu `robot.yaml`. THAY CHO URDF.
//
// ================== VI SAO LOP NAY TON TAI ==================
// Truoc khi co no, phep dung `camera_depth_optical_frame -> base_link` bi
// LAP LAI o bon file (hai tool va hai file test), moi cho mot ban chep cua
// cung mot chuoi QuaternionMultiply. Va `cliff_detect.nominal_tz = 0.803` da
// lech voi `sim.camera_z = 0.80` -- hai con so le ra phai la MOT.
//
// Do dung la lop bug "hai cho phai giu dong bo" ma `PROJECT_CONTEXT.md:71`
// cua repo cu da ghi nhan giua URDF va launch param.
//
// Quy tac: KHONG stage nao duoc tu dung lai mot phep bien doi tu cac so trong
// robot.yaml. Moi stage goi `RobotModel::StaticTransform()` hoac lay tu
// `tree()`.
#include <memory>
#include <string>
#include <vector>
#include "vslam/config.h"
#include "vslam/transform_tree.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct RobotGeometry {
double wheel_radius = 0.075;
double wheel_separation = 0.36;
double robot_radius = 0.24;
double body_half_width = 0.17;
};
struct BaseLimits {
double max_linear = 0.35;
double max_angular = 0.80;
double accel_limit = 0.30;
double cmd_timeout = 0.30;
};
struct WheelOdomNoise {
double sigma_x_per_m = 0.02;
double sigma_y_per_m = 0.02;
double sigma_yaw_per_rad = 0.05;
double slip_threshold = 0.20;
bool slip_sigma_is_measured = true;
};
class RobotModel {
public:
RobotModel();
~RobotModel();
RobotModel(const RobotModel&) = delete;
RobotModel& operator=(const RobotModel&) = delete;
// Nap tu node goc cua robot.yaml. Tra loi thay vi nem: nguoi goi quyet dinh
// dung han hay chay voi mac dinh.
//
// Kiem, va TU CHOI neu sai:
// - canh trung lap (hai dong cung `child`) -- cai sau se am tham thang;
// - canh tao chu trinh;
// - `child` mo coi (parent khong ton tai va khong phai base_link);
// - khoa la trong `geometry:` / `base:` / `wheel_odom:` (go sai ten).
StatusResponse Load(const ConfigNode& root);
// Nap tu duong dan file. Tien loi cho tool.
StatusResponse LoadFile(const std::string& path);
const RobotGeometry& geometry() const { return geometry_; }
const BaseLimits& base() const { return base_; }
const WheelOdomNoise& wheel_odom() const { return wheel_odom_; }
// Cay frame, DA nap moi canh tinh. Ba canh dong (map->odom,
// odom->base_footprint, base_footprint->base_link) do cac stage tuong ung
// ghi vao, moi canh dung mot writer.
TransformTree& tree() { return *tree_; }
const TransformTree& tree() const { return *tree_; }
// Phep bien doi TINH giua hai frame. Chi di qua cac canh tinh, nen khong
// can dau thoi gian va khong bao gio "chua co du lieu".
//
// Tra false neu mot trong hai frame khong ton tai hoac duong di di qua mot
// canh dong -- truong hop do phai dung tree().Lookup() voi stamp.
bool StaticTransform(const std::string& target, const std::string& source,
Transform* out) const;
// Chieu cao camera so voi MAT SAN (khong phai so voi tam truc).
//
// Day chinh la `tz` ma cliff_detect mong doi, va la ly do
// `cliff_detect.nominal_tz` KHONG duoc go tay: no la
// camera_link.z + wheel_radius, tinh tu cung mot nguon.
double camera_height_above_floor() const;
// Goc chuc xuong cua camera (rad), lay tu canh base_link -> camera_link.
double camera_pitch() const;
private:
RobotGeometry geometry_;
BaseLimits base_;
WheelOdomNoise wheel_odom_;
std::unique_ptr<TransformTree> tree_;
double camera_z_in_base_link_ = 0.0;
double camera_pitch_ = 0.0;
bool have_camera_ = false;
};
} // namespace vslam
#endif // VSLAM_ROBOT_MODEL_H

View File

@@ -0,0 +1,125 @@
#ifndef VSLAM_STATS_H
#define VSLAM_STATS_H
// Do dac runtime. Khong phai tien nghi -- day la thu ROS khong cho va vi vay
// repo cu phai doan mo:
// * khong biet mot subscriber bo lo bao nhieu ban tin (queue ROS drop im lang)
// * khong biet mot chuoi nodelet tre bao nhieu
// Moi Channel va moi stage deu phai bao cao duoc so lieu nay ra /api/status.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
#include "vslam/clock.h"
namespace vslam {
// Do tan so bang cua so truot, dung steady_clock.
// An toan cho mot nguoi ghi + nhieu nguoi doc.
class RateMonitor {
public:
explicit RateMonitor(double window_sec = 2.0);
// Goi moi lan co su kien.
void Tick(std::chrono::steady_clock::time_point now);
void Tick(); // dung steady_clock::now(), chi cho main/tool
// Hz uoc luong trong cua so. 0 neu chua du mau.
double hz() const;
// Giay ke tu su kien cuoi. +inf neu chua co su kien nao.
double age_sec(std::chrono::steady_clock::time_point now) const;
uint64_t count() const { return count_.load(std::memory_order_relaxed); }
void Reset();
private:
const double window_sec_;
std::atomic<uint64_t> count_{0};
std::atomic<int64_t> first_ns_{0}; // moc cua so hien tai
std::atomic<int64_t> last_ns_{0};
std::atomic<uint64_t> window_count_{0};
std::atomic<double> hz_{0.0};
};
// Dem su kien bi bo. Chia hai loai vi chung co nguyen nhan khac han nhau.
struct DropCounter {
std::atomic<uint64_t> total{0};
void Add(uint64_t n = 1) { total.fetch_add(n, std::memory_order_relaxed); }
uint64_t get() const { return total.load(std::memory_order_relaxed); }
void Reset() { total.store(0, std::memory_order_relaxed); }
};
// So lieu cua mot Channel.
struct ChannelStats {
std::string name;
uint64_t capacity = 0;
uint64_t published = 0; // tong so ban tin da Publish()
uint64_t overwritten = 0; // so ban tin bi ghi de truoc khi moi reader doc xong
uint64_t readers = 0;
uint64_t max_reader_lag = 0; // reader tut hau nhat, tinh bang so ban tin
uint64_t total_reader_drops = 0;
double hz = 0.0;
};
// So lieu cua ApproxTimeSync.
struct SyncStats {
uint64_t matched = 0;
uint64_t dropped_slop = 0; // co ban tin nhung lech thoi gian qua max_slop
uint64_t dropped_timeout = 0; // het han cho, phat voi input tuy chon de trong
uint64_t dropped_queue = 0; // pivot bi day ra khoi hang doi truoc khi khop
double last_slop_sec = 0.0;
};
// So lieu cua mot driver phan cung.
struct DriverStats {
double hz = 0.0;
uint64_t frames = 0;
uint64_t errors = 0;
uint64_t packets_lost = 0; // LiDAR: suy ra tu do dai sweep
uint64_t short_sweeps = 0; // sweep thieu tia
double stamp_skew_ms = 0.0; // MCU: lech dong ho host <-> thiet bi
double clock_skew_ppm = 0.0; // MCU: he so skew cua ClockSync, tinh theo ppm
bool connected = false;
std::string last_error;
};
// Do thoi luong mot doan code, giu p50/p95/max.
// Dung cho process_ms cua SLAM va cho vong perception.
class LatencyMonitor {
public:
explicit LatencyMonitor(size_t window = 128);
~LatencyMonitor();
void Add(double ms);
double p50() const;
double p95() const;
double max() const;
double last() const;
uint64_t count() const;
void Reset();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
// RAII: do thoi gian song cua object roi day vao LatencyMonitor.
class ScopedLatency {
public:
ScopedLatency(LatencyMonitor* m, const Clock* clock);
~ScopedLatency();
private:
LatencyMonitor* m_;
std::chrono::steady_clock::time_point t0_;
};
} // namespace vslam
#endif // VSLAM_STATS_H

View File

@@ -0,0 +1,144 @@
#ifndef VSLAM_TELEOP_MODEL_H
#define VSLAM_TELEOP_MODEL_H
// Mo hinh trang thai teleop.
//
// ============ NGUON GOC ============
// Port tu robot_bringup/scripts/teleop_model.py cua vSLAM_ws, ma ban than no
// duoc port tu package `virtual_joystick_teleop` (BSD-3-Clause), tac gia
// duongtd, https://git.pnkr.asia/DuongTD/virtual_joystick_teleop.git
//
// LOGIC GIU NGUYEN VEN. Day la ban dich sang C++, khong phai ban viet lai:
// moi nguong, moi thu tu uu tien, moi phep kep deu giong het ban Python.
// test_teleop_model.cc so ket qua voi vector sinh tu chinh ban Python do.
//
// ============ VI SAO KHONG VIET LAI BANG JS ============
// Ban dau toi viet mot joystick moi hoan toan trong app.js va bo qua file
// nay. Do la sai: mo hinh nay da chay that, da duoc chinh theo cam giac lai
// that, va co nhung thu mot ban viet voi khong co -- nhat la toc do chinh
// duoc khi dang chay.
//
// Trang web chi gui truc joystick da chuan hoa [-1, 1] va su kien phim.
// TOAN BO viec quy ra van toc nam o day, trong C++.
//
// ============ BA NGUON NHAP, CO THU TU UU TIEN ============
// manual (thanh truot kieu rqt) -- cao nhat
// joystick (truc analog)
// phim mui ten -- thap nhat
// Dat mot nguon se GIAI PHONG cac nguon khac. Khong bao gio tron hai nguon.
//
// LUU Y: mo hinh nay KHONG co ramp gia toc. Ramp nam o tang duoi (gioi han
// gia toc cua base). Do la dung: teleop noi "muon di bao nhanh", con base noi
// "den do nhanh duoc bao nhieu".
#include <set>
#include <string>
#include <utility>
namespace vslam {
enum class TeleopKey { kUp, kDown, kLeft, kRight };
// Tra ve false neu ten phim khong duoc ho tro. Ten khop ban Python:
// "Up", "Down", "Left", "Right".
bool ParseTeleopKey(const std::string& name, TeleopKey* out);
const char* TeleopKeyName(TeleopKey k);
struct TeleopConfig {
double linear_speed = 0.30; // scale hien tai, chinh duoc luc chay
double angular_speed = 0.70;
double linear_step = 0.05; // buoc chinh
double angular_step = 0.10;
double min_linear_speed = 0.05; // gioi han cua scale
double max_linear_speed = 2.00;
double min_angular_speed = 0.10;
double max_angular_speed = 2.00;
// Gioi han duoi cua LENH (co dau). Mac dinh = -max_*_speed.
// Tach rieng de gioi han lui khac gioi han tien duoc.
bool has_min_linear_command = false;
double min_linear_command = 0.0;
bool has_min_angular_command = false;
double min_angular_command = 0.0;
};
class TeleopModel {
public:
// Nem std::invalid_argument neu cau hinh vo ly, giong ban Python nem
// ValueError. Kiem o day chu khong im lang roi ve default: mot gioi han
// van toc sai la mot robot chay nhanh hon nguoi lai nghi.
explicit TeleopModel(TeleopConfig cfg = TeleopConfig());
// --- Nguon nhap ----------------------------------------------------------
// Dat trang thai mot phim. Tra false neu phim khong ho tro.
bool SetKey(TeleopKey key, bool pressed);
void ClearKeys();
// Truc analog trong [-1, 1] tu joystick chuot/cham.
void SetJoystick(double horizontal, double vertical);
void ReleaseJoystick();
// Lenh co dau ben vung, kieu thanh truot rqt.
// Truyen nullptr cho truc khong muon doi.
std::pair<double, double> SetManualCommand(const double* linear_x,
const double* angular_z);
void ReleaseManualControl();
// Nha het moi nguon -> lenh ve 0.
void ClearMotion();
// --- Ket qua -------------------------------------------------------------
// (linear_x m/s, angular_z rad/s).
std::pair<double, double> Command() const;
// Truc hien thi [-1, 1] cho knob tren trang. Phim mui ten cung lam knob
// dich -- de nguoi lai thay duoc minh dang bam gi.
std::pair<double, double> JoystickPosition() const;
// --- Chinh toc do luc dang chay -----------------------------------------
double AdjustLinearSpeed(double direction);
double AdjustAngularSpeed(double direction);
double SetLinearSpeed(double value);
double SetAngularSpeed(double value);
double SetMaxLinearSpeed(double value);
double SetMaxAngularSpeed(double value);
double SetMinLinearCommand(double value);
double SetMinAngularCommand(double value);
// --- Truy van ------------------------------------------------------------
double linear_speed() const { return linear_speed_; }
double angular_speed() const { return angular_speed_; }
double max_linear_speed() const { return max_linear_speed_; }
double max_angular_speed() const { return max_angular_speed_; }
double min_linear_command() const { return min_linear_command_; }
double min_angular_command() const { return min_angular_command_; }
bool joystick_active() const { return joystick_active_; }
bool manual_control_active() const { return manual_active_; }
bool key_pressed(TeleopKey k) const { return keys_.count(k) != 0; }
private:
std::pair<double, double> ClampCommand(double linear_x, double angular_z) const;
void ClampManualCommand();
double linear_step_, angular_step_;
double min_linear_speed_, max_linear_speed_;
double min_angular_speed_, max_angular_speed_;
double min_linear_command_, min_angular_command_;
double linear_speed_, angular_speed_;
std::set<TeleopKey> keys_;
bool joystick_active_ = false;
double joy_h_ = 0.0, joy_v_ = 0.0;
bool manual_active_ = false;
double manual_lin_ = 0.0, manual_ang_ = 0.0;
};
} // namespace vslam
#endif // VSLAM_TELEOP_MODEL_H

View File

@@ -0,0 +1,169 @@
#ifndef VSLAM_TRANSFORM_TREE_H
#define VSLAM_TRANSFORM_TREE_H
// Thay tf2_ros::Buffer.
//
// Khong dung tf3 (github.com/Huandaotien/tf3, cai ma xloc_cpp dung) vi:
// submodule third_party/tf3 chua bao gio duoc checkout nen khong kiem chung
// duoc, license cua fork ca nhan chua ro, va no la thu vien TONG QUAT cho cay
// tuy y voi re-parent va da publisher. Bai toan o day hep hon nhieu.
//
// BE MAT API van giu tuong thich tf3 (lookupTransform / setTransform) de sau
// nay muon doi sang tf3 chi la thay header.
//
// CAY TF CUA HE NAY -- 9 frame, va chi BA canh la dong:
//
// map
// | <- slam, ~1 Hz, tu getMapCorrection()
// odom
// | <- ekf, 50 Hz
// base_footprint
// | <- gravity_align, 50 Hz (roll/pitch DO duoc)
// base_link
// |-- laser_link tinh
// |-- imu_link tinh
// `-- camera_link tinh
// `-- camera_depth_optical_frame tinh
// |-- camera_infra1_optical_frame tinh
// `-- camera_infra2_optical_frame tinh
//
// Moi canh tinh nap tu robot.yaml. Day chinh la thu THAY URDF, va no xoa luon
// bug "hai cho phai giu dong bo" ma PROJECT_CONTEXT.md ghi: hien gia tri hinh
// hoc nam ca trong robot.urdf.xacro lan robot.yaml.
//
// QUY TAC BAT BUOC: MOI CANH CO DUNG MOT NGUOI GHI.
// Vi pham quy tac nay la lop bug TF kho debug nhat. localization.launch cua
// repo cu da phai canh bao dieu nay bang mot khoi comment o dau file.
//
// Vi cha cua moi frame co dinh luc khoi tao, duong di child->root duoc tinh
// truoc thanh mot mang: vong lookup khong tra map, khong cap phat.
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
using FrameId = uint16_t;
constexpr FrameId kInvalidFrame = 0xFFFF;
class TransformTree {
public:
// history_sec: giu bao lau lich su canh dong.
// slots_per_edge: so mau moi canh dong (ring buffer).
// 50 Hz * 10 s = 500, nen 512 la du cho canh nhanh nhat.
explicit TransformTree(double history_sec = 10.0, size_t slots_per_edge = 512);
~TransformTree();
TransformTree(const TransformTree&) = delete;
TransformTree& operator=(const TransformTree&) = delete;
// --- Dang ky frame ------------------------------------------------------
// Tra ve id on dinh cho ten frame. Goi nhieu lan cung ten tra cung id.
// Chuoi chi bam MOT LAN o day; moi thao tac sau deu dung FrameId.
FrameId Resolve(const std::string& name);
// kInvalidFrame neu chua dang ky.
FrameId Find(const std::string& name) const;
const std::string& Name(FrameId id) const;
size_t frame_count() const;
// --- Canh tinh ----------------------------------------------------------
// Dat canh tinh parent -> child. Goi lai voi cung cap se GHI DE (cho phep,
// vi nap lai config la thao tac hop le).
// Nem ConfigError neu tao vong.
StatusResponse SetStatic(FrameId parent, FrameId child, const Transform& tf);
StatusResponse SetStatic(const std::string& parent, const std::string& child,
const Transform& tf);
// --- Canh dong ----------------------------------------------------------
// Dat mau moi cho canh dong parent -> child.
//
// Tra false neu:
// * stamp lui ve qua khu so voi mau moi nhat (du hieu ban ghi bi xao tron
// thu tu, hoac hai nguoi cung ghi mot canh -- vi pham quy tac tren)
// * canh nay da duoc khai la tinh
//
// Lan goi dau tien tren mot cap (parent, child) se dang ky canh do la dong.
bool SetTransform(FrameId parent, FrameId child, UnixTime stamp,
const Transform& tf);
// --- Tra cuu ------------------------------------------------------------
// Bien doi dua diem tu `source` sang `target` tai thoi diem `stamp`.
//
// Noi suy: LERP tinh tien + SLERP quay giua hai mau kep `stamp`.
// Ngoai suy: TU CHOI neu stamp > mau moi nhat + extrapolation_limit.
// Day la khac biet co y voi tf2: tf2 nem TransformExtrapolationException va
// rat nhieu code goi bat roi bo qua im lang. O day tra false va dien `err`.
bool Lookup(FrameId target, FrameId source, UnixTime stamp, Transform* out,
std::string* err = nullptr) const;
bool Lookup(const std::string& target, const std::string& source, UnixTime stamp,
Transform* out, std::string* err = nullptr) const;
// Dung mau moi nhat cua tung canh, khong noi suy. Tuong duong
// lookupTransform(..., ros::Time(0), ...) cua tf2.
bool LookupLatest(FrameId target, FrameId source, Transform* out,
std::string* err = nullptr) const;
// Thoi diem moi nhat ma CA HAI nhanh deu co du lieu. kTimeZero neu khong co.
UnixTime LatestCommonTime(FrameId a, FrameId b) const;
// Co du lieu de tra cuu tai `stamp` khong, khong thuc su tinh.
bool CanTransform(FrameId target, FrameId source, UnixTime stamp) const;
// --- Cau hinh -----------------------------------------------------------
void SetExtrapolationLimit(double sec);
double extrapolation_limit() const;
// Danh sach canh dong kem tan so va tuoi mau moi nhat -- ra /api/status.
struct EdgeStatus {
std::string parent;
std::string child;
bool is_static = false;
uint64_t samples = 0;
UnixTime latest;
double hz = 0.0;
};
std::vector<EdgeStatus> EdgeStatuses() const;
// In cay ra chuoi nhieu dong, dung de chan doan. Thay rqt_tf_tree.
std::string DumpTree() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
using TransformTreePtr = std::shared_ptr<TransformTree>;
// Tuong duong xloc_cpp/include/tf_bridge.h: thu hep be mat xuong dung mot
// thao tac ma cac stage can -- dua mot frame ve frame theo doi.
class TfBridge {
public:
TfBridge(std::string tracking_frame, double lookup_timeout_sec,
std::shared_ptr<const TransformTree> tree);
bool LookupToTracking(UnixTime time, FrameId frame, Transform* out) const;
bool LookupToTracking(UnixTime time, const std::string& frame, Transform* out) const;
const std::string& tracking_frame() const { return tracking_frame_; }
private:
std::string tracking_frame_;
double lookup_timeout_sec_;
std::shared_ptr<const TransformTree> tree_;
};
} // namespace vslam
#endif // VSLAM_TRANSFORM_TREE_H

View File

@@ -0,0 +1,197 @@
#ifndef VSLAM_UNIX_TIME_H
#define VSLAM_UNIX_TIME_H
// Thay ros::Time / ros::Duration.
//
// Dua tren xloc_cpp/include/unix_time.h, giu nguyen layout {uint32 sec, nsec}
// de tuong thich API voi xloc. Ba sua loi so voi ban goc:
//
// 1. fromSec() voi input am: ban goc lam static_cast<uint32_t>(std::floor(s))
// -> tran im lang. Ban nay kep ve 0 va co fromSecChecked() de goi biet.
// 2. So hoc noi bo lam bang int64_t nanoseconds. Ban goc ep hieu hai UnixTime
// sang int32_t; nam 2038 se tran, va ngay bay gio thi sec ~1.7e9 da sat
// gioi han 2.1e9 cua int32_t.
// 3. TIME_MAX: ban goc dat trong anonymous namespace TRONG HEADER, nen moi
// translation unit co mot ban sao rieng (va sinh canh bao unused). Ban nay
// dung `inline constexpr` cua C++17.
//
// QUY TAC HAI DONG HO -- doc ky truoc khi dung:
// * UnixTime dung de DONG DAU du lieu (stamp). Nguon la system_clock, co the
// nhay khi NTP dieu chinh.
// * Timeout, chu ky, do thoi luong PHAI dung std::chrono::steady_clock.
// Lan lon hai thu nay la lop bug dang co trong safety_monitor_node.cpp: no
// dung ros::Time::now() cho ca hai, nen mot buoc NTP sau khi Jetson bat WiFi
// lam (now - last_cmd_time_) nhay vot -> NO_CMD dung robot dot ngot, hoac
// nhay lui -> watchdog khong bao gio kich.
// Xem clock.h: moi stage nhan Clock& thay vi goi UnixTime::now() truc tiep.
#include <cstdint>
#include <cstdlib>
#include <cmath>
#include <chrono>
#include <limits>
#include <string>
#include <thread>
namespace vslam {
class Duration;
constexpr int64_t kNsPerSec = 1000000000LL;
class UnixTime {
public:
uint32_t sec;
uint32_t nsec;
constexpr UnixTime() : sec(0), nsec(0) {}
constexpr UnixTime(uint32_t s, uint32_t ns) : sec(s), nsec(ns) {}
static UnixTime now() {
using namespace std::chrono;
const auto ns =
duration_cast<nanoseconds>(system_clock::now().time_since_epoch()).count();
return fromNSec(ns);
}
static constexpr UnixTime fromNSec(int64_t ns) {
return ns <= 0 ? UnixTime()
: UnixTime(static_cast<uint32_t>(ns / kNsPerSec),
static_cast<uint32_t>(ns % kNsPerSec));
}
// Input am bi kep ve 0. Ban goc tran im lang o day.
static UnixTime fromSec(double s) {
if (!(s > 0.0)) return UnixTime(); // bat ca NaN
return fromNSec(static_cast<int64_t>(std::llround(s * 1e9)));
}
// Nhu fromSec() nhung bao cho goi biet input co hop le khong.
static bool fromSecChecked(double s, UnixTime* out) {
if (!(s >= 0.0) || s > static_cast<double>(std::numeric_limits<uint32_t>::max())) {
return false;
}
*out = fromNSec(static_cast<int64_t>(std::llround(s * 1e9)));
return true;
}
constexpr int64_t toNSec() const {
return static_cast<int64_t>(sec) * kNsPerSec + static_cast<int64_t>(nsec);
}
constexpr double toSec() const {
return static_cast<double>(sec) + static_cast<double>(nsec) * 1e-9;
}
constexpr bool isZero() const { return sec == 0 && nsec == 0; }
constexpr bool operator==(const UnixTime& o) const {
return sec == o.sec && nsec == o.nsec;
}
constexpr bool operator!=(const UnixTime& o) const { return !(*this == o); }
constexpr bool operator<(const UnixTime& o) const {
return sec < o.sec || (sec == o.sec && nsec < o.nsec);
}
constexpr bool operator>(const UnixTime& o) const { return o < *this; }
constexpr bool operator<=(const UnixTime& o) const { return !(*this > o); }
constexpr bool operator>=(const UnixTime& o) const { return !(*this < o); }
friend Duration operator-(const UnixTime& a, const UnixTime& b);
friend UnixTime operator+(const UnixTime& t, const Duration& d);
friend UnixTime operator-(const UnixTime& t, const Duration& d);
// Giu lai dang ham de tuong thich voi ma goi theo kieu xloc.
static constexpr UnixTime TIME_MAX() {
return UnixTime(std::numeric_limits<uint32_t>::max(),
static_cast<uint32_t>(kNsPerSec - 1));
}
// "1737000000.123456789" -- dung cho log va JSON, khong mat do chinh xac
// nhu khi in double.
std::string toString() const;
};
inline constexpr UnixTime kTimeMax = UnixTime::TIME_MAX();
inline constexpr UnixTime kTimeZero = UnixTime();
class Duration {
public:
int32_t sec;
int32_t nsec;
constexpr Duration() : sec(0), nsec(0) {}
Duration(int32_t s, int32_t ns) : sec(s), nsec(ns) { normalize(); }
explicit Duration(double seconds) { *this = fromNSec(static_cast<int64_t>(std::llround(seconds * 1e9))); }
static Duration fromSec(double s) { return Duration(s); }
static Duration fromNSec(int64_t ns_total) {
Duration d;
d.sec = static_cast<int32_t>(ns_total / kNsPerSec);
d.nsec = static_cast<int32_t>(ns_total % kNsPerSec);
d.normalize();
return d;
}
constexpr int64_t toNSec() const {
return static_cast<int64_t>(sec) * kNsPerSec + static_cast<int64_t>(nsec);
}
constexpr double toSec() const {
return static_cast<double>(sec) + static_cast<double>(nsec) * 1e-9;
}
constexpr bool isZero() const { return sec == 0 && nsec == 0; }
void normalize() {
if (nsec >= kNsPerSec) {
sec += static_cast<int32_t>(nsec / kNsPerSec);
nsec = static_cast<int32_t>(nsec % kNsPerSec);
} else if (nsec < 0) {
const int32_t borrow = (std::abs(nsec) / static_cast<int32_t>(kNsPerSec)) + 1;
sec -= borrow;
nsec += borrow * static_cast<int32_t>(kNsPerSec);
}
}
Duration operator+(const Duration& o) const { return fromNSec(toNSec() + o.toNSec()); }
Duration operator-(const Duration& o) const { return fromNSec(toNSec() - o.toNSec()); }
Duration operator-() const { return fromNSec(-toNSec()); }
Duration& operator+=(const Duration& o) { *this = *this + o; return *this; }
Duration& operator-=(const Duration& o) { *this = *this - o; return *this; }
constexpr bool operator==(const Duration& o) const { return sec == o.sec && nsec == o.nsec; }
constexpr bool operator!=(const Duration& o) const { return !(*this == o); }
bool operator<(const Duration& o) const { return toNSec() < o.toNSec(); }
bool operator>(const Duration& o) const { return o < *this; }
bool operator<=(const Duration& o) const { return !(*this > o); }
bool operator>=(const Duration& o) const { return !(*this < o); }
// Chi dung o main/tool. Trong stage phai dung Clock::SleepUntil() de replay
// tat dinh chay duoc.
void sleep() const {
const int64_t ns = toNSec();
if (ns <= 0) return;
std::this_thread::sleep_for(std::chrono::nanoseconds(ns));
}
};
inline Duration operator-(const UnixTime& a, const UnixTime& b) {
return Duration::fromNSec(a.toNSec() - b.toNSec());
}
inline UnixTime operator+(const UnixTime& t, const Duration& d) {
return UnixTime::fromNSec(t.toNSec() + d.toNSec());
}
inline UnixTime operator-(const UnixTime& t, const Duration& d) {
return UnixTime::fromNSec(t.toNSec() - d.toNSec());
}
// Giay troi qua giua hai stamp. Dung cho moi phep so sanh timeout theo stamp
// du lieu (khong phai timeout tuong doi -- cai do dung steady_clock).
inline double SecondsBetween(const UnixTime& later, const UnixTime& earlier) {
return static_cast<double>(later.toNSec() - earlier.toNSec()) * 1e-9;
}
} // namespace vslam
#endif // VSLAM_UNIX_TIME_H

View File

@@ -0,0 +1,272 @@
#ifndef VSLAM_VSLAM_COMMON_H
#define VSLAM_VSLAM_COMMON_H
// Dinh nghia lai cac kieu ban tin thuong dung, thay cho sensor_msgs /
// geometry_msgs / nav_msgs. Khuon mau: xloc_cpp/include/xloc_common.h.
//
// HAI QUY TAC BAT BUOC cho moi struct trong file nay:
//
// 1. KHONG chua kieu Eigen fixed-size (Eigen::Vector3d, Matrix4d, ...).
// Dung double x, y, z. Eigen fixed-size co yeu cau can chinh 16/32 byte;
// dat chung trong struct di qua bien .so la nguon loi alignment kinh dien
// tren arm64 khi hai phia compile voi EIGEN_MAX_ALIGN_BYTES khac nhau.
// Chuyen sang Eigen o trong ham, khong o trong kieu du lieu.
//
// 2. KHONG include header cua ROS, PCL, OpenCV hay RTAB-Map. File nay phai
// compile duoc voi mot Eigen-less, PCL-less toolchain. Cac lib phia tren
// tu chuyen doi sang kieu cua ho o bien cua minh.
//
// Vung du lieu lon (anh, point cloud, scan) luon di qua he thong duoi dang
// std::shared_ptr<const T>. Khong bao gio copy. Xem channel.h.
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "vslam/unix_time.h"
namespace vslam {
// ---------------------------------------------------------------------------
// Trang thai tra ve
// ---------------------------------------------------------------------------
enum class StatusCode : int32_t {
kOk = 0,
kInvalidArgument = 1,
kNotFound = 2,
kFailedPrecondition = 3,
kUnavailable = 4,
kTimeout = 5,
kInternal = 6,
kUnauthenticated = 7,
};
struct StatusResponse {
StatusCode code = StatusCode::kOk;
std::string message;
bool ok() const { return code == StatusCode::kOk; }
explicit operator bool() const { return ok(); }
static StatusResponse Ok() { return {}; }
static StatusResponse Error(StatusCode c, std::string m) {
return StatusResponse{c, std::move(m)};
}
};
// ---------------------------------------------------------------------------
// std_msgs
// ---------------------------------------------------------------------------
struct Header {
uint32_t seq = 0;
UnixTime stamp;
std::string frame_id;
};
// ---------------------------------------------------------------------------
// geometry_msgs
// ---------------------------------------------------------------------------
struct Point {
double x = 0.0, y = 0.0, z = 0.0;
};
struct Vector3 {
double x = 0.0, y = 0.0, z = 0.0;
};
struct Quaternion {
double x = 0.0, y = 0.0, z = 0.0, w = 1.0;
};
struct Pose {
Point position;
Quaternion orientation;
};
struct Pose2D {
double x = 0.0, y = 0.0, theta = 0.0;
};
struct PoseStamped {
Header header;
Pose pose;
};
struct PoseWithCovariance {
Pose pose;
double covariance[36] = {}; // row-major 6x6: x y z roll pitch yaw
};
struct PoseWithCovarianceStamped {
Header header;
PoseWithCovariance pose;
};
struct Twist {
Vector3 linear;
Vector3 angular;
};
struct TwistWithCovariance {
Twist twist;
double covariance[36] = {};
};
// Phep bien doi cung. Dung trong TransformTree.
struct Transform {
Vector3 translation;
Quaternion rotation;
};
struct TransformStamped {
Header header; // header.frame_id = frame CHA
std::string child_frame_id;
Transform transform;
};
// ---------------------------------------------------------------------------
// nav_msgs
// ---------------------------------------------------------------------------
struct Odometry {
Header header; // header.frame_id = frame tham chieu (vd "odom")
std::string child_frame_id; // vd "base_footprint"
PoseWithCovariance pose;
TwistWithCovariance twist;
};
// value: -1 = chua biet, 0..100 = xac suat bi chiem.
// Bo cuc giong nav_msgs/OccupancyGrid: hang chinh, goc o (origin), o (0,0)
// nam o phan tu data[0].
struct OccupancyGrid {
Header header;
float resolution = 0.05f; // met / o
uint32_t width = 0;
uint32_t height = 0;
Pose origin; // goc duoi-trai cua o (0,0), trong frame header
std::vector<int8_t> data; // size = width * height
};
// ---------------------------------------------------------------------------
// sensor_msgs
// ---------------------------------------------------------------------------
struct Imu {
Header header;
Quaternion orientation;
double orientation_covariance[9] = {}; // [0] < 0 nghia la khong co orientation
Vector3 angular_velocity; // rad/s
double angular_velocity_covariance[9] = {};
Vector3 linear_acceleration; // m/s^2
double linear_acceleration_covariance[9] = {};
};
struct FluidPressure {
Header header;
double fluid_pressure = 0.0; // Pa
double variance = 0.0;
};
struct Temperature {
Header header;
double temperature = 0.0; // do C
double variance = 0.0;
};
// BA NGU NGHIA CUA MOT TIA -- doc truoc khi cham vao bat cu code nao doc scan.
// Duoc dinh nghia o scan_sanitizer va safety_monitor dua vao dung ba thu nay:
//
// NaN : khong do duoc (duoi range_min, hoac driver tra 0).
// +inf : do duoc nhung khong co phan xa (vuot range_max).
// range_max + 1.0 : SENTINEL -- tia bi che boi than robot, da bi cat co
// y boi sector mask. KHAC HAN voi hai truong hop tren:
// day khong phai "khong thay gi", ma la "khong duoc
// phep nhin". safety_monitor dem rieng so tia nay
// (front_blanked) va khong tinh vao front_usable.
//
// Nham ba thu nay lai lam robot hoac dung im (SCAN_SPARSE) hoac dam vao tuong.
struct LaserScan {
Header header;
float angle_min = 0.0f; // rad
float angle_max = 0.0f;
float angle_increment = 0.0f;
float time_increment = 0.0f; // giay giua hai tia
float scan_time = 0.0f; // giay giua hai sweep
float range_min = 0.0f; // met
float range_max = 0.0f;
std::vector<float> ranges;
std::vector<float> intensities; // co the rong
};
struct CameraInfo {
Header header;
uint32_t width = 0;
uint32_t height = 0;
double k[9] = {}; // ma tran noi 3x3, hang chinh
double d[5] = {}; // meo anh (plumb bob)
uint32_t binning_x = 1;
uint32_t binning_y = 1;
double fx() const { return k[0]; }
double fy() const { return k[4]; }
double cx() const { return k[2]; }
double cy() const { return k[5]; }
// Noi suy sau khi decimate: crop_decimate cua image_proc cap nhat binning
// chu KHONG chia lai K. Consumer phai tu bu, dung nhu image_geometry lam.
double fx_binned() const { return k[0] / static_cast<double>(binning_x); }
double fy_binned() const { return k[4] / static_cast<double>(binning_y); }
double cx_binned() const { return k[2] / static_cast<double>(binning_x); }
double cy_binned() const { return k[5] / static_cast<double>(binning_y); }
};
enum class PixelFormat : uint8_t {
kMono8 = 0, // 8UC1 -- infra1 / infra2
kMono16 = 1, // 16UC1 -- depth thang do theo depth_scale
kFloat32 = 2, // 32FC1 -- depth met
};
// Anh KHONG so huu bo nho khi den tu librealsense: `data` tro vao buffer cua
// SDK va `keep_alive` giu rs2::frame song. Xem realsense_driver.
struct Image {
Header header;
uint32_t width = 0;
uint32_t height = 0;
uint32_t step = 0; // byte moi hang
PixelFormat format = PixelFormat::kMono8;
float depth_scale = 0.001f; // met moi don vi, chi co nghia voi kMono16
const uint8_t* data = nullptr;
std::shared_ptr<void> keep_alive; // giu nguon buffer song
size_t size_bytes() const { return static_cast<size_t>(step) * height; }
};
struct PointXYZ {
float x = 0.0f, y = 0.0f, z = 0.0f;
};
// Cloud phang (khong to chuc theo anh). Cac buoc loc tra ve kieu nay.
struct PointCloudXYZ {
Header header;
std::vector<PointXYZ> points;
bool is_dense = false; // false nghia la co the co NaN
};
// ---------------------------------------------------------------------------
// Bi danh cho con tro chia se -- moi thu di qua Channel deu la kieu nay.
// ---------------------------------------------------------------------------
using LaserScanPtr = std::shared_ptr<const LaserScan>;
using ImuPtr = std::shared_ptr<const Imu>;
using ImagePtr = std::shared_ptr<const Image>;
using PointCloudXYZPtr = std::shared_ptr<const PointCloudXYZ>;
using OccupancyGridPtr = std::shared_ptr<const OccupancyGrid>;
using OdometryPtr = std::shared_ptr<const Odometry>;
} // namespace vslam
#endif // VSLAM_VSLAM_COMMON_H

View File

@@ -0,0 +1,101 @@
#include "vslam/clock.h"
#include <mutex>
#include <thread>
#include "vslam/log.h"
namespace vslam {
namespace {
class SystemClock : public Clock {
public:
UnixTime Now() const override { return UnixTime::now(); }
SteadyPoint Steady() const override { return std::chrono::steady_clock::now(); }
void SleepUntil(SteadyPoint tp) override {
std::this_thread::sleep_until(tp);
}
bool is_virtual() const override { return false; }
};
} // namespace
ClockPtr MakeSystemClock() { return std::make_shared<SystemClock>(); }
// ---------------------------------------------------------------------------
struct ReplayClock::Impl {
mutable std::mutex mu;
UnixTime now;
SteadyPoint steady_origin;
std::chrono::nanoseconds steady_offset{0};
double speed = 0.0; // 0 = chay nhanh nhat, khong ngu that
};
ReplayClock::ReplayClock(UnixTime start) : impl_(std::make_unique<Impl>()) {
impl_->now = start;
impl_->steady_origin = std::chrono::steady_clock::now();
}
ReplayClock::~ReplayClock() = default;
UnixTime ReplayClock::Now() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->now;
}
Clock::SteadyPoint ReplayClock::Steady() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->steady_origin + impl_->steady_offset;
}
void ReplayClock::SleepUntil(SteadyPoint tp) {
double speed;
SteadyPoint current;
{
std::lock_guard<std::mutex> lk(impl_->mu);
speed = impl_->speed;
current = impl_->steady_origin + impl_->steady_offset;
if (tp > current) {
// Thoi gian ao luon tien toi moc yeu cau, ke ca khi khong ngu that.
impl_->steady_offset += (tp - current);
}
}
if (speed > 0.0 && tp > current) {
const auto wall = std::chrono::duration_cast<std::chrono::nanoseconds>(
(tp - current) / speed);
std::this_thread::sleep_for(wall);
}
}
void ReplayClock::SetNow(UnixTime t, bool allow_backward) {
std::lock_guard<std::mutex> lk(impl_->mu);
if (!allow_backward && t < impl_->now) {
// Lui thoi gian la dau hieu ban ghi bi xao tron thu tu. Bao chu khong
// im lang chap nhan -- neu im lang thi moi phep timeout sau do deu sai.
VSLAM_WARN("ReplayClock: tu choi lui thoi gian " << impl_->now.toString()
<< " -> " << t.toString());
return;
}
impl_->now = t;
}
void ReplayClock::Advance(Duration d) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->now = impl_->now + d;
impl_->steady_offset += std::chrono::nanoseconds(d.toNSec());
}
void ReplayClock::SetSpeed(double speed) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->speed = speed < 0.0 ? 0.0 : speed;
}
std::shared_ptr<ReplayClock> MakeReplayClock(UnixTime start) {
return std::make_shared<ReplayClock>(start);
}
} // namespace vslam

View File

@@ -0,0 +1,234 @@
#include "vslam/config.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <sstream>
#include "vslam/log.h"
namespace vslam {
struct ConfigNode::Impl {
YAML::Node node;
std::string path; // "safety.scan.stop_distance"
std::string origin; // ten file
Impl() = default;
Impl(YAML::Node n, std::string p, std::string o)
: node(std::move(n)), path(std::move(p)), origin(std::move(o)) {}
};
namespace {
std::string JoinPath(const std::string& base, const std::string& key) {
return base.empty() ? key : base + "." + key;
}
// Thong bao loi luon co ba manh: file, duong dan key day du, va ly do.
// Thieu bat cu manh nao la nguoi doc phai di tim, va do chinh la thu lam
// viec sua config trong ban ROS ton thoi gian.
//
// Nhan chuoi chu khong nhan ConfigNode::Impl: Impl la kieu private, ham tu do
// trong namespace vo danh khong goi ten no duoc.
std::string Where(const std::string& origin, const std::string& path,
const std::string& key) {
std::ostringstream oss;
oss << origin << ": " << JoinPath(path, key);
return oss.str();
}
} // namespace
ConfigNode::ConfigNode() : impl_(std::make_unique<Impl>()) {}
ConfigNode::ConfigNode(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
ConfigNode::ConfigNode(const ConfigNode& o) : impl_(std::make_unique<Impl>(*o.impl_)) {}
ConfigNode::ConfigNode(ConfigNode&&) noexcept = default;
ConfigNode& ConfigNode::operator=(const ConfigNode& o) {
if (this != &o) impl_ = std::make_unique<Impl>(*o.impl_);
return *this;
}
ConfigNode& ConfigNode::operator=(ConfigNode&&) noexcept = default;
ConfigNode::~ConfigNode() = default;
ConfigNode ConfigNode::LoadFile(const std::string& path) {
try {
YAML::Node root = YAML::LoadFile(path);
return ConfigNode(std::make_unique<Impl>(std::move(root), "", path));
} catch (const YAML::BadFile&) {
throw ConfigError("khong mo duoc file cau hinh: " + path);
} catch (const YAML::Exception& e) {
throw ConfigError("YAML sai cu phap trong " + path + ": " + e.what());
}
}
ConfigNode ConfigNode::LoadString(const std::string& yaml, std::string origin) {
try {
YAML::Node root = YAML::Load(yaml);
return ConfigNode(std::make_unique<Impl>(std::move(root), "", std::move(origin)));
} catch (const YAML::Exception& e) {
throw ConfigError("YAML sai cu phap trong " + origin + ": " + e.what());
}
}
ConfigNode ConfigNode::operator[](const std::string& key) const {
// Key thieu tra node Null thay vi nem, de chuoi a["b"]["c"] khong no giua
// chung. Nguoi goi kiem IsNull() hoac dung require() o buoc cuoi.
if (!impl_->node || !impl_->node.IsMap()) {
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
JoinPath(impl_->path, key), impl_->origin));
}
return ConfigNode(std::make_unique<Impl>(impl_->node[key],
JoinPath(impl_->path, key), impl_->origin));
}
ConfigNode ConfigNode::at(size_t index) const {
std::ostringstream oss;
oss << impl_->path << "[" << index << "]";
if (!impl_->node || !impl_->node.IsSequence() || index >= impl_->node.size()) {
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
oss.str(), impl_->origin));
}
return ConfigNode(std::make_unique<Impl>(impl_->node[index], oss.str(), impl_->origin));
}
bool ConfigNode::IsNull() const {
return !impl_->node || impl_->node.IsNull() ||
impl_->node.Type() == YAML::NodeType::Undefined;
}
bool ConfigNode::IsMap() const { return impl_->node && impl_->node.IsMap(); }
bool ConfigNode::IsSequence() const { return impl_->node && impl_->node.IsSequence(); }
bool ConfigNode::IsScalar() const { return impl_->node && impl_->node.IsScalar(); }
size_t ConfigNode::size() const { return impl_->node ? impl_->node.size() : 0; }
const std::string& ConfigNode::path() const { return impl_->path; }
const std::string& ConfigNode::origin() const { return impl_->origin; }
// --- Doc gia tri -----------------------------------------------------------
template <typename T>
T ConfigNode::get(const std::string& key, const T& fallback) const {
const ConfigNode child = (*this)[key];
if (child.IsNull()) return fallback;
try {
return child.impl_->node.template as<T>();
} catch (const YAML::Exception&) {
// Sai KIEU luon la loi, khac han voi THIEU key. Thieu key co the co y
// (dung default); sai kieu thi khong bao gio co y.
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::require(const std::string& key) const {
const ConfigNode child = (*this)[key];
if (child.IsNull()) {
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": thieu key bat buoc");
}
try {
return child.impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::as() const {
if (IsNull()) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": thieu gia tri");
}
try {
return impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::as(const T& fallback) const {
if (IsNull()) return fallback;
try {
return impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
}
}
// --- Kiem key la -----------------------------------------------------------
std::vector<std::string> ConfigNode::Keys() const {
std::vector<std::string> out;
if (!IsMap()) return out;
for (const auto& kv : impl_->node) {
out.push_back(kv.first.as<std::string>());
}
return out;
}
std::vector<std::string> ConfigNode::UnknownKeys(
const std::vector<std::string>& known) const {
std::vector<std::string> out;
for (const auto& k : Keys()) {
if (std::find(known.begin(), known.end(), k) == known.end()) {
out.push_back(JoinPath(impl_->path, k));
}
}
return out;
}
bool ConfigNode::WarnUnknownKeys(const std::vector<std::string>& known) const {
const auto unknown = UnknownKeys(known);
for (const auto& k : unknown) {
// ERROR chu khong phai WARN: mot key la gan nhu luon la go sai ten cua
// mot key that, nghia la gia tri nguoi dung DINH dat dang khong co tac
// dung. "stop_distence" thay vi "stop_distance" van cho robot chay, chi
// la chay voi khoang cach dung mac dinh.
VSLAM_ERROR(impl_->origin << ": key khong nhan ra: " << k);
}
return unknown.empty();
}
std::vector<std::pair<std::string, std::string>> ConfigNode::AsStringMap() const {
std::vector<std::pair<std::string, std::string>> out;
if (!IsMap()) return out;
for (const auto& kv : impl_->node) {
// Giu nguyen van ca khoa lan gia tri. Khoi `rtabmap:` trong slam.yaml di
// thang vao rtabmap::ParametersMap, noi moi gia tri deu la chuoi -- kiem
// kieu o day se lam hong "true"/"0.05" thanh bool/double roi in lai khac.
out.emplace_back(kv.first.as<std::string>(), kv.second.as<std::string>());
}
return out;
}
// --- Khoi tao tuong minh ---------------------------------------------------
#define VSLAM_CONFIG_DEFINE(T) \
template T ConfigNode::get<T>(const std::string&, const T&) const; \
template T ConfigNode::require<T>(const std::string&) const; \
template T ConfigNode::as<T>() const; \
template T ConfigNode::as<T>(const T&) const;
VSLAM_CONFIG_DEFINE(bool)
VSLAM_CONFIG_DEFINE(int)
VSLAM_CONFIG_DEFINE(unsigned int)
VSLAM_CONFIG_DEFINE(float)
VSLAM_CONFIG_DEFINE(double)
VSLAM_CONFIG_DEFINE(std::string)
#undef VSLAM_CONFIG_DEFINE
template std::vector<double> ConfigNode::get<std::vector<double>>(
const std::string&, const std::vector<double>&) const;
template std::vector<double> ConfigNode::require<std::vector<double>>(
const std::string&) const;
template std::vector<std::string> ConfigNode::get<std::vector<std::string>>(
const std::string&, const std::vector<std::string>&) const;
template std::vector<std::string> ConfigNode::require<std::vector<std::string>>(
const std::string&) const;
} // namespace vslam

View File

@@ -0,0 +1,235 @@
#include "vslam/geometry.h"
#include <algorithm>
namespace vslam {
namespace {
constexpr double kPi = 3.14159265358979323846;
constexpr double kTwoPi = 2.0 * kPi;
} // namespace
// --- Goc -------------------------------------------------------------------
double NormalizeAngle(double a) {
// Port tu wheel_odom_node.cpp:45-50. Ban goc dung vong while; std::fmod
// nhanh hon va khong treo khi input la mot so rat lon (vd NaN lan vao tu
// encoder hong -> vong while chay vo han).
if (!std::isfinite(a)) return 0.0;
a = std::fmod(a + kPi, kTwoPi);
if (a < 0.0) a += kTwoPi;
return a - kPi;
}
// --- Quaternion ------------------------------------------------------------
Quaternion QuaternionFromYaw(double yaw) {
const double h = yaw * 0.5;
return Quaternion{0.0, 0.0, std::sin(h), std::cos(h)};
}
Quaternion QuaternionFromRPY(double roll, double pitch, double yaw) {
const double cr = std::cos(roll * 0.5), sr = std::sin(roll * 0.5);
const double cp = std::cos(pitch * 0.5), sp = std::sin(pitch * 0.5);
const double cy = std::cos(yaw * 0.5), sy = std::sin(yaw * 0.5);
Quaternion q;
q.w = cr * cp * cy + sr * sp * sy;
q.x = sr * cp * cy - cr * sp * sy;
q.y = cr * sp * cy + sr * cp * sy;
q.z = cr * cp * sy - sr * sp * cy;
return q;
}
double YawFromQuaternion(const Quaternion& q) {
const double siny = 2.0 * (q.w * q.z + q.x * q.y);
const double cosy = 1.0 - 2.0 * (q.y * q.y + q.z * q.z);
return std::atan2(siny, cosy);
}
void RPYFromQuaternion(const Quaternion& q, double* roll, double* pitch, double* yaw) {
const double sinr = 2.0 * (q.w * q.x + q.y * q.z);
const double cosr = 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
if (roll) *roll = std::atan2(sinr, cosr);
// Kep truoc khi asin: sai so lam tron co the day gia tri ra ngoai [-1,1]
// va asin tra NaN. NaN o pitch lan vao gravity_align roi vao TF la mot
// trong nhung duong lan truyen loi kho truy nhat.
double sinp = 2.0 * (q.w * q.y - q.z * q.x);
sinp = std::max(-1.0, std::min(1.0, sinp));
if (pitch) *pitch = std::asin(sinp);
if (yaw) *yaw = YawFromQuaternion(q);
}
Quaternion QuaternionNormalized(const Quaternion& q) {
const double n = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
if (n < 1e-12) return Quaternion{0.0, 0.0, 0.0, 1.0};
const double inv = 1.0 / n;
return Quaternion{q.x * inv, q.y * inv, q.z * inv, q.w * inv};
}
Quaternion QuaternionInverse(const Quaternion& q) {
// Gia dinh q da chuan hoa -> nghich dao = lien hop.
return Quaternion{-q.x, -q.y, -q.z, q.w};
}
Quaternion QuaternionMultiply(const Quaternion& a, const Quaternion& b) {
Quaternion r;
r.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
r.x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y;
r.y = a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x;
r.z = a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w;
return r;
}
Quaternion QuaternionSlerp(const Quaternion& a, const Quaternion& b, double t) {
t = std::max(0.0, std::min(1.0, t));
double dot = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
// Lat dau de di duong ngan. Thieu buoc nay thi noi suy qua mot goc gan 360
// do thay vi goc nho -- TF se "quay nguoc" mot cach ngoan muc.
Quaternion bb = b;
if (dot < 0.0) {
bb = Quaternion{-b.x, -b.y, -b.z, -b.w};
dot = -dot;
}
// Gan trung nhau: LERP roi chuan hoa, tranh chia cho sin(theta) ~ 0.
if (dot > 0.9995) {
Quaternion r{a.x + (bb.x - a.x) * t, a.y + (bb.y - a.y) * t,
a.z + (bb.z - a.z) * t, a.w + (bb.w - a.w) * t};
return QuaternionNormalized(r);
}
const double theta_0 = std::acos(dot);
const double theta = theta_0 * t;
const double sin_theta_0 = std::sin(theta_0);
const double s0 = std::cos(theta) - dot * std::sin(theta) / sin_theta_0;
const double s1 = std::sin(theta) / sin_theta_0;
return Quaternion{a.x * s0 + bb.x * s1, a.y * s0 + bb.y * s1,
a.z * s0 + bb.z * s1, a.w * s0 + bb.w * s1};
}
Vector3 RotateVector(const Quaternion& q, const Vector3& v) {
// v' = v + 2w(u x v) + 2(u x (u x v)), voi u la phan vector cua q.
// Re hon chuyen sang ma tran quay khi chi xoay mot vai vector.
const double ux = q.x, uy = q.y, uz = q.z, w = q.w;
const double cx = uy * v.z - uz * v.y;
const double cy = uz * v.x - ux * v.z;
const double cz = ux * v.y - uy * v.x;
const double ccx = uy * cz - uz * cy;
const double ccy = uz * cx - ux * cz;
const double ccz = ux * cy - uy * cx;
return Vector3{v.x + 2.0 * (w * cx + ccx),
v.y + 2.0 * (w * cy + ccy),
v.z + 2.0 * (w * cz + ccz)};
}
// --- Transform -------------------------------------------------------------
Transform TransformIdentity() {
Transform t;
t.translation = Vector3{0.0, 0.0, 0.0};
t.rotation = Quaternion{0.0, 0.0, 0.0, 1.0};
return t;
}
Transform TransformCompose(const Transform& a, const Transform& b) {
Transform r;
r.rotation = QuaternionMultiply(a.rotation, b.rotation);
const Vector3 rb = RotateVector(a.rotation, b.translation);
r.translation = a.translation + rb;
return r;
}
Transform TransformInverse(const Transform& t) {
Transform r;
r.rotation = QuaternionInverse(t.rotation);
const Vector3 neg{-t.translation.x, -t.translation.y, -t.translation.z};
r.translation = RotateVector(r.rotation, neg);
return r;
}
Point TransformPoint(const Transform& t, const Point& p) {
const Vector3 v{p.x, p.y, p.z};
const Vector3 r = RotateVector(t.rotation, v) + t.translation;
return Point{r.x, r.y, r.z};
}
Vector3 TransformVector(const Transform& t, const Vector3& v) {
return RotateVector(t.rotation, v) + t.translation;
}
Transform TransformInterpolate(const Transform& a, const Transform& b, double t) {
Transform r;
r.translation = Lerp(a.translation, b.translation, t);
r.rotation = QuaternionSlerp(a.rotation, b.rotation, t);
return r;
}
// --- SE(2) -----------------------------------------------------------------
Pose2D Pose2DFromPose(const Pose& p) {
return Pose2D{p.position.x, p.position.y, YawFromQuaternion(p.orientation)};
}
Pose PoseFromPose2D(const Pose2D& p, double z) {
Pose out;
out.position = Point{p.x, p.y, z};
out.orientation = QuaternionFromYaw(p.theta);
return out;
}
Pose2D Pose2DCompose(const Pose2D& a, const Pose2D& b) {
const double c = std::cos(a.theta), s = std::sin(a.theta);
return Pose2D{a.x + c * b.x - s * b.y,
a.y + s * b.x + c * b.y,
NormalizeAngle(a.theta + b.theta)};
}
Pose2D Pose2DInverse(const Pose2D& p) {
const double c = std::cos(p.theta), s = std::sin(p.theta);
return Pose2D{-(c * p.x + s * p.y),
-(-s * p.x + c * p.y),
NormalizeAngle(-p.theta)};
}
Pose2D Pose2DBetween(const Pose2D& a, const Pose2D& b) {
// a^-1 * b, viet truc tiep thay vi ghep hai ham -- it phep tinh hon va
// day la duong nong khi tinh delta giua hai keyframe.
const double c = std::cos(a.theta), s = std::sin(a.theta);
const double dx = b.x - a.x, dy = b.y - a.y;
return Pose2D{c * dx + s * dy,
-s * dx + c * dy,
NormalizeAngle(b.theta - a.theta)};
}
Transform TransformFromPose2D(const Pose2D& p, double z) {
Transform t;
t.translation = Vector3{p.x, p.y, z};
t.rotation = QuaternionFromYaw(p.theta);
return t;
}
Pose2D Pose2DFromTransform(const Transform& t) {
return Pose2D{t.translation.x, t.translation.y, YawFromQuaternion(t.rotation)};
}
Transform TransformFromPose(const Pose& p) {
Transform t;
t.translation = Vector3{p.position.x, p.position.y, p.position.z};
t.rotation = p.orientation;
return t;
}
Pose PoseFromTransform(const Transform& t) {
Pose p;
p.position = Point{t.translation.x, t.translation.y, t.translation.z};
p.orientation = t.rotation;
return p;
}
} // namespace vslam

View File

@@ -0,0 +1,65 @@
#include "vslam/json_parse.h"
#include <cctype>
#include <cstdlib>
namespace vslam {
namespace {
// Tra ve vi tri ngay sau dau ':' cua "key", hoac npos.
size_t FindValue(const std::string& body, const std::string& key) {
const std::string pat = "\"" + key + "\"";
size_t p = body.find(pat);
if (p == std::string::npos) return std::string::npos;
p += pat.size();
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
if (p >= body.size() || body[p] != ':') return std::string::npos;
++p;
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
return p < body.size() ? p : std::string::npos;
}
} // namespace
bool JsonGetNumber(const std::string& body, const std::string& key, double* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos) return false;
char* end = nullptr;
const double v = std::strtod(body.c_str() + p, &end);
if (end == body.c_str() + p) return false;
*out = v;
return true;
}
bool JsonGetBool(const std::string& body, const std::string& key, bool* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos) return false;
if (body.compare(p, 4, "true") == 0) { *out = true; return true; }
if (body.compare(p, 5, "false") == 0) { *out = false; return true; }
return false;
}
bool JsonGetString(const std::string& body, const std::string& key, std::string* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos || body[p] != '"') return false;
out->clear();
for (size_t i = p + 1; i < body.size(); ++i) {
if (body[i] == '\\' && i + 1 < body.size()) {
++i;
switch (body[i]) {
case 'n': out->push_back('\n'); break;
case 't': out->push_back('\t'); break;
case 'r': out->push_back('\r'); break;
default: out->push_back(body[i]); break;
}
continue;
}
if (body[i] == '"') return true;
out->push_back(body[i]);
}
return false; // chuoi khong dong
}
} // namespace vslam

View File

@@ -0,0 +1,141 @@
#include "vslam/log.h"
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <mutex>
namespace vslam {
namespace {
std::atomic<int> g_level{static_cast<int>(LogLevel::kInfo)};
std::atomic<bool> g_color{false};
std::atomic<bool> g_color_init{false};
std::mutex& SinkMutex() {
static std::mutex m;
return m;
}
LogSink& SinkRef() {
static LogSink sink; // rong = dung sink mac dinh ra stderr
return sink;
}
const char* ColorFor(LogLevel l) {
switch (l) {
case LogLevel::kDebug: return "\033[2m"; // mo
case LogLevel::kInfo: return "";
case LogLevel::kWarn: return "\033[33m"; // vang
case LogLevel::kError: return "\033[31m"; // do
default: return "";
}
}
// Chi lay ten file, bo duong dan. __FILE__ trong build tree rat dai.
const char* BaseName(const char* path) {
const char* slash = std::strrchr(path, '/');
return slash != nullptr ? slash + 1 : path;
}
bool ColorEnabled() {
if (!g_color_init.load(std::memory_order_relaxed)) {
g_color.store(::isatty(STDERR_FILENO) != 0, std::memory_order_relaxed);
g_color_init.store(true, std::memory_order_relaxed);
}
return g_color.load(std::memory_order_relaxed);
}
} // namespace
const char* LogLevelName(LogLevel l) {
switch (l) {
case LogLevel::kDebug: return "DEBUG";
case LogLevel::kInfo: return "INFO";
case LogLevel::kWarn: return "WARN";
case LogLevel::kError: return "ERROR";
case LogLevel::kOff: return "OFF";
}
return "?";
}
bool ParseLogLevel(const std::string& s, LogLevel* out) {
if (s == "debug" || s == "DEBUG") { *out = LogLevel::kDebug; return true; }
if (s == "info" || s == "INFO") { *out = LogLevel::kInfo; return true; }
if (s == "warn" || s == "WARN") { *out = LogLevel::kWarn; return true; }
if (s == "error" || s == "ERROR") { *out = LogLevel::kError; return true; }
if (s == "off" || s == "OFF") { *out = LogLevel::kOff; return true; }
return false;
}
void SetLogLevel(LogLevel l) { g_level.store(static_cast<int>(l), std::memory_order_relaxed); }
LogLevel GetLogLevel() {
return static_cast<LogLevel>(g_level.load(std::memory_order_relaxed));
}
void SetLogSink(LogSink sink) {
std::lock_guard<std::mutex> lk(SinkMutex());
SinkRef() = std::move(sink);
}
void SetLogColor(bool on) {
g_color.store(on, std::memory_order_relaxed);
g_color_init.store(true, std::memory_order_relaxed);
}
namespace detail {
void EmitLog(LogLevel level, const char* file, int line, const std::string& msg) {
{
std::lock_guard<std::mutex> lk(SinkMutex());
if (SinkRef()) {
SinkRef()(level, file, line, msg);
return;
}
}
// Sink mac dinh: stderr, mot lan fwrite co khoa. Dinh dang:
// HH:MM:SS.mmm WARN scan_sanitizer.cc:88 noi dung
using namespace std::chrono;
const auto now = system_clock::now();
const auto t = system_clock::to_time_t(now);
const auto ms = duration_cast<milliseconds>(now.time_since_epoch()).count() % 1000;
std::tm tm_buf{};
::localtime_r(&t, &tm_buf);
char stamp[32];
std::snprintf(stamp, sizeof(stamp), "%02d:%02d:%02d.%03d", tm_buf.tm_hour,
tm_buf.tm_min, tm_buf.tm_sec, static_cast<int>(ms));
const bool color = ColorEnabled();
const char* c_on = color ? ColorFor(level) : "";
const char* c_off = (color && c_on[0] != '\0') ? "\033[0m" : "";
static std::mutex out_mu;
std::lock_guard<std::mutex> lk(out_mu);
std::fprintf(stderr, "%s%s %-5s %s:%d %s%s\n", c_on, stamp,
LogLevelName(level), BaseName(file), line, msg.c_str(), c_off);
}
bool ThrottlePass(std::atomic<int64_t>* state, double period_sec) {
// steady_clock, KHONG phai stamp du lieu. Neu dung stamp thi khi replay
// nhanh (speed=0) moi dong se bi bop nham.
const auto now = std::chrono::steady_clock::now().time_since_epoch();
const int64_t now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
const int64_t period_ns = static_cast<int64_t>(period_sec * 1e9);
int64_t last = state->load(std::memory_order_relaxed);
if (last != 0 && now_ns - last < period_ns) return false;
// CAS: neu hai luong cung toi day thi chi mot luong duoc in.
return state->compare_exchange_strong(last, now_ns, std::memory_order_relaxed);
}
} // namespace detail
} // namespace vslam

View File

@@ -0,0 +1,43 @@
#include "vslam/node_constants.h"
#include <cstdlib>
namespace vslam {
namespace {
// Tra ve $name neu co va khong rong, khong thi `fallback`.
std::string EnvOr(const char* name, const char* fallback) {
const char* v = std::getenv(name);
if (v != nullptr && v[0] != '\0') return std::string(v);
return std::string(fallback);
}
std::string Join(const std::string& dir, const std::string& rel) {
if (dir.empty()) return rel;
if (dir.back() == '/') return dir + rel;
return dir + "/" + rel;
}
} // namespace
std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); }
std::string ResourceDir() { return EnvOr(kResourceDirEnv, kResourceDirectory); }
std::string ConfigPath(const std::string& file_name) {
return Join(ConfigDir(), file_name);
}
std::string ResourcePath(const std::string& rel) { return Join(ResourceDir(), rel); }
std::string MapDir() { return Join(ResourceDir(), "maps"); }
std::string RecordDir() { return Join(ResourceDir(), "records"); }
std::string CorpusDir() {
const char* v = std::getenv(kCorpusDirEnv);
if (v != nullptr && v[0] != '\0') return std::string(v);
return MapDir();
}
} // namespace vslam

View File

@@ -0,0 +1,222 @@
#include "vslam/robot_model.h"
#include <algorithm>
#include <cmath>
#include <set>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Doc mot chuoi 3 so tu node YAML. Tra false kem duong day du khi hong --
// mot phep bien doi sai im lang la ca ban do lech.
bool ReadVec3(const ConfigNode& n, double out[3], std::string* err) {
if (n.IsNull()) {
*err = "thieu";
return false;
}
if (!n.IsSequence() || n.size() != 3) {
*err = "phai la chuoi 3 so, " + n.path();
return false;
}
for (size_t i = 0; i < 3; ++i) {
out[i] = n.at(i).as<double>();
}
return true;
}
} // namespace
RobotModel::RobotModel() : tree_(new TransformTree) {}
RobotModel::~RobotModel() = default;
StatusResponse RobotModel::LoadFile(const std::string& path) {
// ConfigNode::LoadFile nem ConfigError khi file thieu hoac YAML hong. Mot
// file config sai khong duoc phep lam sap tien trinh -- doi thanh loi doc
// duoc de nguoi goi quyet dinh.
try {
return Load(ConfigNode::LoadFile(path));
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml (" + path + "): " + e.what());
}
}
StatusResponse RobotModel::Load(const ConfigNode& root) {
// --- geometry ---
const ConfigNode g = root["geometry"];
if (!g.IsNull()) {
// Go sai ten khoa hien tai roi ve mac dinh mot cach im lang. `wheel_base`
// thay vi `wheel_separation` nghia la moi phep quay sai ti le, va khong
// co gi bao.
const std::vector<std::string> unknown = g.UnknownKeys(
{"wheel_radius", "wheel_separation", "robot_radius", "body_half_width"});
if (!unknown.empty()) {
std::string m = "robot.yaml geometry: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
geometry_.wheel_radius = g.get<double>("wheel_radius", geometry_.wheel_radius);
geometry_.wheel_separation =
g.get<double>("wheel_separation", geometry_.wheel_separation);
geometry_.robot_radius = g.get<double>("robot_radius", geometry_.robot_radius);
geometry_.body_half_width =
g.get<double>("body_half_width", geometry_.body_half_width);
}
if (!(geometry_.wheel_radius > 0.0) || !(geometry_.wheel_separation > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml: wheel_radius va wheel_separation "
"phai duong");
}
// --- base ---
const ConfigNode b = root["base"];
if (!b.IsNull()) {
const std::vector<std::string> unknown = b.UnknownKeys(
{"max_linear", "max_angular", "accel_limit", "cmd_timeout"});
if (!unknown.empty()) {
std::string m = "robot.yaml base: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
base_.max_linear = b.get<double>("max_linear", base_.max_linear);
base_.max_angular = b.get<double>("max_angular", base_.max_angular);
base_.accel_limit = b.get<double>("accel_limit", base_.accel_limit);
base_.cmd_timeout = b.get<double>("cmd_timeout", base_.cmd_timeout);
}
// --- wheel_odom ---
const ConfigNode w = root["wheel_odom"];
if (!w.IsNull()) {
const std::vector<std::string> unknown =
w.UnknownKeys({"sigma_x_per_m", "sigma_y_per_m", "sigma_yaw_per_rad",
"slip_threshold", "slip_sigma_is_measured"});
if (!unknown.empty()) {
std::string m = "robot.yaml wheel_odom: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
wheel_odom_.sigma_x_per_m =
w.get<double>("sigma_x_per_m", wheel_odom_.sigma_x_per_m);
wheel_odom_.sigma_y_per_m =
w.get<double>("sigma_y_per_m", wheel_odom_.sigma_y_per_m);
wheel_odom_.sigma_yaw_per_rad =
w.get<double>("sigma_yaw_per_rad", wheel_odom_.sigma_yaw_per_rad);
wheel_odom_.slip_threshold =
w.get<double>("slip_threshold", wheel_odom_.slip_threshold);
wheel_odom_.slip_sigma_is_measured =
w.get<bool>("slip_sigma_is_measured", wheel_odom_.slip_sigma_is_measured);
}
// --- frames ---
const ConfigNode frames = root["frames"];
if (frames.IsNull() || !frames.IsSequence() || frames.size() == 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml: thieu khoi `frames:` -- khong co "
"no thi khong stage nao dat duoc cam bien vao "
"dau");
}
// Mot `child` chi duoc xuat hien MOT lan. Hai dong cung child thi dong sau
// am tham thang, va nua so doc file se tin dong dau.
std::set<std::string> seen_children;
for (size_t i = 0; i < frames.size(); ++i) {
const ConfigNode f = frames.at(i);
const std::vector<std::string> unknown =
f.UnknownKeys({"parent", "child", "xyz", "rpy"});
if (!unknown.empty()) {
std::string m = "robot.yaml frames[" + std::to_string(i) + "]: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
const std::string parent = f.require<std::string>("parent");
const std::string child = f.require<std::string>("child");
if (parent == child) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"]: parent trung child (" + parent + ")");
}
if (!seen_children.insert(child).second) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"robot.yaml: frame `" + child +
"` duoc khai hai lan -- lan sau am tham thang, va do la lop bug "
"ma file nay sinh ra de xoa");
}
double xyz[3] = {0, 0, 0}, rpy[3] = {0, 0, 0};
std::string err;
if (!ReadVec3(f["xyz"], xyz, &err)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"].xyz: " + err);
}
if (!ReadVec3(f["rpy"], rpy, &err)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"].rpy: " + err);
}
Transform tf = TransformIdentity();
tf.translation = Vector3{xyz[0], xyz[1], xyz[2]};
tf.rotation = QuaternionFromRPY(rpy[0], rpy[1], rpy[2]);
// SetStatic nem ConfigError khi tao vong -- bat lai va tra ve loi doc
// duoc, vi mot file config sai khong duoc phep lam sap tien trinh.
try {
const StatusResponse st = tree_->SetStatic(parent, child, tf);
if (!st.ok()) return st;
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"] " + parent + " -> " + child + ": " +
e.what());
}
if (parent == kBaseLinkFrame && child == kCameraFrame) {
camera_z_in_base_link_ = xyz[2];
camera_pitch_ = rpy[1];
have_camera_ = true;
}
}
VSLAM_INFO("robot: " << frames.size() << " canh tinh, banh r="
<< geometry_.wheel_radius << " d=" << geometry_.wheel_separation
<< (have_camera_
? ", camera cao " + std::to_string(camera_height_above_floor()) +
" m so voi san"
: ", KHONG co camera_link"));
return StatusResponse::Ok();
}
bool RobotModel::StaticTransform(const std::string& target,
const std::string& source, Transform* out) const {
// Canh tinh khong co dau thoi gian, nen LookupLatest la dung: no dung mau
// moi nhat cua tung canh, va voi canh tinh thi chi co mot mau.
//
// `Find` chu khong `Resolve`: tra cuu mot frame chua ton tai phai TRA FALSE
// chu khong duoc am tham tao ra no. Resolve() tao frame moi, va mot frame
// go sai ten se thanh mot nhanh roi ma khong ai bao.
const FrameId t = tree_->Find(target);
const FrameId s = tree_->Find(source);
if (t == kInvalidFrame || s == kInvalidFrame) return false;
return tree_->LookupLatest(t, s, out);
}
double RobotModel::camera_height_above_floor() const {
// base_link o tam truc, cach san dung bang ban kinh banh.
//
// Day la ly do `cliff_detect.nominal_tz` KHONG duoc go tay: no la mot HE
// QUA cua hai so khac, va go tay lan thu hai la cho mot trong hai duoc
// phep lech.
return camera_z_in_base_link_ + geometry_.wheel_radius;
}
double RobotModel::camera_pitch() const { return camera_pitch_; }
} // namespace vslam

View File

@@ -0,0 +1,150 @@
#include "vslam/stats.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <mutex>
#include <vector>
namespace vslam {
namespace {
int64_t ToNs(std::chrono::steady_clock::time_point tp) {
return std::chrono::duration_cast<std::chrono::nanoseconds>(tp.time_since_epoch())
.count();
}
} // namespace
// --- RateMonitor -----------------------------------------------------------
RateMonitor::RateMonitor(double window_sec) : window_sec_(window_sec) {}
void RateMonitor::Tick(std::chrono::steady_clock::time_point now) {
const int64_t ns = ToNs(now);
count_.fetch_add(1, std::memory_order_relaxed);
last_ns_.store(ns, std::memory_order_relaxed);
const int64_t first = first_ns_.load(std::memory_order_relaxed);
if (first == 0) {
first_ns_.store(ns, std::memory_order_relaxed);
window_count_.store(1, std::memory_order_relaxed);
return;
}
const uint64_t wc = window_count_.fetch_add(1, std::memory_order_relaxed) + 1;
const double elapsed = static_cast<double>(ns - first) * 1e-9;
if (elapsed >= window_sec_) {
hz_.store(elapsed > 0.0 ? static_cast<double>(wc) / elapsed : 0.0,
std::memory_order_relaxed);
// Mo cua so moi. Khong dung cua so truot that (deque timestamp) vi o
// 200 Hz thi chi phi bo nho va khoa khong dang -- sai so cua cua so nhay
// la chap nhan duoc cho muc dich chan doan.
first_ns_.store(ns, std::memory_order_relaxed);
window_count_.store(0, std::memory_order_relaxed);
}
}
void RateMonitor::Tick() { Tick(std::chrono::steady_clock::now()); }
double RateMonitor::hz() const { return hz_.load(std::memory_order_relaxed); }
double RateMonitor::age_sec(std::chrono::steady_clock::time_point now) const {
const int64_t last = last_ns_.load(std::memory_order_relaxed);
if (last == 0) return std::numeric_limits<double>::infinity();
return static_cast<double>(ToNs(now) - last) * 1e-9;
}
void RateMonitor::Reset() {
count_.store(0, std::memory_order_relaxed);
first_ns_.store(0, std::memory_order_relaxed);
last_ns_.store(0, std::memory_order_relaxed);
window_count_.store(0, std::memory_order_relaxed);
hz_.store(0.0, std::memory_order_relaxed);
}
// --- LatencyMonitor --------------------------------------------------------
struct LatencyMonitor::Impl {
mutable std::mutex mu;
std::vector<double> ring;
size_t head = 0;
size_t filled = 0;
double max_seen = 0.0;
double last = 0.0;
uint64_t count = 0;
explicit Impl(size_t window) : ring(window, 0.0) {}
// Goi khi da giu mu.
double PercentileLocked(double p) const {
if (filled == 0) return 0.0;
std::vector<double> tmp(ring.begin(), ring.begin() + static_cast<long>(filled));
const size_t idx = static_cast<size_t>(p * static_cast<double>(filled - 1));
std::nth_element(tmp.begin(), tmp.begin() + static_cast<long>(idx), tmp.end());
return tmp[idx];
}
};
LatencyMonitor::LatencyMonitor(size_t window)
: impl_(std::make_unique<Impl>(window == 0 ? 1 : window)) {}
LatencyMonitor::~LatencyMonitor() = default;
void LatencyMonitor::Add(double ms) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->ring[impl_->head] = ms;
impl_->head = (impl_->head + 1) % impl_->ring.size();
if (impl_->filled < impl_->ring.size()) impl_->filled++;
if (ms > impl_->max_seen) impl_->max_seen = ms;
impl_->last = ms;
impl_->count++;
}
double LatencyMonitor::p50() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->PercentileLocked(0.50);
}
double LatencyMonitor::p95() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->PercentileLocked(0.95);
}
double LatencyMonitor::max() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->max_seen;
}
double LatencyMonitor::last() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->last;
}
uint64_t LatencyMonitor::count() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->count;
}
void LatencyMonitor::Reset() {
std::lock_guard<std::mutex> lk(impl_->mu);
std::fill(impl_->ring.begin(), impl_->ring.end(), 0.0);
impl_->head = 0;
impl_->filled = 0;
impl_->max_seen = 0.0;
impl_->last = 0.0;
impl_->count = 0;
}
// --- ScopedLatency ---------------------------------------------------------
ScopedLatency::ScopedLatency(LatencyMonitor* m, const Clock* clock)
: m_(m), t0_(clock != nullptr ? clock->Steady() : std::chrono::steady_clock::now()) {}
ScopedLatency::~ScopedLatency() {
if (m_ == nullptr) return;
const auto dt = std::chrono::steady_clock::now() - t0_;
m_->Add(std::chrono::duration<double, std::milli>(dt).count());
}
} // namespace vslam

View File

@@ -0,0 +1,262 @@
#include "vslam/teleop_model.h"
#include <algorithm>
#include <cmath>
#include <stdexcept>
namespace vslam {
namespace {
double Clamp(double v, double lo, double hi) { return std::max(lo, std::min(v, hi)); }
void ValidateFinite(const char* name, double v) {
if (!std::isfinite(v)) {
throw std::invalid_argument(std::string(name) + " must be a finite number");
}
}
void ValidateRange(const char* name, double minimum, double maximum, double step) {
ValidateFinite(name, minimum);
ValidateFinite(name, maximum);
ValidateFinite(name, step);
if (minimum < 0.0) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be non-negative");
}
if (maximum < minimum) {
throw std::invalid_argument(std::string("maximum ") + name +
" must not be less than its minimum");
}
if (step <= 0.0) {
throw std::invalid_argument(std::string(name) + " step must be positive");
}
}
void ValidateCommandRange(const char* name, double minimum, double maximum) {
ValidateFinite(name, minimum);
ValidateFinite(name, maximum);
if (minimum > 0.0) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be zero or negative");
}
if (maximum < 0.0) {
throw std::invalid_argument(std::string("maximum ") + name +
" must be zero or positive");
}
if (minimum >= maximum) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be less than its maximum");
}
}
} // namespace
bool ParseTeleopKey(const std::string& name, TeleopKey* out) {
if (name == "Up") { *out = TeleopKey::kUp; return true; }
if (name == "Down") { *out = TeleopKey::kDown; return true; }
if (name == "Left") { *out = TeleopKey::kLeft; return true; }
if (name == "Right") { *out = TeleopKey::kRight; return true; }
return false;
}
const char* TeleopKeyName(TeleopKey k) {
switch (k) {
case TeleopKey::kUp: return "Up";
case TeleopKey::kDown: return "Down";
case TeleopKey::kLeft: return "Left";
case TeleopKey::kRight: return "Right";
}
return "?";
}
TeleopModel::TeleopModel(TeleopConfig cfg) {
ValidateRange("linear speed", cfg.min_linear_speed, cfg.max_linear_speed,
cfg.linear_step);
ValidateRange("angular speed", cfg.min_angular_speed, cfg.max_angular_speed,
cfg.angular_step);
ValidateFinite("linear_speed", cfg.linear_speed);
ValidateFinite("angular_speed", cfg.angular_speed);
// Mac dinh: gioi han duoi doi xung voi gioi han tren.
const double min_lin_cmd =
cfg.has_min_linear_command ? cfg.min_linear_command : -cfg.max_linear_speed;
const double min_ang_cmd =
cfg.has_min_angular_command ? cfg.min_angular_command : -cfg.max_angular_speed;
ValidateCommandRange("linear command", min_lin_cmd, cfg.max_linear_speed);
ValidateCommandRange("angular command", min_ang_cmd, cfg.max_angular_speed);
linear_step_ = cfg.linear_step;
angular_step_ = cfg.angular_step;
min_linear_speed_ = cfg.min_linear_speed;
max_linear_speed_ = cfg.max_linear_speed;
min_angular_speed_ = cfg.min_angular_speed;
max_angular_speed_ = cfg.max_angular_speed;
min_linear_command_ = min_lin_cmd;
min_angular_command_ = min_ang_cmd;
linear_speed_ = Clamp(cfg.linear_speed, min_linear_speed_, max_linear_speed_);
angular_speed_ = Clamp(cfg.angular_speed, min_angular_speed_, max_angular_speed_);
}
// --- Nguon nhap ------------------------------------------------------------
bool TeleopModel::SetKey(TeleopKey key, bool pressed) {
if (pressed) {
// Bam phim GIAI PHONG lenh manual. Khong bao gio tron hai nguon.
ReleaseManualControl();
keys_.insert(key);
} else {
keys_.erase(key);
}
return true;
}
void TeleopModel::ClearKeys() { keys_.clear(); }
void TeleopModel::SetJoystick(double horizontal, double vertical) {
ValidateFinite("joystick horizontal axis", horizontal);
ValidateFinite("joystick vertical axis", vertical);
joy_h_ = Clamp(horizontal, -1.0, 1.0);
joy_v_ = Clamp(vertical, -1.0, 1.0);
joystick_active_ = true;
ReleaseManualControl();
}
void TeleopModel::ReleaseJoystick() { joystick_active_ = false; }
void TeleopModel::ClearMotion() {
ClearKeys();
ReleaseJoystick();
ReleaseManualControl();
}
std::pair<double, double> TeleopModel::SetManualCommand(const double* linear_x,
const double* angular_z) {
double cur_lin, cur_ang;
if (!manual_active_) {
const auto c = Command();
cur_lin = c.first;
cur_ang = c.second;
} else {
cur_lin = manual_lin_;
cur_ang = manual_ang_;
}
if (linear_x != nullptr) {
ValidateFinite("manual linear command", *linear_x);
cur_lin = *linear_x;
}
if (angular_z != nullptr) {
ValidateFinite("manual angular command", *angular_z);
cur_ang = *angular_z;
}
ClearKeys();
ReleaseJoystick();
const auto clamped = ClampCommand(cur_lin, cur_ang);
manual_lin_ = clamped.first;
manual_ang_ = clamped.second;
manual_active_ = true;
return clamped;
}
void TeleopModel::ReleaseManualControl() { manual_active_ = false; }
// --- Ket qua ---------------------------------------------------------------
std::pair<double, double> TeleopModel::ClampCommand(double linear_x,
double angular_z) const {
return {Clamp(linear_x, min_linear_command_, max_linear_speed_),
Clamp(angular_z, min_angular_command_, max_angular_speed_)};
}
void TeleopModel::ClampManualCommand() {
if (!manual_active_) return;
const auto c = ClampCommand(manual_lin_, manual_ang_);
manual_lin_ = c.first;
manual_ang_ = c.second;
}
std::pair<double, double> TeleopModel::Command() const {
// Thu tu uu tien: manual > joystick > phim.
if (manual_active_) return {manual_lin_, manual_ang_};
if (joystick_active_) {
return ClampCommand(-joy_v_ * linear_speed_, -joy_h_ * angular_speed_);
}
const int linear_axis = static_cast<int>(keys_.count(TeleopKey::kUp)) -
static_cast<int>(keys_.count(TeleopKey::kDown));
const int angular_axis = static_cast<int>(keys_.count(TeleopKey::kLeft)) -
static_cast<int>(keys_.count(TeleopKey::kRight));
return ClampCommand(linear_axis * linear_speed_, angular_axis * angular_speed_);
}
std::pair<double, double> TeleopModel::JoystickPosition() const {
if (joystick_active_) return {joy_h_, joy_v_};
const int h = static_cast<int>(keys_.count(TeleopKey::kRight)) -
static_cast<int>(keys_.count(TeleopKey::kLeft));
const int v = static_cast<int>(keys_.count(TeleopKey::kDown)) -
static_cast<int>(keys_.count(TeleopKey::kUp));
return {static_cast<double>(h), static_cast<double>(v)};
}
// --- Chinh toc do ----------------------------------------------------------
double TeleopModel::AdjustLinearSpeed(double direction) {
return SetLinearSpeed(linear_speed_ + direction * linear_step_);
}
double TeleopModel::AdjustAngularSpeed(double direction) {
return SetAngularSpeed(angular_speed_ + direction * angular_step_);
}
double TeleopModel::SetLinearSpeed(double value) {
ValidateFinite("linear speed", value);
linear_speed_ = Clamp(value, min_linear_speed_, max_linear_speed_);
return linear_speed_;
}
double TeleopModel::SetAngularSpeed(double value) {
ValidateFinite("angular speed", value);
angular_speed_ = Clamp(value, min_angular_speed_, max_angular_speed_);
return angular_speed_;
}
double TeleopModel::SetMaxLinearSpeed(double value) {
ValidateFinite("maximum linear speed", value);
max_linear_speed_ = std::max(min_linear_speed_, value);
linear_speed_ = std::min(linear_speed_, max_linear_speed_);
ClampManualCommand();
return max_linear_speed_;
}
double TeleopModel::SetMaxAngularSpeed(double value) {
ValidateFinite("maximum angular speed", value);
max_angular_speed_ = std::max(min_angular_speed_, value);
angular_speed_ = std::min(angular_speed_, max_angular_speed_);
ClampManualCommand();
return max_angular_speed_;
}
double TeleopModel::SetMinLinearCommand(double value) {
ValidateFinite("minimum linear command", value);
min_linear_command_ = std::min(0.0, value);
if (min_linear_command_ >= max_linear_speed_) {
min_linear_command_ = std::min(0.0, max_linear_speed_ - linear_step_);
}
ClampManualCommand();
return min_linear_command_;
}
double TeleopModel::SetMinAngularCommand(double value) {
ValidateFinite("minimum angular command", value);
min_angular_command_ = std::min(0.0, value);
if (min_angular_command_ >= max_angular_speed_) {
min_angular_command_ = std::min(0.0, max_angular_speed_ - angular_step_);
}
ClampManualCommand();
return min_angular_command_;
}
} // namespace vslam

View File

@@ -0,0 +1,485 @@
#include "vslam/transform_tree.h"
#include <algorithm>
#include <functional>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/stats.h"
namespace vslam {
namespace {
constexpr size_t kMaxDepth = 32; // cay that co 5 muc; 32 la chan an toan
struct Sample {
UnixTime stamp;
Transform tf;
};
} // namespace
// Mot canh = quan he cha-con. Canh tinh giu mot Transform; canh dong giu ring
// buffer cac mau theo thoi gian.
struct Edge {
FrameId parent = kInvalidFrame;
bool is_static = false;
Transform static_tf; // chi co nghia khi is_static
std::vector<Sample> ring;
size_t head = 0; // vi tri se ghi tiep
size_t filled = 0;
uint64_t samples = 0;
RateMonitor rate{2.0};
const Sample& at(size_t i) const { return ring[i % ring.size()]; }
// Mau moi nhat. Goi phai bao dam filled > 0.
const Sample& newest() const { return ring[(head + ring.size() - 1) % ring.size()]; }
// Mau cu nhat con song.
const Sample& oldest() const {
return filled < ring.size() ? ring[0] : ring[head % ring.size()];
}
};
struct TransformTree::Impl {
mutable std::mutex mu;
std::unordered_map<std::string, FrameId> name_to_id;
std::vector<std::string> id_to_name;
// Chi muc theo frame CON: moi frame co dung mot cha, nen mot canh la du.
// Day chinh la gia dinh cho phep bo toan bo may tra cuu tong quat cua tf2.
std::unordered_map<FrameId, Edge> edges;
double history_sec;
size_t slots_per_edge;
double extrapolation_limit = 0.1;
std::string empty_name;
// Duong di tu `frame` len goc. Tra ve so muc, hoac 0 neu vuot kMaxDepth.
size_t PathToRoot(FrameId frame, FrameId* out) const {
size_t n = 0;
FrameId cur = frame;
while (n < kMaxDepth) {
out[n++] = cur;
auto it = edges.find(cur);
if (it == edges.end()) return n; // toi goc
cur = it->second.parent;
}
return 0; // vong hoac qua sau
}
// To tien chung gan nhat cua a va b. kInvalidFrame neu hai frame khong noi.
bool CommonAncestor(FrameId a, FrameId b, FrameId* pa, size_t* na, FrameId* pb,
size_t* nb, FrameId* lca) const {
*na = PathToRoot(a, pa);
*nb = PathToRoot(b, pb);
if (*na == 0 || *nb == 0) return false;
for (size_t i = 0; i < *na; ++i) {
for (size_t j = 0; j < *nb; ++j) {
if (pa[i] == pb[j]) {
*lca = pa[i];
*na = i; // so canh phai di tu a len lca
*nb = j;
return true;
}
}
}
return false;
}
// Bien doi canh don parent<-child tai `stamp`, noi suy neu can.
bool EdgeAt(const Edge& e, UnixTime stamp, bool latest, Transform* out,
std::string* err) const {
if (e.is_static) {
*out = e.static_tf;
return true;
}
if (e.filled == 0) {
if (err) *err = "canh chua co mau nao";
return false;
}
const Sample& newest = e.newest();
if (latest) {
*out = newest.tf;
return true;
}
// Ngoai suy ve tuong lai: tu choi neu vuot gioi han.
// tf2 nem ExtrapolationException o day va rat nhieu code goi bat roi bo
// qua im lang; tra false + dien err de goi khong the lo.
if (stamp > newest.stamp) {
const double ahead = SecondsBetween(stamp, newest.stamp);
if (ahead > extrapolation_limit) {
if (err) {
std::ostringstream oss;
oss << "ngoai suy " << ahead << " s vuot gioi han "
<< extrapolation_limit << " s";
*err = oss.str();
}
return false;
}
*out = newest.tf;
return true;
}
const Sample& oldest = e.oldest();
if (stamp < oldest.stamp) {
if (err) {
std::ostringstream oss;
oss << "stamp cu hon lich su " << SecondsBetween(oldest.stamp, stamp) << " s";
*err = oss.str();
}
return false;
}
// Tim hai mau kep stamp. Ring nho (512) va truy van gan dau moi nen quet
// nguoc tu moi nhat nhanh hon tim nhi phan tren bo dem vong.
const size_t n = e.filled;
const size_t base = e.filled < e.ring.size() ? 0 : e.head;
for (size_t k = n; k-- > 1;) {
const Sample& hi = e.at(base + k);
const Sample& lo = e.at(base + k - 1);
if (stamp >= lo.stamp && stamp <= hi.stamp) {
const int64_t span = hi.stamp.toNSec() - lo.stamp.toNSec();
if (span <= 0) {
*out = hi.tf;
return true;
}
const double t =
static_cast<double>(stamp.toNSec() - lo.stamp.toNSec()) /
static_cast<double>(span);
*out = TransformInterpolate(lo.tf, hi.tf, t);
return true;
}
}
*out = newest.tf;
return true;
}
};
// ---------------------------------------------------------------------------
TransformTree::TransformTree(double history_sec, size_t slots_per_edge)
: impl_(std::make_unique<Impl>()) {
impl_->history_sec = history_sec;
impl_->slots_per_edge = slots_per_edge == 0 ? 1 : slots_per_edge;
}
TransformTree::~TransformTree() = default;
FrameId TransformTree::Resolve(const std::string& name) {
std::lock_guard<std::mutex> lk(impl_->mu);
auto it = impl_->name_to_id.find(name);
if (it != impl_->name_to_id.end()) return it->second;
const FrameId id = static_cast<FrameId>(impl_->id_to_name.size());
impl_->id_to_name.push_back(name);
impl_->name_to_id.emplace(name, id);
return id;
}
FrameId TransformTree::Find(const std::string& name) const {
std::lock_guard<std::mutex> lk(impl_->mu);
auto it = impl_->name_to_id.find(name);
return it == impl_->name_to_id.end() ? kInvalidFrame : it->second;
}
const std::string& TransformTree::Name(FrameId id) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (id >= impl_->id_to_name.size()) return impl_->empty_name;
return impl_->id_to_name[id];
}
size_t TransformTree::frame_count() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->id_to_name.size();
}
StatusResponse TransformTree::SetStatic(FrameId parent, FrameId child,
const Transform& tf) {
std::lock_guard<std::mutex> lk(impl_->mu);
// Kiem vong truoc khi ghi: di tu `parent` len goc, neu gap `child` thi viec
// dat canh nay se tao vong va moi lookup sau do se treo.
FrameId cur = parent;
for (size_t i = 0; i < kMaxDepth; ++i) {
if (cur == child) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"SetStatic tao vong trong cay TF: " + impl_->id_to_name[child]);
}
auto it = impl_->edges.find(cur);
if (it == impl_->edges.end()) break;
cur = it->second.parent;
}
Edge& e = impl_->edges[child];
if (!e.is_static && e.samples > 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"canh " + impl_->id_to_name[child] + " da la canh dong, khong the dat tinh");
}
e.parent = parent;
e.is_static = true;
e.static_tf = tf;
return StatusResponse::Ok();
}
StatusResponse TransformTree::SetStatic(const std::string& parent,
const std::string& child,
const Transform& tf) {
return SetStatic(Resolve(parent), Resolve(child), tf);
}
bool TransformTree::SetTransform(FrameId parent, FrameId child, UnixTime stamp,
const Transform& tf) {
std::lock_guard<std::mutex> lk(impl_->mu);
Edge& e = impl_->edges[child];
if (e.is_static) {
VSLAM_WARN_THROTTLE(5.0, "SetTransform tren canh tinh "
<< impl_->id_to_name[child] << ", bo qua");
return false;
}
if (e.parent != kInvalidFrame && e.parent != parent) {
// Doi cha giua chung la dau hieu hai nguoi cung ghi mot canh -- vi pham
// quy tac "moi canh dung mot nguoi ghi". Bao to, dung im lang.
VSLAM_ERROR_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
<< " doi cha tu " << impl_->id_to_name[e.parent]
<< " sang " << impl_->id_to_name[parent]);
return false;
}
e.parent = parent;
if (e.ring.empty()) e.ring.resize(impl_->slots_per_edge);
if (e.filled > 0 && stamp < e.newest().stamp) {
// Lui thoi gian: ban ghi bi xao tron thu tu, hoac hai nguoi ghi. Noi suy
// tren ring khong con don dieu nua nen moi lookup sau do se sai.
VSLAM_WARN_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
<< ": stamp lui " << e.newest().stamp.toString()
<< " -> " << stamp.toString() << ", bo qua");
return false;
}
e.ring[e.head] = Sample{stamp, tf};
e.head = (e.head + 1) % e.ring.size();
if (e.filled < e.ring.size()) e.filled++;
e.samples++;
e.rate.Tick();
return true;
}
bool TransformTree::Lookup(FrameId target, FrameId source, UnixTime stamp,
Transform* out, std::string* err) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (target == source) {
*out = TransformIdentity();
return true;
}
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
size_t na = 0, nb = 0;
if (!impl_->CommonAncestor(source, target, pa, &na, pb, &nb, &lca)) {
if (err) {
*err = "khong co duong noi " + impl_->id_to_name[source] + " -> " +
impl_->id_to_name[target];
}
return false;
}
const bool latest = stamp.isZero();
// source -> lca: ghep xuoi cac canh child->parent.
Transform src_to_lca = TransformIdentity();
for (size_t i = 0; i < na; ++i) {
auto it = impl_->edges.find(pa[i]);
if (it == impl_->edges.end()) break;
Transform e;
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
if (err) *err = impl_->id_to_name[pa[i]] + ": " + *err;
return false;
}
src_to_lca = TransformCompose(e, src_to_lca);
}
// target -> lca, roi lay nghich dao.
Transform tgt_to_lca = TransformIdentity();
for (size_t i = 0; i < nb; ++i) {
auto it = impl_->edges.find(pb[i]);
if (it == impl_->edges.end()) break;
Transform e;
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
if (err) *err = impl_->id_to_name[pb[i]] + ": " + *err;
return false;
}
tgt_to_lca = TransformCompose(e, tgt_to_lca);
}
*out = TransformCompose(TransformInverse(tgt_to_lca), src_to_lca);
return true;
}
bool TransformTree::Lookup(const std::string& target, const std::string& source,
UnixTime stamp, Transform* out, std::string* err) const {
const FrameId t = Find(target), s = Find(source);
if (t == kInvalidFrame || s == kInvalidFrame) {
if (err) *err = "frame chua dang ky: " + (t == kInvalidFrame ? target : source);
return false;
}
return Lookup(t, s, stamp, out, err);
}
bool TransformTree::LookupLatest(FrameId target, FrameId source, Transform* out,
std::string* err) const {
return Lookup(target, source, kTimeZero, out, err);
}
UnixTime TransformTree::LatestCommonTime(FrameId a, FrameId b) const {
std::lock_guard<std::mutex> lk(impl_->mu);
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
size_t na = 0, nb = 0;
if (!impl_->CommonAncestor(a, b, pa, &na, pb, &nb, &lca)) return kTimeZero;
// Thoi diem chung moi nhat = MIN cua cac mau moi nhat tren duong di.
// Canh tinh khong gioi han gi nen bo qua.
UnixTime best = kTimeMax;
bool any_dynamic = false;
auto scan = [&](const FrameId* path, size_t n) {
for (size_t i = 0; i < n; ++i) {
auto it = impl_->edges.find(path[i]);
if (it == impl_->edges.end() || it->second.is_static) continue;
if (it->second.filled == 0) {
best = kTimeZero;
return;
}
any_dynamic = true;
const UnixTime s = it->second.newest().stamp;
if (s < best) best = s;
}
};
scan(pa, na);
if (best.isZero()) return kTimeZero;
scan(pb, nb);
if (!any_dynamic) return kTimeZero; // toan canh tinh: moi luc deu hop le
return best.isZero() ? kTimeZero : best;
}
bool TransformTree::CanTransform(FrameId target, FrameId source,
UnixTime stamp) const {
Transform tmp;
return Lookup(target, source, stamp, &tmp, nullptr);
}
void TransformTree::SetExtrapolationLimit(double sec) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->extrapolation_limit = sec;
}
double TransformTree::extrapolation_limit() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->extrapolation_limit;
}
std::vector<TransformTree::EdgeStatus> TransformTree::EdgeStatuses() const {
std::lock_guard<std::mutex> lk(impl_->mu);
std::vector<EdgeStatus> out;
out.reserve(impl_->edges.size());
for (const auto& kv : impl_->edges) {
EdgeStatus s;
s.child = impl_->id_to_name[kv.first];
s.parent = kv.second.parent < impl_->id_to_name.size()
? impl_->id_to_name[kv.second.parent]
: "?";
s.is_static = kv.second.is_static;
s.samples = kv.second.samples;
s.hz = kv.second.rate.hz();
if (kv.second.filled > 0) s.latest = kv.second.newest().stamp;
out.push_back(std::move(s));
}
std::sort(out.begin(), out.end(),
[](const EdgeStatus& a, const EdgeStatus& b) { return a.child < b.child; });
return out;
}
std::string TransformTree::DumpTree() const {
// Thay rqt_tf_tree. In ra dang cay, danh dau canh tinh/dong kem tan so.
const auto edges = EdgeStatuses();
std::lock_guard<std::mutex> lk(impl_->mu);
std::unordered_map<std::string, std::vector<const EdgeStatus*>> children;
std::vector<std::string> roots;
for (const auto& e : edges) children[e.parent].push_back(&e);
for (const auto& name : impl_->id_to_name) {
if (impl_->edges.find(impl_->name_to_id.at(name)) == impl_->edges.end()) {
roots.push_back(name);
}
}
std::ostringstream oss;
std::function<void(const std::string&, int)> walk = [&](const std::string& node,
int depth) {
oss << std::string(static_cast<size_t>(depth) * 2, ' ') << node;
if (depth > 0) {
for (const auto& e : edges) {
if (e.child != node) continue;
if (e.is_static) {
oss << " [tinh]";
} else {
oss << " [dong " << e.hz << " Hz, " << e.samples << " mau]";
}
break;
}
}
oss << "\n";
auto it = children.find(node);
if (it == children.end()) return;
for (const auto* c : it->second) walk(c->child, depth + 1);
};
for (const auto& r : roots) walk(r, 0);
return oss.str();
}
// --- TfBridge --------------------------------------------------------------
TfBridge::TfBridge(std::string tracking_frame, double lookup_timeout_sec,
std::shared_ptr<const TransformTree> tree)
: tracking_frame_(std::move(tracking_frame)),
lookup_timeout_sec_(lookup_timeout_sec),
tree_(std::move(tree)) {}
bool TfBridge::LookupToTracking(UnixTime time, FrameId frame, Transform* out) const {
const FrameId tracking = tree_->Find(tracking_frame_);
if (tracking == kInvalidFrame) return false;
std::string err;
if (tree_->Lookup(tracking, frame, time, out, &err)) return true;
VSLAM_DEBUG_THROTTLE(2.0, "TfBridge: " << err);
return false;
}
bool TfBridge::LookupToTracking(UnixTime time, const std::string& frame,
Transform* out) const {
const FrameId id = tree_->Find(frame);
if (id == kInvalidFrame) return false;
return LookupToTracking(time, id, out);
}
} // namespace vslam

View File

@@ -0,0 +1,15 @@
#include "vslam/unix_time.h"
#include <cstdio>
namespace vslam {
std::string UnixTime::toString() const {
// In nguyen ven sec.nsec thay vi qua double: double chi co 53 bit mantissa,
// khong du de giu ca 1.7e9 giay lan do phan giai nanosecond.
char buf[32];
std::snprintf(buf, sizeof(buf), "%u.%09u", sec, nsec);
return std::string(buf);
}
} // namespace vslam

View File

@@ -0,0 +1,38 @@
# Driver phan cung. Dep ngoai: librealsense2 (tuy chon).
#
# librealsense2 la TUY CHON co y: ba phan kiem chung duoc ma khong can phan
# cung -- ScanSanitizer, ClockSync, giao thuc MCU -- phai build va test duoc
# tren may khong co RealSense SDK, ke ca trong CI.
option(VSLAM_WITH_REALSENSE "Build driver RealSense (can librealsense2)" OFF)
vslam_add_library(vslam_drivers
PUBLIC_HDRS
driver_config.h
driver_interfaces.h
scan_sanitizer.h
clock_sync.h
mcu_protocol.h
record_format.h
record_io.h
replay_source.h
PUBLIC_DEPS
vslam_common
FIND_DEPS
vslam_common
)
# Driver RealSense la file rieng, chi bien dich khi co SDK. GLOB_RECURSE gom
# het src/ nen phai loai no ra khi tat -- neu khong thi `#include <rs.hpp>`
# lam hong build tren may khong co librealsense2, tuc dung cai ma cai
# `option()` nay sinh ra de tranh.
get_target_property(_vslam_drv_srcs vslam_drivers SOURCES)
list(FILTER _vslam_drv_srcs EXCLUDE REGEX "realsense_driver\\.cc$")
set_target_properties(vslam_drivers PROPERTIES SOURCES "${_vslam_drv_srcs}")
if(VSLAM_WITH_REALSENSE)
target_sources(vslam_drivers PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/realsense_driver.cc)
find_package(realsense2 REQUIRED)
target_link_libraries(vslam_drivers PRIVATE ${realsense2_LIBRARY})
target_include_directories(vslam_drivers SYSTEM PRIVATE ${realsense2_INCLUDE_DIR})
target_compile_definitions(vslam_drivers PRIVATE VSLAM_HAVE_REALSENSE=1)
endif()

View File

@@ -0,0 +1,105 @@
#ifndef VSLAM_CLOCK_SYNC_H
#define VSLAM_CLOCK_SYNC_H
// Dong bo dong ho MCU <-> host: host_time = skew * mcu_time + offset.
//
// Port tu robot_drivers/scripts/imu_bridge_node.py:51-111, kem MOT SUA LOI
// quan trong ma ban Python khong co.
//
// ================== BUG TRAN micros() ==================
// micros() tren MCU la uint32_t: no TRAN moi 71.58 phut (2^32 us).
//
// Ban Python khong unwrap. Sau 71 phut, mcu_time nhay tu ~4295 giay ve 0,
// fit tuyen tinh vo, kiem tra |skew - 1| > 1e-3 tu choi ket qua, va fallback
// `offset = (sy - sx) / n` la rac -> MOI stamp IMU sai hang nghin giay.
//
// Trieu chung tren robot that: sau hon mot gio chay, TransformTree tu choi moi
// lookup vi stamp o tuong lai xa, robot dung im, va khong co gi trong log noi
// tai sao. Day dung la loai bug chi hien ra khi chay lau -- tuc la chi hien ra
// khi dang trinh dien.
//
// McuTimeUnwrapper o duoi xu ly viec do. PHAI goi theo dung thu tu ban tin den.
//
// ================== VI SAO CHI GIU MAU RTT NHO ==================
// RTT lon nghia la ban tin bi tre boi lich CPU hoac buffer serial, va do tre
// do gan nhu luon BAT DOI XUNG. Gia dinh `host = (t_send + t_recv) / 2` chi
// dung khi do tre doi xung, nen mau RTT lon lam hong uoc luong. Giu 16 mau
// nho nhat trong cua so 64.
#include <cstddef>
#include <cstdint>
#include <deque>
#include <memory>
namespace vslam {
// Go tran uint32_t cua micros(). PHAI goi theo thu tu ban tin den.
class McuTimeUnwrapper {
public:
// Tra ve thoi gian MCU tinh bang giay, da cong phan tran.
double UnwrapSeconds(uint32_t micros);
void Reset();
uint64_t wrap_count() const { return wraps_; }
private:
uint32_t prev_us_ = 0;
uint64_t high_ = 0; // tong phan da tran, tinh bang micro giay
uint64_t wraps_ = 0;
bool first_ = true;
};
// O pham vi namespace chu khong long trong ClockSync: mot struct long co
// default member initializer khong dung lam DOI SO MAC DINH cho ham thanh vien
// cua chinh lop bao duoc -- NSDMI chua hoan chinh cho toi het lop bao.
struct ClockSyncConfig {
size_t window = 64; // so mau giu lai
size_t keep_best = 16; // so mau RTT nho nhat dung de fit
double max_skew_dev = 1e-3; // |skew - 1| vuot nguong nay = du lieu rac
};
class ClockSync {
public:
using Config = ClockSyncConfig;
explicit ClockSync(ClockSyncConfig cfg = ClockSyncConfig());
// mcu_s: thoi gian MCU DA UNWRAP (giay).
// t_send, t_recv: thoi gian host luc gui ping va nhan pong (giay).
void Add(double mcu_s, double t_send, double t_recv);
// Doi thoi gian MCU sang thoi gian host. Chua san sang thi tra false.
bool ToHost(double mcu_s, double* host_s) const;
bool ready() const { return ready_; }
double skew() const { return skew_; }
double offset() const { return offset_; }
// Sai so ppm cua skew so voi 1.0. Thach anh thuong lech vai chuc ppm;
// vai nghin ppm nghia la giao thuc sai chu khong phai thach anh te.
double skew_ppm() const { return (skew_ - 1.0) * 1e6; }
uint64_t rejected_fits() const { return rejected_; }
size_t sample_count() const { return samples_.size(); }
void Reset();
private:
struct Sample {
double rtt;
double mcu_s;
double host_s;
};
void Fit();
ClockSyncConfig cfg_;
std::deque<Sample> samples_;
double skew_ = 1.0;
double offset_ = 0.0;
bool ready_ = false;
uint64_t rejected_ = 0;
};
} // namespace vslam
#endif // VSLAM_CLOCK_SYNC_H

View File

@@ -0,0 +1,138 @@
#ifndef VSLAM_DRIVER_CONFIG_H
#define VSLAM_DRIVER_CONFIG_H
#include <cstdint>
#include <string>
#include "vslam/scan_sanitizer.h"
namespace vslam {
// --- LiDAR LakiBeam 1L -----------------------------------------------------
enum class LidarStampMode {
// stamp = luc nhan goi DAU cua sweep. Dung quy uoc LaserScan (stamp = tia
// dau tien) va la mac dinh.
kFirstPacket,
// stamp = luc nhan goi CUOI tru scan_time. Dung khi muon bam theo thoi diem
// ket thuc sweep.
kLastPacketMinusScanTime,
};
struct LidarConfig {
std::string host_ip = "0.0.0.0"; // dia chi de bind, KHONG phai IP cua LiDAR
uint16_t port = 2368; // UDP, theo datasheet
std::string frame_id = "laser_link";
// Cau hinh thiet bi. 25 Hz / 0.25 do -> 1081 tia tren 270 do.
double scan_freq_hz = 25.0;
uint32_t samples = 1081;
double fov_rad = 4.712389; // 270 do
LidarStampMode stamp_mode = LidarStampMode::kFirstPacket;
// Bu do tre da do duoc, cong vao stamp. Chua do -> 0.
double stamp_offset_sec = 0.0;
// Canh bao neu do dai sweep lech qua nhieu so voi scan_time du kien. Day la
// bo phat hien mat goi UDP mien phi ma driver goc khong co.
double sweep_duration_tolerance_sec = 0.005;
double recv_timeout_sec = 1.0;
ScanSanitizerConfig sanitizer;
};
// --- Camera RealSense D410 -------------------------------------------------
struct CameraConfig {
std::string serial; // rong = lay thiet bi dau tien
uint32_t depth_width = 640;
uint32_t depth_height = 480;
uint32_t fps = 30;
bool enable_infra1 = true;
bool enable_infra2 = true;
// D410 khong co RGB (chi co Stereo Module) va khong co IMU tich hop.
// Emitter co dinh o 1 (Laser), KHONG bao gio 2 (Laser Auto): che do auto
// lam depth nhap nhay giua cac khung.
int emitter_mode = 1;
// Giam mau ngay tai driver, tuong duong image_proc/crop_decimate.
// 2 -> 320x240. Cap nhat binning_x/y trong CameraInfo chu KHONG chia lai K;
// consumer tu bu, dung nhu image_geometry lam.
uint32_t decimate = 2;
// Bat RS2_OPTION_GLOBAL_TIME_ENABLED de get_timestamp() tra ve dong ho host.
// Neu D410 FW 5.17.0.10 khong ho tro thi fallback sang TIME_OF_ARRIVAL --
// kem chinh xac hon, va driver se log WARN mot lan.
bool use_global_time = true;
std::string depth_frame_id = "camera_depth_optical_frame";
};
// --- MCU: IMU + barometer --------------------------------------------------
struct McuConfig {
std::string port = "/dev/ttyACM0";
uint32_t baud = 921600;
std::string imu_frame_id = "imu_link";
double ping_period_sec = 1.0; // chu ky ping de dong bo dong ho
// Datasheet ICM-42688-P / BMP390. TAT CA deu la doan tu datasheet cho toi
// khi chay allan_variance -- xem docs cua repo cu.
double gyro_variance = 2.4e-7;
double accel_variance = 4.8e-5;
double baro_variance = 9.0;
double read_timeout_sec = 1.0;
};
// --- Base: encoder + motor -------------------------------------------------
// Giao thuc host <-> base. Phan cung CO encoder (xac nhan tu nguoi dung va
// docs/HARDWARE.md muc 4), nhung giao thuc host doc chung thi CHUA XAC DINH
// o bat ky dau trong repo cu -- ban ROS gia dinh "firmware MCU publish
// /joint_states" ma firmware do chua ton tai.
//
// Vi vay transport duoc tach hoan toan khoi phep toan odometry: khi biet giao
// thuc that thi chi them mot lop mong, khong dung toi WheelOdometry.
enum class BaseProtocol {
// Mo rong giao thuc text san co cua MCU bang mot ban ghi:
// E,<micros>,<ticks_l>,<ticks_r>
// Tai dung ClockSync da co, va do la phan kho nhat -- nen day la lua chon
// re nhat neu firmware sua duoc.
kMcuTextEncoder,
// Serial rieng voi giao thuc nhi phan cua nha san xuat base.
kVendorSerial,
// Khong co base that: doc tu ban ghi .vsr.
kReplay,
};
struct BaseConfig {
BaseProtocol protocol = BaseProtocol::kMcuTextEncoder;
// Dung khi protocol = kVendorSerial.
std::string port = "/dev/ttyUSB0";
uint32_t baud = 115200;
// Hinh hoc. PHAI khop robot.yaml -- day la gia tri duy nhat, khong con ban
// sao trong URDF nua.
double wheel_radius = 0.075;
double wheel_separation = 0.36;
uint32_t ticks_per_rev = 0; // 0 = chua biet, PHAI dat truoc khi chay that
// Gioi han gui xuong motor. Lop safety da kep roi; day la chan cuoi.
double max_linear = 0.35;
double max_angular = 0.8;
// Khong nhan duoc lenh trong bao lau thi tu dung. Phai NGAN hon deadman cua
// teleop, de base dung truoc khi lop tren kip phan ung.
double cmd_timeout_sec = 0.3;
double rate_hz = 50.0;
};
} // namespace vslam
#endif // VSLAM_DRIVER_CONFIG_H

View File

@@ -0,0 +1,146 @@
#ifndef VSLAM_DRIVER_INTERFACES_H
#define VSLAM_DRIVER_INTERFACES_H
// Interface truu tuong + factory cho moi nguon du lieu phan cung.
//
// DAY LA DIEM TUA CUA TOAN BO CHIEN LUOC KIEM CHUNG.
//
// Replay source implement CHINH cac interface nay (xem replay_source.h), nen
// vslam_node khong biet minh dang chay live hay dang phat lai mot file .vsr.
// Khong co mot nhanh `if (replay)` nao trong logic. Doi lai: moi thu nhan
// duoc tu replay di qua dung nhung duong ma du lieu that di qua.
//
// Khong con Gazebo va khong con rosbag thi day la cach duy nhat con lai de
// chay lai mot kich ban hong ma khong phai dung ra hanh lang.
#include <functional>
#include <memory>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/stats.h"
#include "vslam/vslam_common.h"
namespace vslam {
// --- LiDAR -----------------------------------------------------------------
class LidarInterface {
public:
using ScanCallback = std::function<void(LaserScanPtr)>;
virtual ~LidarInterface() = default;
// Callback duoc goi tren luong RIENG cua driver. Dat truoc khi mo thiet bi.
virtual void SetCallback(ScanCallback cb) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<LidarInterface> CreateLakiBeamDriver(const LidarConfig& cfg,
ClockPtr clock);
// --- Camera ----------------------------------------------------------------
struct CameraFrame {
Header header; // stamp da quy ve dong ho host
ImagePtr depth; // kMono16, depth_scale met/don vi
ImagePtr infra1; // kMono8, co the null
ImagePtr infra2; // kMono8, co the null
CameraInfo depth_info; // fx/fy/cx/cy + binning sau khi decimate
};
class CameraInterface {
public:
using FrameCallback = std::function<void(const CameraFrame&)>;
virtual ~CameraInterface() = default;
virtual void SetCallback(FrameCallback cb) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<CameraInterface> CreateRealSenseD410(const CameraConfig& cfg,
ClockPtr clock);
// --- MCU: IMU + barometer --------------------------------------------------
// Mot lan doc cua dan sieu am.
//
// ⚠️ BA NGU NGHIA, y het tia laser, va KHONG duoc gop:
// gia tri huu han = khoang cach do duoc
// inf = khong co tieng vong -> hanh lang RONG, HOP LE
// NaN = cam bien khong tra loi -> US_TIMEOUT
// Bien inf thanh 0 se lam FSM tuong co vat cham vao mat cam bien va dung
// robot giua phong trong.
struct UltrasonicReading {
UnixTime stamp;
size_t count = 0;
double range[8] = {};
};
struct BumperReading {
UnixTime stamp;
uint32_t mask = 0; // bit i = cong tac thu i dang bi nhan
bool any() const { return mask != 0; }
};
class McuInterface {
public:
using UltrasonicCallback = std::function<void(const UltrasonicReading&)>;
using BumperCallback = std::function<void(const BumperReading&)>;
using ImuCallback = std::function<void(ImuPtr)>;
using BaroCallback = std::function<void(const FluidPressure&, const Temperature&)>;
virtual ~McuInterface() = default;
virtual void SetImuCallback(ImuCallback cb) = 0;
virtual void SetBaroCallback(BaroCallback cb) = 0;
// Sieu am va bumper deu nam tren MCU: ca hai la cam bien MUC THAP phai toi
// duoc vong an toan ke ca khi may tinh chinh dang ban.
virtual void SetUltrasonicCallback(UltrasonicCallback cb) = 0;
virtual void SetBumperCallback(BumperCallback cb) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg, ClockPtr clock);
// --- Base: encoder vao, lenh motor ra --------------------------------------
// Doc thang tu encoder. CO Y khong tra ve odometry: phep toan odometry
// (tich phan RK2, mo hinh covariance theo slip) nam o vslam_odometry va duoc
// kiem chung rieng, khong phu thuoc transport nao.
struct EncoderReading {
UnixTime stamp;
double left_rad = 0.0; // goc quay tich luy, radian
double right_rad = 0.0;
bool valid = false;
};
class BaseInterface {
public:
using EncoderCallback = std::function<void(const EncoderReading&)>;
virtual ~BaseInterface() = default;
virtual void SetEncoderCallback(EncoderCallback cb) = 0;
// Gui lenh xuong motor. An toan goi tu bat ky luong nao.
// Base PHAI tu dung neu khong nhan duoc lenh trong cmd_timeout_sec -- day la
// chan cuoi cung, doc lap voi lop safety va voi deadman cua teleop.
virtual void SetVelocity(double linear, double angular) = 0;
virtual StatusResponse Open() = 0;
virtual void Close() = 0;
virtual DriverStats Stats() const = 0;
};
std::unique_ptr<BaseInterface> CreateDiffDriveBase(const BaseConfig& cfg, ClockPtr clock);
} // namespace vslam
#endif // VSLAM_DRIVER_INTERFACES_H

View File

@@ -0,0 +1,118 @@
#ifndef VSLAM_MCU_PROTOCOL_H
#define VSLAM_MCU_PROTOCOL_H
// Giao thuc serial text giua host va MCU.
//
// PHAT HANH co y: file nay la DAC TA ma firmware phai khop. Ai viet firmware
// doc file nay, va test trong test_mcu_protocol.cc la bai kiem cho ca hai phia.
//
// ================== KHUNG BAN TIN ==================
// Text, mot ban ghi mot dong, ket thuc bang '\n'. Truong cach nhau bang ','.
//
// MCU -> host:
// I,<micros>,<gx>,<gy>,<gz>,<ax>,<ay>,<az> IMU (rad/s, m/s^2)
// B,<micros>,<pressure_pa>,<temp_c> Baro
// E,<micros>,<ticks_l>,<ticks_r> Encoder <-- MOI
// P,<micros>,<seq> Pong (tra loi ping)
//
// host -> MCU:
// p,<seq> Ping
//
// ================== BAN GHI E ==================
// Ban ROS gia dinh "firmware MCU publish /joint_states", nhung giao thuc cu
// chi co I/B/P -- KHONG co encoder. Phan cung co encoder (xac nhan tu nguoi
// dung va docs/HARDWARE.md muc 4), nen ban ghi E duoc them vao day.
//
// Lam theo huong nay vi no DUNG LAI ClockSync -- phan kho nhat va da duoc
// kiem chung. Mot serial thu hai cho encoder se phai dong bo dong ho lan nua,
// va hai dong ho lech nhau lam slip_metric (so gyro_z voi yaw_rate suy tu
// encoder) vo nghia.
//
// ticks la SO NGUYEN CO DAU, TICH LUY, va duoc phep tran: host tu unwrap.
// Dung gui delta -- mat mot dong serial la mat vinh vien mot doan quang duong,
// va khong co cach nao phat hien.
//
// ================== micros() TRAN ==================
// micros() la uint32_t, tran moi 71.58 phut. Host unwrap bang
// McuTimeUnwrapper (clock_sync.h). Firmware KHONG can lam gi ca.
#include <cstdint>
#include <string>
#include "vslam/vslam_common.h"
namespace vslam {
enum class McuRecordType : char {
kUnknown = '?',
kImu = 'I',
kBaro = 'B',
kEncoder = 'E',
// MO RONG moi, cung nguyen ly voi kEncoder: giao thuc goc chi co I/B/P.
//
// Sieu am va bumper nam tren MCU vi ca hai deu la cam bien MUC THAP phai
// doc o tan so cao va phai toi duoc vong an toan ke ca khi may tinh chinh
// dang ban. Dua chung qua USB rieng la them mot duong co the chet.
kUltrasonic = 'U', // U,<micros>,<mm_0>,<mm_1>,... 0 = khong do duoc
kBumper = 'K', // K,<micros>,<bitmask> bit i = cong tac i
kPong = 'P',
};
struct McuRecord {
McuRecordType type = McuRecordType::kUnknown;
uint32_t micros = 0;
// kImu
double gx = 0.0, gy = 0.0, gz = 0.0; // rad/s
double ax = 0.0, ay = 0.0, az = 0.0; // m/s^2
// kBaro
double pressure_pa = 0.0;
double temp_c = 0.0;
// kEncoder -- tich luy, co dau, duoc phep tran
int32_t ticks_l = 0;
int32_t ticks_r = 0;
// kUltrasonic -- met. INFINITY = ngoai tam; NaN = cam bien khong tra loi.
//
// ⚠️ Phan biet hai thu do la BAT BUOC: "khong thay gi" (hop le, hanh lang
// rong) khac han "cam bien chet" (phai bao US_TIMEOUT). Gop chung lai la
// xoa mat mot nhanh an toan.
static constexpr size_t kMaxUltrasonic = 8;
size_t us_count = 0;
double us_range[kMaxUltrasonic] = {};
// kBumper -- bit i = cong tac thu i dang bi nhan.
uint32_t bumper_mask = 0;
// kPong
uint32_t seq = 0;
};
// Phan tich mot dong (khong gom '\n'). Tra false neu dong hong -- goi nen dem
// va log throttle, KHONG duoc coi dong hong la du lieu 0.
bool ParseMcuLine(const std::string& line, McuRecord* out);
// Dung ban tin ping de gui xuong MCU (da gom '\n').
std::string BuildPing(uint32_t seq);
// Go tran cua bo dem tick uint32 cua encoder. Cung nguyen ly voi
// McuTimeUnwrapper nhung cho so CO DAU va co the chay ca hai chieu.
class TickUnwrapper {
public:
// Tra ve so tick tich luy da unwrap.
int64_t Unwrap(int32_t raw);
void Reset();
uint64_t wrap_count() const { return wraps_; }
private:
int32_t prev_ = 0;
int64_t high_ = 0;
uint64_t wraps_ = 0;
bool first_ = true;
};
} // namespace vslam
#endif // VSLAM_MCU_PROTOCOL_H

View File

@@ -0,0 +1,125 @@
#ifndef VSLAM_RECORD_FORMAT_H
#define VSLAM_RECORD_FORMAT_H
// Dinh dang ghi `.vsr` -- thay rosbag.
//
// ================== VI SAO CAN ==================
// Bo ROS la mat rosbag; bo Gazebo la mat kha nang dung lai mot kich ban hong.
// Khong co ca hai thi cach duy nhat de tai lap mot loi la day robot ra hanh
// lang lan nua va hy vong no hong giong lan truoc.
//
// ================== GHI THO ==================
// Ghi du lieu THO NHAT co the, truoc moi phep bien doi:
// SCAN_RAW ghi TRUOC ScanSanitizer, de doi nguong sanitizer cung test lai
// duoc tren cung mot ban ghi.
// Day dung nguyen tac cua topics_to_record.yaml trong ban ROS: chi ghi topic
// tho, khong ghi dau ra, de thuat toan chay lai duoc tren dung dau vao cu.
//
// ================== CAU TRUC ==================
// File = FileHeader + ChunkRecord*
//
// FileHeader (kHeaderSize byte):
// char[8] magic = "VSREC\0\0\0"
// u32 version
// u32 reserved
// u64 start_stamp_ns
// u32 config_json_len
// u8 config_json[config_json_len] <- toan bo config dang chay
//
// ChunkRecord:
// u32 magic = 0x43525356 ('VSRC')
// u8 stream_id
// u8 flags bit0 = payload nen bang zstd
// u16 reserved
// u64 stamp_ns
// u32 payload_len
// u8 payload[payload_len]
// u32 crc32(payload)
//
// config_json duoc nhung vao de mot ban ghi TU MO TA duoc: doc lai sau sau
// thang van biet no chay voi nguong nao.
//
// crc32 moi chunk de phat hien hong: mot file .vsr tren USB rut ra giua chung
// thi hong o cuoi, va replay phai dung lai o do chu khong doc rac.
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
constexpr char kVsrMagic[8] = {'V', 'S', 'R', 'E', 'C', '\0', '\0', '\0'};
constexpr uint32_t kVsrChunkMagic = 0x43525356u; // 'VSRC' little-endian
constexpr uint32_t kVsrVersion = 1;
constexpr size_t kVsrHeaderFixedSize = 28; // truoc config_json
constexpr size_t kVsrChunkHeaderSize = 20; // truoc payload
enum class VsrStream : uint8_t {
kScanRaw = 1, // TRUOC sanitizer
kImu = 2,
kBaro = 3,
kEncoder = 4,
kDepth = 5,
kInfra1 = 6,
kInfra2 = 7,
kCameraInfo = 8,
kCmdVel = 9, // dau vao cua safety, khong phai dau ra
kEvent = 10, // JSON: drop, doi config, lenh operator, mat goi
// Hai stream nay la MO RONG moi. Chung phai co trong ban ghi vi lop an
// toan TIEU THU chung: mot ban ghi thieu sieu am/bumper thi khi phat lai,
// hai nhanh US_BLOCKED va BUMPER khong bao gio chay -- va bo hoi quy se
// bao "xanh" cho mot he da mat hai nhanh an toan.
kUltrasonic = 11,
kBumper = 12,
};
const char* VsrStreamName(VsrStream s);
struct VsrChunkHeader {
VsrStream stream = VsrStream::kEvent;
bool compressed = false;
uint64_t stamp_ns = 0;
uint32_t payload_len = 0;
};
// --- Ma hoa tung loai ban tin ---------------------------------------------
// Noi them vao `out`. Chi la payload, khong gom chunk header.
void EncodeScanPayload(const LaserScan& scan, std::string* out);
bool DecodeScanPayload(const std::string& buf, LaserScan* out);
void EncodeImuPayload(const Imu& imu, std::string* out);
bool DecodeImuPayload(const std::string& buf, Imu* out);
void EncodeEncoderPayload(double left_rad, double right_rad, std::string* out);
bool DecodeEncoderPayload(const std::string& buf, double* left_rad, double* right_rad);
void EncodeBaroPayload(const FluidPressure& p, const Temperature& t, std::string* out);
bool DecodeBaroPayload(const std::string& buf, FluidPressure* p, Temperature* t);
void EncodeTwistPayload(const Twist& tw, std::string* out);
bool DecodeTwistPayload(const std::string& buf, Twist* out);
void EncodeUltrasonicPayload(const double* range, size_t count, std::string* out);
bool DecodeUltrasonicPayload(const std::string& buf, double* range, size_t* count,
size_t max_count);
void EncodeBumperPayload(uint32_t mask, std::string* out);
bool DecodeBumperPayload(const std::string& buf, uint32_t* mask);
void EncodeCameraInfoPayload(const CameraInfo& info, std::string* out);
bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out);
// Anh: header nho + du lieu pixel tho. Khong nen o day -- nen lam o tang
// chunk de doi thuat toan nen khong phai doi dinh dang ban tin.
void EncodeImagePayload(const Image& img, std::string* out);
bool DecodeImagePayload(const std::string& buf, Image* out, std::vector<uint8_t>* storage);
// --- crc32 (IEEE 802.3, giong zlib) ---------------------------------------
uint32_t Crc32(const void* data, size_t len, uint32_t seed = 0);
} // namespace vslam
#endif // VSLAM_RECORD_FORMAT_H

View File

@@ -0,0 +1,120 @@
#ifndef VSLAM_RECORD_IO_H
#define VSLAM_RECORD_IO_H
// Doc/ghi file .vsr.
//
// ================== NGUYEN TAC CUA WRITER ==================
// GHI LOG TUYET DOI KHONG DUOC NGHEN VONG AN TOAN.
//
// Writer chay tren LUONG RIENG voi hang doi co chan tren. Khi hang doi day
// thi no DROP chu khong bao gio chan nguoi goi. Mot the USB cham khong duoc
// phep lam luong lidar_rx dung lai.
//
// Moi lan drop duoc dem VA ghi vao stream kEvent, nen mot ban ghi TU MO TA
// duoc cac lo hong cua chinh no. Doc lai sau sau thang van biet doan nao
// thieu du lieu va thieu bao nhieu -- thay vi ngoi doan tai sao thuat toan
// cu xu la o giay thu 412.
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include "vslam/record_format.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct RecordWriterConfig {
std::string path;
// Chan tren cua hang doi, tinh bang byte. Vuot thi drop chunk moi.
size_t max_queue_bytes = 64u * 1024u * 1024u;
// Nen payload bang zstd neu co. Chua bat -- can libzstd, va do thi de sau.
bool compress = false;
// Giam tai cho anh depth. Tho: 640x480x2 x 30 Hz x 3 luong = 37 MB/s
// ~ 133 GB/gio, khong dung duoc. Voi decimate=2 va 10 Hz thi xuong duoi
// 5 MB/s, tuc 18 GB/gio -- mot USB 64 GB chua duoc 3.5 gio.
double depth_rate_hz = 10.0;
bool record_infra1 = false;
bool record_infra2 = false;
// Toan bo config dang chay, nhung vao header de ban ghi tu mo ta duoc.
std::string config_json;
};
struct RecordWriterStats {
uint64_t chunks_written = 0;
uint64_t bytes_written = 0;
uint64_t chunks_dropped = 0; // hang doi day
uint64_t queue_bytes = 0;
uint64_t write_errors = 0;
};
class RecordWriter {
public:
explicit RecordWriter(RecordWriterConfig cfg);
~RecordWriter();
RecordWriter(const RecordWriter&) = delete;
RecordWriter& operator=(const RecordWriter&) = delete;
StatusResponse Open();
void Close();
// KHONG BAO GIO CHAN. Tra false neu chunk bi drop vi hang doi day.
bool Write(VsrStream stream, UnixTime stamp, std::string payload);
// Ghi mot su kien JSON vao stream kEvent.
void WriteEvent(UnixTime stamp, const std::string& json);
RecordWriterStats Stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
// --- Reader ----------------------------------------------------------------
struct RecordFileInfo {
uint32_t version = 0;
UnixTime start_stamp;
std::string config_json;
};
class RecordReader {
public:
RecordReader();
~RecordReader();
RecordReader(const RecordReader&) = delete;
RecordReader& operator=(const RecordReader&) = delete;
StatusResponse Open(const std::string& path);
void Close();
const RecordFileInfo& info() const;
// Doc chunk ke tiep. Tra false khi het file HOAC khi gap chunk hong.
//
// Chunk hong KHONG duoc bo qua de doc tiep: mot file .vsr tren USB rut ra
// giua chung thi hong o cuoi, va doc tiep chi cho ra rac. Dung lai va bao
// qua `truncated()`.
bool Next(VsrChunkHeader* header, std::string* payload);
// true neu dung vi CRC sai hoac chunk cut, false neu den cuoi file binh thuong.
bool truncated() const;
uint64_t chunks_read() const;
uint64_t bytes_read() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_RECORD_IO_H

View File

@@ -0,0 +1,109 @@
#ifndef VSLAM_REPLAY_SOURCE_H
#define VSLAM_REPLAY_SOURCE_H
// Phat lai mot file .vsr qua CHINH cac interface driver.
//
// ================== VI SAO DAY LA MANH KHOA ==================
// ReplaySources tra ve nhung LidarInterface / CameraInterface / McuInterface /
// BaseInterface that -- cung kieu ma driver phan cung tra ve.
//
// Hau qua: vslam_node KHONG BIET minh dang chay live hay dang phat lai. Khong
// co mot nhanh `if (replay)` nao trong logic. Moi thu doc tu file di qua dung
// nhung duong ma du lieu that di qua: cung ScanSanitizer, cung EKF, cung
// safety, cung SLAM.
//
// Day la loi ich kien truc lon nhat cua viec dung interface truu tuong +
// factory, va la thu thay the cho ca Gazebo lan rosbag cung mot luc.
//
// ================== CHE DO TAT DINH ==================
// Voi `deterministic = true`: MOT luong duy nhat, day moi ban ghi theo dung
// thu tu stamp, dung ReplayClock. Chay lai cung mot file cho ra ket qua giong
// het den tung byte.
//
// Dieu do CHI kha thi neu quy tac o clock.h duoc giu tu ngay dau: khong stage
// nao goi UnixTime::now() truc tiep, moi stage nhan Clock& qua constructor.
// Vi pham mot cho thoi la mat tinh tat dinh, va khong the sua bang cach sua
// rieng replay.
#include <memory>
#include <string>
#include "vslam/clock.h"
#include "vslam/driver_interfaces.h"
namespace vslam {
struct ReplayConfig {
std::string path;
// 1.0 = thoi gian that. 0 = chay nhanh nhat co the (khong ngu).
double speed = 1.0;
// Bo qua bao nhieu giay dau file, va chay bao lau. 0 = toan bo.
double start_sec = 0.0;
double duration_sec = 0.0;
// Mot luong, day theo thu tu stamp. Bo qua `speed`.
bool deterministic = false;
// Lap lai tu dau khi het file. Dung khi debug UI.
bool loop = false;
// Ap ScanSanitizer len SCAN_RAW. Mac dinh true: ban ghi luu du lieu THO
// (truoc sanitizer) chinh la de doi nguong roi test lai duoc.
bool apply_sanitizer = true;
ScanSanitizerConfig sanitizer;
};
// So huu ca bon nguon. Huy object nay se dung viec phat lai.
class ReplaySource {
public:
explicit ReplaySource(ReplayConfig cfg);
~ReplaySource();
ReplaySource(const ReplaySource&) = delete;
ReplaySource& operator=(const ReplaySource&) = delete;
StatusResponse Open();
// Dong ho ao. Moi stage phai dung dong ho NAY, khong phai dong ho he thong.
ClockPtr clock() const;
// Bon nguon nay la interface driver that. Dat callback nhu voi phan cung.
LidarInterface* lidar();
CameraInterface* camera();
McuInterface* mcu();
BaseInterface* base();
// Chay het file (hoac het `duration_sec`). Chan cho toi khi xong.
// Trong che do tat dinh, day la vong lap don luong duy nhat.
void Run();
// Yeu cau dung som. An toan goi tu luong khac.
void RequestStop();
// Config luc ghi, lay tu header cua file. Cho biet ban ghi chay voi nguong
// nao -- mot ban ghi tu mo ta duoc.
const std::string& recorded_config_json() const;
struct Stats {
uint64_t chunks = 0;
uint64_t scans = 0;
uint64_t imu = 0;
uint64_t encoder = 0;
uint64_t camera_frames = 0;
uint64_t events = 0;
uint64_t skipped = 0; // ngoai cua so start/duration
bool truncated = false; // file hong giua chung
double duration_sec = 0.0;
};
Stats stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_REPLAY_SOURCE_H

View File

@@ -0,0 +1,115 @@
#ifndef VSLAM_SCAN_SANITIZER_H
#define VSLAM_SCAN_SANITIZER_H
// Ve sinh LaserScan tho tu LiDAR truoc khi bat ky ai dung no.
//
// Gop hai thu cua ban ROS lam mot:
// 1. robot_drivers/ScanHeaderFixFilter -- sua ba bug cua driver LakiBeam
// 2. hai laser_filters/LaserScanAngularBoundsFilterInPlace -- cat quat bi
// than robot che
//
// GOP LAI LA CO Y. Ban ROS phai ghi mot khoi comment canh bao rang filter 1
// BAT BUOC chay truoc filter 2, vi filter 2 blank tia bang `range_max + 1.0`:
// neu chay truoc thi sentinel thanh 101.0 thay vi 41.0, va safety_monitor doc
// sai so tia bi che. Gop vao mot ham thi thu tu do khong the sai duoc nua.
//
// ================== BA BUG CUA DRIVER LAKIBEAM ==================
// Da doc source de xac nhan (xem docs/HARDWARE.md cua repo cu):
// range_min = 0.0 <- thiet bi that: 0.05
// range_max = 100.0 <- thiet bi that: 40.0
// time_increment = duration / n / 2 <- thua phep chia 2
//
// `range_min = 0.0` la cai nguy hiem nhat. Phep loc chuan cua MOI consumer la
// `if (r < range_min) continue;`. Voi range_min = 0.0 thi `0.0 < 0.0` la sai,
// nen mot tia bao 0.0 -- von nghia la "khong do duoc" -- duoc CHAP NHAN thanh
// vat can ngay goc LiDAR. Hau qua: safety_monitor thay vat can 0.0 m va dung
// vinh vien.
//
// ================== BA NGU NGHIA CUA MOT TIA ==================
// Phan biet ba thu KHAC NHAU, khong duoc gop:
//
// NaN "khong do duoc" consumer bo qua, KHONG clear free space
// inf "khong co gi trong tam" duoc phep clear free space
// range_max+1.0 "khong duoc phep nhin" bi than robot che; safety_monitor
// dem rieng (front_blanked) va khong
// tinh vao front_usable
//
// Vi sao 0.0 -> NaN chu khong phai inf: LiDAR tra 0.0 cho CA HAI truong hop
// "khong co vat trong tam" VA "be mat den nuot het xung". Map sang inf thi
// robot se clear free space XUYEN QUA ghe da den. Map sang NaN thi hong ve
// phia "coi nhu co vat", tuc an toan.
#include <cstddef>
#include <string>
#include <vector>
#include "vslam/stats.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct SectorMask {
double lower_rad = 0.0; // cat cac tia co goc trong [lower, upper]
double upper_rad = 0.0;
};
struct ScanSanitizerConfig {
// Ep header ve gia tri that cua thiet bi.
double range_min = 0.05;
double range_max = 40.0;
// true = bo phep chia 2 thua cua driver.
bool fix_time_increment = true;
// "nan" hoac "inf". Mac dinh "nan" -- xem khoi comment tren.
std::string zero_is = "nan";
// Quat bi than robot che. Voi cau hinh hien tai: laser o x=0.24, than robot
// nua rong 0.17 va mat truoc x=0.14 -> tu che ngoai +-120.5 do, cat o +-118
// de co bien an toan. Con lai ~236 do huu dung tren 270 do.
std::vector<SectorMask> sector_masks;
// Xoay toan bo scan. Dung khi huong 0 do vat ly cua LiDAR khong trung voi
// truc x cua robot. GIA TRI THAT CHUA DO DUOC -- xem tools/vslam_scan_check.
double angle_offset_rad = 0.0;
};
struct ScanSanitizerStats {
uint64_t scans = 0;
uint64_t rays_total = 0;
uint64_t rays_zero = 0; // driver tra 0.0
uint64_t rays_below_min = 0;
uint64_t rays_above_max = 0;
uint64_t rays_blanked = 0; // bi sector mask cat
uint64_t rays_valid = 0;
};
class ScanSanitizer {
public:
explicit ScanSanitizer(ScanSanitizerConfig cfg);
// Nem std::invalid_argument neu cau hinh vo ly (range_min <= 0, range_max
// <= range_min). Kiem o day chu khong im lang roi ve default: mot LiDAR
// cau hinh sai la mot robot dam vao tuong.
static void Validate(const ScanSanitizerConfig& cfg);
// Sua TAI CHO. Giu nguyen stamp, angle_*, va so luong tia.
void Apply(LaserScan* scan);
const ScanSanitizerStats& stats() const { return stats_; }
void ResetStats() { stats_ = ScanSanitizerStats{}; }
// Gia tri sentinel ma sector mask dung, theo cau hinh hien tai.
float blank_value() const { return static_cast<float>(cfg_.range_max) + 1.0f; }
private:
bool InMaskedSector(double angle) const;
ScanSanitizerConfig cfg_;
bool zero_to_inf_ = false;
ScanSanitizerStats stats_;
};
} // namespace vslam
#endif // VSLAM_SCAN_SANITIZER_H

View File

@@ -0,0 +1,140 @@
#include "vslam/clock_sync.h"
#include <algorithm>
#include <cmath>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
constexpr uint64_t kWrapPeriodUs = 1ULL << 32; // 4294967296 us = 71.58 phut
constexpr uint32_t kHalfRange = 1U << 31;
} // namespace
// --- McuTimeUnwrapper ------------------------------------------------------
double McuTimeUnwrapper::UnwrapSeconds(uint32_t micros) {
if (first_) {
first_ = false;
prev_us_ = micros;
return static_cast<double>(micros) * 1e-6;
}
// Tran khi gia tri moi NHO HON gia tri truoc mot khoang lon. Nguong nua dai
// (2^31) phan biet duoc "tran" voi "ban tin den khong dung thu tu": ban tin
// lech thu tu chi lui vai mili giay, con tran thi lui gan 71 phut.
//
// GIA DINH: khoang cach giua hai lan goi < nua chu ky (35.79 phut). Neu goi
// thua hon nua chu ky thi khong the phan biet "tran" voi "nhay lui" -- day
// la gioi han co ban cua moi bo dem tran, khong phai thieu sot cai dat.
// O 200 Hz (IMU) hay 50 Hz (encoder) thi gia dinh nay du xa an toan; neu
// sau nay co nguon nao goi thua hon 35 phut mot lan thi nguon do can dong
// ho rieng chu khong dung duoc lop nay.
if (micros < prev_us_ && (prev_us_ - micros) > kHalfRange) {
high_ += kWrapPeriodUs;
wraps_++;
VSLAM_INFO("clock_sync: micros() tran lan thu " << wraps_
<< " (moi 71.58 phut) -- da bu");
}
prev_us_ = micros;
return static_cast<double>(high_ + micros) * 1e-6;
}
void McuTimeUnwrapper::Reset() {
prev_us_ = 0;
high_ = 0;
wraps_ = 0;
first_ = true;
}
// --- ClockSync -------------------------------------------------------------
ClockSync::ClockSync(ClockSyncConfig cfg) : cfg_(cfg) {
if (cfg_.window == 0) cfg_.window = 1;
if (cfg_.keep_best == 0) cfg_.keep_best = 1;
}
void ClockSync::Add(double mcu_s, double t_send, double t_recv) {
const double rtt = t_recv - t_send;
if (!(rtt >= 0.0)) return; // bat ca NaN
// Gia dinh do tre doi xung: thoi diem MCU tra loi nam giua luc gui va luc
// nhan. Chi dung khi RTT nho -- do la ly do chi giu mau RTT nho nhat.
const double host_s = 0.5 * (t_send + t_recv);
samples_.push_back(Sample{rtt, mcu_s, host_s});
while (samples_.size() > cfg_.window) samples_.pop_front();
Fit();
}
void ClockSync::Fit() {
if (samples_.size() < 2) return;
std::vector<Sample> best(samples_.begin(), samples_.end());
const size_t k = std::min(cfg_.keep_best, best.size());
std::partial_sort(best.begin(), best.begin() + static_cast<long>(k), best.end(),
[](const Sample& a, const Sample& b) { return a.rtt < b.rtt; });
best.resize(k);
if (best.size() < 2) return;
const double n = static_cast<double>(best.size());
double sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0;
for (const auto& s : best) {
sx += s.mcu_s;
sy += s.host_s;
sxx += s.mcu_s * s.mcu_s;
sxy += s.mcu_s * s.host_s;
}
const double denom = n * sxx - sx * sx;
if (std::abs(denom) < 1e-12) {
// Cac mau qua gan nhau ve thoi gian -> chua uoc luong duoc skew, nhung
// offset thi van uoc luong duoc.
offset_ = (sy - sx) / n;
skew_ = 1.0;
ready_ = true;
return;
}
const double skew = (n * sxy - sx * sy) / denom;
const double offset = (sy - skew * sx) / n;
// Skew phai rat gan 1.0 -- thach anh lech vai chuc ppm. Lech nhieu nghia la
// du lieu rac (giao thuc sai, hoac micros() tran ma khong unwrap).
if (std::abs(skew - 1.0) > cfg_.max_skew_dev) {
rejected_++;
VSLAM_WARN_THROTTLE(30.0, "clock_sync: skew bat thuong ("
<< skew << ", lech " << (skew - 1.0) * 1e6
<< " ppm), bo qua ket qua fit. Kiem giao thuc MCU"
" va viec unwrap micros().");
skew_ = 1.0;
offset_ = (sy - sx) / n;
ready_ = true;
return;
}
skew_ = skew;
offset_ = offset;
ready_ = true;
}
bool ClockSync::ToHost(double mcu_s, double* host_s) const {
if (!ready_) return false;
*host_s = skew_ * mcu_s + offset_;
return true;
}
void ClockSync::Reset() {
samples_.clear();
skew_ = 1.0;
offset_ = 0.0;
ready_ = false;
rejected_ = 0;
}
} // namespace vslam

View File

@@ -0,0 +1,179 @@
#include "vslam/mcu_protocol.h"
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <limits>
#include <vector>
namespace vslam {
namespace {
// Tach theo ',' khong cap phat trung gian.
size_t SplitFields(const std::string& line, std::vector<const char*>* starts,
std::string* buf) {
*buf = line;
starts->clear();
bool in_field = false;
for (size_t i = 0; i < buf->size(); ++i) {
if ((*buf)[i] == ',') {
(*buf)[i] = '\0';
in_field = false;
continue;
}
if (!in_field) {
starts->push_back(buf->c_str() + i);
in_field = true;
}
}
return starts->size();
}
bool ToDouble(const char* s, double* out) {
char* end = nullptr;
const double v = std::strtod(s, &end);
if (end == s || *end != '\0') return false;
*out = v;
return true;
}
bool ToU32(const char* s, uint32_t* out) {
char* end = nullptr;
const unsigned long v = std::strtoul(s, &end, 10);
if (end == s || *end != '\0') return false;
if (v > std::numeric_limits<uint32_t>::max()) return false;
*out = static_cast<uint32_t>(v);
return true;
}
bool ToI32(const char* s, int32_t* out) {
char* end = nullptr;
const long v = std::strtol(s, &end, 10);
if (end == s || *end != '\0') return false;
if (v > std::numeric_limits<int32_t>::max() ||
v < std::numeric_limits<int32_t>::min()) {
return false;
}
*out = static_cast<int32_t>(v);
return true;
}
} // namespace
bool ParseMcuLine(const std::string& line, McuRecord* out) {
if (line.empty() || out == nullptr) return false;
std::string buf;
std::vector<const char*> f;
const size_t n = SplitFields(line, &f, &buf);
if (n < 2) return false;
// Ky tu loai phai dung mot ky tu. "II" hay "I " deu la dong hong.
if (std::strlen(f[0]) != 1) return false;
const char tag = f[0][0];
if (!ToU32(f[1], &out->micros)) return false;
switch (tag) {
case 'I': {
if (n != 8) return false;
if (!ToDouble(f[2], &out->gx) || !ToDouble(f[3], &out->gy) ||
!ToDouble(f[4], &out->gz) || !ToDouble(f[5], &out->ax) ||
!ToDouble(f[6], &out->ay) || !ToDouble(f[7], &out->az)) {
return false;
}
out->type = McuRecordType::kImu;
return true;
}
case 'B': {
if (n != 4) return false;
if (!ToDouble(f[2], &out->pressure_pa) || !ToDouble(f[3], &out->temp_c)) {
return false;
}
out->type = McuRecordType::kBaro;
return true;
}
case 'E': {
if (n != 4) return false;
if (!ToI32(f[2], &out->ticks_l) || !ToI32(f[3], &out->ticks_r)) return false;
out->type = McuRecordType::kEncoder;
return true;
}
case 'U': {
// U,<micros>,<mm_0>,<mm_1>,... So cam bien BIEN THIEN theo cau hinh
// phan cung, nen khong chot so truong.
if (n < 3) return false;
const size_t k = std::min<size_t>(n - 2, McuRecord::kMaxUltrasonic);
for (size_t i = 0; i < k; ++i) {
int32_t mm = 0;
if (!ToI32(f[i + 2], &mm)) return false;
// Quy uoc cua module HC-SR04 va ho hang:
// 0 = khong co tieng vong -> KHONG PHAI 0 met, ma la "khong thay
// gi" -> inf. Doi 0 thanh 0.0 m se lam FSM tuong co vat cham
// vao mat cam bien va dung robot giua hanh lang rong.
// <0 = cam bien khong tra loi -> NaN, de US_TIMEOUT co the kich.
if (mm == 0) out->us_range[i] = std::numeric_limits<double>::infinity();
else if (mm < 0) out->us_range[i] = std::numeric_limits<double>::quiet_NaN();
else out->us_range[i] = mm * 0.001;
}
out->us_count = k;
out->type = McuRecordType::kUltrasonic;
return true;
}
case 'K': {
if (n != 3) return false;
if (!ToU32(f[2], &out->bumper_mask)) return false;
out->type = McuRecordType::kBumper;
return true;
}
case 'P': {
if (n != 3) return false;
if (!ToU32(f[2], &out->seq)) return false;
out->type = McuRecordType::kPong;
return true;
}
default:
return false;
}
}
std::string BuildPing(uint32_t seq) {
char buf[32];
const int len = std::snprintf(buf, sizeof(buf), "p,%u\n", seq);
return std::string(buf, static_cast<size_t>(len));
}
int64_t TickUnwrapper::Unwrap(int32_t raw) {
if (first_) {
first_ = false;
prev_ = raw;
return raw;
}
// Bo dem tran khi hieu vuot nua dai int32. Nguong nua dai phan biet duoc
// "tran" voi "robot lui": lui thi delta nho, tran thi delta gan 2^32.
constexpr int64_t kRange = 1LL << 32;
constexpr int64_t kHalf = 1LL << 31;
const int64_t delta = static_cast<int64_t>(raw) - static_cast<int64_t>(prev_);
if (delta < -kHalf) {
high_ += kRange; // tran len
wraps_++;
} else if (delta > kHalf) {
high_ -= kRange; // tran xuong (robot lui lau)
wraps_++;
}
prev_ = raw;
return high_ + static_cast<int64_t>(raw);
}
void TickUnwrapper::Reset() {
prev_ = 0;
high_ = 0;
wraps_ = 0;
first_ = true;
}
} // namespace vslam

View File

@@ -0,0 +1,404 @@
// Driver RealSense D410.
//
// ================== D410 KHAC GI CAC DONG KIA ==================
// D410 chi co Stereo Module: KHONG RGB, KHONG IMU tich hop. Nen:
// - Kenh "rgb" ma SLAM can duoc lap bang anh IR TRAI (infra1, mono8).
// - Nghieng phai lay tu IMU cua MCU, khong phai tu camera.
//
// ================== BA BAY DA BIET TRUOC ==================
// 1. `decimate` cap nhat `binning_x/y` chu KHONG chia lai K. Do la dung quy
// uoc sensor_msgs/CameraInfo, va moi consumer phai tu bu bang
// `fx_binned()`. Chia lai K o day se lam MOI consumer bu HAI LAN.
//
// 2. `RS2_OPTION_GLOBAL_TIME_ENABLED` chua xac minh tren FW 5.17.0.10. Khong
// co thi `get_timestamp()` tra ve dong ho CUA THIET BI, khong phai dong ho
// host -- va moi phep dong bo voi LiDAR/IMU sai hang chuc nam. Driver kiem
// tra domain THAT SU nhan duoc chu khong tin option da set.
//
// 3. Emitter phai co dinh o 1 (Laser), KHONG BAO GIO 2 (Laser Auto): che do
// auto lam depth nhap nhay giua cac khung, va `cliff_detect` doc su nhap
// nhay do thanh lo hong tren san.
//
// ================== VIET DUOC MA CHUA CO CAMERA ==================
// librealsense2 la API cong khai; cai chua lam duoc la KIEM CHUNG tren thiet
// bi that. Nhung thu chi biet duoc khi cam camera vao duoc danh dau ⚠️ CHUA
// XAC MINH ngay tai cho.
#include <librealsense2/rs.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Giu rs2::frameset song chung voi Image tro vao buffer cua no.
//
// `Image` KHONG so huu bo nho (xem vslam_common.h): `data` tro thang vao
// buffer cua SDK. Khong giu frameset thi SDK tai su dung buffer do ngay khung
// sau, va consumer doc phai anh MOI trong khi tuong minh doc anh CU -- mot
// loi khong bao gio crash, chi lam moi phep do lech mot khung.
struct FrameKeepAlive {
rs2::frameset fs;
};
class RealSenseDriver : public CameraInterface {
public:
RealSenseDriver(CameraConfig cfg, ClockPtr clock)
: cfg_(std::move(cfg)), clock_(std::move(clock)) {}
~RealSenseDriver() override { Close(); }
void SetCallback(FrameCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override {
if (running_.load()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da mo roi");
}
if (cfg_.decimate == 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"camera.decimate = 0");
}
try {
rs2::config rc;
if (!cfg_.serial.empty()) rc.enable_device(cfg_.serial);
rc.enable_stream(RS2_STREAM_DEPTH, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Z16,
static_cast<int>(cfg_.fps));
if (cfg_.enable_infra1) {
rc.enable_stream(RS2_STREAM_INFRARED, 1, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Y8,
static_cast<int>(cfg_.fps));
}
if (cfg_.enable_infra2) {
rc.enable_stream(RS2_STREAM_INFRARED, 2, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Y8,
static_cast<int>(cfg_.fps));
}
pipe_.reset(new rs2::pipeline);
profile_.reset(new rs2::pipeline_profile(pipe_->start(rc)));
const StatusResponse st = Configure();
if (!st.ok()) {
pipe_->stop();
pipe_.reset();
profile_.reset();
return st;
}
} catch (const rs2::error& e) {
pipe_.reset();
profile_.reset();
return StatusResponse::Error(
StatusCode::kUnavailable,
std::string("realsense: ") + e.get_failed_function() + ": " + e.what());
} catch (const std::exception& e) {
pipe_.reset();
profile_.reset();
return StatusResponse::Error(StatusCode::kUnavailable,
std::string("realsense: ") + e.what());
}
running_.store(true);
thread_ = std::thread([this] { Loop(); });
return StatusResponse::Ok();
}
void Close() override {
if (!running_.exchange(false)) return;
if (thread_.joinable()) thread_.join();
try {
if (pipe_) pipe_->stop();
} catch (const std::exception&) {
// Dong thiet bi da rut day thi nem; khong co gi de lam va khong duoc
// phep nem tiep tu destructor.
}
pipe_.reset();
profile_.reset();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
private:
StatusResponse Configure() {
rs2::device dev = profile_->get_device();
auto sensors = dev.query_sensors();
for (rs2::sensor& s : sensors) {
// --- Emitter: co dinh o Laser, KHONG BAO GIO Laser Auto ---
if (s.supports(RS2_OPTION_EMITTER_ENABLED)) {
s.set_option(RS2_OPTION_EMITTER_ENABLED,
static_cast<float>(cfg_.emitter_mode));
}
// --- Dong ho ---
// Dat option la MOT chuyen; thiet bi co thuc su doi domain khong lai la
// chuyen khac. Kiem o Loop() bang domain THAT nhan duoc.
if (cfg_.use_global_time && s.supports(RS2_OPTION_GLOBAL_TIME_ENABLED)) {
s.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, 1.0f);
} else if (cfg_.use_global_time) {
VSLAM_WARN("realsense: thiet bi khong ho tro GLOBAL_TIME_ENABLED -- "
"stamp se theo dong ho THIET BI, khong phai host.");
}
}
// --- depth_scale: met moi don vi ---
// KHONG hardcode 0.001. D4xx mac dinh la vay nhung tuy chinh duoc, va mot
// camera da bi chinh se cho ra do sau sai ti le ma khong co gi bao.
try {
depth_scale_ = profile_->get_device()
.first<rs2::depth_sensor>()
.get_depth_scale();
} catch (const std::exception&) {
depth_scale_ = 0.001f;
VSLAM_WARN("realsense: khong doc duoc depth_scale, dung 0.001 m/don vi");
}
if (!(depth_scale_ > 0.0f)) {
return StatusResponse::Error(StatusCode::kInternal,
"realsense: depth_scale khong duong");
}
// --- Noi suy: doc tu profile, KHONG doan ---
const auto vsp = profile_->get_stream(RS2_STREAM_DEPTH)
.as<rs2::video_stream_profile>();
const rs2_intrinsics in = vsp.get_intrinsics();
info_ = CameraInfo{};
// width/height/K la cua do phan giai LUC HIEU CHUAN, con binning noi anh
// that nho hon bao nhieu lan. Do la dung quy uoc sensor_msgs/CameraInfo.
info_.width = static_cast<uint32_t>(in.width);
info_.height = static_cast<uint32_t>(in.height);
info_.k[0] = in.fx; info_.k[2] = in.ppx;
info_.k[4] = in.fy; info_.k[5] = in.ppy;
info_.k[8] = 1.0;
for (int i = 0; i < 5; ++i) info_.d[i] = in.coeffs[i];
info_.binning_x = cfg_.decimate;
info_.binning_y = cfg_.decimate;
info_.header.frame_id = cfg_.depth_frame_id;
VSLAM_INFO("realsense: " << in.width << "x" << in.height << " @ " << cfg_.fps
<< " Hz, fx=" << in.fx << " cx=" << in.ppx
<< ", depth_scale=" << depth_scale_
<< ", decimate=" << cfg_.decimate);
return StatusResponse::Ok();
}
// Giam mau NEAREST, khong lay trung binh.
//
// Trung binh tren anh depth la SAI: trung binh cua mot diem o 1 m va mot
// diem o 5 m cho ra 3 m, tuc mot be mat KHONG TON TAI lo lung giua. Tren
// mep vat the dieu do sinh ra ca mot vien gia. Lay diem goc la cach
// image_proc/crop_decimate lam, va la ly do no dung `decimate` chu khong
// phai `resize`.
void Decimate16(const uint16_t* src, int sw, int sh, int step,
std::vector<uint8_t>* dst, uint32_t* ow, uint32_t* oh) {
const int w = sw / step, h = sh / step;
dst->resize(static_cast<size_t>(w) * h * 2);
auto* out = reinterpret_cast<uint16_t*>(dst->data());
for (int y = 0; y < h; ++y) {
const uint16_t* row = src + static_cast<size_t>(y) * step * sw;
for (int x = 0; x < w; ++x) out[static_cast<size_t>(y) * w + x] = row[x * step];
}
*ow = static_cast<uint32_t>(w);
*oh = static_cast<uint32_t>(h);
}
void Decimate8(const uint8_t* src, int sw, int sh, int step,
std::vector<uint8_t>* dst, uint32_t* ow, uint32_t* oh) {
const int w = sw / step, h = sh / step;
dst->resize(static_cast<size_t>(w) * h);
for (int y = 0; y < h; ++y) {
const uint8_t* row = src + static_cast<size_t>(y) * step * sw;
for (int x = 0; x < w; ++x) (*dst)[static_cast<size_t>(y) * w + x] = row[x * step];
}
*ow = static_cast<uint32_t>(w);
*oh = static_cast<uint32_t>(h);
}
void Loop() {
bool warned_domain = false;
bool warned_drop = false;
uint64_t last_frame_number = 0;
while (running_.load()) {
rs2::frameset fs;
try {
// Timeout co gioi han: `wait_for_frames()` mac dinh 5 s va se treo ca
// luong neu camera bi rut day. 200 ms cho phep vong kiem `running_`.
if (!pipe_->try_wait_for_frames(&fs, 200)) {
std::lock_guard<std::mutex> lk(mu_);
stats_.errors++; // het gio = mat khung, dem chung o day
continue;
}
} catch (const std::exception& e) {
std::lock_guard<std::mutex> lk(mu_);
stats_.errors++;
VSLAM_ERROR_THROTTLE(5.0, "realsense: " << e.what());
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
rs2::depth_frame depth = fs.get_depth_frame();
if (!depth) continue;
// --- Dau thoi gian ---
//
// Kiem DOMAIN THAT SU nhan duoc, khong tin option da set. Neu khong
// phai HARDWARE_CLOCK/SYSTEM_TIME thi stamp la dong ho CUA THIET BI --
// mot so hoan toan khong lien quan toi dong ho host, va moi phep dong
// bo voi LiDAR/IMU sai hang chuc nam.
const rs2_timestamp_domain dom = depth.get_frame_timestamp_domain();
UnixTime stamp;
if (dom == RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME ||
dom == RS2_TIMESTAMP_DOMAIN_GLOBAL_TIME) {
// get_timestamp() tra milli giay.
stamp = UnixTime::fromSec(depth.get_timestamp() * 1e-3);
} else {
if (!warned_domain) {
warned_domain = true;
VSLAM_WARN("realsense: timestamp domain = "
<< rs2_timestamp_domain_to_string(dom)
<< " (khong phai dong ho host). Dung thoi diem NHAN"
" thay the -- jitter cao hon, nhung it nhat cung mot"
" goc thoi gian voi LiDAR va IMU.");
}
stamp = clock_->Now();
}
// --- Dem khung roi ---
// SDK khong bao khi ta xu ly cham hon camera; so hieu khung thi co.
const uint64_t fn = depth.get_frame_number();
if (last_frame_number != 0 && fn > last_frame_number + 1) {
std::lock_guard<std::mutex> lk(mu_);
stats_.packets_lost += fn - last_frame_number - 1;
if (!warned_drop) {
warned_drop = true;
VSLAM_WARN("realsense: bo lo khung (so hieu nhay " << last_frame_number
<< " -> " << fn << "). Duong camera dang cham hon "
<< cfg_.fps << " Hz.");
}
}
last_frame_number = fn;
if (!cb_) continue;
auto keep = std::make_shared<FrameKeepAlive>();
keep->fs = fs;
CameraFrame out;
out.header.stamp = stamp;
out.header.frame_id = cfg_.depth_frame_id;
auto depth_img = std::make_shared<Image>();
depth_img->header = out.header;
depth_img->format = PixelFormat::kMono16;
depth_img->depth_scale = depth_scale_;
const int sw = depth.get_width(), sh = depth.get_height();
const auto* praw = static_cast<const uint16_t*>(depth.get_data());
if (cfg_.decimate <= 1) {
depth_img->width = static_cast<uint32_t>(sw);
depth_img->height = static_cast<uint32_t>(sh);
depth_img->step = static_cast<uint32_t>(sw) * 2;
depth_img->data = static_cast<const uint8_t*>(depth.get_data());
depth_img->keep_alive = keep; // KHONG copy: giu frameset song
} else {
Decimate16(praw, sw, sh, static_cast<int>(cfg_.decimate), &depth_buf_,
&depth_img->width, &depth_img->height);
depth_img->step = depth_img->width * 2;
depth_img->data = depth_buf_.data();
// Bo dem cua ta: hop le toi lan goi Loop() sau. Consumer chay INLINE
// trong callback (xem PerceptionPipeline) nen dieu do la du.
}
out.depth = depth_img;
if (cfg_.enable_infra1) {
rs2::video_frame ir = fs.get_infrared_frame(1);
if (ir) out.infra1 = WrapIr(ir, out.header, keep, &ir1_buf_);
}
if (cfg_.enable_infra2) {
rs2::video_frame ir = fs.get_infrared_frame(2);
if (ir) out.infra2 = WrapIr(ir, out.header, keep, &ir2_buf_);
}
out.depth_info = info_;
out.depth_info.header = out.header;
{
std::lock_guard<std::mutex> lk(mu_);
stats_.frames++;
stats_.connected = true;
}
cb_(out);
}
}
ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr,
const std::shared_ptr<FrameKeepAlive>& keep,
std::vector<uint8_t>* buf) {
auto img = std::make_shared<Image>();
img->header = hdr;
img->format = PixelFormat::kMono8;
const int w = ir.get_width(), h = ir.get_height();
if (cfg_.decimate <= 1) {
img->width = static_cast<uint32_t>(w);
img->height = static_cast<uint32_t>(h);
img->step = static_cast<uint32_t>(w);
img->data = static_cast<const uint8_t*>(ir.get_data());
img->keep_alive = keep;
} else {
Decimate8(static_cast<const uint8_t*>(ir.get_data()), w, h,
static_cast<int>(cfg_.decimate), buf, &img->width, &img->height);
img->step = img->width;
img->data = buf->data();
}
return img;
}
CameraConfig cfg_;
ClockPtr clock_;
FrameCallback cb_;
std::unique_ptr<rs2::pipeline> pipe_;
std::unique_ptr<rs2::pipeline_profile> profile_;
float depth_scale_ = 0.001f;
CameraInfo info_;
std::vector<uint8_t> depth_buf_, ir1_buf_, ir2_buf_;
std::atomic<bool> running_{false};
std::thread thread_;
mutable std::mutex mu_;
DriverStats stats_;
};
} // namespace
std::unique_ptr<CameraInterface> CreateRealSenseD410(const CameraConfig& cfg,
ClockPtr clock) {
return std::unique_ptr<CameraInterface>(
new RealSenseDriver(cfg, std::move(clock)));
}
} // namespace vslam

View File

@@ -0,0 +1,367 @@
#include "vslam/record_format.h"
#include <cstring>
namespace vslam {
namespace {
// --- Ghi/doc so nguyen little-endian, khong phu thuoc endian cua may -------
// Khong memcpy thang struct: ban ghi phai doc duoc tren may khac, va x86 dev
// voi arm64 Jetson la hai may khac nhau.
void PutU8(std::string* o, uint8_t v) { o->push_back(static_cast<char>(v)); }
void PutU16(std::string* o, uint16_t v) {
for (int i = 0; i < 2; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutU32(std::string* o, uint32_t v) {
for (int i = 0; i < 4; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutU64(std::string* o, uint64_t v) {
for (int i = 0; i < 8; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutF32(std::string* o, float v) {
uint32_t b;
std::memcpy(&b, &v, 4);
PutU32(o, b);
}
void PutF64(std::string* o, double v) {
uint64_t b;
std::memcpy(&b, &v, 8);
PutU64(o, b);
}
struct Reader {
const std::string& b;
size_t o = 0;
bool ok = true;
explicit Reader(const std::string& buf) : b(buf) {}
bool Need(size_t n) {
if (!ok || o + n > b.size()) {
ok = false;
return false;
}
return true;
}
uint8_t U8() { return Need(1) ? static_cast<uint8_t>(b[o++]) : 0; }
uint16_t U16() {
if (!Need(2)) return 0;
uint16_t v = 0;
for (int i = 0; i < 2; ++i) v |= static_cast<uint16_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
o += 2;
return v;
}
uint32_t U32() {
if (!Need(4)) return 0;
uint32_t v = 0;
for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
o += 4;
return v;
}
uint64_t U64() {
if (!Need(8)) return 0;
uint64_t v = 0;
for (int i = 0; i < 8; ++i) v |= static_cast<uint64_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
o += 8;
return v;
}
float F32() {
const uint32_t bits = U32();
float f = 0.0f;
std::memcpy(&f, &bits, 4);
return f;
}
double F64() {
const uint64_t bits = U64();
double d = 0.0;
std::memcpy(&d, &bits, 8);
return d;
}
std::string Str() {
const uint32_t n = U32();
if (!Need(n)) return {};
std::string s = b.substr(o, n);
o += n;
return s;
}
};
void PutStr(std::string* o, const std::string& s) {
PutU32(o, static_cast<uint32_t>(s.size()));
o->append(s);
}
void PutHeader(std::string* o, const Header& h) {
PutU32(o, h.seq);
PutU64(o, static_cast<uint64_t>(h.stamp.toNSec()));
PutStr(o, h.frame_id);
}
void GetHeader(Reader* r, Header* h) {
h->seq = r->U32();
h->stamp = UnixTime::fromNSec(static_cast<int64_t>(r->U64()));
h->frame_id = r->Str();
}
} // namespace
const char* VsrStreamName(VsrStream s) {
switch (s) {
case VsrStream::kScanRaw: return "scan_raw";
case VsrStream::kImu: return "imu";
case VsrStream::kBaro: return "baro";
case VsrStream::kEncoder: return "encoder";
case VsrStream::kDepth: return "depth";
case VsrStream::kInfra1: return "infra1";
case VsrStream::kInfra2: return "infra2";
case VsrStream::kCameraInfo: return "camera_info";
case VsrStream::kCmdVel: return "cmd_vel";
case VsrStream::kEvent: return "event";
case VsrStream::kUltrasonic: return "ultrasonic";
case VsrStream::kBumper: return "bumper";
}
return "?";
}
// --- LaserScan -------------------------------------------------------------
void EncodeScanPayload(const LaserScan& s, std::string* o) {
PutHeader(o, s.header);
PutF32(o, s.angle_min);
PutF32(o, s.angle_max);
PutF32(o, s.angle_increment);
PutF32(o, s.time_increment);
PutF32(o, s.scan_time);
PutF32(o, s.range_min);
PutF32(o, s.range_max);
PutU32(o, static_cast<uint32_t>(s.ranges.size()));
// float32 tho, KHONG luong tu hoa: day la ban ghi de chay lai thuat toan,
// khong phai de hien thi. Mat mat lam tron o day se lam replay khong con
// tat dinh so voi live.
for (const float r : s.ranges) PutF32(o, r);
PutU32(o, static_cast<uint32_t>(s.intensities.size()));
for (const float v : s.intensities) PutF32(o, v);
}
bool DecodeScanPayload(const std::string& buf, LaserScan* s) {
Reader r(buf);
GetHeader(&r, &s->header);
s->angle_min = r.F32();
s->angle_max = r.F32();
s->angle_increment = r.F32();
s->time_increment = r.F32();
s->scan_time = r.F32();
s->range_min = r.F32();
s->range_max = r.F32();
const uint32_t n = r.U32();
if (!r.ok || !r.Need(static_cast<size_t>(n) * 4)) return false;
s->ranges.resize(n);
for (uint32_t i = 0; i < n; ++i) s->ranges[i] = r.F32();
const uint32_t m = r.U32();
if (!r.ok || !r.Need(static_cast<size_t>(m) * 4)) return false;
s->intensities.resize(m);
for (uint32_t i = 0; i < m; ++i) s->intensities[i] = r.F32();
return r.ok;
}
// --- Imu -------------------------------------------------------------------
void EncodeImuPayload(const Imu& v, std::string* o) {
PutHeader(o, v.header);
PutF64(o, v.angular_velocity.x);
PutF64(o, v.angular_velocity.y);
PutF64(o, v.angular_velocity.z);
PutF64(o, v.linear_acceleration.x);
PutF64(o, v.linear_acceleration.y);
PutF64(o, v.linear_acceleration.z);
for (int i = 0; i < 9; ++i) PutF64(o, v.angular_velocity_covariance[i]);
for (int i = 0; i < 9; ++i) PutF64(o, v.linear_acceleration_covariance[i]);
}
bool DecodeImuPayload(const std::string& buf, Imu* v) {
Reader r(buf);
GetHeader(&r, &v->header);
v->angular_velocity.x = r.F64();
v->angular_velocity.y = r.F64();
v->angular_velocity.z = r.F64();
v->linear_acceleration.x = r.F64();
v->linear_acceleration.y = r.F64();
v->linear_acceleration.z = r.F64();
for (int i = 0; i < 9; ++i) v->angular_velocity_covariance[i] = r.F64();
for (int i = 0; i < 9; ++i) v->linear_acceleration_covariance[i] = r.F64();
// D410 khong co IMU tich hop va MCU khong gui orientation -> danh dau
// "khong co orientation" theo dung quy uoc sensor_msgs.
v->orientation_covariance[0] = -1.0;
return r.ok;
}
// --- Encoder ---------------------------------------------------------------
void EncodeUltrasonicPayload(const double* range, size_t count, std::string* o) {
PutU32(o, static_cast<uint32_t>(count));
// f64 chu khong f32: inf va NaN phai di qua nguyen ven. Ba ngu nghia cua
// mot lan doc sieu am (huu han / inf / NaN) la thong tin an toan, khong
// phai chi tiet lam tron duoc.
for (size_t i = 0; i < count; ++i) PutF64(o, range[i]);
}
bool DecodeUltrasonicPayload(const std::string& buf, double* range, size_t* count,
size_t max_count) {
Reader r(buf);
const uint32_t n = r.U32();
if (!r.ok || n > max_count) return false;
for (uint32_t i = 0; i < n; ++i) range[i] = r.F64();
*count = n;
return r.ok;
}
void EncodeBumperPayload(uint32_t mask, std::string* o) { PutU32(o, mask); }
bool DecodeBumperPayload(const std::string& buf, uint32_t* mask) {
Reader r(buf);
*mask = r.U32();
return r.ok;
}
void EncodeEncoderPayload(double l, double rr, std::string* o) {
PutF64(o, l);
PutF64(o, rr);
}
bool DecodeEncoderPayload(const std::string& buf, double* l, double* rr) {
Reader r(buf);
*l = r.F64();
*rr = r.F64();
return r.ok;
}
// --- Baro ------------------------------------------------------------------
void EncodeBaroPayload(const FluidPressure& p, const Temperature& t, std::string* o) {
PutHeader(o, p.header);
PutF64(o, p.fluid_pressure);
PutF64(o, p.variance);
PutF64(o, t.temperature);
PutF64(o, t.variance);
}
bool DecodeBaroPayload(const std::string& buf, FluidPressure* p, Temperature* t) {
Reader r(buf);
GetHeader(&r, &p->header);
p->fluid_pressure = r.F64();
p->variance = r.F64();
t->header = p->header;
t->temperature = r.F64();
t->variance = r.F64();
return r.ok;
}
// --- Twist -----------------------------------------------------------------
void EncodeTwistPayload(const Twist& t, std::string* o) {
PutF64(o, t.linear.x);
PutF64(o, t.linear.y);
PutF64(o, t.linear.z);
PutF64(o, t.angular.x);
PutF64(o, t.angular.y);
PutF64(o, t.angular.z);
}
bool DecodeTwistPayload(const std::string& buf, Twist* t) {
Reader r(buf);
t->linear.x = r.F64();
t->linear.y = r.F64();
t->linear.z = r.F64();
t->angular.x = r.F64();
t->angular.y = r.F64();
t->angular.z = r.F64();
return r.ok;
}
// --- CameraInfo ------------------------------------------------------------
void EncodeCameraInfoPayload(const CameraInfo& c, std::string* o) {
PutHeader(o, c.header);
PutU32(o, c.width);
PutU32(o, c.height);
for (int i = 0; i < 9; ++i) PutF64(o, c.k[i]);
for (int i = 0; i < 5; ++i) PutF64(o, c.d[i]);
PutU32(o, c.binning_x);
PutU32(o, c.binning_y);
}
bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* c) {
Reader r(buf);
GetHeader(&r, &c->header);
c->width = r.U32();
c->height = r.U32();
for (int i = 0; i < 9; ++i) c->k[i] = r.F64();
for (int i = 0; i < 5; ++i) c->d[i] = r.F64();
c->binning_x = r.U32();
c->binning_y = r.U32();
if (c->binning_x == 0) c->binning_x = 1;
if (c->binning_y == 0) c->binning_y = 1;
return r.ok;
}
// --- Image -----------------------------------------------------------------
void EncodeImagePayload(const Image& img, std::string* o) {
PutHeader(o, img.header);
PutU32(o, img.width);
PutU32(o, img.height);
PutU32(o, img.step);
PutU8(o, static_cast<uint8_t>(img.format));
PutU16(o, 0); // reserved, giu can chinh
PutF32(o, img.depth_scale);
const uint32_t n = static_cast<uint32_t>(img.size_bytes());
PutU32(o, n);
if (img.data != nullptr && n > 0) {
o->append(reinterpret_cast<const char*>(img.data), n);
}
}
bool DecodeImagePayload(const std::string& buf, Image* img,
std::vector<uint8_t>* storage) {
Reader r(buf);
GetHeader(&r, &img->header);
img->width = r.U32();
img->height = r.U32();
img->step = r.U32();
img->format = static_cast<PixelFormat>(r.U8());
r.U16();
img->depth_scale = r.F32();
const uint32_t n = r.U32();
if (!r.ok || !r.Need(n)) return false;
// Image khong so huu bo nho (no tro vao buffer cua librealsense khi chay
// that). Khi replay thi `storage` dong vai tro do, va goi phai giu storage
// song it nhat bang Image.
storage->assign(buf.begin() + static_cast<long>(r.o),
buf.begin() + static_cast<long>(r.o) + static_cast<long>(n));
img->data = storage->data();
return true;
}
// --- crc32 -----------------------------------------------------------------
uint32_t Crc32(const void* data, size_t len, uint32_t seed) {
static uint32_t table[256];
static bool init = false;
if (!init) {
for (uint32_t i = 0; i < 256; ++i) {
uint32_t c = i;
for (int k = 0; k < 8; ++k) c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
table[i] = c;
}
init = true;
}
uint32_t c = seed ^ 0xFFFFFFFFu;
const uint8_t* p = static_cast<const uint8_t*>(data);
for (size_t i = 0; i < len; ++i) c = table[(c ^ p[i]) & 0xFF] ^ (c >> 8);
return c ^ 0xFFFFFFFFu;
}
} // namespace vslam

View File

@@ -0,0 +1,326 @@
#include "vslam/record_io.h"
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <mutex>
#include <thread>
#include "vslam/log.h"
namespace vslam {
namespace {
void PutU32(std::string* o, uint32_t v) {
for (int i = 0; i < 4; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutU64(std::string* o, uint64_t v) {
for (int i = 0; i < 8; ++i) o->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
uint32_t GetU32(const char* p) {
uint32_t v = 0;
for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(static_cast<uint8_t>(p[i])) << (8 * i);
return v;
}
uint64_t GetU64(const char* p) {
uint64_t v = 0;
for (int i = 0; i < 8; ++i) v |= static_cast<uint64_t>(static_cast<uint8_t>(p[i])) << (8 * i);
return v;
}
} // namespace
// ---------------------------------------------------------------------------
// Writer
// ---------------------------------------------------------------------------
struct RecordWriter::Impl {
RecordWriterConfig cfg;
std::ofstream file;
mutable std::mutex mu;
std::condition_variable cv;
std::deque<std::string> queue; // chunk da dong goi san
size_t queue_bytes = 0;
bool running = false;
std::thread thread;
mutable std::mutex stats_mu;
RecordWriterStats stats;
// Dem drop giua hai lan ghi su kien, de mot dot drop dai khong sinh hang
// nghin dong su kien.
uint64_t pending_drops = 0;
UnixTime last_drop_stamp;
explicit Impl(RecordWriterConfig c) : cfg(std::move(c)) {}
void Loop() {
while (true) {
std::string chunk;
{
std::unique_lock<std::mutex> lk(mu);
cv.wait(lk, [this] { return !queue.empty() || !running; });
if (queue.empty()) {
if (!running) return;
continue;
}
chunk = std::move(queue.front());
queue.pop_front();
queue_bytes -= chunk.size();
}
file.write(chunk.data(), static_cast<std::streamsize>(chunk.size()));
std::lock_guard<std::mutex> lk(stats_mu);
if (!file) {
stats.write_errors++;
} else {
stats.chunks_written++;
stats.bytes_written += chunk.size();
}
}
}
};
RecordWriter::RecordWriter(RecordWriterConfig cfg)
: impl_(std::make_unique<Impl>(std::move(cfg))) {}
RecordWriter::~RecordWriter() { Close(); }
StatusResponse RecordWriter::Open() {
if (impl_->running) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da mo roi");
}
impl_->file.open(impl_->cfg.path, std::ios::binary | std::ios::trunc);
if (!impl_->file) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong mo duoc de ghi: " + impl_->cfg.path);
}
std::string header;
header.append(kVsrMagic, sizeof(kVsrMagic));
PutU32(&header, kVsrVersion);
PutU32(&header, 0); // reserved
PutU64(&header, static_cast<uint64_t>(UnixTime::now().toNSec()));
PutU32(&header, static_cast<uint32_t>(impl_->cfg.config_json.size()));
header.append(impl_->cfg.config_json);
impl_->file.write(header.data(), static_cast<std::streamsize>(header.size()));
if (!impl_->file) {
return StatusResponse::Error(StatusCode::kInternal, "khong ghi duoc header");
}
impl_->running = true;
impl_->thread = std::thread([this] { impl_->Loop(); });
VSLAM_INFO("record: dang ghi " << impl_->cfg.path);
return StatusResponse::Ok();
}
void RecordWriter::Close() {
if (!impl_ || !impl_->running) return;
{
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->running = false;
}
impl_->cv.notify_all();
if (impl_->thread.joinable()) impl_->thread.join();
impl_->file.flush();
impl_->file.close();
const RecordWriterStats s = Stats();
VSLAM_INFO("record: dong. " << s.chunks_written << " chunk, "
<< s.bytes_written / 1024 / 1024 << " MB, " << s.chunks_dropped
<< " chunk bi drop");
}
bool RecordWriter::Write(VsrStream stream, UnixTime stamp, std::string payload) {
const uint32_t crc = Crc32(payload.data(), payload.size());
std::string chunk;
chunk.reserve(kVsrChunkHeaderSize + payload.size() + 4);
PutU32(&chunk, kVsrChunkMagic);
chunk.push_back(static_cast<char>(stream));
chunk.push_back(static_cast<char>(0)); // flags: chua nen
chunk.push_back(0);
chunk.push_back(0); // reserved
PutU64(&chunk, static_cast<uint64_t>(stamp.toNSec()));
PutU32(&chunk, static_cast<uint32_t>(payload.size()));
chunk.append(payload);
PutU32(&chunk, crc);
{
std::lock_guard<std::mutex> lk(impl_->mu);
if (!impl_->running) return false;
// DROP CHU KHONG CHAN. Mot the USB cham khong duoc phep lam luong
// lidar_rx dung lai -- do la ca ly do writer nam o luong rieng.
if (impl_->queue_bytes + chunk.size() > impl_->cfg.max_queue_bytes) {
impl_->pending_drops++;
impl_->last_drop_stamp = stamp;
std::lock_guard<std::mutex> slk(impl_->stats_mu);
impl_->stats.chunks_dropped++;
return false;
}
// Da tung drop -> ghi mot su kien tom tat TRUOC chunk nay, de ban ghi tu
// mo ta duoc lo hong cua chinh no.
if (impl_->pending_drops > 0) {
const uint64_t n = impl_->pending_drops;
impl_->pending_drops = 0;
std::string ev = "{\"t\":\"drop\",\"chunks\":" + std::to_string(n) + "}";
std::string ev_chunk;
const uint32_t ev_crc = Crc32(ev.data(), ev.size());
PutU32(&ev_chunk, kVsrChunkMagic);
ev_chunk.push_back(static_cast<char>(VsrStream::kEvent));
ev_chunk.push_back(0);
ev_chunk.push_back(0);
ev_chunk.push_back(0);
PutU64(&ev_chunk, static_cast<uint64_t>(impl_->last_drop_stamp.toNSec()));
PutU32(&ev_chunk, static_cast<uint32_t>(ev.size()));
ev_chunk.append(ev);
PutU32(&ev_chunk, ev_crc);
impl_->queue_bytes += ev_chunk.size();
impl_->queue.push_back(std::move(ev_chunk));
}
impl_->queue_bytes += chunk.size();
impl_->queue.push_back(std::move(chunk));
{
std::lock_guard<std::mutex> slk(impl_->stats_mu);
impl_->stats.queue_bytes = impl_->queue_bytes;
}
}
impl_->cv.notify_one();
return true;
}
void RecordWriter::WriteEvent(UnixTime stamp, const std::string& json) {
Write(VsrStream::kEvent, stamp, json);
}
RecordWriterStats RecordWriter::Stats() const {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
return impl_->stats;
}
// ---------------------------------------------------------------------------
// Reader
// ---------------------------------------------------------------------------
struct RecordReader::Impl {
std::ifstream file;
RecordFileInfo info;
bool truncated = false;
uint64_t chunks = 0;
uint64_t bytes = 0;
};
RecordReader::RecordReader() : impl_(std::make_unique<Impl>()) {}
RecordReader::~RecordReader() = default;
StatusResponse RecordReader::Open(const std::string& path) {
impl_->file.open(path, std::ios::binary);
if (!impl_->file) {
return StatusResponse::Error(StatusCode::kNotFound, "khong mo duoc: " + path);
}
char fixed[kVsrHeaderFixedSize];
impl_->file.read(fixed, sizeof(fixed));
if (impl_->file.gcount() != static_cast<std::streamsize>(sizeof(fixed))) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "file qua ngan");
}
if (std::memcmp(fixed, kVsrMagic, sizeof(kVsrMagic)) != 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"khong phai file .vsr (sai magic)");
}
impl_->info.version = GetU32(fixed + 8);
if (impl_->info.version != kVsrVersion) {
// TU CHOI ro rang thay vi co doc. Doi schema lam moi file expected/*.json
// cu vo gia tri, va doc nham mot phien ban khac chi sinh du lieu vo nghia.
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"phien ban .vsr khong khop: file la " + std::to_string(impl_->info.version) +
", chuong trinh doc duoc " + std::to_string(kVsrVersion));
}
impl_->info.start_stamp = UnixTime::fromNSec(static_cast<int64_t>(GetU64(fixed + 16)));
const uint32_t cfg_len = GetU32(fixed + 24);
if (cfg_len > 0) {
impl_->info.config_json.resize(cfg_len);
impl_->file.read(&impl_->info.config_json[0], cfg_len);
if (impl_->file.gcount() != static_cast<std::streamsize>(cfg_len)) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "header cut");
}
}
return StatusResponse::Ok();
}
void RecordReader::Close() { impl_->file.close(); }
const RecordFileInfo& RecordReader::info() const { return impl_->info; }
bool RecordReader::Next(VsrChunkHeader* header, std::string* payload) {
char hdr[kVsrChunkHeaderSize];
impl_->file.read(hdr, sizeof(hdr));
const std::streamsize got = impl_->file.gcount();
if (got == 0) return false; // het file binh thuong
if (got != static_cast<std::streamsize>(sizeof(hdr))) {
impl_->truncated = true;
return false;
}
if (GetU32(hdr) != kVsrChunkMagic) {
impl_->truncated = true;
return false;
}
header->stream = static_cast<VsrStream>(static_cast<uint8_t>(hdr[4]));
header->compressed = (static_cast<uint8_t>(hdr[5]) & 0x01) != 0;
header->stamp_ns = GetU64(hdr + 8);
header->payload_len = GetU32(hdr + 16);
payload->resize(header->payload_len);
if (header->payload_len > 0) {
impl_->file.read(&(*payload)[0], header->payload_len);
if (impl_->file.gcount() != static_cast<std::streamsize>(header->payload_len)) {
impl_->truncated = true;
return false;
}
}
char crc_buf[4];
impl_->file.read(crc_buf, 4);
if (impl_->file.gcount() != 4) {
impl_->truncated = true;
return false;
}
const uint32_t want = GetU32(crc_buf);
const uint32_t got_crc = Crc32(payload->data(), payload->size());
if (want != got_crc) {
// DUNG LAI, khong bo qua de doc tiep. Mot the USB rut ra giua chung lam
// file hong tu diem nao do tro di; doc tiep chi cho ra rac, va rac do se
// di vao thuat toan ma khong ai biet.
VSLAM_ERROR("record: CRC sai o chunk " << impl_->chunks << " (stream "
<< VsrStreamName(header->stream) << "), dung doc");
impl_->truncated = true;
return false;
}
impl_->chunks++;
impl_->bytes += kVsrChunkHeaderSize + header->payload_len + 4;
return true;
}
bool RecordReader::truncated() const { return impl_->truncated; }
uint64_t RecordReader::chunks_read() const { return impl_->chunks; }
uint64_t RecordReader::bytes_read() const { return impl_->bytes; }
} // namespace vslam

View File

@@ -0,0 +1,422 @@
#include <chrono>
#include <thread>
#include "vslam/replay_source.h"
#include <atomic>
#include <memory>
#include <mutex>
#include <vector>
#include "vslam/log.h"
#include "vslam/record_io.h"
#include "vslam/scan_sanitizer.h"
namespace vslam {
namespace {
// Bon lop duoi day la interface driver THAT, chi khac o cho nguon du lieu la
// file chu khong phai socket. vslam_node khong phan biet duoc -- do la muc
// dich.
//
// Chung khong tu chay: ReplaySource::Run() day du lieu vao chung. Open()/
// Close() chi bat/tat co, vi vong doi thuc do ReplaySource quan.
class ReplayLidar : public LidarInterface {
public:
void SetCallback(ScanCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void Push(LaserScanPtr scan) {
if (!open_ || !cb_) return;
stats_.frames++;
stats_.connected = true;
cb_(std::move(scan));
}
private:
ScanCallback cb_;
bool open_ = false;
DriverStats stats_;
};
class ReplayCamera : public CameraInterface {
public:
void SetCallback(FrameCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void Push(const CameraFrame& f) {
if (!open_ || !cb_) return;
stats_.frames++;
stats_.connected = true;
cb_(f);
}
private:
FrameCallback cb_;
bool open_ = false;
DriverStats stats_;
};
class ReplayMcu : public McuInterface {
public:
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
void SetBaroCallback(BaroCallback cb) override { baro_cb_ = std::move(cb); }
void SetUltrasonicCallback(UltrasonicCallback cb) override { us_cb_ = std::move(cb); }
void SetBumperCallback(BumperCallback cb) override { bumper_cb_ = std::move(cb); }
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void PushImu(ImuPtr imu) {
if (!open_ || !imu_cb_) return;
stats_.frames++;
stats_.connected = true;
imu_cb_(std::move(imu));
}
void PushBaro(const FluidPressure& p, const Temperature& t) {
if (!open_ || !baro_cb_) return;
baro_cb_(p, t);
}
private:
ImuCallback imu_cb_;
BaroCallback baro_cb_;
UltrasonicCallback us_cb_;
BumperCallback bumper_cb_;
public:
void PushUltrasonic(const UltrasonicReading& u) { if (us_cb_) us_cb_(u); }
void PushBumper(const BumperReading& b) { if (bumper_cb_) bumper_cb_(b); }
private:
bool open_ = false;
DriverStats stats_;
};
class ReplayBase : public BaseInterface {
public:
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
// Lenh motor khi replay di vao hu khong -- KHONG co banh xe nao quay.
// Dem lai de bai regression kiem duoc rang he thong DA ra lenh dung, du
// khong co gi de thuc thi.
void SetVelocity(double linear, double angular) override {
std::lock_guard<std::mutex> lk(mu_);
last_linear_ = linear;
last_angular_ = angular;
cmds_++;
}
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
void Close() override { open_ = false; }
DriverStats Stats() const override { return stats_; }
void Push(const EncoderReading& e) {
if (!open_ || !cb_) return;
stats_.frames++;
stats_.connected = true;
cb_(e);
}
void LastCommand(double* lin, double* ang, uint64_t* n) const {
std::lock_guard<std::mutex> lk(mu_);
*lin = last_linear_;
*ang = last_angular_;
*n = cmds_;
}
private:
EncoderCallback cb_;
bool open_ = false;
DriverStats stats_;
mutable std::mutex mu_;
double last_linear_ = 0.0;
double last_angular_ = 0.0;
uint64_t cmds_ = 0;
};
} // namespace
// ---------------------------------------------------------------------------
struct ReplaySource::Impl {
ReplayConfig cfg;
RecordReader reader;
ReplayLidar lidar;
ReplayCamera camera;
ReplayMcu mcu;
ReplayBase base;
std::shared_ptr<ReplayClock> clock;
std::unique_ptr<ScanSanitizer> sanitizer;
std::atomic<bool> stop{false};
mutable std::mutex stats_mu;
Stats stats;
// Khung camera duoc rap tu nhieu chunk (depth, infra1, infra2, camera_info)
// roi phat mot lan khi thay chunk depth ke tiep hoac khi het file.
CameraFrame pending_frame;
bool have_pending = false;
std::vector<uint8_t> depth_storage;
std::vector<uint8_t> infra1_storage;
std::vector<uint8_t> infra2_storage;
CameraInfo last_info;
bool have_info = false;
explicit Impl(ReplayConfig c) : cfg(std::move(c)) {}
void FlushCameraFrame() {
if (!have_pending) return;
if (have_info) pending_frame.depth_info = last_info;
camera.Push(pending_frame);
{
std::lock_guard<std::mutex> lk(stats_mu);
stats.camera_frames++;
}
have_pending = false;
pending_frame = CameraFrame{};
}
};
ReplaySource::ReplaySource(ReplayConfig cfg)
: impl_(std::make_unique<Impl>(std::move(cfg))) {}
ReplaySource::~ReplaySource() { RequestStop(); }
StatusResponse ReplaySource::Open() {
const StatusResponse st = impl_->reader.Open(impl_->cfg.path);
if (!st.ok()) return st;
impl_->clock = MakeReplayClock(impl_->reader.info().start_stamp);
impl_->clock->SetSpeed(impl_->cfg.deterministic ? 0.0 : impl_->cfg.speed);
if (impl_->cfg.apply_sanitizer) {
try {
impl_->sanitizer = std::make_unique<ScanSanitizer>(impl_->cfg.sanitizer);
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
std::string("sanitizer: ") + e.what());
}
}
VSLAM_INFO("replay: mo " << impl_->cfg.path << ", bat dau tu "
<< impl_->reader.info().start_stamp.toString()
<< (impl_->cfg.deterministic ? " (che do tat dinh)" : ""));
return StatusResponse::Ok();
}
ClockPtr ReplaySource::clock() const { return impl_->clock; }
LidarInterface* ReplaySource::lidar() { return &impl_->lidar; }
CameraInterface* ReplaySource::camera() { return &impl_->camera; }
McuInterface* ReplaySource::mcu() { return &impl_->mcu; }
BaseInterface* ReplaySource::base() { return &impl_->base; }
const std::string& ReplaySource::recorded_config_json() const {
return impl_->reader.info().config_json;
}
void ReplaySource::RequestStop() { impl_->stop.store(true); }
void ReplaySource::Run() {
VsrChunkHeader h;
std::string payload;
const UnixTime file_start = impl_->reader.info().start_stamp;
UnixTime first_stamp;
bool have_first = false;
// Moc de dong bo thoi gian tuong khi phat theo thoi gian that.
bool have_play_origin = false;
std::chrono::steady_clock::time_point play_origin_wall;
UnixTime play_origin_stamp;
UnixTime last_stamp;
while (!impl_->stop.load() && impl_->reader.Next(&h, &payload)) {
const UnixTime stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
if (!have_first) {
first_stamp = stamp;
have_first = true;
// Dat dong ho ao theo chunk DAU TIEN, khong theo start_stamp cua header.
//
// start_stamp la thoi diem writer MO FILE, do dong ho tuong cua may ghi.
// No khong nhat thiet trung voi moc thoi gian cua du lieu: mot ban ghi
// chuyen doi tu nguon khac, hoac mot may co dong ho sai, se lech han.
// Neu lay theo header thi SetNow() tu choi lui va dong ho ao ket o thoi
// gian that -- moi phep timeout theo stamp sau do deu sai.
//
// allow_backward chi o DUNG lan dau nay.
impl_->clock->SetNow(stamp, /*allow_backward=*/true);
}
last_stamp = stamp;
// Cua so start/duration.
const double rel = SecondsBetween(stamp, first_stamp);
if (rel < impl_->cfg.start_sec) {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.skipped++;
continue;
}
if (impl_->cfg.duration_sec > 0.0 &&
rel > impl_->cfg.start_sec + impl_->cfg.duration_sec) {
break;
}
// Lai dong ho ao TRUOC khi day du lieu, de moi stage nhin thay thoi gian
// dung luc ban tin nay den.
impl_->clock->SetNow(stamp);
if (!impl_->cfg.deterministic && impl_->cfg.speed > 0.0) {
// Ngu cho toi khi thoi gian TUONG bat kip stamp cua chunk nay.
//
// ⚠️ Ban truoc viet `SleepUntil(Steady() + nanoseconds(0))` -- tuc la
// ngu KHONG giay nao. `speed` va `deterministic=false` khong co tac
// dung gi, va ban ghi luon chay het toc. Triong chung danh lua: ca
// duong ong van dung, chi la mot ban ghi 8 giay chay xong trong 0.4
// giay, va tren web UI thi no giong het nhu "replay bi treo o khung
// cuoi".
//
// Moc la chunk DAU TIEN duoc phat (sau cua so start_sec), khong phai
// chunk dau file: neu khong thi voi --start 60 no se ngu 60 giay truoc
// khi phat gi.
if (!have_play_origin) {
play_origin_wall = std::chrono::steady_clock::now();
play_origin_stamp = stamp;
have_play_origin = true;
}
const double elapsed = SecondsBetween(stamp, play_origin_stamp) /
impl_->cfg.speed;
const auto target =
play_origin_wall +
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(elapsed));
// Cho phep tut lai: neu may qua cham thi phat tiep ngay, khong don no
// thanh mot cu ngu bu.
if (target > std::chrono::steady_clock::now()) {
std::this_thread::sleep_until(target);
}
}
{
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.chunks++;
}
switch (h.stream) {
case VsrStream::kScanRaw: {
auto scan = std::make_shared<LaserScan>();
if (!DecodeScanPayload(payload, scan.get())) break;
// Ban ghi luu du lieu THO (truoc sanitizer) chinh la de cho nay: doi
// nguong sanitizer roi chay lai tren cung mot file.
if (impl_->sanitizer) impl_->sanitizer->Apply(scan.get());
impl_->lidar.Push(std::move(scan));
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.scans++;
break;
}
case VsrStream::kImu: {
auto imu = std::make_shared<Imu>();
if (!DecodeImuPayload(payload, imu.get())) break;
impl_->mcu.PushImu(std::move(imu));
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.imu++;
break;
}
case VsrStream::kBaro: {
FluidPressure p;
Temperature t;
if (!DecodeBaroPayload(payload, &p, &t)) break;
impl_->mcu.PushBaro(p, t);
break;
}
case VsrStream::kEncoder: {
EncoderReading e;
if (!DecodeEncoderPayload(payload, &e.left_rad, &e.right_rad)) break;
e.stamp = stamp;
e.valid = true;
impl_->base.Push(e);
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.encoder++;
break;
}
case VsrStream::kUltrasonic: {
UltrasonicReading u;
if (!DecodeUltrasonicPayload(payload, u.range, &u.count, 8)) break;
u.stamp = stamp;
impl_->mcu.PushUltrasonic(u);
break;
}
case VsrStream::kBumper: {
BumperReading b;
if (!DecodeBumperPayload(payload, &b.mask)) break;
b.stamp = stamp;
impl_->mcu.PushBumper(b);
break;
}
case VsrStream::kDepth: {
// Chunk depth moi = khung truoc da day du -> phat khung truoc.
impl_->FlushCameraFrame();
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->depth_storage)) break;
impl_->pending_frame.header = img->header;
impl_->pending_frame.depth = img;
impl_->have_pending = true;
break;
}
case VsrStream::kInfra1: {
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->infra1_storage)) break;
impl_->pending_frame.infra1 = img;
break;
}
case VsrStream::kInfra2: {
auto img = std::make_shared<Image>();
if (!DecodeImagePayload(payload, img.get(), &impl_->infra2_storage)) break;
impl_->pending_frame.infra2 = img;
break;
}
case VsrStream::kCameraInfo: {
if (DecodeCameraInfoPayload(payload, &impl_->last_info)) {
impl_->have_info = true;
}
break;
}
case VsrStream::kCmdVel:
// Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra.
// Replay khong tu dong ap chung: viec do do wiring quyet dinh.
break;
case VsrStream::kEvent: {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.events++;
VSLAM_DEBUG("replay: su kien tai " << stamp.toString() << ": " << payload);
break;
}
}
}
impl_->FlushCameraFrame();
{
std::lock_guard<std::mutex> lk(impl_->stats_mu);
impl_->stats.truncated = impl_->reader.truncated();
if (have_first) impl_->stats.duration_sec = SecondsBetween(last_stamp, first_stamp);
}
const Stats s = stats();
VSLAM_INFO("replay: xong. " << s.chunks << " chunk trong " << s.duration_sec
<< " s -- " << s.scans << " scan, " << s.imu << " imu, "
<< s.encoder << " encoder, " << s.camera_frames << " khung camera"
<< (s.truncated ? " [FILE CUT GIUA CHUNG]" : ""));
(void)file_start;
}
ReplaySource::Stats ReplaySource::stats() const {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
return impl_->stats;
}
} // namespace vslam

View File

@@ -0,0 +1,125 @@
#include "vslam/scan_sanitizer.h"
#include <cmath>
#include <limits>
#include <stdexcept>
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
void ScanSanitizer::Validate(const ScanSanitizerConfig& cfg) {
// Kiem o day chu khong im lang roi ve default. Mot LiDAR cau hinh sai la
// mot robot dam vao tuong, va `range_min = 0` chinh la bug cua driver goc
// ma lop nay ton tai de sua.
if (!(cfg.range_min > 0.0)) {
throw std::invalid_argument("scan_sanitizer: range_min phai > 0 (dang la " +
std::to_string(cfg.range_min) + ")");
}
if (!(cfg.range_max > cfg.range_min)) {
throw std::invalid_argument("scan_sanitizer: range_max phai > range_min");
}
if (cfg.zero_is != "nan" && cfg.zero_is != "inf") {
throw std::invalid_argument("scan_sanitizer: zero_is phai la \"nan\" hoac \"inf\"");
}
for (const auto& m : cfg.sector_masks) {
if (m.upper_rad < m.lower_rad) {
throw std::invalid_argument("scan_sanitizer: sector mask co upper < lower");
}
}
}
ScanSanitizer::ScanSanitizer(ScanSanitizerConfig cfg) : cfg_(std::move(cfg)) {
Validate(cfg_);
zero_to_inf_ = (cfg_.zero_is == "inf");
VSLAM_INFO("scan_sanitizer: ep header ve [" << cfg_.range_min << ", "
<< cfg_.range_max << "] m, 0.0 -> " << (zero_to_inf_ ? "inf" : "NaN")
<< ", " << cfg_.sector_masks.size() << " quat bi cat"
<< (cfg_.angle_offset_rad != 0.0
? ", offset " + std::to_string(cfg_.angle_offset_rad * 180.0 / 3.14159265358979323846) + " do"
: ""));
}
bool ScanSanitizer::InMaskedSector(double angle) const {
for (const auto& m : cfg_.sector_masks) {
if (angle >= m.lower_rad && angle <= m.upper_rad) return true;
}
return false;
}
void ScanSanitizer::Apply(LaserScan* scan) {
if (scan == nullptr || scan->ranges.empty()) return;
const float range_min = static_cast<float>(cfg_.range_min);
const float range_max = static_cast<float>(cfg_.range_max);
// 1. Ep header ve gia tri that cua thiet bi.
scan->range_min = range_min;
scan->range_max = range_max;
// 2. Bo phep chia 2 thua cua driver. Bat ky ai deskew theo truong nay ma
// doc gia tri goc thi chi bu duoc mot nua.
if (cfg_.fix_time_increment) {
scan->time_increment = scan->scan_time / static_cast<float>(scan->ranges.size());
}
// 3. Xoay neu huong 0 do cua LiDAR khong trung truc x cua robot.
if (cfg_.angle_offset_rad != 0.0) {
scan->angle_min += static_cast<float>(cfg_.angle_offset_rad);
scan->angle_max += static_cast<float>(cfg_.angle_offset_rad);
}
const float nan_v = std::numeric_limits<float>::quiet_NaN();
const float inf_v = std::numeric_limits<float>::infinity();
const float zero_v = zero_to_inf_ ? inf_v : nan_v;
const float blank_v = blank_value();
stats_.scans++;
stats_.rays_total += scan->ranges.size();
for (size_t i = 0; i < scan->ranges.size(); ++i) {
// Sector mask ap TRUOC moi thu khac: mot tia bi than robot che thi gia
// tri do duoc cua no khong co y nghia gi ca.
const double angle =
static_cast<double>(scan->angle_min) + static_cast<double>(i) * scan->angle_increment;
if (InMaskedSector(NormalizeAngle(angle))) {
scan->ranges[i] = blank_v;
stats_.rays_blanked++;
continue;
}
const float r = scan->ranges[i];
if (std::isnan(r)) continue; // da la "khong do duoc"
if (r <= 0.0f) {
// 0.0 = khong do duoc HOAC be mat den nuot het xung. Xem khoi comment
// dau header: map sang NaN la hong ve phia an toan.
scan->ranges[i] = zero_v;
stats_.rays_zero++;
continue;
}
if (r < range_min) {
// Gan hon nguong tin cay cua thiet bi. KHONG map sang inf: cho nay co
// the dang co vat that, chi la qua gan de do.
scan->ranges[i] = nan_v;
stats_.rays_below_min++;
continue;
}
if (r > range_max) {
// Ke ca inf san co. "Khong co gi trong tam" -> giu inf de consumer
// duoc phep clear free space.
scan->ranges[i] = inf_v;
stats_.rays_above_max++;
continue;
}
stats_.rays_valid++;
}
}
} // namespace vslam

View File

@@ -0,0 +1,14 @@
# Odometry banh xe + EKF SE(2).
#
# KHONG them dep ngoai nao: Eigen da den qua vslam_common. Do la co y -- lib
# nay phai build duoc truoc khi co PCL, OpenCV hay RTAB-Map, de P3 chay som.
vslam_add_library(vslam_odometry
PUBLIC_HDRS
wheel_odometry.h
ekf_se2.h
PUBLIC_DEPS
vslam_common
FIND_DEPS
vslam_common
)

View File

@@ -0,0 +1,124 @@
#ifndef VSLAM_EKF_SE2_H
#define VSLAM_EKF_SE2_H
// EKF cho pose SE(2). Thay robot_localization/ekf_localization_node.
//
// ================== VI SAO CHI 5 TRANG THAI ==================
// robot_localization mang 15 trang thai. Cau hinh that trong ekf_odom.yaml
// dat two_d_mode=true (khoa z/roll/pitch va dao ham cua chung) va chi bat
// DUNG BA phep do:
// odom0 -> vx (chi so 6), vyaw (chi so 11)
// imu0 -> vyaw (chi so 11)
// Nghia la 10/15 trang thai khong bao gio duoc quan sat va chi bi mang theo.
//
// O day giu dung 5 trang thai co that: [x, y, yaw, vx, vyaw].
//
// ================== HAI QUYET DINH BE NGUYEN TU BAN CU ==================
//
// 1. FUSE VAN TOC, KHONG FUSE POSE TUYET DOI.
// Tich phan pose hai lan trong filter (mot lan o wheel_odom, mot lan nua
// trong EKF) lam sai so cong don nhanh hon han. wheel_odom van xuat pose
// de hien thi, nhung EKF chi an twist.
//
// 2. KHONG FUSE GIA TOC TUYEN TINH tu IMU.
// Tren robot banh, accel nhieu manh do rung (san gach + banh cung) va co
// bias troi. Dua vao thuong lam ket qua TE HON chu khong tot hon. Chi lay
// gyro Z.
//
// ================== Z, ROLL, PITCH DI DAU ==================
// Pose la SE(2): z gia dinh 0, roll/pitch duoc DO tu IMU chu khong bao gio
// uoc luong. Chung khong nam trong filter nay. GravityAlign lo phan do.
#include <cstdint>
#include <memory>
#include <string>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct EkfSe2Config {
double rate_hz = 50.0;
// Khong nhan phep do nao trong bao lau thi coi la khong lanh manh.
double sensor_timeout = 0.2;
// Nhieu qua trinh, duong cheo. Lay tu process_noise_covariance cua
// ekf_odom.yaml tai cac chi so tuong ung:
// x=0 y=1 yaw=5 vx=6 vyaw=11
// MOI gia tri o day la doan tu datasheet, cho hieu chuan that. Dung tin
// chung nhu so do.
double q_x = 0.05;
double q_y = 0.05;
double q_yaw = 0.06;
double q_vx = 0.025;
double q_vyaw = 0.02;
// Hiep phuong sai ban dau.
double p0_pose = 1e-3;
double p0_vel = 1e-2;
// Bo phep do lech qua nhieu so voi du doan (kiem Mahalanobis).
// 0 = tat. Gia tri ~5 nghia la bo diem lech qua 5 sigma.
//
// Bat cai nay chi an toan KHI covariance dau vao dung. Voi bug yaw-rate cu
// (thieu 2 bac, xem wheel_odometry.cc) thi moi phep do deu trong nhu 11
// sigma va cong nay se bo HET -- nen mac dinh la TAT.
double mahalanobis_threshold = 0.0;
};
struct EkfSe2Stats {
uint64_t predicts = 0;
uint64_t odom_updates = 0;
uint64_t imu_updates = 0;
uint64_t rejected_outliers = 0;
uint64_t time_resets = 0;
double last_mahalanobis = 0.0;
};
class EkfSe2 {
public:
explicit EkfSe2(EkfSe2Config cfg = EkfSe2Config());
~EkfSe2();
EkfSe2(const EkfSe2&) = delete;
EkfSe2& operator=(const EkfSe2&) = delete;
// Day trang thai toi `now`. An toan goi nhieu lan.
void Predict(UnixTime now);
// Van toc tu encoder. `var_*` lay tu twist.covariance cua Odometry --
// day chinh la cho wheel_odom bao "dang truot, dung tin toi".
void UpdateOdomTwist(UnixTime stamp, double vx, double vyaw, double var_vx,
double var_vyaw);
// Van toc goc tu gyro Z.
void UpdateImuYawRate(UnixTime stamp, double vyaw, double var);
Pose2D pose() const;
double vx() const;
double vyaw() const;
// Odometry day du, gom ca covariance -- de xuat ra web va cho SLAM.
Odometry State(const std::string& odom_frame, const std::string& base_frame) const;
// Canh odom -> base_footprint. EkfSe2 la NGUOI GHI DUY NHAT cua canh nay.
Transform OdomToBase() const;
// false neu chua nhan phep do nao trong `sensor_timeout`.
bool Healthy(UnixTime now) const;
void SetPose(const Pose2D& p);
void Reset();
EkfSe2Stats stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_EKF_SE2_H

View File

@@ -0,0 +1,113 @@
#ifndef VSLAM_WHEEL_ODOMETRY_H
#define VSLAM_WHEEL_ODOMETRY_H
// Odometry banh xe + phat hien truot.
//
// Port tu robot_drivers/src/wheel_odom_node.cpp cua vSLAM_ws.
// TOAN BO mo hinh covariance duoc BE NGUYEN: no da duoc chinh bang so do thuc
// tren robot that, va cac con so trong comment o wheel_odometry.cc la do
// duoc chu khong phai doan.
//
// ================== VI SAO CAN PHAT HIEN TRUOT ==================
// San nha hang co nuoc va dau mo. Banh truot thi encoder NOI DOI: no bao robot
// da di, thuc te robot dung yen hoac truot ngang.
//
// Gyro Z khong bi anh huong boi truot banh. So hai nguon:
// omega_encoder = (v_phai - v_trai) / wheel_separation
// omega_gyro = imu.angular_velocity.z
// Lech nhieu => dang truot => NANG covariance de back-end tu dong tin encoder
// it di. Khong vut bo du lieu, chi ha do tin cay.
//
// ================== KHONG PHAT TF ==================
// Lop nay KHONG ghi canh odom->base_footprint. Viec do la cua EkfSe2, noi
// encoder va IMU duoc fuse dung cach. Moi canh TF co dung mot nguoi ghi.
#include <cstdint>
#include <string>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct WheelOdometryConfig {
// Hinh hoc. PHAI khop robot.yaml -- day la gia tri duy nhat, khong con ban
// sao trong URDF nua.
double wheel_radius = 0.075;
double wheel_separation = 0.36;
// Truot: lech omega vuot nguong nay thi coi la dang truot.
double slip_omega_threshold = 0.15;
double slip_cov_multiplier = 100.0;
// IMU cu hon nguong nay thi coi nhu khong co gyro.
double imu_timeout = 0.5;
// Sigma co ban, nhan voi QUANG DUONG (khong phai thoi gian).
double sigma_x = 0.02;
double sigma_y = 0.02;
double sigma_yaw = 0.02;
// Xem khoi comment lon trong wheel_odometry.cc -- hai gia tri nay la ket
// qua cua mot bug da do duoc, khong phai tham so tuy chinh.
double yaw_rate_sigma_floor = 0.02;
double yaw_rate_sigma_no_imu = 0.50;
std::string odom_frame = "odom";
std::string base_frame = "base_footprint";
};
struct WheelOdometryStats {
uint64_t updates = 0;
uint64_t slip_events = 0;
uint64_t time_resets = 0; // dt <= 0: reset sim hoac replay nhay lui
uint64_t no_imu_updates = 0; // chay "mu", khong phat hien duoc truot
double last_slip_metric = 0.0;
double total_distance = 0.0;
};
class WheelOdometry {
public:
explicit WheelOdometry(WheelOdometryConfig cfg);
// Gyro Z tu IMU. Goi truoc Update() de phat hien truot hoat dong.
void FeedGyroZ(UnixTime stamp, double wz);
// left_rad / right_rad: goc quay TICH LUY cua tung banh.
//
// Tra false khi chua du du lieu de tich phan (mau dau tien, hoac dt <= 0).
// Khi do `out` khong duoc ghi.
bool Update(UnixTime stamp, double left_rad, double right_rad, Odometry* out);
// |omega_encoder - gyro_z| cua lan cap nhat gan nhat.
double slip_metric() const { return slip_metric_; }
bool slipping() const { return slipping_; }
Pose2D pose() const { return Pose2D{x_, y_, theta_}; }
void SetPose(const Pose2D& p);
void Reset();
const WheelOdometryStats& stats() const { return stats_; }
private:
WheelOdometryConfig cfg_;
bool initialized_ = false;
double prev_pos_l_ = 0.0, prev_pos_r_ = 0.0;
UnixTime prev_time_;
double x_ = 0.0, y_ = 0.0, theta_ = 0.0;
bool have_imu_ = false;
double gyro_z_ = 0.0;
UnixTime last_imu_time_;
double slip_metric_ = 0.0;
bool slipping_ = false;
WheelOdometryStats stats_;
};
} // namespace vslam
#endif // VSLAM_WHEEL_ODOMETRY_H

View File

@@ -0,0 +1,255 @@
#include "vslam/ekf_se2.h"
#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <cmath>
#include <mutex>
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
namespace {
// Chi so trang thai: [x, y, yaw, vx, vyaw]
constexpr int kX = 0, kY = 1, kYaw = 2, kVx = 3, kVyaw = 4, kN = 5;
using Vec5 = Eigen::Matrix<double, kN, 1>;
using Mat5 = Eigen::Matrix<double, kN, kN>;
} // namespace
struct EkfSe2::Impl {
EkfSe2Config cfg;
mutable std::mutex mu;
Vec5 x = Vec5::Zero();
Mat5 P = Mat5::Identity();
Mat5 Q = Mat5::Zero();
bool have_time = false;
UnixTime last_predict;
UnixTime last_measurement;
EkfSe2Stats stats;
explicit Impl(EkfSe2Config c) : cfg(std::move(c)) {
Q(kX, kX) = cfg.q_x;
Q(kY, kY) = cfg.q_y;
Q(kYaw, kYaw) = cfg.q_yaw;
Q(kVx, kVx) = cfg.q_vx;
Q(kVyaw, kVyaw) = cfg.q_vyaw;
P = Mat5::Zero();
P(kX, kX) = P(kY, kY) = P(kYaw, kYaw) = cfg.p0_pose;
P(kVx, kVx) = P(kVyaw, kVyaw) = cfg.p0_vel;
}
// Goi khi da giu mu.
void PredictLocked(double dt) {
if (dt <= 0.0) return;
const double yaw = x(kYaw);
const double vx = x(kVx);
const double c = std::cos(yaw), s = std::sin(yaw);
// Mo hinh van toc khong doi trong he than robot.
// x' = x + vx*cos(yaw)*dt
// y' = y + vx*sin(yaw)*dt
// yaw' = yaw + vyaw*dt
// vx' = vx
// vyaw' = vyaw
//
// KHONG co vy: robot vi sai khong truot ngang duoc. Do la ly do
// odom0_config dat vy = false trong ban cu.
x(kX) += vx * c * dt;
x(kY) += vx * s * dt;
x(kYaw) = NormalizeAngle(x(kYaw) + x(kVyaw) * dt);
Mat5 F = Mat5::Identity();
F(kX, kYaw) = -vx * s * dt;
F(kX, kVx) = c * dt;
F(kY, kYaw) = vx * c * dt;
F(kY, kVx) = s * dt;
F(kYaw, kVyaw) = dt;
// Nhieu qua trinh ty le voi dt: bo qua dt se lam filter qua tu tin khi
// chay o tan so cao va qua bao thu khi chay cham.
P = F * P * F.transpose() + Q * dt;
stats.predicts++;
}
// Cap nhat vo huong. Tra false neu bi bo vi lech qua nhieu.
bool UpdateScalarLocked(int state_idx, double z, double var) {
if (!(var > 0.0) || !std::isfinite(z)) return false;
Eigen::Matrix<double, 1, kN> H = Eigen::Matrix<double, 1, kN>::Zero();
H(0, state_idx) = 1.0;
const double y = z - x(state_idx); // phan du
const double S = (H * P * H.transpose())(0, 0) + var;
if (!(S > 0.0)) return false;
const double mahalanobis = std::sqrt(y * y / S);
stats.last_mahalanobis = mahalanobis;
if (cfg.mahalanobis_threshold > 0.0 &&
mahalanobis > cfg.mahalanobis_threshold) {
stats.rejected_outliers++;
VSLAM_WARN_THROTTLE(2.0, "ekf: bo phep do lech " << mahalanobis
<< " sigma o trang thai "
<< state_idx);
return false;
}
const Vec5 K = P * H.transpose() / S;
x += K * y;
x(kYaw) = NormalizeAngle(x(kYaw));
// Dang Joseph: giu P doi xung xac dinh duong ke ca khi co sai so lam tron.
// Dang don gian (I-KH)P mat tinh chat do sau vai nghin buoc, va khi P mat
// xac dinh duong thi filter phan ky ma khong co dau hieu gi.
const Mat5 IKH = Mat5::Identity() - K * H;
P = IKH * P * IKH.transpose() + K * var * K.transpose();
return true;
}
};
EkfSe2::EkfSe2(EkfSe2Config cfg) : impl_(std::make_unique<Impl>(std::move(cfg))) {}
EkfSe2::~EkfSe2() = default;
void EkfSe2::Predict(UnixTime now) {
std::lock_guard<std::mutex> lk(impl_->mu);
if (!impl_->have_time) {
impl_->last_predict = now;
impl_->have_time = true;
return;
}
const double dt = SecondsBetween(now, impl_->last_predict);
if (dt < 0.0) {
// Thoi gian lui: reset mo phong hoac phat lai ban ghi.
VSLAM_WARN("ekf: thoi gian lui " << dt << " s -- reset moc thoi gian");
impl_->last_predict = now;
impl_->stats.time_resets++;
return;
}
impl_->PredictLocked(dt);
impl_->last_predict = now;
}
void EkfSe2::UpdateOdomTwist(UnixTime stamp, double vx, double vyaw,
double var_vx, double var_vyaw) {
Predict(stamp);
std::lock_guard<std::mutex> lk(impl_->mu);
// var_* den tu twist.covariance cua wheel_odom -- day chinh la cho no bao
// "dang truot, dung tin toi".
const bool a = impl_->UpdateScalarLocked(kVx, vx, var_vx);
const bool b = impl_->UpdateScalarLocked(kVyaw, vyaw, var_vyaw);
if (a || b) {
impl_->stats.odom_updates++;
impl_->last_measurement = stamp;
}
}
void EkfSe2::UpdateImuYawRate(UnixTime stamp, double vyaw, double var) {
Predict(stamp);
std::lock_guard<std::mutex> lk(impl_->mu);
if (impl_->UpdateScalarLocked(kVyaw, vyaw, var)) {
impl_->stats.imu_updates++;
impl_->last_measurement = stamp;
}
}
Pose2D EkfSe2::pose() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return Pose2D{impl_->x(kX), impl_->x(kY), impl_->x(kYaw)};
}
double EkfSe2::vx() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->x(kVx);
}
double EkfSe2::vyaw() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->x(kVyaw);
}
Odometry EkfSe2::State(const std::string& odom_frame,
const std::string& base_frame) const {
std::lock_guard<std::mutex> lk(impl_->mu);
Odometry o;
o.header.stamp = impl_->last_predict;
o.header.frame_id = odom_frame;
o.child_frame_id = base_frame;
o.pose.pose.position.x = impl_->x(kX);
o.pose.pose.position.y = impl_->x(kY);
o.pose.pose.position.z = 0.0;
o.pose.pose.orientation = QuaternionFromYaw(impl_->x(kYaw));
for (int i = 0; i < 36; ++i) o.pose.covariance[i] = 0.0;
o.pose.covariance[0] = impl_->P(kX, kX);
o.pose.covariance[1] = impl_->P(kX, kY);
o.pose.covariance[6] = impl_->P(kY, kX);
o.pose.covariance[7] = impl_->P(kY, kY);
o.pose.covariance[14] = 1e6; // z khong quan sat duoc
o.pose.covariance[21] = 1e6; // roll -> do tu IMU, khong uoc luong
o.pose.covariance[28] = 1e6; // pitch -> do tu IMU, khong uoc luong
o.pose.covariance[35] = impl_->P(kYaw, kYaw);
o.twist.twist.linear.x = impl_->x(kVx);
o.twist.twist.angular.z = impl_->x(kVyaw);
for (int i = 0; i < 36; ++i) o.twist.covariance[i] = 0.0;
o.twist.covariance[0] = impl_->P(kVx, kVx);
o.twist.covariance[14] = 1e6;
o.twist.covariance[21] = 1e6;
o.twist.covariance[28] = 1e6;
o.twist.covariance[35] = impl_->P(kVyaw, kVyaw);
return o;
}
Transform EkfSe2::OdomToBase() const {
std::lock_guard<std::mutex> lk(impl_->mu);
Transform t;
t.translation = Vector3{impl_->x(kX), impl_->x(kY), 0.0};
t.rotation = QuaternionFromYaw(impl_->x(kYaw));
return t;
}
bool EkfSe2::Healthy(UnixTime now) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (impl_->last_measurement.isZero()) return false;
return SecondsBetween(now, impl_->last_measurement) < impl_->cfg.sensor_timeout;
}
void EkfSe2::SetPose(const Pose2D& p) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->x(kX) = p.x;
impl_->x(kY) = p.y;
impl_->x(kYaw) = NormalizeAngle(p.theta);
// Dat lai pose = biet chac vi tri -> ha hiep phuong sai pose ve gia tri dau.
// Van toc KHONG dat lai: robot co the dang chay khi bi dat lai pose.
impl_->P(kX, kX) = impl_->P(kY, kY) = impl_->P(kYaw, kYaw) = impl_->cfg.p0_pose;
impl_->P(kX, kY) = impl_->P(kY, kX) = 0.0;
}
void EkfSe2::Reset() {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->x = Vec5::Zero();
impl_->P = Mat5::Zero();
impl_->P(kX, kX) = impl_->P(kY, kY) = impl_->P(kYaw, kYaw) = impl_->cfg.p0_pose;
impl_->P(kVx, kVx) = impl_->P(kVyaw, kVyaw) = impl_->cfg.p0_vel;
impl_->have_time = false;
impl_->last_measurement = UnixTime();
impl_->stats = EkfSe2Stats{};
}
EkfSe2Stats EkfSe2::stats() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->stats;
}
} // namespace vslam

View File

@@ -0,0 +1,177 @@
#include "vslam/wheel_odometry.h"
#include <algorithm>
#include <cmath>
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
WheelOdometry::WheelOdometry(WheelOdometryConfig cfg) : cfg_(std::move(cfg)) {}
void WheelOdometry::FeedGyroZ(UnixTime stamp, double wz) {
gyro_z_ = wz;
last_imu_time_ = stamp;
have_imu_ = true;
}
void WheelOdometry::SetPose(const Pose2D& p) {
x_ = p.x;
y_ = p.y;
theta_ = NormalizeAngle(p.theta);
}
void WheelOdometry::Reset() {
initialized_ = false;
x_ = y_ = theta_ = 0.0;
slip_metric_ = 0.0;
slipping_ = false;
stats_ = WheelOdometryStats{};
}
bool WheelOdometry::Update(UnixTime stamp, double pos_l, double pos_r,
Odometry* out) {
if (!initialized_) {
prev_pos_l_ = pos_l;
prev_pos_r_ = pos_r;
prev_time_ = stamp;
initialized_ = true;
VSLAM_INFO("wheel_odom: da nhan encoder dau tien, bat dau tich phan");
return false;
}
const double dt = SecondsBetween(stamp, prev_time_);
if (dt <= 0.0) {
// Nhay lui thoi gian: xay ra khi reset mo phong hoac phat lai ban ghi.
// Reset trang thai thay vi tich phan mot dt am -- tich phan dt am se day
// pose di GIAT LUI, va EKF phia sau khong co cach nao biet.
VSLAM_WARN("wheel_odom: dt <= 0 (" << dt << " s) -- reset trang thai tich phan");
prev_pos_l_ = pos_l;
prev_pos_r_ = pos_r;
prev_time_ = stamp;
stats_.time_resets++;
return false;
}
// Quang duong tung banh. Chuan hoa DELTA de an toan voi ca hai kieu bao cao
// vi tri: tich luy khong gioi han, hoac cuon ve [-pi, pi].
const double d_l = NormalizeAngle(pos_l - prev_pos_l_) * cfg_.wheel_radius;
const double d_r = NormalizeAngle(pos_r - prev_pos_r_) * cfg_.wheel_radius;
const double d_center = 0.5 * (d_l + d_r);
const double d_theta = (d_r - d_l) / cfg_.wheel_separation;
// --------- Phat hien truot ---------
const double omega_encoder = d_theta / dt;
slip_metric_ = 0.0;
slipping_ = false;
const bool imu_fresh =
have_imu_ && (SecondsBetween(stamp, last_imu_time_) < cfg_.imu_timeout);
if (imu_fresh) {
slip_metric_ = std::fabs(omega_encoder - gyro_z_);
slipping_ = slip_metric_ > cfg_.slip_omega_threshold;
if (slipping_) {
stats_.slip_events++;
VSLAM_WARN_THROTTLE(2.0, "wheel_odom: nghi TRUOT BANH -- omega encoder "
<< omega_encoder << " vs gyro " << gyro_z_
<< " rad/s (lech " << slip_metric_
<< "). Nang covariance.");
}
} else {
stats_.no_imu_updates++;
VSLAM_WARN_THROTTLE(10.0,
"wheel_odom: khong co IMU moi -> KHONG phat hien duoc "
"truot banh. Odometry dang chay 'mu'.");
}
// --------- Tich phan Runge-Kutta bac 2 ---------
// Dung goc GIUA doan thay vi goc dau doan. Voi mot robot xoay 0.8 rad/s va
// chu ky 20 ms, khac biet giua hai cach la ~0.008 rad moi buoc -- nho, nhung
// no tich luy theo mot chieu va thanh troi yaw sau vai phut.
const double theta_mid = theta_ + 0.5 * d_theta;
x_ += d_center * std::cos(theta_mid);
y_ += d_center * std::sin(theta_mid);
theta_ = NormalizeAngle(theta_ + d_theta);
stats_.updates++;
stats_.total_distance += std::fabs(d_center);
stats_.last_slip_metric = slip_metric_;
// --------- Dong goi ---------
out->header.stamp = stamp;
out->header.frame_id = cfg_.odom_frame;
out->child_frame_id = cfg_.base_frame;
out->pose.pose.position.x = x_;
out->pose.pose.position.y = y_;
out->pose.pose.position.z = 0.0; // 2.5D: robot o tren mat phang
out->pose.pose.orientation = QuaternionFromYaw(theta_);
out->twist.twist.linear.x = d_center / dt;
out->twist.twist.angular.z = omega_encoder;
// Covariance ty le voi QUANG DUONG, khong phai thoi gian: sai so odometry
// tich luy theo quang duong di duoc. Mot robot dung yen khong tich them sai
// so, du dung bao lau.
const double mult = slipping_ ? cfg_.slip_cov_multiplier : 1.0;
const double travel = std::max(std::fabs(d_center), 1e-4);
const double turn = std::max(std::fabs(d_theta), 1e-4);
const double cov_x = std::pow(cfg_.sigma_x * travel, 2) * mult;
const double cov_y = std::pow(cfg_.sigma_y * travel, 2) * mult;
const double cov_yaw = std::pow(cfg_.sigma_yaw * turn, 2) * mult;
// Chi so: 0=x, 7=y, 14=z, 21=roll, 28=pitch, 35=yaw
for (int i = 0; i < 36; ++i) out->pose.covariance[i] = 0.0;
out->pose.covariance[0] = cov_x;
out->pose.covariance[7] = cov_y;
out->pose.covariance[14] = 1e6; // z khong quan sat duoc
out->pose.covariance[21] = 1e6; // roll -> IMU lo
out->pose.covariance[28] = 1e6; // pitch -> IMU lo
out->pose.covariance[35] = cov_yaw;
for (int i = 0; i < 36; ++i) out->twist.covariance[i] = 0.0;
out->twist.covariance[0] = cov_x / (dt * dt);
out->twist.covariance[7] = cov_y / (dt * dt);
out->twist.covariance[14] = 1e6;
out->twist.covariance[21] = 1e6;
out->twist.covariance[28] = 1e6;
// ======================================================================
// YAW-RATE: KHAI BAO DO BAT DINH DA DO, KHONG PHAI DOAN
//
// Khac cac thanh phan o tren: chung dung cov ty le quang duong roi nhan mot
// he so co dinh khi truot. Yaw-rate thi KHONG.
//
// Ly do: slip_metric = |omega_encoder - gyro_z| CHINH LA sai so cua phep do
// banh xe, do duoc tung chu ky. Lay no lam sigma la khai bao do bat dinh DA
// DO, thay vi mot he so doan truoc.
//
// Cach cu (cov_yaw/dt^2 voi he so co dinh 100) THIEU ~2 BAC. Da do khi robot
// xoay tai cho tren robot that:
// sai so that : omega encoder -3.635 vs gyro -1.377 = 2.26 rad/s
// sigma khai bao: (0.02*0.02)^2 * 100 / 0.02^2 = 0.04 -> 0.2 rad/s
// EKF nhan mot diem 11-sigma ma van tin -> yaw troi.
//
// Hau qua da do o tang tren: global_scan_init ghep scan bang odom, nen sau
// khi xoay 301 do no khop ra HUONG SAI 40.8 do (vi tri van dung 0.17 m).
// Khong xoay thi huong DUNG -- vi khong tich luy sai so odom nao.
//
// San khi KHONG co gyro: luc do slip_metric = 0, va neu dung thang thi
// sigma = 0 -> EKF tin banh xe TUYET DOI, te hon ca truoc khi sua. Vi vay
// co yaw_rate_sigma_no_imu.
// ======================================================================
const double sigma_wr = imu_fresh
? std::max(slip_metric_, cfg_.yaw_rate_sigma_floor)
: cfg_.yaw_rate_sigma_no_imu;
out->twist.covariance[35] = sigma_wr * sigma_wr;
prev_pos_l_ = pos_l;
prev_pos_r_ = pos_r;
prev_time_ = stamp;
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,26 @@
# Co y KHONG phu thuoc PCL.
#
# Ban ROS dung pcl::PassThrough + pcl::VoxelGrid + pcl::StatisticalOutlier.
# Ba cai do cong lai ~100 dong thuat toan da biet ro. Doi lai:
# - lib nay build va test duoc tren may KHONG co PCL (cung ly do voi
# vslam_odometry);
# - khong dinh bay -march=native/-msse4.2 ma PCL bom vao, thu vo hieu thang
# tren arm64 (xem vslam_link_pcl trong cmake/vslam_helpers.cmake);
# - VoxelGrid tu viet dung khoa int64 3x21-bit, khong co gioi han
# 2^31 diem cua pcl::VoxelGrid.
#
# PCL chi con can o vslam_slam, noi RTAB-Map da keo no vao san.
vslam_add_library(vslam_perception
PUBLIC_HDRS
perception_types.h
depth_to_cloud.h
depth_filter.h
gravity_align.h
cliff_detect.h
perception_pipeline.h
FIND_DEPS
vslam_common
)
target_link_libraries(vslam_perception PUBLIC vslam_common)

View File

@@ -0,0 +1,223 @@
#ifndef VSLAM_CLIFF_DETECT_H
#define VSLAM_CLIFF_DETECT_H
// Phat hien vuc / bac thang xuong bang anh DEPTH.
//
// Port tu perception_3d/src/cliff_detect_nodelet.cpp (~450 dong, doan thuat
// toan day nhat cua repo cu).
//
// ============ VI SAO CHAY TREN ANH DEPTH CHU KHONG PHAI POINT CLOUD ============
// 1. Bac thang TOI tra ve LO (NaN / 0), khong tra ve diem thap.
// pcl::PassThrough loai NaN => chinh cai tin hieu can tim bi xoa sach.
// Tren anh depth, mot pixel le ra phai thay san ma khong co so do LA bang
// chung cua vuc.
// 2. Tia biet minh di huong nao. Voi moi pixel tinh duoc "san LE RA phai o
// depth bao nhieu" (giao tia voi mat phang san). Cloud da mat thong tin do.
// 3. Danh dau tai P_floor = giao tia voi mat san, tuc la MEP vuc, chu khong
// phai tai diem tra ve (nam sau duoi day vuc, hoac khong ton tai).
//
// ============ VUNG MU 0 - 1.1 m ============
// Camera cao 0.803 m nghieng xuong: tia cham san gan nhat o ~1.07 m. Duoi
// nguong do khong tia nao cham san, detector khong the biet gi. Do la ly do
// min_dist mac dinh 1.10 m, va la ly do BAT BUOC phai co cam bien khac (cliff
// IR / bumper) cho vung gan.
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/perception_types.h"
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct CliffDetectConfig {
bool enabled = true;
// Cua so xet, tinh theo ban kinh tren mat san (m). Duoi min_dist la vung mu
// hinh hoc, khong phai lua chon tuy y.
double min_dist = 1.10;
double max_dist = 2.50;
// Be mat phai thap hon san tham chieu bao nhieu moi tinh la vuc (m).
double cliff_margin = 0.05;
// Sai so pitch con lai sau tu hieu chuan. Nguong no ra theo tam:
// thr = z_ref - (cliff_margin + r * tan(pitch_uncertainty))
double pitch_uncertainty_deg = 2.0;
int pixel_step = 4; // lay mau thua: 1/16 so pixel
int min_neighbors = 3; // trong 8 lang gieng, de loai pixel le
int min_cluster = 12; // so diem toi thieu de bao vuc
double imu_timeout = 0.5;
// Bail khi gravity_align dang khong neo duoc vao trong luc. Pitch luc do la
// gyro thuan va dang troi -> hinh hoc cat tia x san khong dung tin.
bool require_accel_ok = true;
// --- Tu hieu chuan mat san ---
bool self_level = true;
int min_level_samples = 40;
// Cong nay loai CA vat the (mat ban 0.7 m) LAN vuc that (z ~ -1 m) khoi phep
// khop. Nho ve thu hai ma khop duoc tren TOAN cua so ma khong nuot mat chinh
// cai vuc dang can tim.
double level_gate = 0.25;
// Doc vuot tran = dau hieu phep khop hong, KHONG phai san doc that. Ramp la
// san doc THAT va robot phai di duoc -- cong phan biet ramp/vuc la MAD.
double max_level_slope = 0.20;
double max_level_residual = 0.05;
// Mat phang san khop duoc, NGOAI SUY ve r = 0, phai di qua chinh cho robot
// dang dung -- vi robot DANG DUNG TREN no. Mot phep khop noi "san duoi banh
// xe toi thap hon 25 cm" la mot menh de vat ly sai, khong phai mot nguong
// can chinh.
//
// Day la cong bat duoc kieu hong ma `max_obstructed_frac` KHONG bat duoc:
// hanh lang 2.5-3.0 m, tuong cach 1.25-1.5 m. Chi ~9% tia tra ve diem cao
// hon level_gate (xa cong 0.60), nhung diem tuong o r lon van lot cong va
// KEO DOC duong khop len +0.19 -- vua du duoi tran max_level_slope 0.20.
// Sau do san THAT o r ~ 2 m bi do voi z_ref = +0.13 -> roi duoi nguong ->
// vuc gia. Do duoc: 6/210 khung o be rong 3.0 m.
//
// Vi sao KHONG ha max_level_slope thay vi the: 0.20 duoc chon de HAP THU
// dao dong pitch +-8.5 do do duoc tren robot that; ha xuong se vo hieu hoa
// co che bu va tat phat hien vuc khi robot dang chay. Xem ghi chu trong
// depth_filter.yaml cua repo cu.
//
// Vi sao 0.15: sai so cua z_ref(0) chi den tu sai so pitch va sai so chieu
// cao camera, ma ca hai deu da bi chan boi max_tz_dev = 0.08. Mot ramp that
// 8% bat dau o 1.5 m cho z0 = -0.096 -- van lot.
double max_level_offset = 0.15;
// Camera lech khoi chieu cao danh dinh => robot dang nghieng / da nhoai len
// vat gi do. Luc do phep khop mat san se bam theo TANG DUOI va bao "khong co
// vuc" -- nguy hiem hon la im lang.
// ⚠️ PHAI dat tu `RobotModel::camera_height_above_floor()`, khong go tay.
// No la camera_link.z CONG wheel_radius -- mot he qua, khong phai mot so
// doc lap. Mac dinh 0.803 o day tung LECH voi 0.80 ma bo mo phong dung, va
// khong co gi bao. Gio mac dinh khop, nhung van phai dat tu RobotModel vi
// robot.yaml moi la nguon.
double nominal_tz = 0.80;
double max_tz_dev = 0.08;
// Ti le toi da tia trong cua so duoc phep tra ve diem CAO hon level_gate
// truoc khi coi nhu "dang nhin vao vat can, khong nhin thay san".
//
// KHONG co trong ban ROS goc, va no bit mot lo hong THAT cua ban do.
// Trong hanh lang hep hon 2 x min_dist, tuong nam GAN HON vung mu 1.10 m:
// hau het tia dap vao tuong chu khong toi san. Mot so it diem tuong co
// z < level_gate van duoc nhan vao phep khop, va mat san tham chieu bi keo
// LEN theo chung. Sau do san THAT o xa hon bi do voi mat phang bi keo len
// do -> roi duoi nguong -> BAO VUC GIA giua hanh lang phang.
//
// Do duoc trong mo phong (hanh lang 1.6 m, robot quay tai cho): z0 khop
// thanh +0.24 m, MAD chi 0.046 nen lot ca cong MAD, roi 46 tia san that
// roi duoi nguong. Hong kieu nay la hong KHONG AN TOAN -- no bao CO vuc
// chu khong bao "khong biet".
//
// Vi sao dem diem CAO chu khong phai be rong dai mau: be rong la proxy yeu
// (da do: dai mau van trai 50% cua so ma van bao gia). Con dem diem cao thi
// KHONG BAO GIO che duoc vuc that: vuc lam diem THAP hoac MAT HAN, khong
// bao gio lam diem cao. Cong nay chi co the bien "co vuc" thanh "khong
// biet", khong bao gio bien thanh "khong co vuc".
double max_obstructed_frac = 0.60;
bool fail_safe = true;
double fail_safe_after = 1.0; // mu LIEN TUC bao lau thi bao nguy
double wheel_radius = 0.075;
};
// Vi sao khung nay khong phan xet duoc. Gia tri duoc dua ra ngoai de web UI
// hien duoc -- bao "khong biet" khac han bao "khong co vuc".
enum class CliffBail : uint8_t {
kNone = 0,
kDisabled,
kNoRollPitch,
kAccelGated, // robot dang tang/giam toc
kBadGeometry, // tz <= 0
kTzDeviation, // robot khong bang phang
kFewSamples, // khong du mau san de khop
kSlopeClamped, // doc cham tran -> khop hong
kResidualLarge, // MAD lon -> khung nhin khong phai mot mat phang
kBadEncoding,
kObstructed, // phan lon tia dap vao vat can, khong thay san
kOffsetLarge, // mat phang khop duoc khong di qua cho robot dang dung
};
const char* CliffBailName(CliffBail b);
struct CliffResult {
bool detected = false;
bool judged = false; // false = khong phan xet duoc (bail)
CliffBail bail = CliffBail::kNone;
double bail_held = 0.0; // da mu lien tuc bao lau (s)
// Mep vuc trong base_footprint. z giu AM co y (xem ghi chu trong .cc).
PointCloudXYZ edge_cloud;
// Chan doan -- lam nen cho khoi debug throttle cua ban ROS.
int64_t n_total = 0, n_up = 0, n_zneg = 0, n_range = 0, n_inwin = 0;
int64_t n_hole = 0, n_drop = 0;
int n_cliff = 0;
double r_min = 0.0, r_max = 0.0, z_lowest = 0.0;
double lvl_z0 = 0.0, lvl_slope = 0.0, lvl_slope_raw = 0.0, lvl_mad = 0.0;
int64_t lvl_samples = 0; // so mau vao phep khop mat san
int64_t lvl_high = 0; // tia trong cua so tra ve diem CAO hon level_gate
int64_t lvl_window = 0; // tong tia trong cua so o luot do muc san
double lvl_r_lo = 0.0; // ban kinh nho nhat / lon nhat trong so mau do
double lvl_r_hi = 0.0;
bool leveled = false;
double tz = 0.0;
};
struct CliffDetectStats {
uint64_t frames = 0;
uint64_t judged = 0;
uint64_t detected = 0;
uint64_t bailed = 0;
uint64_t bail_by[12] = {0};
};
class CliffDetect {
public:
explicit CliffDetect(CliffDetectConfig cfg);
// roll/pitch tu GravityAlign. accel_ok = bo loc co dang neo duoc vao trong
// luc khong, hay chi dang tich phan gyro.
void SetTilt(UnixTime stamp, double roll, double pitch, bool accel_ok);
// `cam_to_base` la phep bien doi TINH camera -> base_link (tu robot.yaml);
// nghieng do duoc se duoc ap them, giong het GravityAlign.
CliffResult Process(const Image& depth, const CameraInfo& info,
const Transform& cam_to_base, UnixTime now);
void Reset();
const CliffDetectStats& stats() const { return stats_; }
private:
CliffResult Bail(CliffBail why, bool immediate, UnixTime now);
CliffDetectConfig cfg_;
bool have_rp_ = false;
double roll_ = 0.0, pitch_ = 0.0;
bool accel_ok_ = true;
UnixTime last_rp_;
bool bailing_ = false;
UnixTime bail_since_;
// Bo dem tai su dung giua cac khung: 30 Hz x 4800 o, cap phat moi khung la
// lang phi va la nguon jitter.
std::vector<uint8_t> cand_;
std::vector<double> pos_x_, pos_y_;
std::vector<std::pair<double, double>> rz_;
CliffDetectStats stats_;
};
} // namespace vslam
#endif // VSLAM_CLIFF_DETECT_H

View File

@@ -0,0 +1,81 @@
#ifndef VSLAM_DEPTH_FILTER_H
#define VSLAM_DEPTH_FILTER_H
// Loc point cloud tu camera depth.
//
// Port tu perception_3d/src/depth_filter_nodelet.cpp. Chuoi:
// PassThrough(z) -> VoxelGrid -> (tuy chon) xac nhan theo thoi gian
//
// KHONG dung PCL. Ba bo loc nay cong lai khoang 100 dong, va giu
// vslam_perception khong phu thuoc PCL nghia la P5 build va test duoc trên
// may chua co PCL -- cung ly do voi vslam_odometry.
#include <cstdint>
#include <unordered_map>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct DepthFilterConfig {
double min_range = 0.22; // Min-Z cua D410
double max_range = 4.0;
double voxel_size = 0.03;
double max_rate = 10.0; // gioi han tan so dau ra, Hz
// Xac nhan theo thoi gian: mot voxel phai duoc thay `min_hits` lan trong
// `temporal_window` giay moi duoc xuat. Loc nhieu nhap nhay cua depth.
bool enable_temporal = false;
int min_hits = 3;
double temporal_window = 0.5;
};
struct DepthFilterStats {
uint64_t frames_in = 0;
uint64_t frames_out = 0;
uint64_t frames_rate_limited = 0;
uint64_t points_in = 0;
uint64_t points_after_range = 0;
uint64_t points_after_voxel = 0;
uint64_t points_out = 0;
};
class DepthFilter {
public:
explicit DepthFilter(DepthFilterConfig cfg);
// Tra false neu khung bi bo vi gioi han tan so. `out` khong duoc ghi.
//
// `stamp` dung STAMP CUA BAN TIN, khong phai dong ho tuong: gioi han tan so
// theo dong ho tuong se bop nham khi phat lai ban ghi nhanh.
bool Apply(const PointCloudXYZ& in, UnixTime stamp, PointCloudXYZ* out);
void Reset();
const DepthFilterStats& stats() const { return stats_; }
private:
struct VoxelHit {
int hits = 0;
UnixTime last_seen;
PointXYZ centroid;
int count = 0;
};
DepthFilterConfig cfg_;
UnixTime last_output_;
bool have_output_ = false;
std::unordered_map<int64_t, VoxelHit> voxels_;
DepthFilterStats stats_;
};
// Khoa voxel: goi ba chi so 21 bit vao mot int64.
//
// 21 bit moi truc -> dai +-1048575 voxel. Voi voxel 3 cm do la +-31 km, thua
// xa moi ban do trong nha. Goi vao mot int64 cho phep dung unordered_map ma
// khong phai bam mot tuple.
int64_t VoxelKey(double x, double y, double z, double size);
} // namespace vslam
#endif // VSLAM_DEPTH_FILTER_H

View File

@@ -0,0 +1,41 @@
#ifndef VSLAM_DEPTH_TO_CLOUD_H
#define VSLAM_DEPTH_TO_CLOUD_H
// Anh depth -> point cloud. Thay depth_image_proc/point_cloud_xyz.
//
// Cong thuc da XAC MINH tu
// /opt/ros/noetic/include/depth_image_proc/depth_conversions.h:52-100:
//
// constant_x = unit_scaling / fx (uint16 -> 0.001 m moi don vi)
// constant_y = unit_scaling / fy
// x = (u - cx) * depth * constant_x
// y = (v - cy) * depth * constant_y
// z = depth
// depth khong hop le (0 voi uint16, NaN voi float) -> diem = NaN
//
// fx/cx lay TU CameraInfo DA BU BINNING. crop_decimate cap nhat binning chu
// khong chia lai K, nen quen bu la moi diem lech theo he so decimate -- va
// cloud van "trong nhu that", chi la sai ti le.
#include "vslam/vslam_common.h"
namespace vslam {
// `out` duoc ghi de. Diem khong hop le duoc giu lai duoi dang NaN de cloud
// van TO CHUC THEO ANH (width x height) -- buoc sau can dieu do.
// Doc mot diem anh depth ra met. Tra NaN neu khong do duoc.
// Cong khai vi CliffDetect phai doc CHINH cung mot cach -- no lam viec trong
// khong gian anh chu khong qua cloud, va hai cach doc lech nhau (nhat la quy
// uoc 0 = khong do duoc) se sinh vuc gia.
double DepthAtMeters(const Image& img, uint32_t u, uint32_t v);
void DepthToCloud(const Image& depth, const CameraInfo& info, PointCloudXYZ* out);
// Ban KHONG to chuc: bo luon diem khong hop le. Nhanh hon va nho hon khi
// buoc sau khong can cau truc anh.
void DepthToCloudDense(const Image& depth, const CameraInfo& info,
PointCloudXYZ* out);
} // namespace vslam
#endif // VSLAM_DEPTH_TO_CLOUD_H

View File

@@ -0,0 +1,128 @@
#ifndef VSLAM_GRAVITY_ALIGN_H
#define VSLAM_GRAVITY_ALIGN_H
// Uoc luong roll/pitch tu IMU va xoay point cloud ve mat phang ngang.
//
// Port tu perception_3d/src/gravity_align_nodelet.cpp.
//
// ================== VAN DE COT LOI ==================
// Gia toc ke KHONG phan biet duoc nghieng voi tang toc. No do TONG cua:
// 1. trong luc chieu xuong ba truc cua than (phu thuoc roll/pitch)
// 2. gia toc rieng cua robot (tinh tien + huong tam)
//
// Mot robot tang toc 0.3 m/s^2 tren san phang cho ra doc cung gia toc ke nhu
// mot robot dung yen nghieng 1.75 do. Khong co cach nao tach hai truong hop
// bang rieng gia toc ke.
//
// Cach lam: TRU gia toc rieng truoc khi coi phan con lai la trong luc.
// axc = ax - a_lin (gia toc tinh tien, tu dao ham van toc odom)
// ayc = ay - v * omega (gia toc huong tam khi quay)
// Roi chi hieu chinh khi |a| con lai gan g -- tuc la dang gan trang thai tinh.
//
// ================== VI SAO PHAI LOC THONG THAP TRUOC ==================
// Gia toc ke tho dao dong manh do rung tiep xuc banh-san (san gach + banh
// cung). Ap cong |a| ~ g len mau tho se tu choi gan nhu moi mau, va bo loc
// chi con lai phan tich phan gyro -- tuc la troi tu do.
#include <cstdint>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
// base_footprint <- base_link voi nghieng da do. Ca GravityAlign lan
// CliffDetect deu phai dung CHINH ham nay -- hai ban sao hinh hoc lech nhau
// la lop loi da co trong repo cu (URDF vs base_tilt_tf.py).
Transform TiltLift(double roll, double pitch, double wheel_radius);
struct GravityAlignConfig {
// He so bo loc bu: 1 = chi tin gyro, 0 = chi tin accel.
// 0.98 nghia la gyro cho ngan han, accel keo ve dai han.
double alpha = 0.98;
// LPF cho gia toc ke truoc khi dung. Nho = loc manh.
double accel_lpf_alpha = 0.05;
// |a| duoc coi la "gan tinh" khi lech khoi g duoi nguong nay (m/s^2).
double accel_gate = 1.0;
double imu_timeout = 0.5;
double odom_timeout = 0.2;
// Tru gia toc rieng cua robot truoc khi hieu chinh. TAT cai nay la bo loc
// se hieu moi lan tang toc thanh mot cu nghieng.
bool use_odom_accel = true;
double odom_accel_alpha = 0.3; // LPF cho dao ham van toc
// Cat dai chieu cao sau khi xoay ve base_footprint.
double min_height = 0.06;
double max_height = 1.20;
// Chieu cao banh xe: base_footprint o mat dat, base_link o tam truc.
double wheel_radius = 0.075;
};
struct GravityAlignStats {
uint64_t imu_samples = 0;
uint64_t accel_accepted = 0; // so lan cong |a| ~ g mo
uint64_t accel_rejected = 0;
uint64_t clouds_in = 0;
uint64_t clouds_out = 0;
uint64_t points_in = 0;
uint64_t points_out = 0;
double last_accel_norm = 0.0;
};
class GravityAlign {
public:
explicit GravityAlign(GravityAlignConfig cfg);
// Goi moi mau IMU (200 Hz).
void FeedImu(const Imu& imu);
// Goi moi ban tin odometry. Dung de tinh gia toc rieng cua robot.
void FeedOdom(UnixTime stamp, double vx, double vyaw);
// Xoay cloud tu frame quang hoc cua camera ve base_footprint, da bu nghieng.
//
// `cam_to_base` la phep bien doi TINH tu camera toi base_link (tu robot.yaml).
// Nghieng do bo loc uoc luong duoc ap THEM vao.
//
// Tra false neu chua co uoc luong nghieng nao.
bool Align(const PointCloudXYZ& in, const Transform& cam_to_base,
UnixTime stamp, PointCloudXYZ* out) const;
double roll() const { return roll_; }
double pitch() const { return pitch_; }
bool valid() const { return initialized_; }
// true neu mau accel gan nhat duoc chap nhan (dang gan trang thai tinh).
bool accel_ok() const { return accel_ok_; }
void Reset();
const GravityAlignStats& stats() const { return stats_; }
private:
GravityAlignConfig cfg_;
bool initialized_ = false;
double roll_ = 0.0, pitch_ = 0.0;
UnixTime last_imu_;
bool lpf_init_ = false;
double ax_f_ = 0.0, ay_f_ = 0.0, az_f_ = 0.0;
bool accel_ok_ = false;
bool have_odom_ = false;
UnixTime last_odom_;
double v_prev_ = 0.0, w_ = 0.0, a_lin_ = 0.0;
// mutable: Align() la const ve mat logic (khong doi uoc luong nghieng)
// nhung van phai dem. const_cast o day se la mot loi cho, khong phai giai
// phap.
mutable GravityAlignStats stats_;
};
} // namespace vslam
#endif // VSLAM_GRAVITY_ALIGN_H

View File

@@ -0,0 +1,89 @@
#ifndef VSLAM_PERCEPTION_PIPELINE_H
#define VSLAM_PERCEPTION_PIPELINE_H
// Chuoi depth_to_cloud -> depth_filter -> gravity_align -> cliff_detect,
// chay INLINE trong mot loi goi tren chinh luong camera.
//
// Thay cho ba nodelet chung mot manager trong ban ROS. Tot hon: khong
// intrusive_ptr, khong dispatch theo topic, khong nodelet loader, va thu tu
// cac buoc la thu tu dong lenh -- khong con phu thuoc vao thu tu remap trong
// launch file.
//
// Doi tuong nay KHONG tu khoa. No thuoc ve dung mot luong (camera_rx). Ket
// qua di ra ngoai bang shared_ptr<const> qua Channel.
#include <memory>
#include <string>
#include "vslam/cliff_detect.h"
#include "vslam/clock.h"
#include "vslam/depth_filter.h"
#include "vslam/gravity_align.h"
#include "vslam/perception_types.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct PerceptionConfig {
DepthFilterConfig filter;
GravityAlignConfig gravity;
CliffDetectConfig cliff;
// Bo qua buoc dung cloud va loc -- chi chay cliff_detect. Cliff chay tren
// anh depth nen khong can cloud; tren Jetson day la cach ha tai khi chi can
// an toan chu khong can cloud cho SLAM.
bool enable_cloud = true;
bool enable_cliff = true;
};
struct PerceptionStats {
uint64_t frames_in = 0;
uint64_t frames_out = 0;
double last_ms = 0.0;
double max_ms = 0.0;
double avg_ms = 0.0;
};
class PerceptionPipeline {
public:
// `clock` chi dung cho do thoi gian xu ly va cho timeout cua cliff_detect.
// Moi dau thoi gian tren du lieu lay tu stamp cua ban tin -- day la dieu
// kien de phat lai ban ghi cho ket qua y het chay that.
PerceptionPipeline(PerceptionConfig cfg, const Clock& clock);
// Dat phep bien doi TINH camera_depth_optical_frame -> base_link, doc tu
// robot.yaml. Goi mot lan luc khoi tao.
void SetCameraExtrinsic(const Transform& cam_to_base);
// IMU 200 Hz. Goi truc tiep tu luong mcu_rx.
void FeedImu(const Imu& imu);
// Odometry 50 Hz -- can de TRU gia toc rieng cua robot khoi gia toc ke.
void FeedOdom(UnixTime stamp, double vx, double vyaw);
// Mot khung depth. Tra ve ket qua day du; nguoi goi quyet dinh publish gi.
PerceptionOutput Process(const Image& depth, const CameraInfo& info);
const GravityAlign& gravity() const { return gravity_; }
const CliffDetect& cliff() const { return cliff_; }
const PerceptionStats& stats() const { return stats_; }
void Reset();
private:
PerceptionConfig cfg_;
const Clock& clock_;
Transform cam_to_base_;
GravityAlign gravity_;
DepthFilter filter_;
CliffDetect cliff_;
// Tai su dung giua cac khung. 30 Hz x ~300k diem: cap phat moi khung la
// nguon jitter lon hon ban than phep tinh.
PointCloudXYZ buf_raw_, buf_filt_, buf_align_;
PerceptionStats stats_;
};
} // namespace vslam
#endif // VSLAM_PERCEPTION_PIPELINE_H

View File

@@ -0,0 +1,35 @@
#ifndef VSLAM_PERCEPTION_TYPES_H
#define VSLAM_PERCEPTION_TYPES_H
#include <cstdint>
#include <memory>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
// Ket qua cua mot vong perception. Moi truong deu co the null/rong neu buoc
// tuong ung khong chay hoac khong co du lieu.
struct PerceptionOutput {
UnixTime stamp;
PointCloudXYZPtr cloud_raw; // sau depth_to_cloud
PointCloudXYZPtr cloud_filtered; // sau depth_filter
PointCloudXYZPtr cloud_aligned; // sau gravity_align, trong base_footprint
PointCloudXYZPtr cloud_cliff; // diem danh dau mep vuc
// gravity_align
double roll = 0.0;
double pitch = 0.0;
bool tilt_valid = false;
bool accel_ok = false; // accel co dang gan trang thai tinh khong
// cliff_detect
bool cliff_detected = false;
std::string cliff_detail;
};
} // namespace vslam
#endif // VSLAM_PERCEPTION_TYPES_H

View File

@@ -0,0 +1,482 @@
#include "vslam/cliff_detect.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Trung vi cua z tren mot khoang da sap xep theo r; tra ve luon r tai giua
// khoang. Hai trung vi -> mot duong thang. Ben vung hon binh phuong toi thieu:
// mot vet vat can sot lai khong duoc phep keo ca duong.
void MedianOf(std::vector<std::pair<double, double>>::iterator b,
std::vector<std::pair<double, double>>::iterator e, double* r_out,
double* z_out) {
const size_t m = static_cast<size_t>(std::distance(b, e));
std::vector<double> zs;
zs.reserve(m);
for (auto it = b; it != e; ++it) zs.push_back(it->second);
std::nth_element(zs.begin(), zs.begin() + m / 2, zs.end());
*z_out = zs[m / 2];
*r_out = (b + static_cast<long>(m / 2))->first; // da sap xep theo r
}
// Khop BEN VUNG bang hai trung vi, khong dung binh phuong toi thieu: mot vet
// vat can sot lai khong duoc phep keo ca duong thang.
// Tra ve true neu doc bi kep (dau hieu phep khop hong).
bool FitFloorLine(std::vector<std::pair<double, double>>& rz, double* z0,
double* slope, double* slope_raw, double* mad,
double max_slope) {
const size_t n = rz.size(), h = n / 2;
double r1, z1, r2, z2;
MedianOf(rz.begin(), rz.begin() + static_cast<long>(h), &r1, &z1);
MedianOf(rz.begin() + static_cast<long>(h), rz.end(), &r2, &z2);
bool clamped = false;
if (r2 - r1 > 0.15) { // du duong day de uoc luong doc
double sl = (z2 - z1) / (r2 - r1);
*slope_raw = sl; // giu doc TRUOC khi kep, de in ra hieu chuan
// Doc vuot tran = dau hieu phep khop hong, KHONG phai san doc that.
// Ramp la san doc THAT va robot phai di duoc; cong phan biet ramp/vuc la
// MAD, khong phai do lon cua doc.
if (std::fabs(sl) > max_slope) {
clamped = true;
sl = (sl > 0 ? max_slope : -max_slope);
}
*slope = sl;
*z0 = z1 - *slope * r1;
} else {
*slope = 0.0;
*z0 = z1;
}
// MAD cua phan du: duong khop co THUC SU ta duoc mat san khong?
std::vector<double> resid;
resid.reserve(n);
for (const auto& pr : rz) {
resid.push_back(std::fabs(pr.second - (*z0 + *slope * pr.first)));
}
std::nth_element(resid.begin(), resid.begin() + static_cast<long>(n / 2),
resid.end());
*mad = resid[n / 2];
return clamped;
}
} // namespace
const char* CliffBailName(CliffBail b) {
switch (b) {
case CliffBail::kNone: return "none";
case CliffBail::kDisabled: return "disabled";
case CliffBail::kNoRollPitch: return "no_roll_pitch";
case CliffBail::kAccelGated: return "accel_gated";
case CliffBail::kBadGeometry: return "bad_geometry";
case CliffBail::kTzDeviation: return "tz_deviation";
case CliffBail::kFewSamples: return "few_samples";
case CliffBail::kSlopeClamped: return "slope_clamped";
case CliffBail::kResidualLarge: return "residual_large";
case CliffBail::kBadEncoding: return "bad_encoding";
case CliffBail::kObstructed: return "obstructed";
case CliffBail::kOffsetLarge: return "offset_large";
}
return "?";
}
CliffDetect::CliffDetect(CliffDetectConfig cfg) : cfg_(std::move(cfg)) {
if (cfg_.pixel_step < 1) cfg_.pixel_step = 1;
}
void CliffDetect::Reset() {
have_rp_ = false;
bailing_ = false;
stats_ = CliffDetectStats{};
}
void CliffDetect::SetTilt(UnixTime stamp, double roll, double pitch, bool accel_ok) {
roll_ = roll;
pitch_ = pitch;
accel_ok_ = accel_ok;
last_rp_ = stamp;
have_rp_ = true;
}
CliffResult CliffDetect::Bail(CliffBail why, bool immediate, UnixTime now) {
if (!bailing_) {
bailing_ = true;
bail_since_ = now;
}
const double held = SecondsBetween(now, bail_since_);
CliffResult r;
r.judged = false;
r.bail = why;
r.bail_held = held;
// immediate = true -> mot khung du de bao nguy (hinh hoc vo nghia, robot
// dang nghieng / nhoai len vat)
// immediate = false -> mot khung xau la nhieu nhat thoi; nhung mu LIEN TUC
// qua fail_safe_after giay thi bao nguy.
//
// ============ TRU `kObstructed` RA KHOI FAIL-SAFE ============
//
// Fail-safe ton tai cho truong hop "toi khong thay san va KHONG BIET vi
// sao": khong du mau, khop hong, mat phang vo nghia. Luc do khong loai tru
// duoc mot cai vuc, nen phai dung.
//
// `kObstructed` khac han. No la mot quan sat KHANG DINH: cua so nhin san bi
// mot vat DAC lap kin. Vat dac khong phai vuc, va da co nguoi lo -- LiDAR
// thay no va FSM dung robot qua SCAN_SLOW/SCAN_STOP.
//
// Do duoc tren ban do benh vien that: dung o (0.5, 0) cach tuong 2.0 m --
// cua so nhin san 1.1-2.5 m bi buc tuong lap kin -- ra 209/240 khung "bao
// vuc" voi ly do `obstructed`. Hau qua: robot KHONG BAO GIO lai gan tuong
// duoi ~2.5 m duoc, tuc khong di duoc trong bat ky toa nha that nao. Ban do
// SLAM ket o 1.55 x 1.05 m sau 50 giay lai.
//
// ⚠️ Van BAO CAO bail nhu cu (`judged = false`): nguoi van hanh phai thay
// detector dang mu. Chi khong bien cai mu DA GIAI THICH DUOC thanh lenh
// dung.
const bool blind_for_unknown_reason = (why != CliffBail::kObstructed);
r.detected = cfg_.fail_safe && blind_for_unknown_reason &&
(immediate || held > cfg_.fail_safe_after);
stats_.bailed++;
stats_.bail_by[static_cast<size_t>(why)]++;
if (r.detected) stats_.detected++;
return r;
}
CliffResult CliffDetect::Process(const Image& depth, const CameraInfo& info,
const Transform& cam_to_base, UnixTime now) {
stats_.frames++;
if (!cfg_.enabled) {
CliffResult r;
r.judged = false;
r.bail = CliffBail::kDisabled;
return r;
}
if (depth.data == nullptr ||
(depth.format != PixelFormat::kMono16 && depth.format != PixelFormat::kFloat32)) {
return Bail(CliffBail::kBadEncoding, false, now);
}
const bool rp_fresh =
have_rp_ && SecondsBetween(now, last_rp_) < cfg_.imu_timeout;
double roll = 0.0, pitch = 0.0;
if (rp_fresh) {
roll = roll_;
pitch = pitch_;
}
// Khong co roll/pitch moi -> gia dinh phang va di tiep. Ket qua KHONG dang
// tin khi robot nghieng, nhung mot camera gan chac phang van tot hon la
// khong phan xet gi.
// gravity_align dang khong neo duoc vao trong luc -> pitch la gyro thuan va
// dang troi. Hinh hoc cat tia x san khong dung tin o trang thai nay.
if (cfg_.require_accel_ok && rp_fresh && !accel_ok_) {
return Bail(CliffBail::kAccelGated, false, now);
}
// Cung mot hinh hoc voi GravityAlign -- dung chung TiltLift().
const Transform T = TransformCompose(TiltLift(roll, pitch, cfg_.wheel_radius),
cam_to_base);
// Hang thu 3 cua ma tran quay: lay bang cach quay ba vector co so.
const double r20 = RotateVector(T.rotation, Vector3{1, 0, 0}).z;
const double r21 = RotateVector(T.rotation, Vector3{0, 1, 0}).z;
const double r22 = RotateVector(T.rotation, Vector3{0, 0, 1}).z;
const double tz = T.translation.z;
// Tia chi cham san khi no chuc XUONG trong base_footprint, va camera phai o
// TREN san.
if (tz <= 0.0) return Bail(CliffBail::kBadGeometry, true, now);
// Camera lech khoi chieu cao danh dinh => robot dang nghieng / da nhoai len
// vat gi do. Dung luc do phep khop mat san se bam theo TANG DUOI va bao
// "khong co vuc" -- im lang khi that su co vuc la kieu hong nguy hiem nhat.
if (std::fabs(tz - cfg_.nominal_tz) > cfg_.max_tz_dev) {
return Bail(CliffBail::kTzDeviation, true, now);
}
// KHONG duoc doc thang info.K. crop_decimate giao anh 320x240 nhung
// CameraInfo van mang K cua 640x480 va bao muc gop qua binning_x/y = 2.
// Doc thang K thi moi tia bi coi nhu nam ngang -> r_floor [3.5, 134] m thay
// vi [1.07, 3.18] -> khong tia nao roi vao cua so -> detector im lang hoan
// toan MA KHONG BAO LOI GI.
const double fx = info.fx_binned(), fy = info.fy_binned();
const double cx = info.cx_binned(), cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return Bail(CliffBail::kBadGeometry, true, now);
const double tan_unc = std::tan(cfg_.pitch_uncertainty_deg * M_PI / 180.0);
const int W = static_cast<int>(depth.width);
const int H = static_cast<int>(depth.height);
const int step = cfg_.pixel_step;
const int gw = (W + step - 1) / step;
const int gh = (H + step - 1) / step;
const size_t ncell = static_cast<size_t>(gw) * static_cast<size_t>(gh);
cand_.assign(ncell, 0);
pos_x_.assign(ncell, 0.0);
pos_y_.assign(ncell, 0.0);
CliffResult res;
res.judged = true;
res.tz = tz;
double r_min = 1e9, r_max = -1e9, z_lowest = 1e9;
// ============ LUOT 1: DO MUC SAN THAM CHIEU ============
// Tru di muc nay bien phep do thanh VI SAI -> sai so pitch, sai so chieu cao
// camera va lun caster deu la common-mode va bi triet.
// z_ref(r) = lvl_z0 + lvl_slope * r
double lvl_z0 = 0.0, lvl_slope = 0.0, lvl_mad = 0.0, lvl_slope_raw = 0.0;
bool leveled = false;
int64_t n_high = 0, n_window = 0;
if (cfg_.self_level) {
rz_.clear();
rz_.reserve(2048);
for (int gy = 0; gy < gh; ++gy) {
const int v = gy * step;
if (v >= H) break;
for (int gx = 0; gx < gw; ++gx) {
const int u = gx * step;
if (u >= W) break;
const double a = (u - cx) / fx;
const double b = (v - cy) / fy;
const double denom = r20 * a + r21 * b + r22;
if (denom > -1e-6) continue;
const double z_exp = -tz / denom;
if (z_exp <= 0.0) continue;
const Point pf = TransformPoint(T, Point{z_exp * a, z_exp * b, z_exp});
const double rf = std::hypot(pf.x, pf.y);
if (rf < cfg_.min_dist || rf > cfg_.max_dist) continue;
const double d = DepthAtMeters(depth, static_cast<uint32_t>(u),
static_cast<uint32_t>(v));
if (!std::isfinite(d) || d <= 0.0) continue;
const Point po = TransformPoint(T, Point{d * a, d * b, d});
// Cong nay lam CA HAI viec: loai vat the (mat ban 0.7 m, mat ghe
// 0.45 m) VA loai vuc that (z ~ -1 m) khoi phep khop. Nho ve thu hai
// ma khop duoc tren TOAN cua so ma khong nuot mat chinh cai vuc dang
// can tim.
n_window++;
if (po.z > cfg_.level_gate) {
n_high++; // diem CAO: vat can che mat san (tuong, ban, ghe)
continue;
}
if (po.z < -cfg_.level_gate) continue; // diem THAP: co the la vuc
rz_.emplace_back(rf, po.z);
}
}
res.lvl_high = n_high;
res.lvl_window = n_window;
// Phan lon cua so bi vat can che -> khong nhin thay san -> KHONG phan xet.
// Phai kiem TRUOC min_level_samples: mot buc tuong gan van de lai du 40
// mau z thap de "khop duoc" mot mat phang khong co that.
if (n_window > 0 &&
static_cast<double>(n_high) > cfg_.max_obstructed_frac * n_window) {
return Bail(CliffBail::kObstructed, false, now);
}
if (static_cast<int>(rz_.size()) < cfg_.min_level_samples) {
// Khong du mau -> khong biet san o dau -> KHONG phan xet. Im lang con
// hon bao gia: bao gia se chan duong robot giua nha hang va nguoi van
// hanh se tat han node di.
return Bail(CliffBail::kFewSamples, false, now);
}
res.lvl_samples = static_cast<int64_t>(rz_.size());
std::sort(rz_.begin(), rz_.end(),
[](const std::pair<double, double>& p, const std::pair<double, double>& q) {
return p.first < q.first;
});
res.lvl_r_lo = rz_.front().first;
res.lvl_r_hi = rz_.back().first;
bool slope_clamped = FitFloorLine(rz_, &lvl_z0, &lvl_slope, &lvl_slope_raw,
&lvl_mad, cfg_.max_level_slope);
// --- LOAI NGOAI LAI ROI KHOP LAI ---
//
// Phep khop hai-trung-vi chi theo BAN KINH: z = z0 + doc*r. No gop mat
// chieu phuong vi, nen mot buc tuong o MOT BEN lam lech ca vanh.
//
// Do duoc: hanh lang 3.0 m (tuong cach 1.5 m) -> tia nham r > 1.5 dap vao
// tuong o z = 0.8*(1 - 1.5/r); tai r = 2.0 cho z = 0.20, VUA DU lot cong
// level_gate 0.25. Duong khop bi keo len o giua cua so, roi tia san THAT
// o 2.5 m bi do voi mat phang do -> roi duoi nguong -> vuc gia.
// Cong `max_obstructed_frac` KHONG bat duoc: quet ngưỡng tu 0.60 xuong
// 0.20 deu cho dung 6/210 khung sai o be rong 3.0 m, va che% = 0.0 o moi
// nguong -- tuc la vat can chua du nhieu de kich cong.
//
// Mot luot loai ngoai lai giai quyet dung goc: diem tuong la THIEU SO nen
// bi loai, con neu chung la DA SO thi MAD phinh ra va cong
// max_level_residual kich. Khong the lam vuc that bien mat: diem vuc cung
// bi loai khoi phep khop, ma loai chung ra thi mat san tham chieu cang
// dung -> vuc CANG de thay o luot 2.
if (lvl_mad > 1e-6 && rz_.size() >= 8) {
const double cut = std::max(3.0 * lvl_mad, 0.01);
size_t keep = 0;
for (size_t i = 0; i < rz_.size(); ++i) {
if (std::fabs(rz_[i].second - (lvl_z0 + lvl_slope * rz_[i].first)) <= cut) {
rz_[keep++] = rz_[i];
}
}
if (static_cast<int>(keep) >= cfg_.min_level_samples && keep < rz_.size()) {
rz_.resize(keep);
slope_clamped = FitFloorLine(rz_, &lvl_z0, &lvl_slope, &lvl_slope_raw,
&lvl_mad, cfg_.max_level_slope);
}
}
res.lvl_z0 = lvl_z0;
res.lvl_slope = lvl_slope;
res.lvl_mad = lvl_mad;
if (slope_clamped) return Bail(CliffBail::kSlopeClamped, false, now);
if (std::fabs(lvl_z0) > cfg_.max_level_offset) {
// Mat phang khop duoc khong di qua cho robot dang dung -> no khong phai
// mat san. Xem ghi chu o max_level_offset.
return Bail(CliffBail::kOffsetLarge, false, now);
}
if (lvl_mad > cfg_.max_level_residual) {
// Khung nhin khong phai mot mat phang san -> khong co goc quy chieu dang
// tin -> KHONG phan xet.
return Bail(CliffBail::kResidualLarge, false, now);
}
leveled = true;
}
// ============ LUOT 2: PHAN XET TUNG TIA ============
for (int gy = 0; gy < gh; ++gy) {
const int v = gy * step;
if (v >= H) break;
for (int gx = 0; gx < gw; ++gx) {
const int u = gx * step;
if (u >= W) break;
res.n_total++;
const double a = (u - cx) / fx;
const double b = (v - cy) / fy;
const double denom = r20 * a + r21 * b + r22;
if (denom > -1e-6) {
res.n_up++; // tia khong chuc xuong -> khong cham san
continue;
}
const double z_exp = -tz / denom; // depth ma san LE RA phai o do
if (z_exp <= 0.0) {
res.n_zneg++;
continue;
}
const Point p_floor = TransformPoint(T, Point{z_exp * a, z_exp * b, z_exp});
const double r_floor = std::hypot(p_floor.x, p_floor.y);
r_min = std::min(r_min, r_floor);
r_max = std::max(r_max, r_floor);
if (r_floor < cfg_.min_dist || r_floor > cfg_.max_dist) {
res.n_range++;
continue;
}
res.n_inwin++;
const double d_obs = DepthAtMeters(depth, static_cast<uint32_t>(u),
static_cast<uint32_t>(v));
// Nguong no ra theo tam: bu sai so pitch con lai sau tu hieu chuan.
const double z_ref = lvl_z0 + lvl_slope * r_floor;
const double thr = z_ref - (cfg_.cliff_margin + r_floor * tan_unc);
bool is_cand = false;
if (!std::isfinite(d_obs) || d_obs <= 0.0) {
// LO: le ra phai thay san o day ma khong co so do nao. Day la ca cau
// thang TOI, va la ly do phai chay tren anh depth.
is_cand = true;
res.n_hole++;
} else {
const Point p_obs = TransformPoint(T, Point{d_obs * a, d_obs * b, d_obs});
z_lowest = std::min(z_lowest, p_obs.z);
if (p_obs.z < thr) {
is_cand = true; // SUT: be mat thap hon san qua nguong
res.n_drop++;
}
}
if (is_cand) {
const size_t idx = static_cast<size_t>(gy) * static_cast<size_t>(gw) + gx;
cand_[idx] = 1;
// MARK TAI MEP (giao tia x mat san), khong tai diem tra ve. Diem tra
// ve nam duoi day vuc -- hoac khong ton tai.
pos_x_[idx] = p_floor.x;
pos_y_[idx] = p_floor.y;
}
}
}
// ============ DOI CUM: LOAI PIXEL LE ============
res.edge_cloud.header = depth.header;
res.edge_cloud.header.frame_id = kBaseFootprintFrame;
res.edge_cloud.points.clear();
res.edge_cloud.is_dense = true;
const float mark_z = static_cast<float>(-(cfg_.cliff_margin + 0.05));
for (int gy = 0; gy < gh; ++gy) {
for (int gx = 0; gx < gw; ++gx) {
const size_t idx = static_cast<size_t>(gy) * static_cast<size_t>(gw) + gx;
if (!cand_[idx]) continue;
int neigh = 0;
for (int dy = -1; dy <= 1; ++dy) {
const int ny = gy + dy;
if (ny < 0 || ny >= gh) continue;
for (int dx = -1; dx <= 1; ++dx) {
const int nx = gx + dx;
if (nx < 0 || nx >= gw) continue;
if (dx == 0 && dy == 0) continue;
neigh += cand_[static_cast<size_t>(ny) * static_cast<size_t>(gw) + nx];
}
}
if (neigh < cfg_.min_neighbors) continue;
// GIU z AM, khong nang len. Trong costmap cu, vat can ao dat o z duong
// bi chinh tia clearing cua camera xoa ngay frame sau. Khong con costmap
// nua nhung giu nguyen quy uoc de doc lai log cu van khop.
res.edge_cloud.points.push_back(PointXYZ{static_cast<float>(pos_x_[idx]),
static_cast<float>(pos_y_[idx]), mark_z});
res.n_cliff++;
}
}
res.detected = (res.n_cliff >= cfg_.min_cluster);
res.r_min = (r_min > 1e8 ? 0.0 : r_min);
res.r_max = (r_max < -1e8 ? 0.0 : r_max);
res.z_lowest = (z_lowest > 1e8 ? 0.0 : z_lowest);
res.lvl_z0 = lvl_z0;
res.lvl_slope = lvl_slope;
res.lvl_slope_raw = lvl_slope_raw;
res.lvl_mad = lvl_mad;
res.leveled = leveled;
// Den day nghia la da phan xet duoc -> chuoi "khong biet" ket thuc.
bailing_ = false;
stats_.judged++;
if (res.detected) stats_.detected++;
return res;
}
} // namespace vslam

View File

@@ -0,0 +1,123 @@
#include "vslam/depth_filter.h"
#include <cmath>
#include <cstdint>
#include "vslam/log.h"
namespace vslam {
int64_t VoxelKey(double x, double y, double z, double size) {
const int64_t ix = static_cast<int64_t>(std::floor(x / size));
const int64_t iy = static_cast<int64_t>(std::floor(y / size));
const int64_t iz = static_cast<int64_t>(std::floor(z / size));
// Doi sang khong dau 21 bit roi goi. Khong kiem tran o day: voi voxel 3 cm
// thi dai la +-31 km, va mot diem ngoai dai do da la rac tu truoc.
constexpr int64_t kBias = 1 << 20;
const int64_t ux = (ix + kBias) & 0x1FFFFF;
const int64_t uy = (iy + kBias) & 0x1FFFFF;
const int64_t uz = (iz + kBias) & 0x1FFFFF;
return (ux << 42) | (uy << 21) | uz;
}
DepthFilter::DepthFilter(DepthFilterConfig cfg) : cfg_(std::move(cfg)) {}
void DepthFilter::Reset() {
voxels_.clear();
have_output_ = false;
stats_ = DepthFilterStats{};
}
bool DepthFilter::Apply(const PointCloudXYZ& in, UnixTime stamp,
PointCloudXYZ* out) {
stats_.frames_in++;
stats_.points_in += in.points.size();
// Gioi han tan so theo STAMP CUA BAN TIN, khong phai dong ho tuong.
// Dung dong ho tuong se bop nham khi phat lai ban ghi nhanh hon thoi gian
// that -- va bai regression se cho ket qua khac live.
if (cfg_.max_rate > 0.0 && have_output_) {
const double dt = SecondsBetween(stamp, last_output_);
if (dt >= 0.0 && dt < 1.0 / cfg_.max_rate) {
stats_.frames_rate_limited++;
return false;
}
}
// --- 1. PassThrough theo z (khoang cach toi camera) ---
// Duoi Min-Z la vung mu cua D410, khong phai vat can o khoang cach do.
// Tren max_range thi do chinh xac cua stereo giam nhanh theo binh phuong.
std::unordered_map<int64_t, VoxelHit> frame_voxels;
frame_voxels.reserve(in.points.size() / 4 + 16);
size_t after_range = 0;
for (const PointXYZ& p : in.points) {
if (!std::isfinite(p.z)) continue; // NaN cua cloud to chuc theo anh
if (p.z < cfg_.min_range || p.z > cfg_.max_range) continue;
if (!std::isfinite(p.x) || !std::isfinite(p.y)) continue;
after_range++;
// --- 2. VoxelGrid: gop diem trong cung o ---
const int64_t key = VoxelKey(p.x, p.y, p.z, cfg_.voxel_size);
VoxelHit& h = frame_voxels[key];
h.centroid.x += p.x;
h.centroid.y += p.y;
h.centroid.z += p.z;
h.count++;
}
stats_.points_after_range += after_range;
stats_.points_after_voxel += frame_voxels.size();
out->header = in.header;
out->header.stamp = stamp;
out->points.clear();
out->points.reserve(frame_voxels.size());
out->is_dense = true;
if (!cfg_.enable_temporal) {
for (auto& kv : frame_voxels) {
VoxelHit& h = kv.second;
const float inv = 1.0f / static_cast<float>(h.count);
out->points.push_back(PointXYZ{h.centroid.x * inv, h.centroid.y * inv,
h.centroid.z * inv});
}
} else {
// --- 3. Xac nhan theo thoi gian ---
// Mot voxel phai duoc thay `min_hits` lan trong `temporal_window` moi
// duoc xuat. Loc nhieu nhap nhay cua depth, doi lai mot do tre bang
// (min_hits - 1) khung.
for (auto& kv : frame_voxels) {
VoxelHit& cur = kv.second;
VoxelHit& acc = voxels_[kv.first];
if (acc.hits > 0 &&
SecondsBetween(stamp, acc.last_seen) > cfg_.temporal_window) {
acc.hits = 0; // qua cu -> bat dau dem lai
}
acc.hits++;
acc.last_seen = stamp;
const float inv = 1.0f / static_cast<float>(cur.count);
acc.centroid = PointXYZ{cur.centroid.x * inv, cur.centroid.y * inv,
cur.centroid.z * inv};
if (acc.hits >= cfg_.min_hits) {
out->points.push_back(acc.centroid);
}
}
// Don voxel qua han. Khong don thi map phinh vo han khi robot di xa.
for (auto it = voxels_.begin(); it != voxels_.end();) {
if (SecondsBetween(stamp, it->second.last_seen) > cfg_.temporal_window * 2.0) {
it = voxels_.erase(it);
} else {
++it;
}
}
}
stats_.points_out += out->points.size();
stats_.frames_out++;
last_output_ = stamp;
have_output_ = true;
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,93 @@
#include "vslam/depth_to_cloud.h"
#include <cmath>
#include <cstring>
#include <limits>
namespace vslam {
// Doc mot diem anh depth ra met. Tra NaN neu khong hop le.
//
// Quy uoc cua RealSense va cua depth_image_proc:
// uint16 : 0 = khong do duoc
// float32: NaN = khong do duoc
double DepthAtMeters(const Image& img, uint32_t u, uint32_t v) {
const size_t row = static_cast<size_t>(v) * img.step;
if (img.format == PixelFormat::kMono16) {
const size_t off = row + static_cast<size_t>(u) * 2;
const uint16_t raw = static_cast<uint16_t>(img.data[off]) |
(static_cast<uint16_t>(img.data[off + 1]) << 8);
if (raw == 0) return std::numeric_limits<double>::quiet_NaN();
return raw * static_cast<double>(img.depth_scale);
}
if (img.format == PixelFormat::kFloat32) {
float f;
std::memcpy(&f, img.data + row + static_cast<size_t>(u) * 4, 4);
return f;
}
return std::numeric_limits<double>::quiet_NaN();
}
void DepthToCloud(const Image& depth, const CameraInfo& info, PointCloudXYZ* out) {
out->header = depth.header;
out->points.assign(static_cast<size_t>(depth.width) * depth.height, PointXYZ{});
out->is_dense = false;
if (depth.data == nullptr) return;
// fx/cx DA BU BINNING. crop_decimate cap nhat binning chu khong chia lai K;
// quen bu la moi diem lech theo he so decimate, va cloud van "trong nhu
// that" -- chi la sai ti le.
const double fx = info.fx_binned();
const double fy = info.fy_binned();
const double cx = info.cx_binned();
const double cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return;
const float nan_v = std::numeric_limits<float>::quiet_NaN();
for (uint32_t v = 0; v < depth.height; ++v) {
for (uint32_t u = 0; u < depth.width; ++u) {
PointXYZ& p = out->points[static_cast<size_t>(v) * depth.width + u];
const double d = DepthAtMeters(depth, u, v);
if (!std::isfinite(d) || d <= 0.0) {
p.x = p.y = p.z = nan_v;
continue;
}
p.x = static_cast<float>((u - cx) * d / fx);
p.y = static_cast<float>((v - cy) * d / fy);
p.z = static_cast<float>(d);
}
}
}
void DepthToCloudDense(const Image& depth, const CameraInfo& info,
PointCloudXYZ* out) {
out->header = depth.header;
out->points.clear();
out->is_dense = true;
if (depth.data == nullptr) return;
const double fx = info.fx_binned();
const double fy = info.fy_binned();
const double cx = info.cx_binned();
const double cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return;
out->points.reserve(static_cast<size_t>(depth.width) * depth.height / 2);
for (uint32_t v = 0; v < depth.height; ++v) {
for (uint32_t u = 0; u < depth.width; ++u) {
const double d = DepthAtMeters(depth, u, v);
if (!std::isfinite(d) || d <= 0.0) continue;
PointXYZ p;
p.x = static_cast<float>((u - cx) * d / fx);
p.y = static_cast<float>((v - cy) * d / fy);
p.z = static_cast<float>(d);
out->points.push_back(p);
}
}
}
} // namespace vslam

View File

@@ -0,0 +1,167 @@
#include "vslam/gravity_align.h"
#include <cmath>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
GravityAlign::GravityAlign(GravityAlignConfig cfg) : cfg_(std::move(cfg)) {}
void GravityAlign::Reset() {
initialized_ = false;
roll_ = pitch_ = 0.0;
lpf_init_ = false;
have_odom_ = false;
accel_ok_ = false;
stats_ = GravityAlignStats{};
}
void GravityAlign::FeedOdom(UnixTime stamp, double vx, double vyaw) {
if (have_odom_) {
const double dt = SecondsBetween(stamp, last_odom_);
if (dt > 0.0 && dt < 1.0) {
// Dao ham van toc, loc thong thap. Dao ham tho qua nhieu de tru truc
// tiep khoi gia toc ke.
const double a = (vx - v_prev_) / dt;
a_lin_ = cfg_.odom_accel_alpha * a + (1.0 - cfg_.odom_accel_alpha) * a_lin_;
}
}
v_prev_ = vx;
w_ = vyaw;
last_odom_ = stamp;
have_odom_ = true;
}
void GravityAlign::FeedImu(const Imu& imu) {
const UnixTime now = imu.header.stamp;
stats_.imu_samples++;
if (!initialized_) {
last_imu_ = now;
initialized_ = true;
return;
}
const double dt = SecondsBetween(now, last_imu_);
last_imu_ = now;
if (dt <= 0.0 || dt > 1.0) {
// Nhay thoi gian (reset mo phong / phat lai ban ghi) -> bo qua mau nay.
return;
}
// --- Du doan bang gyro ---
roll_ += imu.angular_velocity.x * dt;
pitch_ += imu.angular_velocity.y * dt;
// --- Loc thong thap accel TRUOC khi dung ---
// Accel tho dao dong manh do rung tiep xuc banh-san; ap cong |a| ~ g len
// mau tho se tu choi gan nhu moi mau, va bo loc chi con lai tich phan gyro
// -- tuc la troi tu do.
const double ax_raw = imu.linear_acceleration.x;
const double ay_raw = imu.linear_acceleration.y;
const double az_raw = imu.linear_acceleration.z;
if (!lpf_init_) {
ax_f_ = ax_raw;
ay_f_ = ay_raw;
az_f_ = az_raw;
lpf_init_ = true;
} else {
const double a = cfg_.accel_lpf_alpha;
ax_f_ = a * ax_raw + (1.0 - a) * ax_f_;
ay_f_ = a * ay_raw + (1.0 - a) * ay_f_;
az_f_ = a * az_raw + (1.0 - a) * az_f_;
}
// --- Hieu chinh bang accel, CHI khi dang gan trang thai tinh ---
const double ax = ax_f_, ay = ay_f_, az = az_f_;
// TRU gia toc cua CHINH ROBOT truoc khi coi phan con lai la trong luc.
// axc: gia toc tinh tien (dv/dt)
// ayc: gia toc huong tam khi quay (v * omega)
double axc = ax, ayc = ay;
const bool odom_fresh =
have_odom_ && SecondsBetween(now, last_odom_) < cfg_.odom_timeout;
if (cfg_.use_odom_accel && odom_fresh) {
axc = ax - a_lin_;
ayc = ay - v_prev_ * w_;
}
const double norm = std::sqrt(axc * axc + ayc * ayc + az * az);
stats_.last_accel_norm = norm;
if (std::fabs(norm - kGravity) < cfg_.accel_gate && norm > 1e-3) {
const double roll_acc = std::atan2(ayc, az);
const double pitch_acc = std::atan2(-axc, std::sqrt(ayc * ayc + az * az));
// Bo loc bu: gyro cho ngan han, accel keo ve dai han.
roll_ = cfg_.alpha * roll_ + (1.0 - cfg_.alpha) * roll_acc;
pitch_ = cfg_.alpha * pitch_ + (1.0 - cfg_.alpha) * pitch_acc;
accel_ok_ = true;
stats_.accel_accepted++;
} else {
// Dang tang toc / phanh / va cham -> khong biet dau la trong luc ->
// chi tich phan gyro. Troi cham con hon nghieng sai.
accel_ok_ = false;
stats_.accel_rejected++;
}
}
Transform TiltLift(double roll, double pitch, double wheel_radius) {
// Ghep hai phep bien doi:
// tilt : Ry(pitch) * Rx(roll) -- DUNG dau duong.
// Bo loc bu cho ra pitch = atan2(-ax, |a_yz|); voi robot tinh
// nghieng goc theta quanh +Y, gia toc ke doc ax = -g sin(theta),
// az = g cos(theta) => pitch = theta. Do la phep quay body->the
// gioi, tuc dung chieu de dua diem tu base_link ve mat phang ngang.
// Phu dinh o day se lam nghieng GAP DOI thay vi trie^t tieu.
// lift : base_link (tam truc) -> base_footprint (mat dat).
Transform tilt = TransformIdentity();
tilt.rotation = QuaternionFromRPY(roll, pitch, 0.0);
Transform lift = TransformIdentity();
lift.translation = Vector3{0.0, 0.0, wheel_radius};
return TransformCompose(lift, tilt);
}
bool GravityAlign::Align(const PointCloudXYZ& in, const Transform& cam_to_base,
UnixTime stamp, PointCloudXYZ* out) const {
if (!initialized_) return false;
stats_.clouds_in++;
stats_.points_in += in.points.size();
// Ghep ba phep bien doi:
// lift : base_link -> base_footprint (nang len chieu cao banh xe)
// tilt : bu nghieng DO duoc (nghich dao cua nghieng than)
// cam : camera -> base_link (tinh, tu robot.yaml)
const Transform total =
TransformCompose(TiltLift(roll_, pitch_, cfg_.wheel_radius), cam_to_base);
out->header = in.header;
out->header.stamp = stamp;
out->header.frame_id = kBaseFootprintFrame;
out->points.clear();
out->points.reserve(in.points.size());
out->is_dense = true;
for (const PointXYZ& p : in.points) {
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
const Point q = TransformPoint(total, Point{p.x, p.y, p.z});
// Cat dai chieu cao SAU khi xoay: duoi min_height la san, tren max_height
// la tran va den.
if (q.z < cfg_.min_height || q.z > cfg_.max_height) continue;
out->points.push_back(PointXYZ{static_cast<float>(q.x), static_cast<float>(q.y),
static_cast<float>(q.z)});
}
stats_.clouds_out++;
stats_.points_out += out->points.size();
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,89 @@
#include "vslam/perception_pipeline.h"
#include <algorithm>
#include <chrono>
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
PerceptionPipeline::PerceptionPipeline(PerceptionConfig cfg, const Clock& clock)
: cfg_(std::move(cfg)),
clock_(clock),
cam_to_base_(TransformIdentity()),
gravity_(cfg_.gravity),
filter_(cfg_.filter),
cliff_(cfg_.cliff) {}
void PerceptionPipeline::SetCameraExtrinsic(const Transform& cam_to_base) {
cam_to_base_ = cam_to_base;
}
void PerceptionPipeline::FeedImu(const Imu& imu) { gravity_.FeedImu(imu); }
void PerceptionPipeline::FeedOdom(UnixTime stamp, double vx, double vyaw) {
gravity_.FeedOdom(stamp, vx, vyaw);
}
void PerceptionPipeline::Reset() {
gravity_.Reset();
filter_.Reset();
cliff_.Reset();
stats_ = PerceptionStats{};
}
PerceptionOutput PerceptionPipeline::Process(const Image& depth, const CameraInfo& info) {
// steady_clock cho do thoi gian -- KHONG dung UnixTime. Mot buoc NTP giua
// hai moc se cho ra "khung xu ly het -3 giay".
const auto t0 = std::chrono::steady_clock::now();
stats_.frames_in++;
PerceptionOutput out;
out.stamp = depth.header.stamp;
out.roll = gravity_.roll();
out.pitch = gravity_.pitch();
out.tilt_valid = gravity_.valid();
out.accel_ok = gravity_.accel_ok();
// --- Duong cliff: chay tren ANH DEPTH, khong qua cloud ---
// Dat TRUOC duong cloud vi no la duong an toan. Neu duong cloud nem hay
// cham, cliff van da chay xong.
if (cfg_.enable_cliff) {
cliff_.SetTilt(depth.header.stamp, gravity_.roll(), gravity_.pitch(),
gravity_.accel_ok());
CliffResult cr = cliff_.Process(depth, info, cam_to_base_, clock_.Now());
out.cliff_detected = cr.detected;
out.cliff_detail = cr.judged ? "judged" : CliffBailName(cr.bail);
if (!cr.edge_cloud.points.empty()) {
out.cloud_cliff = std::make_shared<const PointCloudXYZ>(std::move(cr.edge_cloud));
}
}
// --- Duong cloud: cho SLAM va cho hien thi ---
if (cfg_.enable_cloud) {
DepthToCloudDense(depth, info, &buf_raw_);
out.cloud_raw = std::make_shared<const PointCloudXYZ>(buf_raw_);
if (filter_.Apply(buf_raw_, depth.header.stamp, &buf_filt_)) {
out.cloud_filtered = std::make_shared<const PointCloudXYZ>(buf_filt_);
if (gravity_.Align(buf_filt_, cam_to_base_, depth.header.stamp, &buf_align_)) {
out.cloud_aligned = std::make_shared<const PointCloudXYZ>(buf_align_);
}
}
}
const double ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - t0)
.count();
stats_.frames_out++;
stats_.last_ms = ms;
stats_.max_ms = std::max(stats_.max_ms, ms);
// Trung binh truot: du de bao cao, khong giu lich su.
stats_.avg_ms += (ms - stats_.avg_ms) * 0.05;
return out;
}
} // namespace vslam

View File

@@ -0,0 +1,15 @@
# Lop an toan.
#
# KHONG them dep ngoai nao, va do la co y: cang it phu thuoc, cang it thu co
# the keo no chet theo. Ban ROS chay rieng mot process voi respawn="true" vi
# ly do do; o day khong con process rieng, nen phai giu dep toi thieu de
# review duoc doc lap.
vslam_add_library(vslam_safety
PUBLIC_HDRS
safety_monitor.h
PUBLIC_DEPS
vslam_common
FIND_DEPS
vslam_common
)

View File

@@ -0,0 +1,196 @@
#ifndef VSLAM_SAFETY_MONITOR_H
#define VSLAM_SAFETY_MONITOR_H
// Lop an toan. Port tu robot_safety/src/safety_monitor_node.cpp cua vSLAM_ws.
//
// ================== PHU THUOC TOI THIEU LA CO Y ==================
// Lop nay CHI can: scan, cmd_vel, bumper, sieu am, co bao vuc.
// KHONG dung: TF, point cloud, ban do, SLAM.
//
// Cang it phu thuoc, cang it thu co the keo no chet theo. Neu no can TF thi
// TF hong se lam hong an toan -- dung dieu ta muon tranh.
//
// ================== KHAC BIET SO VOI BAN ROS ==================
// Ban ROS chay trong mot process rieng voi respawn="true", va do la cach no
// song sot khi slam_core segfault.
//
// Bo ROS thi khong con process rieng nua. Bu lai bang HAI thu:
// 1. Step() la HAM THUAN: khong I/O, khong doc dong ho, khong khoa. Cung
// dau vao cho cung dau ra. Vi vay kiem thu duoc TOAN BO 10 nhanh FSM --
// dieu ban ROS khong lam duoc.
// 2. Luong safety chay SCHED_FIFO cao nhat va KHONG chia se mutex nao voi
// luong slam (Rtabmap::process() chan 100-600 ms). Day la quy tac review,
// compiler khong bat duoc.
//
// ================== 3 LOP BAO VE ==================
// 1. Sieu am -> KINH va GUONG. LiDAR ToF 940nm va depth IR deu XUYEN QUA
// kinh. Day la cach duy nhat phat hien cua kinh.
// 2. LiDAR -> vat can phia truoc trong tam quet
// 3. Bumper -> chan cuoi, bit vung mu Min-Z ~22 cm ma camera khong thay
#include <cstdint>
#include <map>
#include <string>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
// Thu tu o day CHINH LA thu tu uu tien trong FSM. Nhanh nao khop truoc thi
// tra ve ngay, khong xet tiep.
enum class SafetyState : uint8_t {
kEstop = 0, // chot cung, can reset
kBumper = 1, // chot cung, can reset
kNoCmd = 2, // watchdog lenh dieu khien
kUsTimeout = 3, // mat du lieu sieu am
kUsBlocked = 4, // sieu am thay vat gan -- co the la KINH
kCliffStop = 5, // vuc phia truoc: chan TIEN, cho lui va xoay
kScanTimeout = 6, // mat du lieu LiDAR
kScanSparse = 7, // scan van toi nhung quat truoc khong con tia dung duoc
kScanStop = 8, // vat can gan -- chan tien
kScanSlow = 9, // vat can vua -- giam toc
kOk = 10,
};
const char* SafetyStateName(SafetyState s);
struct SafetyConfig {
// --- LiDAR ---
double stop_distance = 0.35;
double slow_distance = 0.80;
double slow_factor = 0.4;
double front_angle = 0.5; // nua goc quat truoc, rad (~28.6 do)
// Nguong duoi lay MAX cua hai nguon: cai driver khai, va cai ta biet la
// dung. Driver LakiBeam khai range_min = 0.0 (bug), ta van dung 0.05.
double min_valid_range = 0.05;
// So tia DUNG DUOC toi thieu trong quat truoc. Duoi nguong nay thi scan
// khong dang tin, du ban tin van toi dung nhip.
int min_front_rays = 20;
// --- Sieu am ---
double us_stop_distance = 0.30;
// --- Vuc ---
bool enable_cliff_stop = true;
double cliff_timeout = 1.0;
// Giu chan them bao lau sau lan bao vuc CUOI. Xem khoi comment lon trong
// safety_monitor.cc -- con so nay da tra gia bang mot lan di vao bac thang.
double cliff_hold = 3.0;
// --- Thoat khi bumper dang chot ---
//
// ⚠️ Chot bumper la dung -- va cham DA xay ra nen phai co nguoi xac nhan.
// Nhung chot khong duoc bien thanh BE TAC.
//
// Phep do bumper (ca that lan mo phong) kiem vanh robot o vi tri HIEN TAI.
// Robot dang ti vao vat can thi bumper van cham, nen no chot lai ngay sau
// moi lan reset. Cam het chuyen dong thi khong bao gio lui ra duoc, ma
// khong lui ra duoc thi khong bao gio reset duoc -- do la mot vong kin.
//
// Da do: sau khi lui vao tuong, robot khong nhuc nhich duoc 0.000 m theo
// BAT KY huong nao, qua 2 lan reset deu tra HTTP 200.
//
// Nen khi dang chot: TIEN bi ep ve 0 tuyet doi, con LUI va XOAY duoc phep o
// toc do thoat. Phia sau KHONG co cam bien nao che (quat LiDAR chi phu
// +-front_angle phia truoc), nen toc do nay phai cham.
double escape_linear = 0.10; // m/s, CHI cho chieu lui
double escape_angular = 0.4; // rad/s
// --- Chung ---
double sensor_timeout = 1.0;
double cmd_timeout = 0.5;
double max_linear = 0.35;
double max_angular = 0.8;
};
// Moi thu FSM can, dua vao tuong minh. KHONG co con tro toi driver, khong co
// dong ho -- do la ly do Step() kiem thu duoc.
struct SafetyInputs {
UnixTime now;
// Scan da qua ScanSanitizer. nullptr = chua co scan nao.
const LaserScan* scan = nullptr;
UnixTime scan_stamp;
const Twist* cmd = nullptr; // nullptr = chua co lenh nao
UnixTime cmd_stamp;
bool have_bumper = false;
bool bumper = false;
UnixTime bumper_stamp;
bool have_cliff = false;
bool cliff = false;
UnixTime cliff_stamp;
// Detector co THUC SU phan xet duoc khong, hay day la fail-safe luc mu.
//
// Hai thu nay khac nhau VE CHAT: "toi THAY mot cai vuc" so voi "toi khong
// thay san nen gia dinh co vuc". Chi cai thu hai moi co the duoc mot vat
// can gan GIAI THICH -- xem nhanh 4 trong Step().
bool cliff_judged = true;
// Tam gan nhat cua cua so nhin san (`cliff_detect.min_dist`). Duoi tam do
// camera khong thay gi -- vung mu HINH HOC, khong phai lua chon tham so.
double cliff_window_min = 1.10;
// Ten cam bien -> khoang cach (m). Rong = khong co sieu am nao lap dat.
std::map<std::string, double> ultrasonic;
UnixTime us_stamp;
};
struct SafetyOutput {
Twist cmd; // lenh DA loc, gui thang xuong base
SafetyState state = SafetyState::kOk;
std::string detail;
// So lieu quat truoc -- de hien thi va chan doan.
double min_front = 0.0; // INFINITY neu khong do duoc gi
int front_rays = 0; // tong so tia PHU song quat truoc
int front_blanked = 0; // so tia mang sentinel range_max + 1
int front_usable = 0; // front_rays - front_blanked
double us_min = 0.0;
};
struct SafetyStats {
uint64_t steps = 0;
uint64_t blocked_steps = 0; // so buoc lenh bi thay doi
std::map<SafetyState, uint64_t> state_counts;
};
class SafetyMonitor {
public:
explicit SafetyMonitor(SafetyConfig cfg = SafetyConfig());
// HAM THUAN: cung dau vao -> cung dau ra. Khong I/O, khong doc dong ho.
//
// Trang thai duy nhat mang qua cac lan goi la hai cai CHOT (e-stop, bumper)
// va moc thoi gian bao vuc cuoi -- ba thu do la ban chat co trang thai.
SafetyOutput Step(const SafetyInputs& in);
// Thay service std_srvs/Trigger cua ban ROS.
void Reset(); // bo chot bumper
void SetEstop(bool on);
bool estop() const { return estop_; }
bool bumper_latched() const { return bumper_latched_; }
const SafetyStats& stats() const { return stats_; }
private:
// Quet quat truoc. Tach rieng de kiem duoc doc lap voi FSM.
void ScanFan(const LaserScan& scan, SafetyOutput* out) const;
SafetyConfig cfg_;
bool estop_ = false;
bool bumper_latched_ = false;
// Lan doc bumper gan nhat, de Reset() noi duoc rang chot se dat lai ngay.
bool last_bumper_ = false;
UnixTime last_cliff_true_;
bool have_cliff_true_ = false;
SafetyStats stats_;
};
} // namespace vslam
#endif // VSLAM_SAFETY_MONITOR_H

View File

@@ -0,0 +1,323 @@
#include "vslam/safety_monitor.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "vslam/log.h"
namespace vslam {
const char* SafetyStateName(SafetyState s) {
switch (s) {
case SafetyState::kEstop: return "ESTOP";
case SafetyState::kBumper: return "BUMPER";
case SafetyState::kNoCmd: return "NO_CMD";
case SafetyState::kUsTimeout: return "US_TIMEOUT";
case SafetyState::kUsBlocked: return "US_BLOCKED";
case SafetyState::kCliffStop: return "CLIFF_STOP";
case SafetyState::kScanTimeout: return "SCAN_TIMEOUT";
case SafetyState::kScanSparse: return "SCAN_SPARSE";
case SafetyState::kScanStop: return "SCAN_STOP";
case SafetyState::kScanSlow: return "SCAN_SLOW";
case SafetyState::kOk: return "OK";
}
return "?";
}
SafetyMonitor::SafetyMonitor(SafetyConfig cfg) : cfg_(std::move(cfg)) {}
void SafetyMonitor::Reset() {
// ⚠️ Reset thanh cong KHONG co nghia la robot chay tiep duoc.
//
// Neu bumper van dang cham, chot se dat lai ngay o buoc sau. Truoc day reset
// tra ve am tham va nguoi van hanh bam lai nhieu lan ma khong hieu vi sao --
// cung lop loi voi chuyen nhan web noi "SLAM dang chay" khi no dang tat.
if (last_bumper_) {
VSLAM_WARN("safety: da bo chot bumper NHUNG bumper VAN dang cham -- no se "
"chot lai ngay. Lui ra khoi vat can truoc (lenh lui va xoay van "
"duoc phep khi dang chot).");
} else {
VSLAM_INFO("safety: da bo chot bumper");
}
bumper_latched_ = false;
}
void SafetyMonitor::SetEstop(bool on) {
if (on != estop_) {
VSLAM_WARN("safety: e-stop " << (on ? "BAT" : "GO"));
}
estop_ = on;
}
void SafetyMonitor::ScanFan(const LaserScan& scan, SafetyOutput* out) const {
double min_front = std::numeric_limits<double>::infinity();
int front_rays = 0;
int front_blanked = 0;
// Nguong duoi lay MAX cua hai nguon: cai driver khai, va cai ta biet la
// dung. Driver LakiBeam khai range_min = 0.0, ta van dung 0.05.
const double rmin = std::max(cfg_.min_valid_range,
static_cast<double>(scan.range_min));
for (size_t i = 0; i < scan.ranges.size(); ++i) {
const double a = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
if (std::fabs(a) > cfg_.front_angle) continue;
++front_rays;
const double r = scan.ranges[i];
// ==================================================================
// PHAN BIET "BI BLANK" VOI "KHONG CO GI TRONG TAM".
//
// Sector mask blank tia bang range_max + 1.0 -- tuc HUU HAN va LON HON
// range_max. Tia khong co phan xa that thi la inf, con tia khong do duoc
// thi la NaN.
//
// Neu dem nham hai thu nay lam mot thi robot dung giua sanh trong:
// khong vat nao trong 40 m -> moi tia inf -> "khong tia nao hop le" ->
// SCAN_SPARSE -> dung vinh vien giua mot can phong trong khong.
// ==================================================================
if (std::isfinite(r) && r > scan.range_max) {
++front_blanked;
continue;
}
if (!std::isfinite(r) || r < rmin) {
continue; // khong co phan xa, hoac qua gan -> khong dung de do
}
min_front = std::min(min_front, static_cast<double>(r));
}
out->front_rays = front_rays;
out->front_blanked = front_blanked;
out->front_usable = front_rays - front_blanked;
out->min_front = min_front;
}
SafetyOutput SafetyMonitor::Step(const SafetyInputs& in) {
SafetyOutput out; // cmd mac dinh = dung yen
out.us_min = std::numeric_limits<double>::infinity();
out.min_front = std::numeric_limits<double>::infinity();
stats_.steps++;
// Cap nhat chot bumper. Bumper la va cham DA XAY RA nen phai co nguoi xac
// nhan moi bo chot.
if (in.have_bumper) last_bumper_ = in.bumper;
if (in.have_bumper && in.bumper && !bumper_latched_) {
bumper_latched_ = true;
VSLAM_ERROR("safety: BUMPER KICH HOAT -- dung va chot. Goi reset de bo chot.");
}
// Ghi moc lan bao vuc cuoi. Xem khoi comment o nhanh CLIFF_STOP.
if (in.have_cliff && in.cliff) {
last_cliff_true_ = in.cliff_stamp;
have_cliff_true_ = true;
}
if (in.scan != nullptr) ScanFan(*in.scan, &out);
auto finish = [&](SafetyState s, std::string detail) {
out.state = s;
out.detail = std::move(detail);
stats_.state_counts[s]++;
if (s != SafetyState::kOk) stats_.blocked_steps++;
return out;
};
// --- 1. Chot cung ---------------------------------------------------
if (estop_) return finish(SafetyState::kEstop, "dung khan cap");
if (bumper_latched_) {
// ⚠️ Bumper KHONG BIET vat can o dau.
//
// `BumperReading` chi mang mot mat na cong tac; mo phong dung dung mot bit,
// va robot that cung khong hua se noi duoc huong. Nen "chan tien, cho lui"
// la an toan GIA: da do mot lan robot LUI vao tuong, va luc do duong thoat
// chinh la TIEN -- dung chieu bi chan.
//
// Thu biet huong la LiDAR. Nen giu nguyen cong quat truoc cho chieu tien,
// y het luc binh thuong, chi ha toc do xuong muc thoat. Chieu lui va phep
// xoay mo, dung bang phoi nhiem cua luc binh thuong (phia sau von khong co
// cam bien nao che).
out.cmd = Twist{};
if (in.cmd != nullptr) {
out.cmd.linear.x = std::max(-cfg_.escape_linear,
std::min(cfg_.escape_linear, in.cmd->linear.x));
out.cmd.angular.z =
std::max(-cfg_.escape_angular,
std::min(cfg_.escape_angular, in.cmd->angular.z));
// Tien chi duoc phep khi LiDAR XAC NHAN phia truoc trong. Khong co scan
// thi khong xac nhan duoc -> chan, khong doan.
if (out.cmd.linear.x > 0.0 &&
(in.scan == nullptr || out.front_usable < cfg_.min_front_rays ||
out.min_front < cfg_.stop_distance)) {
out.cmd.linear.x = 0.0;
}
}
// Chi tiet phai phan biet "DANG cham" voi "da cham roi roi ra": hai cai
// doi hoi hai hanh dong khac nhau cua nguoi van hanh.
return finish(SafetyState::kBumper,
(in.have_bumper && in.bumper)
? "bumper DANG cham -- lai cham de thoat roi reset"
: "bumper da cham -- can reset");
}
// --- 2. Watchdog lenh dieu khien ------------------------------------
if (in.cmd == nullptr ||
SecondsBetween(in.now, in.cmd_stamp) > cfg_.cmd_timeout) {
return finish(SafetyState::kNoCmd, "khong co lenh dieu khien");
}
// --- 3. Sieu am: KINH va GUONG --------------------------------------
// LiDAR ToF 940 nm va depth IR deu XUYEN QUA kinh. Day la cach duy nhat
// phat hien cua kinh -- khong thuat toan SLAM nao giai duoc viec nay.
// BA NGU NGHIA cua mot lan doc, y het tia laser:
// huu han = khoang cach do duoc
// inf = khong co tieng vong -> hanh lang RONG, HOP LE
// NaN = cam bien KHONG TRA LOI
// Gop NaN voi inf la xoa mat mot nhanh an toan.
int us_answering = 0;
for (const auto& kv : in.ultrasonic) {
if (std::isnan(kv.second)) continue; // khong tra loi, khong tinh
us_answering++;
out.us_min = std::min(out.us_min, kv.second);
}
if (!in.ultrasonic.empty()) {
// Hai kieu HONG KHAC NHAU, deu phai ra US_TIMEOUT:
//
// (a) MCU NGUNG gui ban ghi -> stamp cu dan.
// (b) MCU VAN gui nhung KHONG dau do nao tra loi -> stamp luon moi,
// nhung du lieu vo dung. Day la day cam bien bi dut, hoac ca cum
// chet. Truoc khi co nhanh nay, (b) HOAN TOAN VO HINH: map rong
// trong y het "khong lap sieu am", va robot chay tiep nhu khong co
// chuyen gi. Da phat hien bang kich ban hoi quy `us_dead`.
if (SecondsBetween(in.now, in.us_stamp) > cfg_.sensor_timeout) {
VSLAM_ERROR_THROTTLE(2.0, "safety: mat du lieu sieu am -> dung");
return finish(SafetyState::kUsTimeout, "mat du lieu sieu am");
}
if (us_answering == 0) {
VSLAM_ERROR_THROTTLE(2.0,
"safety: co " << in.ultrasonic.size()
<< " dau do sieu am nhung KHONG cai nao tra loi "
"-> dung. Kiem day cam bien.");
return finish(SafetyState::kUsTimeout, "sieu am khong tra loi");
}
}
if (out.us_min < cfg_.us_stop_distance) {
VSLAM_WARN_THROTTLE(1.0, "safety: sieu am " << out.us_min << " m (< "
<< cfg_.us_stop_distance
<< ") -- co the la KINH. Dung.");
return finish(SafetyState::kUsBlocked, "sieu am chan -- co the la kinh");
}
// --- 4. VUC / BAC THANG ----------------------------------------------
// KHONG chot (khong latch) nhu bumper: bumper la va cham DA XAY RA nen phai
// co nguoi xac nhan; vuc la thu robot co the tu lui ra khoi. Chot lai se lam
// robot ket cung truoc mep ma khong ai cuu.
//
// Chi chan TIEN, cho phep LUI va XOAY -- do la duong thoat duy nhat.
//
// Giu chan them cliff_hold giay sau lan bao vuc CUOI, khong chi khi co dang
// bat. Vuc bien mat khoi tam nhin cua camera khi lai gan hon 1.10 m, va
// CLIFF_STOP chi kich hoat dung khoanh khac co lenh tien -- robot xoay roi
// tien tung dot ngan nen lot qua duoc khe do.
// DA TRA GIA BANG MOT LAN DI THANG VAO BAC THANG.
const bool cliff_recent =
have_cliff_true_ &&
SecondsBetween(in.now, last_cliff_true_) <= cfg_.cliff_hold &&
SecondsBetween(in.now, in.cliff_stamp) <= cfg_.cliff_timeout + cfg_.cliff_hold;
const bool cliff_now = in.have_cliff && in.cliff &&
SecondsBetween(in.now, in.cliff_stamp) <= cfg_.cliff_timeout;
// ============ MU DA GIAI THICH DUOC ============
//
// Neu detector KHONG phan xet duoc (fail-safe) VA LiDAR thay mot vat can
// GAN HON diem bat dau cua so nhin san, thi su mu do da co loi giai: cua so
// nhin san nam SAU vat can, nen tat nhien camera khong thay san.
//
// Luc do dung robot vi "co the co vuc" la thua: chinh vat can do da kich
// SCAN_SLOW/SCAN_STOP o nhanh 6-7, tuc robot van duoc xu ly dung.
//
// ⚠️ Chi ap khi `!cliff_judged`. Neu detector THAY vuc that thi vat can
// khong giai thich duoc gi ca -- vuc va vat can co the cung ton tai, va
// CLIFF_STOP phai thang.
//
// Do duoc tren ban do benh vien that: robot cach tuong 0.5 m, cua so
// 1.1-2.5 m nam hoan toan sau tuong -> `few_samples` -> fail-safe -> robot
// ket cung. Khong co nhanh nay thi khong di duoc trong bat ky toa nha nao.
const bool blind_explained_by_obstacle =
!in.cliff_judged && std::isfinite(out.min_front) &&
out.min_front < in.cliff_window_min;
if (cfg_.enable_cliff_stop && (cliff_recent || cliff_now) &&
!blind_explained_by_obstacle && in.cmd->linear.x > 0.0) {
out.cmd = *in.cmd;
out.cmd.linear.x = 0.0; // chan tien, GIU angular de con xoay ra
out.cmd.angular.z = std::max(-cfg_.max_angular,
std::min(cfg_.max_angular, out.cmd.angular.z));
VSLAM_ERROR_THROTTLE(1.0,
"safety: VUC phia truoc -- chan tien. Lui hoac xoay de "
"thoat. Cam bien nay MU duoi ~1.1 m.");
return finish(SafetyState::kCliffStop, "vuc phia truoc -- chan tien");
}
// --- 5. LiDAR --------------------------------------------------------
if (in.scan != nullptr &&
SecondsBetween(in.now, in.scan_stamp) > cfg_.sensor_timeout) {
VSLAM_ERROR_THROTTLE(2.0, "safety: mat du lieu LiDAR -> dung");
return finish(SafetyState::kScanTimeout, "mat du lieu LiDAR");
}
// --- 6. Scan den deu nhung QUAT TRUOC BI CAT MAT ---------------------
// Khac han SCAN_TIMEOUT: ban tin van toi dung nhip, chi la quat truoc khong
// con tia dung duoc. Hai nguyen nhan:
// front_rays thap -> angle_min/max khong phu quat truoc
// blanked ~ toan bo -> sector mask cat nham bounds
//
// Sanh trong (moi tia inf) KHONG duoc tinh la loi: tia van phu song, chi la
// khong co phan xa. Do la ly do phai tru rieng phan bi blank.
if (in.scan != nullptr && out.front_usable < cfg_.min_front_rays) {
VSLAM_ERROR_THROTTLE(2.0,
"safety: quat truoc chi con "
<< out.front_usable << " tia dung duoc ("
<< out.front_rays << " tia phu song, "
<< out.front_blanked << " bi blank; can >= "
<< cfg_.min_front_rays
<< ") -- KHONG TIN DUOC, dung.");
return finish(SafetyState::kScanSparse, "quat truoc khong du tia dung duoc");
}
// --- 7. Vat can phia truoc -------------------------------------------
out.cmd = *in.cmd;
SafetyState state = SafetyState::kOk;
std::string detail;
if (in.scan != nullptr && out.cmd.linear.x > 0.0) { // chi xet khi dang tien
if (out.min_front < cfg_.stop_distance) {
out.cmd.linear.x = 0.0;
state = SafetyState::kScanStop;
detail = "vat can gan -- dung tien";
VSLAM_WARN_THROTTLE(1.0, "safety: vat can " << out.min_front
<< " m phia truoc -- dung tien");
} else if (out.min_front < cfg_.slow_distance) {
out.cmd.linear.x *= cfg_.slow_factor;
state = SafetyState::kScanSlow;
detail = "vat can vua -- giam toc";
}
}
// --- 8. Chan van toc --------------------------------------------------
out.cmd.linear.x = std::max(-cfg_.max_linear,
std::min(cfg_.max_linear, out.cmd.linear.x));
out.cmd.angular.z = std::max(-cfg_.max_angular,
std::min(cfg_.max_angular, out.cmd.angular.z));
return finish(state, std::move(detail));
}
} // namespace vslam

View File

@@ -0,0 +1,29 @@
# Bo mo phong -- thay Gazebo.
#
# Dep ngoai: chi yaml-cpp (doc map.yaml). Khong OpenGL, khong vat ly 3D,
# khong model database. Do la ca diem: Jetson AGX khong co gi de chay Gazebo,
# ma thu can kiem chung cho duong ong 2.5D chi la ban do 2D + raycast.
find_package(yaml-cpp REQUIRED)
vslam_add_library(vslam_sim
PUBLIC_HDRS
sim_source.h
occupancy_map_io.h
gazebo_world.h
PUBLIC_DEPS
vslam_common
vslam_drivers
FIND_DEPS
vslam_common
vslam_drivers
)
if(TARGET yaml-cpp::yaml-cpp)
target_link_libraries(vslam_sim PRIVATE yaml-cpp::yaml-cpp)
elseif(TARGET yaml-cpp)
target_link_libraries(vslam_sim PRIVATE yaml-cpp)
else()
target_include_directories(vslam_sim SYSTEM PRIVATE ${YAML_CPP_INCLUDE_DIR})
target_link_libraries(vslam_sim PRIVATE ${YAML_CPP_LIBRARIES})
endif()

View File

@@ -0,0 +1,152 @@
#ifndef VSLAM_GAZEBO_WORLD_H
#define VSLAM_GAZEBO_WORLD_H
// Doc file `.world` cua Gazebo va dung the gioi mo phong tu no.
//
// ================== VI SAO DOC WORLD CHU KHONG DOC .db ==================
// Luoi chiem dung xuat tu `map_hospital.db` co goc o cho robot BAT DAU phien
// quet, con file world o he toa do RIENG cua Gazebo. Do duoc: world trai rong
// x -12.4..12.4, y -31.9..19.5; luoi tu .db la x -17.1..9.2, y -49.6..8.5 --
// lech ~18 m theo y.
//
// Nen khong the "dan do dac cua world len luoi tu .db". Doc THANG world lam
// nguon su that thi ca ba thu -- luoi cho sim, mesh cho khung 3D, va tu the
// do dac -- deu o MOT he toa do, va khong can mot phep can chinh nao.
//
// ================== KHONG CAN PARSER XML DAY DU ==================
// Cau truc `.world` cua Gazebo rat deu:
//
// <model name="X">
// <include>
// <uri>model://Ten</uri>
// <static>true</static>
// <pose>x y z roll pitch yaw</pose>
// </include>
// </model>
//
// va `model.sdf` cua tung model chi tro toi mot file `.obj`. Mot bo quet the
// ~100 dong doc duoc ca hai, va tranh keo them mot dep XML vao `vslam_sim` --
// lib nay hien chi phu thuoc `vslam_common`.
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
// Mot the hien model trong world.
struct WorldModel {
std::string name; // ten the hien, vd "MetalCabinet_3"
std::string model_name; // ten model, vd "MetalCabinet"
// Duong dan tuyet doi toi mesh va chat lieu; rong neu khong tim thay.
std::string visual_obj;
std::string collision_obj;
// Tu the trong he toa do WORLD.
double x = 0.0, y = 0.0, z = 0.0;
double roll = 0.0, pitch = 0.0, yaw = 0.0;
// ⚠️ He so ti le cua `<mesh><scale>` trong model.sdf.
//
// File OBJ khong khai don vi, nen Gazebo lay ti le TU SDF. Trong bo model
// nay 27 model dung `<scale>`, phan lon la 0.01 (mesh ve bang CENTIMET) va
// co ca 0.00817 va `1 1 0.95`.
//
// Bo qua the nay lam mot chiec xe day 2.4 m thanh 236 m -- da do:
// `CGMClassic` mot minh ra bao loi 239 x 111 m, va ca the gioi phinh tu
// 25x51 m len 263x146 m.
double sx = 1.0, sy = 1.0, sz = 1.0;
};
struct GazeboWorld {
std::string world_path;
std::vector<WorldModel> models;
// Thu muc goc chua cac model da phan giai, de web phuc vu file tinh.
std::vector<std::string> model_roots;
};
// Doc `.world` va phan giai `model://` qua `model_paths`.
//
// `model_paths`: danh sach thu muc, moi cai chua cac thu muc model con (giong
// GAZEBO_MODEL_PATH). Rong thi thu $GAZEBO_MODEL_PATH roi ~/.gazebo/models.
//
// Model khong phan giai duoc KHONG lam ham that bai -- `ground_plane` va `sun`
// la built-in cua Gazebo, khong co tren dia, va mot the gioi thieu hai cai do
// van dung duoc. Chung duoc bo qua va dem vao `skipped`.
StatusResponse LoadGazeboWorld(const std::string& world_path,
const std::vector<std::string>& model_paths,
GazeboWorld* out, size_t* skipped = nullptr);
// Raster hoa mesh VA CHAM cua world thanh luoi chiem dung 2D.
//
// Chi lay tam giac nam trong dai do cao [z_min, z_max] so voi SAN: do la dai
// ma LiDAR 2D thuc su quet. Lay het moi do cao se bien ca mat san thanh vat
// can, va lay qua cao se bo lot ban ghe.
//
// `resolution` met/o. `pad` la vien trong them quanh bao loi, tinh bang met.
struct WorldRasterOptions {
double resolution = 0.05;
double z_min = 0.05; // tren mat san mot chut, de khong quet trung san
double z_max = 1.20; // duoi tran, tren dinh phan lon do dac
double pad = 1.0;
};
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out);
// ---------------------------------------------------------------------------
// Xuat hinh hoc cho khung 3D
// ---------------------------------------------------------------------------
//
// Khung 3D khong tai duoc file mesh goc: trinh duyet khong co bo doc COLLADA
// offline, va 149 texture PNG cua bo model nay tong cong 74 MB -- gui tung ay
// moi lan mo trang la khong chap nhan duoc.
//
// Nen phia C++ (von DA co bo doc) gui thang TAM GIAC. Hinh hoc duoc gop theo
// TEN MODEL chu khong theo the hien: world co 181 the hien nhung chi ~69 model
// khac nhau, nen 42 chiec ghe chi ton mot ban hinh hoc.
struct WorldMeshGeom {
std::string model_name;
// Mau than vat the, lay tu TEXTURE cua chinh model (xem
// tools/gen_model_colors.py). Mac dinh la xam men su -- dung cho
// KitchenSink va Toilet, hai model duy nhat trong world khong co texture.
uint8_t r = 214, g = 214, b = 210;
// 9 float moi tam giac (x,y,z) x 3, trong he MODEL: da ap `<scale>` nhung
// CHUA ap yaw/tinh tien cua the hien -- do la viec cua instance.
std::vector<float> tri;
};
struct WorldMeshInstance {
uint32_t geom = 0;
float x = 0, y = 0, z = 0, yaw = 0;
};
struct WorldMeshes {
std::vector<WorldMeshGeom> geoms;
std::vector<WorldMeshInstance> instances;
};
// `visual = true` lay mesh HIEN THI (nhieu tam giac, dep hon); false lay mesh
// VA CHAM, von it tam giac va khop chinh xac voi luoi chiem dung.
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
WorldMeshes* out);
// Gan mau cho tung hinh hoc tu bang `model_colors.json`.
//
// Thieu file hoac thieu model trong file KHONG phai loi: vat the do giu mau
// mac dinh. Tra ve so hinh hoc da duoc gan mau.
size_t ApplyModelColors(const std::string& json_path, WorldMeshes* io);
// Dong goi `WorldMeshes` thanh khoi nhi phan cho trinh duyet.
//
// "VSLW" | u32 version | u32 n_geom | u32 n_inst
// moi geom : u32 name_len | name | u8 r,g,b | u32 n_tri | n_tri*9 f32
// moi inst : u32 geom | f32 x,y,z,yaw
void EncodeWorldMeshes(const WorldMeshes& in, std::string* out);
} // namespace vslam
#endif // VSLAM_GAZEBO_WORLD_H

View File

@@ -0,0 +1,49 @@
#ifndef VSLAM_OCCUPANCY_MAP_IO_H
#define VSLAM_OCCUPANCY_MAP_IO_H
// Doc/ghi occupancy grid dang PGM + YAML -- dung dinh dang cua map_server ROS.
//
// Giu dinh dang cu co y: nguoi dung da quen no, `rtabmap-export` sinh ra no,
// va moi map cu trong vSLAM_ws/maps/ deu o dang nay. Bo ROS khong co nghia la
// phai bo moi thu ROS cham vao.
//
// map.yaml:
// image: map.pgm
// resolution: 0.05
// origin: [-5.0, -13.0, 0.0]
// negate: 0
// occupied_thresh: 0.65
// free_thresh: 0.196
//
// PGM P5 (nhi phan, 8 bit): 0 = den = bi chiem, 255 = trang = trong.
// Quy uoc nay NGUOC voi truc quan, va dao nguoc no la mot trong nhung loi
// hay gap nhat khi doc map -- ket qua la robot coi tuong la duong di.
#include <string>
#include "vslam/vslam_common.h"
namespace vslam {
struct MapLoadResult {
OccupancyGrid grid;
std::string image_path;
double occupied_thresh = 0.65;
double free_thresh = 0.196;
};
// Doc map.yaml va file PGM di kem. Duong dan anh trong YAML duoc hieu la
// tuong doi so voi thu muc chua YAML.
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out);
// Ghi ra PGM + YAML. Dung cho tools/vslam_map_export.
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
const std::string& yaml_path);
// Sinh mot the gioi tong hop: hanh lang chinh + phong hai ben.
// Dung khi chua co map that, de chay thu duong ong ngay lap tuc.
OccupancyGrid MakeSyntheticWorld(uint32_t width, uint32_t height, float resolution);
} // namespace vslam
#endif // VSLAM_OCCUPANCY_MAP_IO_H

View File

@@ -0,0 +1,339 @@
#ifndef VSLAM_SIM_SOURCE_H
#define VSLAM_SIM_SOURCE_H
// Bo mo phong -- thay Gazebo.
//
// ================== VI SAO KHONG PHAI GAZEBO ==================
// Bo ROS la mat gazebo_ros. Nhung ke ca con ROS thi Gazebo cung khong hop:
// world `hospital_three_floors.world` co 541 instance model, va `gpu_ray`
// 1081 tia @25 Hz duoc chon vi may dev co RTX 4060 -- Jetson AGX khong co thu
// do de tieu.
//
// Cai thuc su can de kiem chung duong ong 2.5D chi la: mot ban do 2D, mot
// robot vi sai, va phep raycast. Do la vai tram dong, chay duoc tren CPU, va
// KHONG can card do hoa.
//
// ================== VI SAO NO VUA VAN VAO KIEN TRUC ==================
// SimSource implement CHINH cac interface driver, y het ReplaySource. Nen
// vslam_node khong phan biet duoc ba nguon: phan cung that, file .vsr, hay mo
// phong. Khong co mot nhanh `if (sim)` nao trong logic -- day dung la dieu ma
// docs/ARCHITECTURE.md cua repo cu goi la "nguyen tac parity sim <-> real",
// nhung lan nay no duoc bao dam boi kieu du lieu chu khong boi ky luat.
//
// ================== CAI GI KHONG DUOC MO PHONG ==================
// docs/SIM_VS_REAL.md cua repo cu liet ke chinh xac nhung cho Gazebo "noi
// doi". Bo mo phong nay con noi doi NHIEU HON, va phai noi ro:
// * Khong co IR speckle, khong rolling shutter. Depth dropout CO mo phong
// nhung bang xac suat deu, tho hon nhieu so voi that (that thi tap trung
// o be mat toi, be mat bong va mep vat the).
// * Khong co anh infra1/infra2 -- stereo_odometry khong kiem duoc o day.
// * LiDAR khong bi nhieu boi be mat den hay guong. Khong co o kinh/guong
// (trong suot voi LiDAR VA voi depth), khong co vat can nho ra (mep ban).
// * Bien dang anh (distortion) khong mo phong: K la pinhole hoan hao.
// Nhung gi mo phong duoc KIEM CHUNG: dong hoc vi sai, tich phan odometry,
// EKF, SLAM 2D, lop an toan theo scan, camera depth (raycast 2.5D, Z-depth,
// co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va
// toan bo duong ong du lieu.
#include <memory>
#include <string>
#include <vector>
#include "vslam/clock.h"
#include "vslam/gazebo_world.h"
#include "vslam/driver_interfaces.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct SimConfig {
// Ban do. Rong = dung MakeSyntheticWorld().
std::string map_yaml;
// File `.world` cua Gazebo. Uu tien hon `map_yaml`: luoi duoc raster hoa
// THANG tu mesh va cham, nen luoi cua sim, mesh cua khung 3D va tu the do
// dac deu o MOT he toa do -- xem `vslam/gazebo_world.h`.
std::string world_path;
std::vector<std::string> world_model_paths;
uint32_t synthetic_width = 600;
uint32_t synthetic_height = 400;
float synthetic_resolution = 0.05f;
// Vi tri xuat phat trong frame map.
double start_x = 0.0;
double start_y = 0.0;
double start_yaw = 0.0;
// Hat giong RNG. Co dinh => cung mot kich ban cho cung mot file .vsr, byte
// giong byte. Do la dieu kien de `tools/regress.sh` so ket qua duoc: neu
// ban ghi doi moi lan sinh thi moi khac biet deu la nhieu.
uint32_t seed = 1234;
// Hinh hoc robot. PHAI khop robot.yaml.
double wheel_radius = 0.075;
double wheel_separation = 0.36;
// LiDAR -- khop cau hinh LakiBeam 1L that.
double lidar_rate_hz = 25.0;
uint32_t lidar_samples = 1081;
double lidar_fov_rad = 4.712389; // 270 do
double lidar_range_min = 0.05;
double lidar_range_max = 40.0;
double lidar_x = 0.24; // vi tri tren robot, khop laser_joint
double lidar_z = 0.125;
double lidar_noise_stddev = 0.01;
// ================== CAMERA DEPTH ==================
// Gazebo mo phong depth bang libgazebo_ros_openni_kinect. Bo mo phong nay
// lam dieu tuong duong bang raycast 2.5D: ban do chiem dung duoc DUNG THANH
// tuong cao `wall_height`, va moi o co mot DO CAO SAN rieng.
//
// Do cao san la thu cho phep kiem `cliff_detect` -- o nao co floor_height
// AM la mot bac hut xuong. Khong co lop nay thi san tuyet doi phang va
// cliff_detect khong co gi de phat hien.
bool enable_depth_camera = true;
double camera_rate_hz = 30.0;
uint32_t depth_width = 640;
uint32_t depth_height = 480;
double depth_hfov_rad = 1.204; // 69 do, khop D410 that
double depth_near = 0.22; // Min-Z: vung mu truoc mui robot
double depth_far = 10.0;
// ============ NHIEU DEPTH: MO HINH STEREO ============
// sigma_d = sqrt(floor^2 + (d^2 * sigma_disp / (f*B))^2)
//
// Sai so tang theo BINH PHUONG khoang cach, vi depth stereo suy tu DO LECH
// PIXEL chu khong do truc tiep. Mot hang so (ban cu: 7 mm) sai o DANG chu
// khong chi o tri -- gan thi bi quan, xa thi lac quan gap 10 lan.
//
// `f` KHONG khai o day: no suy ra tu `depth_hfov_rad` va `depth_width`, de
// khong co hai nguon cho cung mot so.
//
// ⚠️ CA HAI so duoi CHUA XAC MINH tren thiet bi that:
// * `depth_baseline` 50 mm la UOC LUONG, khong co trong ban ghi datasheet
// nao. Sai 20% thi moi con so nhieu sai 20%.
// * `depth_disparity_noise_px` 0.1 px la gia tri DIEN HINH cua stereo
// block-matching, khong phai thong so do duoc cua D410.
// Do bang `rs-enumerate-devices -c` khi cam camera roi sua o day.
double depth_disparity_noise_px = 0.1;
double depth_baseline = 0.050; // m, khoang cach hai mat IR
// San nhieu gan: dien tu cam bien va luong tu hoa, khong mat khi d -> 0.
double depth_noise_floor = 0.002;
// Ty le diem anh KHONG co gia tri tra ve, mo phong depth dropout cua D410.
// Camera that mat diem o be mat toi, be mat bong, va o mep vat the.
double depth_dropout_rate = 0.0;
// Mo phong RUT DAY LiDAR: ngung phat scan tu giay `lidar_cut_at` trong
// bao lau. 0 = khong cat.
//
// Day la cach duy nhat chay duoc nhanh SCAN_TIMEOUT end-to-end. Tieu chi
// P4 ghi "rut day LiDAR -> SCAN_TIMEOUT < 1.1 s" nhung truoc kich ban nay
// khong co cach nao DO duoc no ngoai viec rut day that.
double lidar_cut_at = 0.0;
double lidar_cut_for = 0.0;
uint32_t depth_decimate = 2; // 640x480 -> 320x240, nhu crop_decimate
// Vi tri camera tren robot. Khop camera_joint cua robot.urdf.xacro.
double camera_x = 0.19;
double camera_z = 0.80;
double camera_pitch = 0.2618; // 15 do chuc xuong
double wall_height = 2.0; // tuong cao bao nhieu, tinh tu san
// ============ SIEU AM ============
// Dan cam bien phia truoc, goc tinh tu +X cua than (rad).
//
// ⚠️ Sieu am ton tai CHI vi mot ly do: KINH. Kinh vo hinh voi LiDAR (tia
// xuyen qua) va voi depth camera (IR xuyen qua), nhung phan xa am rat tot.
// Khong mo phong kinh thi nhanh US_BLOCKED cua FSM khong bao gio chay, va
// ca cam bien do tro thanh do trang tri.
bool enable_ultrasonic = true;
double us_rate_hz = 20.0;
double us_max_range = 2.0; // HC-SR04 thuc te ~4 m, nhung nhieu
double us_min_range = 0.03;
double us_beam_half_angle = 0.26; // ~15 do nua goc -- chum RAT rong
double us_noise_stddev = 0.005;
double us_z = 0.12; // cao bao nhieu so voi tam truc
// Goc cua tung dau do, rad, 0 = thang truoc.
std::vector<double> us_angles = {-0.35, 0.0, 0.35};
// Ti le mot lan doc bi mat (cam bien khong tra loi) -> NaN -> US_TIMEOUT.
double us_dropout_rate = 0.0;
// ============ BUMPER ============
// Cong tac va cham, chot cung. Kich khi than robot cham vat can.
bool enable_bumper = true;
double bumper_rate_hz = 50.0;
// Cong tac bumper NHO RA ngoai vo bao nhieu (m).
//
// ⚠️ PHAI > 0. Phep va cham cua bo mo phong TU CHOI chuyen dong khi vanh
// robot (ban kinh `robot_radius`) cham vat can, nen robot khong bao gio
// vao duoc vi tri ma mot bumper dat DUNG `robot_radius` nhin thay. Ket qua:
// nhanh BUMPER cua FSM khong bao gio chay.
//
// Bumper that cung nho ra that: no la mot cong tac gan tren vanh nhua, kich
// khi CHAM chu khong khi da lun vao. 3 cm la kich thuoc dien hinh.
double bumper_reach = 0.03;
// ============ KINH / GUONG ============
// O danh dau la kinh: LiDAR va depth XUYEN QUA (nhu khong co gi), sieu am
// THAY binh thuong. Dat bang SetGlass().
//
// Day la thu Gazebo cua repo cu KHONG mo phong duoc, va la ly do
// docs/SIM_VS_REAL.md cu phai ghi "kinh phai kiem bang du lieu that".
double glass_lidar_pass_rate = 1.0; // 1.0 = xuyen hoan toan
double imu_rate_hz = 200.0;
double gyro_noise_stddev = 4.9e-4;
double accel_noise_stddev = 6.9e-3;
// ================== NGHIENG THAN ROBOT ==================
// Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG,
// quay gap lam no NGHIENG ra ngoai. Gazebo mo phong dieu nay qua vat ly
// tiep xuc; o day mo phong bang mot he lo xo - giam chan bac hai.
//
// KHONG CO NGHIENG THI KHONG THU THACH DUOC `gravity_align`. Logic cot loi
// cua no la TRU gia toc rieng cua robot truoc khi coi phan con lai la trong
// luc (axc = ax - a_lin, ayc = ay - v*w). San phang va robot cung nhac thi
// ca hai so hang do bang 0 va bo loc khong bao gio bi kiem tra.
//
// Gia tri mac dinh chon de dat ~2 do khi tang toc 0.3 m/s^2 -- do la muc
// docs/SIM_VS_REAL.md cua repo cu goi la "mon no chua tra ve tilt trong TF".
double tilt_pitch_per_accel = 0.12; // rad tren (m/s^2)
double tilt_roll_per_centrip = 0.08; // rad tren (m/s^2)
double tilt_natural_freq = 4.0; // rad/s, lo xo giam xoc
double tilt_damping = 0.7; // he so giam chan
// San doc: robot NGHIENG THEO dia hinh. Do cao san da co trong ban do do
// cao; do doc tinh tu chenh lech giua truoc va sau robot.
bool follow_terrain_slope = true;
double wheelbase_for_slope = 0.44; // khoang cach truoc-sau de do doc
double encoder_rate_hz = 50.0;
// ================== HAI LOAI TRUOT, RAT KHAC NHAU ==================
//
// slip_factor -- truot DOI XUNG: ca hai banh truot bang nhau.
// Encoder bao di xa hon thuc te, nhung KHONG sinh chenh lech quay.
// => slip_metric = |omega_encoder - gyro_z| KHONG PHAT HIEN DUOC.
// Day la mot gioi han THAT cua phuong phap so gyro, khong phai thieu sot
// cai dat. Muon bat loai nay can nguon thu hai (vd visual odometry).
//
// slip_differential -- truot VI SAI: mot banh truot nhieu hon banh kia.
// Sinh mot phep quay GIA ma gyro khong thay => slip_metric bat duoc.
// Day la loai ma wheel_odom duoc thiet ke de phat hien, va la loai da do
// duoc tren robot that o bai L6 (slip_metric 0.170 > nguong 0.15).
//
// San nha hang co nuoc va dau mo thi thuong la truot vi sai: mot banh vao
// vet dau truoc banh kia.
double slip_factor = 0.0;
double slip_differential = 0.0;
double slip_accel_threshold = 0.3; // m/s^2
// Gioi han dong hoc, khop diff_drive_controller cu.
double max_linear = 0.35;
double max_angular = 0.8;
double accel_limit = 0.3;
// DEADMAN: khong nhan lenh trong bao lau thi tu dung.
//
// Phai NGAN hon deadman phia JS (500 ms), de base dung truoc khi lop tren
// kip phan ung. Tab trinh duyet dong giua luc dang lai, hoac wifi rot, deu
// dan toi cung mot chuyen: khong con ai gui lenh nua.
double cmd_timeout_sec = 0.3;
// Va cham: robot dung lai khi cham tuong.
bool enable_collision = true;
double robot_radius = 0.24;
// 1.0 = thoi gian that. 0 = chay nhanh nhat co the (cho bai regression).
double speed = 1.0;
};
// So huu ca bon nguon, y het ReplaySource.
class SimSource {
public:
explicit SimSource(SimConfig cfg);
~SimSource();
SimSource(const SimSource&) = delete;
SimSource& operator=(const SimSource&) = delete;
StatusResponse Open();
ClockPtr clock() const;
LidarInterface* lidar();
McuInterface* mcu();
BaseInterface* base();
// Camera depth mo phong bang raycast 2.5D. Tra nullptr khi tat
// (enable_depth_camera = false) chu khong tra mot camera khong co anh.
CameraInterface* camera();
// Ban do do cao san, cung kich thuoc voi map(). Gia tri AM la mot bac hut
// xuong -- do la thu cliff_detect phai phat hien.
//
// Mac dinh phang (toan 0). Dung AddCliff() de tao bac.
const std::vector<float>& floor_height() const;
// Dat mot vung hinh chu nhat (toa do THE GIOI, met) thanh do cao `z`.
// z am = bac hut xuong / cau thang di xuong.
void SetFloorHeight(double x0, double y0, double x1, double y1, float z);
// Danh dau mot vung hinh chu nhat (toa do THE GIOI, met) la KINH.
//
// O kinh phai la o BI CHIEM trong ban do (data >= 50) -- kinh la vat can
// that, chi la vat can ma hai cam bien kia khong thay. Danh dau mot o
// trong la kinh khong co y nghia gi va bi bo qua.
void SetGlass(double x0, double y0, double x1, double y1, bool is_glass);
// Thay ban do sau khi Open(). CHI dung de dung kich ban thu nghiem -- no
// khong dong bo voi bat ky thu gi dang chay, nen goi truoc khi Run().
void SetMapForTest(const OccupancyGrid& m);
// Model doc duoc tu `.world`; rong neu khong chay tu world. Khung 3D dung
// no de ve do dac that thay vi khoi hop dung tu luoi.
const GazeboWorld& world() const;
const std::vector<uint8_t>& glass_mask() const;
// Cham vao vat can chua (bumper THAT dang bi nhan).
bool true_bumper() const;
// Ban do dung de raycast. Cung la ban do "that" ma SLAM se phai dung lai.
const OccupancyGrid& map() const;
// Do nghieng THAT cua than robot (rad). CHI dung de danh gia -- khong
// estimator nao duoc doc. `gravity_align` phai TU uoc luong hai so nay tu
// IMU, va day la dap an de cham diem.
void true_tilt(double* roll, double* pitch) const;
// Pose that cua robot. CHI dung de danh gia -- khong estimator nao duoc
// doc ham nay. Day la tuong duong cua /ground_truth/odom trong repo cu.
Pose2D ground_truth() const;
// Chay mo phong. Chan cho toi khi RequestStop().
void Run();
// Chay dung `seconds` thoi gian mo phong roi dung. Dung cho test.
void RunFor(double seconds);
void RequestStop();
struct Stats {
uint64_t scans = 0;
uint64_t imu = 0;
uint64_t encoder = 0;
uint64_t camera_frames = 0;
uint64_t collisions = 0;
double sim_time_sec = 0.0;
double distance_travelled = 0.0;
};
Stats stats() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace vslam
#endif // VSLAM_SIM_SOURCE_H

View File

@@ -0,0 +1,863 @@
#include "vslam/gazebo_world.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <map>
#include <sstream>
#include <sys/stat.h>
#include <yaml-cpp/yaml.h>
#include "vslam/log.h"
namespace vslam {
namespace {
bool FileExists(const std::string& p) {
struct stat st;
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISREG(st.st_mode);
}
bool DirExists(const std::string& p) {
struct stat st;
return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
std::string ReadFile(const std::string& p) {
std::ifstream f(p);
if (!f) return "";
std::ostringstream o;
o << f.rdbuf();
return o.str();
}
// Lay noi dung cua the <tag> DAU TIEN tu vi tri `from`. Tra chuoi rong neu
// khong co. `end_out` nhan vi tri ngay sau the dong.
//
// Du cho cau truc rat deu cua SDF; khong nham lam mot parser XML tong quat.
std::string Tag(const std::string& s, const std::string& tag, size_t from,
size_t* end_out = nullptr) {
const std::string open = "<" + tag + ">";
const std::string close = "</" + tag + ">";
const size_t a = s.find(open, from);
if (a == std::string::npos) return "";
const size_t b = s.find(close, a);
if (b == std::string::npos) return "";
if (end_out) *end_out = b + close.size();
return s.substr(a + open.size(), b - a - open.size());
}
std::string Trim(const std::string& s) {
const size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) return "";
const size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
// "x y z roll pitch yaw" -> sau so. Thieu thi de 0.
void ParsePose(const std::string& s, WorldModel* m) {
std::istringstream in(s);
double v[6] = {0, 0, 0, 0, 0, 0};
for (int i = 0; i < 6 && (in >> v[i]); ++i) {}
m->x = v[0]; m->y = v[1]; m->z = v[2];
m->roll = v[3]; m->pitch = v[4]; m->yaw = v[5];
}
std::vector<std::string> DefaultModelPaths() {
std::vector<std::string> out;
if (const char* env = std::getenv("GAZEBO_MODEL_PATH")) {
std::string s(env), cur;
std::istringstream in(s);
while (std::getline(in, cur, ':')) if (!cur.empty()) out.push_back(cur);
}
if (const char* home = std::getenv("HOME")) {
// Cho mac dinh cua Gazebo, va cho ma repo nay that su de model.
out.push_back(std::string(home) + "/.gazebo/models");
out.push_back(std::string(home) + "/gazebo_models/aws_hospital_fuel");
out.push_back(std::string(home) + "/gazebo_models/aws_hospital");
}
return out;
}
// `model://Ten` hoac `model://Ten/meshes/x.obj` -> duong dan tuyet doi.
std::string ResolveModelUri(const std::string& uri,
const std::vector<std::string>& roots,
std::string* root_used) {
const std::string prefix = "model://";
if (uri.compare(0, prefix.size(), prefix) != 0) return "";
const std::string rel = uri.substr(prefix.size());
for (const std::string& r : roots) {
const std::string p = r + "/" + rel;
if (FileExists(p) || DirExists(p)) {
if (root_used) *root_used = r;
return p;
}
}
return "";
}
} // namespace
StatusResponse LoadGazeboWorld(const std::string& world_path,
const std::vector<std::string>& model_paths,
GazeboWorld* out, size_t* skipped) {
const std::string src = ReadFile(world_path);
if (src.empty()) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong doc duoc file world: " + world_path);
}
std::vector<std::string> roots = model_paths;
if (roots.empty()) roots = DefaultModelPaths();
// Bo cac thu muc khong ton tai -- de thong bao loi ben duoi khong liet ke
// mot dong duong dan vo nghia.
roots.erase(std::remove_if(roots.begin(), roots.end(),
[](const std::string& p) { return !DirExists(p); }),
roots.end());
if (roots.empty()) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong tim thay thu muc model nao. Dat GAZEBO_MODEL_PATH, hoac de "
"model o ~/.gazebo/models.");
}
out->world_path = world_path;
out->models.clear();
size_t skip = 0;
// Quet tung the <model name="...">.
size_t pos = 0;
const std::string kModelOpen = "<model name=";
while ((pos = src.find(kModelOpen, pos)) != std::string::npos) {
const size_t name_a = src.find('"', pos);
const size_t name_b = name_a == std::string::npos
? std::string::npos : src.find('"', name_a + 1);
if (name_b == std::string::npos) break;
WorldModel m;
m.name = src.substr(name_a + 1, name_b - name_a - 1);
// Khoi cua model nay ket thuc o </model> gan nhat.
const size_t block_end = src.find("</model>", name_b);
if (block_end == std::string::npos) break;
const std::string block = src.substr(name_b, block_end - name_b);
const std::string uri = Trim(Tag(block, "uri", 0));
ParsePose(Tag(block, "pose", 0), &m);
pos = block_end + 8;
if (uri.empty()) { skip++; continue; }
m.model_name = uri.substr(uri.rfind('/') + 1);
std::string root;
const std::string dir = ResolveModelUri(uri, roots, &root);
if (dir.empty()) {
// `ground_plane` va `sun` la built-in cua Gazebo, khong co tren dia.
// Bo qua chung la DUNG, khong phai loi.
skip++;
continue;
}
if (std::find(out->model_roots.begin(), out->model_roots.end(), root) ==
out->model_roots.end()) {
out->model_roots.push_back(root);
}
// model.sdf tro toi mesh. Lay ca visual lan collision: chung thuong la
// cung mot file, nhung khi khac nhau thi collision la ban da giam da
// giac -- dung cai do de raster hoa se nhanh hon nhieu.
const std::string sdf = ReadFile(dir + "/model.sdf");
if (!sdf.empty()) {
size_t vp = sdf.find("<visual");
if (vp != std::string::npos) {
const std::string u = Trim(Tag(sdf, "uri", vp));
m.visual_obj = ResolveModelUri(u, roots, nullptr);
}
size_t cp = sdf.find("<collision");
if (cp != std::string::npos) {
const std::string u = Trim(Tag(sdf, "uri", cp));
m.collision_obj = ResolveModelUri(u, roots, nullptr);
}
// `<scale>` nam trong khoi <mesh>. Lay cua collision truoc, khong co
// thi cua visual -- hai cai hau nhu luon giong nhau.
{
size_t sp = (cp != std::string::npos) ? cp : vp;
if (sp != std::string::npos) {
const std::string sc = Trim(Tag(sdf, "scale", sp));
std::istringstream in(sc);
double v[3] = {1, 1, 1};
int n = 0;
while (n < 3 && (in >> v[n])) n++;
if (n == 3) { m.sx = v[0]; m.sy = v[1]; m.sz = v[2]; }
else if (n == 1) { m.sx = m.sy = m.sz = v[0]; }
}
}
}
// Khong co collision rieng thi dung visual -- van tot hon la bo qua han
// mot buc tuong.
if (m.collision_obj.empty()) m.collision_obj = m.visual_obj;
if (m.visual_obj.empty()) m.visual_obj = m.collision_obj;
// ⚠️ File world nay co san pose HONG.
//
// `StorageRack_1` mang `<pose>9.07 -10.36 -7.57769e+08 ...>`: mot vat da
// roi xuyen san trong mot phien Gazebo nao do roi world duoc luu lai.
// Gazebo cung khong hien chung -- chung o cach mat dat 757 nghin km.
//
// Khong loc thi luoi van dung (tam giac roi ngoai dai z) nhung khung 3D
// cap phat instance cho vat khong bao gio thay duoc, va moi phep tinh bao
// loi deu vo nghia.
if (std::fabs(m.x) > 1000.0 || std::fabs(m.y) > 1000.0 ||
std::fabs(m.z) > 1000.0) {
VSLAM_WARN("world: bo model " << m.name << " -- pose vo ly ("
<< m.x << ", " << m.y << ", " << m.z << ")");
skip++;
continue;
}
out->models.push_back(std::move(m));
}
if (skipped) *skipped = skip;
VSLAM_INFO("world " << world_path << ": " << out->models.size()
<< " model phan giai duoc"
<< (skip ? ", bo qua " + std::to_string(skip) +
" (ground_plane/sun la built-in)"
: ""));
if (out->models.empty()) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
world_path + ": khong phan giai duoc model nao");
}
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
// Raster hoa
// ---------------------------------------------------------------------------
namespace {
struct Tri { double x[3], y[3], z[3]; };
// Ma tran 4x4 hang-chinh, chi dung cho phep bien doi affine cua COLLADA.
struct Mat4 {
double m[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
};
Mat4 MatMul(const Mat4& a, const Mat4& b) {
Mat4 r;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j) {
double s = 0;
for (int k = 0; k < 4; ++k) s += a.m[i * 4 + k] * b.m[k * 4 + j];
r.m[i * 4 + j] = s;
}
return r;
}
void MatApply(const Mat4& t, double* x, double* y, double* z) {
const double px = *x, py = *y, pz = *z;
*x = t.m[0] * px + t.m[1] * py + t.m[2] * pz + t.m[3];
*y = t.m[4] * px + t.m[5] * py + t.m[6] * pz + t.m[7];
*z = t.m[8] * px + t.m[9] * py + t.m[10] * pz + t.m[11];
}
Mat4 MakeTranslate(double x, double y, double z) {
Mat4 t;
t.m[3] = x; t.m[7] = y; t.m[11] = z;
return t;
}
// Quay quanh truc (ax,ay,az) mot goc `deg` DO -- COLLADA dung do, khong radian.
Mat4 MakeRotate(double ax, double ay, double az, double deg) {
const double n = std::sqrt(ax * ax + ay * ay + az * az);
Mat4 t;
if (n < 1e-12) return t;
ax /= n; ay /= n; az /= n;
const double a = deg * M_PI / 180.0, c = std::cos(a), s = std::sin(a), k = 1 - c;
t.m[0] = c + ax*ax*k; t.m[1] = ax*ay*k - az*s; t.m[2] = ax*az*k + ay*s;
t.m[4] = ay*ax*k + az*s; t.m[5] = c + ay*ay*k; t.m[6] = ay*az*k - ax*s;
t.m[8] = az*ax*k - ay*s; t.m[9] = az*ay*k + ax*s; t.m[10] = c + az*az*k;
return t;
}
Mat4 MakeScale(double x, double y, double z) {
Mat4 t;
t.m[0] = x; t.m[5] = y; t.m[10] = z;
return t;
}
std::vector<double> ParseFloats(const std::string& s) {
std::vector<double> v;
std::istringstream in(s);
double d;
while (in >> d) v.push_back(d);
return v;
}
// Lay gia tri thuoc tinh `attr` cua the bat dau tai `tag_pos`.
std::string Attr(const std::string& s, size_t tag_pos, const std::string& attr) {
const size_t end = s.find('>', tag_pos);
if (end == std::string::npos) return "";
const size_t a = s.find(attr + "=\"", tag_pos);
if (a == std::string::npos || a > end) return "";
const size_t b = a + attr.size() + 2;
const size_t c = s.find('"', b);
if (c == std::string::npos) return "";
return s.substr(b, c - b);
}
// Doc tam giac tu file COLLADA (.dae).
//
// ⚠️ QUY UOC NAM TRONG TUNG FILE, KHONG PHAI TOAN CUC.
//
// Cac mesh `.obj` cua bo model nay la Z-UP, don vi MET. Nhung `.dae` cua
// tuong/san lai la:
// <unit meter="0.01" name="centimeter"/>
// <up_axis>Y_UP</up_axis>
// Ap mot quy uoc chung cho ca hai lam luoi ra la RAC ma van "trong nhu co du
// lieu": da do mot lan ra luoi 5235x5942 o (262 x 297 m) cho mot toa nha chi
// rong 25 x 51 m.
//
// Ho tro tap con thuc su xuat hien trong bo model AWS: <polylist> va
// <triangles>, input co offset, va phep bien doi cua <node> (translate /
// rotate truc-goc theo DO / scale).
// So duoi file KHONG phan biet hoa thuong.
//
// ⚠️ Bo model nay tron ca `.dae` lan `.DAE`: 15 model `aws_robomaker_
// residential_*` va `warehouse_*` dung chu hoa. So phan biet hoa thuong lam
// chung roi vao bo doc OBJ va HONG IM LANG -- khong loi, khong canh bao, chi
// la sofa/tu lanh/tranh tuong bien mat khoi ca khung 3D LAN luoi chiem dung.
bool IsDae(const std::string& p) {
if (p.size() < 4) return false;
const std::string e = p.substr(p.size() - 4);
return (e[0] == '.') && (e[1] == 'd' || e[1] == 'D') &&
(e[2] == 'a' || e[2] == 'A') && (e[3] == 'e' || e[3] == 'E');
}
bool ReadDaeTriangles(const std::string& path, std::vector<Tri>* out) {
const std::string s = ReadFile(path);
if (s.empty()) return false;
// --- don vi va truc len ---
double unit = 1.0;
{
const size_t u = s.find("<unit");
if (u != std::string::npos) {
const std::string v = Attr(s, u, "meter");
if (!v.empty()) unit = std::atof(v.c_str());
}
}
// --- source id -> mang float ---
std::map<std::string, std::vector<double>> sources;
for (size_t p = 0; (p = s.find("<source", p)) != std::string::npos;) {
const std::string id = Attr(s, p, "id");
size_t fa = s.find("<float_array", p);
const size_t next_src = s.find("<source", p + 1);
if (fa != std::string::npos && (next_src == std::string::npos || fa < next_src)) {
const size_t open_end = s.find('>', fa);
const size_t close = s.find("</float_array>", open_end);
if (open_end != std::string::npos && close != std::string::npos && !id.empty()) {
sources[id] = ParseFloats(s.substr(open_end + 1, close - open_end - 1));
}
}
p += 7;
}
// --- vertices id -> source id cua POSITION ---
std::map<std::string, std::string> vert_to_src;
for (size_t p = 0; (p = s.find("<vertices", p)) != std::string::npos;) {
const std::string id = Attr(s, p, "id");
const size_t in = s.find("<input", p);
const size_t close = s.find("</vertices>", p);
if (in != std::string::npos && close != std::string::npos && in < close) {
std::string src = Attr(s, in, "source");
if (!src.empty() && src[0] == '#') src.erase(0, 1);
if (!id.empty()) vert_to_src[id] = src;
}
p += 9;
}
// --- phep bien doi cua node, theo id geometry duoc instance ben trong ---
std::map<std::string, Mat4> geom_xform;
for (size_t p = 0; (p = s.find("<node", p)) != std::string::npos;) {
const size_t node_end = s.find("</node>", p);
const size_t limit = node_end == std::string::npos ? s.size() : node_end;
Mat4 t;
// Thu tu ap la thu tu XUAT HIEN trong file -- COLLADA quy dinh vay.
//
// ⚠️ `<matrix>` KHONG the bo qua. Bo model nay co hai ho file: ho xuat tu
// Blender dung translate/rotate/scale, ho xuat tu 3ds Max dung MOT the
// `<matrix>`. Bo qua the do lam ti le sai tu 10x den 100x ma khong mot
// canh bao nao -- da do sofa ra 24.4 m va buc tranh ra 5 cm, ca hai trong
// file khai `<unit meter="0.01">` y het cac file dung.
for (size_t q = p; q < limit;) {
const size_t tr = s.find("<translate", q), ro = s.find("<rotate", q),
sc = s.find("<scale", q), mx = s.find("<matrix", q);
size_t nxt = std::min({tr == std::string::npos ? limit : tr,
ro == std::string::npos ? limit : ro,
sc == std::string::npos ? limit : sc,
mx == std::string::npos ? limit : mx});
if (nxt >= limit) break;
const size_t oe = s.find('>', nxt), ce = s.find('<', oe + 1);
const std::vector<double> v = ParseFloats(s.substr(oe + 1, ce - oe - 1));
if (nxt == tr && v.size() >= 3) t = MatMul(t, MakeTranslate(v[0], v[1], v[2]));
else if (nxt == ro && v.size() >= 4) t = MatMul(t, MakeRotate(v[0], v[1], v[2], v[3]));
else if (nxt == sc && v.size() >= 3) t = MatMul(t, MakeScale(v[0], v[1], v[2]));
else if (nxt == mx && v.size() >= 16) {
// COLLADA ghi ma tran theo HANG, cung quy uoc voi Mat4 o day.
Mat4 mm;
for (int i = 0; i < 16; ++i) mm.m[i] = v[static_cast<size_t>(i)];
t = MatMul(t, mm);
}
q = ce;
}
for (size_t g = p; (g = s.find("<instance_geometry", g)) != std::string::npos &&
g < limit;) {
std::string url = Attr(s, g, "url");
if (!url.empty() && url[0] == '#') url.erase(0, 1);
if (!url.empty()) geom_xform[url] = t;
g += 18;
}
p += 5;
}
// --- geometry -> tam giac ---
size_t before = out->size();
for (size_t p = 0; (p = s.find("<geometry", p)) != std::string::npos;) {
const std::string gid = Attr(s, p, "id");
const size_t gend = s.find("</geometry>", p);
const size_t limit = gend == std::string::npos ? s.size() : gend;
Mat4 xf;
auto it = geom_xform.find(gid);
if (it != geom_xform.end()) xf = it->second;
// ⚠️ `<up_axis>` cua bo model nay PHAI BI BO QUA.
//
// Moi file deu khai `<up_axis>Y_UP`, nhung do la noi ve he toa do cua bo
// XUAT, khong phai cua du lieu trong file. Bo xuat nay da nuong phep doi
// truc vao node goc, va chi nuong KHI CAN:
//
// walls_collision ID3 : dinh (56.12, 3.00, 25.12) -- Y-up that
// node co `0 1 0 90` + `0 0 1 -270` de doi truc
// walls_visual ID43: dinh (25.12, 56.12, 3.00) -- DA la Z-up
// node RONG, khong can doi gi
//
// Cung mot buc tuong, hai file, hai cach. Ap them `<up_axis>` lam cai thu
// hai bi lat: buc tuong 3 m thanh mot thanh DUNG DUNG cao 56 m giua san.
//
// Tung thu doan theo ma tran node ("node don vi thi lat") -- sai chinh o
// ID43. Node don vi o day nghia la "khong can doi", khong phai "chua doi".
for (size_t q = p; q < limit;) {
const size_t pl = s.find("<polylist", q), trg = s.find("<triangles", q);
size_t prim = std::min(pl == std::string::npos ? limit : pl,
trg == std::string::npos ? limit : trg);
if (prim >= limit) break;
const bool is_poly = (prim == pl);
const size_t pend = s.find(is_poly ? "</polylist>" : "</triangles>", prim);
if (pend == std::string::npos) break;
// Tim input VERTEX va stride (offset lon nhat + 1).
int vert_off = -1, stride = 1;
std::string vsrc;
for (size_t i = prim; (i = s.find("<input", i)) != std::string::npos && i < pend;) {
const std::string off = Attr(s, i, "offset");
if (!off.empty()) stride = std::max(stride, std::atoi(off.c_str()) + 1);
if (Attr(s, i, "semantic") == "VERTEX") {
vert_off = off.empty() ? 0 : std::atoi(off.c_str());
vsrc = Attr(s, i, "source");
if (!vsrc.empty() && vsrc[0] == '#') vsrc.erase(0, 1);
}
i += 6;
}
if (vert_off < 0) { q = pend; continue; }
auto vt = vert_to_src.find(vsrc);
const std::string psrc = vt != vert_to_src.end() ? vt->second : vsrc;
auto ps = sources.find(psrc);
if (ps == sources.end()) { q = pend; continue; }
const std::vector<double>& pos = ps->second;
std::vector<double> vcount;
if (is_poly) {
const size_t vc = s.find("<vcount>", prim);
if (vc != std::string::npos && vc < pend) {
const size_t e = s.find("</vcount>", vc);
vcount = ParseFloats(s.substr(vc + 8, e - vc - 8));
}
}
const size_t pp = s.find("<p>", prim);
if (pp == std::string::npos || pp > pend) { q = pend; continue; }
const size_t pe = s.find("</p>", pp);
const std::vector<double> idx = ParseFloats(s.substr(pp + 3, pe - pp - 3));
auto vertex = [&](size_t n, double* x, double* y, double* z) {
const size_t vi = static_cast<size_t>(idx[n * stride + vert_off]) * 3;
if (vi + 2 >= pos.size()) return false;
// ⚠️ THU TU: ap ma tran node TRUOC, roi moi doi don vi.
//
// `<translate>` cua node nam trong CUNG don vi cua file (o day la
// centimet). Nhan `unit` vao dinh truoc roi ap mot translate tinh
// bang cm se coi 5000 cm thanh 5000 MET -- da do mot lan ra luoi
// 263 x 146 m cho mot toa nha 25 x 51 m.
double px = pos[vi], py = pos[vi + 1], pz = pos[vi + 2];
MatApply(xf, &px, &py, &pz);
px *= unit; py *= unit; pz *= unit;
// Y_UP -> Z_UP cua ROS: (x, y, z)_dae -> (x, -z, y)
*x = px; *y = py; *z = pz;
return true;
};
const size_t nvert = stride > 0 ? idx.size() / stride : 0;
if (is_poly && !vcount.empty()) {
size_t base = 0;
for (double cd : vcount) {
const size_t c = static_cast<size_t>(cd);
for (size_t k = 2; k < c && base + k < nvert; ++k) {
Tri t;
bool ok = vertex(base, &t.x[0], &t.y[0], &t.z[0]) &&
vertex(base + k - 1, &t.x[1], &t.y[1], &t.z[1]) &&
vertex(base + k, &t.x[2], &t.y[2], &t.z[2]);
if (ok) out->push_back(t);
}
base += c;
}
} else {
for (size_t k = 0; k + 2 < nvert; k += 3) {
Tri t;
bool ok = vertex(k, &t.x[0], &t.y[0], &t.z[0]) &&
vertex(k + 1, &t.x[1], &t.y[1], &t.z[1]) &&
vertex(k + 2, &t.x[2], &t.y[2], &t.z[2]);
if (ok) out->push_back(t);
}
}
q = pend;
}
p = limit;
}
return out->size() > before;
}
// Doc tam giac tu file OBJ. Chi can `v` va `f`; bo qua vt/vn/usemtl.
//
// OBJ danh chi so tu 1 va cho phep chi so AM (tinh nguoc tu cuoi). Bo qua
// chi so am se lam mot so mesh mat mat -- xu ly ca hai.
bool ReadObjTriangles(const std::string& path, std::vector<Tri>* out) {
std::ifstream f(path);
if (!f) return false;
std::vector<std::array<double, 3>> v;
std::string line;
while (std::getline(f, line)) {
if (line.size() < 2) continue;
if (line[0] == 'v' && line[1] == ' ') {
std::istringstream in(line.substr(2));
std::array<double, 3> p{0, 0, 0};
in >> p[0] >> p[1] >> p[2];
v.push_back(p);
} else if (line[0] == 'f' && line[1] == ' ') {
std::istringstream in(line.substr(2));
std::string tok;
std::vector<int> idx;
while (in >> tok) {
// "a", "a/b", "a//c", "a/b/c" -- chi lay phan truoc dau '/'.
const size_t slash = tok.find('/');
const std::string num = slash == std::string::npos ? tok : tok.substr(0, slash);
if (num.empty()) continue;
int i = std::atoi(num.c_str());
if (i > 0) i -= 1;
else if (i < 0) i = static_cast<int>(v.size()) + i;
else continue;
if (i >= 0 && i < static_cast<int>(v.size())) idx.push_back(i);
}
// Quat va n-giac: chia thanh quat tam giac.
for (size_t k = 2; k < idx.size(); ++k) {
Tri t;
const int a = idx[0], b = idx[k - 1], c = idx[k];
t.x[0] = v[a][0]; t.y[0] = v[a][1]; t.z[0] = v[a][2];
t.x[1] = v[b][0]; t.y[1] = v[b][1]; t.z[1] = v[b][2];
t.x[2] = v[c][0]; t.y[2] = v[c][1]; t.z[2] = v[c][2];
out->push_back(t);
}
}
}
return true;
}
} // namespace
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out) {
if (!(opt.resolution > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"resolution phai duong");
}
// --- Luot 1: bao loi ---
double minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;
size_t n_tri = 0, n_mesh = 0;
struct Loaded { const WorldModel* m; std::vector<Tri> tris; };
std::vector<Loaded> loaded;
loaded.reserve(world.models.size());
for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue;
Loaded L;
L.m = &m;
// Chon bo doc theo DUOI FILE: bo model nay tron ca .obj lan .dae, va moi
// dinh dang mang quy uoc rieng (xem ghi chu o ReadDaeTriangles).
const std::string& cp = m.collision_obj;
const bool ok = IsDae(cp) ? ReadDaeTriangles(cp, &L.tris)
: ReadObjTriangles(cp, &L.tris);
if (!ok) {
VSLAM_WARN("world: khong doc duoc mesh " << cp << " cua model "
<< m.model_name << " -- vat the nay VANG MAT khoi luoi");
continue;
}
if (L.tris.empty()) continue;
n_mesh++;
n_tri += L.tris.size();
const double cy = std::cos(m.yaw), sny = std::sin(m.yaw);
for (Tri& t : L.tris) {
for (int k = 0; k < 3; ++k) {
// Ti le TRUOC khi quay va tinh tien -- `<scale>` la cua mesh, khong
// phai cua the gioi.
t.x[k] *= m.sx; t.y[k] *= m.sy; t.z[k] *= m.sz;
// Bo doc da tra ve he ROS (Z-len, met) roi -- KHONG doi truc them o
// day. Quy uoc nam trong TUNG FILE (.obj Z-up met, .dae Y-up cm), va
// ap them mot phep doi chung se lam hong dung mot nua so mesh.
const double wx = t.x[k], wy = t.y[k], wz = t.z[k];
// Chi xet yaw: roll/pitch cua do dac dat tren san gan nhu luon 0, va
// xoay day du se lam ham nay dai gap doi ma khong doi ket qua.
const double rx = wx * cy - wy * sny;
const double ry = wx * sny + wy * cy;
t.x[k] = rx + m.x;
t.y[k] = ry + m.y;
t.z[k] = wz + m.z;
minx = std::min(minx, t.x[k]); maxx = std::max(maxx, t.x[k]);
miny = std::min(miny, t.y[k]); maxy = std::max(maxy, t.y[k]);
}
}
loaded.push_back(std::move(L));
}
if (loaded.empty()) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong doc duoc mesh va cham nao tu world");
}
minx -= opt.pad; maxx += opt.pad;
miny -= opt.pad; maxy += opt.pad;
const double res = opt.resolution;
const uint32_t w = static_cast<uint32_t>(std::ceil((maxx - minx) / res));
const uint32_t h = static_cast<uint32_t>(std::ceil((maxy - miny) / res));
out->resolution = static_cast<float>(res);
out->width = w;
out->height = h;
out->origin = Pose{};
out->origin.position.x = minx;
out->origin.position.y = miny;
// Bat dau la TRONG, khong phai chua biet: the gioi nay do ta dung nen moi
// o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM.
out->data.assign(static_cast<size_t>(w) * h, 0);
// --- Luot 2: to tam giac trong dai do cao ---
size_t n_used = 0;
for (const Loaded& L : loaded) {
for (const Tri& t : L.tris) {
// Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua:
// mesh day dac nen mot tam giac bien bi bo van con hang xom phu.
const double tz0 = std::min({t.z[0], t.z[1], t.z[2]});
const double tz1 = std::max({t.z[0], t.z[1], t.z[2]});
if (tz1 < opt.z_min || tz0 > opt.z_max) continue;
n_used++;
// Bao loi cua tam giac, roi kiem tung o bang toa do trong tam.
const double bx0 = std::min({t.x[0], t.x[1], t.x[2]});
const double bx1 = std::max({t.x[0], t.x[1], t.x[2]});
const double by0 = std::min({t.y[0], t.y[1], t.y[2]});
const double by1 = std::max({t.y[0], t.y[1], t.y[2]});
const int cx0 = std::max(0, static_cast<int>((bx0 - minx) / res));
const int cx1 = std::min(static_cast<int>(w) - 1,
static_cast<int>((bx1 - minx) / res));
const int cy0 = std::max(0, static_cast<int>((by0 - miny) / res));
const int cy1 = std::min(static_cast<int>(h) - 1,
static_cast<int>((by1 - miny) / res));
const double ax = t.x[0], ay = t.y[0];
const double bx = t.x[1], by = t.y[1];
const double cx = t.x[2], cy = t.y[2];
const double den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
const bool degenerate = std::fabs(den) < 1e-12;
for (int gy = cy0; gy <= cy1; ++gy) {
for (int gx = cx0; gx <= cx1; ++gx) {
const double px = minx + (gx + 0.5) * res;
const double py = miny + (gy + 0.5) * res;
bool inside;
if (degenerate) {
// Tam giac suy bien (canh rat mong) van phai to, neu khong mot
// buc tuong mong se thung lo.
inside = true;
} else {
const double l1 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / den;
const double l2 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / den;
const double l3 = 1.0 - l1 - l2;
inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9;
}
if (inside) {
out->data[static_cast<size_t>(gy) * w + gx] = 100;
}
}
}
}
}
size_t occ = 0;
for (int8_t v : out->data) if (v >= 50) occ++;
VSLAM_INFO("world -> luoi: " << w << "x" << h << " @ " << res << " m/o, goc ("
<< minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri
<< " tam giac (" << n_used << " trong dai z ["
<< opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem");
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
WorldMeshes* out) {
if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
}
out->geoms.clear();
out->instances.clear();
std::map<std::string, uint32_t> by_model;
for (const WorldModel& m : world.models) {
const std::string& path = visual && !m.visual_obj.empty() ? m.visual_obj
: m.collision_obj;
if (path.empty()) continue;
// Gop theo TEN MODEL, khong theo duong dan mesh: `<scale>` den tu
// model.sdf nen hai model dung chung mot file mesh van co the khac ti le.
uint32_t gid = 0;
auto it = by_model.find(m.model_name);
if (it != by_model.end()) {
gid = it->second;
} else {
std::vector<Tri> tris;
const bool ok = IsDae(path) ? ReadDaeTriangles(path, &tris)
: ReadObjTriangles(path, &tris);
if (!ok || tris.empty()) {
VSLAM_WARN("world: khong doc duoc mesh " << path << " cua model "
<< m.model_name << " -- vat the nay VANG MAT khoi khung 3D");
continue;
}
WorldMeshGeom g;
g.model_name = m.model_name;
g.tri.reserve(tris.size() * 9);
for (const Tri& t : tris) {
for (int k = 0; k < 3; ++k) {
g.tri.push_back(static_cast<float>(t.x[k] * m.sx));
g.tri.push_back(static_cast<float>(t.y[k] * m.sy));
g.tri.push_back(static_cast<float>(t.z[k] * m.sz));
}
}
gid = static_cast<uint32_t>(out->geoms.size());
by_model[m.model_name] = gid;
out->geoms.push_back(std::move(g));
}
WorldMeshInstance inst;
inst.geom = gid;
inst.x = static_cast<float>(m.x);
inst.y = static_cast<float>(m.y);
inst.z = static_cast<float>(m.z);
inst.yaw = static_cast<float>(m.yaw);
out->instances.push_back(inst);
}
if (out->geoms.empty()) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong doc duoc mesh nao tu world");
}
return StatusResponse::Ok();
}
size_t ApplyModelColors(const std::string& json_path, WorldMeshes* io) {
if (io == nullptr) return 0;
// JSON la tap con cua YAML, nen yaml-cpp doc duoc thang -- khong keo them
// mot bo doc JSON vao `vslam_sim` chi vi mot bang 69 dong.
YAML::Node root;
try {
root = YAML::LoadFile(json_path);
} catch (const std::exception& e) {
VSLAM_WARN("world: khong doc duoc bang mau " << json_path << " (" << e.what()
<< ") -- moi vat the se mang mau mac dinh");
return 0;
}
size_t n = 0;
for (WorldMeshGeom& g : io->geoms) {
const YAML::Node c = root[g.model_name];
if (!c || !c.IsSequence() || c.size() < 3) continue;
g.r = static_cast<uint8_t>(c[0].as<int>());
g.g = static_cast<uint8_t>(c[1].as<int>());
g.b = static_cast<uint8_t>(c[2].as<int>());
n++;
}
return n;
}
namespace {
void PutU32(std::string* o, uint32_t v) {
// Little-endian tuong minh: trinh duyet doc bang DataView voi littleEndian
// = true, nen khong duoc phu thuoc endianness cua may chu.
o->push_back(static_cast<char>(v & 0xFF));
o->push_back(static_cast<char>((v >> 8) & 0xFF));
o->push_back(static_cast<char>((v >> 16) & 0xFF));
o->push_back(static_cast<char>((v >> 24) & 0xFF));
}
void PutF32(std::string* o, float f) {
uint32_t u = 0;
std::memcpy(&u, &f, 4);
PutU32(o, u);
}
} // namespace
void EncodeWorldMeshes(const WorldMeshes& in, std::string* out) {
if (out == nullptr) return;
out->clear(); // ⚠️ ghi de, KHONG noi them -- xem EncodeScanPayload
out->append("VSLW");
PutU32(out, 1);
PutU32(out, static_cast<uint32_t>(in.geoms.size()));
PutU32(out, static_cast<uint32_t>(in.instances.size()));
for (const WorldMeshGeom& g : in.geoms) {
PutU32(out, static_cast<uint32_t>(g.model_name.size()));
out->append(g.model_name);
out->push_back(static_cast<char>(g.r));
out->push_back(static_cast<char>(g.g));
out->push_back(static_cast<char>(g.b));
PutU32(out, static_cast<uint32_t>(g.tri.size() / 9));
for (float v : g.tri) PutF32(out, v);
}
for (const WorldMeshInstance& i : in.instances) {
PutU32(out, i.geom);
PutF32(out, i.x); PutF32(out, i.y); PutF32(out, i.z); PutF32(out, i.yaw);
}
}
} // namespace vslam

View File

@@ -0,0 +1,248 @@
#include "vslam/occupancy_map_io.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
std::string DirName(const std::string& path) {
const size_t slash = path.find_last_of('/');
return slash == std::string::npos ? std::string(".") : path.substr(0, slash);
}
// Doc PGM P5 (nhi phan 8 bit). Bo qua comment bat dau bang '#'.
bool ReadPgm(const std::string& path, uint32_t* w, uint32_t* h,
std::vector<uint8_t>* pixels, std::string* err) {
std::ifstream f(path, std::ios::binary);
if (!f) {
*err = "khong mo duoc " + path;
return false;
}
auto next_token = [&f]() -> std::string {
std::string tok;
while (f) {
const int c = f.get();
if (c == EOF) break;
if (c == '#') {
while (f && f.get() != '\n') {
}
continue;
}
if (std::isspace(c)) {
if (!tok.empty()) break;
continue;
}
tok.push_back(static_cast<char>(c));
}
return tok;
};
if (next_token() != "P5") {
*err = path + ": chi ho tro PGM P5 (nhi phan)";
return false;
}
*w = static_cast<uint32_t>(std::stoul(next_token()));
*h = static_cast<uint32_t>(std::stoul(next_token()));
const unsigned long maxval = std::stoul(next_token());
if (maxval > 255) {
*err = path + ": chi ho tro PGM 8 bit";
return false;
}
pixels->resize(static_cast<size_t>(*w) * (*h));
f.read(reinterpret_cast<char*>(pixels->data()),
static_cast<std::streamsize>(pixels->size()));
if (static_cast<size_t>(f.gcount()) != pixels->size()) {
*err = path + ": file anh cut";
return false;
}
return true;
}
} // namespace
StatusResponse LoadOccupancyMap(const std::string& yaml_path, MapLoadResult* out) {
// Kiem TON TAI truoc khi giao cho yaml-cpp.
//
// `YAML::LoadFile` tren mot file khong co nem `BadFile`, va `what()` cua no
// dung la chuoi "bad file" -- khong noi file nao, khong phan biet thieu voi
// hong, khong goi y gi. Nguoi dung go sai duong dan chi nhan duoc
// "hospital.yaml: bad file" roi dung do.
{
std::ifstream probe(yaml_path);
if (!probe) {
return StatusResponse::Error(
StatusCode::kNotFound,
"khong mo duoc ban do: " + yaml_path +
" (khong ton tai hoac khong co quyen doc). Xuat mot ban do tu DB "
"RTAB-Map bang: vslam_slam_bench --db X.db --localize "
"--export-only --export-map out.pgm");
}
}
YAML::Node node;
try {
node = YAML::LoadFile(yaml_path);
} catch (const YAML::Exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": YAML hong: " + e.what());
}
if (!node["image"] || !node["resolution"]) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
yaml_path + ": thieu 'image' hoac 'resolution'");
}
std::string image = node["image"].as<std::string>();
if (!image.empty() && image[0] != '/') image = DirName(yaml_path) + "/" + image;
out->image_path = image;
const double resolution = node["resolution"].as<double>();
double ox = 0.0, oy = 0.0;
if (node["origin"] && node["origin"].size() >= 2) {
ox = node["origin"][0].as<double>();
oy = node["origin"][1].as<double>();
}
const bool negate = node["negate"] ? node["negate"].as<int>() != 0 : false;
out->occupied_thresh =
node["occupied_thresh"] ? node["occupied_thresh"].as<double>() : 0.65;
out->free_thresh = node["free_thresh"] ? node["free_thresh"].as<double>() : 0.196;
uint32_t w = 0, h = 0;
std::vector<uint8_t> pixels;
std::string err;
if (!ReadPgm(image, &w, &h, &pixels, &err)) {
return StatusResponse::Error(StatusCode::kNotFound, err);
}
out->grid.width = w;
out->grid.height = h;
out->grid.resolution = static_cast<float>(resolution);
out->grid.origin.position.x = ox;
out->grid.origin.position.y = oy;
out->grid.data.resize(static_cast<size_t>(w) * h);
for (uint32_t y = 0; y < h; ++y) {
for (uint32_t x = 0; x < w; ++x) {
// PGM hang 0 o TREN CUNG; occupancy grid hang 0 o DUOI CUNG (goc o
// origin). Quen lat truc y la loi kinh dien khi doc map, va hau qua la
// ban do bi lat nguoc ma van "trong nhu that".
const uint8_t px = pixels[static_cast<size_t>(h - 1 - y) * w + x];
double occ = (255.0 - static_cast<double>(px)) / 255.0;
if (negate) occ = 1.0 - occ;
int8_t v;
if (occ > out->occupied_thresh) {
v = 100;
} else if (occ < out->free_thresh) {
v = 0;
} else {
v = -1; // chua biet
}
out->grid.data[static_cast<size_t>(y) * w + x] = v;
}
}
VSLAM_INFO("map: nap " << image << " -- " << w << "x" << h << " @ "
<< resolution << " m/o, goc (" << ox << ", " << oy << ")");
return StatusResponse::Ok();
}
StatusResponse SaveOccupancyMap(const OccupancyGrid& grid,
const std::string& yaml_path) {
std::string base = yaml_path;
const size_t dot = base.find_last_of('.');
if (dot != std::string::npos) base = base.substr(0, dot);
const std::string pgm_path = base + ".pgm";
std::ofstream img(pgm_path, std::ios::binary);
if (!img) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + pgm_path);
}
img << "P5\n# sinh boi vslam\n" << grid.width << " " << grid.height << "\n255\n";
for (uint32_t y = 0; y < grid.height; ++y) {
for (uint32_t x = 0; x < grid.width; ++x) {
const int8_t v = grid.data[static_cast<size_t>(grid.height - 1 - y) * grid.width + x];
const uint8_t px = v < 0 ? 205 : (v >= 50 ? 0 : 254);
img.put(static_cast<char>(px));
}
}
img.close();
std::ofstream y(yaml_path);
if (!y) {
return StatusResponse::Error(StatusCode::kUnavailable,
"khong ghi duoc " + yaml_path);
}
const size_t slash = pgm_path.find_last_of('/');
y << "image: " << (slash == std::string::npos ? pgm_path : pgm_path.substr(slash + 1))
<< "\nresolution: " << grid.resolution << "\norigin: [" << grid.origin.position.x
<< ", " << grid.origin.position.y << ", 0.0]\nnegate: 0\n"
<< "occupied_thresh: 0.65\nfree_thresh: 0.196\n";
VSLAM_INFO("map: da ghi " << yaml_path << " va " << pgm_path);
return StatusResponse::Ok();
}
OccupancyGrid MakeSyntheticWorld(uint32_t w, uint32_t h, float res) {
OccupancyGrid m;
m.width = w;
m.height = h;
m.resolution = res;
m.origin.position.x = -static_cast<double>(w) * res / 2.0;
m.origin.position.y = -static_cast<double>(h) * res / 2.0;
m.data.assign(static_cast<size_t>(w) * h, -1);
auto put = [&](uint32_t x, uint32_t y, int8_t v) {
if (x < w && y < h) m.data[static_cast<size_t>(y) * w + x] = v;
};
const uint32_t cy = h / 2;
const uint32_t half = std::max<uint32_t>(6, h / 24);
for (uint32_t x = w / 10; x < w - w / 10; ++x) {
for (uint32_t y = cy - half; y <= cy + half; ++y) put(x, y, 0);
put(x, cy - half - 1, 100);
put(x, cy + half + 1, 100);
}
// Bit hai dau hanh lang, neu khong thi raycast chay ra vo tan.
for (uint32_t y = cy - half - 1; y <= cy + half + 1; ++y) {
put(w / 10, y, 100);
put(w - w / 10 - 1, y, 100);
}
const uint32_t room = half * 3;
for (uint32_t rx = w / 6; rx + room < w - w / 10; rx += room + room / 2) {
for (int side = 0; side < 2; ++side) {
const uint32_t y0 = side == 0 ? cy + half + 2 : cy - half - 2 - room;
for (uint32_t x = rx; x < rx + room; ++x) {
for (uint32_t y = y0; y < y0 + room; ++y) put(x, y, 0);
}
for (uint32_t x = rx - 1; x <= rx + room; ++x) {
put(x, y0 - 1, 100);
put(x, y0 + room, 100);
}
for (uint32_t y = y0 - 1; y <= y0 + room; ++y) {
put(rx - 1, y, 100);
put(rx + room, y, 100);
}
const uint32_t door = rx + room / 2;
for (uint32_t x = door - 2; x <= door + 2; ++x) {
put(x, side == 0 ? y0 - 1 : y0 + room, 0);
}
}
}
return m;
}
} // namespace vslam

File diff suppressed because it is too large Load Diff

View 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})

View 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

View 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

View 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

View 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

View 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

View 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

View 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

View 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

View 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

View File

@@ -0,0 +1,72 @@
# Web UI mot trang thay RViz.
#
# Dep ngoai DUY NHAT them vao: Boost. Va Beast la header-only nen chi phai
# link Boost::system. Day la ly do chon Beast thay vi cai libwebsockets hay
# cpp-httplib: ca hai deu khong co san tren may nao trong hai may dich.
find_package(Boost REQUIRED COMPONENTS system)
# Nhung asset vao .so: Jetson ngoai hien truong phuc vu duoc UI ke ca khi
# /var/lib chua duoc .deb dien, va khong bao gio lech phien ban .so <-> UI.
vslam_embed_assets(vslam_web VSLAM_WEB_ASSETS_SRC
${CMAKE_CURRENT_SOURCE_DIR}/www
index.html
app.js
app3d.js
style.css
# three.js r160 UMD, vendor vao repo CO Y: robot ngoai hien truong khong
# co internet, nen dung CDN la cach chac chan de UI trang tram.
#
# 654 KB -- lon hon toan bo UI con lai 20 lan. Doi lai la mot trinh ve 3D
# da duoc kiem chung, thay vi mot ban WebGL tu viet phai tu go loi trong
# mot san pham co lop an toan.
vendor/three.min.js)
vslam_add_library(vslam_web
PUBLIC_HDRS
web_server.h
web_config.h
web_snapshot.h
binary_codec.h
rle.h
PUBLIC_DEPS
vslam_common
FIND_DEPS
vslam_common
)
# File sinh khong nam trong src/ nen GLOB cua vslam_add_library() khong thay.
target_sources(vslam_web PRIVATE ${VSLAM_WEB_ASSETS_SRC})
# Bien dich file asset KHONG kem debug info.
#
# Day la du lieu MAY SINH: mot mang `const unsigned char[]` 3.5 MB. Khong ai
# dat breakpoint vao no, va DWARF cho no la lang phi thuan tuy. Do duoc:
# `.o` con 726 KB thay vi vai chuc MB.
#
# ⚠️ Dieu nay KHONG lam .so nho di nhieu. `libvslam_web.so` la ~25 MB o ban
# RelWithDebInfo, va gan het den tu `web_server.cc.o` (41.9 MB) -- debug info
# cua Boost.Beast/Asio, co TU TRUOC va khong lien quan asset. Sau `strip` thi
# .so con ~2 MB. three.js chi them ~650 KB vao `.rodata`.
set_source_files_properties(${VSLAM_WEB_ASSETS_SRC} PROPERTIES
COMPILE_OPTIONS "-g0")
target_link_libraries(vslam_web PRIVATE Boost::system)
target_include_directories(vslam_web SYSTEM PRIVATE ${Boost_INCLUDE_DIRS})
# Beast/Asio sinh rat nhieu canh bao trong header cua chinh no tren Boost 1.71
# + GCC 9. Khong tat -Wall cua minh, chi danh dau header cua Boost la SYSTEM
# (o tren) de canh bao cua ho khong lan vao canh bao cua minh.
#
# TUYET DOI KHONG dat BOOST_BEAST_USE_STD_STRING_VIEW hay
# BOOST_ASIO_NO_DEPRECATED o day.
#
# Chung doi DINH NGHIA cua cac kieu va ham inline cua Beast/Asio. Neu lib nay
# compile voi chung con mot TU khac (vd mot test cung include Beast) thi
# khong, linker se gop cac ham inline trung ten va chon MOT ban tuy y -- vi
# pham ODR. Trieu chung da gap: client Beast chay dung khi ban vao server
# ngoai process, nhung cung client do trong cung process voi server thi nem
# std::length_error "field value too large" ngay o request dau tien.
#
# Neu that su can mot co nhu vay thi no phai la PUBLIC de lan sang moi
# consumer, khong bao gio PRIVATE.

View File

@@ -0,0 +1,95 @@
#ifndef VSLAM_BINARY_CODEC_H
#define VSLAM_BINARY_CODEC_H
// Ma hoa nhi phan cho khung WebSocket. Khung text (JSON) lo o json_writer.h.
//
// Header 16 byte, little-endian:
// off size truong
// 0 4 magic 'V','S','L','1'
// 4 1 type
// 5 1 version = 1
// 6 2 flags
// 8 8 stamp_ns (uint64, unix ns)
// 16 ... payload
//
// Vi sao nhi phan chu khong JSON cho phan nay: mot sweep 1081 tia dang JSON
// la ~15 kB va phai parse 1081 so; dang nhi phan la 2198 byte va doc thang
// vao Uint16Array. O 10 Hz thi khac biet la that.
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
enum class BinaryType : uint8_t {
kScan = 1,
kCloud = 2,
kMapFull = 3,
kMapPatch = 4,
kPath = 5,
// Ban do THE GIOI THAT cua bo mo phong -- tuong duong khung nhin Gazebo.
//
// Tach han khoi kMapFull (ban do SLAM DUNG): hai thu do tra loi hai cau hoi
// khac nhau. Ban do the gioi de LAI cho chuan; ban do SLAM de biet phien
// quet dang ra sao. Gop lam mot la mat kha nang doi chieu -- ma doi chieu
// chinh la ly do nguoi ta mo ca Gazebo lan RViz.
//
// TINH: trong mo phong no khong bao gio doi, nen chi gui MOT lan cho moi
// client.
kWorldMap = 6,
};
constexpr size_t kBinaryHeaderSize = 16;
constexpr uint8_t kBinaryVersion = 1;
// Gia tri canh bien cho tia laser, khop ba ngu nghia o vslam_common.h.
// Doc ky: ba thu nay KHAC NHAU va lan lon chung lam robot dung im hoac dam
// vao tuong.
constexpr uint16_t kRangeNaN = 0xFFFF; // khong do duoc (duoi range_min)
constexpr uint16_t kRangeInf = 0xFFFE; // khong co phan xa (vuot range_max)
constexpr uint16_t kRangeBlanked = 0xFFFD; // bi sector mask cat (than robot)
constexpr uint16_t kRangeMaxValid = 0xFFFC; // 65.532 m -- qua du cho 40 m
// Tat ca deu NOI THEM vao `out`, khong xoa truoc. Cho phep gom nhieu khung.
void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out);
// Giam mau xuong `max_points` bang cach lay buoc deu, roi luong tu hoa theo
// `quant_m`. Bo diem NaN.
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
float quant_m, std::string* out);
// RLE hang-chinh. Xem rle.h.
// `type` cho phep dung chung bo ma hoa cho ban do SLAM (kMapFull) va ban do
// THE GIOI cua bo mo phong (kWorldMap): khung giong het nhau, chi khac y
// nghia. Mot bo ma hoa thu hai se la hai cho de lech dinh dang.
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
BinaryType type = BinaryType::kMapFull);
// Chi vung bao (bbox) cac o doi so voi `prev`. Tra false neu kich thuoc hai
// map khac nhau (khi do phai gui MAP_FULL) hoac khong co o nao doi.
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev,
UnixTime stamp, std::string* out);
// Thua hoa: chi giu diem cach diem truoc > min_step_m.
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
std::string* out);
// --- Giai ma, chi dung cho test round-trip --------------------------------
struct BinaryHeader {
BinaryType type = BinaryType::kScan;
uint8_t version = 0;
uint16_t flags = 0;
uint64_t stamp_ns = 0;
};
bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out);
bool DecodeScan(const std::string& buf, LaserScan* out);
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out);
} // namespace vslam
#endif // VSLAM_BINARY_CODEC_H

View File

@@ -0,0 +1,38 @@
#ifndef VSLAM_RLE_H
#define VSLAM_RLE_H
// Ma hoa do dai loat cho occupancy grid.
//
// Moi run la {u16 count, i8 value} = 3 byte, hang-chinh.
// `count` la u16 nen run > 65535 phai TACH -- de quen cho nay la bug im lang
// tren ban do lon.
//
// Do tren du lieu that (tools/probe_rtabmap):
// map_house.db 323x356 -> 5705 run, 17 kB (6.7x)
// map_hospital.db 526x1162 -> 21242 run, 62 kB (9.6x)
//
// Luu y: ban do trong nha o day chi 16-42% la o "chua biet", KHONG phai >90%
// nhu uoc luong ban dau. Ti le nen thuc te vi vay thap hon du kien, nhung
// 62 kB cho ban do lon nhat van du nho de gui mot lan luc ket noi.
#include <cstdint>
#include <string>
#include <vector>
namespace vslam {
// Noi them vao `out`. Tra ve so run da ghi.
size_t RleEncode(const std::vector<int8_t>& data, std::string* out);
// Doc `count` run tu `buf` bat dau tu `offset`, ghi vao `out`.
// Tra false neu du lieu cut hoac kich thuoc khong khop `expected_size`.
bool RleDecode(const std::string& buf, size_t offset, size_t run_count,
size_t expected_size, std::vector<int8_t>* out);
// So byte can de ma hoa `data` (= so run * 3). Dung de quyet dinh gui
// MAP_FULL hay MAP_PATCH ma khong phai ma hoa hai lan.
size_t RleEncodedSize(const std::vector<int8_t>& data);
} // namespace vslam
#endif // VSLAM_RLE_H

View File

@@ -0,0 +1,51 @@
#ifndef VSLAM_WEB_CONFIG_H
#define VSLAM_WEB_CONFIG_H
#include <cstdint>
#include <string>
namespace vslam {
struct WebConfig {
// --- Mang -------------------------------------------------------------
std::string bind_address = "0.0.0.0";
uint16_t port = 8080;
int io_threads = 1; // 1 la du: moi viec nang deu o luong khac
// --- Bao mat ----------------------------------------------------------
// Neu dat: moi POST /api/* can header X-Auth-Token, WS upgrade can ?token=
// Neu bo trong: log WARN to luc khoi dong.
//
// BAT DOI XUNG CO Y (xem web_server.cc):
// BAT e-stop -> luon duoc phep, khong can token (fail-safe)
// GO e-stop -> BAT BUOC co token
// reset bumper -> BAT BUOC co token
// Mot endpoint e-stop khong xac thuc tren WiFi LAN nghia la bat ky ai trong
// mang deu e-stop duoc; nhung te hon nhieu la GO duoc e-stop cua nguoi khac.
std::string auth_token;
// --- Tan so gui -------------------------------------------------------
double state_hz = 10.0; // JSON: pose, safety, slam, health
double scan_hz = 10.0; // giam mau tu 25 Hz cua LiDAR
double cloud_hz = 2.0;
double path_hz = 1.0;
// MAP khong co tan so: chi gui khi map_version doi.
// --- Giam bang thong --------------------------------------------------
uint32_t cloud_max_points = 4000; // voxel-stride truoc khi ma hoa
float cloud_quant_m = 0.01f; // luong tu hoa i16 -> dai +-327 m
double path_min_step_m = 0.1; // thua hoa quy dao
// Hang doi gui moi phien. Day thi drop khung CU NHAT khong phai MAP.
// MAP khong bao gio bi drop -- thay vao do bat co map_pending.
size_t max_queued_frames = 4;
// --- Asset ------------------------------------------------------------
// Rong = dung asset nhung trong binary (mac dinh, va la cach .deb chay).
// Co gia tri = doc tu dia, che do dev: sua CSS khong phai build lai.
std::string asset_dir;
};
} // namespace vslam
#endif // VSLAM_WEB_CONFIG_H

View File

@@ -0,0 +1,95 @@
#ifndef VSLAM_WEB_SERVER_H
#define VSLAM_WEB_SERVER_H
// Web UI mot trang thay RViz. HTTP + WebSocket tren Boost.Beast.
//
// KIEN TRUC:
// * io_context chay tren `io_threads` luong (mac dinh 1 -- moi viec nang
// nam o luong khac).
// * Publish() goi tu luong web_tx o 10 Hz, KHONG BAO GIO CHAN: no serialize
// roi asio::post sang strand cua tung phien.
// * Luong web KHONG BAO GIO sua state cua estimator. Moi POST /api/* di qua
// CommandHandler -> hang doi lenh -> luong so huu tai nguyen drain.
//
// GIAO THUC: mot WebSocket /ws, hai loai khung.
// Text = JSON, du lieu tan so thap, nguoi doc duoc.
// Binary = scan / cloud / map / path, header 16 byte (xem binary_codec.h).
#include <cstddef>
#include <functional>
#include <memory>
#include <string>
#include "vslam/web_config.h"
#include "vslam/web_snapshot.h"
#include "vslam/vslam_common.h"
namespace vslam {
// Trang thai dung chung cua server. Dinh nghia trong web_server.cc.
//
// KHONG lam struct long trong WebServer: cac lop phien (HttpSession,
// WsSession) o file .cc phai truy cap duoc, ma mot kieu long private thi ho
// khong goi ten duoc. Day la cung lop loi da gap o ConfigNode::Impl.
class WebServerImpl;
class WebServer {
public:
// Xu ly lenh tu POST /api/<cmd>. `json_args` la body tho (co the rong).
// Duoc goi TREN LUONG IO -- phai tra ve ngay, khong duoc chan. Cach dung
// dung la day vao hang doi roi tra Ok.
using CommandHandler =
std::function<StatusResponse(const std::string& cmd, const std::string& json_args)>;
// Teleop tu joypad cam ung, gia tri chuan hoa [-1, 1] o 20 Hz.
// TOAN BO shaping (ramp gia toc, deadman) lam o C++ trong teleop_shaper,
// KHONG o JS: khong bao gio tin browser ve dinh dang chuyen dong, vi WS co
// the lag hoac mat ket noi giua chung.
using TeleopHandler = std::function<void(double vx_norm, double wz_norm)>;
WebServer(WebConfig cfg, CommandHandler on_command, TeleopHandler on_teleop);
~WebServer();
WebServer(const WebServer&) = delete;
WebServer& operator=(const WebServer&) = delete;
StatusResponse Start();
void Stop();
// Khong chan. An toan goi tu bat ky luong nao.
void Publish(const WebSnapshot& snap);
// Khoi hinh hoc 3D cua the gioi, phuc vu tai `GET /api/world.bin`.
//
// Dat MOT lan luc khoi dong roi thoi -- the gioi khong doi trong mot phien.
// Trinh duyet tai no mot lan de dung do dac THAT thay vi khoi hop dung tu
// luoi chiem dung. Rong = khong co, trinh duyet quay ve khoi hop.
void SetWorldMesh(std::string blob);
size_t client_count() const;
// Cong thuc su dang nghe. Khac cfg.port khi cau hinh port=0 (test).
uint16_t port() const;
struct Stats {
uint64_t connections_total = 0;
uint64_t frames_sent = 0;
uint64_t frames_dropped = 0; // hang doi phien day
uint64_t bytes_sent = 0;
uint64_t commands_handled = 0;
uint64_t auth_failures = 0;
};
Stats stats() const;
private:
void DoAccept();
// shared_ptr chu khong unique_ptr: moi phien HTTP/WS giu mot tham chieu toi
// trang thai nay va co the song lau hon loi goi Stop() mot chut (async
// handler dang bay). unique_ptr o day la use-after-free luc tat may.
std::shared_ptr<WebServerImpl> impl_;
};
} // namespace vslam
#endif // VSLAM_WEB_SERVER_H

View File

@@ -0,0 +1,142 @@
#ifndef VSLAM_WEB_SNAPSHOT_H
#define VSLAM_WEB_SNAPSHOT_H
// Anh chup trang thai he thong tai mot thoi diem, do luong web_tx dung tu
// Channel::Latest() cua tung kenh roi day sang WebServer::Publish().
//
// Moi truong du lieu lon la shared_ptr<const T>: khong copy cloud/scan/map.
// Neu khong co client nao ket noi thi web_tx khong serialize gi ca -- kiem
// bang WebServer::client_count() TRUOC khi dung Snapshot.
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "vslam/stats.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct SafetySnapshot {
std::string state = "OK"; // ten trang thai FSM
std::string detail;
double min_front = 0.0; // met; INFINITY neu khong do duoc
int front_rays = 0; // tong so tia trong quat truoc
int front_blanked = 0; // tia bi sector mask cat (sentinel range_max+1)
int front_usable = 0; // tia thuc su dung duoc
bool estop = false;
bool bumper_latched = false;
bool cliff = false;
};
struct SlamSnapshot {
std::string mode = "idle"; // mapping | localization | update_map | idle
bool localized = false;
double score = 0.0;
int loop_closure_id = 0;
uint32_t map_version = 0;
double process_ms = 0.0;
};
struct TeleopSnapshot {
double linear_speed = 0.0; // scale hien tai, chinh duoc luc chay
double angular_speed = 0.0;
double max_linear_speed = 0.0;
double max_angular_speed = 0.0;
};
struct HealthSnapshot {
double lidar_hz = 0.0;
double camera_hz = 0.0;
double imu_hz = 0.0;
double ekf_hz = 0.0;
double clock_skew = 1.0; // he so skew cua ClockSync (1.0 = khop)
double cpu_pct = 0.0;
double rss_mb = 0.0;
// Ten kenh -> so ban tin bi drop. Day la thu queue cua ROS khong cho biet.
std::vector<std::pair<std::string, uint64_t>> drops;
};
// Hinh hoc robot cho trinh ve 3D, lay tu `robot.yaml` qua `RobotModel`.
//
// ⚠️ TRINH DUYET KHONG DUOC TU DOAN KICH THUOC. Truoc khi co khoi nay, app.js
// hardcode `L = 0.30, W = 0.17` -- khong khop voi bat ky so nao trong
// robot.yaml (ban kinh that la 0.24). Do la dung lop bug "hai cho phai giu
// dong bo" ma `RobotModel` sinh ra de xoa, chi la no da tron sang JavaScript.
//
// Gui moi khung: ~120 byte, khong dang ke so voi ngan sach 120 kB/s. Doi lai
// UI khong can bat tay rieng va khong bao gio hien sai kich thuoc sau khi
// nguoi dung sua robot.yaml.
struct RobotShape {
bool valid = false;
double radius = 0.24; // ban kinh bao than, cho footprint
double wheel_radius = 0.075;
double wheel_separation = 0.36;
double body_half_width = 0.17;
// Vi tri cam bien trong base_link (met). z do tu TAM TRUC banh, khong tu
// san -- trinh ve tu cong wheel_radius khi can toa do so voi san.
double laser_x = 0.24, laser_y = 0.0, laser_z = 0.125;
double camera_x = 0.19, camera_y = 0.0, camera_z = 0.725;
double camera_pitch = 0.2618; // rad, DUONG la chuc XUONG
// Goc mo cua camera depth, de ve frustum. Khong doc duoc tu robot.yaml --
// day la thong so ONG KINH, lay tu CameraInfo khi co, khong thi mac dinh
// theo D410 (69 do ngang).
double camera_hfov = 1.204; // rad
double camera_vfov = 0.733;
// Cua so cliff_detect, de ve vung mu len san. Duoi `cliff_min` camera
// KHONG THAY GI -- do la vung hinh hoc, khong phai lua chon.
double cliff_min = 1.10;
double cliff_max = 2.50;
};
struct WebSnapshot {
UnixTime stamp;
RobotShape robot;
Pose2D pose_map; // pose trong frame map
Pose2D pose_odom;
double vx = 0.0;
double vyaw = 0.0;
double slip_metric = 0.0;
double roll = 0.0; // DO tu IMU, khong uoc luong
double pitch = 0.0;
bool accel_ok = true;
// ============ GROUND TRUTH ============
// CHI co khi chay mo phong. Day la tuong duong cua /ground_truth/odom trong
// repo cu, noi ghi ro "khong estimator nao duoc subscribe".
//
// No len web vi do la cach DUY NHAT nhin thay drift. RViz ve duoc ca pose
// uoc luong lan ground truth canh nhau; khong co no thi mot ban do dep va
// mot ban do SAI trong y het nhau.
//
// ⚠️ KHONG stage nao duoc doc gia tri nay. No di thang tu nguon len web.
bool have_ground_truth = false;
Pose2D ground_truth;
double gt_roll = 0.0; // nghieng THAT, de doi chung gravity_align
double gt_pitch = 0.0;
SafetySnapshot safety;
SlamSnapshot slam;
HealthSnapshot health;
TeleopSnapshot teleop;
LaserScanPtr scan;
PointCloudXYZPtr cloud;
OccupancyGridPtr map; // ban do SLAM dung
// Ban do THE GIOI cua bo mo phong (khung nhin "Gazebo"). Null khi chay
// that -- luc do khong co su that nao de doi chieu.
OccupancyGridPtr world_map;
std::vector<Pose2D> trajectory;
};
} // namespace vslam
#endif // VSLAM_WEB_SNAPSHOT_H

View File

@@ -0,0 +1,330 @@
#include "vslam/binary_codec.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>
#include "vslam/rle.h"
namespace vslam {
namespace {
void PutU8(std::string* out, uint8_t v) { out->push_back(static_cast<char>(v)); }
void PutU16(std::string* out, uint16_t v) {
out->push_back(static_cast<char>(v & 0xFF));
out->push_back(static_cast<char>((v >> 8) & 0xFF));
}
void PutU32(std::string* out, uint32_t v) {
for (int i = 0; i < 4; ++i) out->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutI32(std::string* out, int32_t v) { PutU32(out, static_cast<uint32_t>(v)); }
void PutU64(std::string* out, uint64_t v) {
for (int i = 0; i < 8; ++i) out->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
}
void PutF32(std::string* out, float v) {
uint32_t bits;
std::memcpy(&bits, &v, 4);
PutU32(out, bits);
}
void PutI16(std::string* out, int16_t v) { PutU16(out, static_cast<uint16_t>(v)); }
uint16_t GetU16(const std::string& b, size_t o) {
return static_cast<uint16_t>(static_cast<uint8_t>(b[o])) |
(static_cast<uint16_t>(static_cast<uint8_t>(b[o + 1])) << 8);
}
uint32_t GetU32(const std::string& b, size_t o) {
uint32_t v = 0;
for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
return v;
}
uint64_t GetU64(const std::string& b, size_t o) {
uint64_t v = 0;
for (int i = 0; i < 8; ++i) v |= static_cast<uint64_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
return v;
}
float GetF32(const std::string& b, size_t o) {
const uint32_t bits = GetU32(b, o);
float f;
std::memcpy(&f, &bits, 4);
return f;
}
int32_t GetI32(const std::string& b, size_t o) {
return static_cast<int32_t>(GetU32(b, o));
}
void PutHeader(std::string* out, BinaryType type, UnixTime stamp, uint16_t flags = 0) {
out->append("VSL1", 4);
PutU8(out, static_cast<uint8_t>(type));
PutU8(out, kBinaryVersion);
PutU16(out, flags);
PutU64(out, static_cast<uint64_t>(stamp.toNSec()));
}
// Ba ngu nghia cua mot tia -> ba gia tri canh bien. Xem vslam_common.h.
uint16_t RangeToMm(float r, float range_max) {
if (std::isnan(r)) return kRangeNaN;
if (std::isinf(r)) return kRangeInf;
// Sentinel "bi che boi than robot" la range_max + 1.0, dat boi sector mask
// cua ScanSanitizer. Phai phan biet duoc voi inf: inf nghia la "nhin duoc
// nhung khong co gi", sentinel nghia la "khong duoc phep nhin".
if (r > range_max + 0.5f) return kRangeBlanked;
if (r < 0.0f) return kRangeNaN;
const float mm = r * 1000.0f;
if (mm >= static_cast<float>(kRangeMaxValid)) return kRangeMaxValid;
return static_cast<uint16_t>(mm + 0.5f);
}
} // namespace
void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out) {
PutHeader(out, BinaryType::kScan, stamp);
PutF32(out, scan.angle_min);
PutF32(out, scan.angle_increment);
PutF32(out, scan.range_min);
PutF32(out, scan.range_max);
PutU32(out, static_cast<uint32_t>(scan.ranges.size()));
for (const float r : scan.ranges) {
PutU16(out, RangeToMm(r, scan.range_max));
}
}
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
float quant_m, std::string* out) {
if (quant_m <= 0.0f) quant_m = 0.01f;
// Lay buoc deu thay vi cat duoi: cat duoi lam mat ca mot vung khong gian,
// buoc deu giu duoc hinh dang tong the.
const size_t n_in = cloud.points.size();
const size_t stride =
(max_points > 0 && n_in > max_points) ? (n_in + max_points - 1) / max_points : 1;
// Dem truoc so diem hop le de khong phai sua lai truong n sau khi ghi.
uint32_t n_out = 0;
for (size_t i = 0; i < n_in; i += stride) {
const PointXYZ& p = cloud.points[i];
if (std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z)) ++n_out;
}
PutHeader(out, BinaryType::kCloud, stamp);
// Goc = (0,0,0): cloud da o frame base_footprint sau gravity_align.
PutF32(out, 0.0f);
PutF32(out, 0.0f);
PutF32(out, 0.0f);
PutF32(out, quant_m);
PutU32(out, n_out);
const float inv = 1.0f / quant_m;
constexpr float kLim = 32767.0f;
for (size_t i = 0; i < n_in; i += stride) {
const PointXYZ& p = cloud.points[i];
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
// Kep vao dai i16. Voi quant 0.01 m thi dai la +-327 m -- khong bao gio
// cham toi trong nha, nhung kep van re hon la de tran am tham.
const float qx = std::max(-kLim, std::min(kLim, p.x * inv));
const float qy = std::max(-kLim, std::min(kLim, p.y * inv));
const float qz = std::max(-kLim, std::min(kLim, p.z * inv));
PutI16(out, static_cast<int16_t>(std::lround(qx)));
PutI16(out, static_cast<int16_t>(std::lround(qy)));
PutI16(out, static_cast<int16_t>(std::lround(qz)));
}
}
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
BinaryType type) {
PutHeader(out, type, stamp);
PutF32(out, map.resolution);
PutI32(out, static_cast<int32_t>(map.width));
PutI32(out, static_cast<int32_t>(map.height));
PutF32(out, static_cast<float>(map.origin.position.x));
PutF32(out, static_cast<float>(map.origin.position.y));
// Goc quay cua ban do: RTAB-Map luon tra ban do truc giao nen thuong la 0,
// nhung giu truong nay de khong phai doi dinh dang neu sau co xoay.
PutF32(out, 0.0f);
// Ghi truoc so run = 0 roi vá lai sau khi ma hoa: khong phai ma hoa hai lan.
const size_t run_count_off = out->size();
PutU32(out, 0);
const size_t runs = RleEncode(map.data, out);
const uint32_t r32 = static_cast<uint32_t>(runs);
for (int i = 0; i < 4; ++i) {
(*out)[run_count_off + static_cast<size_t>(i)] =
static_cast<char>((r32 >> (8 * i)) & 0xFF);
}
}
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev,
UnixTime stamp, std::string* out) {
// Kich thuoc doi -> khong vá duoc, phai gui full.
if (map.width != prev.width || map.height != prev.height ||
map.data.size() != prev.data.size() ||
std::abs(map.resolution - prev.resolution) > 1e-6f ||
std::abs(map.origin.position.x - prev.origin.position.x) > 1e-6 ||
std::abs(map.origin.position.y - prev.origin.position.y) > 1e-6) {
return false;
}
// Vung bao cac o doi.
int32_t x0 = static_cast<int32_t>(map.width);
int32_t y0 = static_cast<int32_t>(map.height);
int32_t x1 = -1, y1 = -1;
for (uint32_t y = 0; y < map.height; ++y) {
const size_t row = static_cast<size_t>(y) * map.width;
for (uint32_t x = 0; x < map.width; ++x) {
if (map.data[row + x] == prev.data[row + x]) continue;
const int32_t xi = static_cast<int32_t>(x);
const int32_t yi = static_cast<int32_t>(y);
if (xi < x0) x0 = xi;
if (yi < y0) y0 = yi;
if (xi > x1) x1 = xi;
if (yi > y1) y1 = yi;
}
}
if (x1 < 0) return false; // khong o nao doi
const int32_t w = x1 - x0 + 1;
const int32_t h = y1 - y0 + 1;
std::vector<int8_t> patch;
patch.reserve(static_cast<size_t>(w) * static_cast<size_t>(h));
for (int32_t y = y0; y <= y1; ++y) {
const size_t row = static_cast<size_t>(y) * map.width;
for (int32_t x = x0; x <= x1; ++x) {
patch.push_back(map.data[row + static_cast<size_t>(x)]);
}
}
PutHeader(out, BinaryType::kMapPatch, stamp);
PutI32(out, x0);
PutI32(out, y0);
PutI32(out, w);
PutI32(out, h);
const size_t run_count_off = out->size();
PutU32(out, 0);
const size_t runs = RleEncode(patch, out);
const uint32_t r32 = static_cast<uint32_t>(runs);
for (int i = 0; i < 4; ++i) {
(*out)[run_count_off + static_cast<size_t>(i)] =
static_cast<char>((r32 >> (8 * i)) & 0xFF);
}
return true;
}
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
std::string* out) {
std::vector<const Pose2D*> kept;
kept.reserve(path.size());
const double min_sq = min_step_m * min_step_m;
const Pose2D* last = nullptr;
for (const auto& p : path) {
if (last != nullptr) {
const double dx = p.x - last->x, dy = p.y - last->y;
if (dx * dx + dy * dy < min_sq) continue;
}
kept.push_back(&p);
last = &p;
}
// Luon giu diem cuoi: do la vi tri hien tai, mat no thi duong di trong nhu
// dang tut hau.
if (!path.empty() && (kept.empty() || kept.back() != &path.back())) {
kept.push_back(&path.back());
}
PutHeader(out, BinaryType::kPath, stamp);
PutU32(out, static_cast<uint32_t>(kept.size()));
for (const Pose2D* p : kept) {
PutF32(out, static_cast<float>(p->x));
PutF32(out, static_cast<float>(p->y));
}
}
// --- Giai ma (test) --------------------------------------------------------
bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out) {
if (buf.size() < offset + kBinaryHeaderSize) return false;
if (std::memcmp(buf.data() + offset, "VSL1", 4) != 0) return false;
out->type = static_cast<BinaryType>(static_cast<uint8_t>(buf[offset + 4]));
out->version = static_cast<uint8_t>(buf[offset + 5]);
out->flags = GetU16(buf, offset + 6);
out->stamp_ns = GetU64(buf, offset + 8);
return true;
}
bool DecodeScan(const std::string& buf, LaserScan* out) {
BinaryHeader h;
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kScan) return false;
size_t o = kBinaryHeaderSize;
if (buf.size() < o + 20) return false;
out->angle_min = GetF32(buf, o); o += 4;
out->angle_increment = GetF32(buf, o); o += 4;
out->range_min = GetF32(buf, o); o += 4;
out->range_max = GetF32(buf, o); o += 4;
const uint32_t n = GetU32(buf, o); o += 4;
if (buf.size() < o + static_cast<size_t>(n) * 2) return false;
out->ranges.clear();
out->ranges.reserve(n);
for (uint32_t i = 0; i < n; ++i) {
const uint16_t v = GetU16(buf, o + static_cast<size_t>(i) * 2);
switch (v) {
case kRangeNaN:
out->ranges.push_back(std::numeric_limits<float>::quiet_NaN());
break;
case kRangeInf:
out->ranges.push_back(std::numeric_limits<float>::infinity());
break;
case kRangeBlanked:
out->ranges.push_back(out->range_max + 1.0f);
break;
default:
out->ranges.push_back(static_cast<float>(v) * 0.001f);
break;
}
}
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
return true;
}
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) {
BinaryHeader h;
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false;
size_t o = kBinaryHeaderSize;
if (buf.size() < o + 28) return false;
out->resolution = GetF32(buf, o); o += 4;
out->width = static_cast<uint32_t>(GetI32(buf, o)); o += 4;
out->height = static_cast<uint32_t>(GetI32(buf, o)); o += 4;
out->origin.position.x = GetF32(buf, o); o += 4;
out->origin.position.y = GetF32(buf, o); o += 4;
o += 4; // oyaw
const uint32_t runs = GetU32(buf, o); o += 4;
const size_t expected = static_cast<size_t>(out->width) * out->height;
if (!RleDecode(buf, o, runs, expected, &out->data)) return false;
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,213 @@
#include "json_writer.h"
#include "vslam/geometry.h"
#include <cmath>
#include <cstdio>
namespace vslam {
namespace {
void Key(const char* k, std::string* out) {
out->push_back('"');
out->append(k);
out->append("\":");
}
void Comma(std::string* out) { out->push_back(','); }
void Str(const char* k, const std::string& v, std::string* out) {
Key(k, out);
out->push_back('"');
JsonEscape(v, out);
out->push_back('"');
}
void Num(const char* k, double v, int dec, std::string* out) {
Key(k, out);
JsonNumber(v, dec, out);
}
void Int(const char* k, long long v, std::string* out) {
Key(k, out);
char buf[24];
std::snprintf(buf, sizeof(buf), "%lld", v);
out->append(buf);
}
void Bool(const char* k, bool v, std::string* out) {
Key(k, out);
out->append(v ? "true" : "false");
}
} // namespace
void JsonEscape(const std::string& in, std::string* out) {
for (const char c : in) {
switch (c) {
case '"': out->append("\\\""); break;
case '\\': out->append("\\\\"); break;
case '\n': out->append("\\n"); break;
case '\r': out->append("\\r"); break;
case '\t': out->append("\\t"); break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned char>(c));
out->append(buf);
} else {
out->push_back(c);
}
}
}
}
void JsonNumber(double v, int decimals, std::string* out) {
// JSON khong co NaN/Infinity. De nguyen thi JSON.parse() nem loi va browser
// mat CA khung chu khong chi mot truong -- mot min_front = inf (hop le, co
// nghia "khong thay gi") se lam ca bang trang thai bien mat.
if (!std::isfinite(v)) {
out->append("null");
return;
}
char buf[40];
std::snprintf(buf, sizeof(buf), "%.*f", decimals, v);
out->append(buf);
}
void WriteStateJson(const WebSnapshot& s, std::string* out) {
out->append("{\"t\":\"state\",");
Num("stamp", s.stamp.toSec(), 3, out); Comma(out);
// Hinh hoc robot -- trinh duyet KHONG duoc tu doan kich thuoc.
//
// Chi xuat khi `valid`: mot trinh ve nhan so 0 se dung ban kinh 0 va ve ra
// mot cham, con nhan KHONG GI thi biet la chua co du lieu va bao ro.
if (s.robot.valid) {
Key("robot", out);
out->push_back('{');
Num("radius", s.robot.radius, 4, out); Comma(out);
Num("wheel_radius", s.robot.wheel_radius, 4, out); Comma(out);
Num("wheel_sep", s.robot.wheel_separation, 4, out); Comma(out);
Num("half_width", s.robot.body_half_width, 4, out); Comma(out);
Num("laser_x", s.robot.laser_x, 4, out); Comma(out);
Num("laser_y", s.robot.laser_y, 4, out); Comma(out);
Num("laser_z", s.robot.laser_z, 4, out); Comma(out);
Num("cam_x", s.robot.camera_x, 4, out); Comma(out);
Num("cam_y", s.robot.camera_y, 4, out); Comma(out);
Num("cam_z", s.robot.camera_z, 4, out); Comma(out);
Num("cam_pitch", s.robot.camera_pitch, 4, out); Comma(out);
Num("cam_hfov", s.robot.camera_hfov, 4, out); Comma(out);
Num("cam_vfov", s.robot.camera_vfov, 4, out); Comma(out);
Num("cliff_min", s.robot.cliff_min, 3, out); Comma(out);
Num("cliff_max", s.robot.cliff_max, 3, out);
out->push_back('}');
Comma(out);
}
Key("pose", out);
out->push_back('{');
Num("x", s.pose_map.x, 3, out); Comma(out);
Num("y", s.pose_map.y, 3, out); Comma(out);
Num("yaw", s.pose_map.theta, 4, out);
out->push_back('}'); Comma(out);
// Ground truth chi xuat khi CO. Xuat 0 khi khong co la noi doi: client
// khong phan biet duoc "dung o goc" voi "khong biet".
if (s.have_ground_truth) {
Key("gt", out);
out->push_back('{');
Num("x", s.ground_truth.x, 3, out); Comma(out);
Num("y", s.ground_truth.y, 3, out); Comma(out);
Num("yaw", s.ground_truth.theta, 4, out); Comma(out);
Num("roll", s.gt_roll, 4, out); Comma(out);
Num("pitch", s.gt_pitch, 4, out); Comma(out);
// Sai so vi tri cua uoc luong so voi su that. Tinh o day thay vi de
// client tu tru: neu sau nay map va gt khac goc toa do thi phep tru
// ngay tren client se sai am tham.
Num("err", Distance2D(s.pose_map, s.ground_truth), 4, out);
out->push_back('}');
Comma(out);
}
Key("odom", out);
out->push_back('{');
Num("x", s.pose_odom.x, 3, out); Comma(out);
Num("y", s.pose_odom.y, 3, out); Comma(out);
Num("yaw", s.pose_odom.theta, 4, out); Comma(out);
Num("vx", s.vx, 3, out); Comma(out);
Num("vyaw", s.vyaw, 3, out); Comma(out);
Num("slip", s.slip_metric, 3, out);
out->push_back('}'); Comma(out);
Key("tilt", out);
out->push_back('{');
Num("roll", s.roll, 4, out); Comma(out);
Num("pitch", s.pitch, 4, out); Comma(out);
Bool("accel_ok", s.accel_ok, out);
out->push_back('}'); Comma(out);
Key("safety", out);
out->push_back('{');
Str("state", s.safety.state, out); Comma(out);
Str("detail", s.safety.detail, out); Comma(out);
Num("min_front", s.safety.min_front, 3, out); Comma(out);
Int("front_rays", s.safety.front_rays, out); Comma(out);
Int("front_blanked", s.safety.front_blanked, out); Comma(out);
Int("front_usable", s.safety.front_usable, out); Comma(out);
Bool("estop", s.safety.estop, out); Comma(out);
Bool("bumper_latched", s.safety.bumper_latched, out); Comma(out);
Bool("cliff", s.safety.cliff, out);
out->push_back('}'); Comma(out);
Key("slam", out);
out->push_back('{');
Str("mode", s.slam.mode, out); Comma(out);
Bool("localized", s.slam.localized, out); Comma(out);
Num("score", s.slam.score, 3, out); Comma(out);
Int("loop_id", s.slam.loop_closure_id, out); Comma(out);
Int("map_version", s.slam.map_version, out); Comma(out);
Num("process_ms", s.slam.process_ms, 1, out);
out->push_back('}'); Comma(out);
Key("teleop", out);
out->push_back('{');
Num("linear_speed", s.teleop.linear_speed, 3, out); Comma(out);
Num("angular_speed", s.teleop.angular_speed, 3, out); Comma(out);
Num("max_linear_speed", s.teleop.max_linear_speed, 3, out); Comma(out);
Num("max_angular_speed", s.teleop.max_angular_speed, 3, out);
out->push_back('}'); Comma(out);
Key("health", out);
out->push_back('{');
Num("lidar_hz", s.health.lidar_hz, 1, out); Comma(out);
Num("camera_hz", s.health.camera_hz, 1, out); Comma(out);
Num("imu_hz", s.health.imu_hz, 1, out); Comma(out);
Num("ekf_hz", s.health.ekf_hz, 1, out); Comma(out);
Num("clock_skew", s.health.clock_skew, 7, out); Comma(out);
Num("cpu_pct", s.health.cpu_pct, 1, out); Comma(out);
Num("rss_mb", s.health.rss_mb, 0, out); Comma(out);
Key("drops", out);
out->push_back('{');
bool first = true;
for (const auto& kv : s.health.drops) {
if (!first) Comma(out);
first = false;
Int(kv.first.c_str(), static_cast<long long>(kv.second), out);
}
out->push_back('}');
out->push_back('}');
out->push_back('}');
}
void WriteStatusJson(const StatusResponse& st, std::string* out) {
out->push_back('{');
Int("code", static_cast<long long>(st.code), out);
Comma(out);
Str("message", st.message, out);
out->push_back('}');
}
} // namespace vslam

View File

@@ -0,0 +1,36 @@
#ifndef VSLAM_JSON_WRITER_H_
#define VSLAM_JSON_WRITER_H_
// Sinh JSON bang cach noi chuoi. Header NOI BO, khong phat hanh.
//
// Vi sao khong dung nlohmann/json: no khong co san tren may nao trong hai may
// (dev focal lan Jetson jammy), va schema o day co dinh va nho -- mot
// serializer ~150 dong khong phai danh doi gi dang ke.
//
// Chi ho tro chieu GHI. Doc JSON (body cua POST /api/*) lam bang json_parse.h,
// cung mot ly do.
#include <string>
#include <vector>
#include "vslam/web_snapshot.h"
namespace vslam {
// Escape theo RFC 8259: ", \, va cac ky tu dieu khien < 0x20.
void JsonEscape(const std::string& in, std::string* out);
// Ghi so thuc voi so chu so co dinh. Tra "null" neu NaN hoac inf -- JSON
// khong co hai gia tri do, va de nguyen thi JSON.parse() cua browser nem loi
// lam mat CA khung, khong chi mot truong.
void JsonNumber(double v, int decimals, std::string* out);
// Toan bo khung trang thai, khop schema mo ta trong ke hoach.
void WriteStateJson(const WebSnapshot& snap, std::string* out);
// Tra loi cho POST /api/*.
void WriteStatusJson(const StatusResponse& st, std::string* out);
} // namespace vslam
#endif // VSLAM_JSON_WRITER_H_

85
libs/vslam_web/src/rle.cc Normal file
View File

@@ -0,0 +1,85 @@
#include "vslam/rle.h"
#include <cstring>
namespace vslam {
namespace {
constexpr uint16_t kMaxRun = 65535;
void PutU16(std::string* out, uint16_t v) {
out->push_back(static_cast<char>(v & 0xFF));
out->push_back(static_cast<char>((v >> 8) & 0xFF));
}
uint16_t GetU16(const std::string& buf, size_t off) {
return static_cast<uint16_t>(static_cast<uint8_t>(buf[off])) |
(static_cast<uint16_t>(static_cast<uint8_t>(buf[off + 1])) << 8);
}
} // namespace
size_t RleEncode(const std::vector<int8_t>& data, std::string* out) {
if (data.empty()) return 0;
size_t runs = 0;
int8_t value = data[0];
uint32_t len = 1;
for (size_t i = 1; i < data.size(); ++i) {
if (data[i] == value && len < kMaxRun) {
++len;
continue;
}
PutU16(out, static_cast<uint16_t>(len));
out->push_back(static_cast<char>(value));
++runs;
value = data[i];
len = 1;
}
PutU16(out, static_cast<uint16_t>(len));
out->push_back(static_cast<char>(value));
++runs;
return runs;
}
size_t RleEncodedSize(const std::vector<int8_t>& data) {
if (data.empty()) return 0;
size_t runs = 1;
int8_t value = data[0];
uint32_t len = 1;
for (size_t i = 1; i < data.size(); ++i) {
if (data[i] == value && len < kMaxRun) {
++len;
continue;
}
++runs;
value = data[i];
len = 1;
}
return runs * 3;
}
bool RleDecode(const std::string& buf, size_t offset, size_t run_count,
size_t expected_size, std::vector<int8_t>* out) {
if (offset + run_count * 3 > buf.size()) return false;
out->clear();
out->reserve(expected_size);
for (size_t r = 0; r < run_count; ++r) {
const size_t off = offset + r * 3;
const uint16_t len = GetU16(buf, off);
const int8_t value = static_cast<int8_t>(buf[off + 2]);
// Chan phinh bo nho neu du lieu hong: khong reserve theo len chua kiem.
if (out->size() + len > expected_size) return false;
out->insert(out->end(), len, value);
}
return out->size() == expected_size;
}
} // namespace vslam

View File

@@ -0,0 +1,29 @@
#ifndef VSLAM_WEB_ASSETS_H_
#define VSLAM_WEB_ASSETS_H_
// Asset tinh (html/js/css) nhung trong .so luc build boi vslam_embed_assets()
// trong cmake/vslam_helpers.cmake.
//
// Vi sao nhung chu khong doc tu dia: Jetson ngoai hien truong phai phuc vu
// duoc UI ke ca khi /var/lib chua duoc .deb dien, va lech phien ban giua .so
// voi UI la chi phi ho tro co that.
//
// Cua hau: WebConfig::asset_dir khac rong thi doc tu dia (che do dev).
#include <cstddef>
#include <map>
#include <string>
namespace vslam {
struct EmbeddedAsset {
const unsigned char* data;
std::size_t size;
};
// Dinh nghia nam trong web_assets_generated.cc do CMake sinh.
const std::map<std::string, EmbeddedAsset>& EmbeddedAssets();
} // namespace vslam
#endif // VSLAM_WEB_ASSETS_H_

View File

@@ -0,0 +1,779 @@
#include "vslam/web_server.h"
#include <boost/asio/dispatch.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/strand.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
#include <algorithm>
#include <atomic>
#include <deque>
#include <fstream>
#include <memory>
#include <mutex>
#include <map>
#include <set>
#include <sstream>
#include <thread>
#include <vector>
#include "vslam/json_parse.h"
#include "json_writer.h"
#include "vslam/binary_codec.h"
#include "vslam/log.h"
#include "web_assets.h"
namespace vslam {
namespace {
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace asio = boost::asio;
using tcp = asio::ip::tcp;
const char* MimeType(const std::string& path) {
const size_t dot = path.rfind('.');
const std::string ext = dot == std::string::npos ? "" : path.substr(dot);
if (ext == ".html") return "text/html; charset=utf-8";
if (ext == ".js") return "application/javascript; charset=utf-8";
if (ext == ".css") return "text/css; charset=utf-8";
if (ext == ".json") return "application/json";
if (ext == ".svg") return "image/svg+xml";
if (ext == ".ico") return "image/x-icon";
return "application/octet-stream";
}
// Chan duong dan di len tren (..) va duong dan tuyet doi. Endpoint nay khong
// xac thuc nen phai gia dinh duong dan la thu dich.
bool SafeAssetPath(const std::string& target, std::string* out) {
if (target.empty() || target[0] != '/') return false;
std::string p = target.substr(1);
const size_t q = p.find('?');
if (q != std::string::npos) p = p.substr(0, q);
if (p.empty()) p = "index.html";
if (p.find("..") != std::string::npos) return false;
if (p.find('\\') != std::string::npos) return false;
*out = p;
return true;
}
} // namespace
// Giao dien chung cho HttpSession va WsSession, de Stop() dong duoc moi phien
// ma khong can biet loai.
class SessionBase {
public:
virtual ~SessionBase() = default;
virtual void Close() = 0;
};
// ---------------------------------------------------------------------------
class WebServerImpl {
public:
WebConfig cfg;
WebServer::CommandHandler on_command;
WebServer::TeleopHandler on_teleop;
asio::io_context ioc;
std::unique_ptr<tcp::acceptor> acceptor;
std::vector<std::thread> threads;
std::atomic<bool> running{false};
uint16_t bound_port = 0;
// MOI phien deu giu mot shared_ptr<WebServerImpl> (chung can cfg, stats,
// handler). Neu o day giu nguoc lai bang shared_ptr thi thanh chu trinh va
// khong gi duoc giai phong. Giu bang weak_ptr.
//
// Chu trinh thu hai, tinh vi hon, da tung lam ro toan bo server: io_context
// la THANH VIEN cua WebServerImpl, con handler dang cho thi giu
// shared_ptr<WebServerImpl>. ioc.stop() KHONG huy handler dang cho -- chung
// nam lai trong hang doi cua io_context cho toi khi io_context bi huy, ma
// io_context lai khong the bi huy vi chinh chung dang giu no. Vi vay Stop()
// phai DONG MOI PHIEN TRUOC, de handler hoan tat voi loi va nha con tro ra.
mutable std::mutex sessions_mu;
std::map<const SessionBase*, std::weak_ptr<SessionBase>> all_sessions;
std::map<const class WsSession*, std::weak_ptr<class WsSession>> ws_sessions;
void Register(const SessionBase* key, std::weak_ptr<SessionBase> w) {
std::lock_guard<std::mutex> lk(sessions_mu);
all_sessions.emplace(key, std::move(w));
}
void Unregister(const SessionBase* key) {
std::lock_guard<std::mutex> lk(sessions_mu);
all_sessions.erase(key);
}
mutable std::mutex stats_mu;
WebServer::Stats stats;
// Hinh hoc 3D cua the gioi. Dat mot lan luc khoi dong, doc tu luong web --
// mutex RIENG, khong dung chung voi stats_mu: mot yeu cau world.bin sao 6.7
// MB duoi lock, giu stats_mu ngan ay lau se lam nghen moi khung gui di.
mutable std::mutex world_mu;
std::string world_blob;
WebServerImpl(WebConfig c, WebServer::CommandHandler cmd,
WebServer::TeleopHandler tel)
: cfg(std::move(c)), on_command(std::move(cmd)), on_teleop(std::move(tel)) {}
void BumpSent(size_t bytes) {
std::lock_guard<std::mutex> lk(stats_mu);
stats.frames_sent++;
stats.bytes_sent += bytes;
}
void BumpDropped() {
std::lock_guard<std::mutex> lk(stats_mu);
stats.frames_dropped++;
}
void BumpAuthFailure() {
std::lock_guard<std::mutex> lk(stats_mu);
stats.auth_failures++;
}
void BumpCommand() {
std::lock_guard<std::mutex> lk(stats_mu);
stats.commands_handled++;
}
void BumpConnection() {
std::lock_guard<std::mutex> lk(stats_mu);
stats.connections_total++;
}
// Goi khi da giu sessions_mu. stats_mu la khoa khac nen khong deadlock,
// nhung THU TU phai luon la sessions_mu -> stats_mu, khong bao gio nguoc.
void BumpConnectionLocked() { BumpConnection(); }
// Bat doi xung co y: BAT e-stop luon duoc phep (fail-safe); GO e-stop va
// reset bumper bat buoc co token. Mot endpoint e-stop khong xac thuc tren
// WiFi LAN nghia la ai cung e-stop duoc -- chap nhan duoc; nhung ai cung
// GO duoc e-stop cua nguoi khac thi khong.
bool CommandNeedsAuth(const std::string& cmd, const std::string& body) const {
if (cfg.auth_token.empty()) return false;
if (cmd != "safety/estop") return true;
bool on = false;
if (!JsonGetBool(body, "on", &on)) {
// KHONG parse duoc -> DOI XAC THUC (fail closed).
//
// Ban dau cho nay mac dinh on=true roi bo qua xac thuc, va do la mot lo
// hong that: handler dien giai cung mot body hong theo cach khac (no
// tim chuoi "true") nen co the GO e-stop, trong khi lop xac thuc tuong
// la dang BAT. Hai ben bat dong y nghia cua body la du de vuot xac thuc.
//
// Quy tac: khi khong chac y dinh la gi thi doi token. Chi mien xac thuc
// cho truong hop da doc duoc TUONG MINH la on=true.
return true;
}
return !on; // BAT e-stop: mien. GO e-stop: doi token.
}
bool AuthOk(const std::string& provided) const {
return cfg.auth_token.empty() || provided == cfg.auth_token;
}
bool LoadAsset(const std::string& name, std::string* body, const char** mime) {
*mime = MimeType(name);
if (!cfg.asset_dir.empty()) {
const std::string path = cfg.asset_dir + "/" + name;
std::ifstream f(path, std::ios::binary);
if (!f) return false;
std::ostringstream ss;
ss << f.rdbuf();
*body = ss.str();
return true;
}
const auto& assets = EmbeddedAssets();
const auto it = assets.find(name);
if (it == assets.end()) return false;
body->assign(reinterpret_cast<const char*>(it->second.data), it->second.size);
return true;
}
};
// ---------------------------------------------------------------------------
// WsSession: mot ket noi WebSocket.
// ---------------------------------------------------------------------------
class WsSession : public std::enable_shared_from_this<WsSession>,
public SessionBase {
public:
WsSession(tcp::socket&& socket, std::shared_ptr<WebServerImpl> impl)
: ws_(std::move(socket)), impl_(std::move(impl)) {}
~WsSession() override { impl_->Unregister(this); }
void Run(http::request<http::string_body> req) {
ws_.set_option(websocket::stream_base::timeout::suggested(beast::role_type::server));
ws_.set_option(websocket::stream_base::decorator([](websocket::response_type& res) {
res.set(http::field::server, "vslam");
}));
impl_->Register(this, std::weak_ptr<SessionBase>(
std::static_pointer_cast<SessionBase>(shared_from_this())));
auto self = shared_from_this();
ws_.async_accept(req, [self](beast::error_code ec) { self->OnAccept(ec); });
}
// Goi tu luong web_tx. Khong chan.
void Send(std::shared_ptr<const std::string> payload, bool is_binary, bool is_map) {
auto self = shared_from_this();
asio::post(ws_.get_executor(), [self, payload, is_binary, is_map] {
self->Enqueue(std::move(payload), is_binary, is_map);
});
}
uint32_t acked_map_version() const { return acked_map_version_.load(); }
bool world_map_sent() const { return world_map_sent_.load(); }
void mark_world_map_sent() { world_map_sent_.store(true); }
void set_acked_map_version(uint32_t v) { acked_map_version_.store(v); }
void Close() override {
auto self = shared_from_this();
asio::post(ws_.get_executor(), [self] {
beast::error_code ec;
// close() tu te truoc; neu that bai thi dong tho de handler dang cho
// hoan tat voi loi va nha shared_ptr ra.
self->ws_.close(websocket::close_code::going_away, ec);
if (ec) {
beast::get_lowest_layer(self->ws_).close();
}
});
}
private:
struct Frame {
std::shared_ptr<const std::string> data;
bool binary = true;
bool is_map = false;
};
void OnAccept(beast::error_code ec) {
if (ec) {
VSLAM_DEBUG("ws accept: " << ec.message());
Remove();
return;
}
{
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
impl_->ws_sessions.emplace(this, weak_from_this());
impl_->BumpConnectionLocked();
VSLAM_INFO("web: client ket noi (tong " << impl_->ws_sessions.size() << ")");
}
Read();
}
void Read() {
auto self = shared_from_this();
ws_.async_read(buffer_, [self](beast::error_code ec, size_t n) {
self->OnRead(ec, n);
});
}
void OnRead(beast::error_code ec, size_t /*n*/) {
if (ec) {
Remove();
return;
}
const std::string msg = beast::buffers_to_string(buffer_.data());
buffer_.consume(buffer_.size());
HandleClientMessage(msg);
Read();
}
void HandleClientMessage(const std::string& msg) {
std::string type;
if (!JsonGetString(msg, "t", &type)) return;
if (type == "cmd") {
// Joypad cam ung: gia tri chuan hoa [-1,1] o 20 Hz.
// Toan bo shaping (ramp, deadman) lam o C++ trong teleop_shaper, khong
// o JS -- khong bao gio tin browser ve dinh dang chuyen dong.
double vx = 0.0, wz = 0.0;
JsonGetNumber(msg, "vx", &vx);
JsonGetNumber(msg, "wz", &wz);
vx = std::max(-1.0, std::min(1.0, vx));
wz = std::max(-1.0, std::min(1.0, wz));
if (impl_->on_teleop) impl_->on_teleop(vx, wz);
return;
}
if (type == "ack_map") {
double v = 0.0;
if (JsonGetNumber(msg, "version", &v) && v >= 0.0) {
set_acked_map_version(static_cast<uint32_t>(v));
}
return;
}
}
void Enqueue(std::shared_ptr<const std::string> payload, bool is_binary, bool is_map) {
if (queue_.size() >= impl_->cfg.max_queued_frames) {
// Day hang doi. Drop khung CU NHAT KHONG PHAI MAP.
// MAP khong bao gio bi drop: mat mot khung scan la mat 100 ms du lieu,
// mat khung MAP la client hien ban do sai cho toi lan doi version sau --
// co the la vinh vien trong che do localization.
auto it = std::find_if(queue_.begin(), queue_.end(),
[](const Frame& f) { return !f.is_map; });
if (it != queue_.end()) {
queue_.erase(it);
impl_->BumpDropped();
} else if (!is_map) {
impl_->BumpDropped();
return; // hang doi toan MAP, bo khung moi
}
}
queue_.push_back(Frame{std::move(payload), is_binary, is_map});
if (!writing_) Write();
}
void Write() {
if (queue_.empty()) {
writing_ = false;
return;
}
writing_ = true;
const Frame& f = queue_.front();
ws_.binary(f.binary);
auto self = shared_from_this();
const size_t n = f.data->size();
ws_.async_write(asio::buffer(*f.data), [self, n](beast::error_code ec, size_t) {
if (ec) {
self->Remove();
return;
}
self->impl_->BumpSent(n);
self->queue_.pop_front();
self->Write();
});
}
void Remove() {
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
impl_->ws_sessions.erase(this);
}
websocket::stream<beast::tcp_stream> ws_;
std::shared_ptr<WebServerImpl> impl_;
beast::flat_buffer buffer_;
std::deque<Frame> queue_;
bool writing_ = false;
std::atomic<uint32_t> acked_map_version_{0};
// Ban do the gioi la TINH trong mo phong -- gui mot lan la du, khong can
// co che version/ACK nhu ban do SLAM.
std::atomic<bool> world_map_sent_{false};
};
// ---------------------------------------------------------------------------
// HttpSession: phuc vu asset tinh va POST /api/*.
// ---------------------------------------------------------------------------
class HttpSession : public std::enable_shared_from_this<HttpSession>,
public SessionBase {
public:
HttpSession(tcp::socket&& socket, std::shared_ptr<WebServerImpl> impl)
: stream_(std::move(socket)), impl_(std::move(impl)) {}
~HttpSession() override { impl_->Unregister(this); }
void Run() {
// Dang ky de Stop() dong duoc. Phai lam o day chu khong o constructor:
// shared_from_this() chua dung duoc trong constructor.
impl_->Register(this, std::weak_ptr<SessionBase>(
std::static_pointer_cast<SessionBase>(shared_from_this())));
asio::dispatch(stream_.get_executor(),
[self = shared_from_this()] { self->Read(); });
}
void Close() override {
auto self = shared_from_this();
asio::post(stream_.get_executor(), [self] {
beast::error_code ec;
self->stream_.socket().shutdown(tcp::socket::shutdown_both, ec);
self->stream_.close();
});
}
private:
void Read() {
req_ = {};
stream_.expires_after(std::chrono::seconds(30));
auto self = shared_from_this();
http::async_read(stream_, buffer_, req_,
[self](beast::error_code ec, size_t) { self->OnRead(ec); });
}
void OnRead(beast::error_code ec) {
if (ec == http::error::end_of_stream) {
Finish();
return;
}
if (ec) return;
if (websocket::is_upgrade(req_)) {
// Token cho WS di qua query string vi browser khong dat header tuy y
// duoc tren WebSocket handshake.
if (!impl_->cfg.auth_token.empty()) {
const std::string target(req_.target());
const std::string want = "token=" + impl_->cfg.auth_token;
if (target.find(want) == std::string::npos) {
impl_->BumpAuthFailure();
Respond(http::status::unauthorized, "text/plain", "thieu hoac sai token\n");
return;
}
}
std::make_shared<WsSession>(stream_.release_socket(), impl_)->Run(std::move(req_));
return;
}
HandleRequest();
}
void HandleRequest() {
const std::string target(req_.target());
if (req_.method() == http::verb::post && target.rfind("/api/", 0) == 0) {
HandleApi(target.substr(5));
return;
}
if (req_.method() == http::verb::get && target.rfind("/api/", 0) == 0) {
HandleApiGet(target.substr(5));
return;
}
if (req_.method() != http::verb::get && req_.method() != http::verb::head) {
Respond(http::status::method_not_allowed, "text/plain", "chi GET/POST\n");
return;
}
std::string name;
if (!SafeAssetPath(target, &name)) {
Respond(http::status::bad_request, "text/plain", "duong dan khong hop le\n");
return;
}
std::string body;
const char* mime = nullptr;
if (!impl_->LoadAsset(name, &body, &mime)) {
Respond(http::status::not_found, "text/plain", "khong tim thay\n");
return;
}
Respond(http::status::ok, mime, body);
}
void HandleApi(const std::string& cmd) {
const std::string body = req_.body();
if (impl_->CommandNeedsAuth(cmd, body)) {
std::string provided;
const auto it = req_.find("X-Auth-Token");
if (it != req_.end()) provided = std::string(it->value());
if (!impl_->AuthOk(provided)) {
impl_->BumpAuthFailure();
VSLAM_WARN("web: tu choi lenh khong co token: " << cmd);
std::string out;
WriteStatusJson(StatusResponse::Error(StatusCode::kUnauthenticated,
"can X-Auth-Token"),
&out);
Respond(http::status::unauthorized, "application/json", out);
return;
}
}
StatusResponse st = StatusResponse::Error(StatusCode::kNotFound, "khong co handler");
if (impl_->on_command) {
// Handler chay TREN LUONG IO: phai tra ve ngay. Cach dung dung la day
// vao hang doi lenh roi tra Ok -- luong web khong bao gio truc tiep sua
// state cua estimator.
st = impl_->on_command(cmd, body);
}
impl_->BumpCommand();
std::string out;
WriteStatusJson(st, &out);
Respond(st.ok() ? http::status::ok : http::status::bad_request,
"application/json", out);
}
void HandleApiGet(const std::string& cmd) {
if (cmd == "status") {
const WebServer::Stats s = [this] {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
return impl_->stats;
}();
size_t clients = 0;
{
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
clients = impl_->ws_sessions.size();
}
std::ostringstream oss;
oss << "{\"clients\":" << clients
<< ",\"connections_total\":" << s.connections_total
<< ",\"frames_sent\":" << s.frames_sent
<< ",\"frames_dropped\":" << s.frames_dropped
<< ",\"bytes_sent\":" << s.bytes_sent
<< ",\"commands_handled\":" << s.commands_handled
<< ",\"auth_failures\":" << s.auth_failures << "}";
Respond(http::status::ok, "application/json", oss.str());
return;
}
if (cmd == "world.bin") {
std::string blob;
{
std::lock_guard<std::mutex> lk(impl_->world_mu);
blob = impl_->world_blob;
}
if (blob.empty()) {
Respond(http::status::not_found, "application/json",
"{\"code\":2,\"message\":\"khong chay tu file .world\"}");
return;
}
Respond(http::status::ok, "application/octet-stream", blob);
return;
}
Respond(http::status::not_found, "application/json",
"{\"code\":2,\"message\":\"khong co endpoint\"}");
}
void Respond(http::status status, const char* mime, const std::string& body) {
auto res = std::make_shared<http::response<http::string_body>>(status, req_.version());
res->set(http::field::server, "vslam");
res->set(http::field::content_type, mime);
// UI la mot trang duy nhat trong LAN; khong cache de sua asset la thay ngay.
res->set(http::field::cache_control, "no-store");
res->keep_alive(req_.keep_alive());
res->body() = body;
res->prepare_payload();
auto self = shared_from_this();
const bool keep = res->keep_alive();
http::async_write(stream_, *res,
[self, res, keep](beast::error_code ec, size_t) {
if (ec || !keep) {
self->Finish();
return;
}
self->Read();
});
}
// Ket thuc binh thuong sau khi tra loi xong. Khac han Close() cong khai o
// tren: cai do la dong CUONG BUC luc tat server.
void Finish() {
beast::error_code ec;
stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
}
beast::tcp_stream stream_;
std::shared_ptr<WebServerImpl> impl_;
beast::flat_buffer buffer_;
http::request<http::string_body> req_;
};
// ---------------------------------------------------------------------------
// WebServer
// ---------------------------------------------------------------------------
WebServer::WebServer(WebConfig cfg, CommandHandler on_command, TeleopHandler on_teleop)
: impl_(std::make_shared<WebServerImpl>(std::move(cfg), std::move(on_command),
std::move(on_teleop))) {}
WebServer::~WebServer() { Stop(); }
StatusResponse WebServer::Start() {
if (impl_->running.load()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da chay roi");
}
if (impl_->cfg.auth_token.empty()) {
VSLAM_WARN("web: KHONG co auth_token -- bat ky ai trong LAN deu go duoc "
"e-stop. Dat system.web.auth_token truoc khi chay that.");
}
beast::error_code ec;
const auto addr = asio::ip::make_address(impl_->cfg.bind_address, ec);
if (ec) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"bind_address khong hop le: " + ec.message());
}
impl_->acceptor = std::make_unique<tcp::acceptor>(impl_->ioc);
const tcp::endpoint ep(addr, impl_->cfg.port);
impl_->acceptor->open(ep.protocol(), ec);
if (ec) return StatusResponse::Error(StatusCode::kInternal, "open: " + ec.message());
impl_->acceptor->set_option(asio::socket_base::reuse_address(true), ec);
impl_->acceptor->bind(ep, ec);
if (ec) {
return StatusResponse::Error(StatusCode::kUnavailable,
"bind cong " + std::to_string(impl_->cfg.port) + ": " +
ec.message());
}
impl_->acceptor->listen(asio::socket_base::max_listen_connections, ec);
if (ec) return StatusResponse::Error(StatusCode::kInternal, "listen: " + ec.message());
impl_->bound_port = impl_->acceptor->local_endpoint().port();
impl_->running.store(true);
DoAccept();
const int n = std::max(1, impl_->cfg.io_threads);
for (int i = 0; i < n; ++i) {
impl_->threads.emplace_back([impl = impl_] { impl->ioc.run(); });
}
VSLAM_INFO("web: dang nghe tren " << impl_->cfg.bind_address << ":"
<< impl_->bound_port);
return StatusResponse::Ok();
}
void WebServer::DoAccept() {
impl_->acceptor->async_accept(
asio::make_strand(impl_->ioc),
[this](beast::error_code ec, tcp::socket socket) {
if (!impl_->running.load()) return;
if (!ec) {
std::make_shared<HttpSession>(std::move(socket), impl_)->Run();
}
DoAccept();
});
}
void WebServer::Stop() {
if (!impl_ || !impl_->running.exchange(false)) return;
// THU TU O DAY LA QUAN TRONG, khong duoc doi.
//
// 1. Dung nhan ket noi moi.
beast::error_code ec;
if (impl_->acceptor) impl_->acceptor->close(ec);
// 2. Dong moi phien, va lam TRUOC khi dung io_context.
//
// Moi phien giu mot shared_ptr<WebServerImpl>, ma io_context lai la
// thanh vien cua WebServerImpl. ioc.stop() KHONG huy handler dang cho --
// chung nam lai trong hang doi cho toi khi io_context bi huy, ma
// io_context khong the bi huy vi chinh chung dang giu no. Ket qua la ca
// server (io_context, thread, session) ro vinh vien sau moi lan Stop().
//
// Dong socket lam cac async op dang cho hoan tat voi loi, handler chay,
// session nha con tro, chu trinh dut.
{
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
for (const auto& kv : impl_->all_sessions) {
if (auto s = kv.second.lock()) s->Close();
}
}
// 3. Cho io_context can viec mot cach tu nhien. KHONG goi ioc.stop() o day:
// stop() lam run() tra ve ngay va bo lai handler chua chay, dung lai
// dung van de o tren.
for (auto& t : impl_->threads) {
if (t.joinable()) t.join();
}
impl_->threads.clear();
{
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
impl_->all_sessions.clear();
impl_->ws_sessions.clear();
}
VSLAM_INFO("web: da dung");
}
void WebServer::SetWorldMesh(std::string blob) {
std::lock_guard<std::mutex> lk(impl_->world_mu);
impl_->world_blob = std::move(blob);
}
void WebServer::Publish(const WebSnapshot& snap) {
// Khong co client thi KHONG serialize gi ca. Serialize mot cloud 4000 diem
// va mot map cho khong ai xem la lang phi that o 10 Hz tren Jetson.
std::vector<std::shared_ptr<WsSession>> targets;
{
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
if (impl_->ws_sessions.empty()) return;
targets.reserve(impl_->ws_sessions.size());
for (const auto& kv : impl_->ws_sessions) {
if (auto s = kv.second.lock()) targets.push_back(std::move(s));
}
if (targets.empty()) return;
}
auto state = std::make_shared<std::string>();
WriteStateJson(snap, state.get());
for (const auto& s : targets) s->Send(state, /*binary=*/false, /*is_map=*/false);
if (snap.scan) {
auto buf = std::make_shared<std::string>();
EncodeScan(*snap.scan, snap.stamp, buf.get());
for (const auto& s : targets) s->Send(buf, true, false);
}
if (snap.cloud) {
auto buf = std::make_shared<std::string>();
EncodeCloud(*snap.cloud, snap.stamp, impl_->cfg.cloud_max_points,
impl_->cfg.cloud_quant_m, buf.get());
for (const auto& s : targets) s->Send(buf, true, false);
}
if (!snap.trajectory.empty()) {
auto buf = std::make_shared<std::string>();
EncodePath(snap.trajectory, snap.stamp, impl_->cfg.path_min_step_m, buf.get());
for (const auto& s : targets) s->Send(buf, true, false);
}
// BAN DO THE GIOI -- khung nhin "Gazebo". Gui MOT lan cho moi client.
//
// Tach khoi ban do SLAM co y: hai thu tra loi hai cau hoi khac nhau, va
// doi chieu chung chinh la ly do nguoi ta mo ca Gazebo lan RViz.
if (snap.world_map) {
std::shared_ptr<std::string> buf;
for (const auto& s : targets) {
if (s->world_map_sent()) continue;
if (!buf) {
buf = std::make_shared<std::string>();
EncodeMapFull(*snap.world_map, snap.stamp, buf.get(), BinaryType::kWorldMap);
}
s->Send(buf, true, /*is_map=*/true);
s->mark_world_map_sent();
}
}
// MAP chi gui cho client chua xac nhan phien ban nay. Ma hoa mot lan roi
// dung chung -- 62 kB cho ban do lon nhat (do tren map_hospital.db).
if (snap.map && snap.slam.map_version != 0) {
std::shared_ptr<std::string> buf;
for (const auto& s : targets) {
if (s->acked_map_version() == snap.slam.map_version) continue;
if (!buf) {
buf = std::make_shared<std::string>();
EncodeMapFull(*snap.map, snap.stamp, buf.get());
}
s->Send(buf, true, /*is_map=*/true);
s->set_acked_map_version(snap.slam.map_version);
}
}
}
size_t WebServer::client_count() const {
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
return impl_->ws_sessions.size();
}
uint16_t WebServer::port() const { return impl_->bound_port; }
WebServer::Stats WebServer::stats() const {
std::lock_guard<std::mutex> lk(impl_->stats_mu);
return impl_->stats;
}
} // namespace vslam

840
libs/vslam_web/www/app.js Normal file
View File

@@ -0,0 +1,840 @@
'use strict';
// Web UI thay RViz. Khong dependency.
//
// Ban do la occupancy grid 2D, scan la 2D, path la 2D, pose la mot tam giac.
// Thu 3D duy nhat la point cloud, va no la view debug perception -- nhin tu
// tren xuong to mau theo do cao la du. Do la ly do dung canvas 2D chu khong
// three.js: three.js ~600 kB phai vendor va theo doi license, doi lay mot
// goc nhin ma bai toan nay khong can.
// --- Giai ma nhi phan (khop libs/vslam_web/include/vslam/binary_codec.h) ---
const MAGIC = 0x314C5356; // 'VSL1' little-endian
// Phien ban ma nguon giao dien. TANG khi doi app.js / app3d.js / style.css.
// Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con
// cache ban cu".
const UI_VERSION = '2026-09-18c';
const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_MAP_PATCH = 4, T_PATH = 5;
// Ban do THE GIOI cua bo mo phong -- khung nhin "Gazebo". Tinh: gui mot lan.
const T_WORLD_MAP = 6;
// Ba ngu nghia cua mot tia. Lan lon chung la lam sai ca man hinh.
const R_NAN = 0xFFFF; // khong do duoc (duoi range_min)
const R_INF = 0xFFFE; // khong co phan xa (vuot range_max)
const R_BLANKED = 0xFFFD; // bi sector mask cat (than robot che)
const state = {
pose: null, gt: null, scan: null, cloud: null, path: null,
map: null, mapImage: null, mapVersion: 0,
bytes: 0, lastBytes: 0, wireRate: 0,
};
const view = { x: 0, y: 0, scale: 40, init: false }; // scale = pixel/met
// --- WebSocket -------------------------------------------------------------
let ws = null;
let reconnectTimer = null;
function connect() {
const token = new URLSearchParams(location.search).get('token');
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const url = proto + '//' + location.host + '/ws' + (token ? '?token=' + token : '');
ws = new WebSocket(url);
ws.binaryType = 'arraybuffer';
ws.onopen = () => setConn(true);
ws.onclose = () => {
setConn(false);
if (!reconnectTimer) reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connect();
}, 1000);
};
ws.onerror = () => ws.close();
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
state.bytes += ev.data.length;
try { onState(JSON.parse(ev.data)); } catch (e) { /* khung hong, bo */ }
} else {
state.bytes += ev.data.byteLength;
onBinary(new DataView(ev.data));
}
};
}
function setConn(ok) {
const el = document.getElementById('conn');
el.textContent = ok ? 'da ket noi' : 'mat ket noi';
el.className = 'chip ' + (ok ? 'ok' : 'bad');
}
// --- Khung nhi phan --------------------------------------------------------
function onBinary(dv) {
if (dv.byteLength < 16 || dv.getUint32(0, true) !== MAGIC) return;
const type = dv.getUint8(4);
const off = 16;
if (type === T_SCAN) {
const angleMin = dv.getFloat32(off, true);
const angleInc = dv.getFloat32(off + 4, true);
const rangeMax = dv.getFloat32(off + 12, true);
const n = dv.getUint32(off + 16, true);
const pts = new Float32Array(n * 2);
let m = 0;
for (let i = 0; i < n; i++) {
const raw = dv.getUint16(off + 20 + i * 2, true);
// Ba gia tri canh bien deu KHONG ve. Ve tia blanked se lam ra mot
// vong cung gia o ban kinh range_max quanh robot -- trong nhu tuong.
if (raw === R_NAN || raw === R_INF || raw === R_BLANKED) continue;
const r = raw * 0.001;
const a = angleMin + i * angleInc;
pts[m++] = r * Math.cos(a);
pts[m++] = r * Math.sin(a);
}
state.scan = pts.subarray(0, m);
return;
}
if (type === T_CLOUD) {
const scale = dv.getFloat32(off + 12, true);
const n = dv.getUint32(off + 16, true);
const pts = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
const b = off + 20 + i * 6;
pts[i * 3] = dv.getInt16(b, true) * scale;
pts[i * 3 + 1] = dv.getInt16(b + 2, true) * scale;
pts[i * 3 + 2] = dv.getInt16(b + 4, true) * scale;
}
state.cloud = pts;
return;
}
if (type === T_MAP_FULL || type === T_WORLD_MAP) {
const res = dv.getFloat32(off, true);
const w = dv.getInt32(off + 4, true);
const h = dv.getInt32(off + 8, true);
const ox = dv.getFloat32(off + 12, true);
const oy = dv.getFloat32(off + 16, true);
const runs = dv.getUint32(off + 24, true);
const cells = new Int8Array(w * h);
let p = 0;
for (let r = 0; r < runs; r++) {
const b = off + 28 + r * 3;
const len = dv.getUint16(b, true);
const val = dv.getInt8(b + 2);
cells.fill(val, p, p + len);
p += len;
}
const grid = { res, w, h, ox, oy, cells };
if (type === T_WORLD_MAP) {
// Ban do THE GIOI: su that, de lai cho chuan. KHONG lan vao state.map.
state.worldMap = grid;
state.worldMapImage = rasterize(grid);
if (!view.init) centerOnMap(grid);
return;
}
state.map = grid;
state.mapImage = rasterize(grid);
// Can khung theo ban do THE GIOI neu co -- no la cai khong doi, con ban
// do SLAM lon dan khi quet va se keo khung nhin chay theo.
if (!view.init && !state.worldMap) centerOnMap(grid);
// Bao cho server biet da nhan: no se khong gui lai phien ban nay.
if (ws && ws.readyState === 1 && state.mapVersion) {
ws.send(JSON.stringify({ t: 'ack_map', version: state.mapVersion }));
}
return;
}
if (type === T_PATH) {
const n = dv.getUint32(off, true);
const pts = new Float32Array(n * 2);
for (let i = 0; i < n * 2; i++) pts[i] = dv.getFloat32(off + 4 + i * 4, true);
state.path = pts;
return;
}
}
// Giai RLE mot lan cho moi map_version roi blit -- moi khung chi con mot
// drawImage thay vi ve lai tung o.
function rasterize(map) {
const img = new ImageData(map.w, map.h);
const d = img.data;
for (let i = 0; i < map.cells.length; i++) {
const v = map.cells[i];
// Hang 0 cua occupancy grid la o duoi cung (goc o origin), con hang 0 cua
// ImageData la o tren cung -> lat theo truc y khi ghi.
const x = i % map.w;
const y = map.h - 1 - Math.floor(i / map.w);
const j = (y * map.w + x) * 4;
// ⚠️ CHUA BIET phai TRONG SUOT.
//
// Ban truoc ve no DAC (alpha 255) mau xam toi. Hau qua: ban do SLAM luc
// moi quet gan nhu toan o chua biet, nen no hien ra thanh mot TAM XAM DAC
// 11.8 x 21.7 m che kin khung -- va vi phan chua biet doi rat cham, ca
// khung trong nhu dung yen. Bao cao "khung SLAM khong realtime" chinh la
// trieu chung cua viec nay, KHONG phai cua tan so cap nhat.
//
// RViz ve chua-biet trong suot, va do la ly do ban do o do "lon dan" nhin
// thay duoc.
//
// Mau cung dao lai cho nen TOI: bi chiem SANG (tuong noi len), trong thi
// mo. Ban truoc de bi chiem gan DEN tren nen den -- vo hinh.
let c;
if (v < 0) c = [0, 0, 0, 0]; // chua biet -> TRONG SUOT
else if (v < 50) c = [58, 70, 86, 170]; // trong, mo
else c = [222, 232, 244, 255]; // bi chiem, SANG
d[j] = c[0]; d[j + 1] = c[1]; d[j + 2] = c[2]; d[j + 3] = c[3];
}
const cv = document.createElement('canvas');
cv.width = map.w; cv.height = map.h;
cv.getContext('2d').putImageData(img, 0, 0);
return cv;
}
// --- Khung trang thai (JSON) ----------------------------------------------
function onState(s) {
state.pose = s.pose;
state.mapVersion = s.slam.map_version;
// Hinh hoc robot den TU SERVER (robot.yaml). File nay khong duoc chua mot
// hang so kich thuoc nao -- xem ghi chu trong app3d.js.
if (s.robot) state.robot = s.robot;
txt('px', fmt(s.pose.x, 3));
txt('py', fmt(s.pose.y, 3));
txt('pyaw', fmt(s.pose.yaw, 3));
// Ground truth: chi hien khi CO. Khong co ma hien 0 la noi doi -- client
// khong phan biet duoc "dung o goc" voi "khong biet".
state.gt = s.gt || null;
txt('gtErr', s.gt ? fmt(s.gt.err, 3) + ' m' : '--');
state.slamMode = s.slam.mode;
txt('mode', s.slam.mode);
const st = s.safety.state;
const sv = document.getElementById('safeState');
sv.textContent = st;
sv.className = 'state ' + (st === 'OK' ? 'ok' : (st.indexOf('SLOW') >= 0 ? 'warn' : 'bad'));
txt('safeDetail', s.safety.detail || '');
// min_front la null khi khong do duoc (JSON khong co Infinity).
txt('minFront', s.safety.min_front === null ? 'inf' : fmt(s.safety.min_front, 2) + ' m');
txt('rays', s.safety.front_usable + ' / ' + s.safety.front_rays);
txt('blanked', String(s.safety.front_blanked));
// Vuc: ba trang thai phan biet ro. `detail` mang tien to "cliff:" khi
// khong phan xet duoc -- xem CliffBailName trong cliff_detect.cc.
const cd = String(s.safety.detail || '');
const cv = document.getElementById('cliffState');
if (cv) {
if (s.safety.cliff) {
cv.textContent = 'VUC PHIA TRUOC';
cv.className = 'state bad';
} else if (cd.indexOf('cliff:') === 0) {
cv.textContent = 'khong biet (' + cd.slice(6) + ')';
cv.className = 'state warn';
} else {
cv.textContent = 'khong co vuc';
cv.className = 'state ok';
}
}
if (s.tilt) {
txt('tRoll', fmt(s.tilt.roll * 57.2958, 2) + ' deg');
txt('tPitch', fmt(s.tilt.pitch * 57.2958, 2) + ' deg');
// accel_ok=false nghia la bo loc dang chi tich phan gyro (robot dang
// tang/giam toc hoac vua va cham) -> nghieng dang troi.
txt('tAccel', s.tilt.accel_ok ? 'neo trong luc' : 'gyro thuan (troi)');
}
txt('loc', s.slam.localized ? 'co' : 'khong');
txt('score', fmt(s.slam.score, 2));
txt('pms', fmt(s.slam.process_ms, 0) + ' ms');
txt('mapver', String(s.slam.map_version));
txt('hzLidar', fmt(s.health.lidar_hz, 1));
txt('hzCam', fmt(s.health.camera_hz, 1));
txt('hzImu', fmt(s.health.imu_hz, 1));
txt('hzEkf', fmt(s.health.ekf_hz, 1));
txt('cpu', fmt(s.health.cpu_pct, 0) + ' %');
txt('rss', fmt(s.health.rss_mb, 0) + ' MB');
let total = 0;
for (const k in s.health.drops) total += s.health.drops[k];
txt('drops', String(total));
if (s.teleop) {
txt('linSpeed', fmt(s.teleop.linear_speed, 2));
txt('angSpeed', fmt(s.teleop.angular_speed, 2));
}
const btn = document.getElementById('estop');
btn.textContent = s.safety.estop ? 'GO E-STOP' : 'E-STOP';
joy.classList.toggle('estop', !!s.safety.estop);
}
function txt(id, v) {
const el = document.getElementById(id);
if (el) el.textContent = v;
}
function fmt(v, d) {
return (v === null || v === undefined) ? '--' : Number(v).toFixed(d);
}
// --- Ve --------------------------------------------------------------------
const cv = document.getElementById('main');
const ctx = cv.getContext('2d');
function resize() {
const dpr = window.devicePixelRatio || 1;
cv.width = cv.clientWidth * dpr;
cv.height = cv.clientHeight * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
window.addEventListener('resize', resize);
function centerOnMap(grid) {
const m = grid || state.worldMap || state.map;
if (!m) return;
view.x = m.ox + m.w * m.res / 2;
view.y = m.oy + m.h * m.res / 2;
const w = cv.clientWidth, h = cv.clientHeight;
view.scale = Math.min(w / (m.w * m.res), h / (m.h * m.res)) * 0.9;
view.init = true;
}
// The gioi -> man hinh. y lat dau vi truc y cua canvas huong xuong.
// Canvas DANG duoc ve. O che do chia doi, hai khung dung CHUNG `view` -- co
// y: hai ban do phai thang hang thi moi doi chieu duoc, ma doi chieu chinh la
// ly do mo hai khung.
let curCv = null;
function sx(x) { return (x - view.x) * view.scale + curCv.clientWidth / 2; }
function sy(y) { return curCv.clientHeight / 2 - (y - view.y) * view.scale; }
function on(id) { return document.getElementById(id).checked; }
// Tam giac chi huong. Mot ham cho ca pose uoc luong lan ground truth: hai ban
// chep cua cung mot hinh se lech nhau ngay lan sua dau tien, va luc do khong ai
// so sanh duoc hai cai nua.
function drawRobot(ctx, x, y, yaw, color, alpha) {
const L = 0.30 * view.scale, W = 0.17 * view.scale;
ctx.save();
ctx.globalAlpha = alpha;
ctx.translate(sx(x), sy(y));
ctx.rotate(-yaw);
ctx.beginPath();
ctx.moveTo(L, 0);
ctx.lineTo(-L * 0.6, -W);
ctx.lineTo(-L * 0.6, W);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
// Ve MOT khung.
//
// `grid`/`gridImage` : ban do de ve (THE GIOI hay SLAM)
// `robotPose` : pose ve tam giac dac -- su that o khung trai, uoc
// luong o khung phai
// `showGt` : co ve them tam giac ground truth mo khong
//
// Mot ham cho ca hai khung: hai ban chep se lech nhau ngay lan sua dau, va
// luc do khong con doi chieu duoc nua.
function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapToggle) {
curCv = targetCv;
const ctx = targetCtx;
const w = targetCv.clientWidth, h = targetCv.clientHeight;
if (targetCv.width !== w || targetCv.height !== h) {
targetCv.width = w; targetCv.height = h;
}
ctx.fillStyle = '#12151a';
ctx.fillRect(0, 0, w, h);
// Mot khung den khong noi duoc vi sao no den. Neu day la khung SLAM va
// SLAM dang TAT, viet ra -- nguoi van hanh khong phai doan.
if (!grid && mapToggle === 'lyMap' &&
(state.slamMode === 'off' || !state.slamMode)) {
ctx.fillStyle = '#7d8896';
ctx.font = '13px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.fillText('SLAM dang TAT', w / 2, h / 2 - 10);
ctx.fillText('them --slam vao lenh de quet ban do', w / 2, h / 2 + 10);
ctx.textAlign = 'left';
}
if (grid && gridImage && on(mapToggle || 'lyMap')) {
const m = grid;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(gridImage,
sx(m.ox), sy(m.oy + m.h * m.res),
m.w * m.res * view.scale, m.h * m.res * view.scale);
}
if (state.path && on('lyPath')) {
ctx.strokeStyle = '#5aa9e6';
ctx.lineWidth = 1.5;
ctx.beginPath();
for (let i = 0; i < state.path.length; i += 2) {
const X = sx(state.path[i]), Y = sy(state.path[i + 1]);
i === 0 ? ctx.moveTo(X, Y) : ctx.lineTo(X, Y);
}
ctx.stroke();
}
// scan va cloud o frame robot -> xoay theo pose truoc khi ve.
const p = robotPose;
if (p) {
const c = Math.cos(p.yaw), s = Math.sin(p.yaw);
// Ground truth ve TRUOC pose uoc luong, de pose ve de len tren: cai ta
// dang danh gia phai nhin ro hon cai lam chuan.
if (showGt && state.gt && on('lyGt')) {
drawRobot(ctx, state.gt.x, state.gt.y, state.gt.yaw, '#00c853', 0.45);
}
if (state.cloud && on('lyCloud')) {
const pts = state.cloud;
for (let i = 0; i < pts.length; i += 3) {
const x = p.x + c * pts[i] - s * pts[i + 1];
const y = p.y + s * pts[i] + c * pts[i + 1];
const z = pts[i + 2];
// To mau theo do cao: day la view debug perception, va do cao la
// thu duy nhat dang nhin o goc tu tren xuong.
const t = Math.max(0, Math.min(1, z / 1.2));
ctx.fillStyle = 'rgb(' + Math.round(80 + 175 * t) + ',' +
Math.round(200 - 90 * t) + ',' + Math.round(120 + 60 * t) + ')';
ctx.fillRect(sx(x) - 1, sy(y) - 1, 2, 2);
}
}
if (state.scan && on('lyScan')) {
ctx.fillStyle = '#e2574c';
const pts = state.scan;
// ⚠️ Scan trong frame LASER -- phai bu vi tri gan LiDAR truoc khi dua
// vao pose cua base. Xem ghi chu trong v3dSetScan().
const lx = (state.robot && state.robot.laser_x) || 0;
const ly = (state.robot && state.robot.laser_y) || 0;
for (let i = 0; i < pts.length; i += 2) {
const bx = pts[i] + lx, by = pts[i + 1] + ly;
const x = p.x + c * bx - s * by;
const y = p.y + s * bx + c * by;
ctx.fillRect(sx(x) - 1.5, sy(y) - 1.5, 3, 3);
}
}
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, '#4ec9a0', 1.0);
}
}
// Nhan khung phai noi KICH THUOC ban do SLAM.
//
// O muc zoom vua ca toa nha (26 x 58 m), ban do SLAM luc moi quet chi
// 1.3 x 1.1 m -- nho duoi mot pixel, va khung phai trong y het nhu hong. Mot
// con so lam ro khac biet giua "chua quet duoc gi" va "khung bi loi".
// ⚠️ Nhan phai noi DUNG trang thai cua SLAM, khong phai doan tu `state.map`.
//
// Ban truoc luon viet "SLAM dang dung", ke ca khi `slam.mode === 'off'`. Khung
// den kem mot nhan noi SLAM dang chay lam nguoi van hanh di tim loi trong SLAM
// suot nhieu phut, trong khi su that chi la node chay THIEU co `--slam`.
//
// Cung lop loi voi chuyen web hien `cliff` tu so do da cu 10 giay trong khi
// FSM da bo qua no: nguoi van hanh tin cai ho NHIN THAY.
function updateSlamLabel() {
if (state.slamMode === 'off' || !state.slamMode) {
labR.textContent = 'SLAM TAT -- chay lai voi --slam';
return;
}
const m = state.map;
labR.textContent = m
? 'SLAM ' + state.slamMode + ' ' + (m.w * m.res).toFixed(1) + ' x ' +
(m.h * m.res).toFixed(1) + ' m'
: 'SLAM ' + state.slamMode + ' (chua co ban do -- lai them)';
}
function draw() {
// ⚠️ 3D va CHIA DOI phai chay CUNG NHAU.
//
// Ban truoc viet `if (use3d) { draw3d(); return; }` -- tuc khi bat 3D thi
// khung PHAI khong bao gio duoc ve lai, no giu nguyen hinh cuoi truoc luc
// bam nut. Trieu chung dung la "tab SLAM khong cap nhat", va no chi xuat
// hien khi bat CA HAI nut -- dung to hop huu ich nhat:
// trai = the gioi 3D (Gazebo) | phai = ban do SLAM (RViz)
if (use3d) {
draw3d();
// Khung phai VAN phai chay khi dang chia doi.
if (split) {
updateSlamLabel();
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap');
}
requestAnimationFrame(draw);
return;
}
if (split) {
updateSlamLabel();
// TRAI = THE GIOI: ban do that + pose THAT. Day la khung de LAI.
drawScene(cv, ctx, state.worldMap, state.worldMapImage,
state.gt || state.pose, false, 'lyWorld');
// PHAI = SLAM: ban do dang dung + pose UOC LUONG. Khung de xem quet toi
// dau, va lech bao nhieu so voi khung trai.
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap');
} else {
// Mot khung: uu tien ban do SLAM neu co, khong thi ban do the gioi.
const haveSlam = !!state.map;
drawScene(cv, ctx,
haveSlam ? state.map : state.worldMap,
haveSlam ? state.mapImage : state.worldMapImage,
state.pose, true, haveSlam ? 'lyMap' : 'lyWorld');
}
requestAnimationFrame(draw);
}
// --- Tuong tac -------------------------------------------------------------
let dragging = false, lastX = 0, lastY = 0;
cv.addEventListener('mousedown', (e) => {
dragging = true; lastX = e.clientX; lastY = e.clientY;
});
window.addEventListener('mouseup', () => { dragging = false; });
window.addEventListener('mousemove', (e) => {
if (!dragging) return;
view.x -= (e.clientX - lastX) / view.scale;
view.y += (e.clientY - lastY) / view.scale;
lastX = e.clientX; lastY = e.clientY;
view.init = true;
});
cv.addEventListener('wheel', (e) => {
e.preventDefault();
view.scale *= e.deltaY < 0 ? 1.1 : 1 / 1.1;
view.scale = Math.max(2, Math.min(400, view.scale));
view.init = true;
}, { passive: false });
cv.addEventListener('dblclick', () => { centerOnMap(); });
// --- Lenh ------------------------------------------------------------------
function post(cmd, body) {
const token = new URLSearchParams(location.search).get('token');
const headers = { 'Content-Type': 'application/json' };
if (token) headers['X-Auth-Token'] = token;
return fetch('/api/' + cmd, { method: 'POST', headers, body: JSON.stringify(body || {}) })
.then(r => r.json())
.then(r => { if (r.code !== 0) alert(cmd + ': ' + r.message); })
.catch(e => alert(cmd + ': ' + e));
}
document.getElementById('estop').addEventListener('click', () => {
const on = document.getElementById('estop').textContent === 'E-STOP';
// Tuong minh, KHONG toggle: mot request bi retry khong duoc phep GO e-stop.
post('safety/estop', { on });
});
document.getElementById('reset').addEventListener('click', () => post('safety/reset', {}));
// --- Joystick --------------------------------------------------------------
//
// Thay cho virtual_joystick.py (896 dong Tkinter) cua ban ROS.
//
// Trang nay CHI gui gia tri da chuan hoa [-1, 1]. Moi phep ramp gia toc, moi
// gioi han van toc, va deadman deu nam o C++. Khong bao gio tin trinh duyet
// ve dinh dang chuyen dong: WebSocket co the lag, tab co the bi treo, va may
// tram co the ngu giua chung.
//
// Ba lop deadman doc lap, tu nong ra sau:
// 1. o day -- nha tay thi knob ve tam va gui 0
// 2. o day -- ngung gui hoan toan neu mat ket noi
// 3. o base -- tu dung neu khong nhan lenh trong 300 ms (lop duy nhat con
// song khi ca tab lan wifi deu chet)
const joy = document.getElementById('joy');
const knob = document.getElementById('knob');
const stick = { active: false, vx: 0, wz: 0, pointerId: null };
const JOY_RADIUS = 54; // do lech toi da cua knob, pixel
const DEADZONE = 0.08; // bo rung tay quanh tam
function setKnob(dx, dy) {
knob.style.transform = 'translate(' + dx + 'px,' + dy + 'px)';
}
function applyStick(dx, dy) {
// Kep vao hinh TRON, khong phai hinh vuong: keo cheo khong duoc phep cho ra
// van toc lon hon keo thang.
const len = Math.hypot(dx, dy);
if (len > JOY_RADIUS) {
dx = dx / len * JOY_RADIUS;
dy = dy / len * JOY_RADIUS;
}
setKnob(dx, dy);
let vx = -dy / JOY_RADIUS; // keo LEN = tien
let wz = -dx / JOY_RADIUS; // keo TRAI = quay trai (nguoc chieu kim dong ho)
if (Math.abs(vx) < DEADZONE) vx = 0;
if (Math.abs(wz) < DEADZONE) wz = 0;
stick.vx = vx;
stick.wz = wz;
txt('jvx', vx.toFixed(2));
txt('jwz', wz.toFixed(2));
}
function releaseStick() {
stick.active = false;
stick.pointerId = null;
joy.classList.remove('active');
applyStick(0, 0);
sendCmd(); // gui 0 NGAY, khong doi tick 20 Hz ke tiep
}
function pointerPos(e) {
const r = joy.getBoundingClientRect();
return {
dx: e.clientX - (r.left + r.width / 2),
dy: e.clientY - (r.top + r.height / 2),
};
}
joy.addEventListener('pointerdown', (e) => {
e.preventDefault();
stick.active = true;
stick.pointerId = e.pointerId;
joy.setPointerCapture(e.pointerId);
joy.classList.add('active');
const p = pointerPos(e);
applyStick(p.dx, p.dy);
});
joy.addEventListener('pointermove', (e) => {
if (!stick.active || e.pointerId !== stick.pointerId) return;
e.preventDefault();
const p = pointerPos(e);
applyStick(p.dx, p.dy);
});
// pointerup VA pointercancel: pointercancel la truong hop trinh duyet cuop
// lai con tro (cuon trang, goi den, chuyen tab). Thieu no thi knob ket o vi
// tri cu va robot chay tiep.
for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture']) {
joy.addEventListener(ev, (e) => {
if (e.pointerId !== stick.pointerId) return;
releaseStick();
});
}
// --- Ban phim --------------------------------------------------------------
// Phim MUI TEN, khop SUPPORTED_KEYS cua TeleopModel ben C++
// ("Up"/"Down"/"Left"/"Right"). Ban dau toi dung WASD -- do la tu nghi ra,
// khong khop mo hinh da co.
const keys = new Set();
const KEY_MAP = {
ArrowUp: [1, 0], ArrowDown: [-1, 0], ArrowLeft: [0, 1], ArrowRight: [0, -1],
};
window.addEventListener('keydown', (e) => {
if (e.key === ' ') { keys.clear(); applyKeys(); e.preventDefault(); return; }
if (e.key === 'q' || e.key === 'Q') { adjustSpeed('lin', -1); return; }
if (e.key === 'e' || e.key === 'E') { adjustSpeed('lin', +1); return; }
if (e.key === '+' || e.key === '=') { adjustSpeed('lin', +1); return; }
if (e.key === '-' || e.key === '_') { adjustSpeed('lin', -1); return; }
if (!(e.key in KEY_MAP) || stick.active) return;
keys.add(e.key);
applyKeys();
e.preventDefault();
});
window.addEventListener('keyup', (e) => {
if (!keys.delete(e.key)) return;
applyKeys();
});
// Mat focus (chuyen tab, alt-tab) = nha het phim. Neu khong thi mot phim
// "dinh" se lam robot chay mai.
window.addEventListener('blur', () => { keys.clear(); applyKeys(); });
function applyKeys() {
if (stick.active) return;
let vx = 0, wz = 0;
for (const k of keys) { vx += KEY_MAP[k][0]; wz += KEY_MAP[k][1]; }
applyStick(-wz * JOY_RADIUS, -vx * JOY_RADIUS);
}
// --- Chinh toc do ----------------------------------------------------------
// Tinh nang cua teleop_model.py: doi scale van toc NGAY KHI DANG CHAY.
// Viec kep vao [min, max] do C++ lam; o day chi gui yeu cau.
function adjustSpeed(which, dir) {
post('teleop/adjust', { axis: which, dir: dir });
}
for (const b of document.querySelectorAll('.sbtn')) {
b.addEventListener('click', () => adjustSpeed(b.dataset.adj, Number(b.dataset.dir)));
}
// --- Gui lenh 20 Hz --------------------------------------------------------
function sendCmd() {
if (!ws || ws.readyState !== 1) return;
ws.send(JSON.stringify({ t: 'cmd', vx: stick.vx, wz: stick.wz }));
}
setInterval(() => {
// Gui LIEN TUC ke ca khi dung yen: deadman o base can nhan duoc lenh deu
// dan de biet nguoi lai van con day. Ngung gui = base tu dung sau 300 ms.
sendCmd();
}, 50);
// --- Do bang thong ---------------------------------------------------------
setInterval(() => {
state.wireRate = state.bytes - state.lastBytes;
state.lastBytes = state.bytes;
txt('wire', (state.wireRate / 1024).toFixed(1) + ' kB/s');
}, 1000);
resize();
connect();
// --- Doi 2D / 3D ----------------------------------------------------------
//
// Hai trinh ve doc CUNG mot `state`, nen khong the lech du lieu. Chi mot cai
// chay tai mot thoi diem: render WebGL khi khong ai nhin la dot CPU/GPU vo
// ich tren Jetson.
// ============ Chia doi: THE GIOI | SLAM ============
//
// Tuong duong mo ca Gazebo lan RViz. Khung trai la SU THAT (de lai cho
// chuan), khung phai la cai SLAM dang dung (de biet quet toi dau). Hai khung
// dung CHUNG `view`, nen pan/zoom khoa voi nhau va doi chieu duoc truc tiep.
const cvR = document.getElementById('mainR');
const ctxR = cvR.getContext('2d');
const btnSplit = document.getElementById('btnSplit');
const labR = document.getElementById('labR');
const wrap = document.querySelector('.canvas-wrap');
let split = false;
btnSplit.addEventListener('click', () => {
if (!state.worldMap) {
// Khong co su that de doi chieu -- chay that, khong phai mo phong.
btnSplit.textContent = 'khong co su that';
setTimeout(() => { btnSplit.textContent = 'chia doi'; }, 1800);
return;
}
split = !split;
wrap.classList.toggle('split', split);
document.getElementById('labL').style.display = split ? '' : 'none';
labR.style.display = split ? '' : 'none';
btnSplit.textContent = split ? 'mot khung' : 'chia doi';
// 3D va chia doi KHONG loai tru nhau: `.split.three` cho ra
// trai = the gioi 3D (Gazebo) | phai = ban do SLAM 2D (RViz)
// -- dung to hop huu ich nhat khi dang quet.
});
{
const el = document.getElementById('uiVer');
if (el) el.textContent = 'ui ' + UI_VERSION;
console.log('vslam ui ' + UI_VERSION);
}
const cv3d = document.getElementById('main3d');
const btn3d = document.getElementById('btn3d');
let use3d = false;
// Hinh hoc 3D THAT cua the gioi -- tai MOT lan, khi bat 3D lan dau.
//
// Khong tai luc mo trang: 6.7 MB la lang phi voi nguoi chi xem khung 2D. Va
// khong tai lai: the gioi khong doi trong mot phien.
//
// 404 KHONG phai loi -- nghia la node chay tu `--map` chu khong tu `--world`,
// va khung 3D quay ve khoi hop dung tu luoi chiem dung.
let worldMeshState = 'chua'; // chua | dang | xong | khong-co
function loadWorldMeshes() {
if (worldMeshState !== 'chua') return;
worldMeshState = 'dang';
fetch('/api/world.bin')
.then((r) => {
if (r.status === 404) { worldMeshState = 'khong-co'; return null; }
if (!r.ok) throw new Error('HTTP ' + r.status);
return r.arrayBuffer();
})
.then((buf) => {
if (!buf) return;
worldMeshState = v3dSetWorldMeshes(buf) ? 'xong' : 'khong-co';
})
.catch((e) => {
console.warn('world.bin:', e);
worldMeshState = 'khong-co';
});
}
btn3d.addEventListener('click', () => {
if (!use3d && !V3D.ready) {
if (!v3dInit(cv3d)) {
btn3d.textContent = '3D loi';
btn3d.classList.add('bad');
return;
}
}
if (!use3d) loadWorldMeshes();
use3d = !use3d;
// Chi doi CLASS. Dat style inline o day se de bep quy tac .split trong
// stylesheet -- dung cai bay da lam khung phai den xi mot lan.
wrap.classList.toggle('three', use3d);
btn3d.textContent = use3d ? '2D' : '3D';
});
// Khoang cach VE giua hai hinh robot -- do tren chinh hai doi tuong 3D, khong
// phai tinh lai tu du lieu.
//
// ⚠️ Doc NGAY tren cai dang duoc ve moi tra loi duoc cau hoi "no lech that hay
// chi trong nhu lech": sai so du lieu va khoang cach hien thi la HAI so khac
// nhau, va da co lan chung khac nhau that (hinh ground truth bi tut 0.075 m vi
// cau truc nhom lech mot tang).
function updateGapChip() {
const el = document.getElementById('gap');
if (!el) return;
const a = V3D.robotGroup && V3D.robotGroup.position;
const b = V3D.gtGroup && V3D.gtGroup.position;
if (!a || !b || !V3D.gtGroup.visible) { el.textContent = 'gap --'; return; }
const d = Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
el.textContent = 'gap ' + d.toFixed(3) + ' m';
el.classList.toggle('bad', d > 0.05);
}
function draw3d() {
if (state.robot) v3dSetShape(state.robot);
if (state.pose) v3dSetPose(V3D.robotGroup, state.pose);
if (state.gt && on('lyGt')) {
if (V3D.gtGroup) V3D.gtGroup.visible = true;
v3dSetPose(V3D.gtGroup, state.gt);
} else if (V3D.gtGroup) {
V3D.gtGroup.visible = false;
}
updateGapChip();
v3dSetScan(on('lyScan') ? state.scan : null, state.pose, state.robot);
v3dSetCloud(on('lyCloud') ? state.cloud : null, state.pose);
// THE GIOI: tuong 3D dung tu ban do mo phong -- day la phan "Gazebo".
// Dung MOT lan (ban do the gioi la tinh), roi chi bat/tat.
// Overlay cam bien (frustum, vanh cliff): tat mac dinh cho giong Gazebo.
v3dSetOverlays(on('lyCam'));
if (state.worldMap) v3dSetWorld(state.worldMap, 2.0);
v3dSetWorldVisible(on('lyWorld'));
// SLAM: lop phu tren san, hien DAN khi quet -- day la phan "RViz". O chua
// quet trong suot nen tuong 3D van nhin xuyen qua.
if (state.map && on('lyMap')) {
v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion });
}
if (V3D.mapMesh) V3D.mapMesh.visible = on('lyMap') && !!state.map;
if (on('lyPath')) v3dSetPath(state.path);
else if (V3D.pathLine) V3D.pathLine.visible = false;
v3dRender(cv3d, on('lyFollow'));
}
requestAnimationFrame(draw);

715
libs/vslam_web/www/app3d.js Normal file
View File

@@ -0,0 +1,715 @@
// Khung nhin 3D -- thay cho RViz.
//
// ================== VI SAO CAN 3D ==================
// Khung 2D nhin tu tren khong the hien duoc thu quan trong nhat cua he nay:
// CHIEU CAO. Camera o 0.80 m chuc xuong 15 do, va vung mu 1.10 m KHONG phai
// mot lua chon tham so -- no la hinh hoc: tia gan nhat cham san o do. Nhin tu
// tren thi con so 1.10 chi la mot vong tron; nhin nghieng thi thay ngay vi
// sao no la 1.10 chu khong phai 0.5.
//
// ================== KHONG DOAN KICH THUOC ==================
// Moi kich thuoc den tu khoi `robot` trong JSON, tuc tu `robot.yaml`. File
// nay KHONG duoc chua mot hang so hinh hoc nao. Ban 2D tung hardcode
// `L = 0.30, W = 0.17` -- khong khop voi bat ky so nao trong robot.yaml (ban
// kinh that 0.24), va khong ai phat hien vi mot tam giac sai kich thuoc van
// trong "nhu that".
//
// ================== HE TOA DO ==================
// ROS: +X truoc, +Y trai, +Z len. three.js: +Y len, -Z truoc.
// Doi MOT lan o `toScene()`, khong rai rac.
'use strict';
const V3D = {
ready: false,
scene: null, camera: null, renderer: null, root: null,
robotGroup: null, scanPts: null, cloudPts: null, mapMesh: null,
worldMesh: null, worldKey: null,
meshWorld: null, // nhom mesh THAT doc tu .world; co thi khong dung khoi hop
gtGroup: null, pathLine: null,
shape: null, // khoi `robot` gan nhat
orbit: { az: -2.2, el: 0.55, dist: 6.0, tx: 0, ty: 0 },
dragging: null,
};
// ROS (x, y, z) -> three.js (x, y, z).
function toScene(x, y, z) {
return new THREE.Vector3(x, z, -y);
}
function v3dInit(canvas) {
if (typeof THREE === 'undefined') {
console.error('three.js chua nap duoc');
return false;
}
V3D.renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
V3D.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
// Bong do: thu duy nhat lam cac khoi tuong tach khoi nhau tren mot ban do
// chi co ba trang thai o. Khong co no thi tat ca la mot mang xam.
V3D.renderer.shadowMap.enabled = true;
V3D.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
V3D.scene = new THREE.Scene();
// ============ BANG MAU KIEU GAZEBO ============
//
// Gazebo dung nen SANG (troi xam nhat), san xam, vat the trang nga. UI con
// lai cua trang nay la nen toi, nhung khung 3D co bang mau RIENG -- vi muc
// tieu cua no la trong giong Gazebo, va tuong trang tren nen toi doc rat te:
// khong co bong, khong co chieu sau, moi khoi thanh mot mang bet.
V3D.scene.background = new THREE.Color(0xb8c6d4);
// Suong mu xa: ban do 2000x2000 o do phan giai 0.05 m la 100 m moi chieu,
// ve het se thanh mot vung nhieu xam. Suong mu cat no mem hon la cat cung.
// Mau suong = mau nen, neu khong se thay mot duong chan troi gia.
V3D.scene.fog = new THREE.Fog(0xb8c6d4, 12, 40);
V3D.camera = new THREE.PerspectiveCamera(55, 1, 0.05, 200);
// Ba nguon sang, khong phai mot.
//
// Ban do occupancy chi co BA trang thai o -- khong vat lieu, khong mau,
// khong noi that. Thu duy nhat lam khoi tuong "doc duoc" la ANH SANG:
// * hemisphere -> troi sang / san toi, cho chieu cao mot huong ro rang
// * directional -> bong do xien, lam noi goc va khe cua
// * fill yeu -> chong mat hoan toan den o phia khuat
// Mot AmbientLight deu tit lam moi buc tuong thanh mot mang phang cung mau,
// va do la ly do ban truoc trong "khong co chi tiet".
V3D.scene.add(new THREE.HemisphereLight(0xdfe9f2, 0x8a9099, 0.9));
const key = new THREE.DirectionalLight(0xfff6e8, 1.15);
key.position.set(8, 16, 6);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
key.shadow.camera.left = -30; key.shadow.camera.right = 30;
key.shadow.camera.top = 30; key.shadow.camera.bottom = -30;
V3D.scene.add(key);
const fill = new THREE.DirectionalLight(0xa8bccc, 0.3);
fill.position.set(-6, 5, -8);
V3D.scene.add(fill);
V3D.root = new THREE.Group();
V3D.scene.add(V3D.root);
// Luoi san 1 m, va truc goc toa do map.
V3D.gridHelper = new THREE.GridHelper(40, 40, 0x93a3b3, 0xa9b6c4);
V3D.root.add(V3D.gridHelper);
V3D.root.add(new THREE.AxesHelper(0.5));
v3dBindMouse(canvas);
V3D.ready = true;
return true;
}
function v3dBindMouse(canvas) {
canvas.addEventListener('mousedown', (e) => {
V3D.dragging = { x: e.clientX, y: e.clientY, btn: e.button };
e.preventDefault();
});
window.addEventListener('mouseup', () => { V3D.dragging = null; });
window.addEventListener('mousemove', (e) => {
if (!V3D.dragging) return;
const dx = e.clientX - V3D.dragging.x, dy = e.clientY - V3D.dragging.y;
V3D.dragging.x = e.clientX; V3D.dragging.y = e.clientY;
if (V3D.dragging.btn === 0) {
V3D.orbit.az -= dx * 0.006;
// Chan o hai dau: qua thien dinh thi khung nhin lat nguoc va nguoi dung
// mat phuong huong.
V3D.orbit.el = Math.max(0.05, Math.min(1.45, V3D.orbit.el + dy * 0.006));
} else {
V3D.orbit.tx -= dx * 0.01;
V3D.orbit.ty += dy * 0.01;
}
});
canvas.addEventListener('wheel', (e) => {
V3D.orbit.dist = Math.max(1.0, Math.min(60, V3D.orbit.dist * (e.deltaY > 0 ? 1.1 : 0.9)));
e.preventDefault();
}, { passive: false });
}
// ---------------------------------------------------------------------------
// Mo hinh robot, dung tu khoi `robot` cua JSON.
// ---------------------------------------------------------------------------
function v3dBuildRobot(r) {
const g = new THREE.Group();
// `base_link` o TAM TRUC banh, cach san dung bang ban kinh banh. Nang ca
// nhom len de san o y = 0 -- moi thu khac (scan, cloud, ban do) deu o he
// toa do map voi san la 0.
g.position.y = r.wheel_radius;
const bodyMat = new THREE.MeshLambertMaterial({ color: 0x3d6ea5 });
const darkMat = new THREE.MeshLambertMaterial({ color: 0x20262e });
// Than: tru tron ban kinh `radius`. Chieu cao chon theo ban kinh, khong
// phai mot hang so -- robot.yaml khong co chieu cao than.
const bodyH = r.radius * 1.2;
const body = new THREE.Mesh(
new THREE.CylinderGeometry(r.radius, r.radius, bodyH, 28), bodyMat);
body.position.y = bodyH / 2;
g.add(body);
// Mui chi huong +X, de nhin mot cai la biet dau la truoc.
const nose = new THREE.Mesh(
new THREE.ConeGeometry(r.radius * 0.28, r.radius * 0.5, 16),
new THREE.MeshLambertMaterial({ color: 0x8ec5ff }));
nose.rotation.z = -Math.PI / 2;
nose.position.set(r.radius * 0.85, bodyH * 0.55, 0);
g.add(nose);
// Hai banh chu dong, cach nhau `wheel_sep`.
for (const side of [-1, 1]) {
const w = new THREE.Mesh(
new THREE.CylinderGeometry(r.wheel_radius, r.wheel_radius, 0.04, 20),
darkMat);
w.rotation.x = Math.PI / 2;
w.position.set(0, 0, side * r.wheel_sep / 2);
g.add(w);
}
// LiDAR: tru nho o dung vi tri trong robot.yaml.
const lidar = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 0.06, 16),
new THREE.MeshLambertMaterial({ color: 0xe2574c }));
lidar.position.copy(toScene(r.laser_x, r.laser_y, r.laser_z));
g.add(lidar);
// Camera: hop nho tren cot, chuc xuong `cam_pitch`.
const camG = new THREE.Group();
camG.position.copy(toScene(r.cam_x, r.cam_y, r.cam_z));
// Chuc xuong = quay quanh truc +Z cua ROS = truc -Y cua three.js... nhung
// vi ta xoay CA NHOM roi moi dat frustum ben trong theo +X, chi can quay
// quanh truc Z cua scene (tuong ung truc Y cua ROS).
camG.rotation.z = -r.cam_pitch;
const cam = new THREE.Mesh(new THREE.BoxGeometry(0.03, 0.05, 0.10), darkMat);
camG.add(cam);
// Cot do camera, tu than len toi camera.
const mastH = r.cam_z - bodyH;
if (mastH > 0) {
const mast = new THREE.Mesh(
new THREE.CylinderGeometry(0.02, 0.02, mastH, 12), darkMat);
mast.position.copy(toScene(r.cam_x, r.cam_y, bodyH + mastH / 2));
g.add(mast);
}
// Frustum camera: hinh chop cut, ve bang duong vien de khong che mat cloud.
// Frustum va vanh cliff la OVERLAY kieu RViz, khong phai mot phan robot.
// Gazebo khong ve chung. Danh dau de bat/tat rieng -- chung to hon than
// robot nhieu lan (1.1-2.5 m so voi ban kinh 0.24 m) nen bat mac dinh se
// lan at ca khung nhin.
{
const fr = v3dFrustum(r);
fr.userData.overlay = true;
camG.add(fr);
}
g.add(camG);
return g;
}
// Khung day cua frustum camera, keo dai toi `cliff_max`.
//
// Day la thu 2D khong the hien duoc: no cho thay NGAY vi sao vung mu la
// `cliff_min` -- tia duoi cung cua frustum cham san o dung do.
function v3dFrustum(r) {
const far = r.cliff_max;
const hw = Math.tan(r.cam_hfov / 2) * far;
const hh = Math.tan(r.cam_vfov / 2) * far;
// Trong frame CAMERA (truoc khi nhom bi chuc xuong): +X la truc quang.
const corners = [
toScene(far, +hw, +hh), toScene(far, -hw, +hh),
toScene(far, -hw, -hh), toScene(far, +hw, -hh),
];
const pts = [];
for (const c of corners) { pts.push(new THREE.Vector3(0, 0, 0), c); }
for (let i = 0; i < 4; ++i) pts.push(corners[i], corners[(i + 1) % 4]);
return new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(pts),
new THREE.LineBasicMaterial({ color: 0x00c853, transparent: true, opacity: 0.45 }));
}
// Vanh danh dau cua so cliff_detect tren san: trong = VUNG MU.
function v3dCliffRings(r) {
const g = new THREE.Group();
const mk = (radius, color) => {
const pts = [];
for (let i = 0; i <= 64; ++i) {
const a = (i / 64) * Math.PI * 2;
pts.push(toScene(r.cam_x + radius * Math.cos(a), radius * Math.sin(a), 0.005));
}
return new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts),
new THREE.LineBasicMaterial({ color: color }));
};
g.add(mk(r.cliff_min, 0xe2574c)); // trong vanh do: camera KHONG THAY GI
g.add(mk(r.cliff_max, 0x4ec9a0));
return g;
}
// ---------------------------------------------------------------------------
// Cap nhat moi khung
// ---------------------------------------------------------------------------
function v3dSetShape(r) {
if (!V3D.ready || !r) return;
// Dung lai CHI khi hinh hoc that su doi -- dung lai moi khung la 10 lan/s
// cap phat hinh hoc vo ich.
const key = JSON.stringify(r);
if (V3D.shapeKey === key) return;
V3D.shapeKey = key;
V3D.shape = r;
if (V3D.robotGroup) V3D.root.remove(V3D.robotGroup);
V3D.robotGroup = new THREE.Group();
V3D.robotGroup.add(v3dBuildRobot(r));
{
const rings = v3dCliffRings(r);
rings.userData.overlay = true;
V3D.robotGroup.add(rings);
}
V3D.root.add(V3D.robotGroup);
if (V3D.gtGroup) V3D.root.remove(V3D.gtGroup);
// ⚠️ Phai BOC y het robotGroup o tren.
//
// Truoc day gtGroup la ket qua cua v3dBuildRobot() TRUC TIEP, con robotGroup
// la mot Group moi BOC lay no. Cau truc lech nhau mot tang, nen phep nang
// than (`g.position.y = wheel_radius`) roi vao tang KHAC nhau o hai ben:
// robotGroup giu duoc no o tang trong, gtGroup thi bi v3dSetPose() xoa mat.
//
// Ket qua: hinh ground truth nam THAP HON hinh uoc luong dung 0.075 m. O goc
// camera nghieng, chenh lech do chieu ra thanh mot khoang cach NGANG nhin
// thay duoc -- trong y het "robot co mot nhan ban o canh", trong khi sai so
// uoc luong that chi 9 mm.
V3D.gtGroup = new THREE.Group();
const gtBody = v3dBuildRobot(r);
V3D.gtGroup.add(gtBody);
V3D.gtGroup.traverse((o) => {
if (o.material) {
o.material = o.material.clone();
o.material.transparent = true;
o.material.opacity = 0.25;
if (o.material.color) o.material.color.set(0x00c853);
}
});
V3D.root.add(V3D.gtGroup);
}
function v3dSetPose(group, p) {
if (!group || !p) return;
// ⚠️ CHI dat x va z. `position.set(p.x, 0, -p.y)` ghi de luon y, ma y la
// phep nang than ma v3dBuildRobot() da dat (`g.position.y = wheel_radius`,
// vi `base_link` o TAM TRUC banh chu khong o san).
//
// Ghi de lam robot lun 0.075 m vao san: banh chim mot nua, va tru LiDAR
// tren robot nam o 0.125 m trong khi diem quet duoc ve o
// `laser_z + wheel_radius` = 0.20 m -- hai thu le nhau ngay tren cung mot
// robot, dung thu de nguoi xem nghi la "troi".
group.position.x = p.x;
group.position.z = -p.y;
group.rotation.y = p.yaw;
}
// scan: mang [x0,y0, x1,y1, ...] trong frame LASER (xem ghi chu ben trong).
function v3dSetScan(arr, pose, r) {
if (!V3D.ready) return;
if (!V3D.scanPts) {
V3D.scanPts = new THREE.Points(
new THREE.BufferGeometry(),
new THREE.PointsMaterial({ color: 0xe2574c, size: 0.05 }));
V3D.root.add(V3D.scanPts);
}
if (!arr || !pose || !r) { V3D.scanPts.visible = false; return; }
V3D.scanPts.visible = true;
const c = Math.cos(pose.yaw), s = Math.sin(pose.yaw);
const n = arr.length / 2;
const pos = new Float32Array(n * 3);
// Scan nam o do cao cua LiDAR, khong phai o san. Ve o san se lam nguoi xem
// tuong LiDAR thay duoc vat thap -- no KHONG thay.
const z = r.laser_z + r.wheel_radius;
// ⚠️ Scan den trong frame LASER, khong phai frame BASE.
//
// `laser_link` cach `base_link` 0.24 m ve phia truoc (robot.yaml). Dat thang
// toa do laser vao pose cua base lam CA vanh quet lui 24 cm: cac tia khong
// con nam tren tuong, va nhin nhu robot bi "troi".
//
// Da do tren the gioi benh vien: khong bu thi 752/944 diem roi trung tuong
// (79.7%); bu roi thi 944/944 (100%).
const lx = r.laser_x || 0, ly = r.laser_y || 0;
for (let i = 0; i < n; ++i) {
const x = arr[i * 2] + lx, y = arr[i * 2 + 1] + ly;
pos[i * 3] = pose.x + c * x - s * y;
pos[i * 3 + 1] = z;
pos[i * 3 + 2] = -(pose.y + s * x + c * y);
}
V3D.scanPts.geometry.dispose();
V3D.scanPts.geometry = new THREE.BufferGeometry();
V3D.scanPts.geometry.setAttribute('position', new THREE.BufferAttribute(pos, 3));
}
// cloud: mang [x,y,z, ...] trong frame BASE_FOOTPRINT (da can trong luc).
function v3dSetCloud(arr, pose) {
if (!V3D.ready) return;
if (!V3D.cloudPts) {
V3D.cloudPts = new THREE.Points(
new THREE.BufferGeometry(),
new THREE.PointsMaterial({ size: 0.03, vertexColors: true }));
V3D.root.add(V3D.cloudPts);
}
if (!arr || !pose) { V3D.cloudPts.visible = false; return; }
V3D.cloudPts.visible = true;
const c = Math.cos(pose.yaw), s = Math.sin(pose.yaw);
const n = arr.length / 3;
const pos = new Float32Array(n * 3), col = new Float32Array(n * 3);
for (let i = 0; i < n; ++i) {
const x = arr[i * 3], y = arr[i * 3 + 1], z = arr[i * 3 + 2];
pos[i * 3] = pose.x + c * x - s * y;
pos[i * 3 + 1] = z;
pos[i * 3 + 2] = -(pose.y + s * x + c * y);
// To mau theo do cao, cung bang mau voi khung 2D.
const t = Math.max(0, Math.min(1, z / 1.2));
col[i * 3] = (80 + 175 * t) / 255;
col[i * 3 + 1] = (200 - 90 * t) / 255;
col[i * 3 + 2] = (120 + 60 * t) / 255;
}
V3D.cloudPts.geometry.dispose();
V3D.cloudPts.geometry = new THREE.BufferGeometry();
V3D.cloudPts.geometry.setAttribute('position', new THREE.BufferAttribute(pos, 3));
V3D.cloudPts.geometry.setAttribute('color', new THREE.BufferAttribute(col, 3));
}
// The gioi 3D: o BI CHIEM -> hop, dung nhu Gazebo dung tuong tu ban do.
//
// ================== VI SAO INSTANCED ==================
// map_hospital co 32945 o bi chiem tren 611212 (5.4%). Mot `Mesh` moi o la
// San, luoi san va suong mu -- phu thuoc BAO cua the gioi, khong phu thuoc
// the gioi duoc ve bang mesh that hay bang khoi hop.
//
// ⚠️ Tach rieng khoi v3dSetWorld() la co chu y: khi chay tu `.world`, hang
// mesh that lam v3dSetWorld() thoat som, va neu san nam ben trong ham do thi
// ca toa nha se lo lung tren nen den.
//
// San dat o TOA DO THE GIOI chu khong theo robot. Dat theo robot la dung cai
// bay "sàn troi theo robot": robot dung yen giua man hinh con ca the gioi
// truot qua, trong y het loi dinh vi.
function v3dSetGround(grid) {
if (!V3D.ready || !grid) return;
const r = grid.res;
if (V3D.floorMesh) {
V3D.root.remove(V3D.floorMesh);
V3D.floorMesh.geometry.dispose();
}
const fw = grid.w * r, fh = grid.h * r;
V3D.floorMesh = new THREE.Mesh(
new THREE.PlaneGeometry(fw, fh),
new THREE.MeshStandardMaterial({ color: 0x9aa5ad, roughness: 1.0 }));
V3D.floorMesh.rotation.x = -Math.PI / 2;
V3D.floorMesh.position.set(grid.ox + fw / 2, -0.004, -(grid.oy + fh / 2));
V3D.floorMesh.receiveShadow = true;
V3D.root.add(V3D.floorMesh);
// Suong mu phai phu HET toa nha, khong thi phan lon ban do tan vao nen va
// trong nhu chua nap. Mac dinh 12-40 m vua cho the gioi tong hop; mot tang
// benh vien 27x59 m thi khong.
const span = Math.max(fw, fh);
V3D.scene.fog.near = span * 0.35;
V3D.scene.fog.far = span * 1.4;
if (V3D.gridHelper) V3D.root.remove(V3D.gridHelper);
V3D.gridHelper = new THREE.GridHelper(Math.ceil(span), Math.ceil(span),
0x93a3b3, 0xa9b6c4);
V3D.root.add(V3D.gridHelper);
}
// ---------------------------------------------------------------------------
// The gioi dung tu MESH THAT cua Gazebo
// ---------------------------------------------------------------------------
//
// Phia C++ da doc `.obj`/`.dae` va gui thang tam giac qua `GET /api/world.bin`
// -- trinh duyet khong co bo doc COLLADA offline, va 149 texture PNG cua bo
// model nay tong cong 74 MB, gui tung ay moi lan mo trang la khong duoc.
//
// Mau tung model lay tu TRUNG VI texture cua chinh no, tinh san phia may chu
// (tools/gen_model_colors.py). Khong co texture thi hinh dang van dung, va
// hinh dang moi la thu nguoi van hanh dung de nhan ra cho minh dang o.
//
// Khong co khoi nay (chay tu `--map` thay vi `--world`) thi v3dSetWorld() ben
// duoi dung khoi hop tu luoi chiem dung -- kem hon nhung van dinh huong duoc.
function v3dSetWorldMeshes(buf) {
if (!V3D.ready || !buf || buf.byteLength < 16) return false;
const dv = new DataView(buf);
if (String.fromCharCode(dv.getUint8(0), dv.getUint8(1), dv.getUint8(2),
dv.getUint8(3)) !== 'VSLW') {
console.error('world.bin: sai magic');
return false;
}
if (dv.getUint32(4, true) !== 1) {
console.error('world.bin: phien ban la');
return false;
}
const nGeom = dv.getUint32(8, true), nInst = dv.getUint32(12, true);
let o = 16;
const geoms = [];
for (let i = 0; i < nGeom; ++i) {
const nameLen = dv.getUint32(o, true); o += 4;
o += nameLen; // ten chi de go loi, khong ve
const r = dv.getUint8(o), g = dv.getUint8(o + 1), b = dv.getUint8(o + 2);
o += 3;
const nTri = dv.getUint32(o, true); o += 4;
// Doc thang tu buffer: 194k tam giac, mot vong lap tao Vector3 moi dinh
// se sinh 580k doi tuong rac.
const pos = new Float32Array(nTri * 9);
for (let k = 0; k < nTri * 3; ++k) {
// ROS (x, y, z) -> three (x, z, -y), lam NGAY o day chu khong qua
// toScene(): mot lan doi truc tren mang phang re hon nhieu lan.
const x = dv.getFloat32(o, true);
const y = dv.getFloat32(o + 4, true);
const z = dv.getFloat32(o + 8, true);
o += 12;
pos[k * 3] = x; pos[k * 3 + 1] = z; pos[k * 3 + 2] = -y;
}
const bg = new THREE.BufferGeometry();
bg.setAttribute('position', new THREE.BufferAttribute(pos, 3));
bg.computeVertexNormals();
geoms.push({ geom: bg, r: r, g: g, b: b, n: 0 });
}
// Dem the hien TRUOC khi cap phat: InstancedMesh co so luong co dinh.
const inst = [];
for (let i = 0; i < nInst; ++i) {
const gi = dv.getUint32(o, true);
const x = dv.getFloat32(o + 4, true);
const y = dv.getFloat32(o + 8, true);
const z = dv.getFloat32(o + 12, true);
const yaw = dv.getFloat32(o + 16, true);
o += 20;
if (gi < geoms.length) { geoms[gi].n++; inst.push([gi, x, y, z, yaw]); }
}
if (V3D.meshWorld) {
V3D.root.remove(V3D.meshWorld);
V3D.meshWorld.traverse((m) => {
if (m.geometry) m.geometry.dispose();
if (m.material) m.material.dispose();
});
}
const group = new THREE.Group();
const made = [];
for (const gd of geoms) {
if (gd.n === 0) { gd.geom.dispose(); made.push(null); continue; }
const mat = new THREE.MeshStandardMaterial({
color: new THREE.Color(gd.r / 255, gd.g / 255, gd.b / 255),
roughness: 0.85, metalness: 0.05,
});
const im = new THREE.InstancedMesh(gd.geom, mat, gd.n);
im.castShadow = true;
im.receiveShadow = true;
im.userData.fill = 0;
made.push(im);
group.add(im);
}
const m4 = new THREE.Matrix4(), q = new THREE.Quaternion();
const axisY = new THREE.Vector3(0, 1, 0), one = new THREE.Vector3(1, 1, 1);
for (const [gi, x, y, z, yaw] of inst) {
const im = made[gi];
if (!im) continue;
// Quay quanh z cua ROS = quay quanh y cua three voi CUNG dau goc: ROS x
// ung voi three x, ROS y ung voi three -z, nen hai phep quay trung nhau.
q.setFromAxisAngle(axisY, yaw);
m4.compose(toScene(x, y, z), q, one);
im.setMatrixAt(im.userData.fill++, m4);
}
for (const im of made) if (im) im.instanceMatrix.needsUpdate = true;
V3D.meshWorld = group;
V3D.root.add(group);
// Khoi hop tu luoi tro nen thua: bo di de khong ve chong len do dac that.
if (V3D.worldMesh) {
V3D.root.remove(V3D.worldMesh);
V3D.worldMesh.geometry.dispose();
V3D.worldMesh.dispose();
V3D.worldMesh = null;
V3D.worldKey = null;
}
return true;
}
// 33k draw call -- khung hinh sup. `InstancedMesh` ve tat ca trong MOT draw
// call: cung hinh hoc, khac ma tran.
//
// Ban do the gioi la TINH trong mo phong, nen chi dung MOT lan.
function v3dSetWorld(grid, wallHeight) {
if (!V3D.ready || !grid) return;
// Da co mesh that thi khong dung khoi hop nua -- ve ca hai se thay tuong
// hop bao quanh do dac that. Nhung SAN thi van phai dung.
if (V3D.meshWorld) { v3dSetGround(grid); return; }
const key = grid.w + 'x' + grid.h + '@' + grid.ox + ',' + grid.oy;
if (V3D.worldKey === key) return;
V3D.worldKey = key;
if (V3D.worldMesh) {
V3D.root.remove(V3D.worldMesh);
V3D.worldMesh.geometry.dispose();
V3D.worldMesh.dispose();
}
// Dem truoc de cap phat dung so instance.
let n = 0;
for (let i = 0; i < grid.cells.length; ++i) if (grid.cells[i] >= 50) n++;
if (n === 0) { V3D.worldMesh = null; return; }
const r = grid.res, hgt = wallHeight || 2.0;
// `MeshStandardMaterial` chu khong `Lambert`: co roughness nen be mat bat
// duoc huong sang, va goc tuong hien ra thay vi phang lì.
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(r, hgt, r),
new THREE.MeshStandardMaterial({ roughness: 0.85, metalness: 0.05 }),
n);
mesh.castShadow = true;
mesh.receiveShadow = true;
const occ = (cx, cy) =>
cx >= 0 && cy >= 0 && cx < grid.w && cy < grid.h &&
grid.cells[cy * grid.w + cx] >= 50;
const m4 = new THREE.Matrix4();
const col = new THREE.Color();
let k = 0;
for (let cy = 0; cy < grid.h; ++cy) {
for (let cx = 0; cx < grid.w; ++cx) {
if (!occ(cx, cy)) continue;
const wx = grid.ox + (cx + 0.5) * r;
const wy = grid.oy + (cy + 0.5) * r;
// Chieu cao theo DO DAY cua buc tuong.
//
// Mot lop o don le (vach ngan, tu, cot) thap hon tuong chiu luc day
// nhieu lop. Do la thu duy nhat ve "chi tiet kien truc" suy ra duoc tu
// mot luoi occupancy -- va no lam mat bang doc duoc ngay: hanh lang,
// phong, do noi that tach han nhau thay vi mot khoi xam dong nhat.
let nb = 0;
for (let dy = -1; dy <= 1; ++dy)
for (let dx = -1; dx <= 1; ++dx)
if ((dx || dy) && occ(cx + dx, cy + dy)) nb++;
const thick = nb / 8; // 0 = don doc, 1 = trong khoi
const hh = hgt * (0.45 + 0.55 * thick);
m4.makeScale(1, hh / hgt, 1);
m4.setPosition(wx, hh / 2, -wy);
mesh.setMatrixAt(k, m4);
// Mau cung theo do day: vach mong sang hon, tuong day toi hon. Cong
// voi bong do, mat bang doc duoc nhu mot ban ve.
// Trang nga hoi am, dam dan theo do day vach -- kieu vat lieu mac
// dinh cua Gazebo.
col.setHSL(0.09, 0.06, 0.88 - 0.20 * thick);
mesh.setColorAt(k, col);
k++;
}
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
V3D.worldMesh = mesh;
V3D.root.add(mesh);
v3dSetGround(grid);
}
// Ban do occupancy -> mot mat phang co texture, dat o san.
function v3dSetMap(map) {
if (!V3D.ready || !map || !map.w || !map.h) return;
if (V3D.mapKey === map.version) return;
V3D.mapKey = map.version;
const cv = document.createElement('canvas');
cv.width = map.w; cv.height = map.h;
const g = cv.getContext('2d');
const img = g.createImageData(map.w, map.h);
for (let i = 0; i < map.w * map.h; ++i) {
const v = map.data[i];
// -1 = CHUA BIET. Ve no khac han o trong: "chua di toi" va "da di toi,
// khong co gi" la hai chuyen khac nhau, va gop lai se lam ban do trong
// day du hon thuc te.
// Day la lop phu "DA QUET" chong len the gioi 3D -- tuong duong lop
// Map cua RViz. O CHUA BIET phai TRONG SUOT, neu khong no phu kin ca toa
// nha va che mat tuong 3D.
let r, gg, b, a;
if (v < 0) { r = gg = b = 0; a = 0; } // chua quet -> trong suot
else if (v >= 50) { r = 90; gg = 200; b = 255; a = 230; } // tuong da quet
else { r = 40; gg = 90; b = 130; a = 120; } // san da quet
img.data[i * 4] = r; img.data[i * 4 + 1] = gg;
img.data[i * 4 + 2] = b; img.data[i * 4 + 3] = a;
}
g.putImageData(img, 0, 0);
const tex = new THREE.CanvasTexture(cv);
tex.magFilter = THREE.NearestFilter;
tex.minFilter = THREE.LinearMipmapLinearFilter;
if (V3D.mapMesh) { V3D.root.remove(V3D.mapMesh); V3D.mapMesh.geometry.dispose(); }
const wM = map.w * map.res, hM = map.h * map.res;
V3D.mapMesh = new THREE.Mesh(
new THREE.PlaneGeometry(wM, hM),
new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false }));
V3D.mapMesh.rotation.x = -Math.PI / 2;
// Hoi thap hon san mot chut de khong z-fight voi luoi va vanh cliff.
V3D.mapMesh.position.set(map.ox + wM / 2, -0.002, -(map.oy + hM / 2));
V3D.root.add(V3D.mapMesh);
}
function v3dSetPath(pts) {
if (!V3D.ready) return;
if (V3D.pathLine) { V3D.root.remove(V3D.pathLine); V3D.pathLine.geometry.dispose(); }
if (!pts || pts.length < 4) return;
const v = [];
for (let i = 0; i + 1 < pts.length; i += 2) v.push(toScene(pts[i], pts[i + 1], 0.01));
V3D.pathLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(v),
new THREE.LineBasicMaterial({ color: 0xffb300 }));
V3D.root.add(V3D.pathLine);
}
// Bat/tat cac overlay kieu RViz (frustum camera, vanh cliff).
//
// Gazebo chi ve THE GIOI va ROBOT. Frustum 2.5 m va vanh cliff 1.1-2.5 m to
// hon than robot (ban kinh 0.24 m) hang chuc lan, nen de mac dinh BAT thi
// khung nhin trong khong giong Gazebo chut nao.
// Bat/tat lop "the gioi", du no dung tu mesh that hay tu khoi hop.
function v3dSetWorldVisible(on) {
if (V3D.meshWorld) V3D.meshWorld.visible = on;
if (V3D.worldMesh) V3D.worldMesh.visible = on;
}
function v3dSetOverlays(on) {
if (!V3D.ready || !V3D.root) return;
V3D.root.traverse((o) => {
if (o.userData && o.userData.overlay) o.visible = on;
});
}
function v3dRender(canvas, follow) {
if (!V3D.ready) return;
const w = canvas.clientWidth, h = canvas.clientHeight;
if (canvas.width !== w || canvas.height !== h) {
V3D.renderer.setSize(w, h, false);
V3D.camera.aspect = w / Math.max(1, h);
V3D.camera.updateProjectionMatrix();
}
// Tam quay: bam theo robot neu bat, khong thi theo diem pan cua nguoi dung.
let cx = V3D.orbit.tx, cz = V3D.orbit.ty;
if (follow && V3D.robotGroup) {
cx = V3D.robotGroup.position.x + V3D.orbit.tx;
cz = V3D.robotGroup.position.z + V3D.orbit.ty;
}
const o = V3D.orbit;
V3D.camera.position.set(
cx + o.dist * Math.cos(o.el) * Math.cos(o.az),
o.dist * Math.sin(o.el),
cz + o.dist * Math.cos(o.el) * Math.sin(o.az));
V3D.camera.lookAt(cx, 0.2, cz);
V3D.renderer.render(V3D.scene, V3D.camera);
}

View File

@@ -0,0 +1,156 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>vslam</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<div class="layers">
<label><input type="checkbox" id="lyWorld" checked> the gioi</label>
<label><input type="checkbox" id="lyMap" checked> map SLAM</label>
<label><input type="checkbox" id="lyScan" checked> scan</label>
<label><input type="checkbox" id="lyCloud" checked> cloud</label>
<label><input type="checkbox" id="lyPath" checked> path</label>
<label><input type="checkbox" id="lyCam"> overlay cam bien</label>
<label><input type="checkbox" id="lyGt" checked> ground truth</label>
<label><input type="checkbox" id="lyFollow"> bam robot</label>
</div>
<button id="btnSplit" class="chip" title="Hai khung: THE GIOI (de lai) va SLAM (de xem ban do dang dung)">chia doi</button>
<button id="btn3d" class="chip" title="Doi giua nhin tu tren (2D) va 3D">3D</button>
<div class="spacer"></div>
<!-- ⚠️ O nay ton tai de tra loi MOT cau hoi: trinh duyet dang chay ban JS
nao. Sua o `www/` la sua file tinh, khong phai sua server, nen khoi
dong lai node KHONG lam trinh duyet nap lai. Da mat mot vong trao doi
vi khong phan biet duoc "da sua chua chay" voi "sua roi ma van the". -->
<div id="uiVer" class="chip" title="Phien ban ma nguon giao dien. Khong khop voi ban moi nhat nghia la trinh duyet con cache -- Ctrl-Shift-R.">ui --</div>
<div id="gap" class="chip" title="Khoang cach VE giua hinh uoc luong (xanh duong) va hinh ground truth (xanh la). Day la con so that, do tren chinh hai doi tuong 3D.">gap --</div>
<div id="mode" class="chip">--</div>
<div id="conn" class="chip bad">mat ket noi</div>
</header>
<main>
<div class="canvas-wrap">
<canvas id="main"></canvas>
<!-- Canvas 3D nam CHONG len canvas 2D, an/hien bang nut. Hai trinh ve
doc CUNG mot `state`, nen khong the lech du lieu. -->
<canvas id="main3d"></canvas>
<!-- Khung PHAI o che do chia doi: ban do SLAM dang dung. Khung trai giu
nguyen `main`, hien ban do THE GIOI. -->
<canvas id="mainR"></canvas>
<div id="labL" class="pane-label" style="display:none">THE GIOI (su that)</div>
<div id="labR" class="pane-label" style="display:none">SLAM dang dung</div>
<div id="hint">keo de di chuyen &middot; cuon de phong to &middot; nhan dup de ve giua</div>
</div>
<aside>
<section>
<h2>pose (map)</h2>
<table>
<tr><td>x</td><td id="px">--</td></tr>
<tr><td>y</td><td id="py">--</td></tr>
<tr><td>yaw</td><td id="pyaw">--</td></tr>
<!-- Ground truth chi co khi mo phong. Sai so la thuoc do duy nhat
cho biet uoc luong dang tot hay te. -->
<tr><td>sai so</td><td id="gtErr">--</td></tr>
</table>
</section>
<section>
<h2>safety</h2>
<div id="safeState" class="state">--</div>
<div id="safeDetail" class="detail"></div>
<table>
<tr><td>min_front</td><td id="minFront">--</td></tr>
<tr><td>tia dung duoc</td><td id="rays">--</td></tr>
<tr><td>tia bi che</td><td id="blanked">--</td></tr>
</table>
</section>
<section>
<h2>perception</h2>
<!-- Ba trang thai KHAC NHAU, khong duoc gop: co vuc / khong co vuc /
khong biet. "Khong biet" la khi camera khong nhin thay san (bi vat
can che, khop mat san hong, robot khong bang phang). Gop no vao
"khong co vuc" la dung cai lam robot di thang vao bac thang. -->
<div id="cliffState" class="state">--</div>
<table>
<tr><td>roll</td><td id="tRoll">--</td></tr>
<tr><td>pitch</td><td id="tPitch">--</td></tr>
<tr><td>accel</td><td id="tAccel">--</td></tr>
</table>
</section>
<section>
<h2>slam</h2>
<table>
<tr><td>dinh vi</td><td id="loc">--</td></tr>
<tr><td>diem</td><td id="score">--</td></tr>
<tr><td>process</td><td id="pms">--</td></tr>
<tr><td>map ver</td><td id="mapver">--</td></tr>
</table>
</section>
<section>
<h2>tan so (Hz)</h2>
<table>
<tr><td>lidar</td><td id="hzLidar">--</td></tr>
<tr><td>camera</td><td id="hzCam">--</td></tr>
<tr><td>imu</td><td id="hzImu">--</td></tr>
<tr><td>ekf</td><td id="hzEkf">--</td></tr>
</table>
</section>
<section>
<h2>tai nguyen</h2>
<table>
<tr><td>cpu</td><td id="cpu">--</td></tr>
<tr><td>rss</td><td id="rss">--</td></tr>
<tr><td>drop</td><td id="drops">--</td></tr>
<tr><td>wire</td><td id="wire">--</td></tr>
</table>
</section>
<section>
<h2>dieu khien</h2>
<div class="joy-wrap">
<div id="joy" class="joy">
<div class="joy-cross"></div>
<div id="knob" class="joy-knob"></div>
</div>
</div>
<table>
<tr><td>vx</td><td id="jvx">0.00</td></tr>
<tr><td>wz</td><td id="jwz">0.00</td></tr>
</table>
<div class="speed-row">
<button class="sbtn" data-adj="lin" data-dir="-1">&minus;</button>
<span class="slabel">toc do</span>
<span id="linSpeed" class="sval">0.30</span>
<button class="sbtn" data-adj="lin" data-dir="1">+</button>
</div>
<div class="speed-row">
<button class="sbtn" data-adj="ang" data-dir="-1">&minus;</button>
<span class="slabel">quay</span>
<span id="angSpeed" class="sval">0.70</span>
<button class="sbtn" data-adj="ang" data-dir="1">+</button>
</div>
<div class="hint-sm">keo joystick &middot; phim mui ten &middot; Space = dung<br>+ &minus; hoac Q E de chinh toc do</div>
</section>
<section class="controls">
<button id="estop" class="danger">E-STOP</button>
<button id="reset">RESET</button>
</section>
</aside>
</main>
<script src="vendor/three.min.js"></script>
<script src="app3d.js"></script>
<script src="app.js"></script>
</body>
</html>

View File

@@ -0,0 +1,168 @@
/* Mot trang, khong dependency. Muc tieu < 60 kB cho ca ba file. */
:root {
--bg: #12151a;
--panel: #1a1f27;
--line: #2a323d;
--fg: #d6dde7;
--dim: #7c8798;
--ok: #4ec9a0;
--warn: #e0b34a;
--bad: #e2574c;
--accent: #5aa9e6;
}
* { box-sizing: border-box; }
html, body {
margin: 0; height: 100%;
background: var(--bg); color: var(--fg);
font: 13px/1.45 ui-monospace, "JetBrains Mono", Menlo, Consolas, monospace;
}
header {
display: flex; align-items: center; gap: 12px;
padding: 8px 12px; border-bottom: 1px solid var(--line);
background: var(--panel);
}
.spacer { flex: 1; }
.layers { display: flex; gap: 14px; }
.layers label { cursor: pointer; user-select: none; color: var(--dim); }
.layers input { accent-color: var(--accent); margin-right: 4px; }
.chip {
padding: 3px 10px; border-radius: 3px;
background: #222a34; border: 1px solid var(--line);
}
.chip.ok { color: var(--ok); border-color: #2c5b4c; }
.chip.bad { color: var(--bad); border-color: #5b2f2c; }
main { display: flex; height: calc(100% - 41px); }
.canvas-wrap { position: relative; flex: 1; min-width: 0; }
canvas { display: block; width: 100%; height: 100%; cursor: grab; }
canvas:active { cursor: grabbing; }
#hint {
position: absolute; left: 10px; bottom: 8px;
color: var(--dim); font-size: 11px; pointer-events: none;
}
aside {
width: 260px; flex: none; overflow-y: auto;
border-left: 1px solid var(--line); background: var(--panel);
}
aside section { padding: 10px 12px; border-bottom: 1px solid var(--line); }
aside h2 {
margin: 0 0 6px; font-size: 11px; font-weight: 500;
letter-spacing: .08em; text-transform: uppercase; color: var(--dim);
}
aside table { width: 100%; border-collapse: collapse; }
aside td { padding: 1px 0; }
aside td:first-child { color: var(--dim); }
aside td:last-child { text-align: right; font-variant-numeric: tabular-nums; }
.state {
padding: 5px 8px; border-radius: 3px; text-align: center;
background: #222a34; border: 1px solid var(--line); margin-bottom: 4px;
}
.state.ok { color: var(--ok); border-color: #2c5b4c; }
.state.warn { color: var(--warn); border-color: #5b4d2c; }
.state.bad { color: var(--bad); border-color: #5b2f2c; }
.detail { color: var(--dim); font-size: 11px; min-height: 16px; margin-bottom: 4px; }
.controls { display: flex; gap: 8px; }
button {
flex: 1; padding: 9px; cursor: pointer;
background: #222a34; color: var(--fg);
border: 1px solid var(--line); border-radius: 3px;
font: inherit;
}
button:hover { border-color: var(--accent); }
button.danger { color: var(--bad); border-color: #5b2f2c; }
button.danger:hover { background: var(--bad); color: #fff; }
/* --- Joystick ---
Thay cho virtual_joystick.py (896 dong Tkinter) cua ban ROS.
Chi gui gia tri da chuan hoa [-1,1]; moi phep ramp va deadman deu o C++. */
.joy-wrap { display: flex; justify-content: center; padding: 6px 0 10px; }
.joy {
position: relative;
width: 160px; height: 160px;
border-radius: 50%;
background: radial-gradient(circle at 50% 50%, #222a34 0%, #1a1f27 70%);
border: 1px solid var(--line);
touch-action: none; /* tat pan/zoom cua trinh duyet khi keo */
user-select: none;
cursor: grab;
}
.joy:active { cursor: grabbing; }
/* Hai vach chu thap de thay tam va truc */
.joy-cross::before, .joy-cross::after {
content: ''; position: absolute; background: var(--line);
}
.joy-cross::before { left: 50%; top: 8%; bottom: 8%; width: 1px; transform: translateX(-50%); }
.joy-cross::after { top: 50%; left: 8%; right: 8%; height: 1px; transform: translateY(-50%); }
.joy-knob {
position: absolute; left: 50%; top: 50%;
width: 52px; height: 52px; margin: -26px 0 0 -26px;
border-radius: 50%;
background: var(--accent);
border: 2px solid #7cc0f0;
box-shadow: 0 2px 10px rgba(0,0,0,.45);
transition: background .12s;
}
.joy.active .joy-knob { background: var(--ok); border-color: #7fe0c2; }
.joy.estop .joy-knob { background: var(--bad); border-color: #f08a82; }
.hint-sm { color: var(--dim); font-size: 11px; text-align: center; margin-top: 6px; }
.speed-row {
display: flex; align-items: center; gap: 6px;
margin-top: 5px;
}
.speed-row .slabel { flex: 1; color: var(--dim); }
.speed-row .sval {
min-width: 42px; text-align: right;
font-variant-numeric: tabular-nums;
}
.sbtn {
flex: none; width: 26px; height: 24px; padding: 0;
font-size: 15px; line-height: 1;
}
/* ============ Khung chia doi ============ */
/* Trai = THE GIOI (tuong duong Gazebo), phai = SLAM (tuong duong RViz).
Hai canvas tuyet doi chong len .canvas-wrap; JS dat chieu rong. */
/* ⚠️ An bang CSS, KHONG bang style="display:none" tren the.
Style inline thang stylesheet, nen quy tac .split ben duoi se khong bao gio
ap duoc va khung phai ĐEN XI -- da mac loi do mot lan. */
/* ⚠️ An/hien HOAN TOAN bang class tren `.canvas-wrap`, KHONG bao gio bang
style="display:none" tren the.
Style inline thang stylesheet, nen quy tac .split se khong ap duoc va khung
phai ĐEN XI -- da mac loi do mot lan voi #mainR.
Bon to hop:
(khong gi) : #main -- 2D mot khung
.three : #main3d -- 3D mot khung
.split : #main | #mainR -- 2D | 2D
.split.three : #main3d | #mainR -- 3D (Gazebo) | 2D SLAM (RViz) */
#mainR, #main3d { display: none; }
.canvas-wrap.three #main { display: none; }
.canvas-wrap.three #main3d { display: block; }
.canvas-wrap.split #main,
.canvas-wrap.split #main3d { width: 50%; }
.canvas-wrap.split #mainR { display: block; position: absolute;
right: 0; top: 0; width: 50%; height: 100%;
border-left: 1px solid #2a3442; }
.pane-label {
position: absolute; top: 6px;
font: 11px/1.4 ui-monospace, monospace;
color: #8fa3bf; background: rgba(18,21,26,.82);
padding: 2px 7px; border-radius: 3px; pointer-events: none;
}
#labL { left: 8px; }
#labR { left: 50%; margin-left: 8px; }

File diff suppressed because one or more lines are too long