Datasets:
Download generator/scripts/render_ego_camera_preview.py from mage0001/H2SMV-FPV: direct link, hf CLI and curl.
- Browser
- Download file 52.1 kB
-
https://huggingface.co/datasets/mage0001/H2SMV-FPV/resolve/main/generator/scripts/render_ego_camera_preview.py
- Command line
-
hf download hf://datasets/mage0001/H2SMV-FPV/generator/scripts/render_ego_camera_preview.py
-
curl -L -o render_ego_camera_preview.py https://huggingface.co/datasets/mage0001/H2SMV-FPV/resolve/main/generator/scripts/render_ego_camera_preview.py
52.1 kB
#!/usr/bin/env python3
"""Render labelled egocentric camera candidates from an existing prepared sequence.
It supports both lightweight still previews and the formal V2 dataset mode.
Formal mode builds a continuous deformation/camera animation so EEVEE motion
blur is real, then renders only the requested stride-aligned usable frames.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import random
import sys
from pathlib import Path
from types import SimpleNamespace
import bpy
import mathutils
import numpy as np
from bpy_extras.object_utils import world_to_camera_view
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
import render_blender_sequence as base
import render_portrait_png_sequence as portrait
def parse_args() -> argparse.Namespace:
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
parser = argparse.ArgumentParser()
parser.add_argument("--sequence-dir", required=True, type=Path)
parser.add_argument("--out-dir", required=True, type=Path)
parser.add_argument("--manifest", required=True, type=Path)
parser.add_argument("--addon-dir", required=True, type=Path)
parser.add_argument("--render-config", type=Path)
parser.add_argument("--sample-id", default=None)
parser.add_argument("--portrait-camera-json", type=Path)
parser.add_argument("--frames", default="auto", help="Comma-separated source frames, or 'auto'.")
parser.add_argument("--stride", type=int, default=4)
parser.add_argument("--max-preview-frames", type=int, default=8)
parser.add_argument("--width", type=int, default=768)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument("--fps", type=int, default=16)
parser.add_argument("--png-compression", type=int, default=15)
parser.add_argument("--disable-hair", action="store_true")
parser.add_argument("--occluder-probability", type=float, default=0.45)
parser.add_argument("--attached-occluder-probability", type=float, default=0.70)
parser.add_argument("--force-occluder-mode", choices=["auto", "none", "attached_small", "static_large"], default="auto")
parser.add_argument("--min-visible-hand-joints", type=int, default=3)
parser.add_argument("--occluder-seed", type=int, default=0)
parser.add_argument("--debug-visibility-hits", action="store_true")
parser.add_argument("--motion-blur-comparison", action="store_true")
parser.add_argument("--motion-blur-shutters", default="0,0.25,0.5,1.0")
parser.add_argument("--motion-blur-position", choices=["START", "CENTER", "END"], default="CENTER")
parser.add_argument("--motion-blur-shutter-min", type=float, default=0.5)
parser.add_argument("--motion-blur-shutter-max", type=float, default=1.0)
parser.add_argument("--motion-blur-seed", type=int, default=0)
parser.add_argument("--formal-dataset", action="store_true")
return parser.parse_args(argv)
def unit(vector: np.ndarray, fallback: tuple[float, float, float]) -> np.ndarray:
length = float(np.linalg.norm(vector))
if length < 1e-8:
return np.asarray(fallback, dtype=np.float64)
return np.asarray(vector, dtype=np.float64) / length
def body_basis(joints: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, dict]:
"""Return left, up and anatomical forward axes from COCO body joints."""
left_shoulder = np.asarray(joints[5], dtype=np.float64)
right_shoulder = np.asarray(joints[6], dtype=np.float64)
shoulder_mid = 0.5 * (left_shoulder + right_shoulder)
eye_mid = 0.5 * (np.asarray(joints[1]) + np.asarray(joints[2]))
# Prepared H2SMV bodies are upright in a Z-up world. Do not derive the
# camera's up axis from eye-minus-shoulder: torso lean would then tilt the
# mount extrusion downward and can put an eye/chest camera back in the mesh.
up = np.asarray((0.0, 0.0, 1.0), dtype=np.float64)
shoulder_axis = left_shoulder - right_shoulder
shoulder_axis[2] = 0.0
left = unit(shoulder_axis, (1.0, 0.0, 0.0))
forward = unit(np.cross(left, up), (0.0, -1.0, 0.0))
nose_direction = np.asarray(joints[0], dtype=np.float64) - eye_mid
if float(np.dot(forward, nose_direction)) < 0.0:
forward = -forward
return left, up, forward, {
"shoulder_mid": shoulder_mid,
"eye_mid": eye_mid,
"left_shoulder": left_shoulder,
"right_shoulder": right_shoulder,
"left_elbow": np.asarray(joints[7], dtype=np.float64),
"right_elbow": np.asarray(joints[8], dtype=np.float64),
"left_wrist": np.asarray(joints[9], dtype=np.float64),
"right_wrist": np.asarray(joints[10], dtype=np.float64),
}
def hand_activity(joints: np.ndarray) -> dict:
"""Identify signing hands and reject a both-arms-hanging pose.
COCO WholeBody uses 91:112 and 112:133 for the two 21-joint hands.
A hand is useful when it is in the body's front half-space and is either
raised above the relaxed hip region or extended clearly in front.
"""
_, _, forward, key = body_basis(joints)
hip_mid = 0.5 * (np.asarray(joints[11], dtype=np.float64) + np.asarray(joints[12], dtype=np.float64))
definitions = [
("left", 9, 7, slice(91, 112)),
("right", 10, 8, slice(112, 133)),
]
active = []
details = {}
boxes = []
for name, wrist_index, elbow_index, hand_slice in definitions:
points = np.asarray(joints[hand_slice], dtype=np.float64)
wrist = np.asarray(joints[wrist_index], dtype=np.float64)
elbow = np.asarray(joints[elbow_index], dtype=np.float64)
center = 0.5 * (points.min(axis=0) + points.max(axis=0))
front_depth = float(np.dot(center - key["shoulder_mid"], forward))
wrist_above_hip = float(wrist[2] - hip_mid[2])
elbow_above_hip = float(elbow[2] - hip_mid[2])
raised = wrist_above_hip > 0.12 or elbow_above_hip > 0.25
extended = front_depth > 0.08
in_front = front_depth > -0.025
is_active = bool(in_front and (raised or extended))
details[name] = {
"active": is_active,
"front_depth_meters": front_depth,
"wrist_above_hip_meters": wrist_above_hip,
"elbow_above_hip_meters": elbow_above_hip,
}
if is_active:
active.append(name)
boxes.append(np.concatenate((points, wrist[None, :]), axis=0))
box_points = np.concatenate(boxes, axis=0) if boxes else np.empty((0, 3), dtype=np.float64)
return {"valid": bool(active), "active_hands": active, "details": details, "box_points": box_points}
def evenly_spaced(values: list[int], maximum: int) -> list[int]:
if maximum <= 0 or len(values) <= maximum:
return values
positions = np.linspace(0, len(values) - 1, maximum)
return [values[int(round(position))] for position in positions]
def stride_runs(frames: list[int], stride: int) -> list[list[int]]:
"""Split sparse frames into runs Blender can render with one frame_step."""
runs: list[list[int]] = []
for frame in sorted(frames):
if not runs or frame - runs[-1][-1] != stride:
runs.append([frame])
else:
runs[-1].append(frame)
return runs
def render_animation_runs(scene: bpy.types.Scene, view_dir: Path, frames: list[int], stride: int) -> dict:
"""Render accepted sparse frames with one animation operator per run."""
runs = stride_runs(frames, stride)
if not runs:
return {"operator_calls": 0, "runs": []}
# Blender appends its four-digit frame number. The `00` prefix retains
# the established six-digit dataset filename: frame_000004.png.
scene.render.filepath = str(view_dir / "frame_00")
scene.render.use_file_extension = True
scene.frame_step = stride
for run in runs:
scene.frame_start = run[0]
scene.frame_end = run[-1]
print(
f"[ANIMATION RENDER] {view_dir.name} start={run[0]} end={run[-1]} "
f"step={stride} frames={len(run)}",
flush=True,
)
bpy.ops.render.render(animation=True)
missing = [frame for frame in frames if not (view_dir / f"frame_{frame:06d}.png").is_file()]
if missing:
raise RuntimeError(f"Animation render missed {len(missing)} frames in {view_dir}: {missing[:10]}")
return {
"operator_calls": len(runs),
"runs": [{"start": run[0], "end": run[-1], "frames": len(run)} for run in runs],
}
def outside_surface(
anchor: np.ndarray,
extrusion: np.ndarray,
vertices: np.ndarray,
radius: float,
clearance: float,
minimum: float,
) -> np.ndarray:
"""Move a camera beyond nearby mesh along its mount/extrusion direction."""
direction = unit(extrusion, (0.0, -1.0, 0.0))
delta = np.asarray(vertices, dtype=np.float64) - anchor[None, :]
along = delta @ direction
radial = np.linalg.norm(delta - along[:, None] * direction[None, :], axis=1)
candidates = along[radial <= radius]
distance = max(minimum, (float(candidates.max()) if candidates.size else 0.0) + clearance)
return anchor + direction * distance
CAMERA_SPECS = [
{"id": "eye_front_80", "mount": "eyes", "fov": 80.0, "yaw": 0.0, "pitch": -14.0, "roll": -2.0, "core_view": True},
{"id": "head_top_95", "mount": "head_top", "fov": 95.0, "yaw": 5.0, "pitch": -48.0, "roll": 4.0, "core_view": True},
{"id": "left_upper_arm_100", "mount": "left_arm", "fov": 100.0, "yaw": 20.0, "pitch": 3.0, "roll": 9.0, "core_view": True},
{"id": "right_upper_arm_100", "mount": "right_arm", "fov": 100.0, "yaw": -20.0, "pitch": 3.0, "roll": -9.0, "core_view": True},
# Chest is retained as an optional fifth view. It is emitted only when the
# hands remain in the outward camera hemisphere and fit within 100 degrees.
{"id": "chest_90", "mount": "chest", "fov": 90.0, "yaw": -4.0, "pitch": 5.0, "roll": -3.0, "core_view": False},
]
HAND_SLICES = {"left": slice(91, 112), "right": slice(112, 133)}
def camera_pose(spec: dict, vertices: np.ndarray, joints: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
left, up, forward, key = body_basis(joints)
mount = spec["mount"]
if mount == "eyes":
anchor = key["eye_mid"]
location = outside_surface(anchor, forward, vertices, 0.105, 0.045, 0.075)
elif mount == "head_top":
crown = np.asarray(vertices[int(np.argmax(vertices[:, 2]))], dtype=np.float64)
# A literal scalp-mounted camera is unusable with dense hair grooms.
# Model a short head mount instead: above and slightly in front of the
# crown, so hair remains a lower-edge cue rather than filling the view.
anchor = crown + forward * 0.11
location = outside_surface(anchor, up, vertices, 0.14, 0.16, 0.18)
elif mount == "chest":
anchor = key["shoulder_mid"] - up * 0.18
location = outside_surface(anchor, forward, vertices, 0.22, 0.055, 0.12)
elif mount == "left_arm":
anchor = key["left_shoulder"] * 0.58 + key["left_elbow"] * 0.42
extrusion = unit(0.75 * left + 0.66 * forward, tuple(forward))
location = outside_surface(anchor, extrusion, vertices, 0.095, 0.04, 0.07)
elif mount == "right_arm":
anchor = key["right_shoulder"] * 0.58 + key["right_elbow"] * 0.42
extrusion = unit(-0.75 * left + 0.66 * forward, tuple(forward))
location = outside_surface(anchor, extrusion, vertices, 0.095, 0.04, 0.07)
else:
raise KeyError(mount)
yaw = math.radians(float(spec["yaw"]))
pitch = math.radians(float(spec["pitch"]))
direction = unit(forward + math.tan(yaw) * (-left) + math.tan(pitch) * up, tuple(forward))
return location, direction
def set_camera(cam: bpy.types.Object, location: np.ndarray, direction: np.ndarray, spec: dict) -> None:
cam.location = tuple(float(v) for v in location)
look = mathutils.Vector(tuple(float(v) for v in direction)).to_track_quat("-Z", "Y")
local_roll = mathutils.Quaternion((0.0, 0.0, 1.0), math.radians(float(spec["roll"])))
cam.rotation_mode = "QUATERNION"
cam.rotation_quaternion = look @ local_roll
cam.data.type = "PERSP"
cam.data.sensor_fit = "HORIZONTAL"
cam.data.angle = math.radians(float(spec["fov"]))
cam.data.shift_x = 0.0
cam.data.shift_y = 0.0
# A face-mounted camera looking steeply down can otherwise see the mouth or
# scalp only a few centimetres behind its optical centre. Clip that local
# self-geometry while retaining hands, which are substantially farther away.
cam.data.clip_start = 0.10 if spec["mount"] == "eyes" else 0.01
cam.data.clip_end = 100.0
def fit_hand_box_fov(
cam: bpy.types.Object,
points_world: np.ndarray,
width: int,
height: int,
minimum_fov: float = 65.0,
maximum_fov: float = 100.0,
padding: float = 1.28,
) -> dict:
inverse = cam.matrix_world.inverted()
local = np.asarray([tuple(inverse @ mathutils.Vector(tuple(point))) for point in points_world], dtype=np.float64)
depth = -local[:, 2]
if np.any(depth <= cam.data.clip_start):
return {"fits": False, "reason": "hand_box_crosses_camera_plane", "fov_degrees": maximum_fov}
horizontal_tangent = float(np.max(np.abs(local[:, 0]) / depth))
vertical_tangent = float(np.max(np.abs(local[:, 1]) / depth))
aspect = float(width) / float(height)
required_tangent = padding * max(horizontal_tangent, aspect * vertical_tangent)
required_fov = math.degrees(2.0 * math.atan(required_tangent))
selected_fov = float(np.clip(required_fov, minimum_fov, maximum_fov))
cam.data.angle = math.radians(selected_fov)
return {
"fits": required_fov <= maximum_fov + 1e-6,
"required_fov_degrees": required_fov,
"fov_degrees": selected_fov,
"range_degrees": [minimum_fov, maximum_fov],
"padding_factor": padding,
}
def make_occluders() -> dict[str, bpy.types.Object]:
objects = {}
bpy.ops.mesh.primitive_uv_sphere_add(segments=24, ring_count=12, radius=1.0)
objects["sphere"] = bpy.context.object
bpy.ops.mesh.primitive_cube_add(size=2.0)
objects["cube"] = bpy.context.object
bpy.ops.mesh.primitive_cylinder_add(vertices=24, radius=1.0, depth=2.0)
objects["cylinder"] = bpy.context.object
colors = {"sphere": (0.08, 0.25, 0.8, 1.0), "cube": (0.8, 0.18, 0.06, 1.0), "cylinder": (0.12, 0.65, 0.18, 1.0)}
for name, obj in objects.items():
obj.name = f"EGO_PREVIEW_OCCLUDER_{name.upper()}"
mat = bpy.data.materials.new(f"EgoPreviewOccluder_{name}")
mat.diffuse_color = colors[name]
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
output = nodes.new("ShaderNodeOutputMaterial")
shader = nodes.new("ShaderNodeBsdfPrincipled")
texcoord = nodes.new("ShaderNodeTexCoord")
noise = nodes.new("ShaderNodeTexNoise")
noise.inputs["Scale"].default_value = 5.5 if name == "sphere" else 8.0
noise.inputs["Detail"].default_value = 4.0
noise.inputs["Roughness"].default_value = 0.68
ramp = nodes.new("ShaderNodeValToRGB")
base_color = np.asarray(colors[name][:3], dtype=np.float64)
dark = tuple(np.clip(base_color * 0.48, 0.0, 1.0)) + (1.0,)
light = tuple(np.clip(base_color * 1.22 + 0.04, 0.0, 1.0)) + (1.0,)
ramp.color_ramp.elements[0].color = dark
ramp.color_ramp.elements[1].color = light
bump = nodes.new("ShaderNodeBump")
bump.inputs["Strength"].default_value = 0.22
bump.inputs["Distance"].default_value = 0.055
links.new(texcoord.outputs["Generated"], noise.inputs["Vector"])
links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
links.new(ramp.outputs["Color"], shader.inputs["Base Color"])
links.new(noise.outputs["Fac"], bump.inputs["Height"])
links.new(bump.outputs["Normal"], shader.inputs["Normal"])
links.new(shader.outputs["BSDF"], output.inputs["Surface"])
shader.inputs["Roughness"].default_value = 0.58 if name == "sphere" else 0.7
if "Metallic" in shader.inputs:
shader.inputs["Metallic"].default_value = 0.08 if name == "cylinder" else 0.0
obj.data.materials.append(mat)
if name in {"cube", "cylinder"}:
bevel = obj.modifiers.new("Small edge bevel", "BEVEL")
bevel.width = 0.10
bevel.segments = 3
else:
for polygon in obj.data.polygons:
polygon.use_smooth = True
obj.hide_render = True
obj.hide_viewport = True
return objects
def stable_rng(sample_id: str, view_id: str, extra_seed: int) -> tuple[random.Random, int]:
digest = hashlib.sha256(f"{sample_id}|{view_id}|{extra_seed}".encode("utf-8")).digest()
seed = int.from_bytes(digest[:8], "big", signed=False)
return random.Random(seed), seed
def sample_motion_blur_config(args: argparse.Namespace, sample_id: str) -> dict:
if args.motion_blur_shutter_min < 0.0 or args.motion_blur_shutter_max < args.motion_blur_shutter_min:
raise ValueError("Motion-blur shutter range must satisfy 0 <= min <= max")
rng, seed = stable_rng(sample_id, "motion_blur", args.motion_blur_seed)
shutter = rng.uniform(args.motion_blur_shutter_min, args.motion_blur_shutter_max)
return {
"enabled": True,
"engine": "BLENDER_EEVEE",
"shutter_frames": shutter,
"shutter_range_frames": [args.motion_blur_shutter_min, args.motion_blur_shutter_max],
"position": args.motion_blur_position,
"seed": seed,
"scope": "one stable value shared by every view of this sample",
}
def configure_occluder_material(obj: bpy.types.Object, rng: random.Random) -> dict:
material = obj.data.materials[0]
ramp = next(node for node in material.node_tree.nodes if node.type == "VALTORGB")
base_color = np.asarray([rng.uniform(0.08, 0.78) for _ in range(3)], dtype=np.float64)
# Avoid an indistinct neutral grey by forcing one moderately dominant channel.
base_color[rng.randrange(3)] = rng.uniform(0.58, 0.92)
dark = tuple(np.clip(base_color * rng.uniform(0.35, 0.58), 0.0, 1.0)) + (1.0,)
light = tuple(np.clip(base_color * rng.uniform(1.05, 1.30) + 0.035, 0.0, 1.0)) + (1.0,)
ramp.color_ramp.elements[0].color = dark
ramp.color_ramp.elements[1].color = light
material.diffuse_color = tuple(base_color) + (1.0,)
return {"base_color": base_color.tolist(), "dark_color": list(dark[:3]), "light_color": list(light[:3])}
def shape_scale(shape: str, size: float, rng: random.Random) -> list[float]:
if shape == "sphere":
return [size, size, size]
if shape == "cube":
return [size * rng.uniform(0.75, 1.05), size * rng.uniform(0.75, 1.18), size * rng.uniform(0.72, 1.08)]
return [size * rng.uniform(0.68, 0.88), size * rng.uniform(0.68, 0.88), size * rng.uniform(1.15, 1.55)]
def choose_occluder_config(
args: argparse.Namespace,
sample_id: str,
spec: dict,
selected_frames: list[int],
composition: dict,
activity_by_frame: dict,
joints: np.ndarray,
objects: dict[str, bpy.types.Object],
) -> dict:
rng, seed = stable_rng(sample_id, spec["id"], args.occluder_seed)
if args.force_occluder_mode == "auto":
if rng.random() >= args.occluder_probability:
mode = "none"
else:
mode = "attached_small" if rng.random() < args.attached_occluder_probability else "static_large"
else:
mode = args.force_occluder_mode
config = {"enabled": mode != "none", "mode": mode, "seed": seed}
if not selected_frames:
config.update({"enabled": False, "mode": "none", "disabled_reason": "no_feasible_camera_frames"})
return config
if mode == "none":
return config
shape = rng.choice(sorted(objects))
anchor_frame = selected_frames[len(selected_frames) // 2]
active_hands = activity_by_frame[anchor_frame]["active_hands"]
target_hand = rng.choice(active_hands)
# Blender primitive scale is a radius/half-extent. Attached objects must
# remain genuinely small at arm-mounted camera distances; static objects
# may be larger because they do not chase the hand through the sequence.
size = rng.uniform(0.008, 0.016) if mode == "attached_small" else rng.uniform(0.045, 0.085)
rotation = [rng.uniform(-0.6, 0.6), rng.uniform(-0.6, 0.6), rng.uniform(-math.pi, math.pi)]
config.update({
"shape": shape,
"target_hand": target_hand,
"anchor_frame": anchor_frame,
"scale": shape_scale(shape, size, rng),
"rotation_euler": rotation,
"material": configure_occluder_material(objects[shape], rng),
})
if mode == "attached_small":
angle = rng.uniform(0.0, math.tau)
radial_offset = rng.uniform(0.026, 0.048)
config["body_basis_offset_meters"] = [
math.cos(angle) * radial_offset,
math.sin(angle) * radial_offset,
rng.uniform(0.006, 0.020),
]
else:
anchor_joints = np.asarray(joints[anchor_frame])
hand_points = anchor_joints[HAND_SLICES[target_hand]]
hand_center = 0.5 * (hand_points.min(axis=0) + hand_points.max(axis=0))
camera_location = np.asarray(composition[anchor_frame][0])
left, up, _, _ = body_basis(anchor_joints)
position = camera_location + rng.uniform(0.48, 0.72) * (hand_center - camera_location)
position += left * rng.uniform(-0.10, 0.10) + up * rng.uniform(-0.07, 0.07)
config["location_world"] = position.tolist()
return config
def update_occluder(objects: dict, config: dict, joints: np.ndarray) -> tuple[bpy.types.Object | None, dict]:
for obj in objects.values():
obj.hide_render = True
obj.hide_viewport = True
if not config.get("enabled"):
return None, {"enabled": False, "mode": "none"}
shape = config["shape"]
obj = objects[shape]
obj.hide_render = False
obj.hide_viewport = False
if config["mode"] == "attached_small":
points = np.asarray(joints[HAND_SLICES[config["target_hand"]]], dtype=np.float64)
hand_center = 0.5 * (points.min(axis=0) + points.max(axis=0))
left, up, forward, _ = body_basis(joints)
offset = config["body_basis_offset_meters"]
position = hand_center + left * offset[0] + up * offset[1] + forward * offset[2]
else:
position = np.asarray(config["location_world"], dtype=np.float64)
obj.location = tuple(float(v) for v in position)
obj.scale = tuple(config["scale"])
obj.rotation_euler = tuple(config["rotation_euler"])
return obj, {
"enabled": True,
"mode": config["mode"],
"shape": shape,
"target_hand": config["target_hand"],
"location_world": position.tolist(),
"scale": config["scale"],
"object": obj.name,
}
def joint_surface_tolerance(joint_index: int) -> float:
if joint_index < 17:
return 0.085
if joint_index < 23:
return 0.050
if joint_index < 91:
return 0.032
# Hand joints lie inside thin, highly articulated geometry. At grazing
# camera angles the entry surface can be several centimetres before the
# joint centre along the ray even though the finger is visibly exposed.
# Generated occluders are separate objects and therefore bypass this
# tolerance entirely; they remain exact ray hits.
return 0.060
def classify_joint_visibility(
scene: bpy.types.Scene,
camera: bpy.types.Object,
body: bpy.types.Object,
joints: np.ndarray,
) -> tuple[np.ndarray, list[dict]]:
"""Return COCO visibility: 0 outside, 1 occluded, 2 visible.
The scene ray includes the body, hair and generated occluder. A small
joint-class-specific tolerance treats the near skin surface around an
internal skeleton joint as visible rather than self-occluded.
"""
depsgraph = bpy.context.evaluated_depsgraph_get()
origin = mathutils.Vector(camera.matrix_world.translation)
visibility = np.zeros(len(joints), dtype=np.uint8)
hits = []
for index, point_array in enumerate(np.asarray(joints, dtype=np.float64)):
point = mathutils.Vector(tuple(float(value) for value in point_array))
projected = world_to_camera_view(scene, camera, point)
if projected.z <= 0.0 or projected.x < 0.0 or projected.x > 1.0 or projected.y < 0.0 or projected.y > 1.0:
hits.append({"state": "outside"})
continue
segment = point - origin
joint_distance = float(segment.length)
if joint_distance <= camera.data.clip_start:
hits.append({"state": "outside_near_clip"})
continue
direction = segment.normalized()
hit, location, _normal, _face, hit_object, _matrix = scene.ray_cast(
depsgraph, origin, direction, distance=joint_distance,
)
if not hit:
visibility[index] = 2
hits.append({"state": "visible", "hit": None})
continue
hit_distance = float((location - origin).length)
gap = joint_distance - hit_distance
is_body_surface = hit_object is not None and hit_object.name == body.name
if is_body_surface and gap <= joint_surface_tolerance(index):
visibility[index] = 2
hits.append({"state": "visible", "hit": hit_object.name, "surface_gap_meters": gap})
else:
visibility[index] = 1
hits.append({
"state": "occluded",
"hit": hit_object.name if hit_object is not None else None,
"surface_gap_meters": gap,
})
return visibility, hits
def classify_visibility_with_saved_camera(
scene: bpy.types.Scene,
camera: bpy.types.Object,
body: bpy.types.Object,
joints: np.ndarray,
intrinsics: np.ndarray,
width: int,
height: int,
) -> np.ndarray:
"""Ray-cast V for an old fixed portrait camera without re-rendering it."""
depsgraph = bpy.context.evaluated_depsgraph_get()
origin = mathutils.Vector(camera.matrix_world.translation)
inverse = np.asarray(camera.matrix_world.inverted(), dtype=np.float64)
points = np.asarray(joints, dtype=np.float64)
homogeneous = np.concatenate((points, np.ones((len(points), 1))), axis=1)
local = homogeneous @ inverse.T
xyz = np.stack((local[:, 0], -local[:, 1], -local[:, 2]), axis=1)
safe_z = np.where(xyz[:, 2] > 1e-9, xyz[:, 2], np.nan)
u = intrinsics[0, 0] * xyz[:, 0] / safe_z + intrinsics[0, 2]
v = intrinsics[1, 1] * xyz[:, 1] / safe_z + intrinsics[1, 2]
visibility = np.zeros(len(points), dtype=np.uint8)
inside = (xyz[:, 2] > 0.0) & (u >= 0.0) & (u < width) & (v >= 0.0) & (v < height)
for index in np.flatnonzero(inside):
point = mathutils.Vector(tuple(float(value) for value in points[index]))
segment = point - origin
joint_distance = float(segment.length)
if joint_distance <= 1e-8:
continue
hit, location, _normal, _face, hit_object, _matrix = scene.ray_cast(
depsgraph, origin, segment.normalized(), distance=joint_distance,
)
if not hit:
visibility[index] = 2
continue
gap = joint_distance - float((location - origin).length)
is_body_surface = hit_object is not None and hit_object.name == body.name
visibility[index] = 2 if is_body_surface and gap <= joint_surface_tolerance(index) else 1
return visibility
def export_portrait_visibility(
path: Path,
scene: bpy.types.Scene,
camera: bpy.types.Object,
body: bpy.types.Object,
joints: np.ndarray,
occluders: dict[str, bpy.types.Object],
camera_json: Path,
) -> None:
saved = json.loads(camera_json.read_text(encoding="utf-8"))
for obj in occluders.values():
obj.hide_render = True
obj.hide_viewport = True
camera.animation_data_clear()
if camera.data.animation_data is not None:
camera.data.animation_data_clear()
camera.matrix_world = mathutils.Matrix(saved["camera_matrix_world"])
intrinsics = np.asarray(saved["K"], dtype=np.float64)
width = int(saved["image_width"])
height = int(saved["image_height"])
result = []
for frame_index in range(joints.shape[0]):
scene.frame_set(frame_index)
bpy.context.view_layer.update()
result.append(classify_visibility_with_saved_camera(
scene, camera, body, np.asarray(joints[frame_index]), intrinsics, width, height,
))
np.save(path, np.asarray(result, dtype=np.uint8))
print(f"[OK] Old portrait 0/1/2 visibility -> {path}", flush=True)
def active_hand_visibility_summary(visibility: np.ndarray, visibility_hits: list[dict], active_hands: list[str]) -> dict:
summary = {}
for name in active_hands:
hand_slice = HAND_SLICES[name]
values = visibility[hand_slice]
hand_hits = visibility_hits[hand_slice]
summary[name] = {
"visible": int(np.count_nonzero(values == 2)),
"occluded": int(np.count_nonzero(values == 1)),
"outside": int(np.count_nonzero(values == 0)),
"occluded_by_generated_object": sum(
1 for hit in hand_hits
if str(hit.get("hit") or "").startswith("EGO_PREVIEW_OCCLUDER_")
),
}
return summary
def set_all_animation_linear() -> None:
for action in bpy.data.actions:
if hasattr(action, "fcurves"):
fcurves = list(action.fcurves)
else:
fcurves = []
for layer in action.layers:
for strip in layer.strips:
for channelbag in strip.channelbags:
fcurves.extend(channelbag.fcurves)
for fcurve in fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = "LINEAR"
def build_vertex_shape_key_animation(body: bpy.types.Object, vertices: np.ndarray) -> dict:
"""Create continuous deformation animation so EEVEE receives mesh velocity."""
if body.data.shape_keys is not None:
raise RuntimeError("Motion-blur preview expects a body without existing shape keys")
body.shape_key_add(name="Basis", from_mix=False)
for frame_index in range(vertices.shape[0]):
key = body.shape_key_add(name=f"Motion_{frame_index:06d}", from_mix=False)
key.data.foreach_set("co", np.asarray(vertices[frame_index], dtype=np.float32).reshape(-1))
for key_frame, value in (
(frame_index - 1, 0.0),
(frame_index, 1.0),
(frame_index + 1, 0.0),
):
key.value = value
key.keyframe_insert(data_path="value", frame=key_frame)
key.value = 0.0
return {
"method": "per_frame_absolute_shape_keys_linear_crossfade",
"frame_count": int(vertices.shape[0]),
"vertex_count": int(vertices.shape[1]),
}
def fastest_stride_aligned_hand_frame(joints: np.ndarray, stride: int) -> tuple[int, list[float]]:
hand_points = np.asarray(joints[:, 91:133], dtype=np.float64)
speed = np.zeros(joints.shape[0], dtype=np.float64)
if joints.shape[0] > 2:
displacement = np.linalg.norm(hand_points[2:] - hand_points[:-2], axis=2)
speed[1:-1] = np.mean(displacement, axis=1) * 0.5
candidates = [index for index in range(stride, joints.shape[0] - stride) if index % stride == 0]
if not candidates:
candidates = list(range(1, joints.shape[0] - 1))
target = max(candidates, key=lambda index: float(speed[index]))
return target, speed.tolist()
def composition_for_frame(
spec: dict,
vertices: np.ndarray,
joints: np.ndarray,
activity: dict,
camera: bpy.types.Object,
width: int,
height: int,
) -> tuple[tuple[np.ndarray, np.ndarray, dict] | None, dict | None]:
"""Fit one mounted camera to the active-hand box."""
hand_box = activity["box_points"]
location, mount_direction = camera_pose(spec, vertices, joints)
if spec["mount"] == "head_top":
direction = mount_direction
forward_dot = None
else:
box_center = 0.5 * (hand_box.min(axis=0) + hand_box.max(axis=0))
direction = unit(box_center - location, tuple(mount_direction))
_, _, anatomical_forward, _ = body_basis(joints)
forward_dot = float(np.dot(direction, anatomical_forward))
set_camera(camera, location, direction, spec)
bpy.context.view_layer.update()
if spec["mount"] == "head_top":
fit = {"fits": True, "mode": "fixed_head_top", "fov_degrees": float(spec["fov"])}
else:
fit = fit_hand_box_fov(camera, hand_box, width, height)
fit["forward_hemisphere_dot"] = forward_dot
if forward_dot < 0.02:
fit["fits"] = False
fit["reason"] = "hands_require_camera_to_look_back_into_body"
return ((location, direction, fit), None) if fit["fits"] else (None, fit)
def keyframe_formal_view_animation(
scene: bpy.types.Scene,
camera: bpy.types.Object,
spec: dict,
vertices: np.ndarray,
joints: np.ndarray,
composition: dict,
hair_objects: list[bpy.types.Object],
hair_meta: dict,
rest_vertices: np.ndarray,
occluders: dict[str, bpy.types.Object],
occluder_config: dict,
width: int,
height: int,
) -> None:
"""Animate camera, hair and an attached occluder for temporal blur."""
camera.animation_data_clear()
if camera.data.animation_data is not None:
camera.data.animation_data_clear()
for obj in occluders.values():
obj.animation_data_clear()
camera.rotation_mode = "QUATERNION"
full_composition = dict(composition)
for frame_index in range(vertices.shape[0]):
if frame_index in full_composition:
continue
activity = hand_activity(np.asarray(joints[frame_index]))
if not activity["valid"]:
continue
result, _ = composition_for_frame(
spec, np.asarray(vertices[frame_index]), np.asarray(joints[frame_index]),
activity, camera, width, height,
)
if result is not None:
full_composition[frame_index] = result
feasible = sorted(full_composition)
if not feasible:
return
for frame_index in range(vertices.shape[0]):
current_vertices = np.asarray(vertices[frame_index])
current_joints = np.asarray(joints[frame_index])
# Selected frames use their exact accepted fit. Between them, use the
# nearest accepted fit so shutter interpolation remains well-defined.
nearest = min(feasible, key=lambda value: abs(value - frame_index))
location, direction, fit = full_composition.get(frame_index, full_composition[nearest])
set_camera(camera, location, direction, spec)
camera.data.angle = math.radians(float(fit["fov_degrees"]))
camera.keyframe_insert(data_path="location", frame=frame_index)
camera.keyframe_insert(data_path="rotation_quaternion", frame=frame_index)
# `Camera.angle` is a derived, non-animatable RNA property in Blender
# 5.1. Setting angle above updates the physical lens; keyframe that
# animatable value to preserve the per-frame fitted FOV.
camera.data.keyframe_insert(data_path="lens", frame=frame_index)
base.update_hair_transform(hair_objects, hair_meta, rest_vertices, current_vertices)
for hair in hair_objects:
hair.rotation_mode = "QUATERNION"
hair.keyframe_insert(data_path="location", frame=frame_index)
hair.keyframe_insert(data_path="rotation_quaternion", frame=frame_index)
hair.keyframe_insert(data_path="scale", frame=frame_index)
active, _ = update_occluder(occluders, occluder_config, current_joints)
if active is not None and occluder_config.get("mode") == "attached_small":
active.keyframe_insert(data_path="location", frame=frame_index)
active.keyframe_insert(data_path="rotation_euler", frame=frame_index)
active.keyframe_insert(data_path="scale", frame=frame_index)
set_all_animation_linear()
scene.frame_start = 0
scene.frame_end = int(vertices.shape[0]) - 1
def render_motion_blur_comparison(
args: argparse.Namespace,
scene: bpy.types.Scene,
body: bpy.types.Object,
camera: bpy.types.Object,
vertices: np.ndarray,
joints: np.ndarray,
hair_objects: list[bpy.types.Object],
hair_meta: dict,
rest_vertices: np.ndarray,
) -> None:
for obj in bpy.data.objects:
if obj.name.startswith("EGO_PREVIEW_OCCLUDER_"):
obj.hide_render = True
obj.hide_viewport = True
animation_meta = build_vertex_shape_key_animation(body, vertices)
head_spec = next(spec for spec in CAMERA_SPECS if spec["mount"] == "head_top")
camera.rotation_mode = "QUATERNION"
for hair in hair_objects:
hair.rotation_mode = "QUATERNION"
for frame_index in range(vertices.shape[0]):
current_vertices = np.asarray(vertices[frame_index])
current_joints = np.asarray(joints[frame_index])
location, direction = camera_pose(head_spec, current_vertices, current_joints)
set_camera(camera, location, direction, head_spec)
camera.keyframe_insert(data_path="location", frame=frame_index)
camera.keyframe_insert(data_path="rotation_quaternion", frame=frame_index)
base.update_hair_transform(hair_objects, hair_meta, rest_vertices, current_vertices)
for hair in hair_objects:
hair.keyframe_insert(data_path="location", frame=frame_index)
hair.keyframe_insert(data_path="rotation_quaternion", frame=frame_index)
hair.keyframe_insert(data_path="scale", frame=frame_index)
set_all_animation_linear()
target_frame, speed = fastest_stride_aligned_hand_frame(joints, args.stride)
shutters = [float(value.strip()) for value in args.motion_blur_shutters.split(",") if value.strip()]
if not shutters:
raise ValueError("--motion-blur-shutters must contain at least one value")
scene.frame_start = 0
scene.frame_end = int(vertices.shape[0]) - 1
scene.frame_set(target_frame)
scene.render.motion_blur_position = args.motion_blur_position
output_dir = args.out_dir / "motion_blur_comparison"
output_dir.mkdir(parents=True, exist_ok=True)
for stale in output_dir.glob("*.png"):
stale.unlink()
variants = []
for shutter in shutters:
enabled = shutter > 0.0
scene.render.use_motion_blur = enabled
if enabled:
scene.render.motion_blur_shutter = shutter
label = "off" if not enabled else f"shutter_{shutter:g}"
output_path = output_dir / f"frame_{target_frame:06d}_{label}.png"
scene.render.filepath = str(output_path)
bpy.ops.render.render(write_still=True)
variants.append({"enabled": enabled, "shutter_frames": shutter, "path": str(output_path)})
print(f"[MOTION BLUR] {label} -> {output_path}", flush=True)
meta = {
"mode": "eevee_motion_blur_comparison",
"engine": scene.render.engine,
"target_frame": target_frame,
"target_mean_hand_displacement_per_source_frame_meters": speed[target_frame],
"position": args.motion_blur_position,
"variants": variants,
"animation": animation_meta,
"camera_view": head_spec,
"source_frame_count": int(vertices.shape[0]),
"source_stride_for_target_selection": args.stride,
"formal_per_sample_random_config": sample_motion_blur_config(args, args.sequence_dir.name),
}
(output_dir / "motion_blur_meta.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
print(f"[OK] Motion-blur comparison -> {output_dir}", flush=True)
def render(args: argparse.Namespace) -> None:
args.out_dir.mkdir(parents=True, exist_ok=True)
config_path = args.render_config or (args.sequence_dir / "render_config.json")
config = base.load_render_config(config_path)
sequence_meta = json.loads((args.sequence_dir / "meta.json").read_text(encoding="utf-8"))
vertices = np.load(args.sequence_dir / "vertices.npy", mmap_mode="r")
joints = np.load(args.sequence_dir / "coco133_3d.npy", mmap_mode="r")
sample_id = args.sample_id or args.sequence_dir.name
sample_blur_config = sample_motion_blur_config(args, sample_id)
if args.stride < 1:
raise ValueError("--stride must be >= 1")
if args.frames.strip().lower() == "auto":
requested = list(range(0, vertices.shape[0], args.stride))
else:
requested = [int(value.strip()) for value in args.frames.split(",") if value.strip()]
requested = [index for index in requested if index % args.stride == 0]
candidates = sorted(set(index for index in requested if 0 <= index < vertices.shape[0]))
activity_by_frame = {index: hand_activity(np.asarray(joints[index])) for index in candidates}
valid_candidates = [index for index in candidates if activity_by_frame[index]["valid"]]
if not valid_candidates:
raise ValueError("No requested stride-aligned frame contains an active hand in front of the body")
print(
f"[FILTER] candidate={len(candidates)} active={len(valid_candidates)} "
f"skipped_hanging={len(candidates) - len(valid_candidates)}",
flush=True,
)
gender = sequence_meta.get("gender", "neutral")
body = base.create_addon_render_body(
gender, sequence_meta.get("model_variant", "locked_head"), sequence_meta.get("uv_version", "UV_2023"), args.addon_dir,
)
uv_donor = base.find_uv_donor("SMPLX_UPRIGHT_CAMERA_REFERENCE", body)
if uv_donor is None:
raise RuntimeError("No matching SMPL-X UV donor found in template")
base.copy_active_uv_by_loop(uv_donor, body)
base.copy_vertex_groups_by_index(uv_donor, body, ["head"])
body.matrix_world = mathutils.Matrix.Identity(4)
base.validate_topology(body, args.sequence_dir, expected_vertex_count=vertices.shape[1])
base.hide_other_body_meshes(body, expected_vertex_count=vertices.shape[1])
manifest = base.load_manifest(args.manifest)
texture_item = config.get("texture_item")
selected_texture = None
if texture_item:
selected_texture = base.apply_texture_item(body, texture_item, "BASE_COLOR_IMAGE")
elif manifest.get("texture_items"):
selected_texture = base.apply_texture_item(body, manifest["texture_items"][0], "BASE_COLOR_IMAGE")
# Normal still previews do not have a temporal deformation graph. Only
# enable blur in comparison mode, where the complete shape-key animation is
# constructed below. The formal dataset renderer will use the same graph.
temporal_render = bool(args.motion_blur_comparison or args.formal_dataset)
base.set_render_settings(args.width, args.height, "BLENDER_EEVEE", args.fps, temporal_render)
scene = bpy.context.scene
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGB"
scene.render.image_settings.color_depth = "8"
scene.render.image_settings.compression = args.png_compression
scene.render.film_transparent = False
world_meta = base.apply_world_config(config)
base.hide_background_planes()
base.hide_scene_lights()
rest_vertices = base.mesh_vertices_array(body)
head_indices = portrait.weighted_vertex_group_indices(body, "head")
hair_args = SimpleNamespace(
disable_hair=args.disable_hair,
hair_enabled=not args.disable_hair,
hair_unit_scale=0.01,
hair_head_indices=None,
hair_vertical_offset=0.0,
hair_shader_mode="portrait_matte",
)
hair_objects, hair_meta = base.import_hair_objects(config, hair_args, rest_vertices, anchor_indices=head_indices)
if hair_objects:
hair_meta["scalp_alignment"] = portrait.calibrate_hair_to_scalp(
hair_objects, hair_meta, rest_vertices, np.asarray(vertices[0]), head_indices, 0.004, 0.05,
)
camera = base.ensure_camera("EGO_PREVIEW_CAMERA")
scene.camera = camera
occluders = make_occluders()
if args.motion_blur_comparison:
render_motion_blur_comparison(
args, scene, body, camera, vertices, joints,
hair_objects, hair_meta, rest_vertices,
)
return
animation_meta = None
if args.formal_dataset:
animation_meta = build_vertex_shape_key_animation(body, vertices)
scene.render.use_motion_blur = True
scene.render.motion_blur_shutter = float(sample_blur_config["shutter_frames"])
scene.render.motion_blur_position = str(sample_blur_config["position"])
metadata = {
"mode": "h2smv_egocentric_v2" if args.formal_dataset else "egocentric_camera_preview",
"sequence_dir": str(args.sequence_dir),
"sample_id": sample_id,
"resolution": [args.width, args.height],
"active_source_frames": valid_candidates,
"source_stride": args.stride,
"candidate_frame_count": len(candidates),
"active_candidate_count": len(valid_candidates),
"skipped_inactive_frames": [index for index in candidates if index not in valid_candidates],
"motion_blur_requested": bool(args.formal_dataset),
"motion_blur": sample_blur_config if args.formal_dataset else {"enabled": False},
"animation": animation_meta,
"views": [],
"world": world_meta,
"hair": hair_meta,
"selected_texture": str(selected_texture) if selected_texture else None,
}
for spec in CAMERA_SPECS:
view_dir = args.out_dir / spec["id"]
view_dir.mkdir(parents=True, exist_ok=True)
for stale in view_dir.glob("frame_*.png"):
stale.unlink()
# First scan all stride-aligned active frames without rendering. A
# non-head camera is usable only if it can face the complete active-hand
# box while staying in the body's forward hemisphere and within 100 FOV.
composition = {}
rejected = {}
for source_index in valid_candidates:
result, rejection = composition_for_frame(
spec, np.asarray(vertices[source_index]), np.asarray(joints[source_index]),
activity_by_frame[source_index], camera, args.width, args.height,
)
if result is not None:
composition[source_index] = result
else:
rejected[source_index] = rejection
selected_frames = evenly_spaced(sorted(composition), args.max_preview_frames)
print(
f"[VIEW FILTER] {spec['id']} feasible={len(composition)}/{len(valid_candidates)} "
f"selected={selected_frames}",
flush=True,
)
occluder_config = choose_occluder_config(
args, sample_id, spec, selected_frames, composition,
activity_by_frame, joints, occluders,
)
if args.formal_dataset and selected_frames:
keyframe_formal_view_animation(
scene, camera, spec, vertices, joints, composition,
hair_objects, hair_meta, rest_vertices, occluders, occluder_config,
args.width, args.height,
)
view_meta = {
"spec": spec,
"selected_source_frames": selected_frames,
"rejected_frames": rejected,
"occluder_config": occluder_config,
"visibility_rejected_frames": {},
"frames": [],
}
accepted_render_frames = []
for output_index, source_index in enumerate(selected_frames):
current_vertices = np.asarray(vertices[source_index])
current_joints = np.asarray(joints[source_index])
activity = activity_by_frame[source_index]
hand_box = activity["box_points"]
location, direction, fov_fit = composition[source_index]
scene.frame_set(source_index if args.formal_dataset else output_index)
if not args.formal_dataset:
base.set_mesh_vertices(body, current_vertices)
base.update_hair_transform(hair_objects, hair_meta, rest_vertices, current_vertices)
set_camera(camera, location, direction, spec)
camera.data.angle = math.radians(float(fov_fit["fov_degrees"]))
active_occluder, occluder_meta = update_occluder(occluders, occluder_config, current_joints)
bpy.context.view_layer.update()
visibility, visibility_hits = classify_joint_visibility(scene, camera, body, current_joints)
hand_visibility = active_hand_visibility_summary(visibility, visibility_hits, activity["active_hands"])
unusable = [
name for name, values in hand_visibility.items()
if values["visible"] < args.min_visible_hand_joints
]
usable = [name for name in activity["active_hands"] if name not in unusable]
if not usable:
view_meta["visibility_rejected_frames"][source_index] = {
"reason": "all_active_hands_fully_or_almost_fully_hidden",
"unusable_hands": unusable,
"hand_visibility": hand_visibility,
"occluder": occluder_meta,
}
print(
f"[VISIBILITY SKIP] {spec['id']} source_frame={source_index} "
f"unusable_hands={unusable}",
flush=True,
)
continue
if args.formal_dataset:
accepted_render_frames.append(source_index)
else:
scene.render.filepath = str(view_dir / f"frame_{source_index:06d}.png")
bpy.ops.render.render(write_still=True)
frame_meta = {
"source_frame": source_index,
"camera_location_world": location.tolist(),
"camera_direction_world": direction.tolist(),
"camera_matrix_world": [[float(value) for value in row] for row in camera.matrix_world],
"hand_activity": {key: value for key, value in activity.items() if key != "box_points"},
"hand_box_world": {
"min": hand_box.min(axis=0).tolist(),
"max": hand_box.max(axis=0).tolist(),
},
"fov_fit": fov_fit,
"occluder": occluder_meta,
"joint_visibility_coco": visibility.tolist(),
"active_hand_visibility": hand_visibility,
}
if args.debug_visibility_hits:
frame_meta["joint_visibility_hits"] = visibility_hits
view_meta["frames"].append(frame_meta)
if not args.formal_dataset:
print(f"[PREVIEW] {spec['id']} source_frame={source_index} -> {scene.render.filepath}", flush=True)
if args.formal_dataset:
view_meta["animation_render"] = render_animation_runs(
scene, view_dir, accepted_render_frames, args.stride,
)
metadata["views"].append(view_meta)
(args.out_dir / "preview_meta.json").write_text(json.dumps(metadata, indent=2, ensure_ascii=False), encoding="utf-8")
total = sum(len(view["frames"]) for view in metadata["views"])
if args.formal_dataset and args.portrait_camera_json is not None:
export_portrait_visibility(
args.sequence_dir / "portrait_visibility_v2.npy", scene, camera, body,
joints, occluders, args.portrait_camera_json,
)
print(f"[OK] Rendered {total} feasible preview frames across {len(CAMERA_SPECS)} camera candidates -> {args.out_dir}", flush=True)
if __name__ == "__main__":
render(parse_args())
#!/usr/bin/env python3
"""Render labelled egocentric camera candidates from an existing prepared sequence.
It supports both lightweight still previews and the formal V2 dataset mode.
Formal mode builds a continuous deformation/camera animation so EEVEE motion
blur is real, then renders only the requested stride-aligned usable frames.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import random
import sys
from pathlib import Path
from types import SimpleNamespace
import bpy
import mathutils
import numpy as np
from bpy_extras.object_utils import world_to_camera_view
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
import render_blender_sequence as base
import render_portrait_png_sequence as portrait
def parse_args() -> argparse.Namespace:
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
parser = argparse.ArgumentParser()
parser.add_argument("--sequence-dir", required=True, type=Path)
parser.add_argument("--out-dir", required=True, type=Path)
parser.add_argument("--manifest", required=True, type=Path)
parser.add_argument("--addon-dir", required=True, type=Path)
parser.add_argument("--render-config", type=Path)
parser.add_argument("--sample-id", default=None)
parser.add_argument("--portrait-camera-json", type=Path)
parser.add_argument("--frames", default="auto", help="Comma-separated source frames, or 'auto'.")
parser.add_argument("--stride", type=int, default=4)
parser.add_argument("--max-preview-frames", type=int, default=8)
parser.add_argument("--width", type=int, default=768)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument("--fps", type=int, default=16)
parser.add_argument("--png-compression", type=int, default=15)
parser.add_argument("--disable-hair", action="store_true")
parser.add_argument("--occluder-probability", type=float, default=0.45)
parser.add_argument("--attached-occluder-probability", type=float, default=0.70)
parser.add_argument("--force-occluder-mode", choices=["auto", "none", "attached_small", "static_large"], default="auto")
parser.add_argument("--min-visible-hand-joints", type=int, default=3)
parser.add_argument("--occluder-seed", type=int, default=0)
parser.add_argument("--debug-visibility-hits", action="store_true")
parser.add_argument("--motion-blur-comparison", action="store_true")
parser.add_argument("--motion-blur-shutters", default="0,0.25,0.5,1.0")
parser.add_argument("--motion-blur-position", choices=["START", "CENTER", "END"], default="CENTER")
parser.add_argument("--motion-blur-shutter-min", type=float, default=0.5)
parser.add_argument("--motion-blur-shutter-max", type=float, default=1.0)
parser.add_argument("--motion-blur-seed", type=int, default=0)
parser.add_argument("--formal-dataset", action="store_true")
return parser.parse_args(argv)
def unit(vector: np.ndarray, fallback: tuple[float, float, float]) -> np.ndarray:
length = float(np.linalg.norm(vector))
if length < 1e-8:
return np.asarray(fallback, dtype=np.float64)
return np.asarray(vector, dtype=np.float64) / length
def body_basis(joints: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, dict]:
"""Return left, up and anatomical forward axes from COCO body joints."""
left_shoulder = np.asarray(joints[5], dtype=np.float64)
right_shoulder = np.asarray(joints[6], dtype=np.float64)
shoulder_mid = 0.5 * (left_shoulder + right_shoulder)
eye_mid = 0.5 * (np.asarray(joints[1]) + np.asarray(joints[2]))
# Prepared H2SMV bodies are upright in a Z-up world. Do not derive the
# camera's up axis from eye-minus-shoulder: torso lean would then tilt the
# mount extrusion downward and can put an eye/chest camera back in the mesh.
up = np.asarray((0.0, 0.0, 1.0), dtype=np.float64)
shoulder_axis = left_shoulder - right_shoulder
shoulder_axis[2] = 0.0
left = unit(shoulder_axis, (1.0, 0.0, 0.0))
forward = unit(np.cross(left, up), (0.0, -1.0, 0.0))
nose_direction = np.asarray(joints[0], dtype=np.float64) - eye_mid
if float(np.dot(forward, nose_direction)) < 0.0:
forward = -forward
return left, up, forward, {
"shoulder_mid": shoulder_mid,
"eye_mid": eye_mid,
"left_shoulder": left_shoulder,
"right_shoulder": right_shoulder,
"left_elbow": np.asarray(joints[7], dtype=np.float64),
"right_elbow": np.asarray(joints[8], dtype=np.float64),
"left_wrist": np.asarray(joints[9], dtype=np.float64),
"right_wrist": np.asarray(joints[10], dtype=np.float64),
}