File size: 3,976 Bytes
42afafb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Debug: rebuild the B_03 scene, dump object boxes + camera projections, render 1 frame (Workbench).
  blender --background --python debug_scene.py -- --world work/B_03/world --out work/B_03/dbg
"""
import argparse
import json
import sys
from pathlib import Path

import bpy
import numpy as np
from mathutils import Matrix, Vector
import bpy_extras


def parse_args():
    ap = argparse.ArgumentParser()
    ap.add_argument("--world", required=True)
    ap.add_argument("--out", required=True)
    return ap.parse_args(sys.argv[sys.argv.index("--") + 1:])


def add_mesh(name, verts, faces):
    me = bpy.data.meshes.new(name)
    me.from_pydata([tuple(float(x) for x in v) for v in verts], [],
                   [tuple(int(x) for x in f) for f in faces])
    me.update()
    ob = bpy.data.objects.new(name, me)
    bpy.context.scene.collection.objects.link(ob)
    return ob


def main():
    args = parse_args()
    world = Path(args.world)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)

    spec = json.loads((world / "spec.json").read_text())
    cam = json.loads((world / "camera.json").read_text())
    K = np.array(cam["intrinsics"], float)
    E = np.array(cam["extrinsic"], float)
    W, H = spec["video"]["width"], spec["video"]["height"]
    scene = bpy.context.scene
    for ob in list(bpy.data.objects):
        bpy.data.objects.remove(ob, do_unlink=True)

    for mid, v in spec["meshes"].items():
        z = np.load(world / "mesh" / f"{mid}.npz")
        add_mesh(f"mesh_{mid}", z["vertices"][0], z["faces"][0])

    cam_data = bpy.data.cameras.new("cam")
    cam_data.sensor_fit = "HORIZONTAL"
    cam_data.sensor_width = 36.0
    cam_data.lens = float(K[0, 0]) * 36.0 / W
    cam_ob = bpy.data.objects.new("cam", cam_data)
    bpy.context.scene.collection.objects.link(cam_ob)
    D = Matrix.Diagonal((1.0, -1.0, -1.0, 1.0))
    cam_ob.matrix_world = Matrix(E) @ D
    scene.camera = cam_ob
    scene.render.resolution_x = W
    scene.render.resolution_y = H

    sun = bpy.data.lights.new("sun", type="SUN")
    sun.energy = 3.0
    sun_ob = bpy.data.objects.new("sun", sun)
    bpy.context.scene.collection.objects.link(sun_ob)
    sun_ob.rotation_euler = (0.9, 0, 0.5)
    w = bpy.data.worlds.new("w")
    w.use_nodes = True
    w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.8, 0.8, 0.8, 1)
    scene.world = w

    print("=== object bounding boxes (world) ===")
    dg = bpy.context.evaluated_depsgraph_get()
    for ob in bpy.data.objects:
        if ob.type != "MESH":
            continue
        corners = [ob.matrix_world @ Vector(c) for c in ob.bound_box]
        xs = [c.x for c in corners]; ys = [c.y for c in corners]; zs = [c.z for c in corners]
        print(f"{ob.name:12s} x[{min(xs):7.2f},{max(xs):7.2f}] y[{min(ys):7.2f},{max(ys):7.2f}] z[{min(zs):7.2f},{max(zs):7.2f}]")

    print("=== camera projection of pin COMs (should be in-frame) ===")
    bpy.context.view_layer.update()
    for name in ["Pin00", "Pin05", "Pin09"]:
        pos = np.load(world / "dyn" / f"{name}.npz")["pos"]
        p = Vector(pos[0].mean(0))
        uv = bpy_extras.object_utils.world_to_camera_view(scene, cam_ob, p)
        print(f"{name}: blender uv=({uv.x:.3f},{uv.y:.3f}) depth={uv.z:.2f}")
    ball = np.load(world / "dyn" / "Ball.npz")["pos"]
    p = Vector(ball[0].mean(0))
    uv = bpy_extras.object_utils.world_to_camera_view(scene, cam_ob, p)
    print(f"Ball f0: blender uv=({uv.x:.3f},{uv.y:.3f}) depth={uv.z:.2f}")
    p30 = Vector(ball[30].mean(0))
    uv = bpy_extras.object_utils.world_to_camera_view(scene, cam_ob, p30)
    print(f"Ball f30: blender uv=({uv.x:.3f},{uv.y:.3f}) depth={uv.z:.2f}")

    scene.render.engine = "BLENDER_WORKBENCH"
    scene.display.render_aa = "5"
    scene.render.filepath = str(out / "dbg_f1.png")
    scene.frame_set(1)
    bpy.ops.render.render(write_still=True)
    print("wrote", out / "dbg_f1.png")


if __name__ == "__main__":
    main()