"""Generate every asset of the Ironbark Pavilion artifact.

Run with Blender 5 from the repository root:
  /Applications/Blender.app/Contents/MacOS/Blender --background --python \
    frontend/artifacts/claude-fable-5-2/ironbark-pavilion/generate.py

It builds all geometry from code with a fixed seed, then writes scene.glb,
scene-data.js (the GLB as base64 plus the camera views), scene.usdz, the
renders, object-inventory.json and asset-report.json next to this file.

Blender units are metres, Z up. The origin is the viewer's feet on the deck.
The GLB and USDZ exports convert to Y up.
"""

import base64
import json
import random
from hashlib import sha256
from math import cos, pi, radians, sin, sqrt
from pathlib import Path
from shutil import which
from subprocess import run
from tempfile import TemporaryDirectory

import bmesh
import bpy
from mathutils import Euler, Vector

SEED = 5207
HERE = Path(__file__).resolve().parent
rng = random.Random(SEED)

D = 4.6      # half-width of the deck
POST = 4.5   # post line
INNER = 2.7  # inner beam line; the canopy covers the band outside it
H = 2.7      # post height
GROUND = -0.3

# Camera views shared by the renders and the browser scene (eye, target, vertical fov).
VIEWS = {
    "whole": {"label": "Whole pavilion", "eye": (4.2, -12.6, 2.55), "target": (0.0, 0.6, 1.05), "fov": 40},
    "reading": {"label": "Reading corner", "eye": (-0.7, 0.5, 1.6), "target": (-3.1, 3.6, 0.7), "fov": 46},
    "tea": {"label": "Tea setting", "eye": (1.75, 1.45, 1.3), "target": (3.4, 3.3, 0.42), "fov": 40},
    "seating": {"label": "Planted seating", "eye": (-0.9, -1.0, 1.6), "target": (-3.7, -3.0, 0.55), "fov": 46},
    "water": {"label": "Water basin", "eye": (1.5, -1.2, 1.7), "target": (3.5, -3.3, 0.35), "fov": 40},
    "sculpture": {"label": "Sculpture display", "eye": (0.0, 0.9, 1.5), "target": (0.0, 3.95, 1.2), "fov": 40},
}
SUN = (-0.45, -0.62, 0.64)  # direction towards the sun

scene = None
collection = None
MATS = {}
MESHES = {}
NAMES = {}
THINGS = []


# ---------------------------------------------------------------- materials

def linear(hexcolour):
    channels = [int(hexcolour[i:i + 2], 16) / 255 for i in (1, 3, 5)]
    return tuple(c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in channels)


def mat(name, hexcolour, rough=0.8, metal=0.0, double=False):
    if name in MATS:
        return MATS[name]
    material = bpy.data.materials.new(name)
    shader = next(node for node in material.node_tree.nodes if node.type == "BSDF_PRINCIPLED")
    shader.inputs["Base Color"].default_value = (*linear(hexcolour), 1)
    shader.inputs["Roughness"].default_value = rough
    shader.inputs["Metallic"].default_value = metal
    material.use_backface_culling = not double
    MATS[name] = material
    return material


class M:
    pass


def make_materials():
    table = {
        "deck": ("#8b5e3f", 0.72), "deck2": ("#7d5236", 0.78), "ironbark": ("#4b3024", 0.62),
        "trim": ("#2f1f17", 0.55), "slat": ("#a9754e", 0.7), "paleoak": ("#c9a678", 0.6),
        "stone": ("#8e8d86", 0.92), "stonepale": ("#c2beb2", 0.85), "plinth": ("#3a3b40", 0.22),
        "grass": ("#5f7c3c", 1.0), "gravel": ("#b8ab95", 0.95), "pebble": ("#6f6a63", 0.5),
        "water": ("#2f7482", 0.06), "tea": ("#a5521f", 0.08), "celadon": ("#9cc2b0", 0.22),
        "porcelain": ("#ebe5d6", 0.28), "iron": ("#222224", 0.42, 0.85), "brass": ("#b8924a", 0.3, 1.0),
        "bronze": ("#6d4a2a", 0.38, 1.0), "zinc": ("#9aa3a6", 0.35, 0.9), "paper": ("#f1dfb4", 0.85),
        "ochre": ("#c98a2e", 0.96), "terracotta": ("#b3543a", 0.96), "indigo": ("#2f496b", 0.96),
        "shoji": ("#efe6cf", 0.9), "sage": ("#8fa37d", 0.96), "cream": ("#e7ddc7", 0.96), "tatami": ("#c8bb7e", 0.9),
        "moss": ("#3f5a35", 0.95), "pot": ("#b1643f", 0.8), "soil": ("#3b2a20", 1.0),
        "bamboo": ("#a8b06b", 0.5), "leather": ("#6b2f29", 0.55), "page": ("#f0e8d3", 0.9),
        "ink": ("#2a2a33", 0.7), "ribbon": ("#b02a2a", 0.7), "trunk": ("#5c4737", 0.9),
        "foliage": ("#4f7437", 0.95), "foliage2": ("#6a8c45", 0.95), "foliage3": ("#35582f", 0.95),
        "maple": ("#c4502a", 0.9), "hedge": ("#2f4f2c", 0.98), "lavender": ("#8a78b8", 0.9),
        "blossom": ("#f0c9cf", 0.8), "citrus": ("#e8962a", 0.6), "hill": ("#7c9270", 1.0),
        "hillfar": ("#9fb2a6", 1.0), "book1": ("#7a2e2e", 0.7), "book2": ("#2e4f6e", 0.7),
        "book3": ("#3f6347", 0.7), "book4": ("#c49a3c", 0.7), "book5": ("#d9d0bd", 0.7),
        "book6": ("#4a3a5e", 0.7),
    }
    for name, spec in table.items():
        setattr(M, name, mat(name, spec[0], spec[1], spec[2] if len(spec) > 2 else 0.0))
    M.leaf = mat("leaf", "#5c8a3c", 0.8, double=True)
    M.leaf2 = mat("leaf2", "#7fa64e", 0.8, double=True)
    M.leaf3 = mat("leaf3", "#3f6b3a", 0.8, double=True)
    M.lily = mat("lily", "#4f8f4a", 0.6, double=True)


# ------------------------------------------------------------------- meshes

def cached(key, material, build):
    key = (key, material.name)
    if key in MESHES:
        return MESHES[key]
    mesh = bpy.data.meshes.new(f"{key[0]}-{material.name}".replace(" ", "").replace("(", "").replace(")", "").replace(",", "_").replace(".", "p").replace("'", ""))
    bm = bmesh.new()
    build(bm)
    bm.normal_update()
    bm.to_mesh(mesh)
    bm.free()
    mesh.materials.append(material)
    MESHES[key] = mesh
    return mesh


def box_mesh(material):
    return cached("box", material, lambda bm: bmesh.ops.create_cube(bm, size=1))


def cyl_mesh(material, segs=12, top=1.0):
    def build(bm):
        bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=segs, radius1=1, radius2=max(top, 0.001), depth=1)
        bmesh.ops.translate(bm, verts=bm.verts, vec=(0, 0, 0.5))
        for face in bm.faces:
            face.smooth = abs(face.normal.z) < 0.9
    return cached(("cyl", segs, round(top, 3)), material, build)


def ico_mesh(material, sub=2):
    def build(bm):
        bmesh.ops.create_icosphere(bm, subdivisions=sub, radius=1)
        for face in bm.faces:
            face.smooth = True
    return cached(("ico", sub), material, build)


def pillow_mesh(material):
    def build(bm):
        bmesh.ops.create_uvsphere(bm, u_segments=16, v_segments=10, radius=1)
        for vert in bm.verts:
            vert.co = Vector([(1 if c >= 0 else -1) * abs(c) ** 0.5 for c in vert.co])
        for face in bm.faces:
            face.smooth = True
    return cached("pillow", material, build)


def disc_mesh(material, segs=20):
    def build(bm):
        bmesh.ops.create_circle(bm, cap_ends=True, segments=segs, radius=1)
        for face in bm.faces:
            if face.normal.z < 0:
                face.normal_flip()
    return cached(("disc", segs), material, build)


def leaf_mesh(material):
    def build(bm):
        verts = [bm.verts.new(co) for co in ((0, 0, 0), (-0.5, 0.1, 0.45), (0, 0, 1), (0.5, 0.1, 0.45))]
        bm.faces.new(verts)
    return cached("leaf", material, build)


def rock_mesh(material, variant):
    def build(bm):
        local = random.Random(SEED + 31 * variant)
        bmesh.ops.create_icosphere(bm, subdivisions=2, radius=1)
        for vert in bm.verts:
            vert.co *= 1 + local.uniform(-0.16, 0.16)
        for face in bm.faces:
            face.smooth = True
    return cached(("rock", variant), material, build)


def lathe_mesh(key, material, profile, segs=16):
    def build(bm):
        rings = []
        for radius, z in profile:
            if radius < 1e-6:
                rings.append([bm.verts.new((0, 0, z))])
            else:
                rings.append([bm.verts.new((radius * cos(2 * pi * i / segs), radius * sin(2 * pi * i / segs), z)) for i in range(segs)])
        for a, b in zip(rings, rings[1:]):
            for i in range(segs):
                j = (i + 1) % segs
                if len(a) == 1 and len(b) == 1:
                    continue
                if len(a) == 1:
                    face = bm.faces.new((a[0], b[i], b[j]))
                elif len(b) == 1:
                    face = bm.faces.new((a[i], a[j], b[0]))
                else:
                    face = bm.faces.new((a[i], a[j], b[j], b[i]))
                face.smooth = True
        bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    return cached(("lathe", key, segs), material, build)


