#!/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 `` co pose y < y-max - margin. Bo doc world (libs/vslam_sim/src/gazebo_world.cc) tach khoi tu ` model://vslam_tuong_cat true {x} {y} 0 0 0 0 """ CLIP_BLOCK = """ model://{name} true 0 0 0 0 0 0 """ MODEL_CONFIG = """ {name} 1.0 model.sdf vslam_cpp {src} cat o y <= {y_max}, toa do THE GIOI (dat model o goc). Sinh boi tools/cut_world.py -- dung sua tay. """ MODEL_SDF = """ model://{name}/meshes/visual.obj model://{name}/meshes/collision.obj 1 """ 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(" 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("") != 1: sys.exit("world phai co dung mot ") kept, dropped, replaced = [], [], [] def filt(m): body = m.group(2) uri = re.search(r"([^<]+)", body) pose = re.search(r"([^<]+)", 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 GAN NHAT -- dung cach gazebo_world.cc tach khoi. out = re.sub(r'[ \t]*(.*?)[ \t]*\n?', filt, src, flags=re.S) out = re.sub(r"[ \t]*", lambda _: WALL_BLOCK.format(x=a.wall_x, y=a.y_max) + " ", 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()