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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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
#!/usr/bin/env python3
"""Shared Blender rendering helpers for the SMPL-X COCO pipeline."""

from __future__ import annotations

import json
import shutil
import subprocess
from pathlib import Path

import bpy
import mathutils
import numpy as np


def parse_csv_values(value: str | None) -> list[str]:
    if not value:
        return []
    return [item.strip() for item in value.split(",") if item.strip()]


def encode_video_ffmpeg(frame_paths: list[Path], output_mp4: Path, fps: int, crf: int) -> bool:
    """Encode an ordered list of PNG frames to MP4 without assuming frame numbers are contiguous."""
    if not frame_paths:
        raise ValueError("No frames were provided for video encoding.")

    ffmpeg = shutil.which("ffmpeg")
    if ffmpeg is None:
        print("[WARN] ffmpeg not found; skip MP4 encoding.")
        return False

    output_mp4.parent.mkdir(parents=True, exist_ok=True)
    concat_path = output_mp4.with_suffix(".ffconcat.txt")
    with open(concat_path, "w", encoding="utf-8") as f:
        f.write("ffconcat version 1.0\n")
        for frame_path in frame_paths:
            safe_path = str(frame_path.resolve()).replace("\\", "/").replace("'", "'\\''")
            f.write(f"file '{safe_path}'\n")

    encoders = subprocess.run(
        [ffmpeg, "-hide_banner", "-encoders"],
        check=False,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    ).stdout
    if "libx264" in encoders:
        codec_args = ["-c:v", "libx264", "-preset", "medium", "-crf", str(crf)]
    elif "h264_nvenc" in encoders:
        codec_args = ["-c:v", "h264_nvenc", "-preset", "p4", "-cq", str(crf), "-b:v", "0"]
    elif "libopenh264" in encoders:
        codec_args = ["-c:v", "libopenh264", "-b:v", "8M"]
    else:
        print(f"[ERROR] {ffmpeg} has no supported H.264 encoder (libx264, h264_nvenc, or libopenh264).")
        return False

    cmd = [
        ffmpeg,
        "-y",
        "-hide_banner",
        "-loglevel",
        "error",
        "-r",
        str(fps),
        "-f",
        "concat",
        "-safe",
        "0",
        "-i",
        str(concat_path),
        *codec_args,
        "-pix_fmt",
        "yuv420p",
        str(output_mp4),
    ]
    print(f"[INFO] Encoding {output_mp4}")
    try:
        subprocess.run(cmd, check=True)
        return True
    except subprocess.CalledProcessError as exc:
        print(f"[ERROR] ffmpeg failed for {output_mp4}: {exc}")
        return False


def material_image_path(obj: bpy.types.Object) -> Path | None:
    """Return the first image texture path used by the object's first material."""
    if not obj.data.materials:
        return None
    material = obj.data.materials[0]
    if not material.use_nodes or material.node_tree is None:
        return None
    for node in material.node_tree.nodes:
        if node.type == "TEX_IMAGE" and node.image is not None and node.image.filepath:
            return Path(bpy.path.abspath(node.image.filepath))
    return None


def create_textured_emission_material(texture_path: Path, strength: float) -> bpy.types.Material:
    """Create a flat texture material that is independent of scene lighting."""
    mat = bpy.data.materials.new("HandOnlyFlatTextureMaterial")
    mat.use_nodes = True
    nt = mat.node_tree
    for node in list(nt.nodes):
        nt.nodes.remove(node)

    image = bpy.data.images.load(str(texture_path), check_existing=True)
    tex = nt.nodes.new(type="ShaderNodeTexImage")
    tex.image = image
    tex.extension = "EXTEND"
    emission = nt.nodes.new(type="ShaderNodeEmission")
    emission.inputs["Strength"].default_value = float(strength)
    output = nt.nodes.new(type="ShaderNodeOutputMaterial")
    nt.links.new(tex.outputs["Color"], emission.inputs["Color"])
    nt.links.new(emission.outputs["Emission"], output.inputs["Surface"])
    return mat


def create_white_emission_material() -> bpy.types.Material:
    mat = bpy.data.materials.new("HandOnlyMaskMaterial")
    mat.use_nodes = True
    nt = mat.node_tree
    for node in list(nt.nodes):
        nt.nodes.remove(node)
    emission = nt.nodes.new(type="ShaderNodeEmission")
    emission.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0)
    emission.inputs["Strength"].default_value = 1.0
    output = nt.nodes.new(type="ShaderNodeOutputMaterial")
    nt.links.new(emission.outputs["Emission"], output.inputs["Surface"])
    return mat