def torus_mesh(material, major, minor, segs=24, sides=8, arc=2 * pi):
    closed = abs(arc - 2 * pi) < 1e-6

    def build(bm):
        count = segs if closed else segs + 1
        rings = []
        for i in range(count):
            a = arc * i / segs
            rings.append([bm.verts.new(((major + minor * cos(2 * pi * j / sides)) * cos(a),
                                        (major + minor * cos(2 * pi * j / sides)) * sin(a),
                                        minor * sin(2 * pi * j / sides))) for j in range(sides)])
        for i in range(segs):
            a, b = rings[i], rings[(i + 1) % count]
            for j in range(sides):
                k = (j + 1) % sides
                bm.faces.new((a[j], b[j], b[k], a[k])).smooth = True
        bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    return cached(("torus", round(major, 4), round(minor, 4), segs, sides, round(arc, 4)), material, build)


# ------------------------------------------------------------------ objects

def unique(name):
    NAMES[name] = NAMES.get(name, 0) + 1
    return name if NAMES[name] == 1 else f"{name}-{NAMES[name]:02d}"


def add(parent, name, mesh, loc=(0, 0, 0), rot=(0, 0, 0), scale=(1, 1, 1)):
    ob = bpy.data.objects.new(unique(name), mesh)
    collection.objects.link(ob)
    ob.parent = parent
    ob.location = loc
    ob.rotation_euler = rot
    ob.scale = scale
    return ob


def empty(parent, name, loc=(0, 0, 0), rot_z=0.0, **props):
    ob = add(parent, name, None, loc, (0, 0, radians(rot_z)))
    ob.empty_display_size = 0.1
    for key, value in props.items():
        ob[key] = value
    return ob


def thing(parent, name, family, loc=(0, 0, 0), rot_z=0.0, **props):
    """A logical, intentionally placed object. Its parts are children."""
    ob = empty(parent, name, loc, rot_z, family=family, area=parent["area"], **props)
    THINGS.append(ob)
    return ob


def area(name):
    return empty(None, name, area=name)


def box(parent, name, material, size, loc, rot=(0, 0, 0)):
    return add(parent, name, box_mesh(material), loc, tuple(radians(a) for a in rot), size)


def cyl(parent, name, material, radius, height, loc, segs=12, top=1.0, rot=(0, 0, 0)):
    return add(parent, name, cyl_mesh(material, segs, top), loc, tuple(radians(a) for a in rot), (radius, radius, height))


def rod(parent, name, material, radius, start, end, segs=8, top=1.0):
    start, end = Vector(start), Vector(end)
    ob = add(parent, name, cyl_mesh(material, segs, top), start, scale=(radius, radius, (end - start).length))
    ob.rotation_mode = "QUATERNION"
    ob.rotation_quaternion = Vector((0, 0, 1)).rotation_difference((end - start).normalized())
    return ob


def ball(parent, name, material, scale, loc, sub=2, rot=(0, 0, 0)):
    if isinstance(scale, (int, float)):
        scale = (scale, scale, scale)
    return add(parent, name, ico_mesh(material, sub), loc, tuple(radians(a) for a in rot), scale)


def pillow(parent, name, material, half, loc, rot=(0, 0, 0)):
    return add(parent, name, pillow_mesh(material), loc, tuple(radians(a) for a in rot), half)


def rock(parent, name, material, scale, loc, variant=0, rot_z=0.0):
    return add(parent, name, rock_mesh(material, variant), loc, (0, 0, radians(rot_z)), scale)


def lathe(parent, name, key, material, profile, loc, segs=16, scale=(1, 1, 1), rot=(0, 0, 0)):
    return add(parent, name, lathe_mesh(key, material, profile, segs), loc, tuple(radians(a) for a in rot), scale)


def torus(parent, name, material, major, minor, loc, rot=(0, 0, 0), segs=24, sides=8, arc=2 * pi):
    return add(parent, name, torus_mesh(material, major, minor, segs, sides, arc), loc, tuple(radians(a) for a in rot))


def leaf(parent, name, material, width, length, loc, lean, azimuth):
    ob = add(parent, name, leaf_mesh(material), loc, scale=(width, 1, length))
    ob.rotation_euler = Euler((radians(lean), 0, radians(azimuth)), "XYZ")
    return ob


def clump(parent, loc, count, length, width, lean, material, name="blade"):
    """Leaves fanned around a point: grasses, ferns and rosettes."""
    for i in range(count):
        leaf(parent, name, material, width * rng.uniform(0.8, 1.2), length * rng.uniform(0.75, 1.15),
             loc, lean + rng.uniform(-10, 10), 360 * i / count + rng.uniform(-12, 12))


# ---------------------------------------------------------------- structure

def build_structure():
    a = area("structure")
    deck = thing(a, "deck", "timber deck")
    boards = 23
    width = 2 * D / boards
    for i in range(boards):
        box(deck, "deck-board", M.deck if i % 2 else M.deck2, (2 * D, width - 0.012, 0.05), (0, -D + width * (i + 0.5), -0.025))
    box(deck, "deck-underlay", M.trim, (2 * D - 0.02, 2 * D - 0.02, 0.02), (0, 0, -0.06))
    for s in (-1, 1):
        box(deck, "deck-fascia", M.trim, (2 * D + 0.08, 0.04, 0.2), (0, s * (D + 0.02), -0.1))
        box(deck, "deck-fascia", M.trim, (0.04, 2 * D, 0.2), (s * (D + 0.02), 0, -0.1))
    for x in (-4, -2, 0, 2, 4):
        for y in (-4, 0, 4):
            cyl(deck, "deck-stump", M.stone, 0.12, 0.23, (x, y, GROUND), 8)

    steps = thing(a, "front-steps", "steps", (0, -D, 0))
    for i, (y, z) in enumerate(((-0.24, -0.1), (-0.66, -0.2))):
        box(steps, "step-tread", M.deck, (2.4, 0.4, 0.05), (0, y, z - 0.025))
        box(steps, "step-riser", M.stone, (2.3, 0.34, 0.3 + z - 0.05), (0, y, GROUND + (0.3 + z - 0.05) / 2))

    posts = [(sx * POST, sy * POST) for sx in (-1, 1) for sy in (-1, 1)]
    posts += [(-1.5, POST), (1.5, POST), (-POST, -1.5), (POST, -1.5), (-POST, 1.6), (POST, 1.6),
              (-INNER, -POST), (INNER, -POST)]
    for x, y in posts:
        post = thing(a, "post", "ironbark post", (x, y, 0))
        box(post, "post-foot", M.stone, (0.28, 0.28, 0.1), (0, 0, 0.05))
        box(post, "post-shaft", M.ironbark, (0.15, 0.15, H - 0.1), (0, 0, 0.1 + (H - 0.1) / 2))
        box(post, "post-collar", M.trim, (0.21, 0.21, 0.05), (0, 0, H - 0.1))

    beams = thing(a, "roof-beams", "roof beam", (0, 0, H))
    span = 2 * POST + 0.3
    for s in (-1, 1):
        box(beams, "perimeter-beam", M.ironbark, (span, 0.14, 0.22), (0, s * POST, 0.11))
        box(beams, "perimeter-beam", M.ironbark, (0.14, span, 0.22), (s * POST, 0, 0.11))
        box(beams, "inner-beam", M.ironbark, (0.12, 2 * POST, 0.2), (s * INNER, 0, 0.1))
    box(beams, "inner-beam", M.ironbark, (2 * INNER + 0.12, 0.12, 0.2), (0, INNER, 0.1))

    canopy = thing(a, "canopy", "canopy slat", (0, 0, H + 0.24))
    step = 0.2
    x = -D
    while x <= D + 1e-6:
        box(canopy, "canopy-slat", M.slat, (0.07, 2.25, 0.035), (x, 3.65, 0))
        x += step
    y = -D
    while y <= 2.45:
        for s in (-1, 1):
            box(canopy, "canopy-slat", M.slat, (2.25, 0.07, 0.035), (s * 3.65, y, 0))
        y += step
    for s in (-1, 1):
        box(canopy, "canopy-edge", M.trim, (0.05, 2 * D + 0.3, 0.09), (s * (D + 0.15), 0, 0))
    box(canopy, "canopy-edge", M.trim, (2 * D + 0.3, 0.05, 0.09), (0, D + 0.15, 0))

    def battens(name, start, end):
        wall = thing(a, name, "batten wall")
        start, end = Vector(start), Vector(end)
        along = end - start
        length = along.length
        angle = Vector((1, 0)).angle_signed(along.normalized())
        mid = (start + end) / 2
        wall.location = (mid.x, mid.y, 0)
        wall.rotation_euler = (0, 0, -angle)
        for z in (0.12, 2.1):
            box(wall, "batten-rail", M.trim, (length, 0.06, 0.07), (0, 0, z))
        count = int(length / 0.12)
        for i in range(count):
            box(wall, "batten", M.slat, (0.045, 0.03, 1.92), (-length / 2 + length * (i + 0.5) / count, 0, 1.11))

    battens("batten-wall-back-left", (-POST + 0.1, POST), (-1.6, POST))
    battens("batten-wall-back-right", (1.6, POST), (POST - 0.1, POST))
    battens("batten-wall-left", (-POST, 1.7), (-POST, POST - 0.1))

    def railing(name, x):
        rail = thing(a, name, "railing", (x, -3.0, 0))
        box(rail, "rail-top", M.ironbark, (0.08, 2.84, 0.06), (0, 0, 0.92))
        box(rail, "rail-bottom", M.ironbark, (0.06, 2.84, 0.05), (0, 0, 0.14))
        for i in range(18):
            box(rail, "baluster", M.slat, (0.03, 0.03, 0.74), (0, -1.36 + 0.16 * i, 0.53))

    railing("railing-left", -POST)
    railing("railing-right", POST)

    # Sliding screen on the tea side. The slider's local X runs along the wall.
    screen = thing(a, "sliding-screen", "sliding screen", (POST, 1.72, 0), 90, interaction="screen")
    box(screen, "screen-track", M.trim, (2.72, 0.12, 0.05), (1.36, 0, 2.08))
    box(screen, "screen-sill", M.trim, (2.72, 0.12, 0.04), (1.36, 0, 0.06))

    def panel(parent, offset_y):
        box(parent, "screen-stile", M.ironbark, (0.05, 0.035, 1.98), (0.025, offset_y, 1.07))
        box(parent, "screen-stile", M.ironbark, (0.05, 0.035, 1.98), (1.335, offset_y, 1.07))
        for z in (0.105, 2.035):
            box(parent, "screen-rail", M.ironbark, (1.36, 0.035, 0.05), (0.68, offset_y, z))
        box(parent, "screen-paper", M.shoji, (1.28, 0.006, 1.9), (0.68, offset_y, 1.07))
        for i in range(1, 4):
            box(parent, "screen-lattice", M.paleoak, (0.014, 0.02, 1.9), (0.34 * i, offset_y, 1.07))
        for i in range(1, 6):
            box(parent, "screen-lattice", M.paleoak, (1.28, 0.02, 0.014), (0.68, offset_y, 0.13 + 0.317 * i))

    fixed = empty(screen, "screen-fixed-panel", (1.36, 0, 0))
    panel(fixed, -0.03)
    slider = empty(screen, "screen-sliding-panel", role="slide", travel=1.3)
    panel(slider, 0.03)
    return a


