File size: 14,219 Bytes
116e377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"""Build twelve NeoVerse-style camera controls for every SpatialVID scene.

The relative trajectories reproduce ``CameraTrajectory.from_predefined`` in
NeoVerse's ``diffsynth/utils/auxiliary.py``.  SpatialVID is a dynamic source,
so the NeoVerse demo composition is applied frame by frame:

    target_c2w[t] = source_c2w[t] @ relative_c2w[t]

The emitted controls use the unified dataset's absolute OpenCV c2w schema.
"""

from __future__ import annotations

import argparse
import json
from copy import deepcopy
from pathlib import Path
from typing import Any

import numpy as np
from scipy.spatial.transform import Rotation, Slerp


ROOT = Path(__file__).resolve().parent
NUM_FRAMES = 81
LAST_FRAME = NUM_FRAMES - 1
CONTROL_SPECS: dict[str, dict[str, float]] = {
    "pan_left": {"angle": 15.0},
    "pan_right": {"angle": 15.0},
    "tilt_up": {"angle": 15.0},
    "tilt_down": {"angle": 15.0},
    "move_left": {"distance": 0.1},
    "move_right": {"distance": 0.1},
    "push_in": {"distance": 0.1},
    "pull_out": {"distance": 0.1},
    "boom_up": {"distance": 0.1},
    "boom_down": {"distance": 0.1},
    "orbit_left": {"angle": 15.0, "orbit_radius": 1.0},
    "orbit_right": {"angle": 15.0, "orbit_radius": 1.0},
}
COMPOSITION = "target_c2w[t] = source_c2w[t] @ relative_c2w[t]"
PROVENANCE = (
    "NeoVerse CameraTrajectory.from_predefined defaults and dynamic-scene "
    "relative composition"
)


def relative_endpoint(name: str, params: dict[str, float]) -> np.ndarray:
    """Match NeoVerse CameraTrajectory._get_camera_matrix exactly."""
    angle = np.deg2rad(params.get("angle", 30.0))
    radius = params.get("orbit_radius", 0.5)
    pose = np.eye(4, dtype=np.float64)
    if name == "move_left":
        pose[0, 3] = -params["distance"]
    elif name == "move_right":
        pose[0, 3] = params["distance"]
    elif name == "push_in":
        pose[2, 3] = params["distance"]
    elif name == "pull_out":
        pose[2, 3] = -params["distance"]
    elif name == "boom_up":
        pose[1, 3] = -params["distance"]
    elif name == "boom_down":
        pose[1, 3] = params["distance"]
    elif name in {"orbit_left", "orbit_right"}:
        theta = -angle if name == "orbit_left" else angle
        cosine, sine = np.cos(theta), np.sin(theta)
        pose[0, 3] = radius * sine
        pose[2, 3] = radius * (1.0 - cosine)
        pose[0, 0] = cosine
        pose[0, 2] = -sine
        pose[2, 0] = sine
        pose[2, 2] = cosine
    elif name in {"pan_left", "pan_right"}:
        theta = -angle if name == "pan_left" else angle
        cosine, sine = np.cos(theta), np.sin(theta)
        pose[0, 0] = cosine
        pose[0, 2] = sine
        pose[2, 0] = -sine
        pose[2, 2] = cosine
    elif name in {"tilt_up", "tilt_down"}:
        theta = angle if name == "tilt_up" else -angle
        cosine, sine = np.cos(theta), np.sin(theta)
        pose[1, 1] = cosine
        pose[1, 2] = -sine
        pose[2, 1] = sine
        pose[2, 2] = cosine
    else:
        raise ValueError(f"unsupported control: {name}")
    return pose


def relative_trajectory(name: str, params: dict[str, float]) -> np.ndarray:
    """Match NeoVerse's two-keyframe rotation Slerp and linear translation."""
    endpoint = relative_endpoint(name, params)
    frame_times = np.linspace(0.0, 1.0, NUM_FRAMES)
    rotations = Slerp(
        [0.0, 1.0],
        Rotation.from_matrix(np.stack([np.eye(3), endpoint[:3, :3]])),
    )(frame_times).as_matrix()
    positions = frame_times[:, None] * endpoint[:3, 3][None]
    output = np.repeat(np.eye(4, dtype=np.float64)[None], NUM_FRAMES, axis=0)
    output[:, :3, :3] = rotations
    output[:, :3, 3] = positions
    return output


def trajectory_spec(name: str, params: dict[str, float]) -> dict[str, Any]:
    json_params = {
        key: int(value) if key == "angle" and float(value).is_integer() else value
        for key, value in params.items()
    }
    return {
        "name": name,
        "description": f"NeoVerse predefined {name} control for SpatialVID",
        "mode": "relative",
        "num_frames": NUM_FRAMES,
        "zoom_ratio": 1.0,
        "use_first_frame": True,
        "composition": COMPOSITION,
        "keyframes": [
            {"0": [{"static": {}}]},
            {str(LAST_FRAME): [{name: json_params}]},
        ],
    }