def create_depth_emission_material(near_depth: float, far_depth: float, invert: bool = False) -> bpy.types.Material:
    if far_depth <= near_depth:
        far_depth = near_depth + 1e-4

    mat = bpy.data.materials.new("HandOnlyDepthMaterial")
    mat.use_nodes = True
    nt = mat.node_tree
    for node in list(nt.nodes):
        nt.nodes.remove(node)

    camera_data = nt.nodes.new(type="ShaderNodeCameraData")
    map_range = nt.nodes.new(type="ShaderNodeMapRange")
    map_range.inputs["From Min"].default_value = float(near_depth)
    map_range.inputs["From Max"].default_value = float(far_depth)
    map_range.inputs["To Min"].default_value = 0.0 if invert else 1.0
    map_range.inputs["To Max"].default_value = 1.0 if invert else 0.0
    if "Clamp" in map_range.inputs:
        map_range.inputs["Clamp"].default_value = True

    emission = nt.nodes.new(type="ShaderNodeEmission")
    emission.inputs["Strength"].default_value = 1.0
    output = nt.nodes.new(type="ShaderNodeOutputMaterial")
    nt.links.new(camera_data.outputs["View Z Depth"], map_range.inputs["Value"])
    nt.links.new(map_range.outputs["Result"], emission.inputs["Color"])
    nt.links.new(emission.outputs["Emission"], output.inputs["Surface"])
    return mat


def save_black_background(transparent: bool = False) -> dict:
    """Set world/render background for reference passes and return restorable state."""
    scene = bpy.context.scene
    world = scene.world
    state = {
        "film_transparent": scene.render.film_transparent,
        "world_color": tuple(world.color) if world is not None else None,
        "world_use_nodes": world.use_nodes if world is not None else None,
        "world_nodes": [],
    }
    scene.render.film_transparent = bool(transparent)
    if world is not None:
        world.color = (0.0, 0.0, 0.0)
        if world.use_nodes and world.node_tree is not None:
            for node in world.node_tree.nodes:
                node_state = {"name": node.name, "inputs": []}
                for socket in node.inputs:
                    if not hasattr(socket, "default_value"):
                        continue
                    try:
                        saved = tuple(socket.default_value)
                    except TypeError:
                        saved = socket.default_value
                    node_state["inputs"].append((socket.name, saved))
                    if socket.name == "Color":
                        socket.default_value = (0.0, 0.0, 0.0, 1.0)
                    elif socket.name == "Strength":
                        socket.default_value = 0.0
                state["world_nodes"].append(node_state)
    return state


def restore_black_background(state: dict) -> None:
    scene = bpy.context.scene
    world = scene.world
    scene.render.film_transparent = state["film_transparent"]
    if world is None:
        return
    if state["world_color"] is not None:
        world.color = state["world_color"]
    if state["world_use_nodes"] is not None:
        world.use_nodes = state["world_use_nodes"]
    if world.use_nodes and world.node_tree is not None:
        by_name = {node.name: node for node in world.node_tree.nodes}
        for node_state in state["world_nodes"]:
            node = by_name.get(node_state["name"])
            if node is None:
                continue
            by_input = {socket.name: socket for socket in node.inputs}
            for input_name, saved in node_state["inputs"]:
                socket = by_input.get(input_name)
                if socket is not None and hasattr(socket, "default_value"):
                    socket.default_value = saved


def save_depth_color_management() -> dict:
    scene = bpy.context.scene
    view = scene.view_settings
    state = {
        "view_transform": view.view_transform,
        "look": view.look,
        "exposure": view.exposure,
        "gamma": view.gamma,
        "dither_intensity": scene.render.dither_intensity,
    }
    try:
        view.view_transform = "Standard"
    except TypeError:
        pass
    try:
        view.look = "None"
    except TypeError:
        pass
    view.exposure = 0.0
    view.gamma = 1.0
    scene.render.dither_intensity = 0.0
    return state


def restore_depth_color_management(state: dict) -> None:
    scene = bpy.context.scene
    view = scene.view_settings
    for name, value in state.items():
        if name == "dither_intensity":
            scene.render.dither_intensity = value
        else:
            try:
                setattr(view, name, value)
            except TypeError:
                pass


def load_hand_indices_from_json(path: Path, expected_vertex_count: int) -> dict:
    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    vertex_count = int(data.get("vertex_count", expected_vertex_count))
    if vertex_count != expected_vertex_count:
        raise ValueError(
            f"Hand index vertex_count mismatch: json has {vertex_count}, mesh has {expected_vertex_count}."
        )
    indices = sorted({int(index) for index in data.get("indices", [])})
    if not indices:
        raise ValueError(f"Hand index file has no indices: {path}")
    return {
        "source": str(path),
        "vertex_groups": data.get("vertex_groups", []),
        "indices": indices,
        "selected_vertex_count": len(indices),
    }