# ----------------------------------------------------------------- lanterns

SHADE = [(0, 0), (0.07, 0), (0.15, 0.07), (0.185, 0.18), (0.15, 0.29), (0.07, 0.36), (0, 0.36)]


def build_lanterns():
    a = area("lanterns")
    spots = [(-1.6, INNER), (1.6, INNER), (-INNER, 0.9), (-INNER, -1.7), (-INNER, -3.9),
             (INNER, 0.9), (INNER, -1.7), (INNER, -3.9)]
    for x, y in spots:
        lantern = thing(a, "hanging-lantern", "hanging lantern", (x, y, 2.02), interaction="lanterns", lamp=1)
        rod(lantern, "lantern-cord", M.trim, 0.006, (0, 0, 0.2), (0, 0, H - 2.02), 6)
        cyl(lantern, "lantern-cap", M.trim, 0.075, 0.03, (0, 0, 0.18), 12)
        lathe(lantern, "lantern-shade", "shade", M.paper, SHADE, (0, 0, -0.18), 14)
        for z, r in ((-0.09, 0.166), (0, 0.19), (0.09, 0.166)):
            cyl(lantern, "lantern-rib", M.trim, r, 0.008, (0, 0, z - 0.004), 14)
        cyl(lantern, "lantern-base", M.trim, 0.075, 0.025, (0, 0, -0.2), 12)
        rod(lantern, "lantern-tassel", M.ribbon, 0.012, (0, 0, -0.2), (0, 0, -0.36), 6, 0.3)

    for x in (-1.75, 1.75):
        lamp = thing(a, "floor-lantern", "floor lantern", (x, -4.15, 0.36), interaction="lanterns", lamp=1)
        for sx in (-1, 1):
            for sy in (-1, 1):
                box(lamp, "floor-lantern-leg", M.trim, (0.03, 0.03, 0.66), (sx * 0.13, sy * 0.13, -0.03))
        box(lamp, "floor-lantern-paper", M.paper, (0.24, 0.24, 0.44), (0, 0, 0))
        box(lamp, "floor-lantern-top", M.trim, (0.32, 0.32, 0.03), (0, 0, 0.3))
        box(lamp, "floor-lantern-shelf", M.trim, (0.3, 0.3, 0.02), (0, 0, -0.24))
    return a


# ----------------------------------------------------------- reading corner

BOOKS = ("book1", "book2", "book3", "book4", "book5", "book6")


def book_row(parent, name, start_x, end_x, y, z, lean_last=True):
    row = thing(parent, name, "book row", (0, y, z))
    x = start_x
    count = 0
    while x < end_x - 0.05:
        thickness = rng.uniform(0.028, 0.055)
        height = rng.uniform(0.2, 0.3)
        depth = rng.uniform(0.17, 0.21)
        material = getattr(M, rng.choice(BOOKS))
        last = x + thickness + 0.06 > end_x - 0.05
        tilt = -14 if (last and lean_last) else 0
        offset = 0.03 if tilt else 0
        book = box(row, "book-spine", material, (thickness, depth, height), (x + thickness / 2 + offset, -0.02, height / 2), (0, tilt, 0))
        if rng.random() < 0.6:
            box(row, "book-band", M.brass if rng.random() < 0.5 else M.cream, (thickness + 0.002, 0.004, 0.02),
                (book.location.x, -0.02 - depth / 2, height * 0.72), (0, tilt, 0))
        x += thickness + 0.003
        count += 1
    row["parts"] = count
    return row


def book_stack(parent, name, loc, count, rot_z=0):
    stack = thing(parent, name, "book stack", loc, rot_z)
    z = 0
    for i in range(count):
        thickness = rng.uniform(0.03, 0.05)
        box(stack, "stacked-book", getattr(M, BOOKS[(i * 2 + 1) % 6]), (rng.uniform(0.2, 0.26), rng.uniform(0.15, 0.19), thickness),
            (rng.uniform(-0.01, 0.01), rng.uniform(-0.01, 0.01), z + thickness / 2), (0, 0, rng.uniform(-9, 9)))
        z += thickness
    return stack