def source_records(manifest: dict[str, Any]) -> list[dict[str, Any]]:
    """Recover one authoritative source record per scene, also after reruns."""
    records: dict[str, dict[str, Any]] = {}
    for case in manifest["cases"]:
        scene = case["scene"]
        if scene in records:
            continue
        base = deepcopy(case)
        base["case_id"] = scene
        base["traj"] = None
        base["target_path"] = None
        base["camera_control"] = None
        base["pair_id"] = None
        metadata = deepcopy(base.get("metadata", {}))
        metadata.pop("camera_control_provenance", None)
        base["metadata"] = metadata
        records[scene] = base
    return [records[key] for key in sorted(records)]


def control_document(source: dict[str, Any], relative: np.ndarray) -> dict[str, Any]:
    frames = source["frames"]
    if len(frames) != NUM_FRAMES:
        raise ValueError(f"expected {NUM_FRAMES} source frames, got {len(frames)}")
    source_c2w = np.asarray([frame["c2w"] for frame in frames], dtype=np.float64)
    target_c2w = source_c2w @ relative
    return {
        "format_version": source["format_version"],
        "camera_model": source["camera_model"],
        "pose_type": source["pose_type"],
        "coordinate_system": source["coordinate_system"],
        "image_hw": source["image_hw"],
        "num_frames": NUM_FRAMES,
        "frames": [
            {
                "frame_index": index,
                "c2w": target_c2w[index].tolist(),
                "intrinsics": deepcopy(frames[index]["intrinsics"]),
            }
            for index in range(NUM_FRAMES)
        ],
    }


def controlled_case(base: dict[str, Any], name: str, params: dict[str, float]) -> dict[str, Any]:
    scene = base["scene"]
    case = deepcopy(base)
    case["case_id"] = f"{scene}__{name}"
    case["traj"] = name
    case["target_path"] = None
    case["camera_control"] = {
        "path": f"camera_controls/{scene}/{name}/transforms.json",
        "variant": "default",
    }
    case["pair_id"] = None
    case["metadata"]["camera_control_provenance"] = {
        "source": PROVENANCE,
        "spec_path": f"trajectory_specs/{name}.json",
        "mode": "relative",
        "composition": COMPOSITION,
        "angle_degrees": params.get("angle"),
        "distance": params.get("distance"),
        "distance_unit": "source_reconstruction_unit" if "distance" in params else None,
        "orbit_radius": params.get("orbit_radius"),
        "orbit_radius_unit": "source_reconstruction_unit" if "orbit_radius" in params else None,
    }
    return case


def update_manifest(manifest: dict[str, Any], bases: list[dict[str, Any]]) -> dict[str, Any]:
    output = deepcopy(manifest)
    cases = [
        controlled_case(base, name, params)
        for base in bases
        for name, params in CONTROL_SPECS.items()
    ]
    output["protocol"]["control"] = "camera"
    output["camera"].update({
        "default_control_variant": "default",
        "synthetic_control_mode": "relative",
        "synthetic_control_composition": COMPOSITION,
    })
    output["extensions"]["camera_trajectory_specs"] = {
        "path": "trajectory_specs/<trajectory_id>.json",
        "meaning": "NeoVerse-compatible relative keyframe trajectory definition",
        "source": PROVENANCE,
    }
    output["statistics"].update({
        "num_scenes": len(bases),
        "num_cases": len(cases),
        "num_camera_control_cases": len(cases),
        "num_camera_control_frames": len(cases) * NUM_FRAMES,
        "camera_control_trajectory_distribution": {
            name: len(bases) for name in CONTROL_SPECS
        },
        "num_pairs": 0,
        "num_unpaired_cases": len(cases),
    })
    output["pairing"]["unpaired_sources"] = [
        {
            "case_id": case["case_id"],
            "source_scene_id": case["scene"],
            "source_path": case["source_path"],
            "num_frames": NUM_FRAMES,
            "reason": "synthetic_camera_control_only_no_target_rgb",
        }
        for case in cases
    ]
    output["cases"] = cases
    return output


