File size: 6,161 Bytes
ba7ed3f
 
40798b3
ba7ed3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a17e0
 
ba7ed3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Photo-scanned models for the kitchen's objects in the Lit renderer: the YCB Object and Model Set (CC BY 4.0,
http://ycbbenchmarks.com), its 16k-face Google scans, each one GLB with its texture (as JPEG), and the list
of which object body each stands in for (the "objects" of dressing.json).

usage: python tools/make_objects.py        (needs trimesh, numpy, pillow)

Lit draws each model on its body, fitted to the body's collision shapes (src/render/view.js); the physics
and the grasps stay with the shapes. Toon and Pixel keep the shapes. The colours match the objects' labels
(the red can, the blue can).
"""
import io
import json
import os
import struct
import tarfile
import tempfile
import urllib.request

import numpy as np
import trimesh
from PIL import Image

ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
OUT = os.path.join(ROOT, "assets", "environments", "kitchen", "dressing")
URL = "http://ycb-benchmarks.s3-website-us-east-1.amazonaws.com/data/google/{}_google_16k.tgz"

# object body -> (YCB model, yaw in degrees before fitting, texture size, roughness, metalness)
OBJECTS = {
    "apple": ("013_apple", 0, 512, 0.45, 0.0),
    "orange": ("017_orange", 0, 512, 0.6, 0.0),
    "lemon": ("014_lemon", 0, 512, 0.5, 0.0),
    "banana": ("011_banana", 90, 512, 0.55, 0.0),  # its length along the capsule (the body's x)
    "can": ("005_tomato_soup_can", 0, 1024, 0.35, 0.3),  # the red can (scene.xml's material; a cola in the tasks)
    "can_2": ("002_master_chef_can", 0, 1024, 0.35, 0.3),  # the blue can
    "mug": ("025_mug", 0, 1024, 0.25, 0.0),
    "bowl": ("024_bowl", 0, 512, 0.3, 0.0),
    "plate": ("029_plate", 0, 512, 0.3, 0.0),
    "bottle": ("006_mustard_bottle", 0, 1024, 0.35, 0.0),
}


def convert(cache, body, oid, yaw, size, roughness, metalness):
    tgz = os.path.join(cache, f"{oid}.tgz")
    if not os.path.exists(tgz):
        urllib.request.urlretrieve(URL.format(oid), tgz)
    with tarfile.open(tgz) as t:
        t.extractall(cache, filter="data")
    mesh = trimesh.load(os.path.join(cache, oid, "google_16k", "textured.obj"), force="mesh", process=False)
    v = np.asarray(mesh.vertices, np.float64)
    turn = yaw
    if body == "mug":
        # its handle toward +x, where the shape's handle is: the handle is the thin side, away from the mean
        lo, hi = v.min(0), v.max(0)
        if v[:, 0].mean() > (lo[0] + hi[0]) / 2:
            turn += 180
    a = np.radians(turn)
    rz = np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]])
    pos = (v @ rz.T).astype(np.float32)
    nrm = (np.asarray(mesh.vertex_normals, np.float64) @ rz.T).astype(np.float32)
    uv = np.asarray(mesh.visual.uv, np.float32).copy()
    uv[:, 1] = 1 - uv[:, 1]
    idx = np.asarray(mesh.faces, np.uint32).reshape(-1)
    img = mesh.visual.material.image.convert("RGB").resize((size, size), Image.LANCZOS)
    jpg = io.BytesIO()
    img.save(jpg, "JPEG", quality=88, optimize=True)
    # one buffer: indices, positions, normals, uvs, the image
    parts, views, accessors = [], [], []
    data = bytearray()

    def view(blob, target=None):
        while len(data) % 4:
            data.append(0)
        views.append({"buffer": 0, "byteOffset": len(data), "byteLength": len(blob), **({"target": target} if target else {})})
        data.extend(blob)
        return len(views) - 1

    def accessor(arr, kind, comp, target, minmax=False):
        a = {"bufferView": view(arr.tobytes(), target), "componentType": comp, "count": int(len(arr) if kind != "SCALAR" else arr.size), "type": kind}
        if minmax:
            a["min"], a["max"] = arr.min(0).tolist(), arr.max(0).tolist()
        accessors.append(a)
        return len(accessors) - 1

    i_idx = accessor(idx, "SCALAR", 5125, 34963)
    i_pos = accessor(pos, "VEC3", 5126, 34962, True)
    i_nrm = accessor(nrm, "VEC3", 5126, 34962)
    i_uv = accessor(uv, "VEC2", 5126, 34962)
    i_img = view(jpg.getvalue())
    gltf = {
        "asset": {"version": "2.0", "generator": "tools/make_objects.py"},
        "scene": 0,
        "scenes": [{"nodes": [0]}],
        "nodes": [{"mesh": 0, "name": oid}],
        "meshes": [{"name": oid, "primitives": [{"attributes": {"POSITION": i_pos, "NORMAL": i_nrm, "TEXCOORD_0": i_uv}, "indices": i_idx, "material": 0}]}],
        "materials": [{"name": oid, "pbrMetallicRoughness": {"baseColorTexture": {"index": 0}, "metallicFactor": metalness, "roughnessFactor": roughness}}],
        "textures": [{"source": 0, "sampler": 0}],
        "images": [{"bufferView": i_img, "mimeType": "image/jpeg"}],
        "samplers": [{"magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071}],
        "accessors": accessors,
        "bufferViews": views,
        "buffers": [{"byteLength": len(data)}],
    }
    text = json.dumps(gltf, separators=(",", ":")).encode()
    text += b" " * ((4 - len(text) % 4) % 4)
    while len(data) % 4:
        data.append(0)
    name = f"ycb_{oid[4:]}"
    path = os.path.join(OUT, f"{name}.glb")
    with open(path, "wb") as f:
        f.write(struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(text) + 8 + len(data)))
        f.write(struct.pack("<II", len(text), 0x4E4F534A) + text)
        f.write(struct.pack("<II", len(data), 0x004E4942) + bytes(data))
    print(f"{body:8s} {oid:22s} {len(mesh.faces)} faces, {os.path.getsize(path) / 1e6:.2f} MB (turned {turn} degrees)")
    return name


def main():
    os.makedirs(OUT, exist_ok=True)
    path = os.path.join(OUT, "dressing.json")
    with open(path, encoding="utf-8") as f:
        dressing = json.load(f)
    objects = {}
    with tempfile.TemporaryDirectory() as cache:
        for body, (oid, yaw, size, roughness, metalness) in OBJECTS.items():
            name = convert(cache, body, oid, yaw, size, roughness, metalness)
            dressing["models"][name] = {"file": f"{name}.glb", "source": f"http://ycbbenchmarks.com ({oid}, google_16k)", "license": "CC BY 4.0"}
            objects[body] = {"model": name}
    dressing["objects"] = objects
    with open(path, "w", encoding="utf-8", newline="\n") as f:
        json.dump(dressing, f, indent=2)
        f.write("\n")


main()