File size: 9,112 Bytes
0dc9398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import argparse
import json
import math
import sys
from pathlib import Path

import bpy
import numpy as np
from mathutils import Vector


IMPORTERS = {
    "obj": bpy.ops.wm.obj_import,
    "ply": bpy.ops.wm.ply_import,
    "glb": bpy.ops.import_scene.gltf,
    "gltf": bpy.ops.import_scene.gltf,
    "fbx": bpy.ops.import_scene.fbx,
    "stl": bpy.ops.import_mesh.stl,
}


def orthographic_views(num_views: int) -> list[dict[str, float]]:
    base_views = [
        (-0.5 * np.pi, 0.0),
        (0.0, 0.0),
        (0.5 * np.pi, 0.0),
        (np.pi, 0.0),
        (-0.5 * np.pi, 0.5 * np.pi),
        (-0.5 * np.pi, -0.5 * np.pi),
    ]
    if num_views <= len(base_views):
        selected = base_views[:num_views]
    else:
        selected = base_views[:]
        for index in range(num_views - len(base_views)):
            azimuth = 2.0 * np.pi * index / max(1, num_views - len(base_views))
            selected.append((azimuth, np.pi / 6.0))
    return [{"azimuth": yaw, "elevation": pitch, "distance": 1.5, "fov": 0.6} for yaw, pitch in selected]


def clear_scene() -> None:
    for collection in (bpy.data.objects, bpy.data.materials, bpy.data.textures, bpy.data.images):
        for item in list(collection):
            collection.remove(item, do_unlink=True)


def load_model(path: Path) -> None:
    extension = path.suffix.lower().lstrip(".")
    if extension not in IMPORTERS:
        raise ValueError(f"Unsupported model format: {path.suffix}")
    importer = IMPORTERS[extension]
    if extension in {"glb", "gltf"}:
        importer(filepath=str(path), merge_vertices=True, import_shading="NORMALS")
    else:
        importer(filepath=str(path))


def scene_bbox() -> tuple[Vector, Vector]:
    bbox_min = Vector((math.inf, math.inf, math.inf))
    bbox_max = Vector((-math.inf, -math.inf, -math.inf))
    found = False
    for obj in bpy.context.scene.objects:
        if not isinstance(obj.data, bpy.types.Mesh):
            continue
        found = True
        for coord in obj.bound_box:
            world_coord = obj.matrix_world @ Vector(coord)
            bbox_min = Vector(tuple(min(bbox_min[i], world_coord[i]) for i in range(3)))
            bbox_max = Vector(tuple(max(bbox_max[i], world_coord[i]) for i in range(3)))
    if not found:
        raise RuntimeError("The scene does not contain a mesh object.")
    return bbox_min, bbox_max


def normalize_scene() -> tuple[float, Vector]:
    root_objects = [obj for obj in bpy.context.scene.objects if obj.parent is None]
    if len(root_objects) > 1:
        parent = bpy.data.objects.new("SceneRoot", None)
        bpy.context.scene.collection.objects.link(parent)
        for obj in root_objects:
            obj.parent = parent
    else:
        parent = root_objects[0]

    bbox_min, bbox_max = scene_bbox()
    scale = 1.0 / max(bbox_max - bbox_min)
    parent.scale *= scale
    bpy.context.view_layer.update()

    bbox_min, bbox_max = scene_bbox()
    offset = -(bbox_min + bbox_max) * 0.5
    parent.matrix_world.translation += offset
    bpy.context.view_layer.update()
    return scale, offset


def configure_render(resolution: int, engine: str) -> None:
    scene = bpy.context.scene
    scene.render.engine = engine
    scene.render.resolution_x = resolution
    scene.render.resolution_y = resolution
    scene.render.resolution_percentage = 100
    scene.render.image_settings.file_format = "PNG"
    scene.render.image_settings.color_mode = "RGBA"
    scene.render.film_transparent = True

    if engine == "CYCLES":
        scene.cycles.device = "GPU"
        scene.cycles.samples = 64
        scene.cycles.use_denoising = True
        try:
            prefs = bpy.context.preferences.addons["cycles"].preferences
            prefs.compute_device_type = "CUDA"
            prefs.get_devices()
            for device in prefs.devices:
                device.use = device.type == "CUDA"
        except Exception:
            pass


def create_camera() -> bpy.types.Object:
    camera = bpy.data.objects.new("Camera", bpy.data.cameras.new("Camera"))
    bpy.context.collection.objects.link(camera)
    bpy.context.scene.camera = camera
    camera.data.type = "ORTHO"
    camera.data.ortho_scale = 1.2

    target = bpy.data.objects.new("CameraTarget", None)
    bpy.context.collection.objects.link(target)
    target.location = (0.0, 0.0, 0.0)

    constraint = camera.constraints.new(type="TRACK_TO")
    constraint.track_axis = "TRACK_NEGATIVE_Z"
    constraint.up_axis = "UP_Y"
    constraint.target = target
    return camera


