This commit is contained in:
trung09122002
2026-09-25 14:07:58 +07:00
parent 0093df0508
commit fe8b147c6a
21 changed files with 13992 additions and 9 deletions

Binary file not shown.

275
tools/cut_world.py Normal file
View File

@@ -0,0 +1,275 @@
#!/usr/bin/env python3
"""Cat mot world Gazebo theo truc y: giu phan y < --y-max, bo han phan con lai.
Dung de co mot ban do VUA -- lon hon nha hang (12x10 m), nho hon ca benh vien
(25x51 m) -- quet tron duoc trong 10-15 phut.
Ba buoc:
1. LOC MODEL: giu khoi `<model name="...">` co pose y < y-max - margin.
Bo doc world (libs/vslam_sim/src/gazebo_world.cc) tach khoi tu
`<model name="` den `</model>` GAN NHAT, lay `<uri>` va `<pose>` DAU TIEN
-- script nay loc dung theo cach tach do.
2. CAT MESH (--clip): tuong va san cua benh vien la MOT mesh .dae cho ca toa
nha. Khong sua .dae (de hong) -- lay CHINH tam giac ma bo doc world tao ra
(`vslam_world_export --meshes`), cat o y = y-max (tam giac vat qua duong
cat bi cat doi chinh xac, nen tuong doc chay suot toa nha van con phan
phia nam), ghi thanh model .obj moi va thay vao world.
3. TUONG CHAN: duong cat di qua loi hanh lang, nen chen
resources/models/vslam_tuong_cat o y = y-max de bit lai.
Tai tao resources/worlds/hospital_nam.world (chay tu goc repo):
GAZEBO_MODEL_PATH=$PWD/resources/models ./build/tools/vslam_world_export \\
--world ../vSLAM_ws/src/robot_sim/worlds/hospital.world --meshes /tmp/c.bin
GAZEBO_MODEL_PATH=$PWD/resources/models ./build/tools/vslam_world_export \\
--world ../vSLAM_ws/src/robot_sim/worlds/hospital.world --meshes /tmp/v.bin \\
--meshes-visual
python3 tools/cut_world.py \\
--in ../vSLAM_ws/src/robot_sim/worlds/hospital.world \\
--out resources/worlds/hospital_nam.world --y-max -10.12 \\
--meshes-bin /tmp/c.bin --meshes-visual-bin /tmp/v.bin \\
--clip aws_robomaker_hospital_floor_01_walls=vslam_hospital_nam_walls \\
--clip aws_robomaker_hospital_floor_01_floor=vslam_hospital_nam_floor \\
--colors resources/model_colors.json
Chay node voi GAZEBO_MODEL_PATH=$PWD/resources/models de tim thay cac model moi.
y = -10.12 chon tu ban do raster hoa (vslam_world_export): duong ngang o do chi
cat 7.7 m san trong (cac loi hanh lang), con lai trung tuong co san.
⚠️ Chay lai tools/gen_model_colors.py se ghi de model_colors.json va mat mau
cua model moi -- chay lai script nay sau do.
"""
import argparse
import json
import math
import os
import re
import struct
import sys
WALL_BLOCK = """ <model name="vslam_tuong_cat_1">
<include>
<uri>model://vslam_tuong_cat</uri>
<static>true</static>
<pose>{x} {y} 0 0 0 0</pose>
</include>
</model>
"""
CLIP_BLOCK = """ <model name="{name}_1">
<include>
<uri>model://{name}</uri>
<static>true</static>
<pose>0 0 0 0 0 0</pose>
</include>
</model>
"""
MODEL_CONFIG = """<?xml version="1.0" ?>
<model>
<name>{name}</name>
<version>1.0</version>
<sdf version="1.6">model.sdf</sdf>
<author>
<name>vslam_cpp</name>
<email></email>
</author>
<description>
{src} cat o y &lt;= {y_max}, toa do THE GIOI (dat model o goc).
Sinh boi tools/cut_world.py -- dung sua tay.
</description>
</model>
"""
MODEL_SDF = """<?xml version="1.0" ?>
<sdf version="1.6">
<model name="{name}">
<link name="link">
<visual name="visual">
<geometry>
<mesh>
<uri>model://{name}/meshes/visual.obj</uri>
</mesh>
</geometry>
</visual>
<collision name="collision">
<geometry>
<mesh>
<uri>model://{name}/meshes/collision.obj</uri>
</mesh>
</geometry>
</collision>
</link>
<static>1</static>
</model>
</sdf>
"""
def read_meshes(path):
"""Doc khoi "VSLW" cua EncodeWorldMeshes (gazebo_world.h).
Tra ve (geoms, instances): geoms[i] = (ten, [9 float moi tam giac] trong he
MODEL), instances = [(geom, x, y, z, yaw)].
"""
b = open(path, "rb").read()
if b[:4] != b"VSLW":
sys.exit(f"{path}: khong phai khoi VSLW")
_, ng, ni = struct.unpack_from("<III", b, 4)
o = 16
geoms = []
for _ in range(ng):
(n,) = struct.unpack_from("<I", b, o)
o += 4
name = b[o:o + n].decode()
o += n + 3 # bo qua r,g,b
(nt,) = struct.unpack_from("<I", b, o)
o += 4
geoms.append((name, struct.unpack_from(f"<{nt * 9}f", b, o)))
o += nt * 9 * 4
insts = []
for _ in range(ni):
insts.append(struct.unpack_from("<Iffff", b, o))
o += 20
return geoms, insts
def clip_poly(poly, y_max):
"""Sutherland-Hodgman voi mot nua mat phang y <= y_max. Giu thu tu dinh."""
out = []
for i, cur in enumerate(poly):
prev = poly[i - 1]
cin, pin = cur[1] <= y_max, prev[1] <= y_max
if cin != pin:
t = (y_max - prev[1]) / (cur[1] - prev[1])
out.append(tuple(p + t * (c - p) for p, c in zip(prev, cur)))
if cin:
out.append(cur)
return out
def world_triangles(geoms, insts, model_name, y_max):
"""Moi the hien cua `model_name` -> tam giac TOA DO THE GIOI, da cat."""
idx = [i for i, g in enumerate(geoms) if g[0] == model_name]
if not idx:
sys.exit(f"khong co mesh '{model_name}' trong file .bin")
tris = []
for g, x, y, z, yaw in insts:
if g not in idx:
continue
c, s = math.cos(yaw), math.sin(yaw)
t = geoms[g][1]
for k in range(0, len(t), 9):
poly = [(c * t[k + 3 * j] - s * t[k + 3 * j + 1] + x,
s * t[k + 3 * j] + c * t[k + 3 * j + 1] + y,
t[k + 3 * j + 2] + z) for j in range(3)]
poly = clip_poly(poly, y_max)
for j in range(2, len(poly)): # quat tam giac
tris.append((poly[0], poly[j - 1], poly[j]))
return tris
def write_obj(path, tris, header):
with open(path, "w") as f:
f.write(f"# {header}\n# Z-UP, don vi MET, toa do THE GIOI. Sinh boi tools/cut_world.py.\n")
for tri in tris:
for p in tri:
f.write(f"v {p[0]:.4f} {p[1]:.4f} {p[2]:.4f}\n")
for i in range(len(tris)):
f.write(f"f {3 * i + 1} {3 * i + 2} {3 * i + 3}\n")
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--in", dest="src", required=True, help="world goc")
ap.add_argument("--out", required=True, help="world da cat")
ap.add_argument("--y-max", type=float, required=True,
help="giu phan y < y-max; tuong chan dat o y-max")
ap.add_argument("--margin", type=float, default=0.3,
help="model co pose trong khoang nay quanh duong cat bi bo (m)")
ap.add_argument("--keep", action="append", default=[],
help="uri chua chuoi nay thi LUON giu nguyen (khong cat)")
ap.add_argument("--clip", action="append", default=[],
help="MODEL=MOI: cat mesh MODEL, ghi thanh model MOI, thay vao world")
ap.add_argument("--meshes-bin", help="vslam_world_export --meshes (va cham)")
ap.add_argument("--meshes-visual-bin", help="vslam_world_export --meshes --meshes-visual")
ap.add_argument("--models-dir", default="resources/models",
help="noi ghi model moi")
ap.add_argument("--colors", help="model_colors.json: chep mau MODEL sang MOI")
ap.add_argument("--wall-x", type=float, default=0.0,
help="tam x cua tuong chan (mesh rong 27.4 m quanh tam)")
a = ap.parse_args()
clips = dict(c.split("=", 1) for c in a.clip)
if clips and not (a.meshes_bin and a.meshes_visual_bin):
sys.exit("--clip can ca --meshes-bin lan --meshes-visual-bin")
# --- 2. Cat mesh, ghi model moi ---
if clips:
col = read_meshes(a.meshes_bin)
vis = read_meshes(a.meshes_visual_bin)
for src_name, new_name in clips.items():
d = os.path.join(a.models_dir, new_name)
os.makedirs(os.path.join(d, "meshes"), exist_ok=True)
for kind, data in (("collision", col), ("visual", vis)):
tris = world_triangles(*data, src_name, a.y_max)
write_obj(os.path.join(d, "meshes", kind + ".obj"), tris,
f"{src_name} ({kind}) cat o y <= {a.y_max}: {len(tris)} tam giac")
print(f"{new_name}/{kind}.obj: {len(tris)} tam giac")
with open(os.path.join(d, "model.config"), "w") as f:
f.write(MODEL_CONFIG.format(name=new_name, src=src_name, y_max=a.y_max))
with open(os.path.join(d, "model.sdf"), "w") as f:
f.write(MODEL_SDF.format(name=new_name))
if a.colors:
colors = json.load(open(a.colors))
for src_name, new_name in clips.items():
if src_name in colors:
colors[new_name] = colors[src_name]
with open(a.colors, "w") as f:
json.dump(colors, f, indent=0, sort_keys=True)
f.write("\n") # giu dung dinh dang gen_model_colors.py ghi ra
# --- 1 + 3. Loc model, thay model da cat, chen tuong chan ---
src = open(a.src).read()
if src.count("</world>") != 1:
sys.exit("world phai co dung mot </world>")
kept, dropped, replaced = [], [], []
def filt(m):
body = m.group(2)
uri = re.search(r"<uri>([^<]+)</uri>", body)
pose = re.search(r"<pose>([^<]+)</pose>", body)
# Khong co uri: bo doc world cung bo qua, de nguyen cho Gazebo that.
if uri is None:
kept.append(m.group(1))
return m.group(0)
model = uri.group(1).split("://", 1)[-1].split("/", 1)[0]
if model in clips:
replaced.append(m.group(1))
return CLIP_BLOCK.format(name=clips[model])
if any(k in uri.group(1) for k in a.keep):
kept.append(m.group(1))
return m.group(0)
y = float(pose.group(1).split()[1]) if pose else 0.0
if y < a.y_max - a.margin:
kept.append(m.group(1))
return m.group(0)
dropped.append(m.group(1))
return ""
# Non-greedy toi </model> GAN NHAT -- dung cach gazebo_world.cc tach khoi.
out = re.sub(r'[ \t]*<model name="([^"]+)">(.*?)</model>[ \t]*\n?', filt, src,
flags=re.S)
out = re.sub(r"[ \t]*</world>",
lambda _: WALL_BLOCK.format(x=a.wall_x, y=a.y_max) + " </world>",
out, count=1)
with open(a.out, "w") as f:
f.write(out)
print(f"giu {len(kept)}, thay {len(replaced)} (da cat mesh), bo {len(dropped)} model; "
f"tuong chan o y = {a.y_max}")
print(f"-> {a.out}")
if __name__ == "__main__":
main()