def load_hand_indices_from_vertex_groups(obj: bpy.types.Object, group_names: list[str]) -> dict:
    group_indices = {obj.vertex_groups[name].index for name in group_names if name in obj.vertex_groups}
    missing = [name for name in group_names if name not in obj.vertex_groups]
    if missing:
        raise KeyError(f"Missing hand vertex groups on {obj.name}: {', '.join(missing)}")

    selected: set[int] = set()
    for vertex in obj.data.vertices:
        if any(group.group in group_indices and group.weight > 0.0 for group in vertex.groups):
            selected.add(vertex.index)
    if not selected:
        raise ValueError(f"Hand vertex groups are empty on {obj.name}: {', '.join(group_names)}")
    return {
        "source": obj.name,
        "vertex_groups": group_names,
        "indices": sorted(selected),
        "selected_vertex_count": len(selected),
    }


def face_matches_hand(face: tuple[int, ...], hand_indices: set[int], rule: str) -> bool:
    count = sum(1 for index in face if index in hand_indices)
    if rule == "any":
        return count >= 1
    if rule == "all":
        return count == len(face)
    return count >= 2


def build_hand_mesh_from_body(
    body_obj: bpy.types.Object,
    hand_info: dict,
    face_rule: str,
    material: bpy.types.Material | None,
) -> tuple[bpy.types.Object, dict]:
    """Create a hand-only mesh with copied vertices, faces, UV loops, and material."""
    mesh = body_obj.data
    hand_indices = set(hand_info["indices"])
    kept_faces: list[tuple[int, ...]] = []
    source_poly_indices: list[int] = []
    used_indices: set[int] = set()

    for poly_index, poly in enumerate(mesh.polygons):
        face = tuple(poly.vertices)
        if face_matches_hand(face, hand_indices, face_rule):
            kept_faces.append(face)
            source_poly_indices.append(poly_index)
            used_indices.update(face)

    if not kept_faces:
        raise ValueError(f"No hand faces selected with rule={face_rule}.")

    ordered_indices = sorted(used_indices)
    index_map = {old: new for new, old in enumerate(ordered_indices)}
    vertices = [mesh.vertices[index].co.copy() for index in ordered_indices]
    faces = [tuple(index_map[index] for index in face) for face in kept_faces]

    hand_mesh = bpy.data.meshes.new("HandOnlyReferenceMeshData")
    hand_mesh.from_pydata(vertices, [], faces)
    hand_mesh.update()
    hand_obj = bpy.data.objects.new("HandOnlyReferenceMesh", hand_mesh)
    bpy.context.collection.objects.link(hand_obj)
    hand_obj.matrix_world = body_obj.matrix_world.copy()

    source_uv = mesh.uv_layers.active
    if source_uv is not None:
        hand_uv = hand_mesh.uv_layers.new(name=source_uv.name)
        for hand_poly_index, source_poly_index in enumerate(source_poly_indices):
            source_poly = mesh.polygons[source_poly_index]
            hand_poly = hand_mesh.polygons[hand_poly_index]
            for corner_index, hand_loop_index in enumerate(hand_poly.loop_indices):
                source_loop_index = source_poly.loop_indices[corner_index]
                hand_uv.data[hand_loop_index].uv = source_uv.data[source_loop_index].uv

    if material is not None:
        hand_mesh.materials.append(material)

    return hand_obj, {
        "source": hand_info["source"],
        "vertex_groups": hand_info.get("vertex_groups", []),
        "selected_vertex_count": hand_info["selected_vertex_count"],
        "mesh_vertex_count": len(ordered_indices),
        "mesh_face_count": len(kept_faces),
        "face_rule": face_rule,
        "source_vertex_indices": ordered_indices,
    }


def update_hand_mesh_vertices(
    hand_obj: bpy.types.Object,
    body_obj: bpy.types.Object,
    source_vertex_indices: list[int],
) -> None:
    source_mesh = body_obj.data
    hand_mesh = hand_obj.data
    coords = np.empty((len(source_vertex_indices), 3), dtype=np.float32)
    for new_index, source_index in enumerate(source_vertex_indices):
        coords[new_index] = source_mesh.vertices[source_index].co[:]
    hand_mesh.vertices.foreach_set("co", coords.reshape(-1))
    hand_mesh.update()


