File size: 4,530 Bytes
cb8518a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
from __future__ import annotations

import argparse
import pickle
import sys
from pathlib import Path

import bpy
import numpy as np


def parse_args() -> argparse.Namespace:
    argv_source = getattr(bpy.app, "argv", None)
    if argv_source is None:
        argv_source = sys.argv

    argv: list[str] = []
    if "--" in argv_source:
        argv = argv_source[argv_source.index("--") + 1 :]

    parser = argparse.ArgumentParser(description="Extract triangle meshes from a .blend/.glb/.gltf scene")
    parser.add_argument(
        "--input",
        default=None,
        help="Input scene path. If omitted, uses the file already opened by Blender.",
    )
    parser.add_argument("--output", required=True, help="Output pickle path")
    parser.add_argument(
        "--frame_mode",
        default="first_mid_last",
        help="Frame sampling mode: first_only, first_mid_last, last_only, or exact:<frame>",
    )
    return parser.parse_args(argv)


def load_input_scene(input_path: str | None) -> None:
    if not input_path:
        return

    path = Path(input_path).resolve()
    if not path.exists():
        raise FileNotFoundError(f"Input scene does not exist: {path}")

    ext = path.suffix.lower()
    if ext == ".blend":
        bpy.ops.wm.open_mainfile(filepath=str(path))
        return

    if ext in {".glb", ".gltf"}:
        bpy.ops.object.select_all(action="SELECT")
        bpy.ops.object.delete()
        bpy.ops.import_scene.gltf(filepath=str(path))
        return

    raise ValueError(f"Unsupported input scene extension: {path.suffix}")


def _parse_exact_frame(mode: str) -> int | None:
    if not mode.startswith("exact:"):
        return None
    raw = mode.split(":", 1)[1].strip()
    if not raw:
        raise ValueError("exact frame mode requires a frame number, e.g. exact:55")
    return int(raw)


def frame_indices(scene: bpy.types.Scene, mode: str) -> list[int]:
    start = int(scene.frame_start)
    end = int(scene.frame_end)
    if end < start:
        end = start

    exact = _parse_exact_frame(mode)
    if exact is not None:
        return [exact]

    if mode == "last_only":
        return [end]

    if mode == "first_only":
        return [start]

    if mode != "first_mid_last":
        raise ValueError(f"Unsupported frame_mode: {mode}")

    if start == end:
        return [start]

    mid = (start + end) // 2
    out: list[int] = []
    for f in (start, mid, end):
        if f not in out:
            out.append(f)
    return out


def world_vertices(obj_eval: bpy.types.Object, mesh: bpy.types.Mesh) -> np.ndarray:
    local = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
    mesh.vertices.foreach_get("co", local)
    local = local.reshape(-1, 3)

    mat = np.array(obj_eval.matrix_world, dtype=np.float32)
    rot = mat[:3, :3]
    trans = mat[:3, 3]
    return (local @ rot.T + trans).astype(np.float32, copy=False)


def extract_frame(scene: bpy.types.Scene, frame: int) -> dict[str, dict[str, np.ndarray]]:
    scene.frame_set(frame)
    depsgraph = bpy.context.evaluated_depsgraph_get()
    out: dict[str, dict[str, np.ndarray]] = {}

    for obj in scene.objects:
        if obj.type != "MESH" or obj.hide_render:
            continue

        obj_eval = obj.evaluated_get(depsgraph)
        mesh = obj_eval.to_mesh(preserve_all_data_layers=False, depsgraph=depsgraph)
        if mesh is None:
            continue

        try:
            mesh.calc_loop_triangles()
            if len(mesh.vertices) == 0 or len(mesh.loop_triangles) == 0:
                continue
            verts = world_vertices(obj_eval, mesh)
            faces = np.array([tri.vertices for tri in mesh.loop_triangles], dtype=np.int32)
            out[obj.name] = {
                "vertices": verts,
                "faces": faces,
            }
        finally:
            obj_eval.to_mesh_clear()

    return out


def main() -> None:
    args = parse_args()
    load_input_scene(args.input)

    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    scene = bpy.context.scene
    frames = frame_indices(scene, args.frame_mode)
    objects_per_frame: list[dict[str, dict[str, np.ndarray]]] = []

    for frame in frames:
        objects_per_frame.append(extract_frame(scene, frame))

    payload = {
        "frame_indices": frames,
        "objects_per_frame": objects_per_frame,
    }
    with output_path.open("wb") as f:
        pickle.dump(payload, f, protocol=pickle.HIGHEST_PROTOCOL)


if __name__ == "__main__":
    main()