View File

@@ -175,6 +175,16 @@ double AteAligned(const std::vector<vslam::Pose2D>& est,
return std::sqrt(sum / static_cast<double>(n));
}
// Sai so LON NHAT, khong can chinh. Troi tich luy hien o day ro hon RMSE: phan
// lon quy dao tot keo RMSE xuong trong khi mot doan cuoi lech 0.25 m.
double MaxErr(const std::vector<vslam::Pose2D>& a,
const std::vector<vslam::Pose2D>& b) {
double m = 0.0;
const size_t n = std::min(a.size(), b.size());
for (size_t i = 0; i < n; ++i) m = std::max(m, vslam::Distance2D(a[i], b[i]));
return m;
}
} // namespace
int main(int argc, char** argv) {
@@ -189,6 +199,13 @@ int main(int argc, char** argv) {
bool trace = false;
bool with_images = false;
std::string ref_db;
// Moc so: "opt" = pose toi uu trong DB (nhu cu); "odom" = pose odom cua
// node. Trong MO PHONG odom ~ ground truth, nen "odom" do sai so do CHINH
// SLAM gay ra.
std::string ref_kind = "opt";
// Sigma odom moi lien ket gui RTAB-Map (m, rad). <0 = mac dinh SlamInput
// (0.1 m / 0.1 rad) -- dung cai runtime dang gui.
double odom_sigma_lin = -1.0, odom_sigma_ang = -1.0;
std::map<std::string, std::string> extra;
for (int i = 1; i < argc; ++i) {
@@ -204,6 +221,13 @@ int main(int argc, char** argv) {
else if (a == "--trace") trace = true;
else if (a == "--with-images") with_images = true;
else if (a == "--ref-db") ref_db = next();
else if (a == "--ref") ref_kind = next();
else if (a == "--odom-sigma") { // "LIN_M,ANG_RAD"
const std::string v = next();
const size_t c = v.find(',');
odom_sigma_lin = std::atof(v.substr(0, c).c_str());
if (c != std::string::npos) odom_sigma_ang = std::atof(v.substr(c + 1).c_str());
}
else if (a == "--param") {
// --param Key/Name=value. Di thang vao khoi overrides, tuc la CUNG
// duong ma slam.yaml di -- ke ca phep kiem ten key.
@@ -220,7 +244,8 @@ int main(int argc, char** argv) {
} else if (a == "--help") {
std::printf(
"cach dung: %s --db X.db [--localize] [--kidnap M,DEG]\n"
" [--limit N] [--optimizer 0|1|2|3] [--export-map out.pgm]\n",
" [--limit N] [--optimizer 0|1|2|3] [--export-map out.pgm]\n"
" [--ref opt|odom] [--odom-sigma LIN_M,ANG_RAD]\n",
argv[0]);
return 0;
}
@@ -451,6 +476,26 @@ int main(int argc, char** argv) {
const vslam::Pose2D kidnap_offset; // odom khong bi dong toi
// Moc cua PHIEN GOC: pose toi uu ma lan chay that luu trong DB, so voi odom.
// Lan chay lai phai so voi con so nay chu khong phai voi 0.
if (ref_kind == "odom") {
std::vector<vslam::Pose2D> opt, odo;
for (const Frame& f : frames) {
if (!f.has_optimized) continue;
opt.push_back(f.optimized);
odo.push_back(f.odom);
}
std::printf("phien goc (pose toi uu trong DB vs odom): %zu node, RMSE %.4f m, "
"max %.4f m\n", opt.size(), Rmse(opt, odo), MaxErr(opt, odo));
}
std::printf("odom sigma gui RTAB-Map: %s\n",
odom_sigma_lin > 0.0
? (std::to_string(odom_sigma_lin) + " m, " +
std::to_string(odom_sigma_ang) + " rad").c_str()
: ("mac dinh slam.yaml (" + std::to_string(cfg.odom_sigma_m) + " m, " +
std::to_string(cfg.odom_sigma_rad) + " rad)").c_str());
std::fflush(stdout);
std::vector<vslam::Pose2D> est, ref;
est.reserve(frames.size());
ref.reserve(frames.size());
@@ -459,10 +504,14 @@ int main(int argc, char** argv) {
double converge_s = -1.0;
const double t_start = frames.front().stamp;
size_t i_frame = 0;
for (const Frame& f : frames) {
++i_frame;
vslam::SlamInput in;
in.stamp = vslam::UnixTime::fromSec(f.stamp);
in.odom = vslam::Pose2DCompose(kidnap_offset, f.odom);
if (odom_sigma_lin > 0.0) in.odom_linear_var = odom_sigma_lin * odom_sigma_lin;
if (odom_sigma_ang > 0.0) in.odom_angular_var = odom_sigma_ang * odom_sigma_ang;
in.scan = &f.scan;
if (f.has_image) {
in.depth = &f.depth_pod;
@@ -476,14 +525,21 @@ int main(int argc, char** argv) {
if (o.loop_closure_id > 0) loops++;
if (o.proximity_id > 0) prox++;
if (f.has_optimized) {
if (ref_kind == "odom") {
est.push_back(o.pose_map);
ref.push_back(f.odom);
} else if (f.has_optimized) {
est.push_back(o.pose_map);
ref.push_back(f.optimized);
}
if (trace && (processed % 20 == 0)) {
std::printf(" [%4d] ms %7.1f wm %4d loop %d prox %d\n", processed,
o.process_ms, o.nodes_wm, o.loop_closure_id, o.proximity_id);
std::printf(" [%4d] khung %zu/%zu ms %7.1f wm %4d loop %d prox %d\n",
processed, i_frame, frames.size(), o.process_ms, o.nodes_wm,
o.loop_closure_id, o.proximity_id);
// Qua `| tee` stdout bi dem theo khoi 4 kB: khong xa thi terminal im
// lang hang chuc phut va nguoi chay tuong da treo.
std::fflush(stdout);
}
if (localize && converge_s < 0.0 && o.localized && f.has_optimized &&
vslam::Distance2D(o.pose_map, f.optimized) < 0.30) {
@@ -498,10 +554,12 @@ int main(int argc, char** argv) {
std::printf(" vong dong / lan can: %d / %d\n", loops, prox);
std::printf(" process_ms : cuoi %.1f, max %.1f, p95 %.1f\n", s.last_ms,
s.max_ms, s.p95_ms);
std::printf(" cap so sanh : %zu (node co pose toi uu)\n", est.size());
std::printf(" cap so sanh : %zu (moc: %s)\n", est.size(),
ref_kind == "odom" ? "odom" : "node co pose toi uu");
const double ate_raw = Rmse(est, ref);
const double ate = AteAligned(est, ref);
std::printf(" ATE RMSE (tho) : %.4f m\n", ate_raw);
std::printf(" sai so lon nhat : %.4f m (tho)\n", MaxErr(est, ref));
std::printf(" ATE RMSE (can chinh): %.4f m <-- chi tieu < 0.10\n", ate);
if (converge_s >= 0.0) std::printf(" hoi tu sau : %.2f s\n", converge_s);
else if (localize) std::printf(" hoi tu sau : KHONG hoi tu\n");