def validate(root: Path) -> dict[str, Any]:
    manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
    errors: list[str] = []
    max_first_error = 0.0
    max_composition_error = 0.0
    max_orthonormal_error = 0.0
    max_determinant_error = 0.0
    relative = {
        name: relative_trajectory(name, params)
        for name, params in CONTROL_SPECS.items()
    }
    case_ids = [case["case_id"] for case in manifest["cases"]]
    control_paths = [case["camera_control"]["path"] for case in manifest["cases"]]
    if len(case_ids) != len(set(case_ids)):
        errors.append("duplicate case_id")
    if len(control_paths) != len(set(control_paths)):
        errors.append("duplicate camera control path")
    for case in manifest["cases"]:
        control_path = root / case["camera_control"]["path"]
        source_path = root / case["source_path"] / "transforms.json"
        if not control_path.is_file():
            errors.append(f"missing {control_path.relative_to(root)}")
            continue
        control = json.loads(control_path.read_text(encoding="utf-8"))
        source = json.loads(source_path.read_text(encoding="utf-8"))
        if len(control["frames"]) != NUM_FRAMES:
            errors.append(f"{case['case_id']}: wrong frame count")
            continue
        control_c2w = np.asarray([frame["c2w"] for frame in control["frames"]])
        source_c2w = np.asarray([frame["c2w"] for frame in source["frames"]])
        max_first_error = max(max_first_error, float(np.max(np.abs(control_c2w[0] - source_c2w[0]))))
        expected_c2w = source_c2w @ relative[case["traj"]]
        max_composition_error = max(
            max_composition_error,
            float(np.max(np.abs(control_c2w - expected_c2w))),
        )
        rotations = control_c2w[:, :3, :3]
        orth = rotations @ np.swapaxes(rotations, 1, 2)
        max_orthonormal_error = max(
            max_orthonormal_error,
            float(np.max(np.abs(orth - np.eye(3)[None]))),
        )
        max_determinant_error = max(
            max_determinant_error,
            float(np.max(np.abs(np.linalg.det(rotations) - 1.0))),
        )
        if not np.isfinite(control_c2w).all():
            errors.append(f"{case['case_id']}: non-finite pose")
        if any(frame["intrinsics"]["fx"] <= 0 or frame["intrinsics"]["fy"] <= 0 for frame in control["frames"]):
            errors.append(f"{case['case_id']}: non-positive focal length")
        if [frame["frame_index"] for frame in control["frames"]] != list(range(NUM_FRAMES)):
            errors.append(f"{case['case_id']}: invalid frame indexes")
        if [frame["intrinsics"] for frame in control["frames"]] != [
            frame["intrinsics"] for frame in source["frames"]
        ]:
            errors.append(f"{case['case_id']}: intrinsics differ from source")
    if len(manifest["cases"]) != len(CONTROL_SPECS) * manifest["statistics"]["num_scenes"]:
        errors.append("manifest case count does not match scene × trajectory count")
    if max_first_error > 1e-9:
        errors.append(f"first-frame mismatch: {max_first_error}")
    if max_composition_error > 1e-9:
        errors.append(f"composition mismatch: {max_composition_error}")
    if max_orthonormal_error > 1e-6:
        errors.append(f"rotation orthonormal error: {max_orthonormal_error}")
    if max_determinant_error > 1e-6:
        errors.append(f"rotation determinant error: {max_determinant_error}")
    if errors:
        raise RuntimeError("\n".join(errors[:20]))
    return {
        "scenes": manifest["statistics"]["num_scenes"],
        "cases": len(manifest["cases"]),
        "trajectories": list(CONTROL_SPECS),
        "max_first_frame_pose_error": max_first_error,
        "max_composition_error": max_composition_error,
        "max_rotation_orthonormal_error": max_orthonormal_error,
        "max_rotation_determinant_error": max_determinant_error,
    }


def build(root: Path) -> dict[str, Any]:
    manifest_path = root / "manifest.json"
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    bases = source_records(manifest)
    if len(bases) != 200:
        raise ValueError(f"expected 200 SpatialVID scenes, found {len(bases)}")
    spec_root = root / "trajectory_specs"
    spec_root.mkdir(parents=True, exist_ok=True)
    relative = {}
    for name, params in CONTROL_SPECS.items():
        (spec_root / f"{name}.json").write_text(
            json.dumps(trajectory_spec(name, params), indent=2) + "\n",
            encoding="utf-8",
        )
        relative[name] = relative_trajectory(name, params)
    for base in bases:
        scene = base["scene"]
        source_path = root / base["source_path"] / "transforms.json"
        source = json.loads(source_path.read_text(encoding="utf-8"))
        for name in CONTROL_SPECS:
            output_path = root / "camera_controls" / scene / name / "transforms.json"
            output_path.parent.mkdir(parents=True, exist_ok=True)
            output_path.write_text(
                json.dumps(control_document(source, relative[name]), indent=2) + "\n",
                encoding="utf-8",
            )
    manifest_temp = manifest_path.with_suffix(".json.tmp")
    manifest_temp.write_text(
        json.dumps(update_manifest(manifest, bases), indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )
    manifest_temp.replace(manifest_path)
    return validate(root)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, default=ROOT)
    parser.add_argument("--check", action="store_true")
    args = parser.parse_args()
    result = validate(args.root) if args.check else build(args.root)
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()