| """Create or replace the PhysInOne moving-camera Level Sequence. |
| |
| Run inside Unreal Engine while the target level is open. The script reads |
| BP_CameraTrajectory, creates CineCamera_Moving, adds all managed static cameras |
| to a sequence, and writes camera metadata under Rendered/Videos. |
| |
| The post-processing tools intentionally never choose validation views and never |
| overwrite transforms_train.json, transforms_val.json, or transforms_test.json. |
| This script is the single authority for those split files. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import hashlib |
| import json |
| import math |
| from pathlib import Path |
| import random |
| import re |
| import sys |
|
|
| import numpy as np |
| import unreal |
|
|
|
|
| CONFIG_ACTOR_LABEL = "BP_CameraTrajectory" |
| MOVING_CAMERA_LABEL = "CineCamera_Moving" |
| STATIC_CAMERA_PATTERN = re.compile(r"^CineCamera_\d+$") |
| FPS_60_PHENOMENA = { |
| "FixedPlanarRedirect", |
| "FixedArrayRedirect", |
| "FixedConcaveRedirect", |
| "FixedConvexRedirect", |
| "DynMirrorRedirect", |
| "LaserBlock", |
| } |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Generate a PhysInOne camera sequence.") |
| parser.add_argument("--focal", type=float, default=18.0, help="Focal length in mm.") |
| parser.add_argument("--aperture", type=float, default=10.0) |
| parser.add_argument("--radius", type=float, default=100.0, help="Base radius in cm.") |
| parser.add_argument("--latitude-range", type=float, default=60.0) |
| parser.add_argument( |
| "--path-type", |
| choices=("random", "arc", "sine", "loop"), |
| default="random", |
| help="Moving-camera path family.", |
| ) |
| parser.add_argument( |
| "--seed", |
| type=int, |
| default=None, |
| help="Optional trajectory seed. The level name provides a stable seed by default.", |
| ) |
| parser.add_argument( |
| "--output-root", |
| default=None, |
| help="Metadata root. Default: <project>/Rendered/Videos.", |
| ) |
| return parser.parse_known_args()[0] |
|
|
|
|
| def stable_seed(text: str) -> int: |
| return int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "big") |
|
|
|
|
| def current_level_parts() -> tuple[str, str, str, str]: |
| world = unreal.EditorLevelLibrary.get_editor_world() |
| object_path = world.get_path_name().replace("\\", "/") |
| match = re.fullmatch( |
| r"/Game/PhysInOne/Scenes/(Train|Val|Test)/" |
| r"(SinglePhysics|DoublePhysics|TriplePhysics)/([^./]+)(?:\.([^./]+))?", |
| object_path, |
| ) |
| if not match: |
| raise ValueError( |
| "The open level must use /Game/PhysInOne/Scenes/<Split>/<Physics>/<Scene>." |
| ) |
| split, physics, scene, object_name = match.groups() |
| if object_name is not None and object_name != scene: |
| raise ValueError(f"Level package and object names do not match: {object_path}") |
| return split, physics, scene, object_path |
|
|
|
|
| def infer_fps(scene_name: str) -> int: |
| prefix = scene_name.split("__", 1)[0] |
| return 60 if any(name in prefix for name in FPS_60_PHENOMENA) else 30 |
|
|
|
|
| def find_config_actor(): |
| for actor in unreal.EditorLevelLibrary.get_all_level_actors(): |
| if actor.get_actor_label() == CONFIG_ACTOR_LABEL: |
| return actor |
| return None |
|
|
|
|
| def validate_config(config_actor) -> None: |
| scale = config_actor.get_actor_scale3d() |
| rotation = config_actor.get_actor_rotation() |
| tolerance = 1e-4 |
| if max(abs(rotation.roll), abs(rotation.pitch), abs(rotation.yaw)) > tolerance: |
| raise ValueError("BP_CameraTrajectory rotation must be zero.") |
| if max(abs(scale.x - scale.y), abs(scale.x - scale.z)) > tolerance: |
| raise ValueError("BP_CameraTrajectory XYZ scale must be uniform.") |
| if min(scale.x, scale.y, scale.z) <= 0: |
| raise ValueError("BP_CameraTrajectory scale must be positive.") |
| duration = float(config_actor.get_editor_property("Time")) |
| if duration <= 0: |
| raise ValueError("BP_CameraTrajectory.Time must be positive.") |
|
|
|
|
| def choose_hemisphere(config_actor, rng: random.Random) -> bool | None: |
| if bool(config_actor.get_editor_property("RandomHemisphere")): |
| return rng.choice([True, False]) |
| return bool(config_actor.get_editor_property("UpperHemisphere")) |
|
|
|
|
| def generate_path( |
| frame_count: int, |
| longitude_range: float, |
| latitude_range: float, |
| clockwise: bool, |
| upper_hemisphere: bool | None, |
| path_type: str, |
| rng: random.Random, |
| ) -> tuple[list[float], list[float], list[float], str]: |
| if frame_count < 2: |
| raise ValueError("The sequence must contain at least two frames.") |
| selected_type = rng.choice(["arc", "sine", "loop"]) if path_type == "random" else path_type |
| direction = 1.0 if clockwise else -1.0 |
| start_longitude = rng.uniform(0.0, 360.0) |
|
|
| if upper_hemisphere is True: |
| low_latitude, high_latitude = 0.0, latitude_range |
| elif upper_hemisphere is False: |
| low_latitude, high_latitude = -latitude_range, 0.0 |
| else: |
| low_latitude, high_latitude = -latitude_range, latitude_range |
|
|
| start_latitude = rng.uniform(low_latitude, high_latitude) |
| end_latitude = rng.uniform(low_latitude, high_latitude) |
| longitudes: list[float] = [] |
| latitudes: list[float] = [] |
| radius_factors: list[float] = [] |
|
|
| for index in range(frame_count): |
| t = index / (frame_count - 1) |
| if selected_type == "arc": |
| smooth_t = t * t * (3.0 - 2.0 * t) |
| longitude = start_longitude + direction * longitude_range * smooth_t |
| latitude = (1.0 - smooth_t) * start_latitude + smooth_t * end_latitude |
| radius_factor = 1.0 |
| elif selected_type == "sine": |
| longitude = start_longitude + direction * longitude_range * t |
| latitude = start_latitude + (end_latitude - start_latitude) * math.sin(math.pi * t) |
| radius_factor = 1.0 - 0.3 * abs(math.sin(2.0 * math.pi * t)) |
| else: |
| loop_radius = min(40.0, max(10.0, longitude_range / 4.0)) |
| phase = 2.0 * math.pi * t * direction |
| center_latitude = (low_latitude + high_latitude) / 2.0 |
| longitude = start_longitude + loop_radius * math.cos(phase) |
| latitude = center_latitude + min(loop_radius, latitude_range / 2.0) * math.sin(phase) |
| radius_factor = 1.0 |
|
|
| longitudes.append(longitude % 360.0) |
| latitudes.append(max(-90.0, min(90.0, latitude))) |
| radius_factors.append(radius_factor) |
|
|
| return longitudes, latitudes, radius_factors, selected_type |
|
|
|
|
| def spherical_position(radius, longitude, latitude, scale, center): |
| lon = math.radians(longitude) |
| lat = math.radians(latitude) |
| return unreal.Vector( |
| center.x + radius * math.cos(lat) * math.cos(lon) * scale.x, |
| center.y + radius * math.cos(lat) * math.sin(lon) * scale.y, |
| center.z + radius * math.sin(lat) * scale.z, |
| ) |
|
|
|
|
| def look_at(camera_position, target_position): |
| direction = unreal.MathLibrary.normal(target_position - camera_position) |
| rotation = unreal.MathLibrary.make_rot_from_x(direction) |
| rotation.roll = 0.0 |
| return rotation |
|
|
|
|
| def configure_camera(camera_actor, focal: float, aperture: float) -> None: |
| component = camera_actor.get_cine_camera_component() |
| component.set_editor_property("current_focal_length", focal) |
| component.set_editor_property("current_aperture", aperture) |
| filmback = component.get_editor_property("filmback") |
| filmback.sensor_width = 23.76 |
| filmback.sensor_height = 23.76 |
| component.set_editor_property("filmback", filmback) |
| focus = component.get_editor_property("focus_settings") |
| focus.focus_method = unreal.CameraFocusMethod.MANUAL |
| focus.manual_focus_distance = 10000.0 |
| component.set_editor_property("focus_settings", focus) |
|
|
|
|
| def replace_sequence_asset(sequence_object_path: str): |
| package_path, object_name = sequence_object_path.rsplit("/", 1) |
| sequence_name = object_name.split(".", 1)[0] |
| full_object_path = f"{package_path}/{sequence_name}.{sequence_name}" |
| registry = unreal.AssetRegistryHelpers.get_asset_registry() |
| asset_data = registry.get_asset_by_object_path(full_object_path) |
| if asset_data.is_valid(): |
| try: |
| unreal.LevelSequenceEditorBlueprintLibrary.close_level_sequence() |
| except Exception: |
| pass |
| unreal.SystemLibrary.collect_garbage() |
| if not unreal.EditorAssetLibrary.delete_asset(full_object_path): |
| raise RuntimeError(f"Could not replace existing sequence: {full_object_path}") |
|
|
| if not unreal.EditorAssetLibrary.does_directory_exist(package_path): |
| unreal.EditorAssetLibrary.make_directory(package_path) |
| sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset( |
| sequence_name, |
| package_path, |
| unreal.LevelSequence, |
| unreal.LevelSequenceFactoryNew(), |
| ) |
| if sequence is None: |
| raise RuntimeError(f"Could not create sequence: {full_object_path}") |
| return sequence |
|
|
|
|
| def remove_moving_camera() -> None: |
| for actor in unreal.EditorLevelLibrary.get_all_level_actors(): |
| if ( |
| isinstance(actor, unreal.CineCameraActor) |
| and actor.get_actor_label() == MOVING_CAMERA_LABEL |
| ): |
| unreal.EditorLevelLibrary.destroy_actor(actor) |
|
|
|
|
| def add_component_tracks(sequence, actor_binding, camera_actor) -> None: |
| component_binding = sequence.add_possessable(camera_actor.get_cine_camera_component()) |
| component_binding.set_parent(actor_binding) |
| component_binding.set_display_name("CameraComponent") |
| for display_name, property_path in ( |
| ("Current Focal Length", "CurrentFocalLength"), |
| ("Current Aperture", "CurrentAperture"), |
| ("Manual Focus Distance", "FocusSettings.ManualFocusDistance"), |
| ): |
| track = component_binding.add_track(unreal.MovieSceneFloatTrack) |
| track.set_property_name_and_path(display_name, property_path) |
| section = track.add_section() |
| section.set_start_frame_bounded(0) |
| section.set_end_frame_bounded(0) |
|
|
|
|
| def add_moving_camera(sequence, positions, rotations, focal, aperture, frame_count): |
| camera = unreal.EditorLevelLibrary.spawn_actor_from_class( |
| unreal.CineCameraActor, positions[0], rotations[0] |
| ) |
| camera.set_actor_label(MOVING_CAMERA_LABEL) |
| configure_camera(camera, focal, aperture) |
| binding = sequence.add_possessable(camera) |
| binding.set_display_name(MOVING_CAMERA_LABEL) |
| track = binding.add_track(unreal.MovieScene3DTransformTrack) |
| section = track.add_section() |
| section.set_range(0, frame_count) |
| channels = section.get_all_channels() |
| for index, (position, rotation) in enumerate(zip(positions, rotations)): |
| frame = unreal.FrameNumber(index) |
| for channel, value in zip( |
| channels[:6], |
| (position.x, position.y, position.z, rotation.roll, rotation.pitch, rotation.yaw), |
| ): |
| channel.add_key(frame, value) |
| add_component_tracks(sequence, binding, camera) |
| return binding |
|
|
|
|
| def add_static_camera(sequence, camera, frame_count): |
| parent = camera.get_attach_parent_actor() |
| location = camera.get_actor_location() |
| rotation = camera.get_actor_rotation() |
| scale = camera.get_actor_scale3d() |
| if parent: |
| camera.detach_from_actor( |
| location_rule=unreal.DetachmentRule.KEEP_WORLD, |
| rotation_rule=unreal.DetachmentRule.KEEP_WORLD, |
| scale_rule=unreal.DetachmentRule.KEEP_WORLD, |
| ) |
| binding = sequence.add_possessable(camera) |
| binding.set_display_name(camera.get_actor_label()) |
| track = binding.add_track(unreal.MovieScene3DTransformTrack) |
| section = track.add_section() |
| section.set_range(0, frame_count) |
| channels = section.get_all_channels() |
| frame = unreal.FrameNumber(0) |
| for channel, value in zip( |
| channels[:9], |
| ( |
| location.x, |
| location.y, |
| location.z, |
| rotation.roll, |
| rotation.pitch, |
| rotation.yaw, |
| scale.x, |
| scale.y, |
| scale.z, |
| ), |
| ): |
| channel.add_key(frame, value) |
| add_component_tracks(sequence, binding, camera) |
|
|
|
|
| def rotation_matrix(roll: float, pitch: float, yaw: float) -> np.ndarray: |
| roll, pitch, yaw = map(math.radians, (roll, pitch, yaw)) |
| rx = np.array( |
| [[1, 0, 0], [0, math.cos(roll), math.sin(roll)], [0, -math.sin(roll), math.cos(roll)]] |
| ) |
| ry = np.array( |
| [[math.cos(pitch), 0, -math.sin(pitch)], [0, 1, 0], [math.sin(pitch), 0, math.cos(pitch)]] |
| ) |
| rz = np.array( |
| [[math.cos(yaw), -math.sin(yaw), 0], [math.sin(yaw), math.cos(yaw), 0], [0, 0, 1]] |
| ) |
| return rz @ ry @ rx |
|
|
|
|
| def camera_json(camera_name, positions, rotations, frame_count, fov, fps, convention): |
| frames = [] |
| for index in range(frame_count): |
| position_m = np.asarray(positions[index], dtype=float).reshape(3, 1) / 100.0 |
| ue_rotation = rotation_matrix(*rotations[index]) |
| if convention == "ue": |
| matrix = np.vstack((np.hstack((ue_rotation, position_m)), [0, 0, 0, 1])) |
| else: |
| world_conversion = np.diag([1, -1, 1]) |
| camera_conversion = np.array([[0, 0, -1], [1, 0, 0], [0, 1, 0]]) |
| matrix = np.eye(4) |
| matrix[:3, :3] = world_conversion @ ue_rotation @ camera_conversion |
| matrix[:3, 3] = (world_conversion @ position_m).ravel() |
| frames.append( |
| { |
| "frame": index, |
| "transform_matrix": matrix.tolist(), |
| "file_path": f"{camera_name}/rgb/{index:04d}", |
| "time": index / (frame_count - 1) if frame_count > 1 else 0.0, |
| "time_abs": index / float(fps), |
| } |
| ) |
| return { |
| "camera_angle_x": fov, |
| "img_h": 1120, |
| "img_w": 1120, |
| "total_frames": frame_count, |
| "fps": fps, |
| "frames": frames, |
| } |
|
|
|
|
| def write_json(path: Path, data) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| with path.open("w", encoding="utf-8") as handle: |
| json.dump(data, handle, indent=2) |
|
|
|
|
| def clean_camera_metadata(output_dir: Path) -> None: |
| output_dir.mkdir(parents=True, exist_ok=True) |
| names = { |
| "camera_ue_data.json", |
| "static_camera_list.txt", |
| "transforms_train.json", |
| "transforms_val.json", |
| "transforms_test.json", |
| } |
| for path in output_dir.iterdir(): |
| if path.is_file() and ( |
| path.name in names |
| or path.name.startswith("ue_CineCamera_") |
| or path.name.startswith("blender_CineCamera_") |
| ): |
| path.unlink() |
|
|
|
|
| def choose_validation_cameras(static_cameras, center, seed: int) -> set[str]: |
| if len(static_cameras) < 2: |
| return {camera.get_actor_label() for camera in static_cameras} |
| by_name = {camera.get_actor_label(): camera for camera in static_cameras} |
| names = sorted(by_name) |
| first = random.Random(seed).choice(names) |
| first_location = by_name[first].get_actor_location() - center |
| first_yaw = math.degrees(math.atan2(first_location.y, first_location.x)) % 360.0 |
|
|
| def diagonal_error(name: str) -> float: |
| location = by_name[name].get_actor_location() - center |
| yaw = math.degrees(math.atan2(location.y, location.x)) % 360.0 |
| difference = abs(yaw - first_yaw) |
| difference = min(difference, 360.0 - difference) |
| return abs(180.0 - difference) |
|
|
| second = min((name for name in names if name != first), key=lambda name: (diagonal_error(name), name)) |
| return {first, second} |
|
|
|
|
| def combine_split(camera_documents, selected_names, first_half: bool): |
| chosen = [camera_documents[name] for name in sorted(selected_names)] |
| result = {"camera_angle_x": None, "img_h": None, "img_w": None, "frames": []} |
| for document in chosen: |
| if result["camera_angle_x"] is None: |
| for key in ("camera_angle_x", "img_h", "img_w"): |
| result[key] = document.get(key) |
| for frame in document.get("frames", []): |
| include = frame.get("time", 0.0) <= 0.5 if first_half else frame.get("time", 0.0) > 0.5 |
| if include: |
| result["frames"].append(frame) |
| return result |
|
|
|
|
| def generate(args: argparse.Namespace) -> Path: |
| split, physics, scene_name, level_path = current_level_parts() |
| fps = infer_fps(scene_name) |
| config_actor = find_config_actor() |
| if config_actor is None: |
| raise RuntimeError(f"Actor {CONFIG_ACTOR_LABEL!r} was not found in the current level.") |
| validate_config(config_actor) |
|
|
| duration = float(config_actor.get_editor_property("Time")) |
| frame_count = int(round(duration * fps)) |
| if frame_count < 2: |
| raise ValueError("Time multiplied by FPS must produce at least two frames.") |
|
|
| seed = args.seed if args.seed is not None else stable_seed(level_path) |
| rng = random.Random(seed) |
| clockwise = ( |
| rng.choice([True, False]) |
| if bool(config_actor.get_editor_property("RandomSampleDirection")) |
| else bool(config_actor.get_editor_property("SampleClockwise")) |
| ) |
| longitude_range = float(config_actor.get_editor_property("LongtitudeRange")) |
| hemisphere = choose_hemisphere(config_actor, rng) |
| longitudes, latitudes, radius_factors, path_type = generate_path( |
| frame_count, |
| longitude_range, |
| args.latitude_range, |
| clockwise, |
| hemisphere, |
| args.path_type, |
| rng, |
| ) |
| config_actor.set_editor_property("LongitudeAngles", longitudes) |
| config_actor.set_editor_property("LatitudeAngles", latitudes) |
|
|
| center = config_actor.get_actor_location() |
| scale = config_actor.get_actor_scale3d() |
| positions = [ |
| spherical_position(args.radius * factor, longitude, latitude, scale, center) |
| for longitude, latitude, factor in zip(longitudes, latitudes, radius_factors) |
| ] |
| rotations = [look_at(position, center) for position in positions] |
|
|
| sequence_name = f"{scene_name}_trajectory" |
| sequence_object_path = ( |
| f"/Game/PhysInOne/Trajectories/{split}/{physics}/{sequence_name}.{sequence_name}" |
| ) |
| remove_moving_camera() |
| sequence = replace_sequence_asset(sequence_object_path) |
| frame_rate = unreal.FrameRate(fps, 1) |
| sequence.set_display_rate(frame_rate) |
| sequence.set_tick_resolution(frame_rate) |
| sequence.set_playback_start(0) |
| sequence.set_playback_end(frame_count) |
| moving_binding = add_moving_camera( |
| sequence, positions, rotations, args.focal, args.aperture, frame_count |
| ) |
|
|
| static_cameras = sorted( |
| ( |
| actor |
| for actor in unreal.EditorLevelLibrary.get_all_level_actors() |
| if isinstance(actor, unreal.CineCameraActor) |
| and STATIC_CAMERA_PATTERN.fullmatch(actor.get_actor_label()) |
| ), |
| key=lambda actor: int(actor.get_actor_label().rsplit("_", 1)[1]), |
| ) |
| if not static_cameras: |
| raise RuntimeError("No managed static cameras were found. Run generate_static_cameras.py first.") |
| for camera in static_cameras: |
| add_static_camera(sequence, camera, frame_count) |
|
|
| cut_track = sequence.add_track(unreal.MovieSceneCameraCutTrack) |
| cut_section = cut_track.add_section() |
| cut_section.set_range(0, frame_count) |
| cut_section.set_camera_binding_id(sequence.get_binding_id(moving_binding)) |
|
|
| if not unreal.EditorAssetLibrary.save_asset(sequence_object_path): |
| raise RuntimeError(f"Failed to save sequence: {sequence_object_path}") |
|
|
| output_root = ( |
| Path(args.output_root) |
| if args.output_root |
| else Path(unreal.Paths.project_dir()) / "Rendered" / "Videos" |
| ) |
| output_dir = output_root / split / physics / sequence_name |
| clean_camera_metadata(output_dir) |
| fov = 2.0 * math.atan(23.76 / (2.0 * args.focal)) |
|
|
| ue_summary = { |
| "Scene_Location_Info": { |
| "center_location": {"x": center.x, "y": center.y, "z": center.z}, |
| "scale": scale.x, |
| } |
| } |
| camera_documents = {} |
|
|
| moving_positions = [(value.x, value.y, value.z) for value in positions] |
| moving_rotations = [(value.roll, value.pitch, value.yaw) for value in rotations] |
| for convention in ("ue", "blender"): |
| document = camera_json( |
| MOVING_CAMERA_LABEL, |
| moving_positions, |
| moving_rotations, |
| frame_count, |
| fov, |
| fps, |
| convention, |
| ) |
| write_json(output_dir / f"{convention}_{MOVING_CAMERA_LABEL}.json", document) |
| ue_summary[MOVING_CAMERA_LABEL] = { |
| "type": "moving", |
| "total_frames": frame_count, |
| "frames": [ |
| { |
| "frame": index, |
| "location": {"x": position.x, "y": position.y, "z": position.z}, |
| "rotation": {"roll": rotation.roll, "pitch": rotation.pitch, "yaw": rotation.yaw}, |
| } |
| for index, (position, rotation) in enumerate(zip(positions, rotations)) |
| ], |
| } |
|
|
| for camera in static_cameras: |
| name = camera.get_actor_label() |
| location = camera.get_actor_location() |
| rotation = camera.get_actor_rotation() |
| static_positions = [(location.x, location.y, location.z)] * frame_count |
| static_rotations = [(rotation.roll, rotation.pitch, rotation.yaw)] * frame_count |
| for convention in ("ue", "blender"): |
| document = camera_json( |
| name, |
| static_positions, |
| static_rotations, |
| frame_count, |
| fov, |
| fps, |
| convention, |
| ) |
| write_json(output_dir / f"{convention}_{name}.json", document) |
| if convention == "blender": |
| camera_documents[name] = document |
| ue_summary[name] = { |
| "type": "static", |
| "location": {"x": location.x, "y": location.y, "z": location.z}, |
| "rotation": {"roll": rotation.roll, "pitch": rotation.pitch, "yaw": rotation.yaw}, |
| } |
|
|
| write_json(output_dir / "camera_ue_data.json", ue_summary) |
| with (output_dir / "static_camera_list.txt").open("w", encoding="utf-8") as handle: |
| handle.write("\n".join(camera.get_actor_label() for camera in static_cameras) + "\n") |
|
|
| all_names = set(camera_documents) |
| val_names = choose_validation_cameras(static_cameras, center, seed) |
| train_names = all_names - val_names |
| write_json(output_dir / "transforms_train.json", combine_split(camera_documents, train_names, True)) |
| write_json(output_dir / "transforms_val.json", combine_split(camera_documents, val_names, True)) |
| write_json(output_dir / "transforms_test.json", combine_split(camera_documents, all_names, False)) |
|
|
| unreal.log( |
| f"Generated {sequence_object_path}: {frame_count} frames at {fps} FPS, " |
| f"path={path_type}, seed={seed}, static_cameras={len(static_cameras)}." |
| ) |
| unreal.log(f"Camera metadata: {output_dir}") |
| return output_dir |
|
|
|
|
| if __name__ == "__main__": |
| try: |
| generate(parse_args()) |
| except Exception as exc: |
| unreal.log_error(f"Camera sequence generation failed: {exc}") |
| raise |
|
|