Datasets:
File size: 4,037 Bytes
cd572c3 e585019 | 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 | # SPDX-License-Identifier: Apache-2.0
# /// script
# requires-python = "==3.13.*"
# dependencies = ["bpy>=5.2", "pillow"]
# ///
"""Render <id>/preview.png for each asset id given: the front quarter, from starboard.
uv run tools/preview.py coaster_01 multi_purpose_vessel_v
Run from the dataset root. Every preview gets the same view of its object and the
same framing, so thumbnails compare at a glance.
"""
import json
import math
import sys
import tempfile
from pathlib import Path
import bpy
from mathutils import Vector
from PIL import Image
OUT = (1024, 576)
MARGIN = 0.06 # of the width, on every side
AZIMUTH_DEG = 40.0 # from the front towards starboard
ELEVATION_DEG = 20.0
# glTF axis -> Blender axis, as Blender's glTF importer turns Y-up into Z-up.
AXES = {"+z": (0, -1, 0), "-z": (0, 1, 0), "+x": (1, 0, 0), "-x": (-1, 0, 0)}
def render(glb: Path, front_axis: str, out: Path) -> None:
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=str(glb))
for obj in [o for o in bpy.data.objects if o.type in {"CAMERA", "LIGHT"}]:
bpy.data.objects.remove(obj)
bpy.context.view_layer.update()
# An empty's bound_box is a point at its origin: measure meshes only.
pts = [
o.matrix_world @ Vector(c)
for o in bpy.data.objects
if o.type == "MESH"
for c in o.bound_box
]
lo = Vector([min(p[i] for p in pts) for i in range(3)])
hi = Vector([max(p[i] for p in pts) for i in range(3)])
centre, radius = (lo + hi) / 2, (hi - lo).length / 2
front = Vector(AXES[front_axis])
starboard = front.cross(Vector((0, 0, 1)))
az, el = math.radians(AZIMUTH_DEG), math.radians(ELEVATION_DEG)
view = (front * math.cos(az) + starboard * math.sin(az)) * math.cos(el)
view.z = math.sin(el)
sc = bpy.context.scene
sc.render.engine = "BLENDER_EEVEE"
# Twice the output, so the crop below has pixels to spare.
sc.render.resolution_x, sc.render.resolution_y = OUT[0] * 2, OUT[1] * 2
sc.render.film_transparent = True
sc.view_settings.view_transform = "Standard"
sc.world = bpy.data.worlds.new("world")
sc.world.use_nodes = True
background = sc.world.node_tree.nodes["Background"]
background.inputs["Color"].default_value = (0.8, 0.82, 0.85, 1)
sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN"))
sun.data.energy = 3.0
sun.rotation_euler = (math.radians(40), 0, math.radians(150))
sc.collection.objects.link(sun)
cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam"))
sc.collection.objects.link(cam)
sc.camera = cam
cam.data.lens = 50
cam.data.clip_end = radius * 100
# Far enough that the bounding sphere fits the frame's short side; the crop
# below does the real framing.
half_fov = math.atan(cam.data.sensor_width * OUT[1] / OUT[0] / 2 / cam.data.lens)
cam.location = centre + view * (radius / math.sin(half_fov) * 1.1)
cam.rotation_euler = (-view).to_track_quat("-Z", "Y").to_euler()
with tempfile.TemporaryDirectory() as tmp:
sc.render.filepath = str(Path(tmp) / "raw.png")
bpy.ops.render.render(write_still=True)
raw = Image.open(sc.render.filepath)
raw.load()
# Frame on the pixels: crop to the object, centre it, fit it inside the margin.
obj = raw.crop(raw.getchannel("A").getbbox())
room = (OUT[0] * (1 - 2 * MARGIN), OUT[1] - 2 * MARGIN * OUT[0])
k = min(room[0] / obj.width, room[1] / obj.height)
obj = obj.resize(
(round(obj.width * k), round(obj.height * k)), Image.Resampling.LANCZOS
)
canvas = Image.new("RGBA", OUT, (0, 0, 0, 0))
canvas.alpha_composite(obj, ((OUT[0] - obj.width) // 2, (OUT[1] - obj.height) // 2))
canvas.save(out)
rows = {
r["id"]: r for r in map(json.loads, Path("metadata.jsonl").read_text().splitlines())
}
for asset in sys.argv[1:]:
row = rows[asset]
render(Path(row["file"]), row.get("front_axis", "+z"), Path(row["file_name"]))
print(row["file_name"])
|