def build_reading():
    a = area("reading-corner")
    rug = thing(a, "striped-rug", "rug", (-3.25, 3.15, 0))
    box(rug, "rug-field", M.indigo, (2.5, 1.9, 0.014), (0, 0, 0.007))
    for i in range(5):
        box(rug, "rug-stripe", M.cream if i % 2 == 0 else M.ochre, (2.5, 0.09, 0.016), (0, -0.7 + 0.35 * i, 0.008))

    chair = thing(a, "armchair", "armchair", (-3.75, 3.6, 0), 42)
    for sx in (-1, 1):
        for sy in (-1, 1):
            box(chair, "chair-leg", M.ironbark, (0.055, 0.055, 0.27), (sx * 0.36, sy * 0.33, 0.135))
        box(chair, "chair-arm", M.paleoak, (0.09, 0.78, 0.045), (sx * 0.4, -0.02, 0.6))
        box(chair, "chair-arm-post", M.ironbark, (0.05, 0.05, 0.3), (sx * 0.4, -0.33, 0.44))
    box(chair, "chair-seat-frame", M.ironbark, (0.82, 0.76, 0.07), (0, 0, 0.3))
    box(chair, "chair-back-frame", M.ironbark, (0.82, 0.07, 0.62), (0, 0.38, 0.62), (-9, 0, 0))
    for i in range(5):
        box(chair, "chair-back-slat", M.paleoak, (0.07, 0.03, 0.5), (-0.28 + 0.14 * i, 0.345, 0.64), (-9, 0, 0))
    pillow(chair, "chair-seat-cushion", M.sage, (0.36, 0.33, 0.085), (0, -0.03, 0.42))
    pillow(chair, "chair-back-cushion", M.sage, (0.33, 0.085, 0.25), (0, 0.27, 0.7), (-9, 0, 0))
    pillow(chair, "chair-throw-cushion", M.terracotta, (0.17, 0.07, 0.17), (-0.16, 0.14, 0.62), (-20, 0, 18))

    stool = thing(a, "footstool", "footstool", (-3.05, 2.85, 0), 42)
    for sx in (-1, 1):
        for sy in (-1, 1):
            box(stool, "footstool-leg", M.ironbark, (0.045, 0.045, 0.22), (sx * 0.2, sy * 0.16, 0.11))
    box(stool, "footstool-frame", M.ironbark, (0.5, 0.4, 0.05), (0, 0, 0.245))
    pillow(stool, "footstool-cushion", M.ochre, (0.24, 0.19, 0.07), (0, 0, 0.33))

    shelf = thing(a, "bookshelf", "bookshelf", (-2.75, 4.27, 0))
    for sx in (-1, 1):
        box(shelf, "shelf-side", M.ironbark, (0.04, 0.3, 1.52), (sx * 0.8, 0, 0.76))
    levels = (0.08, 0.5, 0.92, 1.34)
    for z in levels + (1.5,):
        box(shelf, "shelf-board", M.paleoak, (1.6, 0.3, 0.035), (0, 0, z))
    box(shelf, "shelf-back", M.trim, (1.6, 0.015, 1.5), (0, 0.143, 0.76))
    book_row(a, "books-lower", -3.5, -2.55, 4.27, levels[0] + 0.018)
    book_row(a, "books-middle", -3.5, -2.9, 4.27, levels[1] + 0.018)
    book_row(a, "books-upper", -3.1, -2.02, 4.27, levels[2] + 0.018)
    book_stack(a, "books-lying", (-2.25, 4.25, levels[0] + 0.018), 4, 4)
    book_stack(a, "books-on-top", (-3.3, 4.25, 1.518), 2, -8)
    vase = thing(a, "shelf-vase", "vase", (-2.45, 4.25, levels[1] + 0.018))
    lathe(vase, "vase-body", "shelfvase", M.celadon, [(0, 0), (0.05, 0), (0.075, 0.06), (0.06, 0.14), (0.03, 0.2), (0.038, 0.23), (0.03, 0.23), (0.022, 0.2), (0, 0.19)], (0, 0, 0), 14)
    rod(vase, "vase-stem", M.trunk, 0.004, (0, 0, 0.2), (0.04, 0, 0.45), 5)
    for dx, dz in ((0.03, 0.4), (0.05, 0.46), (0.0, 0.34)):
        ball(vase, "vase-blossom", M.blossom, 0.02, (dx, 0.0, dz), 1)
    clock = thing(a, "shelf-clock", "clock", (-3.3, 4.22, levels[2] + 0.018))
    cyl(clock, "clock-case", M.brass, 0.09, 0.05, (0, 0.025, 0.1), 16, rot=(90, 0, 0))
    cyl(clock, "clock-face", M.porcelain, 0.078, 0.004, (0, -0.026, 0.1), 16, rot=(90, 0, 0))
    box(clock, "clock-hand", M.ink, (0.006, 0.003, 0.055), (0, -0.031, 0.122))
    box(clock, "clock-hand", M.ink, (0.04, 0.003, 0.006), (0.018, -0.031, 0.1))
    box(clock, "clock-foot", M.brass, (0.12, 0.05, 0.012), (0, 0, 0.006))
    fern = thing(a, "shelf-fern", "potted plant", (-2.3, 4.25, 1.518))
    lathe(fern, "plant-pot", "pot", M.pot, POT, (0, 0, 0), 12, (0.55, 0.55, 0.55))
    clump(fern, (0, 0, 0.1), 11, 0.3, 0.07, 55, M.leaf2, "fern-frond")

    table = thing(a, "side-table", "side table", (-2.55, 3.05, 0))
    cyl(table, "table-top", M.paleoak, 0.34, 0.035, (0, 0, 0.5), 20)
    cyl(table, "table-shelf", M.paleoak, 0.22, 0.02, (0, 0, 0.2), 20)
    for i in range(3):
        angle = 2 * pi * i / 3 + 0.5
        rod(table, "table-leg", M.ironbark, 0.018, (0.27 * cos(angle), 0.27 * sin(angle), 0), (0.2 * cos(angle), 0.2 * sin(angle), 0.5), 6)

    # Journal: the cover hinges on the spine, which lies along local Y at x = 0.
    journal = thing(a, "journal", "journal", (-2.52, 3.03, 0.535), 205, interaction="journal")
    box(journal, "journal-back-cover", M.leather, (0.27, 0.35, 0.005), (0.135, 0, 0.0025))
    box(journal, "journal-pages", M.page, (0.26, 0.34, 0.028), (0.132, 0, 0.019))
    box(journal, "journal-spine", M.leather, (0.008, 0.35, 0.038), (-0.004, 0, 0.019))
    for i in range(7):
        box(journal, "journal-line", M.ink, (0.19, 0.004, 0.001), (0.135, 0.12 - 0.035 * i, 0.0333))
    box(journal, "journal-ribbon", M.ribbon, (0.012, 0.4, 0.001), (0.2, -0.03, 0.0334))
    cover = empty(journal, "journal-cover", (0, 0, 0.0355), role="hinge", angle=168)
    box(cover, "journal-front-cover", M.leather, (0.27, 0.35, 0.005), (0.135, 0, 0))
    box(cover, "journal-endpaper", M.page, (0.25, 0.33, 0.001), (0.135, 0, -0.0028))
    box(cover, "journal-label", M.brass, (0.1, 0.05, 0.001), (0.135, 0.06, 0.003))
    pen = thing(a, "fountain-pen", "pen", (-2.75, 2.93, 0.542), 30)
    rod(pen, "pen-barrel", M.ink, 0.006, (-0.07, 0, 0), (0.07, 0, 0), 6)
    rod(pen, "pen-nib", M.brass, 0.005, (0.07, 0, 0), (0.095, 0, 0), 6, 0.1)
    mug = thing(a, "reading-mug", "mug", (-2.42, 3.25, 0.535))
    lathe(mug, "mug-body", "cup", M.porcelain, CUP, (0, 0, 0), 14, (1.25, 1.25, 1.5))
    torus(mug, "mug-handle", M.porcelain, 0.022, 0.006, (0.058, 0, 0.045), (90, 0, 0), 12, 6, pi)

    lamp = thing(a, "reading-lamp", "reading lamp", (-4.15, 2.75, 0), interaction="lanterns")
    cyl(lamp, "lamp-base", M.iron, 0.16, 0.03, (0, 0, 0), 16)
    rod(lamp, "lamp-stem", M.brass, 0.014, (0, 0, 0.03), (0, 0, 1.5), 8)
    rod(lamp, "lamp-arm", M.brass, 0.012, (0, 0, 1.5), (0.3, 0.22, 1.62), 8)
    bulb = empty(lamp, "lamp-glow", (0.3, 0.22, 1.5), lamp=1)
    cyl(bulb, "lamp-shade", M.paper, 0.17, 0.2, (0, 0, -0.06), 16, 0.45)
    book_stack(a, "books-by-chair", (-4.2, 3.2, 0.014), 3, 20)
    return a


# -------------------------------------------------------------- tea setting

CUP = [(0, 0), (0.026, 0), (0.036, 0.02), (0.04, 0.055), (0.037, 0.055), (0.033, 0.022), (0.024, 0.012), (0, 0.012)]
POT = [(0, 0), (0.1, 0), (0.15, 0.24), (0.165, 0.26), (0.14, 0.26), (0.125, 0.22), (0, 0.2)]
KETTLE = [(0, 0), (0.07, 0), (0.105, 0.035), (0.115, 0.08), (0.1, 0.125), (0.06, 0.145), (0.05, 0.15), (0, 0.15)]


def kettle(parent, prefix, material, scale=1.0):
    s = scale
    lathe(parent, f"{prefix}-body", "kettle", material, KETTLE, (0, 0, 0), 16, (s, s, s))
    lathe(parent, f"{prefix}-lid", "kettlelid", material, [(0, 0.15), (0.05, 0.15), (0.035, 0.165), (0, 0.17)], (0, 0, 0), 12, (s, s, s))
    ball(parent, f"{prefix}-knob", M.brass, 0.014 * s, (0, 0, 0.18 * s), 1)
    rod(parent, f"{prefix}-spout", material, 0.02 * s, (0.09 * s, 0, 0.07 * s), (0.18 * s, 0, 0.14 * s), 8, 0.55)
    torus(parent, f"{prefix}-handle", M.brass, 0.085 * s, 0.006 * s, (0, 0, 0.13 * s), (90, 0, 90), 14, 6, pi)


def tea_cup(parent, name, loc):
    cup = thing(parent, name, "tea cup", loc, interaction="tea")
    lathe(cup, "cup-body", "cup", M.celadon, CUP, (0, 0, 0), 14)
    add(cup, "cup-tea", disc_mesh(M.tea, 14), (0, 0, 0.006), scale=(0.02, 0.02, 1))
    cup.children[-1]["role"] = "level"
    cup.children[-1]["rise"] = 0.042
    cup.children[-1]["grow"] = 1.8
    return cup