def add_lighting() -> None:
    light_specs = [
        ("KeyLight", "POINT", 1000.0, (4.0, 1.0, 6.0), (1.0, 1.0, 1.0)),
        ("TopLight", "AREA", 10000.0, (0.0, 0.0, 10.0), (100.0, 100.0, 100.0)),
        ("BottomLight", "AREA", 1000.0, (0.0, 0.0, -10.0), (100.0, 100.0, 100.0)),
    ]
    for name, kind, energy, location, scale in light_specs:
        light = bpy.data.objects.new(name, bpy.data.lights.new(name, type=kind))
        bpy.context.collection.objects.link(light)
        light.data.energy = energy
        light.location = location
        light.scale = scale


def apply_neutral_material() -> None:
    material = bpy.data.materials.new("NeutralMaterial")
    material.use_nodes = True
    material.node_tree.nodes.clear()
    shader = material.node_tree.nodes.new("ShaderNodeBsdfDiffuse")
    shader.inputs[0].default_value = (0.5, 0.5, 0.5, 1.0)
    output = material.node_tree.nodes.new("ShaderNodeOutputMaterial")
    material.node_tree.links.new(shader.outputs["BSDF"], output.inputs["Surface"])
    bpy.context.scene.view_layers["ViewLayer"].material_override = material


def camera_transform(camera: bpy.types.Object) -> list[list[float]]:
    location, rotation, _ = camera.matrix_world.decompose()
    rotation = rotation.to_matrix()
    rows = []
    for row_index in range(3):
        row = [rotation[row_index][col_index] for col_index in range(3)]
        row.append(location[row_index])
        rows.append(row)
    rows.append([0.0, 0.0, 0.0, 1.0])
    return rows


def export_mesh(path: Path) -> None:
    bpy.ops.object.select_all(action="DESELECT")
    mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"]
    if not mesh_objects:
        return
    bpy.context.view_layer.objects.active = mesh_objects[0]
    for obj in mesh_objects:
        obj.select_set(True)
    bpy.ops.object.convert(target="MESH")
    bpy.ops.object.mode_set(mode="EDIT")
    bpy.ops.mesh.select_all(action="SELECT")
    bpy.ops.mesh.quads_convert_to_tris(quad_method="BEAUTY", ngon_method="BEAUTY")
    bpy.ops.object.mode_set(mode="OBJECT")
    bpy.ops.wm.ply_export(filepath=str(path), export_triangulated_mesh=True, up_axis="Y", forward_axis="NEGATIVE_Z")


def render(args: argparse.Namespace) -> None:
    output_dir = Path(args.output_folder)
    output_dir.mkdir(parents=True, exist_ok=True)

    clear_scene()
    load_model(Path(args.object))
    scale, offset = normalize_scene()
    configure_render(args.resolution, args.engine)
    camera = create_camera()
    add_lighting()
    apply_neutral_material()

    metadata = {
        "aabb": [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]],
        "scale": scale,
        "offset": [offset.x, offset.y, offset.z],
        "frames": [],
    }

    for index, view in enumerate(orthographic_views(args.num_views)):
        camera.location = (
            view["distance"] * np.cos(view["azimuth"]) * np.cos(view["elevation"]),
            view["distance"] * np.sin(view["azimuth"]) * np.cos(view["elevation"]),
            view["distance"] * np.sin(view["elevation"]),
        )
        bpy.context.scene.render.filepath = str(output_dir / f"{index:03d}.png")
        bpy.ops.render.render(write_still=True)
        metadata["frames"].append(
            {
                "file_path": f"{index:03d}.png",
                "camera_angle_x": view["fov"],
                "azimuth": view["azimuth"],
                "elevation": view["elevation"],
                "cam_dis": view["distance"],
                "transform_matrix": camera_transform(camera),
            }
        )

    with (output_dir / "transforms.json").open("w") as handle:
        json.dump(metadata, handle, indent=2)

    if args.geo_mode:
        export_mesh(output_dir / "mesh.ply")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Render a 3D model from fixed orthographic views.")
    parser.add_argument("--object", required=True, help="Path to the model file.")
    parser.add_argument("--output-folder", "--output_folder", dest="output_folder", required=True)
    parser.add_argument("--resolution", type=int, default=512)
    parser.add_argument("--num-views", type=int, default=6)
    parser.add_argument("--engine", default="CYCLES", choices=("CYCLES", "BLENDER_EEVEE_NEXT", "BLENDER_EEVEE"))
    parser.add_argument("--geo-mode", "--geo_mode", dest="geo_mode", action="store_true")
    return parser


if __name__ == "__main__":
    argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else sys.argv[1:]
    render(build_parser().parse_args(argv))