xlerobot-sim / tools /make_appliances.py
VectorW's picture
Lit kitchen: a photographic room built in Blender on the kitchen's layout, its light baked with Cycles
40798b3 verified
Raw History Blame Contribute Delete
20.7 kB
"""Appliance models for the kitchen in the Lit renderer: a top-freezer fridge and a microwave from NVIDIA's
USDCraft-10K (Apache-2.0), each split into the parts that move apart (cabinet, doors) as GLBs (glTF: y up,
front +z), and where they go (dressing.json; tools/home/build_home.py builds them into the kitchen's photographic room):
- a cabinet is an item: it stands in for the static geoms in its region whose names match `geoms` (the
shell; what is inside stays as modelled, for the tasks and to look at);
- a door is a part: it rides on the door's body, fitted to that body's geoms whose names match `geoms`
(its panel), and they hide in Lit; the bar pull stays as modelled, where the arms grasp it. So does
the microwave's lowest button, on the body of the door's release button.
The models' own handles are left out (the kitchen's bar pulls are where the robot reaches them), and so are
the fridge's liner, shelves and door bins (the kitchen's own are where the tasks put things). Flat-shaded
boxes get bevelled edges, as the renderer's own boxes have. A model is fitted on each axis, so it takes the
kitchen's sizes (tools/make_kitchen.py lays out its fridge and microwave as these models are).
usage: python tools/make_appliances.py (needs usd-core: pip install usd-core)
"""
import io
import json
import os
import struct
import sys
import tempfile
import urllib.request
import numpy as np
from PIL import Image
from pxr import Usd, UsdGeom, UsdShade
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from make_kitchen import FRIDGE, MICROWAVE, SIDEBOARD # noqa: E402
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
OUT = os.path.join(ROOT, "assets", "environments", "kitchen", "dressing")
REPO = "https://huggingface.co/datasets/nvidia/USDCraft-10K"
REVISION = "6fbffb56c443237ddae9f6c7a05b72263fd1469e"
AGENT = "xlerobot-sim appliance fetch"
PREFIX = "usdcraft_"
BEVEL = 0.004 # the edges cut off a box, at most (metres, before fitting)
def no_handle(front):
"""Leave out what stands in front of the door's face (`front`, the model's y: its handle)."""
return lambda name, material, lo, hi: lo[1] >= front
# asset -> its models: name -> (links, which visual prims to keep: (prim name, material, world min, max))
ASSETS = {
"rigid/kitchen_dining/R002_refrigerator/01_top_freezer_refrigerator": {
# the shell (no liner, glass shelves, rails or hinge pins)
"fridge_cabinet": (["cabinet"], lambda name, material, lo, hi: material == "white_painted_steel"),
"fridge_freezer_door": (["freezer_door"], lambda name, material, lo, hi: material == "white_painted_steel"),
"fridge_door": (["fridge_door"], lambda name, material, lo, hi: material == "white_painted_steel"),
},
"rigid/kitchen_dining/R001_microwave_oven/02_stainless_inverter_microwave": {
# the turntable and the upper buttons with the cabinet: in the kitchen they do not move; the lowest
# button is the door's release, which is pressed in (its cap, without the bezel behind the panel)
"microwave_cabinet": (["cabinet", "button_1", "button_2", "button_3", "button_4", "turntable"], lambda name, material, lo, hi: True),
"microwave_door": (["door"], no_handle(-0.2195)),
"microwave_button": (["button_5"], lambda name, material, lo, hi: lo[1] < -0.1895),
},
}
def placements():
"""Where each model goes: items (cabinets, the freezer door) and parts (the doors), with the kitchen's
layout (tools/make_kitchen.py). The models' fronts face -y: the fridge's turns to +x."""
e = 0.01
fx0, fx1 = FRIDGE["x0"], FRIDGE["x0"] + FRIDGE["depth"]
ya, yb, hgt = FRIDGE["ya"], FRIDGE["yb"], FRIDGE["height"]
mz0 = SIDEBOARD["top"]
items = [
{"model": f"{PREFIX}fridge_cabinet", "region": [fx0 - e, ya - e, -e, fx1 + e, yb + e, hgt + e], "geoms": "^fridge_shell_", "yaw": 90},
{"model": f"{PREFIX}fridge_freezer_door", "region": [fx1 - e, ya - e, 1.0, fx1 + 0.06, yb + e, hgt + e], "geoms": "^freezer_door$", "yaw": 90},
# all of the microwave's static geoms: its shell, its inside, its control panel
{"model": f"{PREFIX}microwave_cabinet", "region": [MICROWAVE["x0"] - e, MICROWAVE["y0"] - 0.02, mz0 - e, MICROWAVE["x1"] + e, MICROWAVE["y1"] + e, mz0 + MICROWAVE["h"] + e], "yaw": 0},
]
parts = [
{"model": f"{PREFIX}fridge_door", "body": "fridge_door", "geoms": "^fridge_door_panel$", "yaw": 90},
{"model": f"{PREFIX}microwave_door", "body": "microwave_door", "geoms": "^microwave_door_(panel|window)$", "yaw": 0},
{"model": f"{PREFIX}microwave_button", "body": "microwave_button", "geoms": "^microwave_button_cap$", "yaw": 0},
]
return items, parts
def fetch(url):
request = urllib.request.Request(url, headers={"User-Agent": AGENT})
with urllib.request.urlopen(request) as response:
return response.read()
def download(path, into):
"""The asset's files (its meta.json lists them) under `into`; the stage's path."""
meta = json.loads(fetch(f"{REPO}/resolve/{REVISION}/{path}/meta.json"))
physx = meta["assets"]["physx"]
for name in physx["files"]:
target = os.path.join(into, *name.split("/"))
os.makedirs(os.path.dirname(target), exist_ok=True)
with open(target, "wb") as f:
f.write(fetch(f"{REPO}/resolve/{REVISION}/{path}/{name}"))
return os.path.join(into, *physx["entry"].split("/")), meta
def chamfered_box(half, r):
"""A box (half sizes `half`, about the origin) with its edges and corners cut `r` deep, the cuts shaded
as if round (each vertex has the normal of the face it is on): positions and normals, 3 per triangle."""
inner = half - r
tris = []
def point(signs, flat):
p = np.array(signs, float) * inner
p[flat] = signs[flat] * half[flat]
n = np.zeros(3)
n[flat] = signs[flat]
return p, n
for a in range(3):
b, c = (a + 1) % 3, (a + 2) % 3
for s in (-1, 1):
quad = []
for u, v in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
signs = np.zeros(3)
signs[a], signs[b], signs[c] = s, u, v
quad.append(point(signs, a))
tris += [[quad[0], quad[1], quad[2]], [quad[0], quad[2], quad[3]]]
for c in range(3):
a, b = (c + 1) % 3, (c + 2) % 3
for sa in (-1, 1):
for sb in (-1, 1):
ends = []
for sc in (-1, 1):
signs = np.zeros(3)
signs[a], signs[b], signs[c] = sa, sb, sc
ends.append((point(signs, a), point(signs, b)))
(a0, b0), (a1, b1) = ends
tris += [[a0, a1, b1], [a0, b1, b0]]
for sx in (-1, 1):
for sy in (-1, 1):
for sz in (-1, 1):
signs = np.array([sx, sy, sz], float)
tris.append([point(signs, 0), point(signs, 1), point(signs, 2)])
pos, nrm = [], []
for tri in tris:
p = [v[0] for v in tri]
if np.dot(np.cross(p[1] - p[0], p[2] - p[0]), p[0] + p[1] + p[2]) < 0:
tri = [tri[0], tri[2], tri[1]] # wound to face out
for v in tri:
pos.append(v[0])
nrm.append(v[1])
return np.array(pos), np.array(nrm)
def face_values(values, interpolation, counts, indices):
"""A primvar's value at each face-vertex, whatever its interpolation."""
values = np.asarray(values)
if interpolation == "faceVarying":
return values
if interpolation in ("vertex", "varying"):
return values[indices]
if interpolation == "uniform":
return np.repeat(values, counts, axis=0)
return np.repeat(values[:1], len(indices), axis=0)
def surface(material):
"""A UsdPreviewSurface's inputs: name -> ("value", v) or ("texture", file path, shader)."""
if not material:
return {}
shader = material.ComputeSurfaceSource()[0]
if not shader:
return {}
out = {}
for i in shader.GetInputs():
if i.HasConnectedSource():
source = UsdShade.Shader(i.GetConnectedSources()[0][0].source.GetPrim())
f = source.GetInput("file")
if f and f.Get() is not None:
out[i.GetBaseName()] = ("texture", f.Get().resolvedPath or f.Get().path)
else:
out[i.GetBaseName()] = ("value", i.Get())
return out
def triangles(prim, xcache, t):
"""A mesh prim's triangles in the stage's frame, by material: [(material, positions, normals, uvs)]."""
mesh = UsdGeom.Mesh(prim)
points = np.array(mesh.GetPointsAttr().Get(t), float)
counts = np.array(mesh.GetFaceVertexCountsAttr().Get(t))
indices = np.array(mesh.GetFaceVertexIndicesAttr().Get(t))
world = np.array(xcache.GetLocalToWorldTransform(prim), float) # row vectors: p @ M[:3, :3] + M[3, :3]
rot, shift = world[:3, :3], world[3, :3]
binding = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()[0]
inputs = surface(binding)
textured = any(v[0] == "texture" for v in inputs.values())
# a plain box (eight corners, flat faces) gets its edges bevelled, as the renderer's boxes have
lo, hi = points.min(axis=0), points.max(axis=0)
corners = len(np.unique(np.round(points, 6), axis=0))
if corners == 8 and all(len(np.unique(np.round(points[:, k], 6))) == 2 for k in range(3)) and not textured:
r = min(BEVEL, 0.2 * float((hi - lo).min()))
if r >= 0.001:
pos, nrm = chamfered_box((hi - lo) / 2, r)
pos = (pos + (hi + lo) / 2) @ rot + shift
nrm = nrm @ np.linalg.inv(rot).T
return [(binding, pos, nrm, None)]
fv_pos = points[indices]
normals = mesh.GetNormalsAttr().Get(t)
fv_nrm = face_values(normals, mesh.GetNormalsInterpolation(), counts, indices) if normals is not None and len(normals) else None
primvar = UsdGeom.PrimvarsAPI(prim).GetPrimvar("st")
fv_uv = None
if primvar and primvar.HasValue():
values = np.asarray(primvar.Get(t))
if primvar.IsIndexed():
values = values[np.asarray(primvar.GetIndices(t))]
fv_uv = face_values(values, primvar.GetInterpolation(), counts, indices)
# fans, and each triangle's face
tri, face = [], []
start = 0
for k, c in enumerate(counts):
for j in range(1, c - 1):
tri += [start, start + j, start + j + 1]
face.append(k)
start += c
tri = np.array(tri).reshape(-1, 3)
face = np.array(face)
if mesh.GetOrientationAttr().Get() == "leftHanded":
tri = tri[:, [0, 2, 1]]
groups = []
subsets = UsdGeom.Subset.GetAllGeomSubsets(mesh)
assigned = np.zeros(len(counts), bool)
for s in subsets:
faces = np.array(s.GetIndicesAttr().Get(t))
groups.append((faces, UsdShade.MaterialBindingAPI(s.GetPrim()).ComputeBoundMaterial()[0]))
assigned[faces] = True
if not assigned.all():
groups.append((np.nonzero(~assigned)[0], binding))
out = []
for faces, material in groups:
sel = tri[np.isin(face, faces)].reshape(-1)
if not len(sel):
continue
pos = fv_pos[sel] @ rot + shift
if fv_nrm is not None:
nrm = fv_nrm[sel] @ np.linalg.inv(rot).T
else:
a, b, c = pos[0::3], pos[1::3], pos[2::3]
nrm = np.repeat(np.cross(b - a, c - a), 3, axis=0)
out.append((material, pos, nrm, fv_uv[sel] if fv_uv is not None else None))
return out
def linear(rgb):
rgb = np.asarray(rgb, float)
return np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
class Glb:
"""A GLB under construction: one mesh (one primitive) per material."""
def __init__(self, base):
self.base = base # the stage's folder, which texture paths are relative to
self.data = bytearray()
self.views, self.accessors, self.meshes, self.materials, self.images, self.textures = [], [], [], [], [], []
self.image_of = {}
self.albedo = {}
def view(self, blob, target=None):
while len(self.data) % 4:
self.data.append(0)
v = {"buffer": 0, "byteOffset": len(self.data), "byteLength": len(blob)}
if target:
v["target"] = target
self.data += blob
self.views.append(v)
return len(self.views) - 1
def accessor(self, array, kind, bounds=False):
array = np.ascontiguousarray(array, np.float32)
a = {"bufferView": self.view(array.tobytes(), 34962), "componentType": 5126, "count": int(array.shape[0]), "type": kind}
if bounds:
a["min"] = array.min(axis=0).tolist()
a["max"] = array.max(axis=0).tolist()
self.accessors.append(a)
return len(self.accessors) - 1
def texture(self, path):
"""A texture of the image file (embedded as PNG), and its mean linear colour over its opaque pixels."""
if path not in self.image_of:
im = Image.open(path if os.path.isabs(path) else os.path.join(self.base, path)).convert("RGBA")
out = io.BytesIO()
im.save(out, "PNG", optimize=True)
self.images.append({"bufferView": self.view(out.getvalue()), "mimeType": "image/png"})
self.textures.append({"source": len(self.images) - 1, "sampler": 0})
px = np.asarray(im, float) / 255
opaque = px[..., 3] > 0.5
mean = linear(px[..., :3][opaque]).mean(axis=0) if opaque.any() else np.full(3, 0.5)
self.image_of[path] = (len(self.textures) - 1, mean)
return self.image_of[path]
def material(self, binding):
"""glTF PBR from a UsdPreviewSurface (base colour, metallic, roughness, emission, cut-out opacity)."""
name = binding.GetPrim().GetName() if binding else "default"
for k, m in enumerate(self.materials):
if m["name"] == name:
return k
inputs = surface(binding)
pbr = {"baseColorFactor": [0.7, 0.7, 0.7, 1.0], "metallicFactor": 0.0, "roughnessFactor": 0.5}
m = {"name": name, "pbrMetallicRoughness": pbr}
mean = np.array(pbr["baseColorFactor"][:3])
kind, *value = inputs.get("diffuseColor", ("value", None))
if kind == "texture":
index, mean = self.texture(value[0])
pbr["baseColorTexture"] = {"index": index}
pbr["baseColorFactor"] = [1.0, 1.0, 1.0, 1.0]
elif value[0] is not None:
pbr["baseColorFactor"] = [*map(float, value[0]), 1.0]
mean = np.array(pbr["baseColorFactor"][:3])
for usd, gltf in (("metallic", "metallicFactor"), ("roughness", "roughnessFactor")):
if inputs.get(usd, ("",))[0] == "value":
pbr[gltf] = float(inputs[usd][1])
if inputs.get("emissiveColor", ("",))[0] == "value" and max(inputs["emissiveColor"][1]) > 0:
m["emissiveFactor"] = [min(1.0, float(v)) for v in inputs["emissiveColor"][1]]
if inputs.get("opacity", ("",))[0] == "texture":
m["alphaMode"] = "MASK"
m["alphaCutoff"] = float(inputs["opacityThreshold"][1]) if inputs.get("opacityThreshold", ("",))[0] == "value" else 0.5
self.materials.append(m)
self.albedo[name] = [round(float(v), 3) for v in mean]
return len(self.materials) - 1
def add(self, material, pos, nrm, uv):
"""Triangles in the stage's frame (z up, front -y), into glTF's (y up, front +z)."""
to_gltf = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], float) # (x, y, z) -> (x, z, -y), as rows
p = pos @ to_gltf
n = nrm @ to_gltf
n /= np.linalg.norm(n, axis=1, keepdims=True) + 1e-12
attributes = {"POSITION": self.accessor(p, "VEC3", True), "NORMAL": self.accessor(n, "VEC3")}
if uv is not None:
u = np.asarray(uv, float).copy()
u[:, 1] = 1 - u[:, 1] # USD's st has v up, glTF's has it down
attributes["TEXCOORD_0"] = self.accessor(u, "VEC2")
self.meshes.append({"name": self.materials[material]["name"], "primitives": [{"attributes": attributes, "material": material}]})
def write(self, path):
gltf = {
"asset": {"version": "2.0", "generator": "tools/make_appliances.py"},
"scene": 0,
"scenes": [{"nodes": list(range(len(self.meshes)))}],
"nodes": [{"mesh": k, "name": m["name"]} for k, m in enumerate(self.meshes)],
"meshes": self.meshes,
"materials": self.materials,
"accessors": self.accessors,
"bufferViews": self.views,
"buffers": [{"byteLength": 0}],
}
if self.textures:
gltf["textures"] = self.textures
gltf["images"] = self.images
gltf["samplers"] = [{"wrapS": 33071, "wrapT": 33071, "magFilter": 9729, "minFilter": 9987}]
while len(self.data) % 4:
self.data.append(0)
gltf["buffers"][0]["byteLength"] = len(self.data)
text = json.dumps(gltf, separators=(",", ":")).encode()
text += b" " * ((4 - len(text) % 4) % 4)
with open(path, "wb") as f:
f.write(struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(text) + 8 + len(self.data)))
f.write(struct.pack("<II", len(text), 0x4E4F534A) + text)
f.write(struct.pack("<II", len(self.data), 0x004E4942) + bytes(self.data))
def convert(stage_path, links, keep, out):
"""The links' visual meshes the predicate keeps, as one GLB, merged by material; the materials' albedo."""
stage = Usd.Stage.Open(stage_path)
t = Usd.TimeCode.Default()
xcache = UsdGeom.XformCache(t)
bounds = UsdGeom.BBoxCache(t, ["default", "render"])
merged = {} # material path -> [binding, positions, normals, uvs]
for prim in stage.Traverse():
path = str(prim.GetPath())
if not prim.IsA(UsdGeom.Mesh) or "/Visuals/" not in path or path.split("/Links/")[-1].split("/")[0] not in links:
continue
if UsdGeom.Imageable(prim).ComputePurpose() not in ("default", "render"):
continue
box = bounds.ComputeWorldBound(prim).ComputeAlignedRange()
binding = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()[0]
if not keep(prim.GetName(), binding.GetPrim().GetName() if binding else "", np.array(box.GetMin()), np.array(box.GetMax())):
continue
for material, pos, nrm, uv in triangles(prim, xcache, t):
key = str(material.GetPath()) if material else ""
entry = merged.setdefault(key, [material, [], [], []])
entry[1].append(pos)
entry[2].append(nrm)
entry[3].append(uv)
glb = Glb(os.path.dirname(stage_path))
tris = 0
for material, pos, nrm, uvs in merged.values():
uv = np.concatenate(uvs) if all(u is not None for u in uvs) else None
glb.add(glb.material(material), np.concatenate(pos), np.concatenate(nrm), uv)
tris += sum(len(p) for p in pos) // 3
glb.write(out)
print(f"{os.path.basename(out)}: {tris} triangles, {len(glb.materials)} materials, {os.path.getsize(out) / 1024:.0f} KB")
return glb.albedo
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)
# this tool's models replace what it made before; the rest stays
models = {k: v for k, v in dressing["models"].items() if not k.startswith(PREFIX)}
with tempfile.TemporaryDirectory() as cache:
for k, (asset, parts) in enumerate(ASSETS.items()):
stage_path, meta = download(asset, os.path.join(cache, str(k)))
for name, (links, keep) in parts.items():
model = f"{PREFIX}{name}"
albedo = convert(stage_path, links, keep, os.path.join(OUT, f"{model}.glb"))
models[model] = {
"file": f"{model}.glb",
"source": f"{REPO} ({meta['object_id']}, {meta['title']}: {', '.join(links)})",
"license": "Apache-2.0",
"albedo": albedo,
}
items, parts = placements()
dressing["models"] = models
dressing["items"] = [i for i in dressing.get("items", []) if not i["model"].startswith(PREFIX)] + items
dressing["parts"] = [p for p in dressing.get("parts", []) if not p["model"].startswith(PREFIX)] + parts
with open(path, "w", encoding="utf-8", newline="\n") as f:
json.dump(dressing, f, indent=2)
f.write("\n")
main()