def build_tea():
    a = area("tea-setting")
    cx, cy = 3.4, 3.3
    mat_ = thing(a, "tatami-mat", "floor mat", (cx, cy, 0))
    box(mat_, "mat-field", M.tatami, (2.3, 2.2, 0.03), (0, 0, 0.015))
    for s in (-1, 1):
        box(mat_, "mat-border", M.moss, (2.3, 0.07, 0.032), (0, s * 1.065, 0.016))
        box(mat_, "mat-border", M.moss, (0.07, 2.2, 0.032), (s * 1.115, 0, 0.016))
    box(mat_, "mat-seam", M.moss, (0.02, 2.06, 0.031), (0, 0, 0.0158))

    top = 0.41
    table = thing(a, "tea-table", "low table", (cx, cy, 0.03))
    box(table, "tea-table-top", M.ironbark, (1.25, 0.78, 0.05), (0, 0, 0.355))
    box(table, "tea-table-inlay", M.paleoak, (1.1, 0.63, 0.004), (0, 0, 0.381))
    for sx in (-1, 1):
        for sy in (-1, 1):
            box(table, "tea-table-leg", M.ironbark, (0.07, 0.07, 0.33), (sx * 0.55, sy * 0.32, 0.165))
        box(table, "tea-table-apron", M.trim, (0.03, 0.57, 0.06), (sx * 0.55, 0, 0.3))

    tray = thing(a, "serving-tray", "serving tray", (cx - 0.22, cy, top + 0.004))
    box(tray, "tray-base", M.paleoak, (0.56, 0.36, 0.012), (0, 0, 0.006))
    for s in (-1, 1):
        box(tray, "tray-rim", M.trim, (0.56, 0.014, 0.03), (0, s * 0.18, 0.015))
        box(tray, "tray-rim", M.trim, (0.014, 0.36, 0.03), (s * 0.28, 0, 0.015))
    pot = thing(a, "teapot", "teapot", (cx - 0.33, cy + 0.02, top + 0.016), 25)
    kettle(pot, "teapot", M.iron)
    tea_cup(a, "tea-cup-tray-a", (cx - 0.1, cy - 0.08, top + 0.016))
    tea_cup(a, "tea-cup-tray-b", (cx - 0.07, cy + 0.08, top + 0.016))
    tea_cup(a, "tea-cup-guest-a", (cx + 0.2, cy - 0.25, top + 0.004))
    tea_cup(a, "tea-cup-guest-b", (cx + 0.38, cy + 0.2, top + 0.004))

    plate = thing(a, "sweets-plate", "sweets plate", (cx + 0.38, cy - 0.08, top + 0.004))
    lathe(plate, "plate-body", "plate", M.porcelain, [(0, 0), (0.05, 0), (0.085, 0.014), (0.08, 0.016), (0.048, 0.006), (0, 0.006)], (0, 0, 0), 16)
    for i, material in enumerate((M.blossom, M.sage, M.cream)):
        ball(plate, "sweet", material, (0.02, 0.02, 0.014), (0.032 * cos(2.1 * i), 0.032 * sin(2.1 * i), 0.02), 1)
    caddy = thing(a, "tea-caddy", "tea caddy", (cx + 0.05, cy + 0.26, top + 0.004))
    cyl(caddy, "caddy-body", M.brass, 0.035, 0.075, (0, 0, 0), 14)
    cyl(caddy, "caddy-lid", M.trim, 0.037, 0.018, (0, 0, 0.075), 14)
    bud = thing(a, "bud-vase", "vase", (cx + 0.52, cy + 0.28, top + 0.004))
    lathe(bud, "bud-vase-body", "budvase", M.porcelain, [(0, 0), (0.03, 0), (0.042, 0.05), (0.02, 0.11), (0.024, 0.13), (0.017, 0.13), (0.012, 0.11), (0, 0.1)], (0, 0, 0), 12)
    rod(bud, "bud-stem", M.moss, 0.003, (0, 0, 0.1), (0.02, -0.01, 0.34), 5)
    leaf(bud, "bud-leaf", M.leaf, 0.035, 0.09, (0.008, -0.004, 0.2), 50, 40)
    leaf(bud, "bud-leaf", M.leaf, 0.035, 0.08, (0.012, -0.006, 0.25), 55, 220)
    ball(bud, "bud-flower", M.maple, 0.024, (0.02, -0.01, 0.35), 1)

    seats = ((0, -0.82, M.indigo), (0, 0.82, M.terracotta), (-1.0, 0, M.ochre), (1.0, 0, M.sage))
    for i, (dx, dy, material) in enumerate(seats):
        cushion = thing(a, "floor-cushion", "floor cushion", (cx + dx, cy + dy, 0.03), 8 * i - 10)
        pillow(cushion, "floor-cushion-pad", material, (0.29, 0.29, 0.055), (0, 0, 0.055))
        cyl(cushion, "floor-cushion-button", M.cream, 0.02, 0.006, (0, 0, 0.107), 8)

    brazier = thing(a, "brazier", "brazier", (2.25, 4.05, 0))
    cyl(brazier, "brazier-body", M.stone, 0.24, 0.26, (0, 0, 0), 10, 0.85)
    cyl(brazier, "brazier-ash", M.stonepale, 0.17, 0.01, (0, 0, 0.255), 10)
    for i in range(3):
        box(brazier, "brazier-trivet", M.iron, (0.03, 0.2, 0.012), (0.05 * cos(2.1 * i), 0.05 * sin(2.1 * i), 0.27), (0, 0, 120 * i))
    iron = thing(a, "iron-kettle", "kettle", (2.25, 4.05, 0.276), -30)
    kettle(iron, "kettle", M.iron, 1.35)
    return a


# ---------------------------------------------------------- planted seating

def shrub(parent, name, loc, stems, height, material, fruit=None):
    plant = thing(parent, name, "planter shrub", loc)
    for i in range(stems):
        angle = 2 * pi * i / stems + rng.uniform(-0.3, 0.3)
        tip = (0.16 * cos(angle), 0.16 * sin(angle), height * rng.uniform(0.7, 0.9))
        rod(plant, "shrub-stem", M.trunk, 0.012, (0.03 * cos(angle), 0.03 * sin(angle), 0), tip, 5, 0.5)
        ball(plant, "shrub-foliage", material, rng.uniform(0.17, 0.24), (tip[0] * 1.2, tip[1] * 1.2, tip[2] + 0.08), 2)
    ball(plant, "shrub-foliage", material, 0.26, (0, 0, height), 2)
    if fruit:
        for i in range(7):
            angle = rng.uniform(0, 2 * pi)
            ball(plant, "shrub-fruit", fruit, 0.035, (0.27 * cos(angle), 0.27 * sin(angle), height * rng.uniform(0.75, 1.1)), 1)
    return plant


def potted(parent, name, loc, size, kind):
    pot = thing(parent, name, "potted plant", loc)
    lathe(pot, "plant-pot", "pot", M.pot, POT, (0, 0, 0), 12, (size, size, size))
    cyl(pot, "pot-soil", M.soil, 0.125 * size, 0.01, (0, 0, 0.215 * size), 12)
    top = (0, 0, 0.22 * size)
    if kind == "fern":
        clump(pot, top, 13, 0.42 * size, 0.09 * size, 52, M.leaf2, "fern-frond")
    elif kind == "succulent":
        clump(pot, top, 9, 0.16 * size, 0.09 * size, 48, M.leaf3, "rosette-leaf")
        clump(pot, top, 5, 0.1 * size, 0.07 * size, 20, M.leaf2, "rosette-leaf")
    else:
        for i in range(5):
            angle = 2 * pi * i / 5
            tip = (0.1 * size * cos(angle), 0.1 * size * sin(angle), top[2] + rng.uniform(0.45, 0.65) * size)
            rod(pot, "flower-stem", M.moss, 0.006, top, tip, 5)
            ball(pot, "flower-head", M.lavender, (0.035, 0.035, 0.07), tip, 1)
        clump(pot, top, 8, 0.25 * size, 0.05 * size, 35, M.leaf, "flower-leaf")
    return pot


def build_seating():
    a = area("planted-seating")
    bench = thing(a, "garden-bench", "bench", (-3.82, -2.85, 0))
    for i in range(5):
        box(bench, "bench-seat-slat", M.paleoak, (0.095, 2.3, 0.03), (-0.22 + 0.11 * i, 0, 0.43))
    for sy in (-1, 0, 1):
        box(bench, "bench-frame", M.ironbark, (0.52, 0.06, 0.06), (0, sy * 1.05, 0.385))
        for sx in (-1, 1):
            box(bench, "bench-leg", M.ironbark, (0.06, 0.06, 0.36), (sx * 0.22, sy * 1.05, 0.18))
        box(bench, "bench-back-post", M.ironbark, (0.05, 0.06, 0.55), (-0.3, sy * 1.05, 0.68), (0, -8, 0))
    for z in (0.6, 0.74, 0.88):
        box(bench, "bench-back-board", M.paleoak, (0.025, 2.3, 0.1), (-0.27 - (z - 0.6) * 0.14, 0, z), (0, -8, 0))
    for i, material in enumerate((M.terracotta, M.cream, M.indigo)):
        cushion = thing(a, "bench-cushion", "seat cushion", (-3.8, -3.6 + 0.75 * i, 0.445))
        pillow(cushion, "bench-cushion-pad", material, (0.24, 0.35, 0.055), (0, 0, 0.055))
    for y, material, tilt in ((-3.45, M.ochre, 12), (-2.25, M.sage, -10)):
        back = thing(a, "bench-bolster", "seat cushion", (-4.0, y, 0.72), tilt)
        pillow(back, "bench-bolster-pad", material, (0.07, 0.2, 0.2), (0, 0, 0), (0, -14, 0))

    trough = thing(a, "trough-planter", "planter", (-4.34, -2.85, 0))
    box(trough, "trough-body", M.ironbark, (0.26, 2.5, 0.5), (0, 0, 0.25))
    box(trough, "trough-rim", M.trim, (0.3, 2.54, 0.04), (0, 0, 0.5))
    box(trough, "trough-soil", M.soil, (0.22, 2.44, 0.01), (0, 0, 0.522))
    for i in range(7):
        grass = thing(a, "trough-grass", "ornamental grass", (-4.34, -3.9 + 0.35 * i, 0.525))
        clump(grass, (0, 0, 0), 9, 0.62, 0.035, 16, M.leaf if i % 2 else M.leaf2)

    for name, y, material, fruit in (("citrus-planter", -4.18, M.foliage3, M.citrus), ("camellia-planter", -1.5, M.foliage, M.blossom)):
        planter = thing(a, name, "planter", (-3.85, y, 0))
        box(planter, "planter-body", M.stonepale, (0.56, 0.4, 0.5), (0, 0, 0.25))
        box(planter, "planter-rim", M.stone, (0.6, 0.44, 0.04), (0, 0, 0.5))
        box(planter, "planter-soil", M.soil, (0.5, 0.34, 0.01), (0, 0, 0.522))
        shrub(a, name.replace("planter", "shrub"), (-3.85, y, 0.525), 3, 0.62, material, fruit)

    potted(a, "fern-pot", (-2.95, -4.15, 0), 1.25, "fern")
    potted(a, "lavender-pot", (-2.45, -4.25, 0), 0.9, "flower")
    potted(a, "succulent-pot", (-2.78, -3.72, 0), 0.7, "succulent")

    can = thing(a, "watering-can", "watering can", (-3.05, -3.25, 0), 140)
    cyl(can, "can-body", M.zinc, 0.1, 0.22, (0, 0, 0), 14)
    rod(can, "can-spout", M.zinc, 0.016, (0.09, 0, 0.05), (0.3, 0, 0.24), 8, 0.7)
    cyl(can, "can-rose", M.zinc, 0.035, 0.02, (0.3, 0, 0.24), 10, rot=(0, 48, 0))
    torus(can, "can-handle", M.zinc, 0.09, 0.008, (-0.06, 0, 0.17), (90, 0, 0), 14, 6, pi * 1.1)

    crate = thing(a, "crate-table", "crate table", (-3.25, -1.9, 0), 12)
    for z in (0.06, 0.2, 0.34):
        for s in (-1, 1):
            box(crate, "crate-slat", M.slat, (0.5, 0.02, 0.1), (0, s * 0.19, z))
            box(crate, "crate-slat", M.slat, (0.02, 0.36, 0.1), (s * 0.24, 0, z))
    box(crate, "crate-top", M.paleoak, (0.54, 0.44, 0.025), (0, 0, 0.405))
    potted(a, "crate-succulent", (-3.33, -1.83, 0.418), 0.45, "succulent")
    trowel = thing(a, "hand-trowel", "trowel", (-3.15, -1.98, 0.425), 60)
    rod(trowel, "trowel-handle", M.slat, 0.012, (0, 0, 0), (0.1, 0, 0), 6)
    box(trowel, "trowel-blade", M.zinc, (0.11, 0.05, 0.004), (0.155, 0, 0))

    basket = thing(a, "hanging-basket", "hanging basket", (-INNER, -2.8, 1.95))
    lathe(basket, "basket-bowl", "basket", M.trunk, [(0, 0), (0.1, 0.01), (0.19, 0.1), (0.2, 0.16), (0.18, 0.16), (0, 0.12)], (0, 0, 0), 12)
    for i in range(3):
        angle = 2 * pi * i / 3
        rod(basket, "basket-cord", M.trim, 0.004, (0.19 * cos(angle), 0.19 * sin(angle), 0.16), (0, 0, H - 1.95), 4)
    clump(basket, (0, 0, 0.14), 12, 0.38, 0.08, 118, M.leaf2, "trailing-leaf")
    clump(basket, (0, 0, 0.14), 7, 0.22, 0.07, 40, M.leaf, "basket-leaf")
    return a


