Photoreal Blender scenes from a one-paragraph brief, built by AI agents: image→3D props on fal, scripted layout, lighting, camera and grade.
Python
Move AnyKit to its own repo (github.com/apekshik/anykit)
Apekshik Panigrahi2b6966468c44
diff --git a/README.md b/README.mdindex 94d0db9..f4bec83 100644--- a/README.md+++ b/README.md@@ -111,6 +111,17 @@ The code both repos use (`camera/`, `builder/blender_gpu.py`, `farm/app.py`, `pilives in AnyShot; the copies here carry a "synced from" header. Edit them there, then run`python scripts/sync_from_anyshot.py` with AnyShot checked out next to this repo.+## Kits: AnyKit++For props rather than whole sets, use [AnyKit](https://github.com/apekshik/anykit): give it one to four style+reference images and a Claude agent builds a cohesive kit of production-ready props in that style, at real-world+scale (per-item GLB + LOD1, a `kit.blend` asset library, a lineup render), in about 25-40 minutes for about $25. It+uses the same generators, agent harness and container as the scene builder, lives in its own repo and runs as its own+fal app; deployed on the same account it shares this repo's `/data/anyscene/` storage and OptiX cache. AnyKit keeps+synced copies of the code it shares with this repo (`builder/gallery.py`, `builder/blender_gpu.py`,+`generate/fal.mjs`, `pipeline/env.sh`, `pipeline/gpu_run.sh`), so edit those here first. The web UI's kit gallery+calls it over the fal API (`NEXT_PUBLIC_ANYKIT_APP`).+## Render farm add-on[`blender_addon/`](blender_addon) is a Blender add-on that renders the open scene on fal GPUs instead of your own:diff --git a/breakdown/anyshot_supercut.py b/breakdown/anyshot_supercut.pyindex 3d01d09..bd0c0f7 100644--- a/breakdown/anyshot_supercut.py+++ b/breakdown/anyshot_supercut.py@@ -171,7 +171,7 @@ def end_card(out, secs=4.5):canvas = Image.new("RGB", (W, H), BG)d = ImageDraw.Draw(canvas)lines = [(font("segoeuib.ttf", 96), INK, "AnyShot", 128),- (font("bahnschrift.ttf", 36), BRASS, "OPEN SOURCE · github.com/apekshik/anyscene", 92),+ (font("bahnschrift.ttf", 36), BRASS, "OPEN SOURCE · github.com/apekshik/anyshot", 92),(font("segoeuisl.ttf", 30), DIM, "AnyScene builds the set. AnyShot shoots it.", 0)]y = (H - sum(g for *_, g in lines) - 30) // 2for fnt, col, txt, g in lines:diff --git a/breakdown/kit_motion.py b/breakdown/kit_motion.pyindex 36d49d7..e3a9114 100644--- a/breakdown/kit_motion.py+++ b/breakdown/kit_motion.py@@ -1,5 +1,6 @@"""Motion renders of an AnyKit kit for the kit supercut: a lineup dolly and per-item turntables, in the same studio as-kit/tools/present.py (neutral grey ground, soft key/fill/rim, AgX, scale bar, ground labels).+AnyKit's kit/tools/present.py (github.com/apekshik/anykit): neutral grey ground, soft key/fill/rim, AgX, scale bar,+ground labels. Standalone: it imports nothing from AnyKit.blender -b --factory-startup --python builder/blender_gpu.py --python breakdown/kit_motion.py -- \--pkg <unzipped package>/out --out <dir> [--only dolly|turn] [--secs 9] [--turn-secs 4]diff --git a/builder/gallery.py b/builder/gallery.pyindex ef0a741..3185bef 100644--- a/builder/gallery.py+++ b/builder/gallery.py@@ -1,6 +1,6 @@"""The shared builds gallery: every build anyone ran, read from the app's persistent storage (not the fal queue, which-only the submitter's key can read). Used by builder/app.py (/builds, /build_events) and kit/app.py (/kits,-/kit_events). Stdlib only.+only the submitter's key can read). Used by builder/app.py (/builds, /build_events) and by AnyKit's app.py (/kits,+/kit_events; github.com/apekshik/anykit keeps a synced copy). Stdlib only.A build lives at <root>/<id>/ (b_... scenes, k_... kits). out/events.jsonl is its stage stream (scene_builder.emit),out/.alive is touched every 20 s while an attempt runs, and <root>/_index/<fingerprint>.json (builds since the retrydiff --git a/docs/ANYKIT.md b/docs/ANYKIT.mddeleted file mode 100644index 7ac2abe..0000000--- a/docs/ANYKIT.md+++ /dev/null@@ -1,133 +0,0 @@-# AnyKit--`kit/app.py`, deployed on fal Serverless as `<your-fal-username>/anykit` (private). One request = one Claude agent (Opus 5.5 via OpenRouter, fast mode, effort-`medium` by default) on a GPU worker that builds a **kit**: a set of static 3D props in one style, at real-world-scale, from 1-4 style reference images. Part of the AnyAll family: AnyScene builds scenes, AnyKit builds the props-that go in them.--It is agent-driven, not a fixed pipeline. The agent plans the kit, generates a style-conditioned reference per item-(GPT Image 2.5 edit with the customer's images as input), sends every reference to Tripo H3.1 and Meshy 7.1, compares-them under the same light, picks, normalises, fixes by script what looks wrong, renders a lineup and thumbnails, and-loops with an independent critic until it passes. Code: `kit/` (`app.py`, `kit_builder.py`, `PROMPT.md`, `KIT.md`,-`gen.mjs`, `tools/`). It reuses the scene builder's session, hooks, heartbeat, cap guard and container-(`builder/scene_builder.py`, `builder/app.py`).--```-POST /kit style references (+ prompt, items, dials) -> kit (per-item GLB + LOD1 + thumbnail), kit.blend, lineup-POST /smoke {"reference_image_urls": []} -> container, agent and critic check-```--Both run on the fal queue (`https://queue.fal.run/<your-fal-username>/anykit/kit`). A kit takes roughly 40-110 minutes; the request-is capped at 2 hours (the agent is stopped at 110 minutes and whatever is in `out/` is packaged).--```-export ANYKIT_APP=<your-fal-username>/anykit # or pass --app-uv run --python 3.13 --with fal-client python kit/client.py kit ref.png --prompt "1970s mission-control desk clutter" \- --dial count=9 --dial wear=0.4 --out kit_out-```--## Request--```jsonc-{- "reference_image_urls": ["https://..."], // 1-4 style references (required); more than 4 are ignored- "prompt": "1970s mission-control desk clutter, 8-10 items", // optional- "items": ["rotary desk phone", "ashtray"], // optional: built exactly, in this order- "dials": { "count": 9, "wear": 0.4 }, // optional, see below- "effort": "medium" // agent effort: low | medium | high | xhigh | max-}-```--### Dials--Plain settings the agent builds to. A dial that is set is an instruction, even when the reference says otherwise. A-dial left out gets ONE value read from the references and prompt. There are no variants and no switchable rigs. The-values used come back in the response's `dials`, each with its `source`.--| Dial | Range | Controls |-|---|---|---|-| `count` | integer | how many items (default: the item list's length, else the prompt, else 8) |-| `variety` | 0 - 1 | 0 = variations of one object family (matching mugs, jars); 1 = a broad mix that only shares the style |-| `detail` | `low` \| `medium` \| `high` | per-item budget: low <= 20k tris, 1K textures; medium <= 100k, 2K; high <= 200k, 2K. LOD1 is ~1/4 the tris, half-size textures |-| `wear` | 0 pristine - 1 decayed | dirt, scratches, chips, fading |-| `wetness` | 0 dry - 1 soaked | water on surfaces |-| `warmth` | -1 cold - 1 warm | palette colour temperature and the presentation light |-| `look` | `clean` \| `cinematic` \| `gritty` \| `vintage` | surface finish and the presentation renders' grade |--## Response--```jsonc-{- "kit_id": "k_3f9a1c2b7d",- "name": "Apollo-era flight desk",- "style": "one paragraph: era, palette, materials, wear, fictional maker",- "items": [- {- "id": "rotary_phone",- "label": "Rotary desk phone",- "dims_m": [0.22, 0.24, 0.13], // width x (X), depth y (Y), height z (Z), metres- "tris": 98000, "tris_lod1": 24500,- "generator": "meshy", // meshy | tripo-h31 (the pick)- "why": "sharper dial numerals; Tripo fused the handset to the cradle",- "glb_url": "https://...", // LOD0: metres, bottom-centre origin, front faces -Y, textures <= 2K- "lod1_url": "https://...",- "thumb_url": "https://...", // 1024 px, three-quarter front- "turntable_url": null // mp4, when the agent made one- }- ],- "lineup_url": "https://...", // 2400 x 1000: every item on a neutral ground, labels, scale bar- "kit_blend_url": "https://...", // asset library: every item marked as an asset, LOD1s in a hidden collection- "kit_json_url": "https://...", // out/kit.json (the items above + tags and the fixes made per item)- "package_url": "https://...", // zip: out/ (GLBs, renders, kit.blend, kit.json, dials.json, critique/),- // scenes/kit/ (the agent's scripts, NOTES.md), refs/kit/ (item references)- "critiques": [- { "round": 1, "passed": false, "summary": "...", "fixes": ["..."],- "scores": { "cohesion": 7, "reference_fidelity": 8, "brief": 8, "mesh_quality": 6,- "texture_quality": 7, "assembly": 7, "scale": 8, "labels": 6 } }- ],- "dials": { "wear": { "value": 0.4, "source": "customer", "means": "scuffed bakelite, worn paint on edges" } },- "missing": [], // deliverables not produced (empty when complete)- "agent_cost_usd": 18.2, // Claude agent (OpenRouter)- "generation_cost_usd": 31.5, // fal generation, estimated from the spend log- "minutes": 64.3-}-```--The kit passes when no critic score is below 6 and the average is 7 or more: a production-ready base a studio's-artists then refine, judged at normal viewing distance, with the reference setting the world rather than designs to-copy. The critic lists at most five fixes, only ones that would stop a studio using the kit. `assembly` checks that parts that belong together are connected-and seated (cords plugged in at both ends, handsets on cradles, lamp heads on arms, lids on hinges). The critic gets at-most 8 rounds (`MAX_CRITIC_ROUNDS`, shared with the scene builder); after the 8th the kit is delivered as it stands. The critic sees the style references, the lineup, up to 10-thumbnails and each item's dims. A kit stopped at the time cap or after three critic rounds without improvement is-still returned, with the last critique and `missing` saying what is short.--## Events--Same transport and format as the scene builder, so `web/lib/builder.ts` can consume them unchanged. The worker prints-one line per event, `ANYSCENE_STAGE {json}`, and the fal queue relays them as logs (`with_logs=true` on status or-subscribe). Every event:--```jsonc-{ "t": 312.4, // seconds since the build started- "stage": "references", // see below- "status": "running", // running | done | failed- "message": "one plain sentence",- "preview_url": "https://..." // optional image- /* + stage-specific fields */ }-```--| Stage | Kind | Meaning / extra fields |-|---|---|---|-| `received` | system | first event; message `build k_<id>: kit from N style reference(s)`; `reference_urls`, `prompt`, `items`, `dials`, `effort` |-| `log` | tool | one per agent tool call (`tool`: Bash, Read, Write...); `preview_url` when the agent opened an image |-| `thinking` | note | the agent's own words |-| `heartbeat` | status | every 20 s: `working`, `working_s`, `critique_rounds`, `milestones` (every milestone so far, for late attach) |-| `critique` | critic | `status: running` without `critique` = the critic is looking; with `critique` = a round's result (`round`, `scores`, `passed`, `summary`, `fixes`, `stills`) |-| `error` | system | a harness error being resumed, or the time cap; `status: failed` when the build stopped |-| `done` | system | the agent finished; `missing`, `critiques` |-| `packaged` | system | last event; `package_url`, `lineup_url` |-| anything else | milestone | reported by the agent with its best current image: normally `plan`, `references`, `models`, `picks`, `prep`, `fixes`, `lineup`, `finals`, `done`, in that order, with retakes allowed |--The milestone names are the agent's choice within that list; treat any unknown stage as a milestone (as-`builder.ts` does). The `received` message uses the word `build` so the existing `/build (b_\w+)/`-style id parse can-be widened to `/build ([bk]_\w+)/`.diff --git a/kit/KIT.md b/kit/KIT.mddeleted file mode 100644index 8aa7558..0000000--- a/kit/KIT.md+++ /dev/null@@ -1,48 +0,0 @@-# What makes a kit good--A kit is judged as a set. One beautiful item and one off-style item is a failed kit; eight solid items that all look-like the same world is a good one. These are the things that decide it, and what the scene builds learned about the-generators (see also `CRAFT.md`).--## Cohesion comes from the references, not the 3D models--- Tripo and Meshy copy the reference image. If the references don't match each other, nothing later will fix it.- Generate every item reference with the customer's style image as an input image (`kit/gen.mjs edit`), with one- shared style paragraph (era, palette, materials, wear, fictional maker) pasted into every prompt.-- Check the references together, on one sheet, before any 3D: same camera, same light, same level of wear, same- palette. Regenerate the outliers. This is the cheapest place to fix cohesion.-- The style reference is often a whole scene. Its items are a guide to the world, not a list to copy unless the- customer asked for exactly those things.--## The generators (from ~150 props in the scene builds)--- Meshy 7.1 wins about 70% of the time: small consumer items, sharper printed labels. Its front faces -Y.-- Tripo H3.1 wins big hard-surface heroes where real geometry matters (knobs, bezels, dents). Its front faces +X,- and with `orientation: align_image` its glTF node also carries a +-20-30 deg Z rotation that matches the reference- photo's three-quarter view: drop it before turning the mesh (`normalize.py` and `compare.py` do). Raw it is ~2M- tris: generate with `--face-limit` (150000 heroes, 60000 small items).-- Both bake glass opaque, fake screens into the texture, invent depth for boxy things and put real brands on labels.- Expect all four. Meshy speckles flat panels: look at the clay render, not just the beauty.-- References come back with real brands even when told not to. Check every one.--## Scale--- Every item gets a real height (or dims for boxy things) before prep. Look up typical sizes rather than guessing:- a desk phone is ~0.12 m tall, a coffee mug ~0.095 m, a ring binder ~0.32 m, a desk lamp ~0.45 m.-- Check scale in the lineup: items side by side must make sense relative to each other and to the scale bar.--## Prep--- Orientation: decide from the probe or compare renders which way each model faces; `normalize.py --yaw` fixes- anything that isn't front -Y after the generator's rotation.-- glTF imports use quaternion rotation; images arrive packed, and calling `pack()` on an unmodified packed image drops- its data (magenta render). Only repack images you changed.-- Glass: give the glass part a real transmissive material (mask by UV island or by material) and keep labels opaque.-- Brands: repaint the brand's texels (fill with the label's ground colour plus grain) and flatten the same texels in- the normal map, or regenerate the item with a fictional brand.--## Presentation--- The lineup is the kit's cover. Items sorted for a readable silhouette rhythm, a scale bar, labels legible, nothing- cut off, light that shows the materials. Thumbnails: three-quarter front, filling the frame.-- Look at every render you make. A script that ran proves nothing.diff --git a/kit/PROMPT.md b/kit/PROMPT.mddeleted file mode 100644index fca61bd..0000000--- a/kit/PROMPT.md+++ /dev/null@@ -1,136 +0,0 @@-# AnyKit builder (endpoint mode)--You are running inside the AnyKit endpoint. A customer gave you 1-4 style reference images (and maybe a prompt, an-item list and dials) and is paying for a **kit**: a set of static 3D props that clearly belong together, in the-reference's style, at real-world scale, ready to drop into a game or a Blender scene. Nobody will help you: you are-the art director, the 3D generalist and the QA. Read `KIT.md` first (what a kit is and what goes wrong), then-`SKILL.md` steps 3-6 (references -> Tripo and Meshy -> same-light compare -> prep): that is your process. The rest of-`SKILL.md` (rooms, lighting a set, shots) is not part of this job.--This is not a fixed pipeline. The tools in `kit/tools/` and `pipeline/` are starting points. Look at every result-yourself (Read the PNG); when something is wrong, write the script that fixes it in `scenes/kit/scripts/`, run it,-and look again.--## Inputs (`input/`)--- `reference_*.png`: the style reference(s). `style_urls.json`: the same images as fal URLs (use these as image inputs- for `kit/gen.mjs edit`).-- `brief.md`: the customer's prompt (may be empty: then the kit is the props that fill the reference's world).-- `items.json`: the item list, if the customer gave one (build exactly these, in this order). Empty: choose the items.-- `dials.json`: the dials the customer set (below).--## The job--Target: **25-35 minutes for a 10-item kit.** A kit has no room, dressing, lighting or grade; the time goes to waiting-on generators and to Blender launches, so stream the work and batch the Blender sessions (see Speed).--1. **Plan the kit** (`out/plan.json`, report stage `plan`, within ~2 minutes): the kit's name, one paragraph on its- shared style (era, palette, materials, wear, level of detail, the fictional brand every label uses), and every- item: `id` (snake_case), `label`, real-world `h` in metres and `dims` for boxy things, hero or small, and the- prompt you will use. Choose items that cover a range of sizes and silhouettes and read as one set.-2. **References, right once** (stage `references`): one image per item, all launched at once, each generated with the- style reference(s) as input images (`node kit/gen.mjs edit --image <style url> ... --prompt "<item>. In the exact- style, era, palette and materials of the reference image. <scan template from SKILL.md step 4>"`). Put them on- ONE sheet and check it before any 3D: wrong object, a real brand, a different style, more than one object,- cropped, garbled hero text. Regenerate only those real failures, then start 3D. A second 3D round costs far more- than a second look at the sheet.-3. **3D, both generators** (stage `models`): every reference to Tripo H3.1 AND Meshy 7.1 at once, in the background- (`node generate/fal.mjs 3d --model tripo-h31|meshy --ref refs/kit/<id>.json --out assets/gen/<model>/<id>`).- Tripo: always pass `--face-limit 150000` for hero items and `--face-limit 60000` for small ones (raw Tripo is ~2M- tris and makes every later step 10x slower). Retry the ones that fail.-4. **Stream: compare, pick, prep each item as its meshes land.** Don't wait for all 20. Poll with short checks- (`ls assets/gen/*/*/model.glb`, every 20-30 s, a few seconds per check), never `sleep 200`. Each time new GLBs- are in:- - `kit/tools/compare.py -- --ids <ready ids>`: ONE Blender session renders reference | Tripo beauty | Tripo clay |- Meshy beauty | Meshy clay for every ready item (quick Cycles + Workbench clay) into `scenes/kit/compare/<id>.png`- in seconds. Pick by looking (shape in the clay, texture sharpness, labels, glass) and write the pick and a- one-line why into `scenes/kit/prep.json` (stage `picks`). Regenerate an item only if it is bad in both.- - `kit/tools/normalize.py -- --jobs scenes/kit/prep.json`: ONE Blender session preps every picked item that isn't- prepped yet -> `out/items/<id>/<id>.glb` + `<id>_lod1.glb` + `stats.json`, AND rewrites `out/kit.json` from- them in the same pass (stage `prep`). Real metres, bottom-centre origin, front facing -Y (Tripo is unposed and- turned for you), textures <= 2K, tris within the `detail` budget (`max_tris` per item).- - `kit/tools/present.py -- --only thumbs --ids <new ids>`: the new items' thumbnails.- Never launch Blender once per item: a launch plus a GLB import costs more than the render.-5. **Fixes** (stage `fixes`): what the generators got wrong (opaque glass, fake screens, brands, speckled flats),- fixed with scripts in `scenes/kit/scripts/` that work on all affected items in one session, then re-export.- **Assembly:** parts that belong together must be physically connected and seated: cords and cables plugged in at- both ends, handsets on their cradles, lamp heads on their arms, lids on their hinges, nothing hovering or- intersecting. Generators often leave a coiled cord ending in mid-air or a handset floating above its cradle.- Look at every item from a close angle that shows its joints (not only the three-quarter thumbnail), and fix by- script: snap or bridge cord ends to their sockets, re-seat parts, remove stray floating bits.-6. **Critic early** (below): as soon as a first pass of every item is prepped with thumbnails, render a quick lineup- (`present.py --only lineup --samples 32`) and call `critique` with it and the thumbnails. Start fixing what it- says while the final lineup renders.-7. **Present** (stage `lineup`): `kit/tools/present.py` -> `out/renders/lineup.png` (all items side by side on a- neutral ground with a scale bar) and `out/renders/thumbs/<id>.png`. Look at them as the customer will.-8. **Library**: `kit/tools/library.py` -> `out/kit.blend` (every item an asset, LOD1s alongside, packed).-9. Critique again after fixes, until it passes. Then report `finals` and `done`.--Run Blender as `blender -b --factory-startup --python <script> -- <args>`; it renders on the GPU automatically. One-Cycles job at a time (`pipeline/gpu_run.sh blender ...`). Keep test renders small; never let a Bash call run longer-than ~9 minutes, background long jobs and check on them.--## Deliverables (`out/`)--- `items/<id>/<id>.glb`, `items/<id>/<id>_lod1.glb`, `items/<id>/stats.json` for every item.-- `kit.json`: `{"name", "style", "prompt", "items": [{"id", "label", "dims_m": [w, d, h], "tris", "tris_lod1",- "generator": "meshy"|"tripo-h31", "why", "tags": [...], "fixes": [...]}]}`. dims and tris come from the item's- `stats.json`; `why` is the one line on the pick; `fixes` lists what you changed by script (may be empty).-- `renders/lineup.png`, `renders/thumbs/<id>.png` (and `renders/turntables/<id>.mp4` if you make them).-- `kit.blend` (+ `blender_assets.cats.txt`).-- `dials.json`: every dial as built (below).-- `plan.json`, and `scenes/kit/NOTES.md`: what you hit, one line each.--## Dials--The dials are settings you build to, not features to build. `input/dials.json` holds the ones the customer set:-- `count` (integer): how many items. Default: the length of the item list, else what the prompt says, else 8.-- `variety` (0-1): how different the items may be from each other. 0 = variations of one object family (a set of- matching mugs, jars, boxes); 1 = a broad mix of object types that only share the style.-- `detail` (`low` | `medium` | `high`): poly and texture budget per item. low: <= 20k tris, 1K textures; medium:- <= 100k tris, 2K textures; high: <= 200k tris, 2K textures. LOD1 is about a quarter of LOD0.-- `wear` (0 pristine - 1 decayed), `wetness` (0 dry - 1 soaked): condition, written into every reference prompt and- fixed by script where the generators miss it.-- `warmth` (-1 cold - 1 warm): the palette's colour temperature, and the presentation light (`present.py --warmth`).-- `look` (`clean` | `cinematic` | `gritty` | `vintage`): the presentation renders' grade and the surface finish.--A dial the customer set is an instruction: build exactly that, even when the reference says otherwise. A dial left out:-pick the ONE value the reference shows, and build that. Build one version of the kit, no variants. Write-`out/dials.json`: for each of the seven dials, `{"value": ..., "source": "customer" | "reference", "means": "<one-short line on what it meant for this kit>"}`.--## Speed--The customer is waiting and the platform stops the request at 2 hours; aim for 25-35 minutes. The fal account has-no rate limit and no budget cap: launch every reference at once, then every Tripo AND Meshy job at once-(`xargs -P 48`). Meshy takes up to ~10 min, Tripo ~3-5; ~10-20% fail transiently, so retry those at once.-- Stream: compare, pick, prep and thumbnail each item as its meshes land; the first Tripo meshes arrive minutes- before the last Meshy ones.-- Batch Blender: one session per pass over many items (`compare.py`, `normalize.py --jobs`, `present.py`), not one- launch per item. kit.json comes out of the prep session; don't spend a separate pass on it.-- Wait with short polls, never long sleeps.-- Decimation is cheap only on small meshes: keep Tripo at its `--face-limit`.--## Quality gate: the critic--`critique(images)` sends the style reference, your lineup (first) and up to 10 thumbnails, plus `out/kit.json`, to an-independent critic. It scores cohesion, reference fidelity, brief, mesh quality, texture quality, assembly, scale and-labels, and lists at most five fixes: only what would stop a studio using the kit as a base. The bar is a-production-ready base that a studio's artists then refine, judged at normal viewing distance; the reference sets the-world, not designs to copy. It passes with no category below 6 and an average of 7 or more.-Call it on your first complete kit, fix the top problems, re-render, call it again. You are-done when it passes, or after its 8th round (it then refuses more reviews: finish and-deliver). Don't argue with it; fix things (regenerate an item, rescale it, repaint a label, replace it).--## Reporting--The customer watches a live log. Every image you open with Read is shown to them automatically. Call-`report(stage, message, image)` at every milestone with your best current image: `plan`, `references`, `models`,-`picks`, `prep`, `fixes`, `lineup`, `critique`, `finals`, `done`. One plain sentence each, e.g. "Picked Meshy for 7-of 9 items; Tripo for the reel-to-reel, whose knobs are real geometry."--## Rules--- Never print or log keys. They are in the environment (`FAL_KEY`).-- No real brands anywhere: invent one fictional maker for the kit and use it on every label.-- Work only inside this workspace.diff --git a/kit/app.py b/kit/app.pydeleted file mode 100644index 1576fe1..0000000--- a/kit/app.py+++ /dev/null@@ -1,359 +0,0 @@-"""AnyKit as a fal Serverless app: one request = one Claude agent building a cohesive prop kit on a GPU worker.-- fal deploy kit/app.py::AnyKitApp --app-name anykit --auth private- python kit/client.py kit <style reference path or url> [...] --prompt "..." [--items "a,b"] [--dial count=9]--POST /kit style reference images (+ prompt, item list, dials) -> per-item GLB + LOD1 + thumbnail, kit.blend,- lineup render, kit.json, package zip, critic rounds, dials as built.-The agent (kit_builder.py) streams ANYSCENE_STAGE lines the fal queue relays as logs (docs/ANYKIT.md).-Same container, GPU wrapper and OptiX cache as the scene builder (builder/app.py).-"""--import json-import os-import sys-from pathlib import PurePosixPath--import fal-from fal.container import ContainerImage-from pydantic import BaseModel, Field--_HERE = os.path.dirname(os.path.abspath(__file__))-_REPO = os.path.dirname(_HERE)-sys.path.insert(0, _HERE)-sys.path.insert(0, os.path.join(_REPO, "builder"))-sys.path.insert(0, os.path.join(_REPO, "endpoint"))-import planner # noqa: E402,F401 (the critic's Claude client; module level so fal bundles it)-import schema # noqa: E402,F401-import scene_builder # noqa: E402,F401-import kit_builder # noqa: E402-import gallery # noqa: E402 (shared with the scene builder: /kits, /kit_events)--if os.name == "nt":- # Deploying from Windows: ContainerImage's context_dir default is a WindowsPath Linux can't unpickle.- _posix = PurePosixPath("/tmp")- ContainerImage.__dataclass_fields__["context_dir"].default = _posix- ContainerImage.context_dir = _posix- ContainerImage.__init__.__defaults__ = tuple(- _posix if isinstance(d, os.PathLike) else d for d in ContainerImage.__init__.__defaults__ or ()- )--TOOLKIT = kit_builder.toolkit_files()-BLENDER_GPU = open(os.path.join(_REPO, "builder", "blender_gpu.py"), encoding="utf-8").read()-OPTIX_CACHE_LOCAL = "/var/tmp/OptixCache_root/optix7cache.db"-OPTIX_CACHE_SHARED = "/data/anyscene/cache/optix7cache.db" # shared with the scene builder-WARMUP = """import bpy-s = bpy.context.scene-s.render.engine = "CYCLES"; s.cycles.samples = 4; s.render.resolution_x = s.render.resolution_y = 64-m = bpy.data.materials.new("glass"); m.use_nodes = True; m.node_tree.nodes.new("ShaderNodeBsdfGlass")-bpy.ops.mesh.primitive_uv_sphere_add(location=(0, 0, 0.5))-bpy.context.object.data.materials.append(m)-bpy.ops.render.render()-print("WARMUP done")-"""---def save_optix_cache():- import shutil- if os.path.exists(OPTIX_CACHE_LOCAL) and (not os.path.exists(OPTIX_CACHE_SHARED)- or os.path.getsize(OPTIX_CACHE_LOCAL) > os.path.getsize(OPTIX_CACHE_SHARED)):- os.makedirs(os.path.dirname(OPTIX_CACHE_SHARED), exist_ok=True)- tmp = f"{OPTIX_CACHE_SHARED}.{os.getpid()}.tmp"- shutil.copy(OPTIX_CACHE_LOCAL, tmp)- os.replace(tmp, OPTIX_CACHE_SHARED)---BLENDER_WRAPPER = '#!/bin/sh\nexec /usr/local/bin/blender.real --python /opt/anyscene/blender_gpu.py "$@"\n'-KITS_DIR = "/data/anyscene/kit"-BLENDER_VERSION = "5.0.1"--# identical to the scene builder's, so the image layers are shared-DOCKERFILE = f"""-FROM python:3.13-slim-ENV NVIDIA_DRIVER_CAPABILITIES=all-RUN apt-get update && apt-get install -y --no-install-recommends \\- curl ca-certificates xz-utils git procps fonts-dejavu-core libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 \\- libegl1 libxkbcommon0 libsm6 libice6 libx11-6 libglib2.0-0 ffmpeg nodejs ripgrep zip \\- && rm -rf /var/lib/apt/lists/*-RUN curl -fsSL https://download.blender.org/release/Blender{BLENDER_VERSION[:3]}/blender-{BLENDER_VERSION}-linux-x64.tar.xz \\- | tar -xJ -C /opt \\- && ln -s /opt/blender-{BLENDER_VERSION}-linux-x64/blender /usr/local/bin/blender.real-"""---class KitRequest(BaseModel):- reference_image_urls: list[str] = Field(description="1-4 style reference images: the world the kit belongs to.")- prompt: str = Field("", description="What the kit is, e.g. '1970s mission-control desk clutter'.")- items: list[str] = Field(default_factory=list, description="Optional item list; built exactly, in order.")- effort: str = Field("medium", description="Claude effort for the builder: low, medium, high, xhigh, max.")- dials: dict[str, float | int | str] = Field(default_factory=dict, description=(- "Kit dials (docs/ANYKIT.md); any left out are read from the reference. count: integer. variety, wear, "- "wetness: 0-1. warmth: -1 (cold) to 1 (warm). detail: low|medium|high. look: clean|cinematic|gritty|vintage."))- fresh: bool = Field(False, description="Build again even if an identical request already finished.")---class KitItem(BaseModel):- id: str- label: str = ""- dims_m: list[float] = Field(default_factory=list, description="[width x, depth y, height z] in metres.")- tris: int | None = None- tris_lod1: int | None = None- generator: str | None = None- why: str | None = None- glb_url: str | None = None- lod1_url: str | None = None- thumb_url: str | None = None- turntable_url: str | None = None---class KitResponse(BaseModel):- kit_id: str- name: str | None- style: str | None- items: list[KitItem]- lineup_url: str | None- kit_blend_url: str | None- kit_json_url: str | None- package_url: str | None- critiques: list[dict]- dials: dict = Field(default_factory=dict, description="Every dial as built: value, source, means (out/dials.json).")- missing: list[str]- agent_cost_usd: float | None- generation_cost_usd: float | None- minutes: float---class GalleryRequest(BaseModel):- limit: int = Field(200, description="Most kits to list, newest first.")---class KitEventsRequest(BaseModel):- kit_id: str = Field(description="A kit id (k_...) from /kits.")- after: int = Field(0, description="Byte offset into the kit's event stream: 0, then the previous call's `next`.")- heartbeats: bool = Field(False, description="Include every heartbeat (default: only the newest in each page).")---class AnyKitApp(fal.App):- machine_type = ["GPU-RTX5090", "GPU-RTXPRO6000"]- image = ContainerImage.from_dockerfile_str(DOCKERFILE)- requirements = ["pydantic", "anthropic", "pillow", "fal==1.84.0", "fal-client", "claude-agent-sdk==0.2.176"]- local_python_modules = ["kit_builder", "scene_builder", "planner", "schema", "gallery"]- min_concurrency = 0- max_concurrency = 10- request_timeout = 7200- startup_timeout = 1200-- def setup(self):- import shutil- import subprocess- import time- os.makedirs("/opt/anyscene", exist_ok=True)- with open("/opt/anyscene/blender_gpu.py", "w") as f:- f.write(BLENDER_GPU)- with open("/usr/local/bin/blender", "w") as f:- f.write(BLENDER_WRAPPER)- os.chmod("/usr/local/bin/blender", 0o755)- if os.path.exists(OPTIX_CACHE_SHARED):- os.makedirs(os.path.dirname(OPTIX_CACHE_LOCAL), exist_ok=True)- shutil.copy(OPTIX_CACHE_SHARED, OPTIX_CACHE_LOCAL)- t = time.time()- r = subprocess.run(["blender", "-b", "--factory-startup", "--python-expr", WARMUP], capture_output=True, text=True,- timeout=900)- print(f"setup: OptiX warm-up {'ok' if 'WARMUP done' in r.stdout else 'FAILED'} in {time.time() - t:.0f} s", flush=True)- save_optix_cache()-- # fal naming: target fal-ai/anykit/ref2kit; /kit stays as an alias.- @fal.endpoint("/ref2kit")- async def ref2kit(self, req: KitRequest) -> KitResponse:- """Style reference images (+ prompt, items, dials) -> a cohesive kit of production-ready props."""- return await self._kit(req)-- @fal.endpoint("/kit")- async def kit(self, req: KitRequest) -> KitResponse:- return await self._kit(req)-- async def _kit(self, req: KitRequest) -> KitResponse:- import asyncio- import hashlib- import time- import uuid-- t0 = time.time()- # Retry-safe, as in builder/app.py: fal's queue re-runs a request that times out or loses its worker, so an- # identical request returns the finished kit, waits on a live attempt, or resumes a dead one in place.- fp = hashlib.sha256(json.dumps({"refs": req.reference_image_urls, "prompt": req.prompt, "items": req.items,- "dials": req.dials, "effort": req.effort}, sort_keys=True).encode()).hexdigest()[:20]- index = os.path.join(KITS_DIR, "_index", fp + ".json")- os.makedirs(os.path.dirname(index), exist_ok=True)- resume = False- if not req.fresh and os.path.exists(index):- told = False- while True:- rec = json.load(open(index))- if rec.get("response"):- print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": "done", "status": "done", "message":- f"identical request: returning finished kit {rec['kit_id']}"}), flush=True)- return KitResponse(**rec["response"])- alive = os.path.join(KITS_DIR, rec["kit_id"], "out", ".alive")- if not os.path.exists(alive) or time.time() - os.path.getmtime(alive) > 90:- break # its attempt died: resume it below- if not told:- print(scene_builder.PREFIX + json.dumps({"t": 0, "stage": "received", "status": "running", "message":- f"identical request: attached to kit {rec['kit_id']}, still running"}), flush=True)- told = True- await asyncio.sleep(20)- kit_id, resume = rec["kit_id"], True- else:- kit_id = "k_" + uuid.uuid4().hex[:10]- json.dump({"kit_id": kit_id, "fingerprint": fp, "started": time.time()}, open(index, "w"))- work = os.path.join(KITS_DIR, kit_id)- os.makedirs(os.path.join(work, "out"), exist_ok=True)-- async def keep_alive(): # proves this attempt is alive to any retry of the same request- while True:- open(os.path.join(work, "out", ".alive"), "w").close()- await asyncio.sleep(20)- alive_task = asyncio.create_task(keep_alive())- try:- return await self._kit_in(req, kit_id, work, index, resume, t0)- finally:- alive_task.cancel()-- async def _kit_in(self, req, kit_id, work, index, resume, t0) -> KitResponse:- import asyncio- import time- import urllib.request- import zipfile-- from fal.toolkit import File- from PIL import Image-- os.makedirs(os.path.join(work, "input"), exist_ok=True)- upload = lambda p: File.from_path(p).url- if resume: # the workspace is there: refresh the shared tools, keep the kit's own scripts and assets- for rel, text in TOOLKIT.items():- path = os.path.join(work, rel)- os.makedirs(os.path.dirname(path), exist_ok=True)- with open(path, "w", encoding="utf-8", newline="\n") as f:- f.write(text)- else:- pngs = []- for i, url in enumerate(req.reference_image_urls[:4]):- src = os.path.join(work, "input", f"src_{i + 1}")- urllib.request.urlretrieve(url, src)- out = os.path.join(work, f"ref_{i + 1}.png")- Image.open(src).convert("RGB").save(out)- pngs.append(out)- kit_builder.make_workspace(work, pngs, req.prompt, TOOLKIT, req.dials, req.items,- req.reference_image_urls[:4])- refs = sorted(os.path.join(work, "input", f) for f in os.listdir(os.path.join(work, "input"))- if f.startswith("reference_") and f.endswith(".png"))-- b = kit_builder.KitBuilder(work, refs, uploader=upload, effort=req.effort)- if resume:- b.ASK = ("This kit build was cut off (its request was retried) and is resuming in the same workspace. Read "- "out/builder.log, out/events.jsonl and scenes/kit/NOTES.md to see how far it got. Everything "- "already generated is on disk, and generate/fal.mjs and kit/gen.mjs skip finished outputs and pick "- "up jobs that were in flight, so re-running your batch scripts costs nothing for done items. Don't "- "start over: continue from the current state to the deliverables.")- b.emit("received", "running", f"{'resuming' if resume else 'build'} {kit_id}: kit from {len(refs)} style reference(s)",- reference_urls=req.reference_image_urls, prompt=req.prompt, items=req.items, dials=req.dials,- effort=req.effort)- result = None- try:- result = await b.run(kit_builder.agent_env())- except Exception as e:- import traceback- print(traceback.format_exc(), flush=True)- b.emit("error", "failed", f"kit build stopped: {type(e).__name__}: {str(e)[:300]}")-- out = os.path.join(work, "out")- url_if = lambda p: upload(p) if os.path.exists(p) else None- kit = b.kit() or {}- items = []- for it in kit.get("items", []):- i = it.get("id", "")- d = os.path.join(out, "items", i)- items.append(KitItem(- id=i, label=it.get("label", ""), dims_m=it.get("dims_m") or [], tris=it.get("tris"),- tris_lod1=it.get("tris_lod1"), generator=it.get("generator"), why=it.get("why"),- glb_url=url_if(os.path.join(d, f"{i}.glb")), lod1_url=url_if(os.path.join(d, f"{i}_lod1.glb")),- thumb_url=url_if(os.path.join(out, "renders", "thumbs", f"{i}.png")),- turntable_url=url_if(os.path.join(out, "renders", "turntables", f"{i}.mp4"))))- pkg = os.path.join(work, f"{kit_id}.zip")- with zipfile.ZipFile(pkg, "w", zipfile.ZIP_DEFLATED) as z:- for root, _, names in os.walk(out):- for n in names:- z.write(os.path.join(root, n), os.path.relpath(os.path.join(root, n), work))- for sub in ("scenes/kit", "refs/kit"):- for root, _, names in os.walk(os.path.join(work, sub)):- for n in names:- if n.endswith((".py", ".json", ".md", ".sh", ".png")):- z.write(os.path.join(root, n), os.path.relpath(os.path.join(root, n), work))- dials_path = os.path.join(out, "dials.json")- res = KitResponse(- kit_id=kit_id, name=kit.get("name"), style=kit.get("style"), items=items,- lineup_url=url_if(os.path.join(out, "renders", "lineup.png")),- kit_blend_url=url_if(os.path.join(out, "kit.blend")), kit_json_url=url_if(os.path.join(out, "kit.json")),- package_url=upload(pkg),- critiques=[{k: c[k] for k in ("round", "scores", "passed", "summary", "fixes")} for c in b.critiques],- dials=json.load(open(dials_path)) if os.path.exists(dials_path) else {},- missing=b.missing(), agent_cost_usd=getattr(result, "total_cost_usd", None),- generation_cost_usd=kit_builder.generation_spend(work), minutes=round((time.time() - t0) / 60, 1))- save_optix_cache()- rec = json.load(open(index))- rec.update(response=res.model_dump(), finished=time.time())- json.dump(rec, open(index, "w"))- b.emit("packaged", "done", f"package ready after {res.minutes:.0f} min", package_url=res.package_url,- lineup_url=res.lineup_url)- await asyncio.sleep(2) # let the last stage lines reach the queue logs before COMPLETED- return res-- # The shared gallery (builder/gallery.py): every kit anyone ran, read from storage.- @fal.endpoint("/kits")- async def kits(self, req: GalleryRequest) -> dict:- """Every kit on this app's storage, newest first: status, inputs, critic, lineup and thumbnail URLs."""- import asyncio- return await asyncio.to_thread(gallery.list_builds, KITS_DIR, "kit", max(1, min(req.limit, 1000)))-- @fal.endpoint("/kit_events")- async def kit_events(self, req: KitEventsRequest) -> dict:- """One kit's stage events from byte offset `after`, its summary, and on the first page of a finished kit its- response."""- import asyncio-- from fal.toolkit import File- return await asyncio.to_thread(gallery.build_events, KITS_DIR, req.kit_id, req.after, "kit",- req.heartbeats, 8 << 20, lambda p: File.from_path(p).url)-- @fal.endpoint("/smoke")- async def smoke(self, req: KitRequest) -> dict:- """Container check: tools present, the agent starts and runs Bash/Blender/node, the kit critic answers."""- import subprocess- vers = {c[0]: subprocess.run(c, capture_output=True, text=True).stdout.splitlines()[:1]- for c in (["blender", "--version"], ["node", "--version"], ["ffmpeg", "-version"], ["nvidia-smi", "-L"])}- from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, ResultMessage, TextBlock- work = "/tmp/smoke"- os.makedirs(work, exist_ok=True)- said, cost = [], None- opts = ClaudeAgentOptions(model=kit_builder.MODEL, effort="low", permission_mode="bypassPermissions", cwd=work,- setting_sources=[], settings='{"fastMode": true}', env=kit_builder.agent_env())- async with ClaudeSDKClient(opts) as c:- await c.query("Run `blender -b --python-expr \"import bpy; print('BPY', bpy.app.version_string)\"` and "- "`node -e \"console.log(typeof fetch)\"`, then reply with both outputs in one line.")- async for m in c.receive_response():- if isinstance(m, AssistantMessage):- said += [b.text for b in m.content if isinstance(b, TextBlock)]- elif isinstance(m, ResultMessage):- cost = m.total_cost_usd- from PIL import Image- Image.new("RGB", (256, 128), (40, 60, 50)).save(f"{work}/plate.png")- try:- crit = kit_builder.run_critic([f"{work}/plate.png"], [f"{work}/plate.png"], "smoke test: a grey plate",- "- plate: test plate, 20 x 20 x 2 cm, 2 tris")- critic = {"ok": True, "scores": crit["scores"]}- except Exception as e:- critic = {"ok": False, "error": f"{type(e).__name__}: {e}"[:300]}- toolkit = sorted(k for k in TOOLKIT if k.startswith(("kit/", "KIT", ".builder")))- return {"versions": vers, "agent": said[-1] if said else None, "cost": cost, "critic": critic,- "toolkit": toolkit}diff --git a/kit/client.py b/kit/client.pydeleted file mode 100644index 71b019c..0000000--- a/kit/client.py+++ /dev/null@@ -1,107 +0,0 @@-"""Call AnyKit and print its live log.-- uv run --python 3.13 --with fal-client python kit/client.py kit <style image path or url> [...] \- --prompt "1970s mission-control desk clutter" [--items "a,b,c"] [--dial count=9 --dial wear=0.4] [--out DIR]- uv run --python 3.13 --with fal-client python kit/client.py smoke--Local images are uploaded to fal storage first. Every stage event goes to <out>/events.jsonl (for UI replay); the-response, the lineup and the thumbnails are saved to --out. Uses FAL_SERVERLESS_KEY (the account the app is under).-"""--import argparse-import json-import os-import subprocess-import sys-import time-import urllib.request--# The fal app id, <owner>/<app>: set ANYKIT_APP=<your-fal-username>/anykit, or pass --app. No default.-APP_ENV = "ANYKIT_APP"-PREFIX = "ANYSCENE_STAGE "---def user_env(name):- if os.environ.get(name):- return os.environ[name]- if sys.platform == "win32":- parts = subprocess.run(["reg", "query", r"HKCU\Environment", "/v", name], capture_output=True, text=True).stdout.split()- if name in parts:- return parts[parts.index(name) + 2]- return None---def dial(s):- k, v = s.split("=", 1)- for cast in (int, float):- try:- return k, cast(v)- except ValueError:- pass- return k, v---def main():- p = argparse.ArgumentParser()- p.add_argument("cmd", choices=["kit", "smoke"])- p.add_argument("refs", nargs="*")- p.add_argument("--prompt", default="")- p.add_argument("--items", default="")- p.add_argument("--dial", action="append", default=[])- p.add_argument("--effort", default="medium")- p.add_argument("--out", default="kit_out")- p.add_argument("--app", help="fal app id (default: $ANYKIT_APP)")- a = p.parse_args()- app = (a.app or user_env(APP_ENV) or "").strip().strip("/")- if not app:- p.error(f"set {APP_ENV}=<your-fal-username>/anykit or pass --app")- sys.stdout.reconfigure(encoding="utf-8")- os.environ["FAL_KEY"] = user_env("FAL_SERVERLESS_KEY") or user_env("FAL_KEY")- import fal_client-- os.makedirs(a.out, exist_ok=True)- if a.cmd == "smoke":- res = fal_client.subscribe(f"{app}/smoke", arguments={"reference_image_urls": []}, client_timeout=3600)- json.dump(res, open(os.path.join(a.out, "smoke.json"), "w"), indent=1)- print(json.dumps(res, indent=1))- return- up = lambda s: s if s.startswith("http") else fal_client.upload_file(s)- payload = {"reference_image_urls": [up(s) for s in a.refs], "prompt": a.prompt, "effort": a.effort,- "items": [s.strip() for s in a.items.split(",") if s.strip()], "dials": dict(map(dial, a.dial))}- events = open(os.path.join(a.out, "events.jsonl"), "w", encoding="utf-8")- t0, seen = time.time(), set()-- def on_update(update):- for log in getattr(update, "logs", None) or []:- msg = log.get("message", "")- if msg in seen:- continue- seen.add(msg)- if PREFIX not in msg:- if any(k in msg for k in ("Traceback", "Error", "error:", "Exception")):- print(f"[worker] {msg[:600]}", flush=True)- continue- ev = json.loads(msg.split(PREFIX, 1)[1])- events.write(json.dumps(ev) + "\n")- events.flush()- if ev["stage"] == "heartbeat":- continue- line = f"[{(time.time() - t0) / 60:6.1f}m] {ev['stage']:<10} {ev.get('message', '')[:160]}"- if ev.get("preview_url"):- line += f"\n{'':20}image: {ev['preview_url']}"- print(line, flush=True)-- res = fal_client.subscribe(f"{app}/kit", arguments=payload, with_logs=True, on_queue_update=on_update,- on_enqueue=lambda rid: print(f"request {rid}", flush=True), client_timeout=8 * 3600)- with open(os.path.join(a.out, "kit.json"), "w", encoding="utf-8") as f:- json.dump(res, f, indent=1)- if res.get("lineup_url"):- urllib.request.urlretrieve(res["lineup_url"], os.path.join(a.out, "lineup.png"))- for it in res.get("items", []):- if it.get("thumb_url"):- urllib.request.urlretrieve(it["thumb_url"], os.path.join(a.out, f"thumb_{it['id']}.png"))- print(json.dumps({k: v for k, v in res.items() if k not in ("critiques", "items")}, indent=1)[:3000])---if __name__ == "__main__":- main()diff --git a/kit/gen.mjs b/kit/gen.mjsdeleted file mode 100644index 15eb3b0..0000000--- a/kit/gen.mjs+++ /dev/null@@ -1,102 +0,0 @@-// Style-conditioned item references for AnyKit: GPT Image 2.5 edit with the customer's style reference(s) as input-// images, so every item is drawn in the same world. Writes the same <out>.json as generate/fal.mjs `image`, so-// `node generate/fal.mjs 3d --ref <out>.json ...` takes it straight to Tripo / Meshy. Spend goes to generate/spend.jsonl.-//-// node kit/gen.mjs edit --out refs/kit/<id> --prompt "..." --image input/reference_1.png [--image <url|path> ...]-// [--variant sunburst|flare] [--quality high] [--n 1] [--size auto|square_hd|...] [--force]-//-// Re-running is free: an existing <out>.json is skipped (--force regenerates), and a job submitted by a run that-// was cut off (<out>.pending.json) is polled to the end instead of paid for again.-//-// --image takes URLs or local paths (sent inline as data URIs). input/style_urls.json holds the customer's-// references as fal URLs; prefer those.--import { access, appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';-import { dirname, extname, join, resolve } from 'node:path';-import { parseArgs } from 'node:util';--const KEY = process.env.FAL_KEY || process.env.FAL_API_KEY;-const HERE = dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1'));-const REPO = resolve(HERE, '..');-const SPEND_LOG = join(REPO, 'generate', 'spend.jsonl');-const EST = 0.3;--const { positionals, values: a } = parseArgs({- allowPositionals: true,- options: {- out: { type: 'string' }, prompt: { type: 'string' }, image: { type: 'string', multiple: true },- variant: { type: 'string', default: 'sunburst' }, quality: { type: 'string', default: 'high' },- n: { type: 'string', default: '1' }, size: { type: 'string' }, force: { type: 'boolean', default: false },- },-});--async function call(url, init = {}) {- const res = await fetch(url, { ...init, headers: { authorization: `Key ${KEY}`, 'content-type': 'application/json' } });- const text = await res.text();- if (!res.ok) throw new Error(`${res.status} ${url}: ${text.slice(0, 600)}`);- return text ? JSON.parse(text) : null;-}--async function asUrl(s) {- if (/^(https?|data):/.test(s)) return s;- const buf = await readFile(resolve(REPO, s));- const mime = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' }[extname(s).toLowerCase()] || 'image/png';- return `data:${mime};base64,${buf.toString('base64')}`;-}--async function edit() {- if (!KEY) throw new Error('FAL_KEY is not set');- if (!a.out || !a.prompt || !a.image?.length) throw new Error('--out, --prompt and at least one --image are required');- const out = resolve(REPO, a.out);- const exists = (f) => access(f).then(() => true, () => false);- if (!a.force && await exists(`${out}.json`)) {- console.log(`exists ${a.out}.json (skipped; --force to regenerate)`);- return;- }- const endpoint = `openai/gpt-image-2.5/${a.variant}/edit`;- const input = { prompt: a.prompt, image_urls: await Promise.all(a.image.map(asUrl)), quality: a.quality,- num_images: +a.n, output_format: 'png', ...(a.size ? { image_size: a.size } : {}) };- const t0 = performance.now();- const pending = `${out}.pending.json`;- let job;- if (!a.force && await exists(pending)) {- job = JSON.parse(await readFile(pending, 'utf8'));- console.log(`resuming ${endpoint} ${job.request_id}`);- } else {- job = await call(`https://queue.fal.run/${endpoint}`, { method: 'POST', body: JSON.stringify(input) });- await mkdir(dirname(out), { recursive: true });- await writeFile(pending, JSON.stringify(job));- await mkdir(dirname(SPEND_LOG), { recursive: true });- await appendFile(SPEND_LOG, JSON.stringify({ time: new Date().toISOString(), endpoint, est_usd: EST * +a.n,- request_id: job.request_id, kind: 'image', out: a.out }) + '\n');- console.log(`queued ${endpoint} ${job.request_id}`);- }- for (;;) {- await new Promise((r) => setTimeout(r, 3000));- const st = await call(job.status_url);- if (st.status === 'COMPLETED') break;- if (performance.now() - t0 > 15 * 60_000) throw new Error(`timed out; request ${job.request_id}`);- }- const result = await call(job.response_url);- const files = [];- await mkdir(dirname(out), { recursive: true });- for (const [i, img] of (result.images ?? []).entries()) {- const f = `${out}_${i}.png`;- const r = await fetch(img.url);- await writeFile(f, Buffer.from(await r.arrayBuffer()));- files.push({ file: f, url: img.url, width: img.width, height: img.height });- }- if (!files.length) throw new Error('no images in response: ' + JSON.stringify(result).slice(0, 400));- const seconds = (performance.now() - t0) / 1000;- // inputs can be multi-MB data URIs: keep only their kind in the record- const record = { ...input, image_urls: input.image_urls.map((u) => (u.startsWith('data:') ? 'data:(inline)' : u)) };- await writeFile(`${out}.json`, JSON.stringify({ endpoint, request_id: job.request_id, seconds, input: record, files }, null, 2));- await rm(pending, { force: true });- console.log(`saved ${files.map((f) => f.file).join(', ')} (${seconds.toFixed(0)} s)`);-}--if (positionals[0] !== 'edit') {- console.error('usage: node kit/gen.mjs edit --out ... --prompt ... --image ... (see header)');- process.exit(1);-}-await edit();diff --git a/kit/kit_builder.py b/kit/kit_builder.pydeleted file mode 100644index 408b827..0000000--- a/kit/kit_builder.py+++ /dev/null@@ -1,336 +0,0 @@-"""AnyKit: one Claude agent builds a cohesive kit of static 3D props from style reference image(s).--Same machinery as the scene builder (builder/scene_builder.py): an Agent SDK session (Opus 5.5, fast mode, OpenRouter),-report/critique MCP tools, PreToolUse/PostToolUse/Stop hooks, a heartbeat, the 2-hour cap guard and resume on session-errors. What differs: the workspace (kit prompt, KIT.md, kit tools), the critic's rubric (kit cohesion, not a set), and-what "done" means (out/kit.json, per-item GLB + LOD1 + thumbnail, out/kit.blend, out/renders/lineup.png, a passing-critique).-- uv run --python 3.13 --with claude-agent-sdk --with anthropic --with pydantic --with pillow \- python kit/kit_builder.py <reference.png> [...] --work <dir> [--prompt "..."] [--items "a,b,c"]-"""--import argparse-import asyncio-import json-import os-import sys--from claude_agent_sdk import (AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, HookMatcher, ResultMessage,- TextBlock, create_sdk_mcp_server, tool)--HERE = os.path.dirname(os.path.abspath(__file__))-REPO = os.path.dirname(HERE)-sys.path.insert(0, os.path.join(REPO, "builder"))-sys.path.insert(0, os.path.join(REPO, "endpoint"))-import planner # noqa: E402 (the critic's Claude client; module level so fal bundles it)-import scene_builder # noqa: E402-from scene_builder import CAP_STOP_S, CAP_WARN_S, MAX_CRITIC_ROUNDS, MODEL, PREFIX, agent_env, user_env # noqa: E402,F401--DIALS = ("count", "variety", "detail", "wear", "wetness", "warmth", "look")---# ---------------------------------------------------------------- workspace-def toolkit_files():- """The scene builder's toolkit (SKILL.md, generate/, pipeline/, camera/, docs/) with the kit's prompt, KIT.md and- kit tools on top. Read at deploy time so the fal app carries it."""- files = {k: v for k, v in scene_builder.toolkit_files().items() if not k.startswith(".builder/")}- files[".builder/PROMPT.md"] = open(os.path.join(HERE, "PROMPT.md"), encoding="utf-8").read()- files["KIT.md"] = open(os.path.join(HERE, "KIT.md"), encoding="utf-8").read()- files["kit/gen.mjs"] = open(os.path.join(HERE, "gen.mjs"), encoding="utf-8").read()- for n in sorted(os.listdir(os.path.join(HERE, "tools"))):- if n.endswith(".py"):- files[f"kit/tools/{n}"] = open(os.path.join(HERE, "tools", n), encoding="utf-8").read()- return files---def make_workspace(work, refs, prompt, files, dials=None, items=None, ref_urls=None):- scene_builder.make_workspace(work, refs, prompt, "kit", files, dials)- inp = os.path.join(work, "input")- with open(os.path.join(inp, "items.json"), "w", encoding="utf-8") as f:- json.dump(items or [], f, indent=1)- with open(os.path.join(inp, "style_urls.json"), "w", encoding="utf-8") as f:- json.dump(ref_urls or [], f, indent=1)- for d in ("out/items", "out/renders/thumbs", "refs/kit"):- os.makedirs(os.path.join(work, d), exist_ok=True)- # the scene builder's stills dir is not part of a kit- try:- os.rmdir(os.path.join(work, "out", "stills"))- except OSError:- pass---# ---------------------------------------------------------------- critic-CRITIC = """You review 3D prop kits for a service that turns style reference images into production-ready asset kits.-The first {n_refs} image(s) are the customer's STYLE REFERENCE. They asked for: {brief}--The remaining images are the delivered kit: first a lineup render (every item side by side on a neutral ground, with-a scale bar; its label under each item), then per-item thumbnails. The kit's manifest:-{manifest}--The reference is a starting point for the world, not a target to copy: the kit must clearly belong to the same world-(era, materials, palette, design language), but which items were chosen, their exact designs and the presentation-are the builder's own choices and must NOT be marked down for differing from the reference.--The bar is a production-ready base: a kit a studio would accept as the starting point its artists then refine. Judge-it as a whole, from normal viewing distance. Do NOT nitpick: no points off for a creative choice that differs from-the reference, a surface that is a little CG on close inspection, or anything an artist would tweak in ten minutes.--Score each category 1-10 (7 = a solid, usable production kit; 9 = exceptional):-- cohesion: the items read as one set: shared palette, material language, era, wear and level of detail;-- reference_fidelity: the kit belongs in the reference's world;-- brief: the items are what the customer asked for (prompt, item list, count), nothing off-topic;-- mesh_quality: clean recognisable shapes; nothing broken, blobby or melted;-- texture_quality: believable textured surfaces; nothing untextured, smeared or flat grey;-- assembly: parts that belong together are physically connected and seated: cords and cables plugged in at- both ends, handsets on their cradles, lamp heads on their arms, lids on their hinges, nothing hovering or- intersecting;-- scale: each item's real-world size (manifest dims, scale bar) is right, alone and relative to the others;-- labels: no real brands; no garbled text on hero labels.--Then list at most FIVE fixes, most damaging first: only problems that would stop a studio from using the kit as a-base (an item broken, melted or with disconnected parts, garbled hero labels, wrong world, untextured, badly wrong-scale). If the kit is already a good base, say so and list fewer or none. Pass when the kit is a good production-base: no category below 6 and an average of 7 or more."""---def critic_schema():- from pydantic import BaseModel, Field-- class Scores(BaseModel):- cohesion: int- reference_fidelity: int- brief: int- mesh_quality: int- texture_quality: int- assembly: int- scale: int- labels: int-- class Critique(BaseModel):- scores: Scores- fixes: list[str] = Field(description="At most five, most damaging first; may be empty.")- summary: str- return Critique---def manifest_text(work):- try:- kit = json.load(open(os.path.join(work, "out", "kit.json"), encoding="utf-8"))- except Exception:- return "(out/kit.json not written yet)"- rows = []- for it in kit.get("items", []):- d = it.get("dims_m") or []- dims = " x ".join(f"{v * 100:.0f}" for v in d) + " cm (w x d x h)" if len(d) == 3 else "?"- rows.append(f"- {it.get('id')}: {it.get('label', '')}, {dims}, {it.get('tris', '?')} tris")- return "\n".join(rows) or "(no items)"---def run_critic(refs, images, brief, manifest):- Critique = critic_schema()- client, model, extra = planner._client()- content = []- for p in list(refs) + list(images):- content.append({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg",- "data": scene_builder._jpeg(p)}})- content.append({"type": "text", "text": CRITIC.format(n_refs=len(refs), brief=brief, manifest=manifest)})- with client.beta.messages.stream(model=model, max_tokens=16000, thinking={"type": "adaptive"},- output_config={"effort": "high", "format": {"type": "json_schema",- "schema": planner.strict_schema(Critique)}},- messages=[{"role": "user", "content": content}], **extra) as s:- msg = s.get_final_message()- c = Critique.model_validate_json(next(b.text for b in msg.content if b.type == "text"))- d = c.model_dump()- v = list(d["scores"].values())- d["passed"] = min(v) >= 6 and sum(v) / len(v) >= 7 # a good production base, same rule as the scene critic- return d---# ---------------------------------------------------------------- run-class KitBuilder(scene_builder.SceneBuilder):- """The scene builder's session, hooks, heartbeat and cap guard, with the kit's tools, critic and definition of done."""-- ASK = "Build the kit from the style reference in input/. Start by reading KIT.md, then SKILL.md steps 3-6."-- def __init__(self, work, refs, uploader=None, emit=None, effort="medium"):- super().__init__(work, refs, "kit", uploader=uploader, emit=emit, effort=effort)-- def brief(self):- txt = open(os.path.join(self.work, "input", "brief.md"), encoding="utf-8").read().strip()- items = json.load(open(os.path.join(self.work, "input", "items.json"), encoding="utf-8"))- dials = json.load(open(os.path.join(self.work, "input", "dials.json"), encoding="utf-8"))- return (txt + (f"\nItems requested: {', '.join(items)}" if items else "")- + (f"\nDials: {json.dumps(dials)}" if dials else ""))-- def tools(self):- d = self-- @tool("report", "Post a stage event to the customer's live log, optionally with a rendered image.",- {"stage": str, "message": str, "image": str})- async def report(args):- d.emit(args["stage"], "running", args.get("message", ""), args.get("image") or None)- return {"content": [{"type": "text", "text": "reported"}]}-- @tool("critique", "Independent kit critic: compares the style reference with your lineup and thumbnails "- "(paths relative to the workspace or absolute; the lineup FIRST, then up to 10 thumbnails). "- "It also reads out/kit.json for dims. Returns scores 1-10 per category, up to five fixes that "- "matter, and whether it passes (no category below 6, average 7+). At most "- f"{MAX_CRITIC_ROUNDS} rounds.",- {"type": "object", "properties": {"images": {"type": "array", "items": {"type": "string"}}},- "required": ["images"]})- async def critique(args):- if len(d.critiques) >= MAX_CRITIC_ROUNDS:- return {"content": [{"type": "text", "text": (- f"The critic has had its {MAX_CRITIC_ROUNDS} rounds; no more reviews. Stop iterating on the look: "- "finish every remaining deliverable (items/<id>/<id>.glb and _lod1.glb, renders/lineup.png, "- "renders/thumbs/, kit.json, kit.blend, dials.json, NOTES.md) and deliver.")}]}- paths = [p if os.path.isabs(p) else os.path.join(d.work, p) for p in args["images"]]- missing = [p for p in paths if not os.path.exists(p)]- if missing:- return {"content": [{"type": "text", "text": f"missing: {missing}"}], "is_error": True}- d.emit("critique", "running", f"critic is looking at the lineup and {len(paths) - 1} item renders")- res = await asyncio.to_thread(run_critic, d.refs, paths[:11], d.brief(), manifest_text(d.work))- res["round"] = len(d.critiques) + 1- res["stills"] = paths- d.critiques.append(res)- json.dump(res, open(os.path.join(d.work, "out", "critique", f"round_{res['round']}.json"), "w"), indent=1)- sc = res["scores"]- d.emit("critique", "done" if res["passed"] else "running",- f"round {res['round']}: {'PASS' if res['passed'] else 'not yet'} - "- + ", ".join(f"{k} {v}" for k, v in sc.items()), paths[0], critique=res)- return {"content": [{"type": "text", "text": json.dumps(res, indent=1)}]}-- return [report, critique]-- async def pre_tool(self, inp, tool_use_id, ctx):- import time- self.working = (self.describe(inp.get("tool_name", ""), inp.get("tool_input") or {}, self.work), time.time())- if self.elapsed() > CAP_WARN_S and not self.cap_warned:- self.cap_warned = True- return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": (- "The platform ends this request at 120 minutes and the kit is now past 95. Before anything else, make "- "sure out/ holds your best current version of every deliverable (kit.json, items/<id>/<id>.glb and "- "_lod1.glb, renders/lineup.png, renders/thumbs/, kit.blend, dials.json), then keep improving.")}}- return {}-- def kit(self):- try:- return json.load(open(os.path.join(self.work, "out", "kit.json"), encoding="utf-8"))- except Exception:- return None-- def missing(self):- out = os.path.join(self.work, "out")- miss = []- kit = self.kit()- if not kit or not kit.get("items"):- miss.append("out/kit.json with an items list")- else:- for it in kit["items"]:- i = it.get("id", "?")- for rel in (f"items/{i}/{i}.glb", f"items/{i}/{i}_lod1.glb", f"renders/thumbs/{i}.png"):- if not os.path.exists(os.path.join(out, rel)):- miss.append(f"out/{rel}")- for k in ("label", "dims_m", "tris", "generator", "why"):- if k not in it:- miss.append(f"kit.json item {i} has no {k}")- for f in ("kit.blend", "renders/lineup.png", "dials.json"):- if not os.path.exists(os.path.join(out, f)):- miss.append(f"out/{f}")- if not self.critiques:- miss.append("no critique yet")- elif not self.critiques[-1]["passed"] and len(self.critiques) < MAX_CRITIC_ROUNDS:- miss.append("the last critique did not pass")- return miss-- async def run(self, env):- prompt = open(os.path.join(self.work, ".builder", "PROMPT.md"), encoding="utf-8").read()- server = create_sdk_mcp_server("scene", tools=self.tools()) # "scene": the base post_tool quiets mcp__scene__*- beat = asyncio.create_task(self.heartbeat())- self.emit("received", "running", "kit builder starting")- result, session_id, attempt = None, None, 0- ask = self.ASK- while True:- opts = ClaudeAgentOptions(- model=env.get("ANTHROPIC_MODEL") or MODEL, effort=self.effort, permission_mode="bypassPermissions",- cwd=self.work,- system_prompt={"type": "preset", "preset": "claude_code", "append": prompt},- mcp_servers={"scene": server}, setting_sources=[], settings='{"fastMode": true}',- hooks={"PreToolUse": [HookMatcher(hooks=[self.pre_tool])],- "PostToolUse": [HookMatcher(hooks=[self.post_tool])],- "Stop": [HookMatcher(hooks=[self.on_stop])]},- max_buffer_size=256 * 1024 * 1024, resume=session_id,- env=env, stderr=lambda l: self.note("STDERR " + l[:300]))- try:- async with ClaudeSDKClient(opts) as client:- async def cap_guard():- while self.elapsed() < CAP_STOP_S:- await asyncio.sleep(15)- self.capped = True- self.emit("error", "running", "stopping the kit builder before the platform's 2-hour limit; "- "packaging what it has")- await client.interrupt()- guard = asyncio.create_task(cap_guard())- try:- await client.query(ask)- async for m in client.receive_response():- session_id = getattr(m, "session_id", None) \- or (getattr(m, "data", None) or {}).get("session_id") or session_id- if isinstance(m, AssistantMessage):- for b in m.content:- if isinstance(b, TextBlock) and b.text.strip():- self.note("SAY " + b.text.strip()[:2000])- self.emit("thinking", "running", b.text.strip()[:400])- elif isinstance(m, ResultMessage):- result = m- finally:- guard.cancel()- break- except Exception as e:- import traceback- if self.capped:- break- attempt += 1- self.note("SESSION ERROR " + traceback.format_exc()[-3000:])- self.emit("error", "running", f"agent session error ({type(e).__name__}: {str(e)[:200]}); "- f"{'resuming' if attempt <= 3 and session_id else 'giving up'}")- if attempt > 3 or not session_id:- raise- ask = ("The previous turn was cut off by a harness error, not by you. Continue the kit from where "- "you were; check the state of the workspace first.")- beat.cancel()- cost = getattr(result, "total_cost_usd", None)- self.emit("done", "done", f"kit builder finished after {self.elapsed() / 60:.0f} min"- + (f", agent cost ${cost:.2f}" if cost else ""), missing=self.missing(),- critiques=len(self.critiques))- return result---def generation_spend(work):- try:- rows = [json.loads(l) for l in open(os.path.join(work, "generate", "spend.jsonl"), encoding="utf-8") if l.strip()]- except OSError:- return 0.0- return round(sum(r.get("est_usd", 0) for r in rows), 2)---def main():- p = argparse.ArgumentParser()- p.add_argument("refs", nargs="+")- p.add_argument("--work", required=True)- p.add_argument("--prompt", default="")- p.add_argument("--items", default="")- p.add_argument("--effort", default="medium")- a = p.parse_args()- sys.stdout.reconfigure(encoding="utf-8")- work = os.path.abspath(a.work)- if not os.path.exists(os.path.join(work, "KIT.md")):- make_workspace(work, a.refs, a.prompt, toolkit_files(), items=[s for s in a.items.split(",") if s])- refs = sorted(os.path.join(work, "input", f) for f in os.listdir(os.path.join(work, "input")) if f.startswith("reference_")- and f.endswith(".png"))- asyncio.run(KitBuilder(work, refs, effort=a.effort).run(agent_env()))---if __name__ == "__main__":- main()diff --git a/kit/tools/compare.py b/kit/tools/compare.pydeleted file mode 100644index a450d20..0000000--- a/kit/tools/compare.py+++ /dev/null@@ -1,208 +0,0 @@-"""Tripo vs Meshy for kit items, in ONE Blender session: one sheet per item, ready the moment its meshes land.-- blender -b --factory-startup --python kit/tools/compare.py -- [--ids a,b] [--gen assets/gen] [--refs refs/kit] \- [--out scenes/kit/compare] [--res 512] [--samples 24] [--clay workbench|cycles]--Per item: reference | tripo beauty | tripo clay | meshy beauty | meshy clay, written to <out>/<id>.png, with the-tris and dims of each model in <out>/<id>.json. Beauty is a quick Cycles render; clay is Workbench (shows what is-real geometry; `--clay cycles` if Workbench can't open a context). Both models are turned to face -Y first (Tripo--90 deg), so the views match. Items whose sheet is newer than both GLBs are skipped, so call it again as more land.-"""--import json-import math-import os-import sys--import bpy-import numpy as np-from mathutils import Vector--argv = sys.argv[sys.argv.index("--") + 1:]-opt = lambda k, d: type(d)(argv[argv.index(k) + 1]) if k in argv else d-GEN = os.path.abspath(opt("--gen", "assets/gen"))-REFS = os.path.abspath(opt("--refs", "refs/kit"))-OUT = os.path.abspath(opt("--out", "scenes/kit/compare"))-RES = opt("--res", 512)-SAMPLES = opt("--samples", 24)-CLAY = opt("--clay", "workbench")-IDS = [s for s in opt("--ids", "").split(",") if s]-MODELS = ("tripo-h31", "meshy")-os.makedirs(OUT, exist_ok=True)---def glb(model, iid):- return os.path.join(GEN, model, iid, "model.glb")---def ids():- found = set(IDS)- if not found:- for m in MODELS:- d = os.path.join(GEN, m)- if os.path.isdir(d):- found |= {i for i in os.listdir(d) if os.path.exists(glb(m, i))}- return sorted(found)---def reset():- bpy.ops.wm.read_factory_settings(use_empty=True)- sc = bpy.context.scene- sc.render.resolution_x = sc.render.resolution_y = RES- sc.view_settings.view_transform = "AgX"- w = bpy.data.worlds.new("w")- sc.world = w- w.use_nodes = True- w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.5, 0.5, 0.52, 1)- w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.6- return sc---def light(name, loc, energy, size):- d = bpy.data.lights.new(name, "AREA")- d.energy, d.size = energy, size- o = bpy.data.objects.new(name, d)- bpy.context.scene.collection.objects.link(o)- o.location = loc- o.rotation_euler = (-Vector(loc)).to_track_quat("-Z", "Y").to_euler()---def bounds(objs):- """Tight world bounds from the vertices (a rotated object's bound_box is loose: Tripo meshes carry a rotation)."""- los, his = [], []- for o in objs:- co = np.empty(len(o.data.vertices) * 3, np.float32)- o.data.vertices.foreach_get("co", co)- m = np.array(o.matrix_world, np.float32)- w = co.reshape(-1, 3) @ m[:3, :3].T + m[:3, 3]- los.append(w.min(0))- his.append(w.max(0))- return Vector(np.min(los, 0).tolist()), Vector(np.max(his, 0).tolist())---def unpose(objs):- """Tripo's orientation=align_image puts a Z rotation (about +-20-30 deg) on the glTF node to match the reference- photo's three-quarter view. Drop it so the mesh sits in Tripo's canonical frame (front +X)."""- for o in objs:- o.rotation_mode = "QUATERNION"- o.rotation_quaternion = (1, 0, 0, 0)- bpy.context.view_layer.update()---def stats(objs, size):- t = 0- for o in objs:- o.data.calc_loop_triangles()- t += len(o.data.loop_triangles)- return {"tris": t, "raw_size": [round(v, 3) for v in size]}---def render_model(model, iid, prefix):- sc = reset()- before = set(bpy.data.objects)- bpy.ops.import_scene.gltf(filepath=glb(model, iid))- new = [o for o in bpy.data.objects if o not in before]- objs = [o for o in new if o.type == "MESH"]- if model.startswith("tripo"):- unpose(new)- lo, hi = bounds(objs)- st = stats(objs, hi - lo)- root = bpy.data.objects.new("root", None)- sc.collection.objects.link(root)- for o in new:- if o.parent is None:- o.parent = root- s = 1.0 / max(hi - lo)- c = (lo + hi) / 2- root.scale = (s, s, s)- if model.startswith("tripo"):- root.rotation_euler.z = math.radians(-90)- bpy.context.view_layer.update()- lo, hi = bounds(objs)- root.location -= Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))- bpy.context.view_layer.update()- lo, hi = bounds(objs)- centre, radius = (lo + hi) / 2, (hi - lo).length / 2- light("key", (2.2, -2.6, 3.0), 260, 1.6)- light("fill", (-3.0, -1.5, 1.6), 70, 2.5)- light("rim", (-1.0, 3.0, 2.5), 160, 1.2)- cd = bpy.data.cameras.new("cam")- cd.lens = 70- cam = bpy.data.objects.new("cam", cd)- sc.collection.objects.link(cam)- sc.camera = cam- az, el = math.radians(-30), math.radians(18)- cam.location = centre + Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) \- * (radius / math.sin(cd.angle / 2) * 1.02)- cam.rotation_euler = (centre - cam.location).to_track_quat("-Z", "Y").to_euler()- sc.render.engine = "CYCLES"- sc.cycles.device = "GPU"- sc.cycles.samples = SAMPLES- sc.cycles.use_denoising = True- sc.render.filepath = prefix + "_beauty.png"- bpy.ops.render.render(write_still=True)- if CLAY == "workbench":- sc.render.engine = "BLENDER_WORKBENCH"- sh = sc.display.shading- sh.light, sh.color_type, sh.show_cavity = "STUDIO", "SINGLE", True- sh.single_color = (0.6, 0.6, 0.6)- else:- clay = bpy.data.materials.new("clay")- clay.use_nodes = True- clay.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.55, 0.55, 0.55, 1)- for o in objs:- o.data.materials.clear()- o.data.materials.append(clay)- sc.cycles.samples = 16- sc.render.filepath = prefix + "_clay.png"- bpy.ops.render.render(write_still=True)- return st---def pixels(path):- """An RGBA float array (RES x RES), or grey when the file is missing."""- if not path or not os.path.exists(path):- return np.full((RES, RES, 4), 0.25, np.float32)- img = bpy.data.images.load(path)- w, h = img.size- f = RES / max(w, h)- img.scale(max(1, int(w * f)), max(1, int(h * f)))- w, h = img.size- a = np.empty(w * h * 4, np.float32)- img.pixels.foreach_get(a)- a = a.reshape(h, w, 4)- bpy.data.images.remove(img)- cell = np.full((RES, RES, 4), 0.25, np.float32)- y0, x0 = (RES - h) // 2, (RES - w) // 2- cell[y0:y0 + h, x0:x0 + w] = a- return cell---for iid in ids():- sheet = os.path.join(OUT, f"{iid}.png")- srcs = [glb(m, iid) for m in MODELS if os.path.exists(glb(m, iid))]- if os.path.exists(sheet) and all(os.path.getmtime(sheet) > os.path.getmtime(s) for s in srcs) \- and len(srcs) == len(MODELS):- print("skip", iid)- continue- info = {}- cells = [os.path.join(REFS, f"{iid}_0.png")]- for m in MODELS:- prefix = os.path.join(OUT, "_r", f"{iid}_{m}")- os.makedirs(os.path.dirname(prefix), exist_ok=True)- if os.path.exists(glb(m, iid)):- try:- info[m] = render_model(m, iid, prefix)- cells += [prefix + "_beauty.png", prefix + "_clay.png"]- continue- except Exception as e:- info[m] = {"error": repr(e)}- cells += [None, None]- row = np.concatenate([pixels(p) for p in cells], axis=1)- out = bpy.data.images.new("sheet", row.shape[1], row.shape[0], alpha=True)- out.pixels.foreach_set(row.ravel())- out.filepath_raw = sheet- out.file_format = "PNG"- out.save()- json.dump(info, open(os.path.join(OUT, f"{iid}.json"), "w"), indent=1)- print("SHEET", iid, json.dumps(info), flush=True)diff --git a/kit/tools/library.py b/kit/tools/library.pydeleted file mode 100644index a5ca662..0000000--- a/kit/tools/library.py+++ /dev/null@@ -1,99 +0,0 @@-"""kit.blend: a Blender asset library holding every kit item, each marked as an asset with a preview, label, tags-and its LOD1 alongside.-- blender -b --factory-startup --python kit/tools/library.py -- --kit out/kit.json --items out/items --out out/kit.blend--Each item is one object named <id> (LOD0) in a collection named after the kit, laid out in a row so the file is also-browsable; <id>_lod1 sits in a hidden "LOD1" collection. Everything is packed. A blender_assets.cats.txt with one-catalog for the kit is written next to the .blend, and every asset is assigned to it.-"""--import json-import os-import sys-import uuid--import bpy-from mathutils import Vector--argv = sys.argv[sys.argv.index("--") + 1:]-opt = lambda k, d: argv[argv.index(k) + 1] if k in argv else d-KIT = os.path.abspath(opt("--kit", "out/kit.json"))-ITEMS = os.path.abspath(opt("--items", "out/items"))-OUT = os.path.abspath(opt("--out", "out/kit.blend"))-kit = json.load(open(KIT))-name = kit.get("name") or "Kit"--bpy.ops.wm.read_factory_settings(use_empty=True)-sc = bpy.context.scene-main = bpy.data.collections.new(name)-sc.collection.children.link(main)-lods = bpy.data.collections.new("LOD1")-sc.collection.children.link(lods)-cat_id = str(uuid.uuid5(uuid.NAMESPACE_DNS, "anykit/" + name))---def load(path, obname, coll):- before = set(bpy.data.objects)- bpy.ops.import_scene.gltf(filepath=path)- new = [o for o in bpy.data.objects if o not in before]- meshes = [o for o in new if o.type == "MESH"]- for o in bpy.context.selected_objects:- o.select_set(False)- for o in meshes:- mw = o.matrix_world.copy()- o.parent = None- o.matrix_world = mw- o.select_set(True)- bpy.context.view_layer.objects.active = meshes[0]- if len(meshes) > 1:- bpy.ops.object.join()- ob = bpy.context.view_layer.objects.active- bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)- for o in new:- if o.name in bpy.data.objects and o is not ob:- bpy.data.objects.remove(o)- ob.name = ob.data.name = obname- for c in ob.users_collection:- c.objects.unlink(ob)- coll.objects.link(ob)- return ob---x = 0.0-for it in kit["items"]:- d = os.path.join(ITEMS, it["id"])- ob = load(os.path.join(d, f"{it['id']}.glb"), it["id"], main)- lo = min((ob.matrix_world @ Vector(c)).x for c in ob.bound_box)- hi = max((ob.matrix_world @ Vector(c)).x for c in ob.bound_box)- ob.location.x = x - lo- x += (hi - lo) + 0.1- ob.asset_mark()- ad = ob.asset_data- ad.description = it.get("label", it["id"])- ad.catalog_id = cat_id- for t in it.get("tags", []) + [name]:- ad.tags.new(t, skip_if_exists=True)- for k in ("dims_m", "tris", "generator"):- if k in it:- ob[k] = it[k]- ob["label"] = it.get("label", it["id"])- lod_path = os.path.join(d, f"{it['id']}_lod1.glb")- if os.path.exists(lod_path):- lod = load(lod_path, f"{it['id']}_lod1", lods)- lod.location = ob.location- ob["lod1"] = lod.name- with bpy.context.temp_override(id=ob):- try:- bpy.ops.ed.lib_id_generate_preview()- except Exception as e: # previews need a GPU context in some builds; the asset still works without one- print("preview skipped", it["id"], e)--lods.hide_render = True-lods.hide_viewport = True-bpy.ops.file.pack_all()-os.makedirs(os.path.dirname(OUT), exist_ok=True)-bpy.ops.wm.save_as_mainfile(filepath=OUT, compress=True)-with open(os.path.join(os.path.dirname(OUT), "blender_assets.cats.txt"), "w") as f:- f.write(f"VERSION 1\n\n{cat_id}:{name}:{name}\n")-print("LIBRARY", OUT, len(kit["items"]), "assets")diff --git a/kit/tools/normalize.py b/kit/tools/normalize.pydeleted file mode 100644index 6ca5ff5..0000000--- a/kit/tools/normalize.py+++ /dev/null@@ -1,191 +0,0 @@-"""Generator GLB -> kit item: real metres, bottom-centre origin, front facing -Y, textures <= 2K, plus a LOD1.--One item:- blender -b --factory-startup --python kit/tools/normalize.py -- \- --glb assets/gen/meshy/<id>/model.glb --gen meshy --id <id> --out out/items/<id> \- (--h 0.32 | --fit 0.40 0.30 0.32) [--yaw 0] [--tex 2048] [--max-tris 100000] [--lod1 0.25]--Many items in ONE Blender session, and kit.json written in the same pass (the fast path):- blender -b --factory-startup --python kit/tools/normalize.py -- --jobs scenes/kit/prep.json \- [--items out/items] [--kit out/kit.json] [--tex 2048] [--max-tris 100000] [--lod1 0.25]- prep.json: {"name": "...", "style": "...", "prompt": "...",- "items": [{"id", "label", "glb", "gen", "h" | "fit": [x, y, z], "yaw"?, "max_tris"?, "why", "tags"?,- "fixes"?}, ...]}- Items whose GLB is missing are skipped (run it again as more land); kit.json is rewritten from every item that has- a stats.json, in prep.json's order, so it is always current.--Writes out/items/<id>/<id>.glb, <id>_lod1.glb (about 1/4 the tris, half-size textures) and stats.json (dims_m, tris,-tris_lod1, textures).----gen tripo rotates the mesh -90 deg about Z first (Tripo's front faces +X; Meshy's already faces -Y). --yaw adds-a further rotation (degrees, about Z) when a model's front is somewhere else. --h scales uniformly to that height.---fit X Y Z scales each axis to exact dims (for boxy props whose depth the generator invented). A starting point:-copy it into scenes/kit/scripts/ and change it when an item needs more.-"""--import json-import math-import os-import sys--import bpy-from mathutils import Matrix, Vector--argv = sys.argv[sys.argv.index("--") + 1:]---def opt(k, d=None, n=1, cast=str):- if k not in argv:- return d- i = argv.index(k)- vals = [cast(v) for v in argv[i + 1:i + 1 + n]]- return vals[0] if n == 1 else vals---TEX = opt("--tex", 2048, cast=int)-MAX_TRIS = opt("--max-tris", 100000, cast=int)-LOD1 = opt("--lod1", 0.25, cast=float)---def bbox(ob):- vs = [v.co for v in ob.data.vertices]- lo = Vector((min(v.x for v in vs), min(v.y for v in vs), min(v.z for v in vs)))- hi = Vector((max(v.x for v in vs), max(v.y for v in vs), max(v.z for v in vs)))- return lo, hi---def tris(ob):- ob.data.calc_loop_triangles()- return len(ob.data.loop_triangles)---def decimate(ob, target):- t = tris(ob)- if t <= target:- return- m = ob.modifiers.new("dec", "DECIMATE")- m.ratio = target / t- m.use_collapse_triangulate = True- with bpy.context.temp_override(object=ob, active_object=ob):- bpy.ops.object.modifier_apply(modifier=m.name)---def export(path):- bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", use_selection=True, export_apply=True,- export_image_format="AUTO", export_yup=True)---def normalize(glb, gen, iid, out, h=None, fit=None, yaw=0.0, max_tris=MAX_TRIS):- glb, out = os.path.abspath(glb), os.path.abspath(out)- os.makedirs(out, exist_ok=True)- bpy.ops.wm.read_factory_settings(use_empty=True)- bpy.ops.import_scene.gltf(filepath=glb)- meshes = [o for o in bpy.context.scene.objects if o.type == "MESH"]- if not meshes:- raise RuntimeError(f"no meshes in {glb}")- if gen.startswith("tripo"):- # Tripo's orientation=align_image puts a Z rotation (~+-20-30 deg) on the node to match the reference photo's- # three-quarter view; drop it so the mesh is in Tripo's canonical frame (front +X) before the -90 below- for o in bpy.context.scene.objects:- o.rotation_mode = "QUATERNION"- o.rotation_quaternion = (1, 0, 0, 0)- bpy.context.view_layer.update()- # bake every transform (glTF parents, quaternion rotations) into the mesh data, then join into one object- for o in bpy.context.scene.objects:- o.select_set(False)- for o in meshes:- mw = o.matrix_world.copy()- o.parent = None- o.data.transform(mw)- o.matrix_world = Matrix.Identity(4)- for o in [o for o in bpy.context.scene.objects if o.type != "MESH"]:- bpy.data.objects.remove(o)- vl = bpy.context.view_layer- for o in meshes:- o.select_set(True)- vl.objects.active = meshes[0]- if len(meshes) > 1:- bpy.ops.object.join()- ob = vl.objects.active- ob.name = ob.data.name = iid- ob.rotation_mode = "XYZ"- # orientation: rotate the mesh data, never the object- rot = (-90.0 if gen.startswith("tripo") else 0.0) + (yaw or 0.0)- if rot:- ob.data.transform(Matrix.Rotation(math.radians(rot), 4, "Z"))- # decimate before anything else touches 2M-tri Tripo meshes- decimate(ob, max_tris)- lo, hi = bbox(ob)- size = hi - lo- if fit:- s = Vector([fit[i] / max(size[i], 1e-6) for i in range(3)])- elif h:- s = Vector([h / max(size.z, 1e-6)] * 3)- else:- s = Vector((1, 1, 1))- ob.data.transform(Matrix.Translation(-Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))))- ob.data.transform(Matrix.Diagonal((s.x, s.y, s.z, 1)))- lo, hi = bbox(ob)- # textures: downscale anything over TEX, and repack ONLY those (pack() on an untouched packed image drops its data)- textures = {}- for img in bpy.data.images:- if img.size[0] == 0:- continue- w, hh = img.size- if max(w, hh) > TEX:- f = TEX / max(w, hh)- img.scale(max(1, int(w * f)), max(1, int(hh * f)))- img.pack()- textures[img.name] = list(img.size)- bpy.ops.object.select_all(action="SELECT")- export(os.path.join(out, f"{iid}.glb"))- t0 = tris(ob)- decimate(ob, max(500, int(t0 * LOD1)))- for img in bpy.data.images: # LOD1 textures at half resolution- if img.size[0] > 256:- img.scale(max(1, img.size[0] // 2), max(1, img.size[1] // 2))- img.pack()- export(os.path.join(out, f"{iid}_lod1.glb"))- stats = {"id": iid, "source_glb": glb, "generator": gen, "rot_deg": rot, "dims_m": [round(v, 4) for v in hi - lo],- "tris": t0, "tris_lod1": tris(ob), "textures": textures}- json.dump(stats, open(os.path.join(out, "stats.json"), "w"), indent=1)- print("NORMALIZED", json.dumps(stats), flush=True)- return stats---if "--jobs" in argv:- jobs = json.load(open(opt("--jobs")))- items_dir = os.path.abspath(opt("--items", "out/items"))- kit_path = os.path.abspath(opt("--kit", "out/kit.json"))- force = "--force" in argv- for j in jobs["items"]:- out = os.path.join(items_dir, j["id"])- st = os.path.join(out, "stats.json")- if not os.path.exists(j["glb"]):- print("WAITING", j["id"], "(no GLB yet)", flush=True)- continue- if not force and os.path.exists(st) and os.path.getmtime(st) > os.path.getmtime(j["glb"]) \- and os.path.getmtime(st) > os.path.getmtime(opt("--jobs")):- continue # already prepped from this GLB and these settings- try:- normalize(j["glb"], j.get("gen", "meshy"), j["id"], out, j.get("h"), j.get("fit"), j.get("yaw", 0),- j.get("max_tris", MAX_TRIS))- except Exception as e: # keep going; report it- print("FAILED", j["id"], repr(e), flush=True)- items = []- for j in jobs["items"]:- st = os.path.join(items_dir, j["id"], "stats.json")- if not os.path.exists(st):- continue- s = json.load(open(st))- items.append({"id": j["id"], "label": j.get("label", j["id"]), "dims_m": s["dims_m"], "tris": s["tris"],- "tris_lod1": s["tris_lod1"], "generator": j.get("gen", s["generator"]), "why": j.get("why", ""),- "tags": j.get("tags", []), "fixes": j.get("fixes", [])})- kit = {k: jobs.get(k, "") for k in ("name", "style", "prompt")}- kit["items"] = items- os.makedirs(os.path.dirname(kit_path), exist_ok=True)- json.dump(kit, open(kit_path, "w"), indent=1)- print("KIT", kit_path, len(items), "of", len(jobs["items"]), "items", flush=True)-else:- normalize(opt("--glb"), opt("--gen", "meshy"), opt("--id"), opt("--out"), opt("--h", None, cast=float),- opt("--fit", None, n=3, cast=float), opt("--yaw", 0.0, cast=float))diff --git a/kit/tools/present.py b/kit/tools/present.pydeleted file mode 100644index 15fe1fb..0000000--- a/kit/tools/present.py+++ /dev/null@@ -1,237 +0,0 @@-"""Kit presentation renders: the lineup (every item side by side on a neutral ground, with a scale bar and labels),-a thumbnail per item, and optionally a turntable per item.-- blender -b --factory-startup --python kit/tools/present.py -- --kit out/kit.json --items out/items --out out/renders \- [--only lineup|thumbs|turntable] [--samples 128] [--warmth 0] [--turntable 48] [--ids a,b]--Reads item ids and labels from kit.json ("items": [{"id", "label"}, ...]) and loads out/items/<id>/<id>.glb as they-are (already normalised: metres, bottom-centre origin, facing -Y). Writes lineup.png, thumbs/<id>.png and-turntables/<id>.mp4 (needs ffmpeg). A starting point: copy it into scenes/kit/scripts/ to change the look.-"""--import json-import math-import os-import shutil-import subprocess-import sys--import bpy-from mathutils import Vector--argv = sys.argv[sys.argv.index("--") + 1:]-opt = lambda k, d: type(d)(argv[argv.index(k) + 1]) if k in argv else d-KIT = os.path.abspath(opt("--kit", "out/kit.json"))-ITEMS = os.path.abspath(opt("--items", "out/items"))-OUT = os.path.abspath(opt("--out", "out/renders"))-ONLY = opt("--only", "")-SAMPLES = opt("--samples", 128)-WARMTH = opt("--warmth", 0.0)-TURN = opt("--turntable", 0)-IDS = [s for s in opt("--ids", "").split(",") if s]-os.makedirs(OUT, exist_ok=True)--kit = json.load(open(KIT))-items = [it for it in kit["items"] if not IDS or it["id"] in IDS]---def kelvin_rgb(k):- # rough blackbody tint, good enough for a warm/cool key- t = k / 100- r = 1.0 if t <= 66 else max(0, min(1, 1.292936 * (t - 60) ** -0.1332047592))- g = max(0, min(1, (0.39008157876 * math.log(t) - 0.63184144) if t <= 66 else 1.129890861 * (t - 60) ** -0.0755148492))- b = 1.0 if t >= 66 else (0 if t <= 19 else max(0, min(1, 0.54320678911 * math.log(t - 10) - 1.19625408914)))- return (r, g, b)---def setup():- bpy.ops.wm.read_factory_settings(use_empty=True)- sc = bpy.context.scene- sc.render.engine = "CYCLES"- sc.cycles.device = "GPU"- sc.cycles.samples = SAMPLES- sc.cycles.use_denoising = True- sc.view_settings.view_transform = "AgX"- sc.view_settings.look = "AgX - Medium High Contrast"- w = bpy.data.worlds.new("w")- sc.world = w- w.use_nodes = True- w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.36, 0.37, 0.38, 1)- w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.35- # neutral ground + curved backdrop (a sweep), so the horizon never shows- bpy.ops.mesh.primitive_plane_add(size=1)- g = bpy.context.object- g.name = "ground"- g.scale = (60, 60, 1)- gm = bpy.data.materials.new("ground")- gm.use_nodes = True- p = gm.node_tree.nodes["Principled BSDF"]- p.inputs["Base Color"].default_value = (0.42, 0.42, 0.42, 1)- p.inputs["Roughness"].default_value = 0.85- g.data.materials.append(gm)- return sc---def light(name, loc, target, energy, size, color=(1, 1, 1)):- d = bpy.data.lights.new(name, "AREA")- d.energy, d.size, d.color = energy, size, color- o = bpy.data.objects.new(name, d)- bpy.context.scene.collection.objects.link(o)- o.location = loc- o.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()- return o---def studio(centre, radius):- key_k = 5600 + 1800 * -WARMTH # warmth 1 -> ~3800 K, -1 -> ~7400 K- c = Vector(centre)- s = max(radius, 0.2)- light("key", c + Vector((1.6, -2.2, 2.4)) * s, c, 220 * s * s, 1.6 * s, kelvin_rgb(key_k))- light("fill", c + Vector((-2.6, -1.4, 1.2)) * s, c, 60 * s * s, 2.5 * s, kelvin_rgb(key_k + 1500))- light("rim", c + Vector((-0.8, 2.6, 2.2)) * s, c, 140 * s * s, 1.4 * s)---def load(item):- path = os.path.join(ITEMS, item["id"], f"{item['id']}.glb")- before = set(bpy.data.objects)- bpy.ops.import_scene.gltf(filepath=path)- new = [o for o in bpy.data.objects if o not in before]- root = bpy.data.objects.new(item["id"], None)- bpy.context.scene.collection.objects.link(root)- for o in new:- if o.parent is None:- o.parent = root- bpy.context.view_layer.update()- return root, [o for o in new if o.type == "MESH"]---def bounds(objs):- pts = [o.matrix_world @ Vector(c) for o in objs for c in o.bound_box]- lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))- hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))- return lo, hi---def camera(lens=50):- d = bpy.data.cameras.new("cam")- d.lens = lens- o = bpy.data.objects.new("cam", d)- bpy.context.scene.collection.objects.link(o)- bpy.context.scene.camera = o- return o---def aim(cam, centre, az, el, dist):- a, e = math.radians(az), math.radians(el)- cam.location = Vector(centre) + Vector((math.sin(a) * math.cos(e), -math.cos(a) * math.cos(e), math.sin(e))) * dist- cam.rotation_euler = (Vector(centre) - cam.location).to_track_quat("-Z", "Y").to_euler()---def mat(name, rgb, emit=0.0):- m = bpy.data.materials.new(name)- m.use_nodes = True- p = m.node_tree.nodes["Principled BSDF"]- p.inputs["Base Color"].default_value = (*rgb, 1)- p.inputs["Roughness"].default_value = 0.6- return m---def text(body, loc, size, m):- c = bpy.data.curves.new("t", "FONT")- c.body, c.size, c.align_x = body, size, "CENTER"- o = bpy.data.objects.new("label_" + body[:20], c)- bpy.context.scene.collection.objects.link(o)- o.location = loc- o.rotation_euler = (math.pi / 2, 0, 0) # stand it up, facing the camera (-Y)- o.data.materials.append(m)- return o---def lineup():- sc = setup()- loaded = [(it, *load(it)) for it in items]- heights = [bounds(m)[1].z for _, _, m in loaded]- gap = max(0.06, 0.12 * max(heights))- x = 0.0- depth = 0.0- for it, root, meshes in loaded:- lo, hi = bounds(meshes)- w = hi.x - lo.x- root.location.x = x + w / 2 - (lo.x + hi.x) / 2- x += w + gap- depth = max(depth, hi.y - lo.y)- bpy.context.view_layer.update()- allm = [o for _, _, m in loaded for o in m]- lo, hi = bounds(allm)- total = hi.x - lo.x- # scale bar: alternating 10 cm (or 1 cm for tiny kits) blocks, a "nice" length about a fifth of the width- nice = min((0.05, 0.1, 0.2, 0.25, 0.5, 1.0, 2.0, 5.0), key=lambda v: abs(v - total / 5))- step = nice / 10 if nice <= 0.25 else 0.1- dark, light_m, ink = mat("bar_dark", (0.03, 0.03, 0.03)), mat("bar_light", (0.85, 0.85, 0.85)), mat("ink", (0.04, 0.04, 0.04))- by = lo.y - max(0.06, depth * 0.35)- th = max(0.004, nice / 40)- for i in range(round(nice / step)):- bpy.ops.mesh.primitive_cube_add(size=1, location=(lo.x + step * (i + 0.5), by, 0.001))- b = bpy.context.object- b.scale = (step, th * 2, 0.002)- b.data.materials.append(dark if i % 2 == 0 else light_m)- label = f"{nice * 100:.0f} cm" if nice < 1 else f"{nice:g} m"- t = text(label, (lo.x + nice / 2, by - th, th * 1.5), th * 4, ink)- # item labels on the ground in front of each item- lsize = max(0.01, min(0.04, gap * 0.22))- for it, root, meshes in loaded:- l2, h2 = bounds(meshes)- text(it.get("label", it["id"])[:28], ((l2.x + h2.x) / 2, l2.y - lsize * 1.5, 0.003), lsize, ink)- bpy.context.view_layer.update()- lo2, hi2 = bounds(allm)- centre = Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2 - 0.1 * depth, (hi2.z) * 0.42))- sc.render.resolution_x, sc.render.resolution_y = 2400, 1000- cam = camera(50)- fov_h = cam.data.angle- width = max(total * 1.2, (hi2.z) * 2.4 * 1.5)- dist = (width / 2) / math.tan(fov_h / 2) + depth- aim(cam, centre, 0, 14, dist)- studio(centre, max(total, hi2.z) * 0.6)- sc.render.filepath = os.path.join(OUT, "lineup.png")- bpy.ops.render.render(write_still=True)- print("LINEUP", sc.render.filepath)---def per_item(turntable=False):- for it in items:- sc = setup()- root, meshes = load(it)- lo, hi = bounds(meshes)- centre = (lo + hi) / 2- radius = (hi - lo).length / 2- studio(centre, radius * 1.4)- cam = camera(70)- dist = radius / math.sin(cam.data.angle / 2) * 1.05- if not turntable:- sc.render.resolution_x = sc.render.resolution_y = 1024- aim(cam, centre, -30, 20, dist)- os.makedirs(os.path.join(OUT, "thumbs"), exist_ok=True)- sc.render.filepath = os.path.join(OUT, "thumbs", f"{it['id']}.png")- bpy.ops.render.render(write_still=True)- continue- sc.render.resolution_x = sc.render.resolution_y = 640- sc.cycles.samples = min(SAMPLES, 48)- tmp = os.path.join(OUT, "turntables", f"_{it['id']}")- os.makedirs(tmp, exist_ok=True)- for f in range(TURN):- aim(cam, centre, -30 + 360 * f / TURN, 18, dist)- sc.render.filepath = os.path.join(tmp, f"{f:04d}.png")- bpy.ops.render.render(write_still=True)- mp4 = os.path.join(OUT, "turntables", f"{it['id']}.mp4")- subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-framerate", "24", "-i", os.path.join(tmp, "%04d.png"),- "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", mp4], check=True)- shutil.rmtree(tmp)---if ONLY in ("", "lineup"):- lineup()-if ONLY in ("", "thumbs"):- per_item()-if ONLY == "turntable" or (TURN and ONLY == ""):- TURN = TURN or 48- per_item(turntable=True)