"""Object-op realisation (move / add / replace / remove) for CounterGround3D edits. A clean re-implementation of the original research executor. Same maths, same order of operations, so outputs are bit-identical (see tools/parity_test.py). Everything happens in the scene's RAW ScanNet frame. Donor geometry and hand-labelled placements are expressed in the canonical axis-ALIGNED frame and mapped into the target raw frame with the inverse axis-alignment matrix. Record tables (one directory; see RecordTables): all_edits.jsonl one structured edit per uid (scene_id, edit.op, ground_target/ground_anchor, ...) manual_edits.jsonl hand-labelled realisation per uid (status ok|discarded; targets / placements / delete_insts). When present it takes precedence over the automatic path. move_destinations.jsonl automatic move destinations (legacy path, uid not in manual_edits) replace_add_destinations.jsonl automatic add/replace slots (legacy path) donor_bank.json class -> donor instances (legacy path) Normals are not used by the original executor. Here they are carried along consistently: kept for untouched points, rotated with moved/inserted points, and dropped with removed points. """ import json import os import numpy as np from .scannet200 import CLASS_LABELS_200 OUT_THRESH = 0.20 # legacy path: reject a donor whose footprint is >20% out of the room CELL = 0.10 # legacy path: occupancy grid cell (m) # ------------------------------------------------------------------ record tables class RecordTables: def __init__(self, record_dir): self.dir = str(record_dir) rd = self.dir self.all = {r["uid"]: r for r in _jsonl(f"{rd}/all_edits.jsonl")} self.move = {r["uid"]: r for r in _jsonl(f"{rd}/move_destinations.jsonl") if r["status"] == "ok"} \ if os.path.exists(f"{rd}/move_destinations.jsonl") else {} self.ra = {r["uid"]: r for r in _jsonl(f"{rd}/replace_add_destinations.jsonl") if r["status"] == "ok"} \ if os.path.exists(f"{rd}/replace_add_destinations.jsonl") else {} mp = f"{rd}/manual_edits.jsonl" self.manual = {int(r["uid"]): r for r in _jsonl(mp)} if os.path.exists(mp) else {} self._bank = None def bank(self): if self._bank is None: p = f"{self.dir}/donor_bank.json" self._bank = json.load(open(p)) if os.path.exists(p) else {} return self._bank def donors_of(self, uid): """Donor scene ids an object-op uid needs (manual placements; [] for legacy/remove/move).""" m = self.manual.get(int(uid)) if not m: return [] return [p["donor"]["scene_id"] for p in m.get("placements", [])] def _jsonl(path): with open(path) as f: return [json.loads(l) for l in f if l.strip()] # ------------------------------------------------------------------ small helpers def _rotz(deg): a = np.radians(deg) c, s = np.cos(a), np.sin(a) return np.array([[c, -s, 0.], [s, c, 0.], [0., 0., 1.]]) def _contiguous(sp): _, inv = np.unique(sp, return_inverse=True) return inv.astype(np.int64) def _norm(s): return str(s).lower().strip().rstrip("s") def _apply_lin(normal, A): """Rotate normals by the 3x3 linear map A (rows are points).""" return None if normal is None else normal @ np.asarray(A, float).T def _take(raw, keep): out = dict(raw) for k in ("coord", "color", "instance", "segment"): out[k] = raw[k][keep] out["normal"] = None if raw.get("normal") is None else raw["normal"][keep] return out def _hull(xy): """Convex hull vertices (counter-clockwise), Andrew's monotone chain; collinear points dropped.""" P = np.unique(np.asarray(xy, float), axis=0) if len(P) < 3: return P def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) lower, upper = [], [] for p in P: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: lower.pop() lower.append(p) for p in P[::-1]: while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: upper.pop() upper.append(p) return np.array(lower[:-1] + upper[:-1]) def _minrect_angle(xy): """Orientation (radians) of the LONG edge of the 2-D minimum-area bounding rectangle (rotating calipers).""" xy = np.asarray(xy, float) if len(xy) < 3: raise ValueError("too few points") P = _hull(xy) if len(P) < 3: raise ValueError("degenerate hull") best = None n = len(P) for i in range(n): e = P[(i + 1) % n] - P[i] a = np.arctan2(e[1], e[0]) c, s = np.cos(-a), np.sin(-a) q = P @ np.array([[c, -s], [s, c]]).T dx, dy = np.ptp(q[:, 0]), np.ptp(q[:, 1]) area = dx * dy if best is None or area < best[0]: best = (area, a if dx >= dy else a + np.pi / 2.0) return best[1] # ------------------------------------------------------------------ primitive ops def op_remove(raw, target_inst): keep = raw["instance"] != target_inst out = _take(raw, keep) out["superpoint"] = _contiguous(raw["superpoint"][keep]) return out def _aligned_of(raw, store): M = store.axis(raw["_scene_id"]) al = (np.c_[raw["coord"], np.ones(len(raw["coord"]))] @ M.T)[:, :3] return al, M def _to_raw(al, M): return (np.c_[al, np.ones(len(al))] @ np.linalg.inv(M).T)[:, :3] def op_move_manual(raw, targets, store): """Move each labelled target: pivot = the instance's ALIGNED bbox centre, exact yaw about z, translate to dest_xyz_aligned, map back to raw.""" al, M = _aligned_of(raw, store) coord = raw["coord"].copy() normal = None if raw.get("normal") is None else raw["normal"].copy() Minv = np.linalg.inv(M) for t in targets: m = raw["instance"] == int(t["inst"]) if not m.any(): continue pts = al[m]; ctr = (pts.min(0) + pts.max(0)) / 2 R = _rotz(float(t.get("yaw_deg", 0.0))) placed = (R @ (pts - ctr).T).T + np.asarray(t["dest_xyz_aligned"], float) coord[m] = _to_raw(placed, M) if normal is not None: normal[m] = _apply_lin(normal[m], Minv[:3, :3] @ R @ M[:3, :3]) out = dict(raw); out["coord"] = coord; out["normal"] = normal return out def load_donor_aligned(donor, store): """Donor points/colour/semantics/normals in the donor's ALIGNED frame + its aligned bbox centre.""" d = store.load(donor["scene_id"]) m = d["instance"] == donor["obj_id"] M = store.axis(donor["scene_id"]) coord = d["coord"][m] al = (np.c_[coord, np.ones(len(coord))] @ M.T)[:, :3] bc = (al.min(0) + al.max(0)) / 2 nrm = None if d["normal"] is None else _apply_lin(d["normal"][m], M[:3, :3]) return al, d["color"][m], bc, d["segment"][m], nrm def _donor_superpoints(local_xyz, start): """Coarse spatial clusters (0.3 m voxels) -> fresh contiguous superpoint ids from `start`.""" g = np.floor(local_xyz / 0.30).astype(np.int64) _, inv = np.unique(g, axis=0, return_inverse=True) return start + inv.reshape(-1) def _append(raw, placed_raw, color, dseg, new_inst, sp_new, normal_new): out = dict(raw) out["coord"] = np.vstack([raw["coord"], placed_raw]) out["color"] = np.vstack([raw["color"], color]) out["instance"] = np.concatenate([raw["instance"], np.full(len(placed_raw), new_inst)]) out["segment"] = np.concatenate([raw["segment"], dseg.astype(raw["segment"].dtype)]) out["superpoint"] = np.concatenate([raw["superpoint"], sp_new]) if raw.get("normal") is not None: nn = normal_new if normal_new is not None else np.zeros((len(placed_raw), 3)) out["normal"] = np.vstack([raw["normal"], nn]) return out def _insert_donor_manual(raw, donor, dest_aligned, yaw_deg, store, inst_id=None): """Append one donor exactly as labelled: centred at its aligned bbox centre, yawed, translated to dest (placed bbox centre, z included), mapped into the target raw frame.""" al, color, bc, dseg, dn = load_donor_aligned(donor, store) R = _rotz(float(yaw_deg)) oriented = (R @ (al - bc).T).T placed_aligned = oriented + np.asarray(dest_aligned, float) M = store.axis(raw["_scene_id"]) placed_raw = _to_raw(placed_aligned, M) new_inst = (int(raw["instance"].max()) + 1) if inst_id is None else int(inst_id) sp_start = int(raw["superpoint"].max()) + 1 nrm = None if dn is None else _apply_lin(dn, np.linalg.inv(M)[:3, :3] @ R) out = _append(raw, placed_raw, color, dseg, new_inst, _donor_superpoints(oriented, sp_start), nrm) out["_inserted_inst"] = new_inst return out def op_add_manual(raw, placements, store): out = raw for p in placements: out = _insert_donor_manual(out, p["donor"], p["dest_xyz_aligned"], p.get("yaw_deg", 0.0), store) return out def op_replace_manual(raw, delete_insts, placements, store): """Delete every labelled original, then insert every placement; the first placement reuses the first deleted instance id, further placements get fresh ids.""" out = raw for inst in delete_insts: out = op_remove(out, int(inst)) for k, p in enumerate(placements): iid = int(delete_insts[0]) if (k == 0 and delete_insts) else None out = _insert_donor_manual(out, p["donor"], p["dest_xyz_aligned"], p.get("yaw_deg", 0.0), store, inst_id=iid) return out # ------------------------------------------------------------------ legacy (pre-label) automatic path def _resolve(g): if g["status"] == "GROUNDED" and isinstance(g["result"], int): return g["result"] if g["status"] == "AMBIGUOUS" and isinstance(g["result"], list) and g["result"]: return g["result"][0] return None def _snap90(deg): return round(float(deg) / 90.0) * 90.0 def _move_inst(coord, normal, mask, dest_raw, yaw_deg): pts = coord[mask] center = (pts.min(0) + pts.max(0)) / 2 coord = coord.copy() R = _rotz(yaw_deg) newpts = (R @ (pts - center).T).T + np.asarray(dest_raw) zmin = float(newpts[:, 2].min()) if zmin < 0.0: newpts[:, 2] -= zmin coord[mask] = newpts if normal is not None: normal = normal.copy(); normal[mask] = _apply_lin(normal[mask], R) return coord, normal def op_move(raw, rec, target_inst, anchor_inst=None): coord, normal = raw["coord"], raw.get("normal") m = raw["instance"] == target_inst if m.sum(): coord, normal = _move_inst(coord, normal, m, rec["dest_xyz_raw"], _snap90(rec.get("yaw_deg", 0.0))) if rec.get("dest_type") == "swap" and anchor_inst is not None and "anchor_dest_xyz_raw" in rec: ma = raw["instance"] == anchor_inst if ma.sum(): coord, normal = _move_inst(coord, normal, ma, rec["anchor_dest_xyz_raw"], _snap90(rec.get("anchor_yaw_deg", 0.0))) out = dict(raw); out["coord"] = coord; out["normal"] = normal return out def scene_geometry(scan, store): """Aligned points + per-instance geometry + room box (the legacy placement engine's scene view).""" d = store.load(scan) M = store.axis(scan) pts = (np.c_[d["coord"], np.ones(len(d["coord"]))] @ M.T)[:, :3] seg, inst = d["segment"], d["instance"] instances = {} for iid in np.unique(inst): if int(iid) == -1: continue mask = inst == iid s = seg[mask]; s = s[s >= 0] if len(s) == 0: continue P = pts[mask] bmin, bmax = P.min(0), P.max(0) instances[int(iid)] = {"label": CLASS_LABELS_200[int(np.bincount(s).argmax())], "com": P.mean(0), "bbox_center": (bmin + bmax) / 2.0, "extent": bmax - bmin, "n": int(mask.sum()), "mask": mask} mn, mx = pts.min(0), pts.max(0) return {"source": "scannet", "points": pts, "instances": instances, "room_center": (mn + mx) / 2.0, "room_extent": mx - mn} def _close(m, it=3): p = np.pad(m, it) for _ in range(it): p = p | np.roll(p, 1, 0) | np.roll(p, -1, 0) | np.roll(p, 1, 1) | np.roll(p, -1, 1) for _ in range(it): p = p & np.roll(p, 1, 0) & np.roll(p, -1, 0) & np.roll(p, 1, 1) & np.roll(p, -1, 1) return p[it:-it, it:-it] def build_occupancy(scene): P = scene["points"] inst = scene["instances"] floor_ids = [i for i, o in inst.items() if _norm(o["label"]) == "floor"] floor_pts = np.vstack([P[inst[i]["mask"]] for i in floor_ids]) if floor_ids else np.empty((0, 3)) if len(floor_pts) < 50: zmin = P[:, 2].min() floor_pts = P[P[:, 2] <= zmin + 0.2] mn = P[:, :2].min(0) mx = P[:, :2].max(0) W = int(np.ceil((mx[0] - mn[0]) / CELL)) + 1 H = int(np.ceil((mx[1] - mn[1]) / CELL)) + 1 fc = np.clip(np.floor((floor_pts[:, :2] - mn) / CELL).astype(int), 0, [W - 1, H - 1]) floor_mask = np.zeros((W, H), bool) floor_mask[fc[:, 0], fc[:, 1]] = True return dict(mn=mn, W=W, H=H, room_mask=_close(floor_mask, it=3)) def footprint_out_frac(xy, occ): xy = np.asarray(xy, float) if len(xy) == 0: return 0.0 mn, W, H = occ["mn"], occ["W"], occ["H"] c = np.floor((xy - mn) / CELL).astype(int) inside = (c[:, 0] >= 0) & (c[:, 0] < W) & (c[:, 1] >= 0) & (c[:, 1] < H) out = int((~inside).sum()) if inside.any(): ci = c[inside] out += int((~occ["room_mask"][ci[:, 0], ci[:, 1]]).sum()) return out / len(xy) def donor_pool(tables, matched_class, dataset, uid, target_extent=None, same_scene=None): cands = [c for c in tables.bank().get(_norm(matched_class), []) if c["source"] == dataset] if not cands: return [] ss = [c for c in cands if c["scene_id"] == same_scene] pool = ss if ss else cands if target_extent is not None: pool = sorted(pool, key=lambda c: float(np.abs(np.array(c["extent"]) - target_extent).sum()))[:10] else: pool = sorted(pool, key=lambda c: -c["n_points"])[:10] k = uid % len(pool) return pool[k:] + pool[:k] def _insert_donor(raw, donor, ref_dir, dest_aligned, store, target_z_bottom=None, occ=None, inst_id=None): al, color, bc, dseg, dn = load_donor_aligned(donor, store) centered = al - bc ref = np.asarray(ref_dir, float) pref = np.arctan2(ref[1], ref[0]) if (abs(ref[0]) > 1e-9 or abs(ref[1]) > 1e-9) else 0.0 yaw = None try: theta = _minrect_angle(centered[:, :2]) yaw = np.degrees(np.round(pref / (np.pi / 2.0)) * (np.pi / 2.0) - theta) except Exception: yaw = None if yaw is None: yaw = 0.0 facing = donor.get("facing") if facing is not None: f = np.asarray(facing, float) if np.linalg.norm(f) > 1e-6 and np.linalg.norm(ref) > 1e-6: yaw = np.degrees(np.arctan2(ref[1], ref[0]) - np.arctan2(f[1], f[0])) R = _rotz(yaw) oriented = (R @ centered.T).T dest = np.asarray(dest_aligned, float).copy() h = oriented[:, 2].max() - oriented[:, 2].min() dest[2] = (target_z_bottom + h / 2) if target_z_bottom is not None else dest[2] placed_aligned = oriented + dest Minv = np.linalg.inv(store.axis(raw["_scene_id"])) placed_raw = (np.c_[placed_aligned, np.ones(len(placed_aligned))] @ Minv.T)[:, :3] new_inst = (int(raw["instance"].max()) + 1) if inst_id is None else int(inst_id) sp_start = int(raw["superpoint"].max()) + 1 nrm = None if dn is None else _apply_lin(dn, Minv[:3, :3] @ R) out = _append(raw, placed_raw, color, dseg, new_inst, _donor_superpoints(oriented, sp_start), nrm) out["_inserted_inst"] = new_inst if occ is not None: out["_frac_out"] = footprint_out_frac(placed_aligned[:, :2], occ) return out def op_replace(raw, rec, scene, target_inst, uid, tables, store, occ=None): t = scene["instances"][target_inst] z_bottom = float(t["bbox_center"][2] - t["extent"][2] / 2) base = footprint_out_frac(scene["points"][t["mask"]][:, :2], occ) if occ is not None else 0.0 pool = donor_pool(tables, rec["matched_class"], "scannet", uid, target_extent=np.asarray(t["extent"]), same_scene=raw["_scene_id"]) raw = op_remove(raw, target_inst) if not pool: return raw best = None for donor in pool: out = _insert_donor(raw, donor, np.asarray(rec["slot_facing"]), rec["dest_xyz_aligned"], store, z_bottom, occ=occ, inst_id=target_inst) fo = out.get("_frac_out", 0.0) if fo <= base + OUT_THRESH: return out if best is None or fo < best["_frac_out"]: best = out return best if best is not None else raw def op_add(raw, rec, uid, tables, store, occ=None): ph = np.asarray(rec["placeholder_extent"]) pool = donor_pool(tables, rec["matched_class"], "scannet", uid, target_extent=ph, same_scene=raw["_scene_id"]) if not pool: return raw z_bottom = float(rec["dest_xyz_aligned"][2] - ph[2] / 2) best = None for donor in pool: out = _insert_donor(raw, donor, np.asarray(rec["face_dir"]), rec["dest_xyz_aligned"], store, z_bottom, occ=occ) fo = out.get("_frac_out", 0.0) if fo <= OUT_THRESH: return out if best is None or fo < best["_frac_out"]: best = out return best if best is not None else raw # ------------------------------------------------------------------ orchestration def edited_cloud(uid, tables, store): """Realise move/add/replace `uid` on its scene (loaded fresh from the store, RAW frame). Returns the edited arrays dict or None when the edit is not executable (discarded / unresolved).""" e = tables.all[uid] op = e["edit"]["op"] sid = e["scene_id"] if not sid.startswith("scene"): return None m = tables.manual.get(int(uid)) if tables.manual else None if m is not None: if m.get("status") != "ok": return None raw = store.load(sid) if m["op"] == "move": return op_move_manual(raw, m["targets"], store) if m["op"] == "add": return op_add_manual(raw, m["placements"], store) if m["op"] == "replace": return op_replace_manual(raw, m.get("delete_insts") or [], m["placements"], store) return None raw = store.load(sid) if op == "remove": tid = _resolve(e["ground_target"]) return op_remove(raw, tid) if tid is not None else None if op == "move": if uid not in tables.move: return None return op_move(raw, tables.move[uid], _resolve(e["ground_target"]), _resolve(e["ground_anchor"])) if op in ("replace", "add"): if uid not in tables.ra: return None scene = scene_geometry(sid, store) occ = build_occupancy(scene) if op == "replace": return op_replace(raw, tables.ra[uid], scene, _resolve(e["ground_target"]), uid, tables, store, occ) return op_add(raw, tables.ra[uid], uid, tables, store, occ) return None