# ------------------------------------------------------------ water feature

BASIN = [(0, 0), (0.42, 0), (0.6, 0.12), (0.72, 0.34), (0.74, 0.46), (0.7, 0.46), (0.66, 0.36), (0.52, 0.2), (0.3, 0.14), (0, 0.13)]


def build_water():
    a = area("water-feature")
    cx, cy = 3.45, -3.25
    bed = thing(a, "gravel-bed", "gravel bed", (cx, cy, 0))
    box(bed, "gravel-surface", M.gravel, (2.1, 2.1, 0.04), (0, 0, 0.02))
    for s in (-1, 1):
        box(bed, "bed-edge", M.ironbark, (2.26, 0.08, 0.08), (0, s * 1.09, 0.04))
        box(bed, "bed-edge", M.ironbark, (0.08, 2.1, 0.08), (s * 1.09, 0, 0.04))
    pebbles = thing(a, "pebble-scatter", "pebbles", (cx, cy, 0.04))
    count = 0
    while count < 26:
        x, y = rng.uniform(-0.98, 0.98), rng.uniform(-0.98, 0.98)
        if sqrt(x * x + y * y) < 0.82:
            continue
        size = rng.uniform(0.03, 0.06)
        ball(pebbles, "pebble", M.pebble if count % 3 else M.stonepale, (size, size * rng.uniform(0.7, 1), size * 0.5), (x, y, size * 0.3), 1, (0, 0, rng.uniform(0, 180)))
        count += 1
    pebbles["parts"] = count
    for i, (x, y, size) in enumerate(((-0.82, -0.72, 0.17), (0.86, -0.3, 0.13), (-0.55, 0.88, 0.12), (0.2, -0.95, 0.1))):
        stone = thing(a, "river-stone", "river stone", (cx + x, cy + y, 0.04), 40 * i)
        rock(stone, "river-stone-body", M.pebble if i % 2 else M.stone, (size, size * 0.8, size * 0.55), (0, 0, size * 0.4), i)

    basin = thing(a, "stone-basin", "stone basin", (cx, cy, 0.04), interaction="water")
    lathe(basin, "basin-bowl", "basin", M.stone, BASIN, (0, 0, 0), 28)
    water = add(basin, "basin-water", disc_mesh(M.water, 28), (0, 0, 0.24), scale=(0.555, 0.555, 1))
    water["role"] = "level"
    water["rise"] = 0.18
    water["grow"] = 1.225
    for x, y, r, turn in ((0.42, 0.2, 0.2, 20), (-0.3, 0.4, 0.16, 130), (-0.1, -0.5, 0.18, 250)):
        pad = add(water, "lily-pad", torus_mesh(M.lily, 0.5, 0.5, 12, 4, pi * 1.8), (x, y, 0.004), (0, 0, radians(turn)), (r, r, 0.012))
    ball(water, "lily-flower", M.blossom, (0.09, 0.09, 0.05), (-0.3, 0.4, 0.03), 1)
    ball(water, "lily-flower-heart", M.ochre, (0.035, 0.035, 0.035), (-0.3, 0.4, 0.06), 1)

    spout = thing(a, "bamboo-spout", "bamboo spout", (cx + 0.78, cy + 0.6, 0.04))
    cyl(spout, "spout-post", M.bamboo, 0.04, 0.95, (0, 0, 0), 10)
    for z in (0.3, 0.62, 0.93):
        cyl(spout, "bamboo-node", M.moss, 0.044, 0.012, (0, 0, z), 10)
    rod(spout, "spout-pipe", M.bamboo, 0.026, (0.12, 0.09, 0.88), (-0.5, -0.38, 0.7), 10)
    rod(spout, "spout-stream", M.water, 0.008, (-0.5, -0.38, 0.69), (-0.5, -0.38, 0.2), 6)
    box(spout, "spout-binding", M.trim, (0.1, 0.1, 0.03), (0, 0, 0.84), (0, 0, 37))

    ladle = thing(a, "bamboo-ladle", "ladle", (cx - 0.5, cy - 0.52, 0.505), 35)
    cyl(ladle, "ladle-cup", M.bamboo, 0.045, 0.06, (0, 0, 0), 10)
    rod(ladle, "ladle-handle", M.bamboo, 0.008, (-0.04, 0, 0.035), (-0.42, 0, 0.035), 6)

    toro = thing(a, "stone-lantern", "stone lantern", (cx + 0.75, cy - 0.85, 0.04), 20, interaction="lanterns")
    cyl(toro, "toro-base", M.stone, 0.2, 0.08, (0, 0, 0), 6)
    cyl(toro, "toro-shaft", M.stone, 0.07, 0.42, (0, 0, 0.08), 8)
    cyl(toro, "toro-platform", M.stone, 0.19, 0.05, (0, 0, 0.5), 6)
    glow = empty(toro, "toro-glow", (0, 0, 0.66), lamp=1)
    box(glow, "toro-window", M.paper, (0.17, 0.17, 0.2), (0, 0, 0))
    for sx in (-1, 1):
        for sy in (-1, 1):
            box(glow, "toro-pillar", M.stone, (0.035, 0.035, 0.22), (sx * 0.085, sy * 0.085, 0))
    cyl(toro, "toro-roof", M.stone, 0.27, 0.16, (0, 0, 0.77), 6, 0.12)
    ball(toro, "toro-finial", M.stone, 0.045, (0, 0, 0.95), 1)

    stool = thing(a, "stone-stool", "stone stool", (2.42, -2.45, 0))
    cyl(stool, "stool-body", M.stonepale, 0.2, 0.38, (0, 0, 0), 12, 0.88)
    cyl(stool, "stool-seat", M.stone, 0.21, 0.04, (0, 0, 0.38), 12)
    potted(a, "basin-fern", (cx - 0.85, cy + 0.2, 0.04), 0.8, "fern")
    return a


# -------------------------------------------------------- sculpture display

