Files
vslam_cpp/libs/vslam_common/src/transform_tree.cc
trung09122002 48bd5377dc upload
2026-09-18 18:14:42 +07:00

486 lines
15 KiB
C++

#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