def compute_depth_range_for_frames(
    hand_obj: bpy.types.Object,
    body_obj: bpy.types.Object,
    source_vertex_indices: list[int],
    frame_indices: list[int],
    vertices: np.ndarray,
    set_body_vertices,
    margin_ratio: float,
) -> dict:
    camera = bpy.context.scene.camera
    if camera is None:
        raise RuntimeError("Cannot compute hand depth without an active camera.")

    depths: list[float] = []
    camera_inv = camera.matrix_world.inverted()
    for frame_idx in frame_indices:
        set_body_vertices(body_obj, np.asarray(vertices[frame_idx]))
        update_hand_mesh_vertices(hand_obj, body_obj, source_vertex_indices)
        bpy.context.view_layer.update()
        for vertex in hand_obj.data.vertices:
            world_co = hand_obj.matrix_world @ vertex.co
            camera_co = camera_inv @ world_co
            depth = -camera_co.z
            if depth > 0.0:
                depths.append(float(depth))

    if not depths:
        raise RuntimeError("Could not compute a positive camera-space hand depth range.")

    auto_near = min(depths)
    auto_far = max(depths)
    span = max(auto_far - auto_near, 1e-4)
    margin = max(0.0, float(margin_ratio)) * span
    return {
        "mode": "auto",
        "auto_near": auto_near,
        "auto_far": auto_far,
        "near": auto_near - margin,
        "far": auto_far + margin,
        "margin": margin,
    }


def blender_camera_intrinsics(
    cam_data: bpy.types.Camera,
    scene: bpy.types.Scene,
) -> tuple[list[list[float]], dict]:
    scale = scene.render.resolution_percentage / 100.0
    resolution_x = scene.render.resolution_x * scale
    resolution_y = scene.render.resolution_y * scale
    pixel_aspect_ratio = scene.render.pixel_aspect_y / scene.render.pixel_aspect_x

    sensor_fit = cam_data.sensor_fit
    if sensor_fit == "AUTO":
        sensor_fit = "HORIZONTAL" if resolution_x >= pixel_aspect_ratio * resolution_y else "VERTICAL"

    if sensor_fit == "VERTICAL":
        sensor_size = cam_data.sensor_height
        view_fac_px = pixel_aspect_ratio * resolution_y
    else:
        sensor_size = cam_data.sensor_width
        view_fac_px = resolution_x

    pixel_size_mm = sensor_size / cam_data.lens / view_fac_px
    fx = 1.0 / pixel_size_mm
    fy = 1.0 / pixel_size_mm / pixel_aspect_ratio
    cx = resolution_x * 0.5 - cam_data.shift_x * view_fac_px
    cy = resolution_y * 0.5 + cam_data.shift_y * view_fac_px / pixel_aspect_ratio

    K = [[float(fx), 0.0, float(cx)], [0.0, float(fy), float(cy)], [0.0, 0.0, 1.0]]
    meta = {
        "sensor_fit_resolved": sensor_fit,
        "sensor_size_mm": float(sensor_size),
        "view_fac_px": float(view_fac_px),
        "pixel_aspect_ratio_y_over_x": float(pixel_aspect_ratio),
    }
    return K, meta


def export_camera_calibration(
    camera_obj: bpy.types.Object,
    smplx_obj: bpy.types.Object,
    out_json_path: Path,
    image_width: int,
    image_height: int,
) -> None:
    """Export OpenCV-style camera intrinsics/extrinsics and SMPL-X world transform."""
    scene = bpy.context.scene
    cam_data = camera_obj.data

    K, intrinsics_meta = blender_camera_intrinsics(cam_data, scene)

    r_bcam_to_cv = mathutils.Matrix(((1, 0, 0), (0, -1, 0), (0, 0, -1)))
    world_to_bcam = camera_obj.matrix_world.inverted()
    r_world_to_cv = r_bcam_to_cv @ world_to_bcam.to_3x3()
    t_world_to_cv = r_bcam_to_cv @ world_to_bcam.translation

    def matrix_to_list(mat):
        return [[float(v) for v in row] for row in mat]

    out = {
        "image_width": int(image_width),
        "image_height": int(image_height),
        "K": K,
        "intrinsics_meta": intrinsics_meta,
        "R_world_to_cam": matrix_to_list(r_world_to_cv),
        "t_world_to_cam": [float(v) for v in t_world_to_cv],
        "camera_matrix_world": matrix_to_list(camera_obj.matrix_world),
        "smplx_matrix_world": matrix_to_list(smplx_obj.matrix_world),
        "camera_name": camera_obj.name,
        "smplx_object_name": smplx_obj.name,
        "coordinate_note": "OpenCV camera: +Z forward, X right, Y down. SMPL-X vertices are rendered in Blender world directly.",
    }

    out_json_path.parent.mkdir(parents=True, exist_ok=True)
    with open(out_json_path, "w", encoding="utf-8") as f:
        json.dump(out, f, indent=2)