def build_sculpture():
    a = area("sculpture-display")
    wall = thing(a, "plank-backdrop", "backdrop", (0, POST, 0))
    for i in range(8):
        box(wall, "backdrop-plank", M.ironbark if i % 2 else M.trim, (3.0, 0.03, 0.27), (0, 0, 0.24 + 0.28 * i))
    box(wall, "backdrop-cap", M.paleoak, (3.1, 0.07, 0.05), (0, 0, 2.39))
    dais = thing(a, "stone-dais", "dais", (0, 3.92, 0))
    box(dais, "dais-slab", M.stonepale, (3.0, 0.95, 0.08), (0, 0, 0.04))

    def plinth(name, x, size, height):
        base = thing(a, name, "plinth", (x, 3.95, 0.08))
        box(base, "plinth-body", M.plinth, (size, size, height), (0, 0, height / 2))
        box(base, "plinth-cap", M.stone, (size + 0.04, size + 0.04, 0.03), (0, 0, height + 0.015))
        box(base, "plinth-plaque", M.brass, (0.14, 0.006, 0.05), (0, -size / 2 - 0.003, height * 0.72))
        return 0.08 + height + 0.03

    top = plinth("plinth-left", -1.02, 0.42, 0.7)
    cairn = thing(a, "balanced-stones", "sculpture", (-1.02, 3.95, top))
    z = 0
    for i, size in enumerate((0.15, 0.115, 0.085, 0.055)):
        rock(cairn, "cairn-stone", M.stonepale if i % 2 == 0 else M.pebble, (size, size * 0.85, size * 0.5), (0.012 * (-1) ** i, 0, z + size * 0.46), i + 4, 50 * i)
        z += size * 0.92

    top = plinth("plinth-centre", 0, 0.52, 0.92)
    rings = thing(a, "bronze-rings", "sculpture", (0, 3.95, top), interaction="sculpture")
    turn = empty(rings, "bronze-rings-turntable", role="turn", angle=90)
    cyl(turn, "rings-base", M.bronze, 0.14, 0.035, (0, 0, 0), 20)
    torus(turn, "rings-outer", M.bronze, 0.27, 0.036, (0, 0, 0.335), (90, 0, 0), 32, 10)
    torus(turn, "rings-arc", M.brass, 0.17, 0.024, (0, 0, 0.335), (90, 0, 90), 16, 8, pi)
    ball(turn, "rings-heart", M.brass, 0.062, (0, 0, 0.335), 2)

    top = plinth("plinth-right", 1.02, 0.42, 0.56)
    frame = thing(a, "brass-frame", "sculpture", (1.02, 3.95, top), 28)
    e = 0.16
    for sa in (-1, 1):
        for sb in (-1, 1):
            rod(frame, "frame-edge", M.brass, 0.009, (sa * e, sb * e, 0), (sa * e, sb * e, 2 * e), 6)
            rod(frame, "frame-edge", M.brass, 0.009, (-e, sa * e, e + sb * e), (e, sa * e, e + sb * e), 6)
            rod(frame, "frame-edge", M.brass, 0.009, (sa * e, -e, e + sb * e), (sa * e, e, e + sb * e), 6)
    ball(frame, "frame-sphere", M.celadon, 0.105, (0, 0, e), 2)

    vase = thing(a, "branch-vase", "vase", (-1.75, 3.9, 0))
    lathe(vase, "floor-vase-body", "floorvase", M.indigo, [(0, 0), (0.1, 0), (0.17, 0.2), (0.14, 0.45), (0.07, 0.58), (0.09, 0.63), (0.075, 0.63), (0.055, 0.58), (0, 0.55)], (0, 0, 0), 16)
    for dx, dy, dz in ((0.25, 0.05, 1.45), (-0.2, 0.08, 1.3), (0.02, -0.1, 1.6)):
        rod(vase, "branch", M.trunk, 0.008, (0, 0, 0.55), (dx, dy, dz), 5, 0.4)
        for t in (0.55, 0.75, 0.95):
            ball(vase, "branch-blossom", M.blossom, 0.03, (dx * t, dy * t, 0.55 + (dz - 0.55) * t), 1)
    return a


# ---------------------------------------------------------------- landscape

def tree(parent, name, loc, height, spread, material, cypress=False):
    t = thing(parent, name, "tree", loc)
    if cypress:
        cyl(t, "tree-trunk", M.trunk, 0.14, 0.9, (0, 0, 0), 8)
        cyl(t, "cypress-crown", material, spread, height, (0, 0, 0.7), 10, 0.04)
        return t
    cyl(t, "tree-trunk", M.trunk, 0.2 * spread / 2, height * 0.62, (0, 0, 0), 8, 0.5)
    for i in range(4):
        angle = 2 * pi * i / 4 + rng.uniform(-0.4, 0.4)
        reach = spread * rng.uniform(0.3, 0.5)
        tip = (reach * cos(angle), reach * sin(angle), height * rng.uniform(0.62, 0.82))
        rod(t, "tree-branch", M.trunk, 0.06, (0, 0, height * 0.42), tip, 6, 0.4)
        ball(t, "tree-foliage", material, (spread * rng.uniform(0.38, 0.5),) * 2 + (spread * rng.uniform(0.28, 0.36),), tip, 2)
    ball(t, "tree-foliage", material, (spread * 0.5, spread * 0.5, spread * 0.38), (0, 0, height * 0.9), 2)
    return t


def build_landscape():
    a = area("landscape")
    ground = thing(a, "lawn", "ground", (0, 0, GROUND))
    add(ground, "lawn-disc", disc_mesh(M.grass, 48), scale=(30, 30, 1))
    box(ground, "gravel-apron", M.gravel, (2 * D + 1.3, 2 * D + 1.3, 0.02), (0, 0, 0.01))
    box(ground, "gravel-path", M.gravel, (1.5, 6.6, 0.02), (0, -8.5, 0.01))

    for i in range(8):
        stone = thing(a, "stepping-stone", "stepping stone", (0.16 * (-1) ** i, -5.95 - 0.78 * i, GROUND + 0.02), rng.uniform(0, 180))
        rock(stone, "stepping-stone-slab", M.stone if i % 2 else M.stonepale, (0.36, 0.28, 0.05), (0, 0, 0.01), i % 4)

    arbor = thing(a, "garden-arbor", "arbor", (0, -10.2, GROUND))
    for s in (-1, 1):
        box(arbor, "arbor-post", M.ironbark, (0.16, 0.16, 2.5), (s * 1.15, 0, 1.25))
        box(arbor, "arbor-brace", M.trim, (0.5, 0.08, 0.08), (s * 0.95, 0, 2.2), (0, s * 45, 0))
    box(arbor, "arbor-lintel", M.ironbark, (3.1, 0.18, 0.16), (0, 0, 2.58))
    for i in range(7):
        box(arbor, "arbor-rafter", M.slat, (0.06, 0.9, 0.08), (-1.2 + 0.4 * i, 0, 2.7))

    for side in (-1, 1):
        for i in range(5):
            hedge = thing(a, "clipped-hedge", "hedge", (side * 6.6, -5.2 + 2.6 * i, GROUND))
            pillow(hedge, "hedge-mass", M.hedge, (0.6, 1.25, 0.55), (0, 0, 0.55))

    trees = [((-6.2, 8.2), 6.2, 3.4, M.foliage, False), ((-2.2, 10.4), 7.4, 3.8, M.foliage2, False),
             ((3.2, 9.6), 6.6, 3.5, M.foliage3, False), ((7.4, 3.3), 3.6, 2.5, M.maple, False),
             ((-9.6, 1.6), 6.8, 3.6, M.foliage2, False), ((-10.4, -5.0), 5.6, 1.1, M.foliage3, True),
             ((10.2, -4.0), 6.0, 3.2, M.foliage, False), ((9.6, 8.6), 6.4, 1.2, M.foliage3, True),
             ((0.6, 15.5), 8.0, 4.4, M.foliage, False), ((-8.6, 14.0), 7.0, 1.3, M.foliage3, True),
             ((11.5, 13.0), 7.2, 4.0, M.foliage2, False), ((-12.5, 8.0), 6.0, 3.4, M.foliage, False)]
    for i, ((x, y), height, spread, material, cypress) in enumerate(trees):
        tree(a, "maple" if material is M.maple else ("cypress" if cypress else "gum-tree"), (x, y, GROUND), height, spread, material, cypress)

    placed = 0
    while placed < 14:
        radius, angle = rng.uniform(6.2, 12.5), rng.uniform(0, 2 * pi)
        x, y = radius * cos(angle), radius * sin(angle)
        if abs(x) < 1.6 and y < -4 or abs(abs(x) - 6.6) < 1.0:
            continue
        size = rng.uniform(0.45, 0.85)
        bush = thing(a, "garden-shrub", "shrub", (x, y, GROUND))
        ball(bush, "shrub-mass", (M.foliage, M.foliage2, M.foliage3)[placed % 3], (size, size, size * 0.75), (0, 0, size * 0.55), 2)
        ball(bush, "shrub-mass", (M.foliage2, M.foliage3, M.foliage)[placed % 3], (size * 0.6, size * 0.6, size * 0.5), (size * 0.6, size * 0.2, size * 0.4), 2)
        placed += 1

    for i, (x, y, size) in enumerate(((-5.6, -5.4, 0.55), (5.5, -5.7, 0.45), (-2.0, -7.6, 0.3), (2.3, -9.0, 0.4),
                                      (5.6, 5.6, 0.6), (-5.7, 5.5, 0.5), (1.9, -6.2, 0.22))):
        boulder = thing(a, "boulder", "boulder", (x, y, GROUND), 47 * i)
        rock(boulder, "boulder-body", M.stone if i % 2 else M.pebble, (size, size * 0.8, size * 0.62), (0, 0, size * 0.4), i % 4)

    for i, (x, y) in enumerate(((-1.5, -6.4), (1.45, -7.3), (-1.4, -8.6), (1.5, -9.3), (-2.6, -5.5), (2.9, -5.6))):
        drift = thing(a, "lavender-drift", "flower drift", (x, y, GROUND))
        for j in range(8):
            dx, dy = rng.uniform(-0.35, 0.35), rng.uniform(-0.35, 0.35)
            rod(drift, "lavender-stem", M.moss, 0.008, (dx, dy, 0), (dx * 1.3, dy * 1.3, 0.36), 4)
            ball(drift, "lavender-spike", M.lavender, (0.04, 0.04, 0.1), (dx * 1.3, dy * 1.3, 0.4), 1)
        clump(drift, (0, 0, 0), 8, 0.3, 0.06, 40, M.leaf3, "drift-leaf")

    for i, (x, y) in enumerate(((-3.2, -6.3), (3.4, -7.0), (-0.9, -11.0), (4.6, -5.4), (-4.9, -6.6), (6.0, 0.4), (-6.0, 0.2), (0.9, -5.5))):
        tuft = thing(a, "grass-tuft", "grass tuft", (x, y, GROUND))
        clump(tuft, (0, 0, 0), 11, 0.55, 0.05, 22, M.leaf if i % 2 else M.leaf2)

    fence = thing(a, "paddock-fence", "fence", (0, 12.2, GROUND))
    for i in range(15):
        box(fence, "fence-post", M.trunk, (0.12, 0.12, 1.1), (-14 + 2 * i, 0, 0.55))
    for z in (0.45, 0.9):
        box(fence, "fence-rail", M.trunk, (28.2, 0.05, 0.1), (0, 0, z))

    hills = [(-30, 34, 17, 6.5, M.hill), (2, 42, 22, 8.5, M.hillfar), (30, 32, 16, 6, M.hill), (-44, 8, 15, 6, M.hillfar),
             (44, 4, 16, 7, M.hillfar), (-38, -22, 14, 5, M.hill), (38, -24, 15, 5.5, M.hill), (-14, 46, 14, 6, M.hill)]
    for x, y, spread, height, material in hills:
        hill = thing(a, "distant-hill", "hill", (x, y, GROUND - 1))
        ball(hill, "hill-mass", material, (spread, spread * 0.8, height), (0, 0, 0), 2)
    return a


