"""CounterGround3D edit dispatcher: apply an `edit` spec to a ScanNet scene. Edit schemas (as stored in the CF json items): {"op": "recolor", "targets": [{"object_ids": [int, ...], "new_color": str}, ...], "answer_template": ...} {"op": "remove", "target_inst": int} {"op": "move" | "add" | "replace", "uid": int} -> realised from the record tables {"op": "flip"} -> global left/right mirror {"op": "composite", "ops": [...]} -> applied object-op -> recolor -> flip, whatever the order {"op": "clone_replace", "gt_id", "distractor_id", "modify"} (DEER-3D style, kept for completeness) Two entry points: * apply_edit(...) drop-in equivalent of the original research `cf_edit.apply_edit`: geometry/colour ops are realised on the raw arrays, and a flip is NOT applied but returned as the `lateral_flip` flag (the original pipeline mirrors raw x inside its point-cloud transform, before axis alignment). * realize(...) materialise the full edited scene (coord / color / normal / superpoint, plus instance / segment), with the flip applied in a chosen frame. Used to pre-build edited scenes. Flip frames "raw_x" x -> -x in the RAW ScanNet frame (what the original FRAME=none pipeline did). After axis alignment this is a mirror across a vertical plane whose normal is R*e_x (R = rotation part of the axis-align matrix), so the aligned room is generally NOT axis-aligned any more, and raw x becomes negative. Both are cheap tells that a scene was flipped. "aligned_x" mirror across the vertical plane x = c_x of the ALIGNED frame (c = aligned bbox centre), expressed back in the raw frame with the scene's own axis-align matrix. The aligned scene stays axis-aligned and in place, so no tell is left in either frame. Default for materialisation. Both are reflections across a vertical plane, so both swap left and right identically; they differ only by a rigid motion of the result. """ import numpy as np from . import executor as EX from .recolor import apply_color _ORDER = {"remove": 0, "move": 0, "add": 0, "replace": 0, "clone_replace": 0, "recolor": 1, "flip": 2} ORDER_PRESERVING = {"recolor", "flip", "move"} # ops that keep the number and order of points def edit_ops(edit): if not edit: return [] return list(edit["ops"]) if edit.get("op") == "composite" else [edit] def has_flip(edit): return any(o.get("op") == "flip" for o in edit_ops(edit)) def preserves_point_order(edit): return all(o["op"] in ORDER_PRESERVING for o in edit_ops(edit)) def scenes_needed(edit, scene_id, tables): """Every scene whose labelled geometry the edit reads (target + donors).""" out = {scene_id} for o in edit_ops(edit): if o["op"] in ("move", "add", "replace"): out.add(tables.all[int(o["uid"])]["scene_id"]) out.update(tables.donors_of(int(o["uid"]))) return out def canonical_edit(edit): """Scene-relevant part of an edit (drops answer templates / modes), ops in application order. Two items with equal canonical edits on the same scene produce identical scenes.""" def prim(o): o = {k: v for k, v in o.items() if k not in ("answer_template", "mode")} if o["op"] in ("move", "add", "replace"): o["uid"] = int(o["uid"]) return o return {"ops": [prim(o) for o in sorted(edit_ops(edit), key=lambda x: _ORDER[x["op"]])]} # ------------------------------------------------------------------ one primitive op on a state dict def _apply_one(e, scene_name, st, tables, store): op = e["op"] if op == "recolor": color = np.asarray(st["color"], float).copy() for t in e["targets"]: mask = np.isin(st["instance"], list(t["object_ids"])) if mask.any(): color[mask] = apply_color(color[mask], t["new_color"]) st = dict(st); st["color"] = color return st if op == "remove": keep = st["instance"] != e["target_inst"] out = EX._take(st, keep) out["superpoint"] = EX._contiguous(st["superpoint"][keep]) return out if op == "clone_replace": return _clone_replace(e, st) if op in ("move", "add", "replace"): if tables is None or store is None: raise ValueError(f"{op} needs RecordTables and a SceneStore") out = EX.edited_cloud(int(e["uid"]), tables, store) if out is None: raise RuntimeError(f"[cg3d] executor could not realize {op} uid={e['uid']}") res = dict(st) res["coord"] = np.asarray(out["coord"]) res["color"] = np.asarray(out["color"]) res["instance"] = np.asarray(out["instance"]) res["superpoint"] = np.asarray(out["superpoint"]).astype(np.int64) res["segment"] = np.asarray(out["segment"]) res["normal"] = out.get("normal") return res raise ValueError(f"[cg3d] unknown edit op: {op!r}") def _clone_replace(edit, st): coord = np.asarray(st["coord"], float).copy(); color = np.asarray(st["color"], float).copy() segment = np.asarray(st["segment"]).copy(); instance = np.asarray(st["instance"]).copy() sp = np.asarray(st["superpoint"]).astype(np.int64).copy() gt_id = int(edit["gt_id"]); od_id = int(edit["distractor_id"]); mod = edit.get("modify", {}) or {} gt_m = instance == gt_id; od_m = instance == od_id if not gt_m.any() or not od_m.any(): raise RuntimeError(f"[cg3d] clone_replace: missing gt/distractor ({gt_id}/{od_id})") gt_ctr = coord[gt_m].mean(0); od_ctr = coord[od_m].mean(0) clone_xyz = coord[gt_m] - gt_ctr R = np.eye(3) if mod.get("type") == "rotate": th = np.deg2rad(float(mod["theta"])); c, s = np.cos(th), np.sin(th) R = np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]], float) clone_xyz = clone_xyz @ R.T clone_xyz = clone_xyz + od_ctr clone_col = color[gt_m].copy() if mod.get("type") == "recolor": clone_col[:] = np.asarray(mod["rgb"], float) keep = ~od_m sp_keep = EX._contiguous(sp[keep]) clone_sp = EX._contiguous(sp[gt_m]) + int(sp_keep.max()) + 1 new_id = int(instance.max()) + 1 out = dict(st) out["coord"] = np.vstack([coord[keep], clone_xyz]) out["color"] = np.vstack([color[keep], clone_col]) out["segment"] = np.concatenate([segment[keep], segment[gt_m]]) out["instance"] = np.concatenate([instance[keep], np.full(len(clone_xyz), new_id, instance.dtype)]) out["superpoint"] = np.concatenate([sp_keep, clone_sp]).astype(np.int64) if st.get("normal") is not None: n = st["normal"] out["normal"] = np.vstack([n[keep], n[gt_m] @ R.T]) return out # ------------------------------------------------------------------ public API def apply_edit(edit, scene_name, coord, color, segment, instance, superpoint_mask, tables=None, store=None): """Drop-in for the original cf_edit.apply_edit. Returns (coord, color, segment, instance, superpoint_mask, lateral_flip); a flip only sets lateral_flip=True (realise it with flip_transform / realize).""" st = dict(coord=coord, color=color, segment=segment, instance=instance, superpoint=superpoint_mask, normal=None, _scene_id=scene_name) lateral_flip = False for e in sorted(edit_ops(edit), key=lambda x: _ORDER[x["op"]]): if e["op"] == "flip": lateral_flip = True continue st = _apply_one(e, scene_name, st, tables, store) return st["coord"], st["color"], st["segment"], st["instance"], st["superpoint"], lateral_flip def flip_transform(coord_raw, axis_align, frame="aligned_x"): """4x4 map T (raw -> raw) realising the left/right mirror of a raw-frame cloud. See module doc.""" if frame == "raw_x": return np.diag([-1.0, 1.0, 1.0, 1.0]) if frame != "aligned_x": raise ValueError(frame) M = np.asarray(axis_align, float).reshape(4, 4) al = (np.c_[coord_raw, np.ones(len(coord_raw))] @ M.T)[:, :3] cx = (al[:, 0].min() + al[:, 0].max()) / 2.0 S = np.eye(4); S[0, 0] = -1.0; S[0, 3] = 2.0 * cx return np.linalg.inv(M) @ S @ M def apply_T(T, coord, normal=None): c = (np.c_[coord, np.ones(len(coord))] @ T.T)[:, :3] n = None if normal is None else normal @ T[:3, :3].T return c, n def realize(edit, scene_id, store, tables=None, flip_frame="aligned_x"): """Materialise the edited scene. Returns (state, info): state has raw-frame coord / color / normal / superpoint / instance / segment; info = {flip: bool, T_flip: 4x4 or None, order_preserved: bool}. The scene keeps the original axis-align matrix: store.axis(scene_id) applied to state["coord"] gives the edited aligned scene.""" st = store.load(scene_id) flip = False for e in sorted(edit_ops(edit), key=lambda x: _ORDER[x["op"]]): if e["op"] == "flip": flip = True continue st = _apply_one(e, scene_id, st, tables, store) T = None if flip: T = flip_transform(st["coord"], store.axis(scene_id), flip_frame) st = dict(st) st["coord"], st["normal"] = apply_T(T, st["coord"], st.get("normal")) return st, {"flip": flip, "T_flip": T, "order_preserved": preserves_point_order(edit)} # ------------------------------------------------------------------ situated pose under a flip def _quat_to_mat(q): x, y, z, w = q n = np.sqrt(x * x + y * y + z * z + w * w); x, y, z, w = x / n, y / n, z / n, w / n return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) def _mat_to_quat(R): tr = np.trace(R) if tr > 0: s = np.sqrt(tr + 1.0) * 2; w = 0.25 * s x = (R[2, 1] - R[1, 2]) / s; y = (R[0, 2] - R[2, 0]) / s; z = (R[1, 0] - R[0, 1]) / s elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]: s = np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2; x = 0.25 * s w = (R[2, 1] - R[1, 2]) / s; y = (R[0, 1] + R[1, 0]) / s; z = (R[0, 2] + R[2, 0]) / s elif R[1, 1] > R[2, 2]: s = np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2; y = 0.25 * s w = (R[0, 2] - R[2, 0]) / s; x = (R[0, 1] + R[1, 0]) / s; z = (R[1, 2] + R[2, 1]) / s else: s = np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2; z = 0.25 * s w = (R[1, 0] - R[0, 1]) / s; x = (R[0, 2] + R[2, 0]) / s; y = (R[1, 2] + R[2, 1]) / s q = np.array([x, y, z, w]) q[np.abs(q) < 1e-12] = 0.0 return q def mirror_situated_pose(pose, T, coord_before, coord_after): """Mirror an SQA3D-convention pose {"position": [x,y,z], "rotation": [qx,qy,qz,qw]} through the flip T. SQA3D convention (verified against SQA3D's utils/visualize_data.py): position is in the RAW ScanNet frame minus the raw bounding-box centre of the scene's points; rotation is a z-yaw quaternion in that frame whose body x axis is the (reversed) facing direction and body y the lateral axis. The mirrored agent keeps its up and facing axes and has its lateral axis reversed: R' = T_lin @ R @ diag(1, -1, 1) (a proper rotation again).""" c0 = (coord_before.min(0) + coord_before.max(0)) / 2.0 c1 = (coord_after.min(0) + coord_after.max(0)) / 2.0 p_raw = np.asarray(pose["position"], float) + c0 p_new = (T @ np.r_[p_raw, 1.0])[:3] - c1 R = _quat_to_mat(pose["rotation"]) R_new = T[:3, :3] @ R @ np.diag([1.0, -1.0, 1.0]) q = _mat_to_quat(R_new) p_new = [float(v) for v in p_new] if abs(pose["position"][2]) < 1e-12 and abs(p_new[2]) < 1e-6: p_new[2] = 0.0 # SQA3D stores the floor-plane position with z = 0 return {"position": p_new, "rotation": [float(v) for v in q]} def aligned_flip(axis_align, T): """Aligned-frame 4x4 of a raw-frame flip T: M @ T @ M^-1 (for aligned_x this is x -> 2*c_x - x).""" M = np.asarray(axis_align, float).reshape(4, 4) return M @ T @ np.linalg.inv(M) def mirror_aligned_pose(pose, S): """Mirror an AXIS-ALIGNED-frame pose {"position": [x,y,z], "rotation": [qx,qy,qz,qw]} (observer faces along the quaternion's +x axis, z up) through the aligned-frame reflection S (4x4). The position is reflected; the heading vector is reflected and a proper z-rotation is rebuilt from it.""" S = np.asarray(S, float) p = (S @ np.r_[np.asarray(pose["position"], float), 1.0])[:3] f = S[:3, :3] @ _quat_to_mat(pose["rotation"])[:, 0] th = np.arctan2(f[1], f[0]) q = [0.0, 0.0, float(np.sin(th / 2)), float(np.cos(th / 2))] return {"position": [float(v) for v in p], "rotation": q}