# ------------------------------------------------------------------ outputs

def checksum(path):
    return sha256(path.read_bytes()).hexdigest()


def yup(vector):
    return [round(vector.x, 3), round(vector.z, 3), round(-vector.y, 3)]


def geometry_report():
    bpy.context.view_layer.update()
    triangles = vertices = mesh_objects = 0
    low, high = Vector((1e9,) * 3), Vector((-1e9,) * 3)
    clear = 1e9
    for ob in scene.objects:
        if ob.type != "MESH":
            continue
        mesh_objects += 1
        ob.data.calc_loop_triangles()
        triangles += len(ob.data.loop_triangles)
        vertices += len(ob.data.vertices)
        local = ob.get("area") is None and ob.parent is not None
        for vert in ob.data.vertices:
            world = ob.matrix_world @ vert.co
            if abs(world.x) < 20 and abs(world.y) < 20:
                for i in range(3):
                    low[i], high[i] = min(low[i], world[i]), max(high[i], world[i])
            if 0.02 < world.z < 2.3:
                clear = min(clear, sqrt(world.x ** 2 + world.y ** 2))
    return {
        "meshObjects": mesh_objects,
        "uniqueMeshes": len({ob.data.name for ob in scene.objects if ob.type == "MESH"}),
        "materials": len(MATS),
        "triangles": triangles,
        "meshVertices": vertices,
        "boundsWithin20mYUp": {"min": yup(low), "max": yup(high)},
        "clearCentreRadiusMetres": round(clear, 3),
    }


def inventory():
    bpy.context.view_layer.update()
    families = {}
    for ob in THINGS:
        parts = sum(1 for child in ob.children_recursive if child.type == "MESH")
        families.setdefault(ob["family"], []).append({
            "name": ob.name, "area": ob["area"], "positionYUp": yup(ob.matrix_world.translation),
            "meshParts": parts, **({"interaction": ob["interaction"]} if "interaction" in ob else {}),
        })
    return {
        "seed": SEED,
        "units": "metres, Y up, origin at the viewer's feet",
        "familyCount": len(families),
        "placedObjectCount": len(THINGS),
        "note": "A placed object is one named, positioned item. Pebbles, leaves and book spines are mesh parts of a placed object and are not counted separately.",
        "families": [{"family": name, "count": len(items), "objects": items} for name, items in sorted(families.items())],
    }


def export_glb(path):
    bpy.ops.export_scene.gltf(
        filepath=str(path), export_format="GLB", export_extras=True, export_texcoords=False,
        export_normals=True, export_yup=True, export_apply=False, export_animations=False,
        export_lights=False, export_cameras=False, export_skins=False, export_morph=False,
    )


def export_usdz(path):
    with TemporaryDirectory() as temporary:
        temporary = Path(temporary)
        layer = temporary / "ironbark-pavilion.usdc"
        loose = temporary / "ironbark-pavilion.usdz"
        bpy.ops.wm.usd_export(
            filepath=str(layer), selected_objects_only=False, export_materials=True, export_animation=False,
            export_cameras=False, export_lights=False, export_uvmaps=False, export_custom_properties=False,
            triangulate_meshes=True, convert_orientation=True, export_global_up_selection="Y",
            export_global_forward_selection="NEGATIVE_Z", convert_scene_units="METERS", meters_per_unit=1.0,
            convert_world_material=False,
        )
        run(["usdzip", "--checkCompliance", str(loose), layer.name], check=True, cwd=temporary)
        run(["usdcrush", str(loose), "-o", str(path)], check=True)
    result = run(["usdchecker", str(path)], capture_output=True, text=True)
    print(result.stdout.strip(), result.stderr.strip())
    return result.returncode == 0


def render_stills():
    world = bpy.data.worlds.new("dusk-sky")
    scene.world = world
    background = next(node for node in world.node_tree.nodes if node.type == "BACKGROUND")
    background.inputs["Color"].default_value = (*linear("#c9d8e6"), 1)
    background.inputs["Strength"].default_value = 0.9
    sun_data = bpy.data.lights.new("sun", "SUN")
    sun_data.energy = 4.2
    sun_data.color = linear("#ffe2bd")
    sun_data.angle = radians(2)
    sun = bpy.data.objects.new("sun", sun_data)
    collection.objects.link(sun)
    sun.rotation_mode = "QUATERNION"
    sun.rotation_quaternion = Vector(SUN).normalized().to_track_quat("Z", "Y")

    camera_data = bpy.data.cameras.new("camera")
    camera_data.sensor_fit = "VERTICAL"
    camera_data.clip_start, camera_data.clip_end = 0.05, 200
    camera = bpy.data.objects.new("camera", camera_data)
    collection.objects.link(camera)
    scene.camera = camera
    scene.render.engine = "BLENDER_EEVEE"
    scene.render.resolution_percentage = 100
    scene.render.film_transparent = False
    try:
        scene.eevee.taa_render_samples = 48
    except AttributeError:
        pass

    shots = [("preview.png", "whole", 1280, 800, "PNG"), ("render-whole.jpg", "whole", 1920, 1200, "JPEG"),
             ("render-reading.jpg", "reading", 1280, 800, "JPEG"), ("render-tea.jpg", "tea", 1280, 800, "JPEG"),
             ("render-seating.jpg", "seating", 1280, 800, "JPEG"), ("render-water.jpg", "water", 1280, 800, "JPEG"),
             ("render-sculpture.jpg", "sculpture", 1280, 800, "JPEG")]
    for filename, view, width, height, file_format in shots:
        spec = VIEWS[view]
        eye, target = Vector(spec["eye"]), Vector(spec["target"])
        camera.location = eye
        camera.rotation_mode = "QUATERNION"
        camera.rotation_quaternion = (target - eye).to_track_quat("-Z", "Y")
        camera_data.angle_y = radians(spec["fov"])
        scene.render.resolution_x, scene.render.resolution_y = width, height
        scene.render.image_settings.file_format = file_format
        scene.render.image_settings.color_mode = "RGB"
        if file_format == "JPEG":
            scene.render.image_settings.quality = 86
        else:
            scene.render.image_settings.compression = 90
        scene.render.filepath = str(HERE / filename)
        bpy.ops.render.render(write_still=True)
    return [shot[0] for shot in shots]


def main():
    global scene, collection
    missing = [tool for tool in ("usdzip", "usdcrush", "usdchecker") if which(tool) is None]
    if missing:
        raise RuntimeError(f"Missing required USD tools: {', '.join(missing)}")
    bpy.ops.wm.read_factory_settings(use_empty=True)
    scene = bpy.context.scene
    collection = scene.collection
    scene.unit_settings.system = "METRIC"
    scene.unit_settings.scale_length = 1.0

    make_materials()
    build_structure()
    build_lanterns()
    build_reading()
    build_tea()
    build_seating()
    build_water()
    build_sculpture()
    build_landscape()

    glb = HERE / "scene.glb"
    usdz = HERE / "scene.usdz"
    export_glb(glb)
    usd_valid = export_usdz(usdz)

    def blender_to_yup(point):
        return [point[0], point[2], -point[1]]

    data = {
        "seed": SEED,
        "sun": blender_to_yup(SUN),
        "views": {key: {"label": spec["label"], "eye": blender_to_yup(spec["eye"]),
                        "target": blender_to_yup(spec["target"]), "fov": spec["fov"]} for key, spec in VIEWS.items()},
        "glb": base64.b64encode(glb.read_bytes()).decode("ascii"),
    }
    (HERE / "scene-data.js").write_text(
        "// Generated by generate.py. The GLB is inlined so the page needs no fetch.\n"
        f"window.IRONBARK_SCENE = {json.dumps(data, separators=(',', ':'))};\n")

    listing = inventory()
    (HERE / "object-inventory.json").write_text(json.dumps(listing, indent=1) + "\n")
    geometry = geometry_report()
    renders = render_stills()

    files = ["scene.glb", "scene-data.js", "scene.usdz", *renders, "object-inventory.json"]
    report = {
        "generator": "generate.py",
        "seed": SEED,
        "blender": bpy.app.version_string,
        "usdcheckerPassed": usd_valid,
        "geometry": {**geometry, "placedObjects": listing["placedObjectCount"], "objectFamilies": listing["familyCount"]},
        "files": {name: {"bytes": (HERE / name).stat().st_size, "sha256": checksum(HERE / name)} for name in files},
    }
    (HERE / "asset-report.json").write_text(json.dumps(report, indent=1) + "\n")
    print(json.dumps({key: report[key] for key in ("usdcheckerPassed", "geometry")}, indent=1))
    for name, entry in report["files"].items():
        print(f"{entry['bytes']:>9}  {entry['sha256'][:16]}  {name}")
    if not usd_valid:
        raise RuntimeError("usdchecker rejected scene.usdz")


main()
