Photoreal Blender scenes from a one-paragraph brief, built by AI agents: image→3D props on fal, scripted layout, lighting, camera and grade.
Python
AnyScene: brief to photoreal Blender scene, built by AI agents
Apekshik Panigrahib6ad3ce9be82
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..6313b56--- /dev/null+++ b/.gitattributes@@ -0,0 +1 @@+* text=auto eol=lfdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..be64e22--- /dev/null+++ b/.gitignore@@ -0,0 +1,34 @@+# Build outputs and generated assets: large, downloaded separately+*.blend+*.blend1+*.glb+*.vdb+*.exr+*.mp4+*.png+*.jpg+assets/+refs/+out/+cache/+scenes/*/props/+scenes/*/props_prebrand/+scenes/*/compare/+scenes/*/debrand/+scenes/*/out/+scenes/*/cache/+breakdown/*/+!breakdown/*.py+!breakdown/*.md++# Local state+generate/spend.jsonl+logs/+.gpu.queue/+.gpu.*_done+__pycache__/+node_modules/+.env*++# Blender writes this into the working directory+waveletNoiseTile.bindiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..197f554--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Apekshik Panigrahi++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..0baa4ae--- /dev/null+++ b/README.md@@ -0,0 +1,61 @@+# AnyScene++Photoreal Blender scenes from a one-paragraph brief, built by AI agents.++You describe a place. An agent following [`SKILL.md`](SKILL.md) then:+1. generates concept images and a reference image for every prop;+2. turns each prop into 3D with both Tripo H3.1 and Meshy 7.1 on [fal](https://fal.ai), and picks the better one;+3. scripts the room, dresses it from big furniture down to small clutter, and checks every prop for collisions and floating;+4. adds grime, decals, night lighting, haze, steam and rain;+5. shoots cinematic and handheld walk-through shots, renders them in Cycles and grades them;+6. cuts a behind-the-scenes video of how the scene was built.++No prop is modelled by hand. The two example scenes were each made in about a day of agent work, for about $150 of generation.++| Scene | Props | Shots |+|---|---|---|+| [`scenes/tokyo-electronics-repair`](scenes/tokyo-electronics-repair) — a 1 AM electronics repair counter, rain outside | 86 generated | 7 cinematic + 2 handheld |+| [`scenes/tokyo-ramen-shop`](scenes/tokyo-ramen-shop) — a ramen counter at last orders, steam and rain | 74 generated | 6 cinematic + 2 handheld |++This repo holds the process and the code. The finished scenes (.blend files, generated models, renders) are large and are+downloaded separately.++## Layout++```+SKILL.md the process, step by step, with every gotcha we hit; agents start here+generate/ fal client: reference images and image→3D (Tripo H3.1, Meshy 7.1), with a spend log+pipeline/ env.sh (finds Blender/ffmpeg), GPU queue, comparison renders, gallery page+camera/ camera rig and shot renderer: moves, rack focus, handheld walk, lens FX (see camera/README.md)+breakdown/ the behind-the-scenes video and the promo cut+scenes/<name>/ one folder per scene: assets.json (props), picks.json (model choices), shots.json, NOTES.md, scripts/+```++Each scene keeps its own build scripts in `scripts/`. A scene's room shell and dressing are specific to that place, so a+new scene starts from the closer example and an agent rewrites those parts.++## Requirements++- Blender 5.0+ (`BLENDER`, otherwise found on PATH or in the default install location)+- ffmpeg with `h264_nvenc` (`FFMPEG`, default `ffmpeg`). The example scenes were built on Windows with an NVIDIA GPU;+ on other GPUs, swap `h264_nvenc` for `libx264` in the encode steps.+- Node 20++- A fal API key in `FAL_KEY`+- `uv` for the breakdown videos (`uv run --with pillow python breakdown/assemble.py <scene>`)++## Start a new scene++Point your agent at `SKILL.md` and give it a brief:++> Use SKILL.md to build a new scene: a Lisbon tram depot at dawn, one tram half-stripped for repair.++Then check its work at each step's gate: concept, prop picks, clay layout, lit stills, shot previews.++## Credits++The process follows the "create high quality blender scene with AI" video workflow: concept image, scripted room shell,+image-to-3D props, scripted repair, dressing, shaders, lighting, handheld camera, grade.++## License++Code: MIT, see [LICENSE](LICENSE). Generated assets are released separately under their own license.diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..6a87c71--- /dev/null+++ b/SKILL.md@@ -0,0 +1,261 @@+---+name: anyscene+description: Build a photoreal, film-style Blender scene from a one-paragraph brief. Generate concept images and every prop with image→3D models on fal, then script the layout, set dressing, grime, lighting, camera moves and grade. Use it when someone asks for a realistic 3D environment, a set or a cinematic shot of a place, whether starting fresh or extending an existing AnyScene scene.+---++# AnyScene++AnyScene turns a brief like "a 1 AM electronics repair shop in Tokyo, rain outside" into a dressed, lit Blender scene with+cinematic shots and a behind-the-scenes video. Agents built the two example scenes (`scenes/tokyo-electronics-repair`, `scenes/tokyo-ramen-shop`) with this process.+Each has 75–90 generated props, 8–9 shots, and about $150 of generation per round.++You are the art department, set dresser, gaffer and DP. Everything is a script you can re-run; the .blend is a build output.+Never hand-edit a .blend you can't regenerate.++## Requirements++| Tool | Notes |+|---|---|+| Blender 5.0+ | `$BLENDER`. Background mode (`-b`) for everything; the GUI is only for a human to look. |+| ffmpeg | `$FFMPEG`. Needs an h264 encoder (`libx264` or `h264_nvenc`), `curves`, `hue`, `vignette`, `noise`, `xfade`. |+| Node 20+ | for `generate/fal.mjs` |+| fal key | `FAL_KEY` env var. Never print or log it. |+| GPU | 12–16 GB is enough for one Cycles render at a time. Two at once runs out of memory: see GPU rules. |++## Layout of a scene++```+scenes/<scene>/+ brief.md the brief + decisions (mood, time, lens style), kept up to date (new; the reference scenes keep this in NOTES.md)+ assets.json room dims + every prop: id, prompt, height h, optional dims [x,y,z]+ picks.json per prop: chosen model + one-line why; retired / debranded flags+ shots.json camrig shots (see camera/README.md)+ NOTES.md gotchas you hit, in one line each — read it before touching the scene+ props/<id>.blend prepped props (output of prep)+ out/ renders, sheets, graded shots+ scripts/ the scene's build scripts: shell, dress, validate, grime, lights, post+refs/<scene>/ concept images, prop references, textures/decals+assets/gen/<model>/<id>/model.glb raw generator output (never edited)+```++Reusable pieces (don't fork them per scene unless you need to change them):+- `generate/fal.mjs`: image and 3D generation, with an append-only spend log.+- `pipeline/gpu_run.sh`: a FIFO GPU queue.+- `pipeline/render_compare.py`: same-light comparison renders.+- `camera/`: camera rig and shot renderer.+- `breakdown/assemble.py`: the behind-the-scenes video.+- `pipeline/build_scenes_page.mjs`: the gallery page.++## The pipeline++Work in this order. Each step ends with a **gate**: a contact sheet or check you look at before moving on. Look at the+images yourself. A script that ran without errors proves nothing about how the scene looks.++### 1. Brief → scene spec++Write `brief.md`:+- the place, the time of day and the weather;+- 3–5 mood words;+- the room size in metres;+- where the street/door is (put it at y=0 and make the room deep along +Y);+- zones (counter, bench, kitchen, racks);+- 2–3 hero spots the camera will live on;+- the light sources that would really exist there (practicals).++Real places are small: the repair shop is about 3.5 × 6 m. Keep it tight. Density sells realism more than size does.++### 2. Concept images++Run `node generate/fal.mjs image --variant sunburst --out refs/<scene>/concept_wide --prompt "..."`, and again for a+detail shot. GPT Image 2.5 Sunburst beat Flare on legible signage text and natural grade. These set palette, clutter level+and the prop list; you don't match them shot for shot.++**Gate:** the user (or you, if running solo) agrees on the look.++### 3. Prop manifest++List every object in `assets.json`. Sort them into four tiers:+- **furniture** (scripted);+- **hero props** (generated);+- **mid props** (generated);+- **clutter and decals** (generated or direct-modelled).++Decide per object whether to generate it or direct-model it:+- **Direct-model** anything architectural or simple-and-exact: walls, counters, shelving, boxes, cables, paper, glass panes, signage text (real font text objects).+- **Generate** anything with character: appliances, tools, electronics, crockery, food, bins.++Give every generated prop:+- `h`: its real height in metres;+- `dims`: for boxy things, because generators invent depth (fridges, ticket machines, ranges);+- a prompt describing one object, its condition and its materials. **No brand names.**++### 4. References → 3D, both models++For each prop:+1. Generate a reference with the scan template appended. This is the exact text the reference scenes used:+ > No real-world brand names or logos. Product reference photograph for 3D scanning. The entire object fully visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft even diffuse studio lighting, no harsh shadows, no other objects, no hands, realistic used and worn condition, sharp focus, true-to-life materials.+2. Send the same reference to **both** Tripo H3.1 (`--model tripo-h31`) and Meshy 7.1 (`--model meshy`).++Notes:+- Run about 12 jobs concurrently. About 10–20% fail transiently (504, ECONNRESET, Meshy timeouts after about 10 min); re-run the same ids. The script skips GLBs that already exist.+- **Never run two generation passes at once.** Existence is checked at start, so in-flight jobs get double-submitted.+- References often come back with real brands even when told not to. Check every reference and regenerate those that carry one as `<id>_nb`, with a fictional brand.++**Gate:** a reference sheet with no real brands.++### 5. Compare and pick++Render reference | Tripo | Meshy, front, back and clay, under the same light (`render_compare.py`), then sheet them. Pick per prop and+record the choice and a one-line why in `picks.json`.++What the reference scenes found across ~150 props:+- **Meshy 7.1** wins about 70% of the time: small consumer items, sharper printed labels.+- **Tripo H3.1** wins big hard-surface heroes, where real geometry matters (knobs, bezels, dents). It's about 2M tris, so it needs decimating.+- **Both** produce opaque glass, so fix glass by script.+- Meshy speckles flat panels. Look at the clay render, not just the beauty render: it shows which details are real geometry.++**Gate:** the picks sheet. Every prop has a winner or is retired.++### 6. Prep++Turn every pick into `props/<id>.blend`:+- **Front faces −Y.** Tripo's front faces +X, so rotate it −90°; Meshy's already faces −Y. Rotate the mesh data, not the object.+- **Real scale** from `h`/`dims`.+- **Bottom-centre origin.**+- **Decimate** heroes to about 150k tris.+- **Textures** at 2K or less.++Gotchas:+- glTF imports use QUATERNION rotation mode, so `rotation_euler` is silently ignored. Set `rotation_mode = "XYZ"` first.+- glTF images arrive packed. Calling `pack()` again on an unmodified image drops its data and the prop renders magenta. Repack only the images you resized.+- Pass absolute paths to Blender, or relative paths resolve against the wrong directory.++### 7. Shell and layout++Script the room: floor, walls, ceiling, storefront and glass, counters, shelving and fixed furniture. Name objects clearly; shots and+lights reference them by name. Gotchas:+- A smooth-shaded box without a bevel acts as a lens when it's glass.+- `matrix_world` on objects created in the same script is stale until `view_layer.update()`.++**Gate:** a clay sheet from the hero camera positions.++### 8. Dressing, big → small++Place furniture props, then heroes, then mid props, then clutter. Each pass drops props onto surfaces with raycasts.++- **Start drop rays below anything overhead** (shelf above, hood, conduit), or the prop lands on top of it.+- **Vary instances** with `ob.color` multiplied into albedo (Object Info › Color), so repeated meshes don't read as copies.+- **Run the validator after every pass.** Check each prop for:+ - a BVH mesh overlap against fixed furniture (lift the prop 3 mm before testing);+ - prop–prop clashes;+ - floating more than 1 cm. Start the float ray *above* the support's top face, or a thin bench top reports its own thickness.++ Clashing small props get spiral-searched to a clear spot. Validator reports are noisy, so read them: a plinth or pots on a burner can be legitimate.++**Gate:** the validator shows 0 unexplained issues, plus a dressed clay sheet and a textured flat-lit sheet.++### 9. Script fixes, grime and de-branding++- **Screens:** CRT screens become emissive with a scanline glow, and scopes get a graticule and trace. Fix lamp lenses, display glass and bottles to real glass.+- **Grime:** a shared node group with AO-driven dirt, edge wear and per-instance tint. Add decals (stains, flyers, stickers) generated on flat backgrounds, alpha-keyed and stuck on with raycasts.+- **De-branding without regenerating:** render ortho views and mark the brand rectangles. Raycast the rectangles to texels, fill each with the label's ground colour plus grain, and flatten the same texels in the normal map, or embossed text survives.++### 10. Lighting (night)++1. Start with practicals: the light fixtures a real place would have (lamps, pendants, tubes, signage, screens, the fridge, the street spill).+2. Add fills last and keep them weak. A 45 W bounce at exposure 1.0 made the room look like the overhead lights were on. Let the practicals make the contrast.++Gotchas:+- **Lamp shades:** generated shades are closed meshes, so put spots just under the rim, not inside.+- **Light direction:** area lights shine along local −Z.+- **Glass:** hide fills from camera, glossy *and* transmission rays, or they show through glass as bright discs.+- **Emissive meshes:** on dense generated meshes, texture-driven emission turns every triangle into a light. Set `material.cycles.emission_sampling = "NONE"` on those.+- **Exposure:** re-check it after every new practical.++**Gate:** Cycles stills of each hero spot at 32–64 spp.++### 11. Atmosphere and FX++- **Volumetric haze:** cheap and worth it.+- **Steam (Mantaflow):** set `surface_distance` around 1.0 (it is measured in cells), and keep emitters well inside the domain.+- **Bake cache:** use negative cache frames so plumes are developed at frame 1. Clear the cache folder with `rmtree`: `fluid.free_all()` is async in background mode and deletes the new bake.+- **Motion blur:** turn object motion blur **off** on volume domains, or each frame costs about 290 s.+- **Rain:** particles with `rotation_mode = "VEL"` and drop geometry along +X.++### 12. Shots++Write `shots.json` for `camera/shoot.py`. Its README is the contract: moves, rack focus, lens FX and the handheld profiles.++1. **Block:** start with `--framing` (3 stamped stills per shot), then `--preview` (Eevee, stamped).+2. **Design:** mix 2–3 cinematic moves (push-ins, a dolly zoom, a 100–135 mm rack) with 1–2 long **handheld walkthroughs**: `"handheld": {"profile": "walk"}`, a 4–6 key `path` at walking pace. People respond most to the walkthroughs. Keep them as long, uncut takes.+3. **Path check:** check the camera against the scene before rendering, keeping more than 0.45 m from every mesh on every frame.+4. **Focus:**+ - A focus target must never be one the camera passes through, or the distance collapses to 0 and the frame goes soft. Rack to something past it first.+ - Focus `obj` uses the bounding-box centre. For deep objects, put a `pos` on the face you want sharp.++**Gate:** previews reviewed. Each shot's framing, move and focus are approved before any final render.++### 13. Final renders++- **GPU prefs:** `blender -b file.blend` renders Cycles on the **CPU** unless a pre-script sets the GPU compute device (`--python scenes/<scene>/scripts/gpu_prefs.py`, before any other `--python`). Device prefs are user prefs and aren't saved in the .blend. This cost the reference scenes hours.+- **Chunks:** render in 24-frame chunks through `pipeline/gpu_run.sh`. Existing frames are skipped, so runs resume.+- **Settings:** 2.39:1 at 1280–1920 px wide, 48–64 spp with the denoiser. That runs about 4–12 s per frame on a 5070 Ti.+- **Encode:** with NVENC. Check every graded output's duration and frame count. A grade run over a frame folder with a gap silently produces a short clip.++### 14. Post++Grade in ffmpeg, not the Blender compositor. The 5.0 colour-balance and mask nodes misbehave. Keep only Glare and Lens+Distortion in Blender. Grade with `curves` (lift blacks to about 0.03, teal shadows, warm highlights), `hue=s=0.88`, a slight+`rgbashift`, `vignette` and temporal `noise`.++Deliver:+- graded shots;+- a reel (concat with stream copy);+- a compressed copy under 30 MB for chat.++### 15. Behind the scenes (optional)++`breakdown/SPEC.md` + `breakdown/assemble.py` make a one-minute video: concept, layout, props, dressing, materials, lighting, post and final shot.+The scene supplies four "dollhouse" clips, one 120° orbit with the ceiling and near walls hidden:+- clay layout;+- props popping in;+- clay to textures to grime;+- lights coming on in order.++## Running several scenes or agents at once++- **Ownership:** each agent owns its scene's folders and asset ids. Shared tools are read-only; copy one into your scene to change it.+- **One Blender on the GPU at a time:** previews included, everything through `pipeline/gpu_run.sh`. Keep each locked call under about 10 minutes.+- **Waiting on a condition:** wait on the actual condition, not a guess. A "GPU busy" check must not match its own command line, and killing a waiting shell does not kill its child processes. Both of these caused duplicate renders that overwrote finished work. After a pause or crash, list every `blender` process before starting anything.+- **Cross-scene ordering:** marker files only, e.g. `.gpu.<scene>_done`, and create one only when the work is actually done.+- **Other GPU apps:** another GPU-heavy app (Houdini, Unreal) running alongside can slow Cycles 8×. Tell the user rather than closing their apps.++## Budget and time (fal, Oct 2026)++| Item | Cost |+|---|---|+| Reference image | ~$0.25 |+| Tripo H3.1 | ~$0.60 |+| Meshy 7.1 | ~$0.80 |+| Per prop, both models | **~$1.65** |+| ~90-prop scene | ~$150 |++Every call is logged to `generate/spend.jsonl`; `node generate/fal.mjs spend` totals it.++Time on one 16 GB GPU: a scene is roughly a day of agent work, and the final shots are about 1–2 GPU-hours.++## Generalising to a new scene++1. Start from the closer example scene: copy its `assets.json`, `shots.json` and `scripts/` into `scenes/<your-scene>/`+ (name the folder after the place, e.g. `lisbon-tram-depot`), then rewrite `brief.md` and `assets.json` for it.+2. Reuse the shared tools as they are. Reuse an example scene's `scripts/` as a starting point, but the+ shell and the dressing passes are always scene-specific. That's where your judgement goes.+3. Keep `NOTES.md` as you go. Anything that cost you more than 10 minutes gets one line. The next agent reads it first.++## Definition of done++- [ ] Every placed prop is in `picks.json` with a reason, and no real brands are visible in any shot.+- [ ] The validator is clean, or every remaining report is explained.+- [ ] Each hero spot has a final still, and every shot is rendered, graded and has the right duration.+- [ ] There's a reel and a compressed copy; an optional BTS video.+- [ ] `NOTES.md` is updated, and the spend is totalled.diff --git a/breakdown/SPEC.md b/breakdown/SPEC.mdnew file mode 100644index 0000000..e061e87--- /dev/null+++ b/breakdown/SPEC.md@@ -0,0 +1,54 @@+# Behind-the-scenes videos — shared spec++One BTS video per scene (repair, ramen), about 60–75 s, showing how the scene was built:+layout → generated props → placing them → materials and grime → lighting → post → final shot.+The two videos must look like a pair, so both scenes follow this spec exactly.++## Who makes what++- **Scene agents (repair, ramen)** render the four "dollhouse" clips below from their own scene files,+ into `breakdown/<scene>/clips/`. Nobody else knows your stage files and object collections.+- **Main session** makes the concept, asset-generation, post-wipe and final-shot segments,+ the captions, and assembles the video (`breakdown/assemble.py`). Don't make captions or titles.++## Output format for the dollhouse clips++- 1920×1080, 24 fps, PNG frames in `breakdown/<scene>/clips/<clip>/####.png` plus an mp4 of the same+ (h264_nvenc, any decent bitrate) at `breakdown/<scene>/clips/<clip>.mp4`. No text, no grade, no letterbox.+- Leave the bottom 140 px free of anything important (captions go there).++## The dollhouse camera (same for all four clips)++One continuous orbit split into four clips, so they cut together as one move:++- A cutaway view of the whole interior from a high three-quarter angle (about 35–45° down), looking at the+ middle of the room. Hide the ceiling and the one or two walls nearest the camera at every angle, so the+ interior reads like a dollhouse. Hide anything that blocks the view for the whole orbit (exterior shell,+ awning, street) unless it is part of what that clip shows.+- Lens about 28–35 mm, f/8 or no DOF. Fit the whole interior with a little margin.+- Total orbit: 120° around the room's vertical axis, at constant angular speed, ease in on clip A only and+ ease out on clip D only. Clip A covers 0–30°, B 30–60°, C 60–90°, D 90–120°.+- Put the start angle where the room reads best (counter/bench in view all the way).++## The four clips++| Clip | Frames | What it shows |+|---|---|---|+| `a_layout` | 144 (6 s) | The empty shell as the layout: walls, floor, counter/bench blocks, shelves. Clay look: one flat light-grey material on everything (Workbench or Eevee with a soft studio light and AO). Optionally the shell pieces rise into place in the first 2 s. |+| `b_props` | 240 (10 s) | Same clay look. The generated props appear one at a time in a sensible order (big furniture and shelves first, then big props, then small clutter), each scaling up from 0 with a small overshoot over ~6 frames. All props in place by frame ~200; hold after that. |+| `c_materials` | 144 (6 s) | Switch from clay to the real textured materials with neutral flat lighting (bright, even, no night mood): a wipe or dissolve over the first ~2 s. Then fade in the grime and decals (stains, wear, posters, signage) over the next ~2 s. |+| `d_lighting` | 240 (10 s) | Start from the textured scene in darkness (world near black, every light off). Turn the lights on one after another over ~7 s, with a short ramp each: key practicals first (lamp/pendants), then signage/neon, window/street, fills and bounce last. Then the volumetrics (steam, haze, rain) fade in. End on the full night look. |++Render engines: A–C in Eevee (fast). D in Cycles with low samples and the denoiser; it is the money shot,+so keep it clean, but under ~10 GPU-minutes.++## GPU rules (one 16 GB card shared by both scenes)++- Every Blender run, previews included, goes through `pipeline/gpu_run.sh`. Never two Blenders on the GPU.+- Don't hold the GPU between clips; release it so the other scene can interleave.+- Don't save over any existing .blend; build the BTS setup in a script on a copy (`breakdown/<scene>/bts.blend`).++## When done++Check a contact sheet of each clip yourself, then report: clip paths, frame counts, GPU minutes, and anything+that looks off. Don't commit or publish.diff --git a/breakdown/assemble.py b/breakdown/assemble.pynew file mode 100644index 0000000..a2d8305--- /dev/null+++ b/breakdown/assemble.py@@ -0,0 +1,328 @@+"""Assemble a behind-the-scenes video for one scene (see breakdown/SPEC.md).++ uv run --with pillow python -I breakdown/assemble.py repair|ramen [--only seg1,seg2] [--draft]++Segments (1920x1080, 24 fps), each written to breakdown/<scene>/seg/<nn>_<name>.mp4, then joined with short crossfades:+ title, concept, a_layout, assets, b_props, c_materials, d_lighting, post, final, end+The dollhouse clips (a_..d_) come from the scene agents in breakdown/<scene>/clips/; a missing clip becomes a labelled+placeholder so the cut can be reviewed before every clip exists. Captions are drawn here with Pillow, because the+ffmpeg builds without libfreetype have no drawtext.+"""++import json+import os+import random+import subprocess+import sys+from pathlib import Path++from PIL import Image, ImageDraw, ImageFilter, ImageFont++ROOT = Path(__file__).resolve().parent.parent+FF = os.environ.get("FFMPEG", "ffmpeg")+W, H, FPS = 1920, 1080, 24+XF = 0.5 # crossfade between segments, seconds+FONTS = "C:/Windows/Fonts/"+BG = (14, 13, 12)+INK = (236, 230, 220)+DIM = (178, 170, 158)++# Scene id (the prefix on its asset ids) -> its folder under scenes/ and breakdown/.+FOLDER = {"repair": "tokyo-electronics-repair", "ramen": "tokyo-ramen-shop"}++SCENES = {+ "repair": dict(+ title="Electronics repair, late night",+ kicker="Night Shops · Scene 01",+ concept="refs/tokyo-electronics-repair/concept_wide_sunburst_0.png",+ concept2="refs/tokyo-electronics-repair/concept_detail_sunburst_0.png",+ post_raw="scenes/tokyo-electronics-repair/out/shots/h1_back_to_bench/h1_back_to_bench.mp4",+ post_graded="scenes/tokyo-electronics-repair/out/shots/h1_back_to_bench_graded.mp4",+ finals=["scenes/tokyo-electronics-repair/out/shots/h1_back_to_bench_graded.mp4", "scenes/tokyo-electronics-repair/out/shots/s3_bench_rack_100_graded.mp4"],+ res="1920×804",+ accent=(122, 200, 168),+ ),+ "ramen": dict(+ title="Ramen counter, last orders",+ kicker="Night Shops · Scene 02",+ concept="refs/tokyo-ramen-shop/concept_wide_sunburst_0.png",+ concept2="refs/tokyo-ramen-shop/concept_detail_sunburst_0.png",+ post_raw="scenes/tokyo-ramen-shop/out/shots/h1_door_to_counter/h1_door_to_counter.mp4",+ post_graded="scenes/tokyo-ramen-shop/out/shots/h1_door_to_counter/h1_door_to_counter_graded.mp4",+ finals=["scenes/tokyo-ramen-shop/out/shots/h1_door_to_counter/h1_door_to_counter_graded.mp4"],+ res="1280×536",+ accent=(232, 150, 92),+ ),+}+++def ff(*args):+ subprocess.run([FF, "-v", "error", "-y", *map(str, args)], check=True)+++def duration(path):+ out = subprocess.run([FF, "-i", str(path)], capture_output=True, text=True).stderr+ h, m, s = out.split("Duration: ")[1].split(",")[0].split(":")+ return int(h) * 3600 + int(m) * 60 + float(s)+++def font(name, size):+ return ImageFont.truetype(FONTS + name, size)+++def caption_png(path, step, head, sub, accent):+ """Bottom-band caption: step number, heading, one line of detail, over a soft dark gradient."""+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ grad = Image.new("L", (1, 260))+ for y in range(260):+ grad.putpixel((0, y), int(200 * (y / 259) ** 1.6))+ img.paste(Image.new("RGBA", (W, 260), (8, 8, 8, 255)), (0, H - 260), grad.resize((W, 260)))+ d = ImageDraw.Draw(img)+ x, y = 96, H - 128+ d.text((x, y), step, font=font("bahnschrift.ttf", 30), fill=accent + (255,))+ sx = x + d.textlength(step, font=font("bahnschrift.ttf", 30)) + 22+ d.text((sx, y - 6), head, font=font("segoeuib.ttf", 36), fill=INK + (255,))+ d.text((sx, y + 44), sub, font=font("segoeui.ttf", 27), fill=DIM + (255,))+ img.save(path)+++def with_caption(src_args, vf, dur, cap, out):+ """Encode one segment: src (any ffmpeg input args) through vf to 1920x1080, caption fading in and out."""+ fade = f"fade=t=in:st=0.35:d=0.5:alpha=1,fade=t=out:st={max(dur - 0.9, 0.5):.2f}:d=0.5:alpha=1"+ ff(*src_args, "-loop", "1", "-t", f"{dur:.3f}", "-i", cap,+ "-filter_complex", f"[0:v]{vf},fps={FPS},setsar=1,format=yuv420p,trim=duration={dur:.3f}[v];[1:v]format=rgba,{fade}[c];[v][c]overlay=0:0:format=auto,format=yuv420p",+ "-an", "-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "19", "-b:v", "0", out)+++LETTERBOX = f"scale={W}:-2:flags=lanczos,pad={W}:{H}:0:(oh-ih)/2:color=black"+++def title_card(cfg, out, end=False):+ still = ROOT / cfg["finals"][0]+ frame = out.with_suffix(".bg.png")+ ff("-ss", "6" if not end else "3", "-i", still, "-frames:v", "1", "-vf", f"scale={W}:-2", frame)+ bg = Image.open(frame).convert("RGB")+ bg = bg.resize((W, int(bg.height * W / bg.width)))+ canvas = Image.new("RGB", (W, H), BG)+ canvas.paste(bg.filter(ImageFilter.GaussianBlur(14)).point(lambda v: int(v * 0.42)), (0, (H - bg.height) // 2))+ d = ImageDraw.Draw(canvas)+ if end:+ lines = [("segoeuisl.ttf", 30, DIM, "Layout, props, lighting and post all scripted in Blender 5.0"),+ ("segoeuisl.ttf", 30, DIM, "Props: GPT Image 2.5 references → Tripo H3.1 / Meshy 7.1 on fal"),+ ("segoeuib.ttf", 44, INK, cfg["title"])]+ else:+ lines = [("bahnschrift.ttf", 30, cfg["accent"], cfg["kicker"].upper()),+ ("segoeuib.ttf", 76, INK, cfg["title"]),+ ("segoeuisl.ttf", 34, DIM, "How the scene was built")]+ total = sum(s + 26 for _, s, _, _ in lines)+ y = (H - total) // 2+ for f, s, c, t in lines:+ fnt = font(f, s)+ d.text(((W - d.textlength(t, font=fnt)) / 2, y), t, font=fnt, fill=c)+ y += s + 26+ canvas.save(frame)+ dur = 3.0+ ff("-loop", "1", "-t", dur, "-i", frame, "-vf", f"fps={FPS},format=yuv420p", "-c:v", "h264_nvenc", "-preset", "p6", "-cq", "18", out)+ return dur+++def concept(cfg, out, cap):+ """Two reference images with a slow push each (zoompan), the starting point for the scene."""+ parts = []+ for i, key in enumerate(["concept", "concept2"]):+ p = out.with_name(f"{out.stem}_{i}.mp4")+ frames = 72+ ff("-loop", "1", "-i", ROOT / cfg[key], "-vf",+ f"scale=3840:-2,zoompan=z='1.0+0.06*on/{frames}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d={frames}:s={W}x{H}:fps={FPS},format=yuv420p",+ "-frames:v", frames, "-c:v", "h264_nvenc", "-preset", "p6", "-cq", "18", p)+ parts.append(p)+ lst = out.with_suffix(".txt")+ lst.write_text("".join(f"file '{p.as_posix()}'\n" for p in parts))+ joined = out.with_name(out.stem + "_j.mp4")+ ff("-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", joined)+ dur = duration(joined)+ with_caption(["-i", joined], "null", dur, cap, out)+ return dur+++def prop_list(scene):+ picks = json.loads((ROOT / f"scenes/{FOLDER[scene]}/picks.json").read_text(encoding="utf-8"))+ refs = [p for p in (ROOT / "refs").rglob("*_0.png")]+ keys = [k for k in picks if not k.startswith("_")]+ rows = []+ for k in keys:+ v = picks[k]+ if not isinstance(v, dict) or v.get("model") in (None, "none") or v.get("retired") or f"{k}_nb" in keys:+ continue+ ids = [k, f"{scene}_{k}"]+ ref = next((r for r in refs if any(r.name == f"{i}_0.png" for i in ids)), None)+ model = v["model"]+ rend = {}+ for view in ("clay", "beauty"):+ for d in (f"scenes/{FOLDER[scene]}/compare/{model}", f"out/compare/{model}"):+ f = next((ROOT / d / f"{i}_{view}.png" for i in ids if (ROOT / d / f"{i}_{view}.png").exists()), None)+ if f:+ rend[view] = f+ break+ if ref and len(rend) == 2:+ rows.append(dict(key=k, model=model, ref=ref, **rend))+ counts = {}+ for k in keys:+ v = picks[k]+ if isinstance(v, dict) and v.get("model") not in (None, "none") and not v.get("retired") and f"{k}_nb" not in keys:+ counts[v["model"]] = counts.get(v["model"], 0) + 1+ return rows, counts+++def assets(cfg, scene, out, cap):+ """A wall of props: each tile goes image reference → untextured mesh → textured mesh, staggered in a wave."""+ rows, counts = prop_list(scene)+ random.seed(7)+ cols, nrows = 8, 4+ pick = rows[: cols * nrows]+ tile = 184+ gap = 10+ gx = (W - cols * tile - (cols - 1) * gap) // 2+ gy = 140+ cache = {}++ def load(p):+ if p not in cache:+ im = Image.open(p).convert("RGB")+ im.thumbnail((tile, tile))+ t = Image.new("RGB", (tile, tile), (29, 27, 25))+ t.paste(im, ((tile - im.width) // 2, (tile - im.height) // 2))+ cache[p] = t+ return cache[p]++ frames_dir = out.with_suffix("")+ frames_dir.mkdir(parents=True, exist_ok=True)+ n = int(8.5 * FPS)+ hdr = font("segoeuisl.ttf", 30)+ tag = font("bahnschrift.ttf", 20)+ total = sum(counts.values())+ header = f"{total} props generated · " + " · ".join(f"{'Meshy 7.1' if m == 'meshy' else 'Tripo H3.1'}: {c}" for m, c in sorted(counts.items()))+ for f in range(n):+ canvas = Image.new("RGB", (W, H), BG)+ d = ImageDraw.Draw(canvas)+ d.text(((W - d.textlength(header, font=hdr)) / 2, 76), header, font=hdr, fill=DIM)+ for i, r in enumerate(pick):+ cx, cy = i % cols, i // cols+ delay = (cx + cy) * 5 # diagonal wave, frames+ t = f - delay+ # 0..48 reference, 48..60 → clay, 60..96 clay, 96..108 → textured, then textured+ stages = [(0, load(r["ref"])), (60, load(r["clay"])), (108, load(r["beauty"]))]+ im = stages[0][1]+ for start, s_im in stages[1:]:+ a = min(max((t - (start - 12)) / 12, 0), 1)+ if a > 0:+ im = Image.blend(im, s_im, a)+ x, y = gx + cx * (tile + gap), gy + cy * (tile + gap)+ canvas.paste(im, (x, y))+ label = "REF" if t < 54 else ("MESH" if t < 102 else ("TRIPO" if r["model"] != "meshy" else "MESHY"))+ d.text((x + 8, y + tile - 24), label, font=tag, fill=cfg["accent"] if label in ("TRIPO", "MESHY") else DIM)+ canvas.save(frames_dir / f"{f:04d}.png")+ raw = out.with_name(out.stem + "_raw.mp4")+ ff("-framerate", FPS, "-i", frames_dir / "%04d.png", "-c:v", "h264_nvenc", "-preset", "p6", "-cq", "18", "-pix_fmt", "yuv420p", raw)+ dur = n / FPS+ with_caption(["-i", raw], "null", dur, cap, out)+ return dur+++def clip(scene, name, out, cap, fallback_s):+ src = ROOT / f"breakdown/{FOLDER[scene]}/clips/{name}.mp4"+ if src.exists():+ dur = duration(src)+ with_caption(["-i", src], f"scale={W}:{H}", dur, cap, out)+ else:+ dur = fallback_s+ with_caption(["-f", "lavfi", "-i", f"color=c=0x222018:s={W}x{H}:d={dur}"], "null", dur, cap, out)+ return dur+++def post(cfg, out, cap):+ """Raw render vs graded: a divider sweeps across, raw on the left of it, final on the right."""+ raw, graded = ROOT / cfg["post_raw"], ROOT / cfg["post_graded"]+ dur = 6.0+ ss = 4.0+ sweep = f"(0.85-0.7*(t/{dur}))" # divider moves from 85% to 15% of the width+ tmp = out.with_name(out.stem + "_raw.mp4")+ ff("-ss", ss, "-t", dur, "-i", raw, "-ss", ss, "-t", dur, "-i", graded, "-filter_complex",+ f"[0:v]{LETTERBOX},setsar=1,format=yuv444p[a];[1:v]{LETTERBOX},setsar=1,format=yuv444p[b];"+ f"[a][b]blend=all_expr='if(lt(X,W*{sweep.replace('t/', 'T/')}),A,B)'[o];"+ f"color=c=white:s=3x804:d={dur}[ln];[o][ln]overlay=x='W*{sweep}-1':y=138:eval=frame,format=yuv420p",+ "-c:v", "h264_nvenc", "-preset", "p6", "-cq", "18", tmp)+ with_caption(["-i", tmp], "null", dur, cap, out)+ return dur+++def final(cfg, out, cap):+ parts = [ROOT / p for p in cfg["finals"]]+ lst = out.with_suffix(".txt")+ lst.write_text("".join(f"file '{p.as_posix()}'\n" for p in parts))+ joined = out.with_name(out.stem + "_j.mp4")+ ff("-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", joined)+ dur = duration(joined)+ with_caption(["-i", joined], LETTERBOX, dur, cap, out)+ return dur+++def main():+ scene = sys.argv[1]+ only = None+ if "--only" in sys.argv:+ only = set(sys.argv[sys.argv.index("--only") + 1].split(","))+ cfg = SCENES[scene]+ seg = ROOT / f"breakdown/{FOLDER[scene]}/seg"+ seg.mkdir(parents=True, exist_ok=True)+ rows, counts = prop_list(scene)+ total = sum(counts.values())+ ac = cfg["accent"]+ plan = [+ ("title", lambda o, c: title_card(cfg, o), None),+ ("concept", lambda o, c: concept(cfg, o, c), ("01", "Concept", "GPT Image 2.5 night references set the mood, palette and the props to make")),+ ("a_layout", lambda o, c: clip(scene, "a_layout", o, c, 6), ("02", "Layout", "The room is blocked out in Blender from a Python script: walls, counter, shelving, window")),+ ("assets", lambda o, c: assets(cfg, scene, o, c), ("03", "Props", f"Each prop: an image reference, then a 3D mesh from Tripo H3.1 or Meshy 7.1, the better one picked by eye")),+ ("b_props", lambda o, c: clip(scene, "b_props", o, c, 10), ("04", "Set dressing", f"{total} generated props placed by script, then checked for collisions and floating")),+ ("c_materials", lambda o, c: clip(scene, "c_materials", o, c, 6), ("05", "Materials and grime", "The generated textures, then wear, stains, decals and signage layered on top")),+ ("d_lighting", lambda o, c: clip(scene, "d_lighting", o, c, 10), ("06", "Lighting", "Practical lamps first, then signage and the street, fills last, then haze and steam")),+ ("post", lambda o, c: post(cfg, o, c), ("07", "Post", "Left: the raw Cycles render. Right: lens distortion, dispersion, glare, grade and grain")),+ ("final", lambda o, c: final(cfg, o, c), ("08", "Final", f"Handheld walk camera, Cycles at {cfg['res']}")),+ ("end", lambda o, c: title_card(cfg, o, end=True), None),+ ]+ durs = {}+ dur_file = seg / "durations.json"+ if dur_file.exists():+ durs = json.loads(dur_file.read_text())+ for i, (name, fn, capt) in enumerate(plan):+ out = seg / f"{i:02d}_{name}.mp4"+ if only and name not in only and out.exists():+ durs.setdefault(name, duration(out))+ continue+ cap = seg / f"{i:02d}_{name}_cap.png"+ if capt:+ caption_png(cap, *capt, ac)+ print(f"segment {name}", flush=True)+ durs[name] = fn(out, cap)+ dur_file.write_text(json.dumps(durs, indent=1))++ # Join with crossfades.+ names = [n for n, _, _ in plan]+ inputs, chain, offset = [], [], 0.0+ for i, n in enumerate(names):+ inputs += ["-i", seg / f"{i:02d}_{n}.mp4"]+ prev = "[0:v]"+ offset = durs[names[0]] - XF+ for i in range(1, len(names)):+ lbl = f"[x{i}]"+ chain.append(f"{prev}[{i}:v]xfade=transition=fade:duration={XF}:offset={offset:.3f}{lbl}")+ prev = lbl+ offset += durs[names[i]] - XF+ out = ROOT / f"breakdown/{FOLDER[scene]}/{scene}_bts.mp4"+ ff(*inputs, "-filter_complex", ";".join(chain), "-map", prev, "-c:v", "h264_nvenc", "-preset", "p7", "-tune", "hq",+ "-rc", "vbr", "-b:v", "12M", "-maxrate", "18M", "-bufsize", "24M", "-pix_fmt", "yuv420p", "-movflags", "+faststart", out)+ print(f"wrote {out} ({duration(out):.1f} s)")+++if __name__ == "__main__":+ main()diff --git a/breakdown/promo.py b/breakdown/promo.pynew file mode 100644index 0000000..ced67aa--- /dev/null+++ b/breakdown/promo.py@@ -0,0 +1,141 @@+"""One combined video for posting: both scenes' hero shots with each scene's breakdown cut in between.++ uv run --with pillow python -I breakdown/promo.py++Order: repair h1 (with a name tag) → repair breakdown → repair h2 → s3 bokeh close-up →+ ramen h1 (name tag) → ramen breakdown → ramen h2 → end card.+The breakdown reuses the captioned BTS segments from breakdown/<scene>/seg/ (run assemble.py first), sped up or trimmed so+each scene's breakdown runs about 20 s. Writes breakdown/night_shops_promo.mp4 (posting quality) and a _small copy (< 30 MB).+"""++import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from assemble import BG, DIM, FOLDER, FPS, H, INK, LETTERBOX, ROOT, SCENES, W, XF, duration, ff, font # noqa: E402+from PIL import Image, ImageDraw # noqa: E402++OUT = ROOT / "breakdown/promo"+ENC = ["-c:v", "h264_nvenc", "-preset", "p6", "-cq", "18", "-pix_fmt", "yuv420p", "-an"]++# (segment, mode, target seconds): "speed" plays the whole segment faster, "trim" keeps its start.+BREAKDOWN = [+ ("01_concept", "trim", 2.6),+ ("02_a_layout", "speed", 2.6),+ ("03_assets", "speed", 3.6),+ ("04_b_props", "speed", 3.6),+ ("05_c_materials", "speed", 3.0),+ ("06_d_lighting", "speed", 4.4),+ ("07_post", "trim", 3.2),+]++HEROES = {+ "repair": {+ "open": "scenes/tokyo-electronics-repair/out/shots/h1_back_to_bench_graded.mp4",+ "close": ["scenes/tokyo-electronics-repair/out/shots/h2_shop_walkaround_graded.mp4", "scenes/tokyo-electronics-repair/out/shots/s3_bench_rack_100_graded.mp4"],+ },+ "ramen": {+ "open": "scenes/tokyo-ramen-shop/out/shots/h1_door_to_counter/h1_door_to_counter_graded.mp4",+ "close": ["scenes/tokyo-ramen-shop/out/shots/h2_counter_walkaround/h2_counter_walkaround_graded.mp4"],+ },+}+++def tag_png(path, kicker, title, accent):+ """Lower-left name tag in the bottom letterbox bar."""+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ d = ImageDraw.Draw(img)+ d.text((96, H - 118), kicker.upper(), font=font("bahnschrift.ttf", 24), fill=accent + (255,))+ d.text((96, H - 88), title, font=font("segoeuib.ttf", 40), fill=INK + (255,))+ img.save(path)+++def hero(src, out, tag=None):+ if tag:+ fade = "fade=t=in:st=0.6:d=0.6:alpha=1,fade=t=out:st=4.2:d=0.6:alpha=1"+ ff("-i", ROOT / src, "-loop", "1", "-i", tag, "-filter_complex",+ f"[0:v]{LETTERBOX},fps={FPS},setsar=1,format=yuv420p[v];[1:v]format=rgba,{fade}[c];[v][c]overlay=0:0:shortest=1,format=yuv420p",+ *ENC, out)+ else:+ ff("-i", ROOT / src, "-vf", f"{LETTERBOX},fps={FPS},setsar=1,format=yuv420p", *ENC, out)+ return duration(out)+++def piece(seg, mode, target, out):+ src_dur = duration(seg)+ if mode == "speed":+ vf = f"setpts=PTS*{target / src_dur:.5f},fps={FPS}"+ ff("-i", seg, "-vf", f"{vf},format=yuv420p", "-t", f"{target:.3f}", *ENC, out)+ else:+ ff("-ss", "0.2", "-t", f"{target:.3f}", "-i", seg, "-vf", f"fps={FPS},format=yuv420p", *ENC, out)+ return duration(out)+++def end_card(out):+ canvas = Image.new("RGB", (W, H), BG)+ d = ImageDraw.Draw(canvas)+ lines = [("segoeuib.ttf", 72, INK, "Night Shops"),+ ("segoeuisl.ttf", 34, DIM, "Two scenes · 160 generated props · no hand modelling"),+ ("segoeuisl.ttf", 30, DIM, "GPT Image 2.5 → Tripo H3.1 / Meshy 7.1 on fal → Blender, scripted by AI agents")]+ y = (H - sum(s + 30 for _, s, _, _ in lines)) // 2+ for f, s, c, t in lines:+ fnt = font(f, s)+ d.text(((W - d.textlength(t, font=fnt)) / 2, y), t, font=fnt, fill=c)+ y += s + 30+ png = out.with_suffix(".png")+ canvas.save(png)+ ff("-loop", "1", "-t", "3.5", "-i", png, "-vf", f"fps={FPS},format=yuv420p", *ENC, out)+ return 3.5+++def main():+ OUT.mkdir(parents=True, exist_ok=True)+ parts = [] # (path, seconds, crossfade into this part?)+ for scene in ("repair", "ramen"):+ cfg, h = SCENES[scene], HEROES[scene]+ tag = OUT / f"{scene}_tag.png"+ tag_png(tag, cfg["kicker"], cfg["title"], cfg["accent"])+ p = OUT / f"{scene}_0_open.mp4"+ parts.append((p, hero(h["open"], p, tag), True))+ for seg, mode, target in BREAKDOWN:+ p = OUT / f"{scene}_1_{seg}.mp4"+ parts.append((p, piece(ROOT / f"breakdown/{FOLDER[scene]}/seg/{seg}.mp4", mode, target, p), True))+ # Back-to-back closing heroes hard-cut (like the handheld reel): join them first with a stream copy,+ # since xfade won't chain after a filter concat.+ closes = []+ for i, src in enumerate(h["close"]):+ p = OUT / f"{scene}_2_close{i}.mp4"+ hero(src, p)+ closes.append(p)+ p = OUT / f"{scene}_2_close.mp4"+ lst = OUT / f"{scene}_close.txt"+ lst.write_text("".join(f"file '{c.as_posix()}'\n" for c in closes))+ ff("-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", p)+ parts.append((p, duration(p), True))+ p = OUT / "end.mp4"+ parts.append((p, end_card(p), True))++ inputs, chain = [], []+ for p, _, _ in parts:+ inputs += ["-i", p]+ prev, offset = "[0:v]", parts[0][1]+ for i in range(1, len(parts)):+ lbl = f"[x{i}]"+ chain.append(f"{prev}[{i}:v]xfade=transition=fade:duration={XF}:offset={offset - XF:.3f}{lbl}")+ offset += parts[i][1] - XF+ prev = lbl+ final = ROOT / "breakdown/night_shops_promo.mp4"+ ff(*inputs, "-filter_complex", ";".join(chain), "-map", prev, "-c:v", "h264_nvenc", "-preset", "p7", "-tune", "hq",+ "-rc", "vbr", "-b:v", "14M", "-maxrate", "20M", "-bufsize", "28M", "-pix_fmt", "yuv420p", "-movflags", "+faststart", final)+ dur = duration(final)+ small = final.with_name("night_shops_promo_small.mp4")+ kbps = int(28 * 8 * 1000 / dur) # ~28 MB+ ff("-i", final, "-c:v", "h264_nvenc", "-preset", "p7", "-tune", "hq", "-multipass", "fullres", "-rc", "vbr",+ "-b:v", f"{kbps}k", "-maxrate", f"{int(kbps * 1.4)}k", "-bufsize", f"{kbps * 2}k", "-pix_fmt", "yuv420p", "-movflags", "+faststart", small)+ (OUT / "parts.json").write_text(json.dumps([[str(p.name), round(s, 2)] for p, s, _ in parts], indent=1))+ print(f"wrote {final} ({dur:.1f} s) and {small.name}")+++if __name__ == "__main__":+ main()diff --git a/camera/README.md b/camera/README.mdnew file mode 100644index 0000000..7f9904c--- /dev/null+++ b/camera/README.md@@ -0,0 +1,214 @@+# camrig: cinematic camera rig and shot renderer++`camera/shoot.py` adds one camera rig per shot to a scene .blend, then renders:+- preview blocking passes,+- framing checks,+- lens charts,+- final Cycles frames and mp4s.++Shots are described in a JSON file. Each scene keeps its own at `scenes/<scene>/shots.json`. Copies of the examples live in `examples/`.++The contract is stable. New fields may be added, but existing ones will not change meaning.++## CLI++```bash+. pipeline/env.sh # sets $B (Blender) and $ROOT_ABS (absolute repo root)+# always through the shared GPU queue+pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen.blend --python camera/shoot.py -- \+ --shots $ROOT_ABS/scenes/tokyo-ramen-shop/shots.json \+ --out $ROOT_ABS/scenes/tokyo-ramen-shop/out/shots \+ [--only a,b] [--preview | --framing | --lenschart NAME] [--frames 1-24] [--still 12] [--save rigged.blend] [--no-encode] \n [--engine eevee|cycles|workbench] [--step N]+```++| Mode | What it does | Output (`<out>/<shot>/…`) |+|---|---|---|+| *(default)* final | Renders with Cycles. Scene settings stay unless a shot field overrides them. Frames that already exist are skipped, so a run can be resumed. Encodes `<shot>.mp4` and a contact sheet once every frame exists. | `frames/####.png`, `<shot>.mp4`, `contact.png` |+| `--preview` | Renders with Eevee at 50% resolution, every frame (`--step N` renders every Nth), 16 TAA samples, no motion blur. The stamp is burned in per frame: shot name, frame, lens mm, f-stop, focus distance. `--engine cycles` gives a 16 spp denoised preview with the real lighting. | `preview/####.png`, `preview.mp4` |+| `--framing` | Renders a stamped low-res still of each shot at t = 0, 0.5 and 1 with Eevee, plus one 3×3 sheet for all shots. | `framing/t0.png`, `framing/t5.png`, `framing/t10.png`, `<out>/_framing.png` |+| `--lenschart NAME` | Renders shot NAME's t=0 position and aim at 18/24/35/50/85/135 mm with Eevee. | `lenschart/<mm>.png`, `<out>/<NAME>_lenschart.png` |+| `--frames a-b` | Renders only frames a..b of the shot (1-based). Use it to keep each `gpu_run` call short (aim for under about 10 minutes). | |+| `--still N` | Renders a single final-quality frame N. | `still_####.png` |+| `--save path.blend` | Writes the rigged scene so a human can open and tweak it in the UI. It never overwrites the input file. | |+| `--no-encode` | Skips mp4 and contact-sheet encoding. | |++The script never saves the input .blend. Every shot's rig is built fresh on each run.++## shots.json++```jsonc+{+ "defaults": { "fps": 24, "res": [1920, 1080], "aspect": "16:9", "samples": 256,+ "shutter": 180, "sensor": "s35", "fstop": 2.8, "ease": "inout", "handheld": 0.0 },+ "shots": [+ {+ "name": "counter_push", // [a-z0-9_], used for folders and the rig name+ "frames": 120, // length in frames+ "fps": 24,+ "res": [1920, 1080],+ "aspect": "2.39", // "16:9" | "1.85" | "2.39" — output is cropped to the aspect (res height recomputed from width)+ "samples": 256, // Cycles samples for final+ "shutter": 180, // motion blur shutter in degrees (0 = off)+ "sensor": "s35", // "s35" (24.89 mm) | "ff" (36 mm) | number in mm (sensor width)+ "move": "push_in", // see Moves+ "ease": "inout", // linear | in | out | inout — position/aim: one ease over the whole shot (passes through middle keys without stopping); lens/roll/focus/f-stop keys: eased per segment (hold + pull)+ "keys": [+ { "t": 0.0, "pos": [x,y,z], "aim": [x,y,z], "lens": 35, "roll": 0 },+ { "t": 1.0, "pos": [x,y,z], "aim_obj": "ramen_bowl_unfinished", "lens": 35 }+ ],+ "focus": { "mode": "rack", "keys": [ { "t": 0.0, "obj": "water_glass" }, { "t": 0.6, "pos": [x,y,z] } ] },+ "fstop": 2.0, // or "fstop_keys": [{ "t":0, "v":4 }, { "t":1, "v":1.4 }]+ "blades": 0, "ratio": 1.0, // aperture blades (0 = round) and anamorphic ratio (>1 = oval bokeh)+ "handheld": 0.35, // 0..1, shake layered on top of the move+ "breathing": 0.5, // 0..1, slow drift (default = handheld)+ "lens_fx": { "distortion": 0.01, "dispersion": 0.01, "glare": "fog" } // optional, see notes+ }+ ]+}+```++Units are metres and Blender world axes (Z up). Wherever the contract takes a position, an object name works too.+- `aim_obj` and `focus.obj` resolve to the **centre of that object's world bounding box**.+- `obj` matches the object name exactly. If nothing matches exactly, it uses the first object whose name starts with the given string, then the first case-insensitive substring match. Bounds include all mesh children, so a GLB import root works.+- `"aim_obj": "name", "aim_offset": [dx,dy,dz]` nudges the aim point from that centre. Keys also take `pos_obj` + `pos_offset`. A key that omits `pos` or `aim` holds the previous one.+- Optional `"exposure": EV` offsets the scene exposure for the shot. The scenes' old keyed exposure drift is removed and frozen at its frame-1 value, so it can't leak into new shots.++### Moves++All moves interpolate between `keys`; `move` sets defaults and validation:++| move | keys needed | notes |+|---|---|---|+| `static` | 1 | Locked off. Add `handheld` for life. |+| `dolly`, `truck`, `pedestal`, `push_in`, `crane` | 2 or more | Each key has a position and an aim. The names describe intent; they all interpolate the same way. |+| `pan`, `tilt` | 2 or more | Keep `pos` the same and change `aim`. |+| `orbit` | none (or 1 for lens and roll) | `"orbit": {"center":[x,y,z] or "center_obj":"name", "radius":1.2, "start_deg":-30, "end_deg":30, "height":1.3}`. Aims at the centre. Angles are measured from +X, counter-clockwise from above. |+| `dolly_zoom` | 2 (start and end `pos`; aim and lens at t=0) | Lens is solved per frame to hold the subject size: `lens(t) = lens0 · dist(t) / dist0`. Distance is measured to `"subject"` (pos or obj, defaults to the aim). |+| `path` | 3 or more | Smooth path through every key: Catmull-Rom on position, eased in time. |++### Focus++- `{"mode":"track","obj":"name"}`: the focus empty is parented to and follows that object's bounds centre.+- `{"mode":"point","pos":[x,y,z]}`+- `{"mode":"rack","keys":[{"t":0,"obj":"a"},{"t":0.6,"pos":[...]}]}`: the focus empty moves between points with the same ease. The pull happens between successive keys, so to hold and then pull, repeat a key: `t 0 → a`, `t 0.4 → a`, `t 0.6 → b`.+- `{"mode":"none"}`: depth of field off.+- `fstop` (or `fstop_keys`), `blades` and `ratio` are optional.++### Handheld++- **Shake (`handheld`):** two Noise layers per channel on `CR_<shot>_shake` (between aim and camera, so it moves in camera space).+ - Hand bob: period about 11 frames, 4 mm and 0.27° × intensity.+ - Fine jitter: period about 3.5 frames, 1.2 mm and 0.07° × intensity.+ - Roll runs at about 60% of pan and tilt.+- **Breathing:** body sway with a period of about 2 s, 14 mm and 0.4° × breathing.+- **Lens length:** the shift scales with focal length the way real handheld does. At 85 mm, handheld 0.4 already reads clearly; at 24 mm, 0.3–0.5 feels like a steady operator.++### Handheld walk profile (opt-in)++`"handheld": {"profile": "walk", "amount": 1.0}` replaces the noise shake with a baked operator-walking motion. Shots that keep a number for `handheld` are unchanged.++- **Footsteps:** a bob of about 1 cm, once per step at 1.8 Hz (`step_hz`), and a 0.3° roll that alternates left and right with each step.+ Both scale with the speed of the move's path: full at or above `walk_speed` (default 0.55 m/s), zero when standing.+ Walking intensity is smoothed over about 0.4 s, so steps fade in and out with the move's ease.+- **Body sway:** 0.17–0.57 Hz. Position moves ±2–3 cm and pan/tilt ±0.7°. When the operator stands still this drops to about 45%.+- **Aim lag:** the aim follows a spring (`aim_lag_hz` 0.9, `aim_damping` 0.62). Pans trail behind the keyed aim and overshoot slightly when they settle.+ Focus that follows the aim (the default focus mode) uses the lagged aim as well.+- **Reframes:** `corrections` (default 2) small reframes. Each drifts off by 0.6° and is quickly corrected back.+- **Frequency ceiling:** nothing is above about 1.9 Hz, so there is no jitter. Motion blur sees smooth curves.+- **Baking:** everything is baked per frame onto `CR_<shot>_shake` (location in metres, rotation in radians, in the camera's local axes).+ It is deterministic per shot index.+- **Setting it up:** use `move: "path"` with 4–6 keys at a walking pace (about 0.3–0.6 m/s) and `ease: "inout"`, so the operator starts and stops gently.+ Check the camera path against the scene before rendering. In the repair scene, `scenes/tokyo-electronics-repair/scripts/check_path.py` reports the closest mesh and its frame.++## Rig hierarchy (in the saved .blend)++```+CR_<shot>_base (location baked one LINEAR key per frame)+ └ CR_<shot>_aim (rotation: Track To an animated aim empty CR_<shot>_target)+ └ CR_<shot>_shake (noise only)+ └ CR_<shot>_cam (camera data: lens/sensor/DOF; lens animated)+CR_<shot>_target (aim point, animated)+CR_<shot>_focus (DOF focus object, animated or parented)+```++Moves are evaluated in Python and **baked one key per frame**, so every move type behaves the same and Cycles motion blur sees smooth subframes.++The real way to change a move is to edit shots.json and rerun. In a `--save`d file you can still:+- turn the shake empty's Noise modifiers up or down (Graph Editor → Modifiers),+- move the focus empty,+- change lens and f-stop keys on the camera data.++Each shot's rig lives in its own collection `camrig/CamRig_<shot>`. Rerunning a shot deletes and rebuilds that rig.++## Lens FX / grading (Blender 5.0)++- `lens_fx.distortion` and `lens_fx.dispersion` use the **Lens Distortion** compositor node. `lens_fx.glare` (`"fog"`, `"bloom"`, `"streaks"`) uses the **Glare** node.+- **Vignette, colour balance and grain are not done here.** The 5.0 mask and colour-balance nodes misbehave, so finish those in your own ffmpeg grade pass on the rendered frames.+- **Existing compositor:** if the scene already has one, it is kept unless the shot sets `lens_fx`. In that case camrig copies the scene's tree to `camrig_fx` and splices its nodes in just before the Group Output. (Wrapping the old tree in a group node renders **black** in 5.0, because Render Layers inside a nested group yields nothing.)++## Encoding++- ffmpeg comes from `$FFMPEG` (default `ffmpeg` on PATH). camrig encodes with `h264_nvenc` (CQ 18, yuv420p, faststart), which is fast and barely touches the GPU.+- If NVENC fails, it falls back to `h264_mf`.+- Frames are fed through an ffmpeg concat list, so no glob is needed and stepped previews work. 16-bit PNG frames encode fine.++## Helpers (python, inside Blender)++```python+import sys; sys.path.append("<repo>/camera")+import camrig+camrig.bounds("ticket_machine") # -> (min Vector, max Vector, center Vector)+camrig.find("ramen_bowl") # exact name or prefix match+```++`--list "pattern"` prints the matching objects with their bounds centre and size, then exits:++```bash+"$B" -b scene.blend --python camera/shoot.py -- --list bowl+```++## Measured on this box (RTX 5070 Ti, Blender 5.0.1)++| Pass | Scene | Time |+|---|---|---|+| `--framing`, 4 shots → 12 Eevee stills at 640 px | either | 30–50 s, including the file load |+| `--preview`, 960×402 Eevee | ramen | ~0.25 s/frame |+| `--preview`, 960×402 Eevee | repair | ~0.35 s/frame |+| `--lenschart` | either | ~12 s |+| Final Cycles, 960×402, 32 spp, motion blur, glare + lens distortion | repair | ~10 s/frame |+| Final Cycles, 640×360, 16 spp | repair | ~3.3 s/frame |++Scale final times by pixels × samples before you pick a `--frames` chunk size.++## Robust vs flaky (Blender 5.0)++**Robust:**+- every move type, including dolly_zoom lens solving and Catmull-Rom paths+- Track To aim+- rack, track and point focus+- f-stop keys and blades/ratio+- Noise-modifier handheld+- per-frame stamps (a `frame_change_post` handler updates the note)+- Eevee previews+- resume via `use_overwrite=False`+- NVENC encode+- Glare and Lens Distortion spliced into the scene's compositor++**Avoid:**+- compositor mask, ellipse and colour-balance nodes (grade in ffmpeg)+- nesting the scene's compositor group (renders black)+- Track To flips when the aim is exactly vertical, so keep aim points off the camera's plumb line++**Eevee previews differ from Cycles:**+- Glass reads as dark.+- Light falloff is flatter.+- Previews are for framing, move and focus, not for look.++## Examples and tests+- `examples/ramen_shots.json` and `examples/repair_shots.json`: 35 mm push-in with a foreground→subject rack, 85 mm static handheld at f/1.8, 24 mm orbit, and a dolly zoom. All are wired to real object names in each scene.+- Test outputs are in `test/{ramen,repair}/`:+ - `_framing.png`+ - `<shot>/preview.mp4`+ - `scope_85_lenschart.png`+ - `bench_push/frames` (Cycles, with lens_fx)+ - `tiny/` (full chunked final → mp4 + contact)diff --git a/camera/camrig.py b/camera/camrig.pynew file mode 100644index 0000000..b26c790--- /dev/null+++ b/camera/camrig.py@@ -0,0 +1,588 @@+"""camrig: cinematic camera rigs for the night-shop scenes (Blender 5.0). See README.md for the shots.json contract.++Rig per shot: CR_<shot>_base (baked position) -> CR_<shot>_aim (Track To CR_<shot>_target) -> CR_<shot>_shake (noise)+ -> CR_<shot>_cam (lens/roll/DOF), plus CR_<shot>_focus (DOF focus object).+Moves are evaluated in Python and baked one key per frame, so every move type (eased keys, Catmull-Rom paths, orbits,+dolly zooms) behaves the same and motion blur sees smooth subframes; handheld is live Noise modifiers on the shake empty."""+import math++import bpy+from mathutils import Vector++SENSORS = {"s35": 24.89, "ff": 36.0}+ASPECTS = {"2.39": 2.39, "2.35": 2.35, "1.85": 1.85, "16:9": 16 / 9, "1.78": 16 / 9, "4:3": 4 / 3}+LENS_CHART = (18, 24, 35, 50, 85, 135)+++# ------------------------------------------------------------------ scene lookups+def find(name):+ """Object by exact name, then prefix, then case-insensitive substring."""+ obs = bpy.data.objects+ if name in obs:+ return obs[name]+ for o in obs:+ if o.name.startswith(name):+ return o+ low = name.lower()+ for o in obs:+ if low in o.name.lower():+ return o+ raise KeyError(f"camrig: no object matches '{name}'")+++def bounds(name_or_obj):+ """World-space (min, max, center) of an object and all its mesh descendants."""+ root = find(name_or_obj) if isinstance(name_or_obj, str) else name_or_obj+ pts = []+ for o in [root, *root.children_recursive]:+ if o.type in {"MESH", "CURVE", "FONT", "SURFACE", "META", "VOLUME"}:+ pts += [o.matrix_world @ Vector(c) for c in o.bound_box]+ if not pts:+ p = root.matrix_world.translation.copy()+ return p, p, p+ 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, (lo + hi) / 2+++def point(spec, offset=None):+ """[x,y,z] or an object name (bounds centre) -> Vector."""+ p = bounds(spec)[2] if isinstance(spec, (str, bpy.types.Object)) else Vector(spec)+ return p + Vector(offset) if offset else p+++# ------------------------------------------------------------------ easing / interpolation+def ease(u, mode="inout"):+ u = min(1.0, max(0.0, u))+ if mode == "linear":+ return u+ if mode == "in":+ return 1 - math.cos(u * math.pi / 2)+ if mode == "out":+ return math.sin(u * math.pi / 2)+ return 0.5 - 0.5 * math.cos(u * math.pi)+++def _segment(ts, t):+ if t <= ts[0]:+ return 0, 0.0+ for i in range(len(ts) - 1):+ if t <= ts[i + 1]:+ span = ts[i + 1] - ts[i]+ return i, (t - ts[i]) / span if span > 0 else 1.0+ return len(ts) - 2, 1.0+++def path_at(ts, pts, t):+ """Through all points: linear for 2, Catmull-Rom (uniform per segment) for 3+. t is already eased."""+ if len(pts) == 1:+ return Vector(pts[0])+ i, u = _segment(ts, t)+ p1, p2 = Vector(pts[i]), Vector(pts[i + 1])+ if len(pts) == 2:+ return p1.lerp(p2, u)+ p0 = Vector(pts[i - 1]) if i > 0 else p1 + (p1 - p2)+ p3 = Vector(pts[i + 2]) if i + 2 < len(pts) else p2 + (p2 - p1)+ u2, u3 = u * u, u * u * u+ return 0.5 * ((2 * p1) + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u2 + (-p0 + 3 * p1 - 3 * p2 + p3) * u3)+++def segment_at(ts, vals, t, mode):+ """Per-segment eased interpolation (holds + pulls): focus racks, lens zooms, f-stop, roll."""+ if len(vals) == 1:+ return vals[0]+ i, u = _segment(ts, t)+ e = ease(u, mode)+ a, b = vals[i], vals[i + 1]+ if isinstance(a, Vector):+ return a.lerp(b, e)+ return a + (b - a) * e+++# ------------------------------------------------------------------ animation helpers (5.0 layered actions)+def _fc(id_, path, index=0):+ if id_.animation_data is None:+ id_.animation_data_create()+ ad = id_.animation_data+ if ad.action is None:+ ad.action = bpy.data.actions.new(f"{id_.name}_act")+ return ad.action.fcurve_ensure_for_datablock(id_, path, index=index)+++def bake(id_, path, values, index=None, frame0=1):+ """values: list per frame (scalar or sequence). One LINEAR key per frame."""+ seq = isinstance(values[0], (list, tuple, Vector))+ idxs = range(len(values[0])) if seq else [index or 0]+ for j in idxs:+ fc = _fc(id_, path, j)+ fc.keyframe_points.clear()+ fc.keyframe_points.add(len(values))+ co = []+ for k, v in enumerate(values):+ co += [frame0 + k, v[j] if seq else v]+ fc.keyframe_points.foreach_set("co", co)+ for kp in fc.keyframe_points:+ kp.interpolation = "LINEAR"+ fc.update()+++def _noise(fc, scale, strength, phase, depth=0):+ m = fc.modifiers.new("NOISE")+ m.blend_type = "REPLACE" # value + (noise - 0.5) * strength: centred, stacks additively+ m.scale, m.strength, m.phase, m.depth = scale, strength, phase, depth+ return m+++def shake(obj, handheld, breathing, seed):+ """Layered noise on location + rotation of the shake empty. Amplitudes are peak-to-peak-ish at intensity 1."""+ obj.animation_data_clear()+ for path in ("location", "rotation_euler"):+ for i in range(3):+ fc = _fc(obj, path, i)+ fc.keyframe_points.insert(1, 0.0)+ ph = seed * 13.7 + i * 5.3 + (0 if path == "location" else 101)+ if path == "location":+ if breathing:+ _noise(fc, 48, 0.014 * breathing, ph, depth=1) # slow body sway (~2 s)+ if handheld:+ _noise(fc, 11, 0.004 * handheld, ph + 31) # step/hand bob+ _noise(fc, 3.5, 0.0012 * handheld, ph + 57) # fine jitter+ else:+ k = 0.6 if i < 2 else 0.35 # less roll than pan/tilt+ if breathing:+ _noise(fc, 56, math.radians(0.7 * k) * breathing, ph, depth=1)+ if handheld:+ _noise(fc, 13, math.radians(0.45 * k) * handheld, ph + 31)+ _noise(fc, 4, math.radians(0.12 * k) * handheld, ph + 57)+++# ------------------------------------------------------------------ handheld "walk" profile (opt-in)+def walk_settings(s):+ """Return the walk dict if the shot opts in with "handheld": {"profile": "walk", ...}, else None."""+ h = s.get("handheld")+ if isinstance(h, dict) and h.get("profile") == "walk":+ return h+ return None+++def _spring(xs, fps, freq=0.9, zeta=0.62):+ """Second-order follower (semi-implicit Euler, 8 substeps/frame): lags behind moves and overshoots slightly on settle."""+ w = 2 * math.pi * freq+ y, v = xs[0].copy(), Vector((0, 0, 0))+ out, dt = [], 1.0 / fps / 8+ for x in xs:+ for _ in range(8):+ a = w * w * (x - y) - 2 * zeta * w * v+ v += a * dt+ y += v * dt+ out.append(y.copy())+ return out+++def _smooth(vals, k):+ """Symmetric moving average (k frames each side), edge-clamped."""+ n = len(vals)+ return [sum(vals[min(n - 1, max(0, i + j))] for j in range(-k, k + 1)) / (2 * k + 1) for i in range(n)]+++def walk_motion(ev, s, seed):+ """Per-frame (location xyz, rotation xyz) for the shake empty, plus a lagged aim path. All components <= ~1.9 Hz:+ footstep bob + alternating roll scaled by walking speed, low-frequency body sway (calmer when standing), aim lag and+ overshoot, and one or two small reframing corrections. Units: metres / radians, in the camera's local frame+ (x right, y up, z back)."""+ h = walk_settings(s)+ amt = float(h.get("amount", 1.0))+ fps = float(s.get("fps", 24))+ n = ev["n"]+ pos = ev["pos"]+ # walking intensity from the move's speed: 0 standing, 1 at >= walk_speed m/s, eased and smoothed so steps fade in/out+ vmax = float(h.get("walk_speed", 0.55))+ sp = [(pos[min(n - 1, i + 1)] - pos[max(0, i - 1)]).length * fps / (2 if 0 < i < n - 1 else 1) for i in range(n)]+ wv = [min(1.0, v / vmax) for v in sp]+ wv = _smooth([x * x * (3 - 2 * x) for x in wv], int(fps * 0.4))+ step_hz = float(h.get("step_hz", 1.8))+ rnd = __import__("random").Random(seed * 7919 + 17)+ ph = [rnd.uniform(0, 6.283) for _ in range(12)]+ loc, rot = [], []+ phi = 0.0+ # reframing corrections: slow drift off, quicker fix back (pan), at one or two moments+ ncorr = int(h.get("corrections", 2))+ corr_t = sorted(rnd.uniform(0.25, 0.85) for _ in range(ncorr))+ corr_sign = [rnd.choice((-1, 1)) for _ in range(ncorr)]+ for i in range(n):+ t = i / fps+ w = wv[i]+ phi += 2 * math.pi * step_hz / fps * (0.35 + 0.65 * w) if w > 0.02 else 0.0+ calm = 0.45 + 0.55 * w # body sway is calmer when the operator stands+ sway = lambda f, p, a: a * math.sin(2 * math.pi * f * t + p)+ x = sway(0.23, ph[0], 0.016) + sway(0.47, ph[1], 0.008)+ y = sway(0.31, ph[2], 0.010) + sway(0.57, ph[3], 0.005)+ z = sway(0.19, ph[4], 0.012) + sway(0.41, ph[5], 0.006)+ bob = 0.010 * w * (0.5 - 0.5 * math.cos(phi)) # dip once per step (heel strike), ~1 cm+ loc.append(Vector((x * calm + 0.004 * w * math.sin(phi / 2), y * calm - bob, z * calm)) * amt)+ tilt = math.radians(sway(0.29, ph[6], 0.45) + sway(0.53, ph[7], 0.25)) * calm + math.radians(0.12) * w * math.cos(phi)+ pan = math.radians(sway(0.21, ph[8], 0.5) + sway(0.44, ph[9], 0.25)) * calm+ roll = math.radians(0.3) * w * math.sin(phi / 2) + math.radians(sway(0.17, ph[10], 0.25)) * calm+ for ct, cs in zip(corr_t, corr_sign):+ u = i / max(1, n - 1)+ d0, d1 = ct - 0.09, ct # drift over ~9% of the shot, fix in ~0.35 s+ fix = 0.35 * fps / max(1, n - 1)+ if d0 <= u < d1:+ k = (u - d0) / (d1 - d0)+ pan += cs * math.radians(0.6) * k * k * (3 - 2 * k)+ elif d1 <= u < d1 + fix:+ k = (u - d1) / fix+ pan += cs * math.radians(0.6) * (1 - k * k * (3 - 2 * k))+ rot.append(Vector((tilt, pan, roll)) * amt)+ aim = _spring(ev["aim"], fps, float(h.get("aim_lag_hz", 0.9)), float(h.get("aim_damping", 0.62)))+ return loc, rot, aim+++# ------------------------------------------------------------------ shot evaluation+def merged(defaults, shot):+ s = dict(defaults)+ s.update(shot)+ return s+++def evaluate(s):+ """Per-frame lists: pos, aim, lens, roll, focus (Vector or None), fstop."""+ n = int(s.get("frames", 120))+ mode = s.get("ease", "inout")+ move = s.get("move", "static")+ keys = sorted(s.get("keys", []), key=lambda k: k.get("t", 0))+ lens0 = s.get("lens", 35)+ T = [i / max(1, n - 1) for i in range(n)]++ def kpt(k, field):+ if field == "aim" and "aim_obj" in k:+ return point(k["aim_obj"], k.get("aim_offset"))+ if field == "pos" and "pos_obj" in k:+ return point(k["pos_obj"], k.get("pos_offset"))+ return Vector(k[field]) if field in k else None++ if move == "orbit":+ o = s["orbit"]+ c = point(o.get("center_obj") or o["center"], o.get("center_offset"))+ r, a0, a1 = o["radius"], o.get("start_deg", 0), o.get("end_deg", 90)+ h = o.get("height", c.z)+ pos = []+ for t in T:+ a = math.radians(a0 + (a1 - a0) * ease(t, mode))+ pos.append(Vector((c.x + r * math.cos(a), c.y + r * math.sin(a), h)))+ aim_pt = point(o["aim_obj"], o.get("aim_offset")) if "aim_obj" in o else (Vector(o["aim"]) if "aim" in o else c)+ aim = [aim_pt.copy() for _ in T]+ else:+ if not keys:+ raise ValueError(f"shot {s['name']}: move '{move}' needs keys")+ ts = [k.get("t", 0) for k in keys]+ P = [kpt(k, "pos") for k in keys]+ A = [kpt(k, "aim") for k in keys]+ # keys may omit pos/aim to hold the previous value+ for L in (P, A):+ for i in range(len(L)):+ if L[i] is None:+ L[i] = L[i - 1] if i else next(x for x in L if x is not None)+ pos = [path_at(ts, P, ease(t, mode)) for t in T]+ aim = [path_at(ts, A, ease(t, mode)) for t in T]++ # lens+ lkeys = [(k.get("t", 0), k["lens"]) for k in keys if "lens" in k]+ if move == "dolly_zoom":+ subj = point(s["subject"]) if "subject" in s else aim[0]+ l0 = lkeys[0][1] if lkeys else lens0+ d0 = (subj - pos[0]).length+ lens = [l0 * (subj - p).length / d0 for p in pos]+ elif lkeys:+ lens = [segment_at([a for a, _ in lkeys], [b for _, b in lkeys], t, mode) for t in T]+ else:+ lens = [lens0] * n+ rkeys = [(k.get("t", 0), k["roll"]) for k in keys if "roll" in k]+ roll = [segment_at([a for a, _ in rkeys], [b for _, b in rkeys], t, mode) for t in T] if rkeys else [0.0] * n++ # focus+ f = s.get("focus", {"mode": "track_aim"})+ fm = f.get("mode", "point")+ if fm == "none":+ focus = None+ elif fm == "rack":+ fk = sorted(f["keys"], key=lambda k: k.get("t", 0))+ fts = [k.get("t", 0) for k in fk]+ fps = [point(k["obj"], k.get("offset")) if "obj" in k else Vector(k["pos"]) for k in fk]+ focus = [segment_at(fts, fps, t, f.get("ease", "inout")) for t in T]+ elif fm == "track":+ focus = "track"+ elif fm == "point":+ p = Vector(f["pos"]) if "pos" in f else point(f["obj"], f.get("offset"))+ focus = [p] * n+ else: # default: focus where the camera aims+ focus = list(aim)++ if "fstop_keys" in s:+ fk = sorted(s["fstop_keys"], key=lambda k: k["t"])+ fstop = [segment_at([k["t"] for k in fk], [k["v"] for k in fk], t, mode) for t in T]+ else:+ fstop = [s.get("fstop", 2.8)] * n+ return dict(n=n, pos=pos, aim=aim, lens=lens, roll=roll, focus=focus, fstop=fstop)+++# ------------------------------------------------------------------ rig build+def _empty(name, coll, size=0.1, shape="PLAIN_AXES"):+ o = bpy.data.objects.get(name)+ if o is None:+ o = bpy.data.objects.new(name, None)+ coll.objects.link(o)+ o.empty_display_size, o.empty_display_type = size, shape+ return o+++def clear_rig(name):+ for o in [o for o in bpy.data.objects if o.name.startswith(f"CR_{name}_")]:+ data = o.data+ bpy.data.objects.remove(o, do_unlink=True)+ if data is not None and data.users == 0:+ bpy.data.cameras.remove(data)+ c = bpy.data.collections.get(f"CamRig_{name}")+ if c:+ bpy.data.collections.remove(c)+++def build(s, seed=0):+ """Create the rig for merged shot dict s. Returns the camera object."""+ name = s["name"]+ clear_rig(name)+ sc = bpy.context.scene+ root = bpy.data.collections.get("camrig") or bpy.data.collections.new("camrig")+ if root.name not in sc.collection.children:+ sc.collection.children.link(root)+ coll = bpy.data.collections.new(f"CamRig_{name}")+ root.children.link(coll)++ ev = evaluate(s)+ walk = None+ if walk_settings(s):+ wl, wr, ev["aim"] = walk_motion(ev, s, seed + 1)+ if ev["focus"] is not None and ev["focus"] != "track" and s.get("focus", {}).get("mode", "track_aim") == "track_aim":+ ev["focus"] = list(ev["aim"])+ walk = (wl, wr)+ base = _empty(f"CR_{name}_base", coll, 0.15, "CUBE")+ aim = _empty(f"CR_{name}_aim", coll, 0.1, "ARROWS")+ shk = _empty(f"CR_{name}_shake", coll, 0.05)+ tgt = _empty(f"CR_{name}_target", coll, 0.08, "SPHERE")+ foc = _empty(f"CR_{name}_focus", coll, 0.05, "CIRCLE")+ cd = bpy.data.cameras.new(f"CR_{name}_cam")+ cam = bpy.data.objects.new(f"CR_{name}_cam", cd)+ coll.objects.link(cam)+ aim.parent, shk.parent, cam.parent = base, aim, shk+ con = aim.constraints.new("TRACK_TO")+ con.target, con.track_axis, con.up_axis = tgt, "TRACK_NEGATIVE_Z", "UP_Y"++ bake(base, "location", [tuple(p) for p in ev["pos"]])+ bake(tgt, "location", [tuple(p) for p in ev["aim"]])+ bake(cam, "rotation_euler", [math.radians(r) for r in ev["roll"]], index=2)++ sens = s.get("sensor", "s35")+ cd.sensor_width = SENSORS.get(sens, sens) if isinstance(sens, str) else float(sens)+ cd.sensor_fit = "HORIZONTAL"+ cd.clip_start, cd.clip_end = 0.02, 300+ bake(cd, "lens", ev["lens"])+ dof = cd.dof+ if ev["focus"] is None:+ dof.use_dof = False+ else:+ dof.use_dof = True+ dof.focus_object = foc+ dof.aperture_blades = int(s.get("blades", 0))+ dof.aperture_ratio = float(s.get("ratio", 1.0))+ bake(cd, "dof.aperture_fstop", ev["fstop"])+ if ev["focus"] == "track":+ f = s["focus"]+ ob = find(f["obj"])+ c = point(ob, f.get("offset"))+ foc.parent = ob+ foc.matrix_parent_inverse = ob.matrix_world.inverted()+ foc.location = c+ else:+ bake(foc, "location", [tuple(p) for p in ev["focus"]])++ if walk:+ shk.animation_data_clear()+ bake(shk, "location", [tuple(v) for v in walk[0]])+ bake(shk, "rotation_euler", [tuple(v) for v in walk[1]])+ else:+ hh = float(s.get("handheld", 0))+ br = float(s.get("breathing", hh))+ if hh or br:+ shake(shk, hh, br, seed + 1)+ cam["camrig"] = {"lens0": ev["lens"][0], "frames": ev["n"]}+ return cam+++# ------------------------------------------------------------------ render setup+def eevee_id():+ ids = {e.identifier for e in bpy.types.RenderSettings.bl_rna.properties["engine"].enum_items}+ return "BLENDER_EEVEE_NEXT" if "BLENDER_EEVEE_NEXT" in ids else "BLENDER_EEVEE"+++def res_for(s):+ w, h = s.get("res", [1920, 1080])+ a = s.get("aspect", "16:9")+ a = ASPECTS.get(str(a), None) if not isinstance(a, (int, float)) else float(a)+ if a and abs(a - w / h) > 0.01:+ h = int(round(w / a / 2) * 2)+ return w, h+++def setup_render(s, cam, mode="final"):+ sc = bpy.context.scene+ r = sc.render+ sc.camera = cam+ sc.frame_start, sc.frame_end, sc.frame_step = 1, int(s.get("frames", 120)), 1+ r.fps = int(s.get("fps", 24))+ r.resolution_x, r.resolution_y = res_for(s)+ r.resolution_percentage = 100+ r.pixel_aspect_x = r.pixel_aspect_y = 1+ r.use_border = False+ r.image_settings.file_format = "PNG"+ r.image_settings.color_mode = "RGB"+ r.image_settings.color_depth = "16" if (mode == "final" and s.get("png16", True)) else "8"+ r.use_overwrite = False+ r.use_placeholder = False+ sh = float(s.get("shutter", 180))+ r.use_motion_blur = sh > 0+ r.motion_blur_shutter = sh / 360.0+ _fix_exposure(sc, s.get("exposure", 0.0))+ if mode == "final":+ r.engine = "CYCLES"+ sc.cycles.samples = int(s.get("samples", sc.cycles.samples))+ r.use_persistent_data = True+ r.use_stamp = False+ else:+ r.engine = s.get("_engine", eevee_id())+ r.resolution_percentage = s.get("_pct", 50)+ if r.engine.startswith("BLENDER_EEVEE"):+ sc.eevee.taa_render_samples = 16+ r.use_motion_blur = False+ elif r.engine == "CYCLES":+ sc.cycles.samples = 16+ sc.cycles.use_denoising = True+ stamp(sc)+ if sc.name not in _COMP_BASE:+ _COMP_BASE[sc.name] = sc.compositing_node_group+ sc.compositing_node_group = _COMP_BASE[sc.name]+ if s.get("lens_fx"):+ lens_fx(sc, s["lens_fx"])+++_COMP_BASE = {}+++_EXPOSURE_BASE = {}+++def _fix_exposure(sc, offset):+ """Scenes ship with a keyed exposure drift for their old clip; freeze it at its frame-1 value (+ shot offset)."""+ vs = sc.view_settings+ if sc.name not in _EXPOSURE_BASE:+ ad = sc.animation_data+ if ad and ad.action:+ sc.frame_set(1)+ base = vs.exposure+ for fc in _fcurves(ad):+ if fc.data_path == "view_settings.exposure":+ _fcurves(ad).remove(fc)+ break+ else:+ base = vs.exposure+ _EXPOSURE_BASE[sc.name] = base+ vs.exposure = _EXPOSURE_BASE[sc.name] + offset+++def _fcurves(ad):+ act = ad.action+ if hasattr(act, "fcurves"):+ return act.fcurves+ from bpy_extras import anim_utils+ return anim_utils.action_get_channelbag_for_slot(act, ad.action_slot).fcurves+++def stamp(sc):+ r = sc.render+ r.use_stamp = True+ for k in ("date", "time", "render_time", "filename", "scene", "memory", "hostname", "marker", "frame_range",+ "sequencer_strip", "camera"):+ if hasattr(r, f"use_stamp_{k}"):+ setattr(r, f"use_stamp_{k}", False)+ r.use_stamp_frame = True+ r.use_stamp_lens = True+ r.use_stamp_note = True+ r.stamp_font_size = 14+ r.stamp_background = (0, 0, 0, 0.6)+++def stamp_note(sc, depsgraph=None):+ cam = sc.camera+ if cam is None or not cam.name.startswith("CR_"):+ return+ ce = cam.evaluated_get(depsgraph) if depsgraph else cam+ cd = ce.data+ mw = ce.matrix_world+ fwd = -(mw.to_3x3() @ Vector((0, 0, 1))).normalized()+ if cd.dof.use_dof and cd.dof.focus_object:+ fo = cd.dof.focus_object.evaluated_get(depsgraph) if depsgraph else cd.dof.focus_object+ dist = (fo.matrix_world.translation - mw.translation).dot(fwd)+ dof = f"f/{cd.dof.aperture_fstop:.1f} focus {dist:.2f} m"+ else:+ dof = "no DOF"+ shot = cam.name[3:-4]+ sc.render.stamp_note_text = f"{shot} {cd.lens:.0f}mm {dof}"+++def _stamp_handler(scene, depsgraph=None):+ stamp_note(scene, depsgraph)+++def install_handler():+ h = bpy.app.handlers.frame_change_post+ for f in list(h):+ if getattr(f, "__name__", "") == "_stamp_handler":+ h.remove(f)+ h.append(_stamp_handler)+++def lens_fx(sc, fx):+ """Glare + lens distortion/dispersion via the 5.0 node-group compositor, appended after the scene's own tree."""+ # A Render Layers node nested inside a group renders black in 5.0, so copy the scene's tree and splice in before+ # its Group Output instead.+ old = sc.compositing_node_group+ out = None+ if old is not None:+ t = old.copy()+ t.name = "camrig_fx"+ out = next((n for n in t.nodes if n.bl_idname == "NodeGroupOutput"), None)+ if out is None or not out.inputs[0].links:+ t = bpy.data.node_groups.new("camrig_fx", "CompositorNodeTree")+ t.interface.new_socket("Image", in_out="OUTPUT", socket_type="NodeSocketColor")+ img = t.nodes.new("CompositorNodeRLayers").outputs["Image"]+ out = t.nodes.new("NodeGroupOutput")+ else:+ lk = out.inputs[0].links[0]+ img = lk.from_socket+ t.links.remove(lk)+ N, L = t.nodes, t.links.new+ if fx.get("glare"):+ g = N.new("CompositorNodeGlare")+ g.inputs["Type"].default_value = {"fog": "Fog Glow", "bloom": "Bloom", "streaks": "Streaks"}.get(fx["glare"], "Bloom")+ g.inputs["Threshold"].default_value = fx.get("glare_threshold", 1.0)+ g.inputs["Strength"].default_value = fx.get("glare_strength", 0.15)+ L(img, g.inputs["Image"])+ img = g.outputs["Image"]+ if fx.get("distortion") or fx.get("dispersion"):+ ld = N.new("CompositorNodeLensdist")+ ld.inputs["Distortion"].default_value = fx.get("distortion", 0.0)+ ld.inputs["Dispersion"].default_value = fx.get("dispersion", 0.0)+ L(img, ld.inputs["Image"])+ img = ld.outputs["Image"]+ L(img, out.inputs[0])+ sc.compositing_node_group = t+ sc.render.use_compositing = Truediff --git a/camera/examples/ramen_shots.json b/camera/examples/ramen_shots.jsonnew file mode 100644index 0000000..5e4cc09--- /dev/null+++ b/camera/examples/ramen_shots.json@@ -0,0 +1,22 @@+{+ "defaults": { "fps": 24, "frames": 96, "res": [1920, 1080], "aspect": "2.39", "samples": 192,+ "shutter": 180, "sensor": "s35", "fstop": 2.8, "ease": "inout", "handheld": 0.0 },+ "shots": [+ { "name": "counter_push", "move": "push_in", "frames": 120, "handheld": 0.15,+ "keys": [ { "t": 0, "pos": [2.95, 4.35, 1.30], "aim_obj": "ramen_bowl_unfinished", "lens": 35 },+ { "t": 1, "pos": [2.55, 3.60, 1.13], "aim_obj": "ramen_bowl_unfinished" } ],+ "focus": { "mode": "rack", "keys": [ { "t": 0, "obj": "ramen_water_glass" }, { "t": 0.35, "obj": "ramen_water_glass" },+ { "t": 0.75, "obj": "ramen_bowl_unfinished" } ] },+ "fstop": 2.0 },+ { "name": "neko_85", "move": "static", "frames": 72, "handheld": 0.4, "fstop": 1.8, "blades": 7,+ "keys": [ { "t": 0, "pos": [3.25, 4.20, 1.28], "aim_obj": "ramen_maneki_neko", "lens": 85 } ],+ "focus": { "mode": "track", "obj": "ramen_maneki_neko" } },+ { "name": "bowl_orbit", "move": "orbit", "frames": 120, "handheld": 0.1, "fstop": 2.8,+ "orbit": { "center_obj": "ramen_bowl_unfinished", "radius": 0.55, "start_deg": -50, "end_deg": 45, "height": 1.22 },+ "keys": [ { "t": 0, "lens": 24 } ] },+ { "name": "aisle_vertigo", "move": "dolly_zoom", "frames": 120, "fstop": 4.0, "ease": "inout",+ "keys": [ { "t": 0, "pos": [3.05, 5.70, 1.45], "aim_obj": "ticket_machine", "lens": 50 },+ { "t": 1, "pos": [3.05, 3.10, 1.42] } ],+ "subject": "ticket_machine" }+ ]+}diff --git a/camera/examples/repair_shots.json b/camera/examples/repair_shots.jsonnew file mode 100644index 0000000..6272d73--- /dev/null+++ b/camera/examples/repair_shots.json@@ -0,0 +1,22 @@+{+ "defaults": { "fps": 24, "frames": 96, "res": [1920, 1080], "aspect": "2.39", "samples": 192,+ "shutter": 180, "sensor": "s35", "fstop": 2.8, "ease": "inout", "handheld": 0.0 },+ "shots": [+ { "name": "bench_push", "move": "push_in", "frames": 120, "handheld": 0.15,+ "keys": [ { "t": 0, "pos": [1.60, 3.65, 1.36], "aim_obj": "oscilloscope", "lens": 35 },+ { "t": 1, "pos": [1.05, 2.80, 1.16], "aim_obj": "oscilloscope" } ],+ "focus": { "mode": "rack", "keys": [ { "t": 0, "obj": "helping_hands" }, { "t": 0.35, "obj": "helping_hands" },+ { "t": 0.75, "obj": "oscilloscope" } ] },+ "fstop": 2.0 },+ { "name": "scope_85", "move": "static", "frames": 72, "handheld": 0.4, "fstop": 1.8, "blades": 7,+ "keys": [ { "t": 0, "pos": [1.90, 3.40, 1.25], "aim_obj": "oscilloscope", "lens": 85 } ],+ "focus": { "mode": "track", "obj": "oscilloscope" } },+ { "name": "bench_orbit", "move": "orbit", "frames": 120, "handheld": 0.1, "fstop": 2.8,+ "orbit": { "center": [0.42, 2.55, 0.98], "radius": 0.75, "start_deg": -40, "end_deg": 40, "height": 1.32 },+ "keys": [ { "t": 0, "lens": 24 } ] },+ { "name": "shop_vertigo", "move": "dolly_zoom", "frames": 120, "fstop": 4.0,+ "keys": [ { "t": 0, "pos": [3.30, 5.80, 1.50], "aim_obj": "oscilloscope", "lens": 50 },+ { "t": 1, "pos": [2.10, 3.75, 1.38] } ],+ "subject": "oscilloscope" }+ ]+}diff --git a/camera/shoot.py b/camera/shoot.pynew file mode 100644index 0000000..d4ec433--- /dev/null+++ b/camera/shoot.py@@ -0,0 +1,191 @@+"""camrig CLI. Run through pipeline/gpu_run.sh:+ blender -b <scene.blend> --python camera/shoot.py -- --shots <shots.json> --out <abs dir>+ [--only a,b] [--preview | --framing | --lenschart NAME | --still N] [--frames a-b] [--save x.blend] [--no-encode]+ [--engine eevee|cycles|workbench] [--step 2]+ blender -b <scene.blend> --python camera/shoot.py -- --list <pattern>+See README.md."""+import argparse+import json+import os+import subprocess+import sys+import time++import bpy++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import camrig # noqa: E402++FF = os.environ.get("FFMPEG", "ffmpeg")+++def args():+ a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+ p = argparse.ArgumentParser()+ p.add_argument("--shots")+ p.add_argument("--out")+ p.add_argument("--only", default="")+ p.add_argument("--preview", action="store_true")+ p.add_argument("--framing", action="store_true")+ p.add_argument("--lenschart")+ p.add_argument("--still", type=int)+ p.add_argument("--frames")+ p.add_argument("--save")+ p.add_argument("--no-encode", action="store_true")+ p.add_argument("--engine", default="eevee")+ p.add_argument("--step", type=int, default=1)+ p.add_argument("--list")+ return p.parse_args(a)+++def ff(*cmd):+ r = subprocess.run([FF, "-v", "error", "-y", *cmd], capture_output=True, text=True)+ if r.returncode:+ raise RuntimeError(r.stderr[-800:])+++def encode(files, fps, out):+ """files: ordered frame paths (any numbering) -> H.264 mp4 via concat list (no glob)."""+ lst = out + ".txt"+ with open(lst, "w") as f:+ for p in files:+ f.write(f"file '{p.replace(os.sep, '/')}'\nduration {1 / fps:.6f}\n")+ f.write(f"file '{files[-1].replace(os.sep, '/')}'\n")+ common = ["-f", "concat", "-safe", "0", "-i", lst, "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2,format=yuv420p",+ "-r", str(fps), "-movflags", "+faststart"]+ try:+ ff(*common, "-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "18", "-b:v", "0", out)+ except RuntimeError:+ ff(*common, "-c:v", "h264_mf", "-b:v", "20M", out)+ os.remove(lst)+ print("camrig: encoded", out)+++def sheet(files, cols, out, width=640):+ """Equal-size tiles in a grid (pads with black)."""+ n = len(files)+ rows = (n + cols - 1) // cols+ ins = []+ for p in files:+ ins += ["-i", p]+ pad = rows * cols - n+ for _ in range(pad):+ ins += ["-i", files[0]]+ flt = "".join(f"[{i}:v]scale={width}:-2{',drawbox=c=black:t=fill' if i >= n else ''}[v{i}];" for i in range(rows * cols))+ lay = "|".join(("+".join(["w0"] * (i % cols)) or "0") + "_" + ("+".join(["h0"] * (i // cols)) or "0")+ for i in range(rows * cols))+ flt += "".join(f"[v{i}]" for i in range(rows * cols)) + f"xstack=inputs={rows * cols}:layout={lay}"+ if rows * cols == 1:+ flt = "[0:v]scale=%d:-2" % width+ ff(*ins, "-filter_complex", flt, "-frames:v", "1", out)+ print("camrig: sheet", out)+++def render_still(path):+ bpy.context.scene.render.filepath = path+ bpy.ops.render.render(write_still=True)+++def main():+ a = args()+ if a.list:+ for o in sorted(bpy.data.objects, key=lambda o: o.name):+ if a.list.lower() in o.name.lower():+ lo, hi, c = camrig.bounds(o)+ sz = hi - lo+ print(f" {o.name:40s} center ({c.x:.3f}, {c.y:.3f}, {c.z:.3f}) size ({sz.x:.2f}, {sz.y:.2f}, {sz.z:.2f})")+ return+ cfg = json.load(open(a.shots, encoding="utf-8"))+ out = os.path.abspath(a.out)+ os.makedirs(out, exist_ok=True)+ only = {x for x in a.only.split(",") if x}+ shots = [camrig.merged(cfg.get("defaults", {}), s) for s in cfg["shots"]]+ if a.lenschart:+ only = {a.lenschart}+ if only:+ missing = only - {s["name"] for s in shots}+ if missing:+ raise SystemExit(f"camrig: unknown shots {missing}")+ shots = [s for s in shots if s["name"] in only]+ sc = bpy.context.scene+ camrig.install_handler()+ engine = {"eevee": camrig.eevee_id(), "cycles": "CYCLES", "workbench": "BLENDER_WORKBENCH"}[a.engine]++ cams = {}+ for i, s in enumerate(shots):+ cams[s["name"]] = camrig.build(s, seed=i * 7)+ print(f"camrig: rig {s['name']} ({s.get('move', 'static')}, {s.get('frames', 120)} f)")+ if a.save:+ bpy.ops.wm.save_as_mainfile(filepath=os.path.abspath(a.save), copy=True)+ print("camrig: saved", a.save)++ framing_tiles = []+ for s in shots:+ name, cam = s["name"], cams[s["name"]]+ d = os.path.join(out, name)+ n = int(s.get("frames", 120))+ if a.framing or a.lenschart:+ s2 = dict(s, _engine=engine, _pct=100, res=[640, int(640 / (camrig.res_for(s)[0] / camrig.res_for(s)[1]))])+ camrig.setup_render(s2, cam, mode="preview")+ if a.framing:+ for tag, f in (("t0", 1), ("t5", (n + 1) // 2), ("t10", n)):+ sc.frame_set(f)+ camrig.stamp_note(sc, bpy.context.evaluated_depsgraph_get())+ p = os.path.join(d, "framing", tag + ".png")+ render_still(p)+ framing_tiles.append(p)+ else:+ sc.frame_set(1)+ tiles = []+ for mm in camrig.LENS_CHART:+ for fc_owner in (cam.data,):+ if fc_owner.animation_data:+ fc_owner.animation_data.action = None+ cam.data.lens = mm+ camrig.stamp_note(sc, bpy.context.evaluated_depsgraph_get())+ p = os.path.join(d, "lenschart", f"{mm:03d}.png")+ render_still(p)+ tiles.append(p)+ sheet(tiles, 3, os.path.join(out, f"{name}_lenschart.png"))+ continue+ if a.preview:+ s2 = dict(s, _engine=engine, _pct=50)+ camrig.setup_render(s2, cam, mode="preview")+ sc.frame_step = max(1, a.step)+ sc.render.filepath = os.path.join(d, "preview", "")+ t0 = time.time()+ bpy.ops.render.render(animation=True)+ files = [os.path.join(d, "preview", f"{f:04d}.png") for f in range(1, n + 1, sc.frame_step)]+ files = [p for p in files if os.path.exists(p)]+ print(f"camrig: preview {name} {len(files)} frames in {time.time() - t0:.0f}s")+ if not a.no_encode and files:+ encode(files, s.get("fps", 24) / sc.frame_step, os.path.join(d, "preview.mp4"))+ continue+ camrig.setup_render(s, cam, mode="final")+ if a.still:+ sc.frame_set(a.still)+ sc.render.use_overwrite = True+ t0 = time.time()+ render_still(os.path.join(d, f"still_{a.still:04d}.png"))+ print(f"camrig: still {name} f{a.still} in {time.time() - t0:.0f}s")+ continue+ f0, f1 = 1, n+ if a.frames:+ f0, f1 = (int(x) for x in a.frames.split("-"))+ f1 = min(f1, n)+ sc.frame_start, sc.frame_end = f0, f1+ sc.render.filepath = os.path.join(d, "frames", "")+ t0 = time.time()+ bpy.ops.render.render(animation=True)+ print(f"camrig: final {name} frames {f0}-{f1} in {time.time() - t0:.0f}s")+ files = [os.path.join(d, "frames", f"{f:04d}.png") for f in range(1, n + 1)]+ if not a.no_encode and all(os.path.exists(p) for p in files):+ encode(files, s.get("fps", 24), os.path.join(d, f"{name}.mp4"))+ sheet([files[0], files[n // 2], files[-1]], 3, os.path.join(d, "contact.png"))+ elif not a.no_encode:+ print(f"camrig: {name} incomplete ({sum(os.path.exists(p) for p in files)}/{n}); mp4 after the last chunk")+ if framing_tiles:+ sheet(framing_tiles, 3, os.path.join(out, "_framing.png"), width=480)+++main()diff --git a/generate/concepts.sh b/generate/concepts.shnew file mode 100644index 0000000..2d25cb5--- /dev/null+++ b/generate/concepts.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# Concept shots for both scenes, each prompt through both GPT Image 2.5 variants.+cd "$(dirname "$0")/.."+F="node generate/fal.mjs image --quality high --size landscape_16_9"+STYLE="Candid photo taken on a phone at night, realistic, slightly underexposed, natural sensor noise, no people, no text overlays."++REPAIR_WIDE="Inside a cramped, cluttered electronics repair shop in a Tokyo back street, late at night after closing. A long wooden workbench runs along the wall under a single articulated work lamp; on it a vintage CRT oscilloscope, a soldering station with helping hands, multimeters, a disassembled cassette radio and a VCR with its lid off, coiled wires, parts trays, solder spools and handwritten repair tags. Above the bench, small-parts drawer cabinets and shelves of boxed devices waiting for pickup. Overhead fluorescent tubes switched off; the room lit by the work lamp, a green oscilloscope glow and cold blue street light through a rain-streaked shop window with blurred neon outside. $STYLE"+REPAIR_DETAIL="Close-up of a well-worn electronics repair workbench late at night: a soldering iron resting in its stand with a thin curl of smoke, an open circuit board held in helping hands with a magnifier, a CRT oscilloscope showing a green waveform, a multimeter with probes, a small tray of salvaged capacitors and screws, flux bottle, solder wick, a mug of cold coffee and a handwritten repair ticket. Warm pool of light from an articulated lamp, the rest of the shop falling into darkness. $STYLE"+RAMEN_WIDE="Inside a tiny old ramen shop in Tokyo late at night just after closing. A narrow L-shaped wooden counter with eight worn stools faces an open kitchen: dented aluminium stockpots on gas burners with faint steam, ladles and strainers hanging, stacked ceramic bowls, tare containers, a cutting board with green onions. Handwritten wooden menu tags on the wall, a meal-ticket vending machine glowing by the sliding door, a red paper lantern outside throwing light through the noren curtain, rain on the street. Warm tungsten light over the counter, everything else dim. $STYLE"+RAMEN_DETAIL="Close-up of a ramen shop counter late at night after closing: an unfinished bowl of ramen pushed aside, chopsticks resting on the rim, a condiment caddy with chili oil, vinegar and soy bottles, a tissue box, a glass of water, wiped wooden counter with old stains, behind it the kitchen pass with a dented stockpot still steaming under a single warm hanging light. $STYLE"++for v in flare sunburst; do+ $F --variant $v --out refs/tokyo-electronics-repair/concept_wide_$v --prompt "$REPAIR_WIDE" &+ $F --variant $v --out refs/tokyo-electronics-repair/concept_detail_$v --prompt "$REPAIR_DETAIL" &+ $F --variant $v --out refs/tokyo-ramen-shop/concept_wide_$v --prompt "$RAMEN_WIDE" &+ $F --variant $v --out refs/tokyo-ramen-shop/concept_detail_$v --prompt "$RAMEN_DETAIL" &+done+waitdiff --git a/generate/fal.mjs b/generate/fal.mjsnew file mode 100644index 0000000..3b10117--- /dev/null+++ b/generate/fal.mjs@@ -0,0 +1,164 @@+// fal client for AnyScene: GPT Image 2.5 references + Tripo / Meshy image-to-3D, with a spend log.+// Adapted from character-lab/generate/fal.mjs.+//+// The key comes from the user environment variable FAL_KEY (machine-wide; never print it):+// node generate/fal.mjs <command> [flags]+//+// Commands+// image --out refs/tokyo-electronics-repair/concept_a --prompt "..." [--variant flare|sunburst] [--size landscape_16_9] [--quality high] [--n 1]+// -> <out>_<i>.png + <out>.json (keeps the fal URL so 3D endpoints can reuse it)+// 3d --model tripo-h31|tripo-p2|meshy --ref refs/props/x.json --out assets/gen/<model>/<id>+// -> <out>/model.glb + result.json+// spend -> totals so far+//+// All paid calls append {time, endpoint, est_usd, request_id, ...} to generate/spend.jsonl.++import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { dirname, join, resolve } from 'node:path';+import { parseArgs } from 'node:util';++// The machine-wide key lives in the user environment (FAL_KEY). Read it from the registry so shells started+// before it was set still pick it up; fall back to the process env / --env-file.+function globalKey() {+ if (process.platform !== 'win32') return undefined;+ try {+ const out = execFileSync('reg', ['query', 'HKCU\\Environment', '/v', 'FAL_KEY'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });+ return out.match(/FAL_KEY\s+REG_\w+\s+(\S+)/)?.[1];+ } catch {+ return undefined;+ }+}+const KEY = globalKey() || 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');++/** Budget is unlimited per the user; this only guards against runaway loops. */+const TOTAL_CAP = 1000;++/** Rough per-call estimates for the log (fal pricing API, 2026-10-27; GPT Image is token-billed, so estimated). */+const EST = { image: 0.25, 'tripo-h31': 0.6, 'tripo-p2': 0.6, meshy: 0.8 };++const MODELS3D = {+ 'tripo-h31': {+ endpoint: 'tripo3d/h3.1/image-to-3d',+ input: { pbr: true, texture: true, geometry_quality: 'detailed', texture_quality: 'detailed', auto_size: true, orientation: 'align_image' },+ },+ 'tripo-p2': {+ endpoint: 'tripo3d/p2/image-to-3d',+ input: { pbr: true, texture: true, texture_quality: 'extreme', texture_version: 'v3.5-20260815', delight: true, auto_size: true, export_uv: true },+ },+ meshy: {+ endpoint: 'meshy/v7.1/image-to-3d',+ input: { enable_pbr: true, should_texture: true, geometry_resolution: '4k', topology: 'triangle', should_remesh: true, target_polycount: 150000, symmetry_mode: 'auto' },+ },+};++const { positionals, values: a } = parseArgs({+ allowPositionals: true,+ options: {+ out: { type: 'string' }, prompt: { type: 'string' }, variant: { type: 'string', default: 'flare' },+ size: { type: 'string', default: 'landscape_16_9' }, quality: { type: 'string', default: 'high' }, n: { type: 'string', default: '1' },+ model: { type: 'string' }, ref: { type: 'string' },+ },+});++async function readSpend() {+ if (!existsSync(SPEND_LOG)) return [];+ return (await readFile(SPEND_LOG, 'utf8')).split('\n').filter(Boolean).map((l) => JSON.parse(l));+}++async function logSpend(row) {+ await mkdir(dirname(SPEND_LOG), { recursive: true });+ await appendFile(SPEND_LOG, JSON.stringify({ time: new Date().toISOString(), ...row }) + '\n');+}++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;+}++/** Queue-submit, poll, return result. Logs spend as soon as the request is accepted. */+async function run(endpoint, input, { est, meta = {}, timeoutMin = 30 }) {+ if (!KEY) throw new Error('FAL_KEY is not set (user environment variable)');+ const spent = (await readSpend()).reduce((s, r) => s + r.est_usd, 0);+ if (spent + est > TOTAL_CAP) throw new Error(`BUDGET: total would reach $${(spent + est).toFixed(2)} > $${TOTAL_CAP}. Stop and report.`);+ const t0 = performance.now();+ const job = await call(`https://queue.fal.run/${endpoint}`, { method: 'POST', body: JSON.stringify(input) });+ await logSpend({ endpoint, est_usd: est, request_id: job.request_id, ...meta });+ console.log(`queued ${endpoint} ${job.request_id}`);+ for (;;) {+ await new Promise((r) => setTimeout(r, 4000));+ const st = await call(job.status_url);+ if (st.status === 'COMPLETED') break;+ if (performance.now() - t0 > timeoutMin * 60_000) throw new Error(`timed out; request ${job.request_id}`);+ }+ const result = await call(job.response_url);+ const seconds = (performance.now() - t0) / 1000;+ console.log(`done ${endpoint} in ${seconds.toFixed(0)} s`);+ return { result, request_id: job.request_id, seconds };+}++async function download(url, out) {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`download ${res.status} ${url}`);+ await mkdir(dirname(out), { recursive: true });+ await writeFile(out, Buffer.from(await res.arrayBuffer()));+ return out;+}++function need(name) {+ if (!a[name]) throw new Error(`--${name} is required`);+ return a[name];+}++async function cmdImage() {+ const out = resolve(REPO, need('out'));+ const endpoint = `openai/gpt-image-2.5/${a.variant}/text-to-image`;+ const input = { prompt: need('prompt'), image_size: a.size, quality: a.quality, num_images: +a.n, output_format: 'png' };+ const { result, request_id, seconds } = await run(endpoint, input, { est: EST.image * +a.n, meta: { kind: 'image', out: a.out } });+ const files = [];+ for (const [i, img] of (result.images ?? []).entries()) {+ const f = `${out}_${i}.png`;+ await download(img.url, f);+ files.push({ file: f, url: img.url, width: img.width, height: img.height });+ }+ await writeFile(`${out}.json`, JSON.stringify({ endpoint, request_id, seconds, input, files }, null, 2));+ console.log(`saved ${files.map((f) => f.file).join(', ')}`);+}++async function cmd3d() {+ const spec = MODELS3D[need('model')];+ if (!spec) throw new Error(`--model must be one of ${Object.keys(MODELS3D).join(', ')}`);+ const ref = JSON.parse(await readFile(resolve(REPO, need('ref')), 'utf8'));+ const out = resolve(REPO, need('out'));+ const input = { ...spec.input, image_url: ref.files[0].url };+ const { result, request_id, seconds } = await run(spec.endpoint, input, { est: EST[a.model], meta: { kind: '3d', model: a.model, out: a.out } });+ await mkdir(out, { recursive: true });+ await writeFile(join(out, 'result.json'), JSON.stringify({ endpoint: spec.endpoint, request_id, seconds, input, result }, null, 2));+ // Tripo returns model_mesh / pbr_model, Meshy returns model_glb; take the first GLB we find.+ const glb = JSON.stringify(result).match(/https:\/\/[^"]+?\.glb[^"]*/)?.[0];+ if (!glb) throw new Error('no GLB in response: ' + JSON.stringify(result).slice(0, 500));+ await download(glb, join(out, 'model.glb'));+ console.log(`saved ${a.out}/model.glb (${seconds.toFixed(0)} s)`);+}++async function cmdSpend() {+ const rows = await readSpend();+ const by = {};+ for (const r of rows) by[r.endpoint] = (by[r.endpoint] ?? 0) + r.est_usd;+ for (const [e, v] of Object.entries(by)) console.log(`${e.padEnd(48)} $${v.toFixed(2)}`);+ console.log(`${'total'.padEnd(48)} $${rows.reduce((s, r) => s + r.est_usd, 0).toFixed(2)} (${SPEND_LOG})`);+}++const cmds = { image: cmdImage, '3d': cmd3d, spend: cmdSpend };+const cmd = cmds[positionals[0]];+if (!cmd) {+ console.error(`usage: fal.mjs <${Object.keys(cmds).join('|')}> [flags] (see header)`);+ process.exit(1);+}+await cmd();diff --git a/generate/gen3d.sh b/generate/gen3d.shnew file mode 100644index 0000000..cde8765--- /dev/null+++ b/generate/gen3d.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+# Same reference image through every 3D model, for the head-to-head.+cd "$(dirname "$0")/.."+F="node generate/fal.mjs 3d"+for ref in refs/props/*.json; do+ id=$(basename "$ref" .json)+ for m in tripo-h31 tripo-p2 meshy; do+ [ -f assets/gen/$m/$id/model.glb ] && continue+ ( $F --model $m --ref "$ref" --out assets/gen/$m/$id > logs/gen_${m}_$id.log 2>&1; echo "$m $id exit=$? $(tail -1 logs/gen_${m}_$id.log)" ) &+ done+done+waitdiff --git a/generate/models.mjs b/generate/models.mjsnew file mode 100644index 0000000..c6e7446--- /dev/null+++ b/generate/models.mjs@@ -0,0 +1,8 @@+// Search the fal model catalog: node generate/models.mjs <query>...+const KEY = process.env.FAL_KEY || process.env.FAL_API_KEY;+for (const q of process.argv.slice(2)) {+ const r = await fetch(`https://api.fal.ai/v1/models?q=${encodeURIComponent(q)}&limit=40`, { headers: { authorization: `Key ${KEY}` } });+ const j = await r.json();+ console.log(`## ${q} (${r.status})`);+ for (const m of j.models ?? []) console.log(m.endpoint_id, '|', m.metadata?.display_name, '|', m.metadata?.status, '|', m.metadata?.updated_at?.slice(0, 10));+}diff --git a/generate/props.sh b/generate/props.shnew file mode 100644index 0000000..a8cfa67--- /dev/null+++ b/generate/props.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash+# Isolated prop reference shots (GPT Image 2.5 Sunburst) to feed image-to-3D, as in the video.+cd "$(dirname "$0")/.."+F="node generate/fal.mjs image --variant sunburst --quality high --size square_hd"+REF="Product reference photograph for 3D scanning. The entire object fully visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft even diffuse studio lighting, no harsh shadows, no other objects, no hands, realistic used and worn condition, sharp focus, true-to-life materials."+declare -A P=(+ [oscilloscope]="A 1980s analog CRT oscilloscope with a beige and grey metal case, round-cornered green-tinted screen with graticule, rows of knobs, toggle switches and BNC connectors on the front panel, small printed labels, scuffed paint."+ [solder_station]="A worn analog soldering station: a grey control unit with a temperature dial, a soldering iron resting in its coiled-wire holder stand with a yellow brass-wool tip cleaner, the iron's cable connecting to the unit."+ [helping_hands]="A helping-hands soldering aid on a heavy cast-iron base, two articulated arms with alligator clips holding a small green circuit board, a round magnifying glass on an adjustable arm."+ [boombox_open]="A 1980s silver cassette boombox radio lying open for repair with its back cover removed, exposing circuit boards, wires and the tape mechanism; the removed back panel and a few screws lying next to it."+ [stockpot]="A large, heavily used aluminium ramen stockpot, about 40 cm tall, with two riveted side handles, dented sides, heat discoloration and dried broth stains, a slightly warped lid resting on top."+ [ticket_machine]="A Japanese restaurant meal-ticket vending machine (shokkenki), a tall white and grey metal cabinet with a grid of illuminated rectangular menu buttons with Japanese labels, coin slot, bill slot and ticket tray, scuffed and slightly yellowed."+ [condiment_caddy]="A small stainless-steel condiment tray from a ramen counter holding glass bottles of chili oil, soy sauce and vinegar with chrome caps, a shaker of white pepper, and a jar of chopped garlic, slightly greasy."+ [lantern]="A red Japanese paper lantern (akachochin) for a ramen shop with black brush-stroke kanji ラーメン painted on it, ribbed paper over a bamboo frame, black lacquered top and bottom rims, slightly weathered."+)+for k in "${!P[@]}"; do+ $F --out refs/props/$k --prompt "${P[$k]} $REF" &+done+waitdiff --git a/generate/schema.mjs b/generate/schema.mjsnew file mode 100644index 0000000..69e3923--- /dev/null+++ b/generate/schema.mjs@@ -0,0 +1,16 @@+// Print input schema + price for fal endpoints.+const KEY = process.env.FAL_KEY || process.env.FAL_API_KEY;+const ids = process.argv.slice(2);+const pr = await fetch(`https://api.fal.ai/v1/models/pricing?${ids.map((i) => 'endpoint_id=' + encodeURIComponent(i)).join('&')}`, { headers: { authorization: `Key ${KEY}` } }).then((r) => r.json());+for (const p of pr.prices ?? []) console.log('PRICE', p.endpoint_id, p.unit_price, p.unit, p.currency);+for (const id of ids) {+ const j = await fetch(`https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=${encodeURIComponent(id)}`).then((r) => r.json());+ const schemas = j.components?.schemas ?? {};+ const inName = Object.keys(schemas).find((k) => /Input$/.test(k));+ const s = schemas[inName];+ console.log(`\n## ${id} (${inName}) required=${JSON.stringify(s?.required)}`);+ for (const [k, v] of Object.entries(s?.properties ?? {})) {+ const en = v.enum ?? v.anyOf?.flatMap((x) => x.enum ?? []) ?? (v.allOf?.[0]?.$ref ? schemas[v.allOf[0].$ref.split('/').pop()]?.enum : undefined);+ console.log(` ${k}: ${v.type ?? ''} default=${JSON.stringify(v.default)}${en?.length ? ' enum=' + JSON.stringify(en) : ''} — ${(v.description ?? '').slice(0, 110)}`);+ }+}diff --git a/pipeline/build_compare_page.mjs b/pipeline/build_compare_page.mjsnew file mode 100644index 0000000..f491768--- /dev/null+++ b/pipeline/build_compare_page.mjs@@ -0,0 +1,157 @@+// Builds out/page/index.html + jpgs from out/compare (render_compare.py) and out/compare/verdicts.json.+// node pipeline/build_compare_page.mjs+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++const FF = process.env.FFMPEG || 'ffmpeg';+const CMP = 'out/compare';+const PAGE = 'out/page';+const MODELS = [+ ['tripo-h31', 'Tripo H3.1', 'detailed geometry + texture'],+ ['tripo-p2', 'Tripo P2', 'extreme texture, delit'],+ ['meshy', 'Meshy 7.1', '4k geometry, PBR'],+];+const PROPS = [+ ['oscilloscope', 'CRT oscilloscope', 'repair', 'hard surface, panel labels'],+ ['solder_station', 'Soldering station', 'repair', 'thin cable, coiled holder'],+ ['helping_hands', 'Helping hands', 'repair', 'wiry arms, glass lens'],+ ['boombox_open', 'Open boombox', 'repair', 'exposed internals'],+ ['stockpot', 'Stockpot', 'ramen', 'dented metal'],+ ['ticket_machine', 'Ticket machine', 'ramen', 'dense printed buttons'],+ ['condiment_caddy', 'Condiment caddy', 'ramen', 'glass and liquid'],+ ['lantern', 'Akachochin lantern', 'ramen', 'ribbed paper, kanji'],+];+const VIEWS = ['beauty', 'back', 'clay'];++const stats = JSON.parse(readFileSync(join(CMP, 'stats.json'), 'utf8'));+const verdicts = existsSync(join(CMP, 'verdicts.json')) ? JSON.parse(readFileSync(join(CMP, 'verdicts.json'), 'utf8')) : {};+const files = {};+const jpg = (src, dst, w) => {+ mkdirSync(join(PAGE, 'img'), { recursive: true });+ execFileSync(FF, ['-v', 'error', '-y', '-i', src, '-vf', `scale=${w}:-1`, '-q:v', '4', join(PAGE, dst)]);+ files[dst] = join(PAGE, dst);+};++const CONCEPTS = [+ ['repair', 'wide', 'Repair shop, wide'], ['repair', 'detail', 'Repair bench, close'],+ ['ramen', 'wide', 'Ramen shop, wide'], ['ramen', 'detail', 'Ramen counter, close'],+];+for (const [s, k] of CONCEPTS) jpg(`refs/${s}/concept_${k}_sunburst_0.png`, `img/concept_${s}_${k}.jpg`, 1100);++for (const [p] of PROPS) {+ jpg(`refs/props/${p}_0.png`, `img/${p}_ref.jpg`, 640);+ for (const [m] of MODELS) for (const v of VIEWS) {+ const src = join(CMP, m, `${p}_${v}.png`);+ if (existsSync(src)) jpg(src, `img/${p}_${m}_${v}.jpg`, 640);+ }+}++const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);+const kfmt = (n) => (n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? Math.round(n / 1e3) + 'k' : n);+// Texture maps named by the glTF image name prefix (Color / ORM / NormalGL / ...), with the largest edge size.+const texSummary = (imgs = {}) => {+ const ents = Object.entries(imgs);+ if (!ents.length) return 'no textures';+ return ents.map(([name, i]) => `${name.split(/[_.]/)[0].replace('NormalGL', 'Normal').replace('Color', 'Albedo')} ${i.size[0] / 1024}K`).join(' · ');+};+const gen = existsSync(join(CMP, 'gen.json')) ? JSON.parse(readFileSync(join(CMP, 'gen.json'), 'utf8')) : {};++const score = { 'tripo-h31': 0, 'tripo-p2': 0, meshy: 0 };+for (const v of Object.values(verdicts.props ?? {})) if (v.winner in score) score[v.winner]++;++const rows = PROPS.map(([p, name, scene, stress]) => {+ const v = verdicts.props?.[p] ?? {};+ const cells = MODELS.map(([m, label]) => {+ const s = stats[m]?.[p];+ const imgs = VIEWS.map((view) => `<img data-view="${view}" ${view === 'beauty' ? '' : 'hidden'} src="img/${p}_${m}_${view}.jpg" alt="${esc(label)} ${esc(name)}, ${view}" loading="lazy">`).join('');+ const meta = !s ? '<span class="bad">not generated</span>' : s.error ? `<span class="bad">import failed</span>` :+ `<span>${kfmt(s.tris)} tris · ${gen[m]?.[p]?.mb ?? '?'} MB GLB · ${gen[m]?.[p]?.sec ?? '?'} s</span><span>${esc(texSummary(s.images))}</span><span>${s.size_m.map((x) => x.toFixed(2)).join(' × ')} m${m === 'meshy' ? ' (unscaled)' : ''}</span>`;+ const win = v.winner === m;+ return `<figure class="cell${win ? ' win' : ''}"><div class="frame">${imgs}${win ? '<span class="chip">pick</span>' : ''}</div>+ <figcaption><b>${esc(label)}</b>${meta}${v.notes?.[m] ? `<p>${esc(v.notes[m])}</p>` : ''}</figcaption></figure>`;+ }).join('');+ return `<section class="prop" id="${p}">+ <header><h2>${esc(name)}</h2><span class="tag ${scene}">${scene === 'repair' ? 'Repair bench' : 'Ramen shop'}</span><span class="stress">stress: ${esc(stress)}</span></header>+ <div class="grid"><figure class="cell ref"><div class="frame"><img src="img/${p}_ref.jpg" alt="${esc(name)} reference"></div><figcaption><b>Reference</b><span>GPT Image 2.5 Sunburst</span></figcaption></figure>${cells}</div>+ </section>`;+}).join('\n');++const html = `<title>Tripo vs Meshy Props</title>+<meta name="claude:viewport-fit-sides" content="cover">+<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wght@500;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap">+<style>+/* Layout: a lookdev review board. Reference on the left, three generators across; one view toggle drives every row. */+:root{+ --bg:#ecebe8;--panel:#f7f6f3;--line:#d3d1cb;--fg:#1d1e20;--mute:#66676b;--accent:#c4421a;--good:#2f7d4f;--ramen:#9a2a1c;--repair:#2a5a73;+ --display:"Archivo",system-ui,sans-serif;--mono:"IBM Plex Mono",ui-monospace,Consolas,monospace;+}+@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#17181a;--panel:#202124;--line:#34363a;--fg:#e9e8e4;--mute:#9a9ba0;--accent:#f0753f;--good:#5cc488;--ramen:#e0705f;--repair:#6fb0d2;color-scheme:dark}}+:root[data-theme="dark"]{--bg:#17181a;--panel:#202124;--line:#34363a;--fg:#e9e8e4;--mute:#9a9ba0;--accent:#f0753f;--good:#5cc488;--ramen:#e0705f;--repair:#6fb0d2;color-scheme:dark}+body{background:var(--bg);color:var(--fg);font:14px/1.5 var(--mono);padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:28px 64px}+main{max-width:1400px;margin:0 auto;display:grid;gap:36px}+h1{font:800 clamp(28px,4vw,44px)/1.05 var(--display);letter-spacing:-.02em;margin:0;text-wrap:balance}+h2{font:700 20px/1.2 var(--display);margin:0}+.intro{display:grid;gap:14px;max-width:72ch}.intro p{margin:0;color:var(--mute)}+.board{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}+.score{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:14px 16px;display:grid;gap:4px}+.score b{font:800 32px/1 var(--display);font-variant-numeric:tabular-nums}.score span{color:var(--mute);font-size:12px}+.score.lead{border-color:var(--accent)}.score.lead b{color:var(--accent)}+.summary{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:16px 18px;max-width:90ch}.summary p{margin:.4em 0}+.bar{position:sticky;top:env(safe-area-inset-top,0px);z-index:5;background:var(--bg);padding-block:10px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;border-bottom:1px solid var(--line)}+body::before{content:"";position:fixed;inset:0 0 auto;height:env(safe-area-inset-top,0px);z-index:10;background:var(--bg)}+.bar span{color:var(--mute);font-size:12px;letter-spacing:.06em;text-transform:uppercase;margin-right:4px}+.bar button{font:500 13px var(--mono);background:var(--panel);color:var(--fg);border:1px solid var(--line);border-radius:4px;padding:6px 12px;cursor:pointer}+.bar button[aria-pressed="true"]{background:var(--fg);color:var(--bg);border-color:var(--fg)}+.bar button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}+.prop{display:grid;gap:12px}+.prop header{display:flex;gap:12px;align-items:baseline;flex-wrap:wrap}+.tag{font-size:11px;letter-spacing:.08em;text-transform:uppercase;font-weight:500}.tag.repair{color:var(--repair)}.tag.ramen{color:var(--ramen)}+.stress{color:var(--mute);font-size:12px}+.grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}+@media (max-width:900px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}}+.cell{margin:0;display:grid;gap:8px;align-content:start;min-width:0}+.frame{position:relative;aspect-ratio:1;max-width:100%;background:var(--panel);border:1px solid var(--line);border-radius:4px;overflow:hidden}+.frame img{width:100%;height:100%;object-fit:cover;display:block}+.cell.win .frame{border:2px solid var(--good)}+.chip{position:absolute;top:8px;left:8px;background:var(--good);color:var(--bg);font:500 11px var(--mono);letter-spacing:.08em;text-transform:uppercase;padding:2px 8px;border-radius:3px}+figcaption{display:grid;gap:2px;font-size:12px;color:var(--mute);font-variant-numeric:tabular-nums;min-width:0}+figcaption b{color:var(--fg);font:700 14px var(--display)}+figcaption p{margin:4px 0 0;color:var(--fg);font-size:12.5px;line-height:1.45}+.bad{color:var(--accent)}+.concepts{display:grid;gap:10px}.concepts p{margin:0;color:var(--mute);max-width:72ch}+.cgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}+@media (max-width:700px){.cgrid{grid-template-columns:1fr}}+.cframe{aspect-ratio:16/9;max-width:100%;border:1px solid var(--line);border-radius:4px;overflow:hidden;background:var(--panel)}+.cframe img{width:100%;height:100%;object-fit:cover;display:block}+@media (prefers-reduced-motion:no-preference){.frame img{transition:opacity .15s}}+</style>+<main>+ <div class="intro">+ <h1>Tripo vs Meshy on late-night props</h1>+ <p>Eight props for the repair bench and ramen shop. Each one is the same GPT Image 2.5 reference through Tripo H3.1, Tripo P2 and Meshy 7.1 at their highest settings, rendered in Blender Cycles under one studio light and camera fit. Use the toggle to see the back (the side the generator had to invent) and clay with wireframe.</p>+ </div>+ <section class="concepts"><h2>Concept shots</h2><p>GPT Image 2.5 Sunburst, picked over Flare for legible Japanese signage and a more natural grade. These are the targets each scene is built toward.</p>+ <div class="cgrid">${CONCEPTS.map(([s, k, label]) => `<figure class="cell"><div class="cframe"><img src="img/concept_${s}_${k}.jpg" alt="${esc(label)} concept"></div><figcaption><b>${esc(label)}</b></figcaption></figure>`).join('')}</div>+ </section>+ <h2>Generator results</h2>+ <div class="board">${MODELS.map(([m, label, how]) => `<div class="score${score[m] === Math.max(...Object.values(score)) && score[m] > 0 ? ' lead' : ''}"><b>${score[m]}</b><span>${esc(label)} picks · ${esc(how)}</span></div>`).join('')}</div>+ ${verdicts.summary ? `<div class="summary">${verdicts.summary.map((s) => `<p>${esc(s)}</p>`).join('')}</div>` : ''}+ <div class="bar" role="group" aria-label="View"><span>View</span>+ <button id="v-beauty" data-v="beauty" aria-pressed="true">Front · textured</button>+ <button id="v-back" data-v="back" aria-pressed="false">Back · textured</button>+ <button id="v-clay" data-v="clay" aria-pressed="false">Clay + wire</button>+ </div>+ ${rows}+</main>+<script>+document.querySelectorAll('.bar button').forEach(b=>b.addEventListener('click',()=>{+ document.querySelectorAll('.bar button').forEach(x=>x.setAttribute('aria-pressed',x===b));+ document.querySelectorAll('img[data-view]').forEach(i=>i.hidden=i.dataset.view!==b.dataset.v);+}));+</script>+`;+writeFileSync(join(PAGE, 'index.html'), html);+writeFileSync(join(PAGE, 'files.json'), JSON.stringify(files, null, 2));+console.log(`wrote ${PAGE}/index.html + ${Object.keys(files).length} images`);diff --git a/pipeline/build_scenes_page.mjs b/pipeline/build_scenes_page.mjsnew file mode 100644index 0000000..ded8363--- /dev/null+++ b/pipeline/build_scenes_page.mjs@@ -0,0 +1,432 @@+// Build out/scenes/index.html: one tab per scene (shots, stills, assets, process) plus an overview.+// Every derived file lands in out/scenes/img and is rebuilt only when its source is newer.+import { execFileSync } from "node:child_process";+import { mkdirSync, readFileSync, writeFileSync, existsSync, statSync, readdirSync } from "node:fs";+import { join, sep } from "node:path";++const ROOT = join(import.meta.dirname, "..");+const OUT = join(ROOT, "out/scenes");+const IMG = join(OUT, "img");+const FF = process.env.FFMPEG || "ffmpeg";+mkdirSync(IMG, { recursive: true });++// Rebuild a derived file when it's missing or older than any of its sources (renders get replaced in place).+const stale = (srcs, dst) => !existsSync(dst) || [srcs].flat().some((s) => existsSync(s) && statSync(dst).mtimeMs < statSync(s).mtimeMs);+const ff = (args) => execFileSync(FF, ["-v", "error", "-y", ...args]);+const jpg = (src, name, w) => {+ const dst = join(IMG, name + ".jpg");+ if (stale(src, dst)) ff(["-i", src, "-vf", `scale=${w}:-2`, "-q:v", "3", dst]);+ return `img/${name}.jpg`;+};+const mp4 = (src, name) => {+ const dst = join(IMG, name + ".mp4");+ // The clips are already H.264 yuv420p, so copy with faststart.+ if (stale(src, dst)) ff(["-i", src, "-an", "-c:v", "copy", "-movflags", "+faststart", dst]);+ return `img/${name}.mp4`;+};+const poster = (src, name) => {+ const dst = join(IMG, name + "_poster.jpg");+ if (stale(src, dst)) ff(["-ss", "1.2", "-i", src, "-frames:v", "1", "-vf", "scale=960:-2", "-q:v", "4", dst]);+ return `img/${name}_poster.jpg`;+};++// One sprite per prop: reference | Tripo beauty | Tripo clay | Meshy beauty | Meshy clay, 360 px tiles.+// The page shows single tiles via background-position, which keeps the artifact under its file-count limit.+const TILE = 360;+const sprite = (name, tiles) => {+ const dst = join(IMG, `a_${name}.jpg`);+ if (!stale(tiles.filter(Boolean), dst)) return `img/a_${name}.jpg`;+ const args = [], chains = [];+ tiles.forEach((t, i) => {+ if (t) args.push("-i", t);+ else args.push("-f", "lavfi", "-i", `color=c=0x1d1b19:s=${TILE}x${TILE}:d=1`);+ chains.push(`[${i}:v]scale=${TILE}:${TILE}:force_original_aspect_ratio=decrease,pad=${TILE}:${TILE}:-1:-1:color=0x1d1b19,setsar=1,format=yuv420p[t${i}]`);+ });+ ff([...args, "-filter_complex", `${chains.join(";")};${tiles.map((_, i) => `[t${i}]`).join("")}hstack=inputs=${tiles.length}`, "-frames:v", "1", "-q:v", "4", dst]);+ return `img/a_${name}.jpg`;+};++const REFS = readdirSync(join(ROOT, "refs"), { recursive: true }).map((f) => String(f).split(sep).join("/")).filter((f) => f.endsWith("_0.png"));+const findRef = (ids) => { const r = REFS.find((f) => ids.some((id) => f.endsWith("/" + id + "_0.png"))); return r && join(ROOT, "refs", r); };+const findRender = (scene, model, ids, view) => {+ for (const dir of [`scenes/${FOLDER[scene]}/compare/${model}`, `out/compare/${model}`])+ for (const id of ids) { const f = join(ROOT, dir, `${id}_${view}.png`); if (existsSync(f)) return f; }+};++const spendRows = readFileSync(join(ROOT, "generate/spend.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l));+const spendFor = (id) => spendRows.filter((r) => (r.out || "").includes(id)).reduce((s, r) => s + r.est_usd, 0);+const spendShared = spendRows.filter((r) => !/ramen|repair/.test(r.out || "")).reduce((s, r) => s + r.est_usd, 0);++// Scene id (the prefix on its asset ids) -> its folder under scenes/.+const FOLDER = { repair: "tokyo-electronics-repair", ramen: "tokyo-ramen-shop" };++const SCENES = [+ {+ id: "repair", title: "Electronics repair, late night", short: "Repair shop", kicker: "Scene 01",+ dir: "scenes/tokyo-electronics-repair/out", shotDir: (n) => `${n}_graded.mp4`,+ blurb: "A narrow Tokyo repair counter after hours: racks of tagged jobs, a parts-drawer wall, one clamp lamp on at the bench and rain on the storefront.",+ heroes: [["hero_wide.png", "hero_wide_v1.png", "The shop from the back — rain on the storefront, one lamp on at the bench"], ["hero_bench.png", "hero_bench_v1.png", "The bench — scripted CRT graticule, helping-hands lens rebuilt as glass"]],+ clip: ["clip.mp4", "Round 1 handheld push, back of the shop to the bench (1080p)"],+ r2: [+ ["process_r2_passA_wide.png", "Pass A — mid props: boxed jobs, parts cart, second station"],+ ["process_r2_passA_wide_clay.png", "Pass A, clay"],+ ["process_r2_passB_wide.png", "Pass B — small clutter: screws, PCBs, cups, tape"],+ ["process_r2_passB_wide_clay.png", "Pass B, clay"],+ ["process_r2_passC_wide.png", "Pass C — cables, notes, flyers, price tags"],+ ["process_r2_passC_bench.png", "Pass C at the bench"],+ ],+ r1: [+ ["process_01_shell_clay.png", "Scripted shell, clay"],+ ["process_02_dress_pass1.png", "Dress pass 1 — benches, racks"],+ ["process_02_dress_pass3.png", "Dress pass 3 — small props"],+ ["process_04_bench_repairs.png", "Script repairs on the bench"],+ ["process_03_lighting_first_pass.png", "Lighting, first pass"],+ ["process_05_lighting_balanced.png", "Lighting, balanced"],+ ["process_00_prop_refs.png", "GPT Image 2.5 prop references"],+ ["process_00_compare_tripo_vs_meshy.png", "Tripo H3.1 vs Meshy pick sheet"],+ ],+ weak: [+ "The two TVs left on still show a flat no-signal blue.",+ "s1's interior through the glass is busy and low-contrast at 18 mm.",+ "In the bench still the lamp arm cuts into the right edge of frame.",+ "A few generated props were picked but not placed (magnifier lamp, parts bins, ribbon cables).",+ ],+ },+ {+ id: "ramen", title: "Ramen shop, after close", short: "Ramen shop", kicker: "Scene 02",+ dir: "scenes/tokyo-ramen-shop/out", shotDir: (n) => `${n}/${n}_graded.mp4`,+ blurb: "An eight-stool ramen counter at closing: stockpots still steaming, the ticket machine glowing by the door, rain on the street outside.",+ heroes: [["hero_wide.png", "hero_wide_v1.png", "Down the aisle — 食券 machine, ラーメン lantern against the rain"], ["hero_counter.png", "hero_counter_v1.png", "Seated at the counter — last bowl, steam rolling off the pass"]],+ clip: ["clip.mp4", "Round 1 handheld push down the aisle (720p)"],+ r2: [+ ["process/r2_passA.png", "Pass A — mid props: pots, bowl stacks, kitchen gear"],+ ["process/r2_passB.png", "Pass B — small clutter: ladles, towels, slips"],+ ["process/r2_passC.png", "Pass C — micro: cords, flyers, stickers"],+ ["process/r2_grime.png", "Grime — grease film, stains, worn edges"],+ ["process/r2_steam.png", "Steam — Mantaflow plumes off pots and bowl"],+ ["process/r2_exterior_from_inside.png", "Exterior relit — street through the door"],+ ["process/r2_generated_props.png", "Generated props swapped in"],+ ],+ r1: [+ ["process/01_shell_clay.png", "Scripted shell, clay"],+ ["process/02_shell_lit.png", "Shell, first light"],+ ["process/03_dressing_partial.png", "Dressing — big props first"],+ ["process/04_dressing_full_plus_top.png", "Fully dressed + top view"],+ ["process/08_clay_dressed.png", "Dressed, clay check"],+ ["process/05_lighting_fixed.png", "Night lighting fixed"],+ ["process/06_lookdev_graded.png", "Look-dev, graded"],+ ["process/00_prop_refs.png", "GPT Image 2.5 prop references"],+ ],+ weak: [+ "First second of exterior_establish: a band of out-of-focus rain streaks (fix queued).",+ "Steam volumes don't motion-blur; the kitchen haze can read as a flat wall from the counter.",+ "A few small props float 2–8 cm above their surface.",+ "Round-1 props still carry real brands (Kirin crate and fridge, Sapporo poster, Kikkoman).",+ ],+ },+];++const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/"/g, """);+const pretty = (k, id) => k.replace(new RegExp(`^${id}_`), "").replace(/_nb$/, "").replace(/_/g, " ");+const MODEL = { "tripo-h31": "Tripo H3.1", meshy: "Meshy 7.1", none: "Not used" };++const totals = { "tripo-h31": 0, meshy: 0 };+const built = SCENES.map((s) => {+ // ---- assets+ const picks = JSON.parse(readFileSync(join(ROOT, `scenes/${FOLDER[s.id]}/picks.json`), "utf8"));+ const keys = Object.keys(picks).filter((k) => !k.startsWith("_") && picks[k]?.model);+ const assets = keys.map((k) => {+ const v = picks[k], ids = [k, `${s.id}_${k}`];+ const superseded = keys.includes(`${k}_nb`);+ const used = v.model !== "none" && !v.retired && !superseded;+ const tiles = [findRef(ids), findRender(s.id, "tripo-h31", ids, "beauty"), findRender(s.id, "tripo-h31", ids, "clay"), findRender(s.id, "meshy", ids, "beauty"), findRender(s.id, "meshy", ids, "clay")];+ if (used) totals[v.model] = (totals[v.model] || 0) + 1;+ return {+ k, name: pretty(k, s.id), model: v.model, used, why: v.why || v.reason || "",+ flags: [k.endsWith("_nb") || v.debranded ? "de-branded" : "", v.retired ? "retired" : "", superseded ? "replaced by de-branded" : ""].filter(Boolean),+ has: { t: !!tiles[1], m: !!tiles[3] }, src: sprite(`${s.id}_${k}`, tiles),+ };+ }).sort((a, b) => b.used - a.used || a.name.localeCompare(b.name));+ const n = { "tripo-h31": 0, meshy: 0, unused: 0 };+ assets.forEach((a) => (a.used ? n[a.model]++ : n.unused++));++ // ---- shots, from shots.json so unrendered ones still show up+ const def = JSON.parse(readFileSync(join(ROOT, `scenes/${FOLDER[s.id]}/shots.json`), "utf8"));+ const fps = def.defaults?.fps || 24;+ const shots = def.shots.map((sh) => {+ const src = join(ROOT, s.dir, "shots", s.shotDir(sh.name));+ const lenses = (sh.keys || []).map((k) => k.lens).filter(Boolean);+ const lens = lenses.length ? (lenses.at(-1) !== lenses[0] ? `${lenses[0]}→${lenses.at(-1)} mm` : `${lenses[0]} mm`) : "";+ const frames = sh.frames || def.defaults?.frames || 96;+ const handheld = /^h\d/.test(sh.name) || sh.handheld?.profile === "walk";+ const ready = existsSync(src);+ return {+ name: sh.name, handheld, ready,+ label: sh.name.replace(/^[sh]\d+_/, "").replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase()), code: sh.name.match(/^[sh]\d+/)?.[0] || "",+ meta: [lens, `f/${sh.fstop ?? def.defaults?.fstop ?? 2.8}`, `${(frames / fps).toFixed(1)} s`, (sh.move || "").replace(/_/g, " "), sh.focus?.mode ? `${sh.focus.mode} focus` : ""].filter(Boolean),+ video: ready && mp4(src, `${s.id}_shot_${sh.name}`), poster: ready && poster(src, `${s.id}_shot_${sh.name}`),+ };+ });+ const clipSrc = join(ROOT, s.dir, s.clip[0]);+ const clip = { name: "round1_clip", label: "Round 1 clip", code: "r1", handheld: true, ready: true, meta: [s.clip[1]], video: mp4(clipSrc, `${s.id}_clip`), poster: poster(clipSrc, `${s.id}_clip`) };++ return {+ ...s, assets, n, shots, clip,+ spend: spendFor(s.id),+ heroes: s.heroes.map(([now, v1, cap], i) => ({ cap, now: jpg(join(ROOT, s.dir, now), `${s.id}_hero${i}`, 1920), v1: jpg(join(ROOT, s.dir, v1), `${s.id}_v1_${i}`, 1920) })),+ r2: s.r2.map(([f, cap], i) => ({ cap, src: jpg(join(ROOT, s.dir, f), `${s.id}_r2_${i}`, 1200) })),+ r1: s.r1.map(([f, cap], i) => ({ cap, src: jpg(join(ROOT, s.dir, f), `${s.id}_p${i}`, 1200) })),+ };+});++// ---------------------------------------------------------------- markup+const shotCard = (sh, id) => sh.ready+ ? `<figure class="shot"><video src="${sh.video}" poster="${sh.poster}" controls muted loop playsinline preload="none"></video>+ <figcaption><b><span>${esc(sh.code)}</span>${esc(sh.label)}</b><small>${sh.meta.map(esc).join(" · ")}</small></figcaption></figure>`+ : `<figure class="shot pending"><div class="ph"><span>In the render queue</span></div>+ <figcaption><b><span>${esc(sh.code)}</span>${esc(sh.label)}</b><small>${sh.meta.map(esc).join(" · ")}</small></figcaption></figure>`;++const assetCard = (a) => {+ const tile = (i, label, win, missing) => `<div class="tile${win ? " win" : ""}${missing ? " none" : ""}" data-i="${i}"><i data-bg="${a.src}"></i><span>${label}${win ? " · picked" : ""}</span>${missing ? "<em>no mesh</em>" : ""}</div>`;+ return `<article class="asset" data-model="${a.used ? a.model : "unused"}" data-name="${esc(a.name)}" data-src="${a.src}">+ <header><h4>${esc(a.name)}</h4><span class="tag ${a.used ? (a.model === "meshy" ? "m" : "t") : "u"}">${a.used ? MODEL[a.model] : "Not used"}</span></header>+ <div class="tiles">${tile(0, "Reference", false, false)}${tile(1, "Tripo H3.1", a.used && a.model === "tripo-h31", !a.has.t)}${tile(3, "Meshy 7.1", a.used && a.model === "meshy", !a.has.m)}</div>+ <p>${esc(a.why)}${a.flags.length ? ` <span class="flags">${a.flags.map(esc).join(" · ")}</span>` : ""}</p>+ </article>`;+};++const strip = (items, mark) => items.map((p, i) => `<figure><img src="${p.src}" alt="${esc(p.cap)}" loading="lazy" data-zoom><figcaption><span>${mark(i)}</span>${esc(p.cap)}</figcaption></figure>`).join("");++const sceneView = (s) => {+ const hand = [...s.shots.filter((x) => x.handheld), s.clip], cine = s.shots.filter((x) => !x.handheld);+ const readyCount = s.shots.filter((x) => x.ready).length;+ return `+<section class="view" id="v-${s.id}" data-view="${s.id}" hidden>+ <header class="shead">+ <div><p class="kicker">${s.kicker}</p><h2>${esc(s.title)}</h2><p class="lede">${esc(s.blurb)}</p></div>+ <dl class="facts">+ <div><dt>Shots</dt><dd>${readyCount}<small>/${s.shots.length}</small></dd></div>+ <div><dt>Props placed</dt><dd>${s.n["tripo-h31"] + s.n.meshy}</dd></div>+ <div><dt>Tripo H3.1</dt><dd class="t">${s.n["tripo-h31"]}</dd></div>+ <div><dt>Meshy 7.1</dt><dd class="m">${s.n.meshy}</dd></div>+ <div><dt>fal spend</dt><dd>$${s.spend.toFixed(0)}</dd></div>+ </dl>+ </header>+ <nav class="sub" aria-label="${esc(s.short)} sections"><a href="#${s.id}-shots">Shots</a><a href="#${s.id}-stills">Stills</a><a href="#${s.id}-assets">Assets <small>${s.assets.length}</small></a><a href="#${s.id}-process">Process</a></nav>++ <section id="${s.id}-shots" class="block">+ <h3>Handheld <small>walkthroughs — an operator moving through the room</small></h3>+ <div class="shots">${hand.map((x) => shotCard(x, s.id)).join("")}</div>+ <h3>Cinematic <small>camera rig — lens, focus pulls, dollies, dolly zooms · 2.39</small></h3>+ <div class="shots">${cine.map((x) => shotCard(x, s.id)).join("")}</div>+ </section>++ <section id="${s.id}-stills" class="block">+ <h3>Stills <small>drag to compare with round 1</small></h3>+ ${s.heroes.map((h) => `<figure class="ba" style="--x:50%">+ <img src="${h.now}" alt="${esc(h.cap)}" loading="lazy" data-zoom>+ <img class="before" src="${h.v1}" alt="Round 1 version" loading="lazy">+ <input type="range" min="0" max="100" value="50" aria-label="Compare with round 1">+ <span class="lab l">Round 1</span><span class="lab r">Round 2</span>+ <figcaption>${esc(h.cap)}</figcaption></figure>`).join("")}+ </section>++ <section id="${s.id}-assets" class="block assets-block">+ <h3>Assets <small>every prop generated by both Tripo H3.1 and Meshy 7.1 from one GPT Image 2.5 reference</small></h3>+ <div class="controls">+ <div class="seg" role="group" aria-label="Filter by winner">+ <button data-f="all" aria-pressed="true">All <small>${s.assets.length}</small></button>+ <button data-f="tripo-h31" aria-pressed="false">Tripo wins <small>${s.n["tripo-h31"]}</small></button>+ <button data-f="meshy" aria-pressed="false">Meshy wins <small>${s.n.meshy}</small></button>+ <button data-f="unused" aria-pressed="false">Not used <small>${s.n.unused}</small></button>+ </div>+ <div class="seg" role="group" aria-label="Render view">+ <button data-v="beauty" aria-pressed="true">Textured</button><button data-v="clay" aria-pressed="false">Clay</button>+ </div>+ <input type="search" placeholder="Find a prop" aria-label="Find a prop">+ </div>+ <div class="agrid">${s.assets.map(assetCard).join("")}</div>+ </section>++ <section id="${s.id}-process" class="block">+ <h3>Round 2 <small>coarse → fine dressing passes, grime, effects</small></h3>+ <div class="strip">${strip(s.r2, (i) => String(i + 1).padStart(2, "0"))}</div>+ <h3>Round 1 <small>the original build</small></h3>+ <div class="strip">${strip(s.r1, (i) => String(i + 1).padStart(2, "0"))}</div>+ <div class="weak"><h3>Still weak</h3><ul>${s.weak.map((w) => `<li>${esc(w)}</li>`).join("")}</ul></div>+ </section>+</section>`;+};++const all = totals.meshy + totals["tripo-h31"];+const spendTotal = built.reduce((t, s) => t + s.spend, 0) + spendShared;+const overview = `+<section class="view" id="v-overview" data-view="overview">+ <p class="lede big">Two late-night Tokyo interiors built end to end by two agents in parallel. Rooms, counters and fixtures are scripted in Blender; every prop was generated by both Tripo H3.1 and Meshy 7.1 from a GPT Image 2.5 reference, and the better mesh was kept.</p>+ <ol class="pipe"><li>concept</li><li>scripted shell</li><li>refs per prop</li><li>Tripo + Meshy</li><li>pick & script-repair</li><li>dress big → small</li><li>grime</li><li>night light + haze</li><li>camera rig</li><li>grade</li></ol>+ <div class="cards">${built.map((s) => `+ <a class="scard" href="#${s.id}">+ <img src="${s.heroes[0].now}" alt="${esc(s.heroes[0].cap)}">+ <div><p class="kicker">${s.kicker}</p><h2>${esc(s.title)}</h2>+ <p class="mono">${s.shots.filter((x) => x.ready).length} shots · ${s.n["tripo-h31"] + s.n.meshy} props · $${s.spend.toFixed(0)} fal</p></div>+ </a>`).join("")}+ </div>+ <div class="verdicts">+ <div class="verdict"><p class="kicker">Generator verdict</p><p><strong>Across ${all} placed props: Meshy ${totals.meshy}, Tripo H3.1 ${totals["tripo-h31"]}.</strong> Tripo keeps the big hard-surface heroes where real geometry matters (oscilloscope, stockpots, ticket machine, cash register). Meshy wins most small consumer items because its textures and printed labels are sharper. Glass came back opaque from both and was rebuilt by script.</p></div>+ <div class="verdict"><p class="kicker">Round 2</p><p>Both rooms re-dressed in coarse → fine passes, with grime and grease, Mantaflow steam in the ramen kitchen, relit streets, a validator that catches mesh collisions, real brands painted out or regenerated, and a camera rig with per-shot lenses, focus pulls and dolly zooms. Handheld walkthroughs are rendering now. Total fal spend so far: <strong>$${spendTotal.toFixed(0)}</strong>.</p></div>+ </div>+</section>`;++const DARK = "--bg:#0f0e0d;--fg:#ece8df;--mute:#9a9385;--line:#2a2724;--card:#171513;--accent:#ff6a48;--tripo:#8fb8e4;--meshy:#f0a868;--tbg:#1b2733;--mbg:#33241a;--ubg:#26231f;--tile:#1d1b19;color-scheme:dark";+const html = `<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">+<title>Night Shops</title>+<meta name="claude:viewport-fit-sides" content="cover">+<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wght@400;600;800&family=IBM+Plex+Mono:wght@400;500&display=swap">+<style>+:root{--bg:#f3f1ec;--fg:#1b1a18;--mute:#6b665c;--line:#d9d4c8;--card:#fbfaf6;--accent:#c2361f;--tripo:#2c5d8f;--meshy:#a3591a;--tbg:#e3ecf5;--mbg:#f6e8da;--ubg:#ebe7de;--tile:#1d1b19}+@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){${DARK}}}+:root[data-theme="dark"]{${DARK}}+body{background:var(--bg);color:var(--fg);font:15px/1.55 Archivo,system-ui,sans-serif}+body::before{content:"";position:fixed;inset:0 0 auto;height:env(safe-area-inset-top,0px);z-index:10;background:var(--bg)}+.wrap{max-width:1280px;margin:0 auto;padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:28px 80px}+.mono,.kicker,dt,figcaption span,.tag,.seg,.sub,.tile span,h3 small,.flags{font-family:"IBM Plex Mono",ui-monospace,monospace}+h1{font-size:clamp(30px,5vw,52px);font-weight:800;letter-spacing:-.02em;line-height:1;margin:0;text-wrap:balance}+h2{font-size:clamp(24px,3.4vw,38px);font-weight:800;letter-spacing:-.01em;margin:0;line-height:1.1;text-wrap:balance}+h3{font-size:13px;text-transform:uppercase;letter-spacing:.12em;color:var(--fg);margin:40px 0 14px;font-weight:600;display:flex;flex-wrap:wrap;gap:4px 12px;align-items:baseline}+h3 small{color:var(--mute);letter-spacing:0;text-transform:none;font-weight:400;font-size:12px}+.lede{max-width:66ch;color:var(--mute);margin:10px 0 0}.lede.big{font-size:17px;margin:0}+.kicker{font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--accent);margin:0 0 6px}+/* top bar */+.top{position:sticky;top:env(safe-area-inset-top,0px);z-index:5;background:var(--bg);border-bottom:1px solid var(--line);margin-bottom:28px}+.top .in{max-width:1280px;margin:0 auto;padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:14px;display:flex;flex-wrap:wrap;gap:12px 28px;align-items:center;justify-content:space-between}+.tabs{display:flex;flex-wrap:wrap;gap:4px}+.tabs a{color:var(--mute);text-decoration:none;padding:7px 12px;border-radius:6px;font-weight:600;font-size:14px}+.tabs a[aria-current="page"]{background:var(--fg);color:var(--bg)}+.tabs a:not([aria-current="page"]):hover{color:var(--fg)}+.tabs a.ext{font-weight:400}+@media (max-width:700px){.top{position:static}.top .kicker{display:none}.block{scroll-margin-top:16px}}+/* overview */+.pipe{display:flex;flex-wrap:wrap;gap:6px;margin:18px 0 0;padding:0;list-style:none;font:12px "IBM Plex Mono",monospace;color:var(--mute)}+.pipe li:not(:last-child)::after{content:"→";margin-left:6px;color:var(--line)}+.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,460px),1fr));gap:20px;margin-top:28px}+.scard{display:grid;gap:14px;color:inherit;text-decoration:none;background:var(--card);border:1px solid var(--line);border-radius:8px;overflow:hidden;padding-bottom:18px}+.scard img{width:100%;aspect-ratio:16/9;object-fit:cover;display:block;max-width:100%}+.scard>div{padding-inline:18px}.scard .mono{font-size:12px;color:var(--mute);margin:8px 0 0}+.scard:hover{border-color:var(--accent)}+.verdicts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,440px),1fr));gap:20px;margin-top:20px}+.verdict{background:var(--card);border:1px solid var(--line);border-left:3px solid var(--accent);padding:16px 18px;border-radius:6px}+.verdict p{margin:0}.verdict .kicker{margin-bottom:8px}+/* scene header */+.shead{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:end;gap:20px}+.shead>div{min-width:0;flex:1 1 420px}+.facts{display:flex;flex-wrap:wrap;gap:22px;margin:0}+dt{font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--mute)}dd{margin:0;font-size:26px;font-weight:800}+dd small{font-size:14px;color:var(--mute);font-weight:400}dd.t{color:var(--tripo)}dd.m{color:var(--meshy)}+.sub{display:flex;flex-wrap:wrap;gap:6px;margin:26px 0 0;font-size:13px}+.sub a{color:var(--fg);text-decoration:none;border:1px solid var(--line);padding:6px 12px;border-radius:999px}+.sub a:hover{border-color:var(--accent)}.sub small{color:var(--mute)}+.block{scroll-margin-top:150px}+figure{margin:0}+figcaption{font-size:13px;color:var(--mute);padding-top:8px}+figcaption span{color:var(--accent);margin-right:8px}+/* shots */+.shots{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,480px),1fr));gap:22px 18px}+.shot video,.ph{width:100%;display:block;border-radius:6px;background:#000;aspect-ratio:2.39;max-width:100%}+.shot figcaption{display:grid;gap:2px}.shot b{color:var(--fg);font-weight:600}+.shot small{font:12px "IBM Plex Mono",monospace}+.ph{display:grid;place-items:center;background:repeating-linear-gradient(135deg,var(--card) 0 10px,var(--bg) 10px 20px);border:1px dashed var(--line)}+.ph span{font:12px "IBM Plex Mono",monospace;color:var(--mute)}+/* before / after */+.ba{position:relative;margin-bottom:26px}+.ba img{width:100%;display:block;border-radius:6px;aspect-ratio:16/9;object-fit:cover;max-width:100%}+.ba .before{position:absolute;inset:0;clip-path:inset(0 calc(100% - var(--x)) 0 0);height:auto;pointer-events:none}+.ba::after{content:"";position:absolute;top:0;left:var(--x);width:2px;margin-left:-1px;background:#fff;opacity:.85;pointer-events:none;aspect-ratio:auto;height:calc(100% - 2.6em)}+.ba input{position:absolute;inset:0 0 auto;width:100%;aspect-ratio:16/9;margin:0;opacity:0;cursor:ew-resize}+.ba .lab{position:absolute;top:10px;font:11px "IBM Plex Mono",monospace;color:#fff;background:rgba(0,0,0,.55);padding:3px 7px;border-radius:3px;pointer-events:none}+.ba .l{left:10px}.ba .r{right:10px}+/* assets */+.controls{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:16px}+.seg{display:inline-flex;flex-wrap:wrap;border:1px solid var(--line);border-radius:6px;overflow:hidden;font-size:12px}+.seg button{all:unset;cursor:pointer;padding:7px 11px;color:var(--mute)}+.seg button small{opacity:.7}+.seg button[aria-pressed="true"]{background:var(--fg);color:var(--bg)}+.seg button:focus-visible,.controls input:focus-visible{outline:2px solid var(--accent);outline-offset:1px}+.controls input{font:inherit;font-size:13px;padding:7px 10px;border:1px solid var(--line);border-radius:6px;background:var(--card);color:var(--fg);min-width:0;flex:1 1 160px;max-width:260px}+.agrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,330px),1fr));gap:14px}+.asset{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:12px;display:grid;gap:10px;align-content:start;cursor:zoom-in}+.asset:hover{border-color:var(--mute)}+.asset header{display:flex;justify-content:space-between;align-items:start;gap:8px}+.asset h4{margin:0;font-size:15px;font-weight:600;text-transform:capitalize;min-width:0}+.asset p{margin:0;font-size:13px;color:var(--mute);line-height:1.45}+.flags{display:block;margin-top:4px;font-size:11px;color:var(--accent)}+.tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}+.tile{position:relative;border-radius:5px;overflow:hidden;background:var(--tile);outline:2px solid transparent;outline-offset:-2px}+.tile i{display:block;aspect-ratio:1;background-size:500% 100%;background-repeat:no-repeat;background-position:var(--p,0) 0}+.tile[data-i="1"] i{--p:25%}.tile[data-i="3"] i{--p:75%}+.clay .tile[data-i="1"] i{--p:50%}.clay .tile[data-i="3"] i{--p:100%}+.tile span{position:absolute;left:0;right:0;bottom:0;font-size:10px;padding:3px 5px;color:#fff;background:linear-gradient(transparent,rgba(0,0,0,.7));white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.tile.win{outline-color:var(--accent)}+.tile.win span{background:var(--accent)}+.tile.none em{position:absolute;inset:0;display:grid;place-items:center;font:11px "IBM Plex Mono",monospace;color:#8a8379;font-style:normal}+.tag{font-size:11px;padding:2px 7px;border-radius:3px;white-space:nowrap}+.tag.t{background:var(--tbg);color:var(--tripo)}.tag.m{background:var(--mbg);color:var(--meshy)}.tag.u{background:var(--ubg);color:var(--mute)}+.asset[hidden]{display:none}+/* process */+.strip{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,280px),1fr));gap:14px}+.strip img{width:100%;border-radius:4px;display:block;aspect-ratio:16/9;object-fit:cover;cursor:zoom-in;max-width:100%}+.weak ul{margin:0;padding-left:18px;display:grid;gap:8px;max-width:80ch}+dialog{border:0;padding:0;background:transparent;max-width:96vw}dialog::backdrop{background:rgba(0,0,0,.9)}+dialog img{max-width:96vw;max-height:88vh;display:block;margin:auto}+dialog p{color:#ddd;font:12px "IBM Plex Mono",monospace;text-align:center;margin:10px 0 0}+</style>+<div class="top"><div class="in">+ <div><p class="kicker" style="margin:0 0 2px">Blender 5.0 · Cycles · GPT Image 2.5 · Tripo H3.1 + Meshy 7.1</p><h1>Night Shops</h1></div>+ <nav class="tabs" aria-label="Scenes"><a href="#overview">Overview</a>${built.map((s) => `<a href="#${s.id}">${esc(s.short)}</a>`).join("")}<a class="ext" href="https://claude.ai/artifact/5mk8VH8hkEbYfucp57z3FJ">Generator test ↗</a></nav>+</div></div>+<div class="wrap">+${overview}+${built.map(sceneView).join("")}+</div>+<dialog id="lb"><img alt=""><p></p></dialog>+<script>+const views=[...document.querySelectorAll(".view")];+function route(){+ const h=location.hash.slice(1)||"overview";+ const scene=h.split("-")[0];+ const v=views.find(x=>x.dataset.view===scene)||views[0];+ views.forEach(x=>x.hidden=x!==v);+ document.querySelectorAll(".tabs a").forEach(a=>a.getAttribute("href")==="#"+v.dataset.view?a.setAttribute("aria-current","page"):a.removeAttribute("aria-current"));+ if(h.includes("-")){const t=document.getElementById(h);if(t)requestAnimationFrame(()=>t.scrollIntoView())}else scrollTo(0,0);+ v.querySelectorAll("video").forEach(()=>{});+ lazy(v);+}+// sprite backgrounds load only when a card scrolls near the viewport+const io=new IntersectionObserver(es=>es.forEach(e=>{if(e.isIntersecting){const i=e.target;i.style.backgroundImage="url("+i.dataset.bg+")";io.unobserve(i)}}),{rootMargin:"400px"});+function lazy(v){v.querySelectorAll(".tile i[data-bg]").forEach(i=>{if(!i.style.backgroundImage)io.observe(i)})}+addEventListener("hashchange",route);route();+// pause other videos when one plays+document.addEventListener("play",e=>document.querySelectorAll("video").forEach(v=>v!==e.target&&v.pause()),true);+// before/after+document.querySelectorAll(".ba input").forEach(r=>r.addEventListener("input",()=>r.parentElement.style.setProperty("--x",r.value+"%")));+// asset filters+document.querySelectorAll(".assets-block").forEach(b=>{+ let f="all",q="";+ const cards=[...b.querySelectorAll(".asset")],grid=b.querySelector(".agrid");+ const apply=()=>{cards.forEach(c=>c.hidden=!((f==="all"||c.dataset.model===f)&&c.dataset.name.includes(q)));lazy(b)};+ b.querySelectorAll("[data-f]").forEach(x=>x.onclick=()=>{f=x.dataset.f;b.querySelectorAll("[data-f]").forEach(y=>y.setAttribute("aria-pressed",y===x));apply()});+ b.querySelectorAll("[data-v]").forEach(x=>x.onclick=()=>{grid.classList.toggle("clay",x.dataset.v==="clay");b.querySelectorAll("[data-v]").forEach(y=>y.setAttribute("aria-pressed",y===x))});+ b.querySelector("input[type=search]").oninput=e=>{q=e.target.value.trim().toLowerCase();apply()};+});+// lightbox: stills and process images, or a prop's full sheet+const lb=document.getElementById("lb"),li=lb.querySelector("img"),lp=lb.querySelector("p");+document.addEventListener("click",e=>{+ const z=e.target.closest("[data-zoom]"),a=e.target.closest(".asset");+ if(z&&!z.closest(".ba")){li.src=z.src;lp.textContent=z.alt;lb.showModal()}+ else if(a){li.src=a.dataset.src;lp.textContent=a.dataset.name+" — reference · Tripo textured · Tripo clay · Meshy textured · Meshy clay";lb.showModal()}+});+lb.addEventListener("click",()=>lb.close());+</script>`;+writeFileSync(join(OUT, "index.html"), html);+const files = readdirSync(IMG);+console.log("ok", totals, `${files.length} img files`, `${(files.reduce((t, f) => t + statSync(join(IMG, f)).size, 0) / 1e6).toFixed(1)} MB`);diff --git a/pipeline/env.sh b/pipeline/env.shnew file mode 100644index 0000000..dc2db48--- /dev/null+++ b/pipeline/env.sh@@ -0,0 +1,20 @@+# Sourced by every shell script: finds the repo root, Blender and ffmpeg.+# . pipeline/env.sh (from the repo root)+# Override any of them in your shell: BLENDER=/path/to/blender FFMPEG=/path/to/ffmpeg+ANYSCENE_ROOT_POSIX="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+# Blender and ffmpeg on Windows want C:/... paths, not Git Bash's /c/...+ROOT_ABS="$(cd "$ANYSCENE_ROOT_POSIX" && (pwd -W 2>/dev/null || pwd))"+export ANYSCENE_ROOT="$ROOT_ABS"++if [ -z "$BLENDER" ]; then+ for c in blender \+ "/c/Program Files/Blender Foundation/Blender 5.0/blender.exe" \+ "/Applications/Blender.app/Contents/MacOS/Blender"; do+ if command -v "$c" >/dev/null 2>&1 || [ -x "$c" ]; then BLENDER="$c"; break; fi+ done+fi+export BLENDER FFMPEG="${FFMPEG:-ffmpeg}"+# Short names the scene scripts use.+B="$BLENDER"+FF="$FFMPEG"+[ -n "$B" ] || echo "env.sh: Blender not found; set BLENDER=/path/to/blender" >&2diff --git a/pipeline/gpu_run.sh b/pipeline/gpu_run.shnew file mode 100644index 0000000..473af0c--- /dev/null+++ b/pipeline/gpu_run.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+# Run a command holding the shared GPU, first come first served, so parallel scene builds never render in Cycles at once+# (16 GB card) and nobody can re-grab the GPU ahead of a caller that is already waiting.+# pipeline/gpu_run.sh "$B" -b ...+# Each caller drops a ticket named <epoch-ns>_<pid> in .gpu.queue and runs once its ticket sorts first.+# Tickets whose process is gone, or older than 90 minutes, are cleared.+Q="$(dirname "$0")/../.gpu.queue"+mkdir -p "$Q"+TICKET="$Q/$(date +%s%N)_$$"+echo "$(date -Is) $*" > "$TICKET"+trap 'rm -f "$TICKET"' EXIT+while :; do+ for t in "$Q"/*; do+ [ "$t" = "$TICKET" ] && continue+ pid="${t##*_}"+ if ! kill -0 "$pid" 2>/dev/null || [ -n "$(find "$t" -maxdepth 0 -mmin +90 2>/dev/null)" ]; then+ echo "gpu_run: clearing stale ticket $(basename "$t")" >&2+ rm -f "$t"+ fi+ done+ [ "$(ls "$Q" | sort | head -n1)" = "$(basename "$TICKET")" ] && break+ sleep 5+done+"$@"diff --git a/pipeline/lan_gallery.py b/pipeline/lan_gallery.pynew file mode 100644index 0000000..d5c5f96--- /dev/null+++ b/pipeline/lan_gallery.py@@ -0,0 +1,137 @@+"""Live LAN gallery of both scenes: stills, process passes and cinematic shots, rebuilt on every page load.+ python pipeline/lan_gallery.py [port] -> http://<lan-ip>:<port>/+Serves the project folder read-only (GET only); new renders show up on refresh."""+import html, os, socket, sys, time+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import quote++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8765+SCENES = ["repair", "ramen"]+++def files(rel, exts, recursive=False, skip=()):+ base = os.path.join(ROOT, rel)+ out = []+ if not os.path.isdir(base):+ return out+ walker = os.walk(base) if recursive else [(base, [], os.listdir(base))]+ for d, _, names in walker:+ if any(s in d.replace("\\", "/") for s in skip):+ continue+ for n in names:+ if n.lower().endswith(exts):+ p = os.path.join(d, n)+ out.append((os.path.relpath(p, ROOT).replace("\\", "/"), os.path.getmtime(p)))+ return sorted(out, key=lambda x: x[0])+++def ago(t):+ m = int((time.time() - t) // 60)+ return f"{m} min ago" if m < 120 else time.strftime("%b %d %H:%M", time.localtime(t))+++def tile(rel, t, kind):+ url = "/" + quote(rel)+ name = html.escape(rel.split("/")[-1])+ media = (f'<video src="{url}" controls muted loop playsinline preload="metadata"></video>' if kind == "v"+ else f'<a href="{url}" target="_blank"><img src="{url}" loading="lazy"></a>')+ return f'<figure>{media}<figcaption>{name}<span>{ago(t)}</span></figcaption></figure>'+++def section(title, items, kind, cls=""):+ if not items:+ return ""+ return f'<h3>{title} <small>{len(items)}</small></h3><div class="grid {cls}">' + "".join(tile(r, t, kind) for r, t in items) + "</div>"+++def page():+ body = ""+ for s in SCENES:+ out = f"scenes/{s}/out"+ shots = [f for f in files(f"{out}/shots", (".mp4",), True) if "/frames/" not in f[0]]+ graded = [f for f in shots if "graded" in f[0]]+ shots = graded or shots+ heroes = [f for f in files(out, (".png",)) if f[0].split("/")[-1].startswith("hero")]+ process = files(out, (".png",)) if s == "repair" else files(f"{out}/process", (".png",))+ process = [f for f in process if not f[0].split("/")[-1].startswith("hero")]+ clips = files(out, (".mp4",))+ body += f'<section><h2>{s.title()} shop</h2>'+ body += section("Cinematic shots", sorted(shots, key=lambda x: -x[1]), "v", "big")+ body += section("Hero stills", sorted(heroes, key=lambda x: -x[1]), "i", "big")+ body += section("Clips", clips, "v")+ body += section("Process", process, "i")+ body += "</section>"+ return f"""<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">+<title>Night Shops — live</title><style>+body{{margin:0;background:#0f0e0d;color:#ece8df;font:14px/1.5 system-ui,sans-serif;padding:24px max(16px,3vw) 60px}}+h1{{margin:0 0 4px;font-size:28px}}h2{{font-size:24px;margin:40px 0 0;border-top:1px solid #2a2724;padding-top:24px}}+h3{{font-size:12px;letter-spacing:.12em;text-transform:uppercase;color:#9a9385;margin:24px 0 10px}}small{{color:#ff5a3c}}+.grid{{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px}}.big{{grid-template-columns:repeat(auto-fill,minmax(560px,1fr))}}+@media(max-width:640px){{.big{{grid-template-columns:1fr}}}}+figure{{margin:0;min-width:0}}img,video{{width:100%;display:block;background:#000;border-radius:3px}}+figcaption{{font:12px ui-monospace,monospace;color:#9a9385;padding-top:6px;display:flex;justify-content:space-between;gap:8px;word-break:break-all}}+p{{color:#9a9385;margin:0}}</style>+<h1>Night Shops — live renders</h1><p>Rebuilt on each refresh · newest first · {time.strftime('%H:%M:%S')}</p>{body}"""+++class H(SimpleHTTPRequestHandler):+ def __init__(self, *a, **k):+ super().__init__(*a, directory=ROOT, **k)++ def do_GET(self):+ if self.path in ("/", "/index.html"):+ b = page().encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(b)))+ self.end_headers()+ self.wfile.write(b)+ return+ rng = self.headers.get("Range")+ path = self.translate_path(self.path)+ if not rng or not os.path.isfile(path):+ return super().do_GET()+ # Byte ranges, so video seeks and Safari/iOS playback work.+ size = os.path.getsize(path)+ a, _, b = rng.replace("bytes=", "").partition("-")+ start = int(a) if a else max(0, size - int(b))+ end = min(int(b), size - 1) if a and b else size - 1+ self.send_response(206)+ self.send_header("Content-Type", self.guess_type(path))+ self.send_header("Accept-Ranges", "bytes")+ self.send_header("Content-Range", f"bytes {start}-{end}/{size}")+ self.send_header("Content-Length", str(end - start + 1))+ self.end_headers()+ with open(path, "rb") as f:+ f.seek(start)+ left = end - start + 1+ try:+ while left > 0:+ chunk = f.read(min(1 << 20, left))+ if not chunk:+ break+ self.wfile.write(chunk)+ left -= len(chunk)+ except (ConnectionResetError, BrokenPipeError):+ pass++ def list_directory(self, path):+ self.send_error(404)++ def log_message(self, *a):+ pass+++def lan_ip():+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ s.connect(("10.255.255.255", 1))+ return s.getsockname()[0]+ finally:+ s.close()+++if __name__ == "__main__":+ print(f"serving http://{lan_ip()}:{PORT}/", flush=True)+ ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever()diff --git a/pipeline/render_compare.py b/pipeline/render_compare.pynew file mode 100644index 0000000..9f6ed45--- /dev/null+++ b/pipeline/render_compare.py@@ -0,0 +1,202 @@+"""Head-to-head renders of generated props: same studio light and camera fit for every model.++blender -b --factory-startup --python pipeline/render_compare.py -- assets/gen out/compare+For every assets/gen/<model>/<prop>/model.glb writes out/compare/<model>/<prop>_{beauty,clay}.png + stats.json.+"""+import json+import math+import os+import sys++import bpy+from mathutils import Vector++ROOT, OUT = map(os.path.abspath, sys.argv[sys.argv.index("--") + 1:][:2])+HDRI = bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")+RES = 900+PROBE = bool(os.environ.get("PROBE"))+# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.+_yaw_path = os.path.join(OUT, "yaw.json")+YAW = json.load(open(_yaw_path)) if os.path.exists(_yaw_path) else {}+++def reset():+ bpy.ops.wm.read_factory_settings(use_empty=True)+ sc = bpy.context.scene+ sc.render.engine = "CYCLES"+ prefs = bpy.context.preferences.addons["cycles"].preferences+ prefs.compute_device_type = "OPTIX"+ prefs.get_devices()+ for d in prefs.devices:+ d.use = d.type == "OPTIX"+ sc.cycles.device = "GPU"+ sc.cycles.samples = 96+ sc.cycles.use_denoising = True+ sc.render.resolution_x = sc.render.resolution_y = RES+ sc.render.film_transparent = False+ sc.view_settings.view_transform = "AgX"+ sc.view_settings.look = "AgX - Medium High Contrast"+ world = bpy.data.worlds.new("w")+ sc.world = world+ world.use_nodes = True+ nt = world.node_tree+ env = nt.nodes.new("ShaderNodeTexEnvironment")+ env.image = bpy.data.images.load(HDRI)+ bg = nt.nodes["Background"]+ bg.inputs["Strength"].default_value = 0.6+ nt.links.new(env.outputs["Color"], bg.inputs["Color"])+ return sc+++def add_light(name, loc, 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(loc)).to_track_quat("-Z", "Y").to_euler() # area lights shine along -Z+++def import_glb(path):+ before = set(bpy.data.objects)+ bpy.ops.import_scene.gltf(filepath=path)+ meshes = [o for o in bpy.data.objects if o not in before and o.type == "MESH"]+ return meshes+++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 stats(objs, real_size):+ tris = verts = 0+ images = {}+ for o in objs:+ me = o.data+ me.calc_loop_triangles()+ tris += len(me.loop_triangles)+ verts += len(me.vertices)+ for slot in o.material_slots:+ if slot.material and slot.material.use_nodes:+ for n in slot.material.node_tree.nodes:+ if n.type == "TEX_IMAGE" and n.image:+ out = [l.to_socket.name for l in n.outputs["Color"].links]+ images[n.image.name] = {"size": list(n.image.size), "feeds": out}+ return {"tris": tris, "verts": verts, "objects": len(objs), "images": images, "size_m": [round(v, 3) for v in real_size]}+++def clay_wire(objs):+ m = bpy.data.materials.new("clay")+ m.use_nodes = True+ nt = m.node_tree+ bsdf = nt.nodes["Principled BSDF"]+ bsdf.inputs["Base Color"].default_value = (0.55, 0.55, 0.55, 1)+ bsdf.inputs["Roughness"].default_value = 0.6+ wire = nt.nodes.new("ShaderNodeWireframe")+ wire.use_pixel_size = True+ wire.inputs["Size"].default_value = 0.35+ mix = nt.nodes.new("ShaderNodeMix")+ mix.data_type = "RGBA"+ mix.inputs["A"].default_value = (0.55, 0.55, 0.55, 1)+ mix.inputs["B"].default_value = (0.08, 0.12, 0.2, 1)+ nt.links.new(wire.outputs["Fac"], mix.inputs["Factor"])+ nt.links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])+ for o in objs:+ o.data.materials.clear()+ o.data.materials.append(m)+++def render_one(glb, out_prefix):+ sc = reset()+ objs = import_glb(glb)+ lo, hi = bounds(objs)+ real = hi - lo+ # Normalize: centre on origin, rest on the floor, largest dimension 1 m (framing only; real size goes in stats).+ s = 1.0 / max(real)+ root = bpy.data.objects.new("root", None)+ sc.collection.objects.link(root)+ for o in [o for o in bpy.data.objects if o.parent is None and o is not root]:+ o.parent = root+ c = (lo + hi) / 2+ root.scale = (s, s, s)+ root.location = (-c.x * s, -c.y * s, -lo.z * s)+ bpy.context.view_layer.update()+ lo, hi = bounds(objs)+ centre = (lo + hi) / 2+ radius = (hi - lo).length / 2++ # Shadow catcher-ish floor.+ bpy.ops.mesh.primitive_plane_add(size=20)+ floor = bpy.context.object+ fm = bpy.data.materials.new("floor")+ fm.use_nodes = True+ fm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.32, 0.32, 0.33, 1)+ fm.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.8+ floor.data.materials.append(fm)++ add_light("key", (2.2, -2.6, 3.0), 260, 1.6)+ add_light("fill", (-3.0, -1.5, 1.6), 70, 2.5, (0.85, 0.9, 1.0))+ add_light("rim", (-1.0, 3.0, 2.5), 160, 1.2)++ cam_d = bpy.data.cameras.new("cam")+ cam_d.lens = 70+ cam = bpy.data.objects.new("cam", cam_d)+ sc.collection.objects.link(cam)+ sc.camera = cam+ fov = cam_d.angle+ dist = radius / math.sin(fov / 2) * 1.02++ def shoot(az_deg, el_deg, path):+ az, el = math.radians(az_deg), math.radians(el_deg)+ d = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))+ cam.location = centre + d * dist+ cam.rotation_euler = (centre - cam.location).to_track_quat("-Z", "Y").to_euler()+ sc.render.filepath = path+ bpy.ops.render.render(write_still=True)++ st = stats(objs, real)+ if PROBE: # four cardinal views to find which way a generator's "front" faces+ sc.render.resolution_x = sc.render.resolution_y = 360+ sc.cycles.samples = 16+ for az in (0, 90, 180, 270):+ shoot(az, 15, f"{out_prefix}_az{az:03d}.png")+ return st+ yaw = YAW.get(os.path.basename(os.path.dirname(out_prefix)), 0)+ shoot(yaw - 30, 18, out_prefix + "_beauty.png")+ shoot(yaw + 150, 22, out_prefix + "_back.png")+ clay_wire(objs)+ shoot(yaw - 30, 18, out_prefix + "_clay.png")+ return st+++def main():+ allstats = {}+ for model in sorted(os.listdir(ROOT)):+ for prop in sorted(os.listdir(os.path.join(ROOT, model))):+ glb = os.path.join(ROOT, model, prop, "model.glb")+ if not os.path.exists(glb):+ continue+ od = os.path.join(OUT, model)+ os.makedirs(od, exist_ok=True)+ prefix = os.path.join(od, prop)+ done = prefix + ("_az270.png" if PROBE else "_clay.png")+ if os.path.exists(done) and os.path.getmtime(done) > os.path.getmtime(glb):+ print("skip", model, prop)+ continue+ print("render", model, prop, flush=True)+ try:+ allstats.setdefault(model, {})[prop] = render_one(glb, prefix)+ except Exception as e: # keep going; a broken GLB is itself a result+ allstats.setdefault(model, {})[prop] = {"error": repr(e)}+ print("FAILED", model, prop, e, flush=True)+ sp = os.path.join(OUT, "stats.json")+ old = json.load(open(sp)) if os.path.exists(sp) else {}+ for m, d in allstats.items():+ old.setdefault(m, {}).update(d)+ json.dump(old, open(sp, "w"), indent=2)+++main()diff --git a/scenes/tokyo-electronics-repair/NOTES.md b/scenes/tokyo-electronics-repair/NOTES.mdnew file mode 100644index 0000000..fdb85d7--- /dev/null+++ b/scenes/tokyo-electronics-repair/NOTES.md@@ -0,0 +1,77 @@+# Repair shop — notes and gotchas++Pipeline (all scripted, run from the repo root):++1. `scenes/tokyo-electronics-repair/assets.json` — 32 generated props (4 from the head-to-head + 28 new), direct-modelled list.+2. `node scenes/tokyo-electronics-repair/scripts/refs.mjs` — GPT Image 2.5 Sunburst product refs + scene textures (street, tags, labels, poster, calendar, decal).+3. `node scenes/tokyo-electronics-repair/scripts/gen3d.mjs [ids]` — every prop through Tripo H3.1 and Meshy 7.1, 12 at a time; skips existing GLBs.+4. `bash scenes/tokyo-electronics-repair/scripts/compare_ready.sh` + `scenes/tokyo-electronics-repair/scripts/sheet.sh` — same-light renders, review sheets; picks in `picks.json`.+5. `scenes/tokyo-electronics-repair/scripts/prep.py` → `scenes/tokyo-electronics-repair/props/<id>.blend` (front to -Y, real scale, bottom-centre origin, decimate, ≤2K textures).+6. `scenes/tokyo-electronics-repair/scripts/fixes.py` — script repairs: oscilloscope CRT (finds the green screen by ray-casting the front and sampling the+ albedo at the hit UVs, then builds a domed emissive graticule + trace patch), helping-hands lens faces → glass, CRT TV screen → blue glow.+7. `bash scenes/tokyo-electronics-repair/scripts/rebuild.sh 4` — shell → dress (passes 1-4) → validate → lights → cameras → `repair_final.blend`.+8. Renders through `pipeline/gpu_run.sh`: `preview.py` (stills), `render_frames.py` (clip chunks), `grade.sh` (post).++Gotchas:++- glTF imports come in with `rotation_mode = QUATERNION`; setting `rotation_euler` on a copy does nothing until the mode is XYZ.+- A smooth-shaded box without a bevel interpolates normals across its faces; a glass slab built that way refracts like a lens.+- Generated lamp shades are closed meshes: a spot light placed inside the shade is blocked. Put it just under the rim.+- Light panels outside a storefront show up as bright discs through the glass; turn off camera/glossy/transmission visibility.+- Drop rays must start under whatever is above the support (ceiling conduit at 2.65 m, the rack shelf above, the bench drawer+ cabinets); starting on a face lands the prop inside it.+- A float check that starts its ray just below the prop's bottom begins inside a thin bench top and reports the top's thickness.+- The fal queue is shared with the ramen agent; ~10 % of jobs failed with Tripo 504 "downstream service unavailable" or+ ECONNRESET while polling. Re-running gen3d.mjs with the ids recovers them.+- Blender 5.0 compositing is `scene.compositing_node_group` (a CompositorNodeTree with a Group Output); Glare's type is an input socket.+- The CapCut ffmpeg has no glob, drawtext, eq or libx264; it has curves, hue, rgbashift, vignette, noise and h264_nvenc.++## Round 2 (densify, grime, de-brand, cinematic shots)++Build: `bash scenes/tokyo-electronics-repair/scripts/rebuild2.sh C` = shell -> dress.py pass 4 -> validate -> dress2.py A|B|C -> grime.py -> lights.py ->+cameras.py -> `repair_final.blend`. Finals: `bash scenes/tokyo-electronics-repair/scripts/render_round2.sh` (heroes, then every shot in 24-frame chunks+through `scenes/tokyo-electronics-repair/scripts/shoot.sh`, then a graded mp4 per shot). Shots: `scenes/tokyo-electronics-repair/shots.json` (camrig contract).++- fal was locked ("Exhausted balance") for all of round 2. The manifest already holds the 70 round-2 props (pass A/B, `*_nb`+ regenerations, street props, `models` per prop, P2 for tiny ones); `refs.mjs` then `gen3d.mjs` pick them up after a top-up.+ Everything in the round-2 passes is therefore direct-modelled or an instanced/tinted generated prop.+- De-branding without regeneration: `views.py` renders bbox-fitted ortho views; `debrand.py` takes rectangles in those views'+ normalised coordinates, ray-casts them onto the mesh, maps hits to texels per material, dilates, and fills each region with the+ label's ground colour (median of its brighter half) plus grain, and flattens the same texels in the normal map (embossed text+ otherwise survives). A UV-space blur fill smeared neighbouring UV islands into the patch: flat ground colour works better.+ Labels that cover a whole product (spray cans, cup noodle, tissue box) were replaced by generic direct-modelled versions.+ Originals are kept in `scenes/tokyo-electronics-repair/props_prebrand/`.+- `box_blur` via cumulative sums leaves round-off non-zeros everywhere: threshold masks at > 0.01, not > 0.+- Joined direct props get a bottom-centre origin; children parented after a join must be offset by the moved origin.+ `put()` settles by the world bbox minimum, so it works for any origin.+- Per-instance variation: the `grime_layer` group multiplies albedo by Object Info > Color, so `ob.color` tints instances that+ share a mesh (yellowed / dark / cool).+- camrig's final mode doesn't enable a GPU compute device: run it with `--python scenes/tokyo-electronics-repair/scripts/gpu_prefs.py` first+ (`shoot.sh` does), otherwise Cycles renders on the CPU at ~4-5 min/frame instead of ~12-15 s.+- Night look is fragile: each new practical needs the exposure re-checked (round 2 ended at exposure 0.45 with the counter lamp,+ ring lamp, one rack tube, TV glow and the vending spill).+- The AO node inside the grime group costs almost nothing here (profiled: 6.1 s with or without).+- Left racks / under-counter were near black in the first round-2 hero. Fix: a clip-lamp practical on the middle rack post+ (`rack_clip_lamp`, own spot + glow), a soft overhead `rack_bounce` area (11 W, glossy off), a low warm `counter_bounce`+ on the shop side of the counter, rack tube 13 W, exposure 0.95 (+0.5 EV), and the grade lifts blacks (curves start at+ ~0.03 instead of ~0.01). A 45 W bounce plus 1.0 exposure looked like the room lights were on: keep bounce low and let the+ practicals make the contrast.+- s3, s4, s5 and s6 were rendered before that exposure lift (one stop of difference is mostly absorbed by the per-shot grade).+- CRT TVs: scanlines + rolling bar + sin*sin vignette on the no-signal glow (grime.py); a product of triangle waves made+ visible diamond banding.+- camrig focus `obj` uses the bbox centre: for a deep object (oscilloscope) the screen face sits ~15 cm in front of it and is+ slightly soft at 135 mm; use a `pos` on the face instead.+- fal unlocked mid-round (new user-env key). 73 round-2 props through both models: 146 jobs, ~31 failed on the first pass+ (Meshy timeouts, a fal-side 422 "AIModel must be one of ..." from meshy/v7.1, ECONNRESET); two retries recovered all but+ three Meshy jobs (cable_crate, parts_bins, receipts -> H3.1 only).+- Generated winners replace direct stand-ins in `dress2.py` (`SWAPS` by object name, `ADDS` for new ones; names are kept so+ lights/shots that reference them keep working). Debranded originals are swapped for their `*_nb` regenerations through+ `scenes/tokyo-electronics-repair/nb_swap.json`, except the oscilloscope, solder station, helping hands and CRT TV, which carry script fixes.+- Generated props are larger than the stand-ins: `resolve_clashes()` (end of dress2) runs the validator's rules and+ spiral-searches each clashing or floating smaller prop to a clear spot (23 moved, 0 removed).+- Validator now has a real mesh check against fixed furniture (`FURNITURE`, BVH overlap with the prop lifted 3 mm). It caught:+ the work lamp through `drawer_cabinet_2` (the user's bug; lamp re-posed from the front edge right of the scope, arm reaching+ back-left over the helping hands, spot re-aimed at them), the vintage radio through the ceiling conduit drop, the desk fan,+ kerosene heater, portable TV and microwave through the rack shelf above them, the speaker pair through a rack shelf, and the+ wall clock into the back wall (v1 scene). rebuild2.sh now validates after dress2 as well.+- The street had no ground beyond the pavement strip, so a dropped generated vending machine fell to z = -48; added a road slab.diff --git a/scenes/tokyo-electronics-repair/assets.json b/scenes/tokyo-electronics-repair/assets.jsonnew file mode 100644index 0000000..2a61585--- /dev/null+++ b/scenes/tokyo-electronics-repair/assets.json@@ -0,0 +1,1071 @@+{+ "room": {+ "w": 4.2,+ "d": 6.5,+ "h": 2.7,+ "note": "x across, y from storefront (y=0) to back wall (y=6.5), z up. Bench along left wall x=0."+ },+ "generate": [+ {+ "id": "oscilloscope",+ "ref": "refs/props/oscilloscope.json",+ "fit": "h",+ "size": 0.21,+ "prompt": "existing",+ "hero": true+ },+ {+ "id": "solder_station",+ "ref": "refs/props/solder_station.json",+ "fit": "h",+ "size": 0.22,+ "prompt": "existing",+ "hero": true+ },+ {+ "id": "helping_hands",+ "ref": "refs/props/helping_hands.json",+ "fit": "h",+ "size": 0.26,+ "prompt": "existing",+ "hero": true+ },+ {+ "id": "boombox_open",+ "ref": "refs/props/boombox_open.json",+ "fit": "max",+ "size": 0.62,+ "prompt": "existing",+ "hero": true+ },+ {+ "id": "repair_multimeter_yellow",+ "fit": "max",+ "size": 0.19,+ "prompt": "A yellow analog-digital handheld multimeter with a rotary dial, LCD display and rubber holster, red and black test leads coiled beside it, lying flat face up.",+ "hero": true+ },+ {+ "id": "repair_multimeter_red",+ "fit": "max",+ "size": 0.2,+ "prompt": "A red and grey digital multimeter standing on its kickstand, large LCD, rotary selector, test probes plugged in and draped down.",+ "hero": true+ },+ {+ "id": "repair_bench_psu",+ "fit": "max",+ "size": 0.3,+ "prompt": "A 1990s laboratory bench DC power supply, grey metal case, two analog needle meters, voltage and current knobs, red and black binding posts, worn front panel.",+ "hero": true+ },+ {+ "id": "repair_work_lamp",+ "fit": "h",+ "size": 0.62,+ "prompt": "A black metal articulated architect desk lamp with a cone shade and spring arms, mounted on a C-clamp, arm raised and bent so the shade points down, scuffed paint.",+ "hero": true+ },+ {+ "id": "repair_vcr_open",+ "fit": "max",+ "size": 0.43,+ "prompt": "A silver 1990s VHS video cassette recorder with its top cover removed, exposing the video head drum, tape transport, circuit boards and ribbon cables.",+ "hero": true+ },+ {+ "id": "repair_crt_tv",+ "fit": "h",+ "size": 0.36,+ "prompt": "A small 14-inch beige CRT television from the late 1980s with a curved dark screen, buttons and a rotary channel knob below the screen, dusty."+ },+ {+ "id": "repair_vintage_radio",+ "fit": "max",+ "size": 0.32,+ "prompt": "A 1960s Japanese tabletop transistor radio in a wood-grain cabinet with a fabric speaker grille, a tuning dial window and two cream knobs."+ },+ {+ "id": "repair_receiver",+ "fit": "max",+ "size": 0.43,+ "prompt": "A 1970s silver hifi stereo receiver with a long blue-lit tuning dial, two signal meters, a row of silver knobs and toggle switches, wooden side panels."+ },+ {+ "id": "repair_turntable",+ "fit": "max",+ "size": 0.45,+ "prompt": "A vintage direct-drive record turntable with a dark wood plinth, silver platter with strobe dots, tonearm, and a dusty smoked plastic lid propped open."+ },+ {+ "id": "repair_rice_cooker",+ "fit": "h",+ "size": 0.25,+ "prompt": "A white Japanese household electric rice cooker with a flower pattern, a domed lid and a carry handle, a handwritten repair tag tied to the handle with string."+ },+ {+ "id": "repair_desk_fan",+ "fit": "h",+ "size": 0.42,+ "prompt": "A small vintage Japanese electric desk fan with a light blue plastic body, metal wire guard, three translucent blades and push buttons on the base."+ },+ {+ "id": "repair_kerosene_heater",+ "fit": "h",+ "size": 0.45,+ "prompt": "A Japanese convection kerosene heater (stove), round white metal body with a perforated chimney top, a small viewing window and a fuel gauge, slightly yellowed."+ },+ {+ "id": "repair_tool_chest",+ "fit": "h",+ "size": 1,+ "prompt": "A red steel rolling mechanic's tool chest with a top lid and stacked drawers with aluminium handles, on caster wheels, scratched and stickered."+ },+ {+ "id": "repair_stool",+ "fit": "h",+ "size": 0.62,+ "prompt": "A round shop stool with a cracked black vinyl seat and four chrome steel tube legs with a foot ring, worn."+ },+ {+ "id": "repair_mug",+ "fit": "h",+ "size": 0.1,+ "prompt": "A white ceramic coffee mug with coffee stains on the outside and a dark ring of old coffee inside, chipped rim.",+ "hero": true+ },+ {+ "id": "repair_cup_noodle",+ "fit": "h",+ "size": 0.12,+ "prompt": "An empty instant cup noodle cup with its paper lid torn half open and a pair of disposable wooden chopsticks resting across the top.",+ "hero": true+ },+ {+ "id": "repair_solder_junk",+ "fit": "max",+ "size": 0.2,+ "prompt": "A small cluster of soldering consumables: a spool of solder wire, a bottle of liquid flux, a roll of desoldering wick, a few loose snipped component leads.",+ "hero": true+ },+ {+ "id": "repair_parts_tray",+ "fit": "max",+ "size": 0.3,+ "prompt": "A black antistatic compartment tray full of salvaged electronic components: electrolytic capacitors, resistors, screws, a few chips and small springs.",+ "hero": true+ },+ {+ "id": "repair_tool_block",+ "fit": "h",+ "size": 0.2,+ "prompt": "A wooden block tool holder with a set of precision screwdrivers, tweezers, a pair of side cutters and pliers standing upright in its holes.",+ "hero": true+ },+ {+ "id": "repair_cable_coils",+ "fit": "h",+ "size": 0.6,+ "prompt": "A bundle of assorted coiled cables, power cords, RCA leads and an extension cord hanging together from a single metal wall hook."+ },+ {+ "id": "repair_boxes_a",+ "fit": "h",+ "size": 0.7,+ "prompt": "A stack of three cardboard boxes of different sizes containing old electronics waiting for pickup, Japanese marker writing on the sides, each with a paper repair tag taped on."+ },+ {+ "id": "repair_boxes_b",+ "fit": "h",+ "size": 0.55,+ "prompt": "Two worn cardboard boxes stacked, the top one open with a cassette deck sticking out, wrapped in bubble wrap, taped paper repair ticket."+ },+ {+ "id": "repair_trash_bin",+ "fit": "h",+ "size": 0.35,+ "prompt": "A small grey plastic office waste bin overflowing with crumpled paper, an empty drink can and plastic wrappers."+ },+ {+ "id": "repair_spray_cans",+ "fit": "h",+ "size": 0.21,+ "prompt": "Three aerosol spray cans standing together: contact cleaner, compressed air duster with a red straw, and a lubricant can, worn labels."+ },+ {+ "id": "repair_wall_clock",+ "fit": "max",+ "size": 0.3,+ "prompt": "A round cheap white plastic office wall clock with black numerals and hands, a slightly yellowed face, viewed from the front."+ },+ {+ "id": "repair_tissue_box",+ "fit": "max",+ "size": 0.24,+ "prompt": "A Japanese paper tissue box with a soft pastel pattern and a tissue pulled up from the slot."+ },+ {+ "id": "repair_laptop_broken",+ "fit": "max",+ "size": 0.36,+ "prompt": "An old grey business laptop opened at 110 degrees, cracked dark screen, a couple of missing keys, screws and the bottom panel lying beside it.",+ "hero": true+ },+ {+ "id": "repair_crt_stack",+ "fit": "h",+ "size": 1.1,+ "prompt": "A stack of three old CRT televisions and monitors of different sizes and colours piled on top of each other, dusty, with repair tags."+ },+ {+ "id": "repair_oscilloscope_nb",+ "replaces": "oscilloscope",+ "fit": "h",+ "size": 0.21,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1980s analog CRT oscilloscope with a beige and grey metal case, round-cornered green-tinted screen with graticule, rows of knobs, toggle switches and BNC connectors on the front panel, small printed labels, scuffed paint. The only brand name visible is the fictional brand \"KOSEI\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_solder_station_nb",+ "replaces": "solder_station",+ "fit": "h",+ "size": 0.22,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A worn analog soldering station: a grey control unit with a temperature dial, a soldering iron resting in its coiled-wire holder stand with a yellow brass-wool tip cleaner, the iron's cable connecting to the unit. The only brand name visible is the fictional brand \"HANDA-YA\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_boombox_open_nb",+ "replaces": "boombox_open",+ "fit": "max",+ "size": 0.62,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1980s silver cassette boombox radio lying open for repair with its back cover removed, exposing circuit boards, wires and the tape mechanism; the removed back panel and a few screws lying next to it. The only brand name visible is the fictional brand \"SONICA\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_multimeter_yellow_nb",+ "replaces": "repair_multimeter_yellow",+ "fit": "max",+ "size": 0.19,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A yellow analog-digital handheld multimeter with a rotary dial, LCD display and rubber holster, red and black test leads coiled beside it, lying flat face up. The only brand name visible is the fictional brand \"VOLTEK\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_multimeter_red_nb",+ "replaces": "repair_multimeter_red",+ "fit": "max",+ "size": 0.2,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A red and grey digital multimeter standing on its kickstand, large LCD, rotary selector, test probes plugged in and draped down. The only brand name visible is the fictional brand \"VOLTEK\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_bench_psu_nb",+ "replaces": "repair_bench_psu",+ "fit": "max",+ "size": 0.3,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1990s laboratory bench DC power supply, grey metal case, two analog needle meters, voltage and current knobs, red and black binding posts, worn front panel. The only brand name visible is the fictional brand \"DENKO\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_tool_chest_nb",+ "replaces": "repair_tool_chest",+ "fit": "h",+ "size": 1,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A red steel rolling mechanic's tool chest with a top lid and stacked drawers with aluminium handles, on caster wheels, scratched and stickered. The only brand name visible is the fictional brand \"IRONSIDE\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_spray_cans_nb",+ "replaces": "repair_spray_cans",+ "fit": "h",+ "size": 0.21,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "Three aerosol spray cans standing together: contact cleaner, compressed air duster with a red straw, and a lubricant can, worn labels. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_cup_noodle_nb",+ "replaces": "repair_cup_noodle",+ "fit": "h",+ "size": 0.12,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "An empty instant cup noodle cup with its paper lid torn half open and a pair of disposable wooden chopsticks resting across the top. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_boxes_b_nb",+ "replaces": "repair_boxes_b",+ "fit": "h",+ "size": 0.55,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "Two worn cardboard boxes stacked, the top one open with a cassette deck sticking out, wrapped in bubble wrap, taped paper repair ticket. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_vcr_open_nb",+ "replaces": "repair_vcr_open",+ "fit": "max",+ "size": 0.43,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A silver 1990s VHS video cassette recorder with its top cover removed, exposing the video head drum, tape transport, circuit boards and ribbon cables. The only brand name visible is the fictional brand \"MIRAVISION\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_tissue_box_nb",+ "replaces": "repair_tissue_box",+ "fit": "max",+ "size": 0.24,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A Japanese paper tissue box with a soft pastel pattern and a tissue pulled up from the slot. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_rice_cooker_nb",+ "replaces": "repair_rice_cooker",+ "fit": "h",+ "size": 0.25,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A white Japanese household electric rice cooker with a flower pattern, a domed lid and a carry handle, a handwritten repair tag tied to the handle with string. The only brand name visible is the fictional brand \"HARUKA\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_vintage_radio_nb",+ "replaces": "repair_vintage_radio",+ "fit": "max",+ "size": 0.32,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1960s Japanese tabletop transistor radio in a wood-grain cabinet with a fabric speaker grille, a tuning dial window and two cream knobs. The only brand name visible is the fictional brand \"AOZORA\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_receiver_nb",+ "replaces": "repair_receiver",+ "fit": "max",+ "size": 0.43,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1970s silver hifi stereo receiver with a long blue-lit tuning dial, two signal meters, a row of silver knobs and toggle switches, wooden side panels. The only brand name visible is the fictional brand \"SOUNDHILL\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_solder_junk_nb",+ "replaces": "repair_solder_junk",+ "fit": "max",+ "size": 0.2,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small cluster of soldering consumables: a spool of solder wire, a bottle of liquid flux, a roll of desoldering wick, a few loose snipped component leads. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_laptop_broken_nb",+ "replaces": "repair_laptop_broken",+ "fit": "max",+ "size": 0.36,+ "hero": true,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "An old grey business laptop opened at 110 degrees, cracked dark screen, a couple of missing keys, screws and the bottom panel lying beside it. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_crt_stack_nb",+ "replaces": "repair_crt_stack",+ "fit": "h",+ "size": 1.1,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A stack of three old CRT televisions and monitors of different sizes and colours piled on top of each other, dusty, with repair tags. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_crt_tv_nb",+ "replaces": "repair_crt_tv",+ "fit": "h",+ "size": 0.36,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small 14-inch beige CRT television from the late 1980s with a curved dark screen, buttons and a rotary channel knob below the screen, dusty. The only brand name visible is the fictional brand \"MIRAVISION\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_turntable_nb",+ "replaces": "repair_turntable",+ "fit": "max",+ "size": 0.45,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A vintage direct-drive record turntable with a dark wood plinth, silver platter with strobe dots, tonearm, and a dusty smoked plastic lid propped open. The only brand name visible is the fictional brand \"SOUNDHILL\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_desk_fan_nb",+ "replaces": "repair_desk_fan",+ "fit": "h",+ "size": 0.42,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small vintage Japanese electric desk fan with a light blue plastic body, metal wire guard, three translucent blades and push buttons on the base. The only brand name visible is the fictional brand \"KAZEMARU\"; no real-world brand names, model names or logos anywhere."+ },+ {+ "id": "repair_kerosene_heater_nb",+ "replaces": "repair_kerosene_heater",+ "fit": "h",+ "size": 0.45,+ "pass": "nb",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A Japanese convection kerosene heater (stove), round white metal body with a perforated chimney top, a small viewing window and a fuel gauge, slightly yellowed. All printing and labels are generic or plain, with no real-world brand names, product names or logos."+ },+ {+ "id": "repair_cassette_deck",+ "fit": "max",+ "size": 0.43,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1980s black stereo cassette tape deck with a single tape door, VU meters and piano-key transport buttons, dusty. No real-world brand names or logos."+ },+ {+ "id": "repair_amp_black",+ "fit": "max",+ "size": 0.43,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A black 1990s integrated stereo amplifier with a large volume knob, small input selector knobs and a row of push buttons, scratched top. No real-world brand names or logos."+ },+ {+ "id": "repair_crt_monitor_beige",+ "fit": "h",+ "size": 0.38,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A beige 1990s computer CRT monitor with a deep back, curved dark screen, small tilt-swivel base, yellowed plastic, a paper repair tag taped to the side. No real-world brand names or logos."+ },+ {+ "id": "repair_portable_tv",+ "fit": "h",+ "size": 0.24,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small 1980s portable black-and-white TV with a carry handle, telescopic antenna folded down and a small round speaker grille, red plastic case. No real-world brand names or logos."+ },+ {+ "id": "repair_tv_wood",+ "fit": "h",+ "size": 0.45,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1970s CRT television in a wood-grain cabinet with a rounded screen, two rotary channel dials on the right and four short legs. No real-world brand names or logos."+ },+ {+ "id": "repair_speaker_pair",+ "fit": "h",+ "size": 0.4,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A pair of small vintage bookshelf speakers in walnut veneer cabinets, one with its grille cloth removed showing the woofer and tweeter. No real-world brand names or logos."+ },+ {+ "id": "repair_camcorder",+ "fit": "max",+ "size": 0.3,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A 1990s VHS-C camcorder with a shoulder pad, side viewfinder and a cracked lens hood, black and grey plastic. No real-world brand names or logos."+ },+ {+ "id": "repair_microwave",+ "fit": "max",+ "size": 0.5,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small white household microwave oven with a dial timer and a dirty glass door, a paper repair ticket taped to the door. No real-world brand names or logos."+ },+ {+ "id": "repair_pc_tower",+ "fit": "h",+ "size": 0.42,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A yellowed beige 1990s PC tower computer with a floppy drive and CD drive bay, side panel removed showing the motherboard and cables. No real-world brand names or logos."+ },+ {+ "id": "repair_dotmatrix_printer",+ "fit": "max",+ "size": 0.45,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A beige dot-matrix printer with tractor-feed perforated paper coming out the top, dusty, lid slightly open. No real-world brand names or logos."+ },+ {+ "id": "repair_fax_phone",+ "fit": "max",+ "size": 0.32,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A beige 1990s home fax telephone with a corded handset, a keypad and thermal paper roll slot. No real-world brand names or logos."+ },+ {+ "id": "repair_radio_cassette",+ "fit": "max",+ "size": 0.35,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small silver radio cassette player with a carry handle, one round speaker, a tuning dial and a cassette door, worn. No real-world brand names or logos."+ },+ {+ "id": "repair_karaoke_machine",+ "fit": "h",+ "size": 0.4,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A home karaoke machine: a black box with two microphone inputs, a small built-in screen, colourful buttons, with a wired microphone resting on top. No real-world brand names or logos."+ },+ {+ "id": "repair_electric_kettle",+ "fit": "h",+ "size": 0.25,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A white electric hot-water pot dispenser with a push-button top and a cord, Japanese style, slightly stained. No real-world brand names or logos."+ },+ {+ "id": "repair_job_bin",+ "fit": "max",+ "size": 0.45,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A blue plastic storage bin holding a disassembled DVD player, loose screws in a sandwich bag and a paper repair ticket clipped to the rim. No real-world brand names or logos."+ },+ {+ "id": "repair_cable_crate",+ "fit": "max",+ "size": 0.45,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A black plastic milk crate overflowing with tangled power cords, AV cables, AC adapters and remote controls. No real-world brand names or logos."+ },+ {+ "id": "repair_parts_bins",+ "fit": "h",+ "size": 0.45,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A stack of small blue and red plastic stackable parts bins with open fronts, filled with screws, knobs and small components, handwritten labels. No real-world brand names or logos."+ },+ {+ "id": "repair_parts_cart",+ "fit": "h",+ "size": 0.85,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A grey steel three-tier rolling utility cart loaded with a disassembled stereo, a box of parts, cables and a coffee cup, on casters, worn. No real-world brand names or logos."+ },+ {+ "id": "repair_hot_air_station",+ "fit": "max",+ "size": 0.3,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A hot-air rework station: a grey control box with two digital displays and knobs, the hot-air gun resting in its holder with a coiled hose. No real-world brand names or logos."+ },+ {+ "id": "repair_magnifier_lamp",+ "fit": "h",+ "size": 0.55,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A white ring-light magnifier lamp on a heavy desk base with a spring arm, the round lens head tilted down, scuffed. No real-world brand names or logos."+ },+ {+ "id": "repair_pcb_vise",+ "fit": "max",+ "size": 0.22,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small PCB holder vise on a weighted base clamping a green circuit board with components partly desoldered. No real-world brand names or logos."+ },+ {+ "id": "repair_fume_extractor",+ "fit": "h",+ "size": 0.25,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small black desktop solder fume extractor fan with a square carbon filter on the front, on a tilting stand. No real-world brand names or logos."+ },+ {+ "id": "repair_cash_register",+ "fit": "max",+ "size": 0.4,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small old electronic cash register with a cash drawer, a receipt printer, rows of keys and a small green display, plain, no brand. No real-world brand names or logos."+ },+ {+ "id": "repair_desk_phone",+ "fit": "max",+ "size": 0.22,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A beige office desk telephone with a coiled cord handset and a large-key keypad, yellowed. No real-world brand names or logos."+ },+ {+ "id": "repair_counter_lamp",+ "fit": "h",+ "size": 0.42,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small green-shaded metal desk lamp with a weighted round base and a pull chain, worn paint. No real-world brand names or logos."+ },+ {+ "id": "repair_display_case",+ "fit": "max",+ "size": 0.7,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small countertop glass display showcase with a wooden frame and sliding back doors, holding used portable cassette players, old mobile phones and calculators with price tags. No real-world brand names or logos."+ },+ {+ "id": "repair_calculator",+ "fit": "max",+ "size": 0.17,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A grey desktop printing calculator with a paper roll and large keys, tape curling out. No real-world brand names or logos."+ },+ {+ "id": "repair_umbrella_stand",+ "fit": "h",+ "size": 0.7,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A metal umbrella stand by a shop door holding three wet transparent plastic umbrellas and one black umbrella, water pooled at the base. No real-world brand names or logos."+ },+ {+ "id": "repair_shop_vac",+ "fit": "h",+ "size": 0.55,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small grey wet-dry shop vacuum with a coiled hose wrapped around it, dusty. No real-world brand names or logos."+ },+ {+ "id": "repair_step_stool",+ "fit": "h",+ "size": 0.5,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small aluminium two-step folding step ladder, open, paint drips on the steps. No real-world brand names or logos."+ },+ {+ "id": "repair_floor_fan",+ "fit": "h",+ "size": 0.9,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A tall cream-coloured pedestal electric fan with a round metal cage, standing, the cord coiled at the base. No real-world brand names or logos."+ },+ {+ "id": "repair_storage_boxes_flat",+ "fit": "max",+ "size": 0.6,+ "pass": "A",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A stack of four flat cardboard boxes of different sizes tied with plastic string, labelled in marker, slightly crushed corners. No real-world brand names or logos."+ },+ {+ "id": "repair_pcbs_loose",+ "fit": "max",+ "size": 0.25,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small pile of four loose salvaged green and brown circuit boards with components, one with burnt marks. No real-world brand names or logos."+ },+ {+ "id": "repair_screw_jar",+ "fit": "h",+ "size": 0.11,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A glass jar with a dented metal lid full of assorted screws, nuts and washers. No real-world brand names or logos."+ },+ {+ "id": "repair_screwdriver_case",+ "fit": "max",+ "size": 0.24,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "An open plastic case with a precision screwdriver set and interchangeable bits, a few bits missing. No real-world brand names or logos."+ },+ {+ "id": "repair_tweezers",+ "fit": "max",+ "size": 0.14,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "Three stainless steel precision tweezers of different tip shapes lying side by side. No real-world brand names or logos."+ },+ {+ "id": "repair_ashtray",+ "fit": "max",+ "size": 0.14,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A round glass ashtray with several crushed cigarette butts and ash. No real-world brand names or logos."+ },+ {+ "id": "repair_tape_rolls",+ "fit": "max",+ "size": 0.14,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A roll of black electrical tape, a roll of yellow kapton tape and a half-used roll of masking tape stacked loosely. No real-world brand names or logos."+ },+ {+ "id": "repair_receipts",+ "fit": "max",+ "size": 0.22,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A messy pile of small paper receipts and handwritten repair slips held with a black binder clip. No real-world brand names or logos."+ },+ {+ "id": "repair_cable_bundle",+ "fit": "max",+ "size": 0.35,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A loosely coiled bundle of black power cords tied with a red twist tie, lying on a table. No real-world brand names or logos."+ },+ {+ "id": "repair_canned_coffee",+ "fit": "h",+ "size": 0.12,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "Two empty steel canned-coffee drink cans, one crushed, plain dark brown labels with no logos. No real-world brand names or logos."+ },+ {+ "id": "repair_desolder_pump",+ "fit": "max",+ "size": 0.2,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A blue and silver spring-loaded desoldering pump with a white tip. No real-world brand names or logos."+ },+ {+ "id": "repair_flux_bottles",+ "fit": "h",+ "size": 0.11,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "Two small plastic flux dispenser bottles with needle tips and a jar of rosin flux paste, generic labels. No real-world brand names or logos."+ },+ {+ "id": "repair_component_bag",+ "fit": "max",+ "size": 0.15,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small zip-lock plastic bag of electrolytic capacitors and resistors with a handwritten paper label. No real-world brand names or logos."+ },+ {+ "id": "repair_ribbon_cables",+ "fit": "max",+ "size": 0.3,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A few grey flat ribbon cables with black connectors, loosely folded. No real-world brand names or logos."+ },+ {+ "id": "repair_extension_block",+ "fit": "max",+ "size": 0.32,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A white power strip extension block with six sockets, several plugs inserted, cord coiled, dirty. No real-world brand names or logos."+ },+ {+ "id": "repair_sticky_notes",+ "fit": "max",+ "size": 0.09,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A pad of yellow sticky notes with handwriting on the top note and a ballpoint pen. No real-world brand names or logos."+ },+ {+ "id": "repair_remote_controls",+ "fit": "max",+ "size": 0.22,+ "pass": "B",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "Three old TV and VCR remote controls of different sizes lying together, one with its battery cover missing. No real-world brand names or logos."+ },+ {+ "id": "repair_vending_machine",+ "fit": "h",+ "size": 1.83,+ "pass": "street",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A Japanese street drink vending machine with a lit display of plastic drink bottle samples in rows, price buttons, coin slot, rain-wet, generic labels. No real-world brand names or logos."+ },+ {+ "id": "repair_bicycle",+ "fit": "max",+ "size": 1.75,+ "pass": "street",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A black Japanese city bicycle (mamachari) with a front wire basket and a rear rack, standing on its kickstand, side view, wet. No real-world brand names or logos."+ },+ {+ "id": "repair_aframe_sign",+ "fit": "h",+ "size": 0.9,+ "pass": "street",+ "models": [+ "tripo-h31",+ "meshy"+ ],+ "prompt": "A small A-frame sidewalk sign board for an izakaya with handwritten Japanese menu chalk text and a small lamp on top. No real-world brand names or logos."+ }+ ],+ "direct": [+ "shell (walls, ceiling, floor tiles)",+ "storefront glass + aluminium frames + sliding door",+ "workbench (wood top, steel frame, under-shelf)",+ "small-parts drawer cabinets x3 with labels",+ "wall shelves above bench",+ "steel angle shelving x2",+ "pegboard with hooks",+ "fluorescent ceiling fixtures (off)",+ "repair tags / posters / calendar planes",+ "night street backdrop emissive plane",+ "back door",+ "power strips + floor cables",+ "neon sign outside"+ ]+}\ No newline at end of filediff --git a/scenes/tokyo-electronics-repair/nb_swap.json b/scenes/tokyo-electronics-repair/nb_swap.jsonnew file mode 100644index 0000000..5014c1c--- /dev/null+++ b/scenes/tokyo-electronics-repair/nb_swap.json@@ -0,0 +1,18 @@+{+ "boombox_open": "repair_boombox_open_nb",+ "repair_multimeter_yellow": "repair_multimeter_yellow_nb",+ "repair_multimeter_red": "repair_multimeter_red_nb",+ "repair_bench_psu": "repair_bench_psu_nb",+ "repair_tool_chest": "repair_tool_chest_nb",+ "repair_boxes_b": "repair_boxes_b_nb",+ "repair_vcr_open": "repair_vcr_open_nb",+ "repair_rice_cooker": "repair_rice_cooker_nb",+ "repair_vintage_radio": "repair_vintage_radio_nb",+ "repair_receiver": "repair_receiver_nb",+ "repair_solder_junk": "repair_solder_junk_nb",+ "repair_laptop_broken": "repair_laptop_broken_nb",+ "repair_crt_stack": "repair_crt_stack_nb",+ "repair_turntable": "repair_turntable_nb",+ "repair_desk_fan": "repair_desk_fan_nb",+ "repair_kerosene_heater": "repair_kerosene_heater_nb"+}diff --git a/scenes/tokyo-electronics-repair/picks.json b/scenes/tokyo-electronics-repair/picks.jsonnew file mode 100644index 0000000..244a7fa--- /dev/null+++ b/scenes/tokyo-electronics-repair/picks.json@@ -0,0 +1,442 @@+{+ "oscilloscope": {+ "model": "tripo-h31",+ "why": "real knobs, bezel and handle; Meshy speckles the case",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "solder_station": {+ "model": "tripo-h31",+ "why": "cable, coil holder and dial are geometry; Meshy washed out",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "helping_hands": {+ "model": "tripo-h31",+ "why": "cleanest arms and clips; lens rebuilt by script"+ },+ "boombox_open": {+ "model": "tripo-h31",+ "why": "cassette mechanism and cones modelled; back is flat but faces the wall"+ },+ "repair_work_lamp": {+ "model": "meshy",+ "why": "shade proportions match the ref, clean clamp"+ },+ "repair_bench_psu": {+ "model": "meshy",+ "why": "sharper meters, knobs and binding posts are geometry",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_multimeter_red": {+ "model": "meshy",+ "why": "crisper LCD and dial, real kickstand",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_multimeter_yellow": {+ "model": "meshy",+ "why": "cleaner holster and readable display",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_vcr_open": {+ "model": "meshy",+ "why": "silver case and exposed transport match the ref; H3.1 darker and muddier",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_crt_tv": {+ "model": "meshy",+ "why": "glossy curved screen and closer proportions"+ },+ "repair_vintage_radio": {+ "model": "meshy",+ "why": "grille cloth and dial read better; H3.1 back is blank",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_turntable": {+ "model": "tripo-h31",+ "why": "darker platter and tonearm read as real; Meshy lid blotchy",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_desk_fan": {+ "model": "meshy",+ "why": "blades and cage silhouette closest to the ref",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_kerosene_heater": {+ "model": "meshy",+ "why": "lit viewing window and cage both clean",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_rice_cooker": {+ "model": "meshy",+ "why": "cleaner floral print and tag",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_cable_coils": {+ "model": "meshy",+ "why": "keeps the wall hook and cable separation"+ },+ "repair_mug": {+ "model": "tripo-h31",+ "why": "outside coffee drips like the ref"+ },+ "repair_tool_block": {+ "model": "meshy",+ "why": "tool order and colours match the ref"+ },+ "repair_boxes_b": {+ "model": "meshy",+ "why": "open box, bubble wrap and taped ticket match the ref",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_trash_bin": {+ "model": "meshy",+ "why": "fuller, crisper crumpled paper and can"+ },+ "repair_spray_cans": {+ "model": "meshy",+ "why": "sharper labels and the duster straw",+ "retired": "round 2: brand covers the whole label; replaced by a direct-modelled generic version in dress2.py"+ },+ "repair_wall_clock": {+ "model": "meshy",+ "why": "cleaner face and numerals (the mirrored face on the back is against the wall)"+ },+ "repair_tissue_box": {+ "model": "meshy",+ "why": "print and tissue shape closest to the ref",+ "retired": "round 2: brand covers the whole label; replaced by a direct-modelled generic version in dress2.py"+ },+ "repair_laptop_broken": {+ "model": "meshy",+ "why": "cracked screen and keyboard read clearly; H3.1 smaller and muddier",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_crt_stack": {+ "model": "meshy",+ "why": "three distinct sets with tags; H3.1 bottom set lost its screen on the back",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_receiver": {+ "model": "tripo-h31",+ "why": "wood sides and lit dial; Meshy invented a grille on the back",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_stool": {+ "model": "tripo-h31",+ "why": "cracked vinyl and thin chrome legs closest to the ref"+ },+ "repair_tool_chest": {+ "model": "tripo-h31",+ "why": "crisp drawers and stickers; Meshy lid blotchy",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_solder_junk": {+ "model": "meshy",+ "why": "flux label and wick spool read better",+ "debranded": "round 2: brand marks texture-painted over (scenes/tokyo-electronics-repair/scripts/debrand.py)"+ },+ "repair_cup_noodle": {+ "model": "tripo-h31",+ "why": "torn lid and chopsticks match the ref; both close",+ "retired": "round 2: brand covers the whole label; replaced by a direct-modelled generic version in dress2.py"+ },+ "repair_boxes_a": {+ "model": "meshy",+ "why": "larger marker handwriting and tags; H3.1 boxes more uniform"+ },+ "repair_parts_tray": {+ "model": "meshy",+ "why": "fuller compartments with readable components; H3.1 tray sparse"+ },+ "repair_oscilloscope_nb": {+ "model": "meshy",+ "why": "larger screen and crisper panel print; kept as backup, the fixed original stays in the scene"+ },+ "repair_solder_station_nb": {+ "model": "meshy",+ "why": "cleaner dial and holder; kept as backup, the debranded original stays"+ },+ "repair_boombox_open_nb": {+ "model": "meshy",+ "why": "brighter exposed mechanism, readable fictional badge"+ },+ "repair_multimeter_yellow_nb": {+ "model": "meshy",+ "why": "sharper LCD and dial, VOLTEK badge clean"+ },+ "repair_multimeter_red_nb": {+ "model": "meshy",+ "why": "crisper keypad and kickstand"+ },+ "repair_bench_psu_nb": {+ "model": "meshy",+ "why": "meters and knobs read better"+ },+ "repair_tool_chest_nb": {+ "model": "meshy",+ "why": "drawers and stickers sharper, open lid"+ },+ "repair_spray_cans_nb": {+ "model": "meshy",+ "why": "three distinct generic labels and the duster straw"+ },+ "repair_cup_noodle_nb": {+ "model": "meshy",+ "why": "torn lid and chopsticks closest to the ref"+ },+ "repair_boxes_b_nb": {+ "model": "meshy",+ "why": "bubble wrap and repair ticket sharper"+ },+ "repair_vcr_open_nb": {+ "model": "meshy",+ "why": "silver case and transport closest to the ref"+ },+ "repair_tissue_box_nb": {+ "model": "meshy",+ "why": "print and tissue closest to the ref"+ },+ "repair_rice_cooker_nb": {+ "model": "meshy",+ "why": "clean floral print and tag"+ },+ "repair_vintage_radio_nb": {+ "model": "meshy",+ "why": "grille and dial window read better"+ },+ "repair_receiver_nb": {+ "model": "tripo-h31",+ "why": "clean top; Meshy smeared front-panel texture across the lid"+ },+ "repair_solder_junk_nb": {+ "model": "meshy",+ "why": "flux bottle and wick spool clearer"+ },+ "repair_laptop_broken_nb": {+ "model": "tripo-h31",+ "why": "cracked screen reads; Meshy screen washed out"+ },+ "repair_crt_stack_nb": {+ "model": "meshy",+ "why": "three distinct sets with tags"+ },+ "repair_crt_tv_nb": {+ "model": "meshy",+ "why": "glossy curved screen; backup, the fixed original stays"+ },+ "repair_turntable_nb": {+ "model": "meshy",+ "why": "see-through lid and platter detail"+ },+ "repair_desk_fan_nb": {+ "model": "meshy",+ "why": "cage and blades closest to the ref"+ },+ "repair_kerosene_heater_nb": {+ "model": "meshy",+ "why": "lit window and cage clean"+ },+ "repair_cassette_deck": {+ "model": "meshy",+ "why": "VU meters and transport keys crisp"+ },+ "repair_amp_black": {+ "model": "meshy",+ "why": "knobs and buttons crisp; odd patch on the back faces the wall"+ },+ "repair_crt_monitor_beige": {+ "model": "meshy",+ "why": "deep back and paper tag"+ },+ "repair_portable_tv": {+ "model": "meshy",+ "why": "handle, antenna and dials closest to the ref"+ },+ "repair_tv_wood": {+ "model": "meshy",+ "why": "curved screen and wood cabinet; H3.1 screen flatter"+ },+ "repair_speaker_pair": {+ "model": "meshy",+ "why": "woofer and tweeter detail"+ },+ "repair_camcorder": {+ "model": "meshy",+ "why": "lens and viewfinder detail"+ },+ "repair_microwave": {+ "model": "meshy",+ "why": "dirty door and ticket"+ },+ "repair_dotmatrix_printer": {+ "model": "meshy",+ "why": "tractor paper and lid"+ },+ "repair_fax_phone": {+ "model": "meshy",+ "why": "handset cord and keypad"+ },+ "repair_karaoke_machine": {+ "model": "meshy",+ "why": "screen and microphone"+ },+ "repair_electric_kettle": {+ "model": "meshy",+ "why": "buttons and window"+ },+ "repair_job_bin": {+ "model": "meshy",+ "why": "bin contents and ticket"+ },+ "repair_display_case": {+ "model": "meshy",+ "why": "real glass frame; H3.1 filled sides with white panels"+ },+ "repair_calculator": {+ "model": "tripo-h31",+ "why": "clean display; Meshy display garbled"+ },+ "repair_umbrella_stand": {+ "model": "tripo-h31",+ "why": "keeps the black umbrella of the ref"+ },+ "repair_shop_vac": {+ "model": "meshy",+ "why": "hose wrap and casters"+ },+ "repair_step_stool": {+ "model": "meshy",+ "why": "paint drips and proportions"+ },+ "repair_floor_fan": {+ "model": "meshy",+ "why": "cage and cord"+ },+ "repair_storage_boxes_flat": {+ "model": "meshy",+ "why": "string tie and marker labels"+ },+ "repair_bicycle": {+ "model": "meshy",+ "why": "basket and rack detail"+ },+ "repair_aframe_sign": {+ "model": "meshy",+ "why": "menu legible on both faces"+ },+ "repair_pc_tower": {+ "model": "meshy",+ "why": "open side, cabling and drive bays crisp"+ },+ "repair_radio_cassette": {+ "model": "meshy",+ "why": "dial and grille sharper"+ },+ "repair_cable_crate": {+ "model": "tripo-h31",+ "why": "only model: Meshy failed twice (timeout / 422)"+ },+ "repair_parts_bins": {+ "model": "tripo-h31",+ "why": "labels and contents; Meshy bins came out empty"+ },+ "repair_parts_cart": {+ "model": "meshy",+ "why": "load on every tier reads"+ },+ "repair_hot_air_station": {+ "model": "meshy",+ "why": "displays and hose"+ },+ "repair_magnifier_lamp": {+ "model": "meshy",+ "why": "lens glass and arm"+ },+ "repair_pcb_vise": {+ "model": "meshy",+ "why": "cleaner board and knobs"+ },+ "repair_fume_extractor": {+ "model": "meshy",+ "why": "filter grid and stand"+ },+ "repair_cash_register": {+ "model": "tripo-h31",+ "why": "clean display; Meshy display garbled"+ },+ "repair_desk_phone": {+ "model": "meshy",+ "why": "handset cord and keys"+ },+ "repair_counter_lamp": {+ "model": "meshy",+ "why": "shade wear and pull chains"+ },+ "repair_pcbs_loose": {+ "model": "meshy",+ "why": "more distinct boards"+ },+ "repair_screw_jar": {+ "model": "tripo-h31",+ "why": "contents visible through the glass; Meshy jar milky"+ },+ "repair_screwdriver_case": {+ "model": "meshy",+ "why": "bits and lid"+ },+ "repair_tweezers": {+ "model": "meshy",+ "why": "tip shapes"+ },+ "repair_ashtray": {+ "model": "tripo-h31",+ "why": "butts visible; neither is glass"+ },+ "repair_tape_rolls": {+ "model": "meshy",+ "why": "kapton and masking tape layering"+ },+ "repair_receipts": {+ "model": "tripo-h31",+ "why": "only model: Meshy failed"+ },+ "repair_cable_bundle": {+ "model": "meshy",+ "why": "twist tie and connector ends"+ },+ "repair_canned_coffee": {+ "model": "meshy",+ "why": "crushed can"+ },+ "repair_desolder_pump": {+ "model": "meshy",+ "why": "knurled barrel"+ },+ "repair_flux_bottles": {+ "model": "meshy",+ "why": "needle tips and labels"+ },+ "repair_component_bag": {+ "model": "meshy",+ "why": "contents and label"+ },+ "repair_ribbon_cables": {+ "model": "meshy",+ "why": "connectors and red stripe"+ },+ "repair_extension_block": {+ "model": "meshy",+ "why": "plugs and cord"+ },+ "repair_sticky_notes": {+ "model": "meshy",+ "why": "handwriting on the top note"+ },+ "repair_remote_controls": {+ "model": "meshy",+ "why": "buttons and open battery bay"+ },+ "repair_vending_machine": {+ "model": "meshy",+ "why": "lit bottle rows; generic labels"+ }+}\ No newline at end of filediff --git a/scenes/tokyo-electronics-repair/scripts/bts.py b/scenes/tokyo-electronics-repair/scripts/bts.pynew file mode 100644index 0000000..a6300fb--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/bts.py@@ -0,0 +1,381 @@+"""Behind-the-scenes "dollhouse" clips for the repair shop (breakdown/SPEC.md).++ blender -b scenes/tokyo-electronics-repair/repair_final.blend --python scenes/tokyo-electronics-repair/scripts/bts.py -- setup+ -> breakdown/tokyo-electronics-repair/bts.blend (copy of the final scene + bts camera); never saves over a scene file+ blender -b breakdown/tokyo-electronics-repair/bts.blend --python scenes/tokyo-electronics-repair/scripts/bts.py -- <a_layout|b_props|c_materials|d_lighting> [first last]+ -> breakdown/tokyo-electronics-repair/clips/<clip>/####.png (existing frames are skipped). Run each through pipeline/gpu_run.sh.++One continuous 120° orbit around the room centre, split A 0-30°, B 30-60°, C 60-90°, D 90-120° (ease-in on A,+ease-out on D). Walls nearest the camera and the ceiling are hidden per frame, so the interior reads as a dollhouse.+"""+import math+import os+import sys++import bpy+from mathutils import Vector++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+OUT = os.path.join(ROOT, "breakdown", "tokyo-electronics-repair")+W, D, H = 4.2, 6.5, 2.7+CENTRE = Vector((2.0, 3.35, 0.75))+AZ0 = -150.0 # world azimuth (deg, from +X, CCW) at orbit 0°: front-left; the orbit sweeps across the storefront+ELEV, DIST, LENS = 42.0, 10.2, 30.0 # side to front-right, bench (left) and racks (right) both side-on, counter in the middle+CLIPS = {"a_layout": (144, 0, 30, "in"), "b_props": (240, 30, 60, None),+ "c_materials": (144, 60, 90, None), "d_lighting": (240, 90, 120, "out")}+args = sys.argv[sys.argv.index("--") + 1:]+sc = bpy.context.scene++# ------------------------------------------------------------------ object groups+SHELL_COLLS = ("shell", "storefront", "bench", "drawers", "shelving", "counter", "ceiling", "deco")+PROP_COLLS = ("props", "dress2_A_mid", "dress2_B_clutter", "dress2_C_micro")+EXTERIOR = ("pavement", "road", "street_backdrop")+CEILING_EXTRA = ("fixture_racks", "tube_racks_", "tube_on")+# cutaway walls: outward normal -> objects that go with that wall+WALLS = {+ (-1, 0): ("wall_left", "baseboard_l", "poster_extra_0", "poster_tape_0", "outlet_"),+ (1, 0): ("wall_right", "baseboard_r", "poster_parts", "sticky_7"),+ (0, -1): ("front_", "glass_", "door_leaf", "decal_signage", "flyer_glass", "flyer_tape"),+ (0, 1): ("wall_back", "door_frame", "door_slab", "door_handle", "baseboard_b", "calendar", "backroom_dark", "repair_wall_clock", "poster_extra_1",+ "poster_tape_1"),+}+++def coll_objs(names):+ out = []+ for n in names:+ c = bpy.data.collections.get(n)+ if c:+ out += list(c.all_objects)+ return out+++def starts(o, prefixes):+ return o.name.startswith(prefixes)+++def azimuth(clip, f):+ n, a0, a1, ease = CLIPS[clip]+ u = (f - 1) / (n - 1)+ if ease == "in":+ u = 2 * u * u - u ** 3 # slope 0 -> 1+ elif ease == "out":+ u = u + u * u - u ** 3 # slope 1 -> 0+ return AZ0 + a0 + (a1 - a0) * u+++def cam_pose(az):+ a, e = math.radians(az), math.radians(ELEV)+ p = CENTRE + Vector((math.cos(a) * math.cos(e), math.sin(a) * math.cos(e), math.sin(e))) * DIST+ return p, (CENTRE - p).to_track_quat("-Z", "Y").to_euler()+++# ------------------------------------------------------------------ setup+if args[0] == "setup":+ cd = bpy.data.cameras.new("bts_cam")+ cd.lens, cd.sensor_width, cd.sensor_fit = LENS, 36.0, "HORIZONTAL"+ cd.shift_y = -0.12 # room sits higher in frame: bottom 140 px stay clear for captions+ cd.dof.use_dof = False+ cd.clip_end = 100+ cam = bpy.data.objects.new("bts_cam", cd)+ sc.collection.objects.link(cam)+ clay = bpy.data.materials.new("bts_clay")+ b = clay.node_tree.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (0.62, 0.62, 0.6, 1)+ b.inputs["Roughness"].default_value = 0.7+ os.makedirs(OUT, exist_ok=True)+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "bts.blend"), copy=True)+ print("BTS setup saved")+ sys.exit(0)++clip = args[0]+n = CLIPS[clip][0]+first, last = (int(args[1]), int(args[2])) if len(args) > 2 else (1, n)+CLAY_PLATE = len(args) > 3 and args[3] == "clay" # c_materials clay plate for the clay -> material wipe+cam = bpy.data.objects["bts_cam"]+sc.camera = cam+sc.frame_start, sc.frame_end = 1, n+r = sc.render+r.resolution_x, r.resolution_y, r.resolution_percentage = 1920, 1080, 100+r.fps = 24+r.use_motion_blur = False+r.use_compositing = False # no lens fx / glare: clean plates, the main session grades+r.image_settings.file_format = "PNG"+r.image_settings.color_mode = "RGB"+r.image_settings.color_depth = "8"+r.film_transparent = False+for o in bpy.data.objects:+ if o.animation_data and o.name.startswith(("CR_", "cam_handheld")):+ o.animation_data_clear()++# camera: one key per frame+for f in range(1, n + 1):+ p, rot = cam_pose(azimuth(clip, f))+ cam.location, cam.rotation_euler = p, rot+ cam.keyframe_insert("location", frame=f)+ cam.keyframe_insert("rotation_euler", frame=f)++# ------------------------------------------------------------------ visibility+everything = [o for o in sc.objects if o.type in ("MESH", "CURVE", "LIGHT", "VOLUME")]+shell = set(coll_objs(SHELL_COLLS))+props = set(coll_objs(PROP_COLLS))+ceiling = set(coll_objs(("ceiling",))) | {o for o in sc.objects if starts(o, CEILING_EXTRA)} | {sc.objects["ceiling"]}+exterior = set(coll_objs(("street",))) | {o for o in sc.objects if starts(o, EXTERIOR)}+exterior |= {o for o in props if starts(o, ("vending_", "vm_bottle", "bike_", "aframe_", "umbrella_puddle"))+ and o.location.y < -0.1}+night = [o for o in coll_objs(("night_rig",))]+haze = sc.objects.get("haze")+lights = [o for o in sc.objects if o.type == "LIGHT"]+for o in everything:+ o.hide_render = False+++def wall_objs(normal):+ pre = WALLS[normal]+ return [o for o in sc.objects if starts(o, pre) and o not in props or o.name in pre]+++cut = {k: wall_objs(k) for k in WALLS}+for o in ceiling:+ o.hide_render = True+show_exterior = False # with the storefront cut away the street props sit in the foreground; street light comes from lamps+for o in exterior:+ o.hide_render = not show_exterior+for o in sc.objects:+ if o.name.startswith(("CR_", "focus_", "clay_")):+ o.hide_render = True+# per-frame wall cutaway (constant keys)+for f in range(1, n + 1):+ a = math.radians(azimuth(clip, f))+ d = (math.cos(a), math.sin(a))+ for (nx, ny), objs in cut.items():+ hide = d[0] * nx + d[1] * ny > 0.25+ for o in objs:+ o.hide_render = hide+ o.keyframe_insert("hide_render", frame=f)+for o in {o for objs in cut.values() for o in objs}:+ if o.animation_data and o.animation_data.action:+ act = o.animation_data.action+ for fc in act.layers[0].strips[0].channelbag(act.slots[0]).fcurves:+ for kp in fc.keyframe_points:+ kp.interpolation = "CONSTANT"+++def studio(clay):+ """Bright even look: grey world, a soft sun, night lights + haze off, neutral exposure."""+ for o in lights:+ o.hide_render = True+ if haze:+ haze.hide_render = True+ w = sc.world+ bg = w.node_tree.nodes["Background"]+ bg.inputs["Color"].default_value = (0.75, 0.77, 0.8, 1)+ bg.inputs["Strength"].default_value = 1.2 if clay else 0.9+ ld = bpy.data.lights.new("bts_sun", "SUN")+ ld.energy, ld.angle = (2.2 if clay else 2.5), math.radians(12)+ s = bpy.data.objects.new("bts_sun", ld)+ sc.collection.objects.link(s)+ s.rotation_euler = (math.radians(38), math.radians(8), math.radians(140))+ sc.view_settings.view_transform = "AgX"+ sc.view_settings.look = "None"+ sc.view_settings.exposure = 0.0+ r.engine = "BLENDER_EEVEE"+ ev = sc.eevee+ ev.taa_render_samples = 32+ ev.use_raytracing = True+ ev.use_shadows = True+++def clay_override():+ m = bpy.data.materials.get("bts_clay")+ if m is None: # an unused material is not saved with the copy, so build it here+ m = bpy.data.materials.new("bts_clay")+ b = m.node_tree.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (0.62, 0.62, 0.6, 1)+ b.inputs["Roughness"].default_value = 0.7+ sc.view_layers[0].material_override = m+++# ------------------------------------------------------------------ clips+if clip == "a_layout":+ studio(True)+ clay_override()+ for o in props:+ o.hide_render = True+ # furniture blocks rise into place over the first 2 s (walls and floor stay)+ risers = [o for o in shell if o.parent is None and not starts(o, ("floor", "wall_", "front_", "glass_", "door", "baseboard",+ "backroom", "ceiling", "pavement", "road", "street", "decal"))]+ risers.sort(key=lambda o: (o.users_collection[0].name, o.location.y))+ for i, o in enumerate(risers):+ f0 = 1 + int(30 * i / max(1, len(risers) - 1))+ o.delta_location = (0, 0, -3.0)+ o.keyframe_insert("delta_location", index=2, frame=f0)+ o.delta_location = (0, 0, 0.12)+ o.keyframe_insert("delta_location", index=2, frame=f0 + 12)+ o.delta_location = (0, 0, 0)+ o.keyframe_insert("delta_location", index=2, frame=f0 + 18)++elif clip == "b_props":+ studio(True)+ clay_override()+ tops = [o for o in props if o.parent is None and not o.hide_render and o not in exterior]++ def vol(o):+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]+ s = Vector((max(p.x for p in pts) - min(p.x for p in pts), max(p.y for p in pts) - min(p.y for p in pts),+ max(p.z for p in pts) - min(p.z for p in pts)))+ return s.x * s.y * max(s.z, 0.01)+ curves = [o for o in tops if o.type == "CURVE"]+ meshes = sorted([o for o in tops if o.type != "CURVE"], key=vol, reverse=True)+ order = meshes + curves # cables last: they grow along their length+ span = 194+ for i, o in enumerate(order):+ f0 = 1 + int(span * (i / max(1, len(order) - 1)) ** 1.35) # big things get more room, clutter speeds up+ if o.type == "CURVE":+ o.data.bevel_factor_mapping_end = "SPLINE"+ o.data.bevel_factor_end = 0.0+ o.data.keyframe_insert("bevel_factor_end", frame=f0)+ o.data.bevel_factor_end = 1.0+ o.data.keyframe_insert("bevel_factor_end", frame=f0 + 8)+ continue+ for fr, s in ((f0, 0.0), (f0 + 4, 1.12), (f0 + 6, 0.97), (f0 + 8, 1.0)):+ o.delta_scale = (s, s, s)+ o.keyframe_insert("delta_scale", frame=fr)++elif clip == "c_materials" and CLAY_PLATE:+ studio(True)+ clay_override()++elif clip == "c_materials":+ studio(False)+ # grime + decals fade in over frames 48-96 (the clay->material wipe over 1-48 is done on the frames, see bts_wipe)+ def key_value(sock, v0, v1):+ sock.default_value = v0+ sock.keyframe_insert("default_value", frame=48)+ sock.default_value = v1+ sock.keyframe_insert("default_value", frame=96)+ for m in bpy.data.materials:+ if not m.node_tree:+ continue+ for nd in m.node_tree.nodes:+ if nd.type == "GROUP" and nd.node_tree and nd.node_tree.name == "grime_layer":+ key_value(nd.inputs["Amount"], 0.0, nd.inputs["Amount"].default_value)+ DECALS = ("poster", "calendar", "flyer", "sticky", "price", "repair_tags", "tape_yellowed", "decal_signage", "drawer_labels",+ "puddle")+ for m in bpy.data.materials:+ if not m.node_tree or not any(k in m.name for k in DECALS):+ continue+ nt = m.node_tree+ out = next(nd for nd in nt.nodes if nd.type == "OUTPUT_MATERIAL")+ src = out.inputs["Surface"].links[0].from_socket+ mix = nt.nodes.new("ShaderNodeMixShader")+ tr = nt.nodes.new("ShaderNodeBsdfTransparent")+ nt.links.new(tr.outputs[0], mix.inputs[1])+ nt.links.new(src, mix.inputs[2])+ nt.links.new(mix.outputs[0], out.inputs["Surface"])+ key_value(mix.inputs[0], 0.0, 1.0)++elif clip == "d_lighting":+ r.engine = "CYCLES"+ prefs = bpy.context.preferences.addons["cycles"].preferences+ prefs.compute_device_type = "OPTIX"+ prefs.get_devices()+ for dv in prefs.devices:+ dv.use = dv.type == "OPTIX"+ c = sc.cycles+ c.device = "GPU"+ c.samples = 12+ c.use_adaptive_sampling = True+ c.adaptive_threshold = 0.05+ c.use_denoising = True+ c.denoiser = "OPTIX"+ c.max_bounces = 4+ c.diffuse_bounces, c.glossy_bounces, c.transmission_bounces = 2, 2, 4+ c.volume_step_rate = 8.0+ c.volume_max_steps = 256+ r.use_persistent_data = True+ sc.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.4 # near black+ # (start frame, names): practicals, signage/neon, window/street, fills + bounce+ STAGES = [+ (10, ("lamp_spot", "lamp_bounce")), (22, ("scope_spill",)), (32, ("counter_lamp_spot", "counter_lamp_fill")),+ (42, ("ring_lamp_light",)), (52, ("rack_clip_spot", "rack_clip_glow")),+ (72, ("neon_magenta",)), (80, ("neon_cyan",)), (88, ("aframe_glow", "vending_spill")),+ (108, ("street_fill",)), (118, ("streetlamp",)),+ (138, ("tube_racks_light",)), (150, ("rack_bounce",)), (160, ("counter_bounce",)),+ ]+ EMIT = { # emissive materials switch on with their practical+ "scope_crt": 22, "tv_crt": 52, "register_vfd": 32, "ring_led": 42, "clip_bulb": 52, "fluoro_on": 138,+ "street_backdrop": 108, "vending_panel": 88, "aframe_bulb": 88,+ }+ RAMP = 10+ staged = set()+ for f0, names in STAGES:+ for nm in names:+ o = sc.objects.get(nm)+ if not o:+ continue+ e = o.data.energy+ o.data.energy = 0.0+ o.data.keyframe_insert("energy", frame=f0)+ o.data.energy = e+ o.data.keyframe_insert("energy", frame=f0 + RAMP)+ staged.add(o.name)+ for o in lights: # anything not in the list comes on with the fills+ if o.name not in staged and not o.hide_render:+ e = o.data.energy+ o.data.energy = 0.0+ o.data.keyframe_insert("energy", frame=160)+ o.data.energy = e+ o.data.keyframe_insert("energy", frame=170)+ # emissive materials: a keyed multiplier in front of Emission Strength (default 0 = off until its stage)+ for m in bpy.data.materials:+ if not m.node_tree:+ continue+ b = next((nd for nd in m.node_tree.nodes if nd.type == "BSDF_PRINCIPLED"), None)+ if b is None:+ continue+ es = b.inputs["Emission Strength"]+ if not es.is_linked and es.default_value <= 0:+ continue+ f0 = next((v for k, v in EMIT.items() if k in m.name), 100)+ nt = m.node_tree+ mul = nt.nodes.new("ShaderNodeMath")+ mul.operation = "MULTIPLY"+ if es.is_linked:+ nt.links.new(es.links[0].from_socket, mul.inputs[0])+ else:+ mul.inputs[0].default_value = es.default_value+ nt.links.new(mul.outputs[0], es)+ mul.inputs[1].default_value = 0.0+ mul.inputs[1].keyframe_insert("default_value", frame=f0)+ mul.inputs[1].default_value = 1.0+ mul.inputs[1].keyframe_insert("default_value", frame=f0 + RAMP)+ # volumetrics: haze and rain fade in at the end+ if haze:+ haze.hide_render = False+ pv = next(nd for nd in haze.active_material.node_tree.nodes if nd.type == "PRINCIPLED_VOLUME")+ dens = pv.inputs["Density"]+ d = dens.default_value+ dens.default_value = 0.0+ dens.keyframe_insert("default_value", frame=176)+ dens.default_value = d+ dens.keyframe_insert("default_value", frame=212)+ rain = bpy.data.materials.get("rain")+ if rain:+ b = rain.node_tree.nodes["Principled BSDF"]+ a = b.inputs["Alpha"]+ a.default_value = 0.0+ a.keyframe_insert("default_value", frame=176)+ a.default_value = 0.35+ a.keyframe_insert("default_value", frame=212)++out = os.path.join(OUT, "clips", clip + ("_clayplate" if CLAY_PLATE else ""))+os.makedirs(out, exist_ok=True)+for f in range(first, last + 1):+ path = os.path.join(out, f"{f:04d}.png")+ if os.path.exists(path):+ continue+ sc.frame_set(f)+ r.filepath = path+ bpy.ops.render.render(write_still=True)+ print("BTS", clip, f, flush=True)diff --git a/scenes/tokyo-electronics-repair/scripts/bts_render.sh b/scenes/tokyo-electronics-repair/scripts/bts_render.shnew file mode 100644index 0000000..92da2e8--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/bts_render.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+# Render the four BTS dollhouse clips in short GPU-queue chunks, build the C wipe, encode mp4s and contact sheets.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++C=breakdown/tokyo-electronics-repair/clips+run() { # clip first last [clay]+ local t0=$(date +%s)+ bash pipeline/gpu_run.sh "$B" -b breakdown/tokyo-electronics-repair/bts.blend --python scenes/tokyo-electronics-repair/scripts/bts.py -- "$@" 2>&1 | grep -E "Traceback|Error:" | grep -v HIPEW+ echo "$* : $(( $(date +%s) - t0 )) s"+}+for r in "1 72" "73 144"; do run a_layout $r; done+for r in "1 80" "81 160" "161 240"; do run b_props $r; done+run c_materials 1 48 clay+for r in "1 72" "73 144"; do run c_materials $r; done+for r in "1 60" "61 120" "121 180" "181 240"; do run d_lighting $r; done+# C: soft diagonal wipe clay -> materials over frames 1-48 (frame files are the source of truth; mp4 is made from them)+mkdir -p $C/c_tmp+"$FF" -v error -y -framerate 24 -i $C/c_materials_clayplate/%04d.png -framerate 24 -i $C/c_materials/%04d.png -frames:v 48 \+ -filter_complex "[0:v][1:v]blend=all_expr='A*(1-clip((N/47*1.25-(X/W*0.8+Y/H*0.2))/0.25,0,1))+B*clip((N/47*1.25-(X/W*0.8+Y/H*0.2))/0.25,0,1)'" \+ -start_number 1 $C/c_tmp/%04d.png+for f in $C/c_tmp/*.png; do mv -f "$f" $C/c_materials/; done+rmdir $C/c_tmp+for c in a_layout b_props c_materials d_lighting; do+ "$FF" -v error -y -framerate 24 -i $C/$c/%04d.png -c:v h264_nvenc -preset p7 -rc vbr -cq 16 -b:v 0 -pix_fmt yuv420p -movflags +faststart $C/$c.mp4+ n=$(ls $C/$c | wc -l)+ "$FF" -v error -y -i $C/$c.mp4 -vf "select='not(mod(n\,$(( n / 8 ))))',scale=480:-1,tile=4x2" -frames:v 1 $C/${c}_contact.png+ echo "$c: $n frames"+done+echo BTS DONEdiff --git a/scenes/tokyo-electronics-repair/scripts/build_shell.py b/scenes/tokyo-electronics-repair/scripts/build_shell.pynew file mode 100644index 0000000..8661875--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/build_shell.py@@ -0,0 +1,240 @@+"""Repair shop: scripted room shell, storefront, furniture and fixtures (the video's "Building the Room" step).++blender -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/build_shell.py+-> scenes/tokyo-electronics-repair/repair_shell.blend+Coordinates: x across the shop (0 = bench wall), y from the storefront (0) to the back wall (6.5), z up. Metres.+"""+import math+import os+import random+import sys++import bpy+from mathutils import Vector++sys.path.insert(0, os.path.dirname(__file__))+import lib # noqa: E402+from lib import box, collection, cylinder, plane # noqa: E402++W, D, H = 4.2, 6.5, 2.7+T = 0.12 # wall thickness+SCN = os.path.join(lib.ROOT, "scenes", "tokyo-electronics-repair")+TEX = os.path.join(lib.ROOT, "refs", "tokyo-electronics-repair", "tex")+random.seed(7)++bpy.ops.wm.read_factory_settings(use_empty=True)+sc = bpy.context.scene+sc.unit_settings.system = "METRIC"++# ---------------------------------------------------------------- materials+M = {+ "floor": lib.floor_tiles("floor_vinyl", a=(0.4, 0.385, 0.34), b2=(0.24, 0.24, 0.23)),+ "wall": lib.wall_paint("wall_paint"),+ "ceiling": lib.grimy("ceiling_tile", (0.7, 0.69, 0.64), (0.4, 0.37, 0.3), amount=0.2, scale=2),+ "wood": lib.wood("bench_wood", light=(0.3, 0.19, 0.1), dark=(0.16, 0.09, 0.045), worn=0.6),+ "shelfwood": lib.wood("shelf_wood", light=(0.5, 0.36, 0.22), dark=(0.3, 0.2, 0.11), worn=0.2),+ "steel": lib.grimy("painted_steel", (0.32, 0.34, 0.33), (0.12, 0.1, 0.08), rough=(0.4, 0.7), metal=0.3, amount=0.3),+ "shelfsteel": lib.grimy("shelf_steel", (0.55, 0.56, 0.54), (0.2, 0.18, 0.15), rough=(0.35, 0.6), metal=0.4, amount=0.25),+ "alu": lib.grimy("aluminium", (0.62, 0.63, 0.64), (0.25, 0.24, 0.22), rough=(0.3, 0.5), metal=1.0, amount=0.2, bump=0.05),+ "glass": lib.rain_glass("rain_glass"),+ "doorglass": lib.principled("plain_glass", (0.9, 0.95, 0.95), 0.02, **{"Transmission Weight": 1.0}),+ "pegboard": None,+ "plastic_drawer": lib.principled("drawer_plastic", (0.75, 0.78, 0.8), 0.3, **{"Transmission Weight": 0.6, "IOR": 1.45}),+ "cabinet": lib.grimy("drawer_cabinet", (0.42, 0.44, 0.43), (0.15, 0.13, 0.1), amount=0.25),+ "door": lib.wood("door_wood", light=(0.32, 0.2, 0.12), dark=(0.18, 0.1, 0.06), scale=1.0, worn=0.15),+ "baseboard": lib.principled("baseboard", (0.12, 0.11, 0.1), 0.6),+ "tube": lib.principled("fluoro_tube_off", (0.85, 0.85, 0.82), 0.25, **{"Transmission Weight": 0.3}),+ "fixture": lib.grimy("fixture_white", (0.75, 0.74, 0.7), (0.35, 0.3, 0.22), amount=0.25),+ "conduit": lib.grimy("conduit", (0.6, 0.6, 0.58), (0.25, 0.22, 0.18), metal=0.6, amount=0.25),+ "black_plastic": lib.principled("black_plastic", (0.03, 0.03, 0.03), 0.45),+ "outlet": lib.principled("outlet_white", (0.8, 0.79, 0.74), 0.4),+}++# Pegboard: hardboard with a regular hole grid (Voronoi with zero randomness).+pm = bpy.data.materials.new("pegboard")+nt = pm.node_tree+bs = nt.nodes["Principled BSDF"]+tc = nt.nodes.new("ShaderNodeTexCoord")+vo = nt.nodes.new("ShaderNodeTexVoronoi")+vo.inputs["Scale"].default_value = 40+vo.inputs["Randomness"].default_value = 0.0+nt.links.new(tc.outputs["Object"], vo.inputs["Vector"])+hole = lib._ramp(nt, vo.outputs["Distance"], [(0.12, (0.015, 0.01, 0.008)), (0.16, (0.17, 0.11, 0.065))])+nt.links.new(hole.outputs["Color"], bs.inputs["Base Color"])+bs.inputs["Roughness"].default_value = 0.8+nt.links.new(lib._bump(nt, vo.outputs["Distance"], 0.6), bs.inputs["Normal"])+M["pegboard"] = pm++# ---------------------------------------------------------------- shell+C_SHELL = collection("shell")+box("floor", (-T, -0.5, -0.05), (W + T, D + T, 0), M["floor"], C_SHELL, bevel=0)+box("ceiling", (-T, -0.2, H), (W + T, D + T, H + 0.05), M["ceiling"], C_SHELL, bevel=0)+box("wall_left", (-T, 0, 0), (0, D, H), M["wall"], C_SHELL, bevel=0)+box("wall_right", (W, 0, 0), (W + T, D, H), M["wall"], C_SHELL, bevel=0)+# back wall with a door opening at x 2.4..3.3+DX0, DX1, DH = 2.4, 3.3, 2.05+box("wall_back_a", (-T, D, 0), (DX0, D + T, H), M["wall"], C_SHELL, bevel=0)+box("wall_back_b", (DX1, D, 0), (W + T, D + T, H), M["wall"], C_SHELL, bevel=0)+box("wall_back_c", (DX0, D, DH), (DX1, D + T, H), M["wall"], C_SHELL, bevel=0)+for name, lo, hi in (("baseboard_l", (0, 0.05, 0), (0.012, D, 0.08)), ("baseboard_r", (W - 0.012, 0.05, 0), (W, D, 0.08)),+ ("baseboard_b1", (0, D - 0.012, 0), (DX0, D, 0.08)), ("baseboard_b2", (DX1, D - 0.012, 0), (W, D, 0.08))):+ box(name, lo, hi, M["baseboard"], C_SHELL)+# door: frame + slab, slightly ajar into the dark back room+box("door_frame_l", (DX0, D - 0.02, 0), (DX0 + 0.05, D + T, DH + 0.05), M["door"], C_SHELL)+box("door_frame_r", (DX1 - 0.05, D - 0.02, 0), (DX1, D + T, DH + 0.05), M["door"], C_SHELL)+box("door_frame_t", (DX0, D - 0.02, DH), (DX1, D + T, DH + 0.05), M["door"], C_SHELL)+slab = box("door_slab", (DX0 + 0.05, D + 0.02, 0.01), (DX1 - 0.05, D + 0.06, DH - 0.005), M["door"], C_SHELL)+cylinder("door_handle", (DX1 - 0.13, D - 0.0, 1.0), 0.012, 0.12, M["alu"], C_SHELL, axis="X")+box("backroom_dark", (DX0 - 0.5, D + 1.5, 0), (DX1 + 0.5, D + 1.6, 2.4), lib.principled("backroom", (0.02, 0.02, 0.02), 0.9), C_SHELL, bevel=0)++# ---------------------------------------------------------------- storefront (y = 0)+C_FRONT = collection("storefront")+KNEE, TOP = 0.5, 2.3+A = M["alu"]+F = 0.05 # frame member size+box("front_knee_l", (0, -T, 0), (1.5, 0, KNEE), M["wall"], C_FRONT, bevel=0)+box("front_knee_r", (2.74, -T, 0), (W, 0, KNEE), M["wall"], C_FRONT, bevel=0)+box("front_header", (0, -T, TOP + F), (W, 0, H), M["wall"], C_FRONT, bevel=0)+for x in (0.0, 1.47, 2.72, W - F):+ box(f"front_post_{x:.2f}", (x, -0.07, 0), (x + F, 0.0, TOP + F), A, C_FRONT)+box("front_head", (0, -0.07, TOP), (W, 0.0, TOP + F), A, C_FRONT)+box("front_sill_l", (F, -0.07, KNEE), (1.47, 0.02, KNEE + F * 0.6), A, C_FRONT)+box("front_sill_r", (2.72 + F, -0.07, KNEE), (W - F, 0.02, KNEE + F * 0.6), A, C_FRONT)+box("glass_l", (F, -0.04, KNEE + 0.03), (1.47, -0.032, TOP), M["glass"], C_FRONT, bevel=0)+box("glass_r", (2.72 + F, -0.04, KNEE + 0.03), (W - F, -0.032, TOP), M["glass"], C_FRONT, bevel=0)+# two sliding door leaves, the right one slightly behind the left+for i, (x0, x1, y) in enumerate(((1.52, 2.16, -0.03), (2.08, 2.72, -0.06))):+ for nm, lo, hi in (("l", (x0, y - 0.03, 0.02), (x0 + F, y, TOP - 0.02)), ("r", (x1 - F, y - 0.03, 0.02), (x1, y, TOP - 0.02)),+ ("b", (x0, y - 0.03, 0.02), (x1, y, 0.14)), ("t", (x0, y - 0.03, TOP - 0.07), (x1, y, TOP - 0.02))):+ box(f"door_leaf{i}_{nm}", lo, hi, A, C_FRONT)+ box(f"door_leaf{i}_glass", (x0 + F, y - 0.018, 0.14), (x1 - F, y - 0.01, TOP - 0.07), M["glass"], C_FRONT, bevel=0)+ box(f"door_leaf{i}_pull", (x1 - 0.09 if i == 0 else x0 + 0.06, y + 0.0, 0.9), (x1 - 0.07 if i == 0 else x0 + 0.08, y + 0.03, 1.2), A, C_FRONT)+# window decal (reads mirrored from inside, as it should)+deco = lib.image_mat("decal_signage", os.path.join(TEX, "signage_0.png"), rough=0.4, alpha=True)+dp = plane("decal_signage", (3.43, -0.03, 1.55), 1.25, 0.7, "Y", deco, C_FRONT)+lib.set_uv_rect(dp, 0, 0, 1, 1) # exterior lettering: reads mirrored from inside+# outside: wet pavement strip, then the street backdrop as an emissive plane+box("pavement", (-1, -2.5, -0.08), (W + 1, -0.12, -0.06), lib.grimy("wet_pavement", (0.08, 0.08, 0.085), (0.02, 0.02, 0.02), rough=(0.05, 0.3), amount=0.4), C_FRONT, bevel=0)+box("road", (-3, -5.2, -0.1), (W + 3, -2.5, -0.08), lib.grimy("wet_asphalt", (0.035, 0.035, 0.04), (0.01, 0.01, 0.012), rough=(0.04, 0.25), amount=0.5, scale=1.5), C_FRONT, bevel=0)+street = lib.image_mat("street_backdrop", os.path.join(TEX, "street_0.png"), emission=1.2)+plane("street_backdrop", (W / 2, -4.5, 1.4), 9.0, 5.06, "Y", street, C_FRONT)++# ---------------------------------------------------------------- workbench along the left wall+C_BENCH = collection("bench")+BY0, BY1, BZ, BD = 1.3, 5.3, 0.88, 0.75+box("bench_top", (0.0, BY0, BZ - 0.045), (BD, BY1, BZ), M["wood"], C_BENCH, bevel=0.004)+box("bench_apron", (BD - 0.03, BY0 + 0.05, BZ - 0.13), (BD - 0.01, BY1 - 0.05, BZ - 0.045), M["steel"], C_BENCH)+for y in (BY0 + 0.04, (BY0 + BY1) / 2, BY1 - 0.04):+ for x in (0.04, BD - 0.06):+ box(f"bench_leg_{x:.2f}_{y:.2f}", (x - 0.02, y - 0.02, 0), (x + 0.02, y + 0.02, BZ - 0.045), M["steel"], C_BENCH)+box("bench_shelf", (0.02, BY0 + 0.02, 0.14), (BD - 0.04, BY1 - 0.02, 0.165), M["shelfwood"], C_BENCH)+box("bench_rail", (BD - 0.08, BY0, 0.14), (BD - 0.04, BY1, 0.18), M["steel"], C_BENCH)+# antistatic mat on part of the bench+box("bench_mat", (0.12, 2.0, BZ), (0.62, 2.9, BZ + 0.003), lib.grimy("esd_mat", (0.08, 0.13, 0.12), (0.03, 0.03, 0.03), rough=(0.5, 0.8), amount=0.3), C_BENCH, bevel=0)++# shelves above the bench+for z in (1.68, 2.12):+ box(f"shelf_{z}", (0.0, BY0, z), (0.32, BY1, z + 0.025), M["shelfwood"], C_BENCH)+ for y in (BY0 + 0.1, (BY0 + BY1) / 2, BY1 - 0.1):+ box(f"shelf_bracket_{z}_{y:.2f}", (0.0, y - 0.01, z - 0.18), (0.25, y + 0.01, z), M["steel"], C_BENCH)++# pegboard behind the right half of the bench+box("pegboard", (0.0, 3.15, 0.95), (0.012, 5.25, 1.6), M["pegboard"], C_BENCH, bevel=0)++# ---------------------------------------------------------------- sales counter in the front half (customers hand devices over here)+C_COUNTER = collection("counter")+CX0, CX1, CY0, CY1, CZ = 1.9, 3.5, 1.55, 2.15, 0.95+box("counter_body", (CX0, CY0, 0.0), (CX1, CY1 - 0.04, CZ - 0.03), M["door"], C_COUNTER, bevel=0.004)+box("counter_kick", (CX0 + 0.03, CY0 - 0.005, 0.0), (CX1 - 0.03, CY0 + 0.02, 0.09), M["baseboard"], C_COUNTER)+box("counter_top", (CX0 - 0.03, CY0 - 0.04, CZ - 0.03), (CX1 + 0.03, CY1, CZ), M["wood"], C_COUNTER, bevel=0.003)+box("counter_mat", (CX0 + 0.1, CY0 + 0.08, CZ), (CX0 + 0.55, CY0 + 0.45, CZ + 0.003), lib.principled("rubber_mat", (0.05, 0.05, 0.055), 0.7), C_COUNTER, bevel=0)++# ---------------------------------------------------------------- parts drawer cabinets (wall-mounted, labelled)+C_DRAW = collection("drawers")+labels = lib.image_mat("drawer_labels", os.path.join(TEX, "labels_0.png"), rough=0.6)+COLS, ROWS, CW, CH, CDEP = 5, 7, 0.1, 0.072, 0.17+for k, y0 in enumerate((BY0 + 0.05, BY0 + 0.6, BY0 + 1.15)):+ z0 = 1.15 # tucked under the lower shelf (1.68) so the bench below stays usable+ parts = [box(f"drawer_cab{k}_body", (0.0, y0, z0), (CDEP, y0 + COLS * CW + 0.02, z0 + ROWS * CH + 0.02), M["cabinet"], C_DRAW)]+ for r in range(ROWS):+ for c in range(COLS):+ yy = y0 + 0.01 + c * CW+ zz = z0 + 0.01 + r * CH+ pull = random.uniform(0, 0.025) if random.random() < 0.15 else 0.0+ parts.append(box(f"d{k}_{r}_{c}", (CDEP - 0.005 + pull, yy + 0.004, zz + 0.004), (CDEP + 0.003 + pull, yy + CW - 0.004, zz + CH - 0.004), M["plastic_drawer"], C_DRAW, bevel=0.001))+ parts.append(box(f"h{k}_{r}_{c}", (CDEP + 0.003 + pull, yy + CW / 2 - 0.012, zz + 0.008), (CDEP + 0.012 + pull, yy + CW / 2 + 0.012, zz + 0.016), M["cabinet"], C_DRAW, bevel=0.001))+ lab = plane(f"l{k}_{r}_{c}", (CDEP + 0.0035 + pull, yy + CW / 2, zz + CH * 0.62), CW * 0.62, CH * 0.32, "X", labels, C_DRAW)+ cell = random.randrange(36)+ u, v = cell % 6, cell // 6+ lib.set_uv_rect(lab, u / 6 + 0.01, 1 - (v + 1) / 6 + 0.02, (u + 1) / 6 - 0.01, 1 - v / 6 - 0.02)+ parts.append(lab)+ # join per cabinet: one object instead of ~100+ bpy.ops.object.select_all(action="DESELECT")+ for p in parts:+ for mod in p.modifiers:+ bpy.context.view_layer.objects.active = p+ bpy.ops.object.modifier_apply(modifier=mod.name)+ p.select_set(True)+ bpy.context.view_layer.objects.active = parts[0]+ bpy.ops.object.join()+ parts[0].name = f"drawer_cabinet_{k}"++# ---------------------------------------------------------------- steel shelving on the right wall+C_SHELF = collection("shelving")+for u, (y0, y1) in enumerate(((1.15, 2.35), (2.45, 3.65), (3.75, 4.95))):+ x0, x1, h = W - 0.46, W - 0.01, 1.95+ for x in (x0, x1 - 0.035):+ for y in (y0, y1 - 0.035):+ box(f"rack{u}_post_{x:.2f}_{y:.2f}", (x, y, 0), (x + 0.035, y + 0.035, h), M["shelfsteel"], C_SHELF, bevel=0.001)+ for z in (0.08, 0.5, 0.92, 1.34, 1.76):+ box(f"rack{u}_shelf_{z}", (x0, y0, z), (x1, y1, z + 0.02), M["shelfsteel"], C_SHELF, bevel=0.001)++# ---------------------------------------------------------------- ceiling: fluorescent fixtures (off) + conduit+C_CEIL = collection("ceiling")+for y in (2.0, 4.6):+ box(f"fixture_{y}", (1.9, y - 0.65, H - 0.06), (2.3, y + 0.65, H), M["fixture"], C_CEIL)+ for dx in (-0.08, 0.08):+ cylinder(f"tube_{y}_{dx}", (2.1 + dx, y, H - 0.08), 0.013, 1.2, M["tube"], C_CEIL, axis="Y")+cylinder("conduit_long", (0.12, D / 2, H - 0.04), 0.012, D, M["conduit"], C_CEIL, axis="Y")+cylinder("conduit_cross", (W / 2, D - 0.1, H - 0.04), 0.012, W, M["conduit"], C_CEIL, axis="X")+cylinder("conduit_drop", (0.04, BY0 + 0.3, (H + 1.0) / 2), 0.012, H - 1.0, M["conduit"], C_CEIL)+for y in (2.2, 3.4, 4.6):+ box(f"outlet_{y}", (0.0, y - 0.035, 0.95), (0.012, y + 0.035, 1.05), M["outlet"], C_SHELL)++# ---------------------------------------------------------------- textured planes: poster, calendar, repair tags+C_DECO = collection("deco")+plane("poster_parts", (W - 0.002, 5.55, 1.55), 0.5, 0.67, "-X", lib.image_mat("poster_parts", os.path.join(TEX, "poster_parts_0.png"), 0.8), C_DECO)+plane("calendar", (1.2, D - 0.002, 1.5), 0.36, 0.48, "-Y", lib.image_mat("calendar", os.path.join(TEX, "calendar_0.png"), 0.8), C_DECO)+tags = lib.image_mat("repair_tags", os.path.join(TEX, "tags_0.png"), 0.8)+for i in range(6): # tags pinned along the shelf edge+ t = plane(f"tag_{i}", (0.33, BY0 + 0.4 + i * 0.6, 1.62), 0.07, 0.11, "X", tags, C_DECO)+ t.rotation_euler = (random.uniform(-0.15, 0.15), 0, 0)+ cell = random.randrange(8)+ u, v = cell % 4, cell // 4+ lib.set_uv_rect(t, u / 4, 1 - (v + 1) / 2, (u + 1) / 4, 1 - v / 2)++# ---------------------------------------------------------------- cameras (refined after dressing)+def camera(name, loc, target, lens):+ cd = bpy.data.cameras.new(name)+ cd.lens = lens+ cd.sensor_width = 36+ cam = bpy.data.objects.new(name, cd)+ sc.collection.objects.link(cam)+ cam.location = loc+ cam.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()+ return cam+++sc.camera = camera("cam_wide", (3.35, 6.15, 1.55), (0.55, 1.2, 0.95), 20)+camera("cam_bench", (1.55, 3.2, 1.32), (0.25, 2.2, 0.92), 32)+camera("cam_front", (2.1, 5.9, 1.6), (2.1, 0, 1.2), 24)++os.makedirs(SCN, exist_ok=True)+bpy.ops.wm.save_as_mainfile(filepath=os.path.join(SCN, "repair_shell.blend"))+print("saved shell", len(bpy.data.objects), "objects")++# Window glass must not block light: refractive caustics are off, so a shadow-casting pane would cut off all street light.+for o in bpy.data.objects:+ if "glass" in o.name:+ o.visible_shadow = False+bpy.ops.wm.save_as_mainfile(filepath=os.path.join(SCN, "repair_shell.blend"))diff --git a/scenes/tokyo-electronics-repair/scripts/cameras.py b/scenes/tokyo-electronics-repair/scripts/cameras.pynew file mode 100644index 0000000..17a0484--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/cameras.py@@ -0,0 +1,95 @@+"""Hero cameras + a handheld clip camera for the repair shop (the video's phone-footage camera).++blender -b scenes/tokyo-electronics-repair/repair_lit.blend --python scenes/tokyo-electronics-repair/scripts/cameras.py -- <out.blend>+cam_wide / cam_bench: stills with DOF. cam_handheld: 120 frames (5 s @ 24 fps): a slow drift from the back of the shop+toward the bench, noise-driven shake on location + rotation, a slight exposure drift (auto-exposure hunting).+"""+import math+import os+import sys++import bpy+from mathutils import Vector++out = os.path.abspath(sys.argv[sys.argv.index("--") + 1])+sc = bpy.context.scene+++def aim(cam, loc, target):+ cam.location = loc+ cam.rotation_mode = "XYZ"+ cam.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()+++def focus_empty(name, loc):+ e = bpy.data.objects.get(name) or bpy.data.objects.new(name, None)+ if e.name not in sc.collection.objects:+ sc.collection.objects.link(e)+ e.location = loc+ return e+++def dof(cam, target, fstop):+ cam.data.dof.use_dof = True+ cam.data.dof.focus_object = target+ cam.data.dof.aperture_fstop = fstop+ cam.data.dof.aperture_blades = 6+++osc = sc.objects.get("oscilloscope")+osc_p = osc.location + Vector((0, 0, 0.1)) if osc else Vector((0.32, 2.2, 1.0))++# wide: from the back right, bench wall on the right, storefront glowing at the far end+wide = bpy.data.objects["cam_wide"]+aim(wide, (3.45, 6.2, 1.5), (0.9, 1.0, 0.95))+wide.data.lens = 21+dof(wide, focus_empty("focus_wide", (0.6, 2.6, 1.0)), 4.0)++# bench close-up: low over the bench edge, lamp pool and scope+bench = bpy.data.objects["cam_bench"]+aim(bench, (1.25, 3.05, 1.2), (0.3, 2.35, 0.95))+bench.data.lens = 30+dof(bench, focus_empty("focus_bench", osc_p), 2.0)++# handheld clip+cd = bpy.data.cameras.get("cam_handheld") or bpy.data.cameras.new("cam_handheld")+hh = bpy.data.objects.get("cam_handheld") or bpy.data.objects.new("cam_handheld", cd)+if hh.name not in sc.collection.objects:+ sc.collection.objects.link(hh)+cd.lens = 24+cd.sensor_width = 36+dof(hh, focus_empty("focus_hh", osc_p), 2.8)+hh.animation_data_clear()+sc.frame_start, sc.frame_end = 1, 120+keys = [ # frame, location, look-at+ (1, (3.3, 5.6, 1.58), (1.2, 1.2, 1.0)),+ (60, (2.6, 4.4, 1.5), (0.7, 2.0, 0.98)),+ (120, (1.75, 3.45, 1.38), (0.35, 2.35, 0.95)),+]+for f, loc, tgt in keys:+ aim(hh, loc, tgt)+ hh.keyframe_insert("location", frame=f)+ hh.keyframe_insert("rotation_euler", frame=f)+for fc in hh.animation_data.action.layers[0].strips[0].channelbag(hh.animation_data.action.slots[0]).fcurves if hasattr(hh.animation_data.action, "layers") else hh.animation_data.action.fcurves:+ for k in fc.keyframe_points:+ k.interpolation = "BEZIER"+ k.easing = "EASE_IN_OUT"+ m = fc.modifiers.new("NOISE")+ if fc.data_path == "location":+ m.strength, m.scale, m.phase = 0.018, 22, fc.array_index * 7.3+ else:+ m.strength, m.scale, m.phase = 0.01, 14, 3 + fc.array_index * 5.1+ m2 = fc.modifiers.new("NOISE") # fine jitter on top of the sway+ m2.strength, m2.scale, m2.phase = (0.004 if fc.data_path == "location" else 0.003), 3, 11 + fc.array_index++# exposure drift: a phone hunting for exposure as it moves toward the bright lamp+vs = sc.view_settings+base = vs.exposure+for f, d in ((1, 0.15), (40, 0.05), (85, -0.1), (120, -0.2)):+ vs.exposure = base + d+ vs.keyframe_insert("exposure", frame=f)+vs.exposure = base++sc.camera = wide+bpy.ops.wm.save_as_mainfile(filepath=out)+print("cameras ->", out)diff --git a/scenes/tokyo-electronics-repair/scripts/check_path.py b/scenes/tokyo-electronics-repair/scripts/check_path.pynew file mode 100644index 0000000..09db36f--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/check_path.py@@ -0,0 +1,43 @@+"""Camera-path clearance check for camrig shots: every frame's camera position vs every render-visible mesh (BVH nearest).+blender -b scenes/tokyo-electronics-repair/repair_final.blend --python scenes/tokyo-electronics-repair/scripts/check_path.py -- <shots.json> <name,name> [min=0.25]"""+import json, os, sys+import bpy+from mathutils import Vector+from mathutils.bvhtree import BVHTree+sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "camera"))+import camrig # noqa: E402+a = sys.argv[sys.argv.index("--") + 1:]+cfg = json.load(open(a[0]))+names = a[1].split(",")+lim = float(a[2]) if len(a) > 2 else 0.25+sc = bpy.context.scene+dg = bpy.context.evaluated_depsgraph_get()+skip = ("rain_", "haze", "street_backdrop", "CR_", "clay")+trees = []+for o in sc.objects:+ if o.type not in ("MESH", "CURVE") or not o.visible_get() or o.hide_render or o.name.startswith(skip):+ continue+ eo = o.evaluated_get(dg)+ me = eo.to_mesh()+ if me is None or not len(me.polygons):+ continue+ me.transform(o.matrix_world)+ trees.append((o.name, BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])))+ eo.to_mesh_clear()+shots = [camrig.merged(cfg.get("defaults", {}), s) for s in cfg["shots"]]+for i, s in enumerate(shots):+ if s["name"] not in names:+ continue+ cam = camrig.build(s, seed=i * 7)+ worst = (9, None, 0)+ bad = 0+ for f in range(1, int(s["frames"]) + 1):+ sc.frame_set(f)+ p = cam.matrix_world.translation.copy()+ for n, t in trees:+ loc, nrm, idx, d = t.find_nearest(p, lim * 2)+ if loc is not None and d < worst[0]:+ worst = (d, n, f)+ if loc is not None and d < lim:+ bad += 1+ print(f"PATH {s['name']}: min clearance {worst[0]:.2f} m to {worst[1]} at frame {worst[2]}; {bad} frame-object hits under {lim} m")diff --git a/scenes/tokyo-electronics-repair/scripts/compare.py b/scenes/tokyo-electronics-repair/scripts/compare.pynew file mode 100644index 0000000..b2bd435--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/compare.py@@ -0,0 +1,206 @@+"""Head-to-head renders of generated props: same studio light and camera fit for every model.++blender -b --factory-startup --python pipeline/render_compare.py -- assets/gen out/compare+For every assets/gen/<model>/<prop>/model.glb writes out/compare/<model>/<prop>_{beauty,clay}.png + stats.json.+"""+import json+import math+import os+import sys++import bpy+from mathutils import Vector++ARGS = sys.argv[sys.argv.index("--") + 1:]+ROOT, OUT = map(os.path.abspath, ARGS[:2])+IDS = set(ARGS[2].split(",")) if len(ARGS) > 2 else None+HDRI = bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")+RES = 640+PROBE = bool(os.environ.get("PROBE"))+# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.+_yaw_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "out", "compare", "yaw.json")+YAW = json.load(open(_yaw_path)) if os.path.exists(_yaw_path) else {}+++def reset():+ bpy.ops.wm.read_factory_settings(use_empty=True)+ sc = bpy.context.scene+ sc.render.engine = "CYCLES"+ prefs = bpy.context.preferences.addons["cycles"].preferences+ prefs.compute_device_type = "OPTIX"+ prefs.get_devices()+ for d in prefs.devices:+ d.use = d.type == "OPTIX"+ sc.cycles.device = "GPU"+ sc.cycles.samples = 48+ sc.cycles.use_denoising = True+ sc.render.resolution_x = sc.render.resolution_y = RES+ sc.render.film_transparent = False+ sc.view_settings.view_transform = "AgX"+ sc.view_settings.look = "AgX - Medium High Contrast"+ world = bpy.data.worlds.new("w")+ sc.world = world+ world.use_nodes = True+ nt = world.node_tree+ env = nt.nodes.new("ShaderNodeTexEnvironment")+ env.image = bpy.data.images.load(HDRI)+ bg = nt.nodes["Background"]+ bg.inputs["Strength"].default_value = 0.6+ nt.links.new(env.outputs["Color"], bg.inputs["Color"])+ return sc+++def add_light(name, loc, 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(loc)).to_track_quat("-Z", "Y").to_euler() # area lights shine along -Z+++def import_glb(path):+ before = set(bpy.data.objects)+ bpy.ops.import_scene.gltf(filepath=path)+ meshes = [o for o in bpy.data.objects if o not in before and o.type == "MESH"]+ return meshes+++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 stats(objs, real_size):+ tris = verts = 0+ images = {}+ for o in objs:+ me = o.data+ me.calc_loop_triangles()+ tris += len(me.loop_triangles)+ verts += len(me.vertices)+ for slot in o.material_slots:+ if slot.material and slot.material.use_nodes:+ for n in slot.material.node_tree.nodes:+ if n.type == "TEX_IMAGE" and n.image:+ out = [l.to_socket.name for l in n.outputs["Color"].links]+ images[n.image.name] = {"size": list(n.image.size), "feeds": out}+ return {"tris": tris, "verts": verts, "objects": len(objs), "images": images, "size_m": [round(v, 3) for v in real_size]}+++def clay_wire(objs):+ m = bpy.data.materials.new("clay")+ m.use_nodes = True+ nt = m.node_tree+ bsdf = nt.nodes["Principled BSDF"]+ bsdf.inputs["Base Color"].default_value = (0.55, 0.55, 0.55, 1)+ bsdf.inputs["Roughness"].default_value = 0.6+ wire = nt.nodes.new("ShaderNodeWireframe")+ wire.use_pixel_size = True+ wire.inputs["Size"].default_value = 0.35+ mix = nt.nodes.new("ShaderNodeMix")+ mix.data_type = "RGBA"+ mix.inputs["A"].default_value = (0.55, 0.55, 0.55, 1)+ mix.inputs["B"].default_value = (0.08, 0.12, 0.2, 1)+ nt.links.new(wire.outputs["Fac"], mix.inputs["Factor"])+ nt.links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])+ for o in objs:+ o.data.materials.clear()+ o.data.materials.append(m)+++def render_one(glb, out_prefix):+ sc = reset()+ objs = import_glb(glb)+ lo, hi = bounds(objs)+ real = hi - lo+ # Normalize: centre on origin, rest on the floor, largest dimension 1 m (framing only; real size goes in stats).+ s = 1.0 / max(real)+ root = bpy.data.objects.new("root", None)+ sc.collection.objects.link(root)+ for o in [o for o in bpy.data.objects if o.parent is None and o is not root]:+ o.parent = root+ c = (lo + hi) / 2+ root.scale = (s, s, s)+ root.location = (-c.x * s, -c.y * s, -lo.z * s)+ bpy.context.view_layer.update()+ lo, hi = bounds(objs)+ centre = (lo + hi) / 2+ radius = (hi - lo).length / 2++ # Shadow catcher-ish floor.+ bpy.ops.mesh.primitive_plane_add(size=20)+ floor = bpy.context.object+ fm = bpy.data.materials.new("floor")+ fm.use_nodes = True+ fm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.32, 0.32, 0.33, 1)+ fm.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.8+ floor.data.materials.append(fm)++ add_light("key", (2.2, -2.6, 3.0), 260, 1.6)+ add_light("fill", (-3.0, -1.5, 1.6), 70, 2.5, (0.85, 0.9, 1.0))+ add_light("rim", (-1.0, 3.0, 2.5), 160, 1.2)++ cam_d = bpy.data.cameras.new("cam")+ cam_d.lens = 70+ cam = bpy.data.objects.new("cam", cam_d)+ sc.collection.objects.link(cam)+ sc.camera = cam+ fov = cam_d.angle+ dist = radius / math.sin(fov / 2) * 1.02++ def shoot(az_deg, el_deg, path):+ az, el = math.radians(az_deg), math.radians(el_deg)+ d = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))+ cam.location = centre + d * dist+ cam.rotation_euler = (centre - cam.location).to_track_quat("-Z", "Y").to_euler()+ sc.render.filepath = path+ bpy.ops.render.render(write_still=True)++ st = stats(objs, real)+ if PROBE: # four cardinal views to find which way a generator's "front" faces+ sc.render.resolution_x = sc.render.resolution_y = 360+ sc.cycles.samples = 16+ for az in (0, 90, 180, 270):+ shoot(az, 15, f"{out_prefix}_az{az:03d}.png")+ return st+ yaw = YAW.get(os.path.basename(os.path.dirname(out_prefix)), 0)+ shoot(yaw - 30, 18, out_prefix + "_beauty.png")+ shoot(yaw + 150, 22, out_prefix + "_back.png")+ clay_wire(objs)+ shoot(yaw - 30, 18, out_prefix + "_clay.png")+ return st+++def main():+ allstats = {}+ for model in ("tripo-h31", "meshy"):+ for prop in sorted(os.listdir(os.path.join(ROOT, model))):+ glb = os.path.join(ROOT, model, prop, "model.glb")+ if IDS and prop not in IDS:+ continue+ if not os.path.exists(glb):+ continue+ od = os.path.join(OUT, model)+ os.makedirs(od, exist_ok=True)+ prefix = os.path.join(od, prop)+ done = prefix + ("_az270.png" if PROBE else "_clay.png")+ if os.path.exists(done) and os.path.getmtime(done) > os.path.getmtime(glb):+ print("skip", model, prop)+ continue+ print("render", model, prop, flush=True)+ try:+ allstats.setdefault(model, {})[prop] = render_one(glb, prefix)+ except Exception as e: # keep going; a broken GLB is itself a result+ allstats.setdefault(model, {})[prop] = {"error": repr(e)}+ print("FAILED", model, prop, e, flush=True)+ sp = os.path.join(OUT, "stats.json")+ old = json.load(open(sp)) if os.path.exists(sp) else {}+ for m, d in allstats.items():+ old.setdefault(m, {}).update(d)+ json.dump(old, open(sp, "w"), indent=2)+++main()diff --git a/scenes/tokyo-electronics-repair/scripts/compare_ready.sh b/scenes/tokyo-electronics-repair/scripts/compare_ready.shnew file mode 100644index 0000000..7d1c0f5--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/compare_ready.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# Render compare views for every repair_* GLB that exists and has not been rendered yet (under the GPU lock).+cd "$(dirname "$0")/../../.."+. pipeline/env.sh+ids=$(ls -d assets/gen/tripo-h31/repair_* assets/gen/meshy/repair_* 2>/dev/null | xargs -n1 basename | sort -u | tr '\n' ',')+[ -z "$ids" ] && exit 0+bash pipeline/gpu_run.sh "$B" -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/compare.py -- assets/gen scenes/tokyo-electronics-repair/compare "${ids%,}" 2>&1 | grep -E "^render|FAILED"diff --git a/scenes/tokyo-electronics-repair/scripts/debrand.py b/scenes/tokyo-electronics-repair/scripts/debrand.pynew file mode 100644index 0000000..2a0b9bc--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/debrand.py@@ -0,0 +1,201 @@+"""De-brand prepped props by painting over brand marks in their albedo textures (scripted texture paint).++blender -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/debrand.py -- [id ...]+Regions are rectangles in the normalised coordinates of views.py's ortho images (u right, v down, 0..1).+For each region: cast rays from that view across the rectangle, collect the texels the hits land on, dilate that mask+in UV space, and fill it with a normalised-convolution blur of the surrounding unmasked texels plus a little grain, so+the patch takes the colour of the plastic/paint around it. The edited texture is saved next to the original as *_nb.png.+"""+import os+import sys++import bpy+import numpy as np+from mathutils import Vector+from mathutils.bvhtree import BVHTree++sys.path.insert(0, os.path.dirname(__file__))+from views import VIEWS, frame # noqa: E402++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+PROPS = os.path.join(ROOT, "scenes", "tokyo-electronics-repair", "props")+only = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []++WRAP = [("front", 0.0, 0.22, 1.0, 1.0), ("back", 0.0, 0.22, 1.0, 1.0), ("left", 0.0, 0.22, 1.0, 1.0), ("right", 0.0, 0.22, 1.0, 1.0)]+REGIONS = {+ "oscilloscope": [("front", 0.46, 0.2, 0.62, 0.255)],+ "solder_station": [("front", 0.02, 0.42, 0.39, 0.55), ("front", 0.73, 0.2, 0.9, 0.42)],+ "repair_multimeter_yellow": [("top", 0.13, 0.09, 0.36, 0.19)],+ "repair_multimeter_red": [("front", 0.13, 0.04, 0.27, 0.13), ("front", 0.5, 0.03, 0.72, 0.14), ("top", 0.16, 0.22, 0.7, 0.32)],+ "repair_bench_psu": [("front", 0.02, 0.11, 0.98, 0.2)],+ "repair_tool_chest": [("front", 0.2, 0.02, 0.58, 0.18), ("front", 0.56, 0.15, 0.7, 0.23), ("front", 0.64, 0.24, 0.8, 0.31),+ ("front", 0.66, 0.51, 0.82, 0.59), ("front", 0.15, 0.25, 0.3, 0.4), ("front", 0.22, 0.73, 0.48, 0.85),+ ("right", 0.45, 0.25, 0.7, 0.42), ("right", 0.5, 0.55, 0.72, 0.7), ("left", 0.28, 0.25, 0.6, 0.42),+ ("left", 0.25, 0.55, 0.5, 0.7), ("back", 0.62, 0.02, 0.82, 0.13), ("top", 0.1, 0.1, 0.9, 0.9)],+ # spray cans, cup noodle and tissue box are replaced by direct-modelled generic versions (props_direct.py)+ "repair_boxes_b": [("front", 0.28, 0.64, 0.62, 0.82), ("back", 0.28, 0.64, 0.62, 0.82)],+ "repair_vcr_open": [("front", 0.02, 0.43, 0.13, 0.54)],+ "repair_rice_cooker": [("front", 0.38, 0.46, 0.54, 0.56)],+ "repair_vintage_radio": [("front", 0.1, 0.58, 0.35, 0.69)],+ "repair_receiver": [("front", 0.02, 0.3, 0.27, 0.38)],+ "repair_solder_junk": [("top", 0.08, 0.26, 0.34, 0.38), ("top", 0.68, 0.38, 0.94, 0.49),+ ("front", 0.43, 0.34, 0.69, 0.48), ("back", 0.3, 0.34, 0.57, 0.48),+ ("left", 0.0, 0.3, 1.0, 0.6), ("right", 0.0, 0.3, 1.0, 0.6)],+ "repair_laptop_broken": [("top", 0.26, 0.3, 0.38, 0.38), ("top", 0.48, 0.72, 0.58, 0.8)],+ "repair_crt_stack": [("front", 0.46, 0.22, 0.58, 0.31)],+ "repair_turntable": [("front", 0.43, 0.18, 0.57, 0.37), ("top", 0.44, 0.27, 0.58, 0.36), ("top", 0.06, 0.71, 0.24, 0.81)],+ "repair_desk_fan": [("front", 0.36, 0.86, 0.57, 0.96), ("front", 0.4, 0.28, 0.6, 0.4)],+ "repair_kerosene_heater": [("front", 0.4, 0.46, 0.6, 0.56)],+}+++def albedo_nodes(ob):+ """Material index -> the image node feeding Base Color (generated props can carry several materials)."""+ out = {}+ for i, slot in enumerate(ob.material_slots):+ if not slot.material or not slot.material.node_tree:+ continue+ for n in slot.material.node_tree.nodes:+ if n.type == "TEX_IMAGE" and n.image and any(l.to_socket.name == "Base Color" for l in n.outputs["Color"].links):+ out[i] = n+ break+ return out+++def box_blur(a, r):+ """Separable box blur (r px) over axes 0 and 1, edge-clamped, via cumulative sums."""+ for ax in (0, 1):+ pad = [(0, 0)] * a.ndim+ pad[ax] = (r + 1, r)+ p = np.pad(a, pad, mode="edge")+ c = np.cumsum(p, axis=ax)+ hi = np.take(c, range(2 * r + 1, c.shape[ax]), axis=ax)+ lo = np.take(c, range(0, c.shape[ax] - 2 * r - 1), axis=ax)+ a = (hi - lo) / (2 * r + 1)+ return a+++class Tex:+ def __init__(self, node):+ self.node, self.img = node, node.image+ self.w, self.h = self.img.size+ px = np.empty(self.w * self.h * 4, dtype=np.float32)+ self.img.pixels.foreach_get(px)+ self.px = px.reshape(self.h, self.w, 4)+ self.rgb = self.px[..., :3].copy()+ self.total = np.zeros((self.h, self.w), dtype=bool)+++def debrand(pid):+ bpy.ops.wm.open_mainfile(filepath=os.path.join(PROPS, f"{pid}.blend"))+ ob = bpy.data.objects[pid]+ if ob.get("debranded"):+ print("already", pid)+ return+ nodes = albedo_nodes(ob)+ texs = {} # image name -> Tex (materials may share an image)+ mat_tex = {}+ for mi, n in nodes.items():+ texs.setdefault(n.image.name, Tex(n))+ mat_tex[mi] = texs[n.image.name]+ me = ob.data+ me.calc_loop_triangles()+ verts = [v.co.copy() for v in me.vertices]+ tris = me.loop_triangles+ bvh = BVHTree.FromPolygons(verts, [tuple(t.vertices) for t in tris])+ uvl = me.uv_layers.active.data+ hits = 0+ rng = np.random.default_rng(1)+ for view, u0, v0, u1, v1 in REGIONS[pid]:+ masks = {k: np.zeros((t.h, t.w), dtype=bool) for k, t in texs.items()}+ c, span, d, hx, vx = frame(ob, view)+ area = (u1 - u0) * (v1 - v0)+ step = 1 / 512 if area > 0.05 else 0.5 / 512+ for u in np.arange(u0, u1, step):+ for v in np.arange(v0, v1, step):+ p = c + hx * ((u - 0.5) * span) + vx * ((0.5 - v) * span) - d * 3+ loc, nrm, idx, dist = bvh.ray_cast(p, d)+ if loc is None:+ continue+ t = tris[idx]+ tx = mat_tex.get(t.material_index)+ if tx is None:+ continue+ a, b, cc = (verts[i] for i in t.vertices)+ e0, e1, e2 = b - a, cc - a, loc - a+ d00, d01, d11, d20, d21 = e0.dot(e0), e0.dot(e1), e1.dot(e1), e2.dot(e0), e2.dot(e1)+ den = d00 * d11 - d01 * d01 or 1e-12+ bv = (d11 * d20 - d01 * d21) / den+ bw = (d00 * d21 - d01 * d20) / den+ uv = uvl[t.loops[0]].uv * (1 - bv - bw) + uvl[t.loops[1]].uv * bv + uvl[t.loops[2]].uv * bw+ masks[tx.img.name][int((uv.y % 1) * (tx.h - 1)), int((uv.x % 1) * (tx.w - 1))] = True+ hits += 1+ for k, mask in masks.items():+ tx = texs[k]+ # dilate a few texels so glyph edges are covered too (threshold: cumsum round-off leaves tiny non-zeros)+ m = box_blur(mask.astype(np.float64), 3) > 0.01+ if not m.any():+ continue+ # paint colour: the label background, i.e. the median of the brighter half of the texels under the region+ # (printing is mostly dark marks on a lighter ground); dark grounds use the darker half instead+ cols = tx.px[..., :3][m]+ lum = cols @ np.array([0.2126, 0.7152, 0.0722])+ side = lum >= np.median(lum) if np.median(lum) > 0.25 else lum <= np.median(lum)+ base_col = np.median(cols[side], axis=0)+ grain = 1 + rng.normal(0, 0.02, (tx.h, tx.w))[..., None] + box_blur(rng.normal(0, 1, (tx.h, tx.w)), 6)[..., None] * 0.15+ soft = np.clip(box_blur(m.astype(np.float64), 2) * 1.5, 0, 1)[..., None]+ tx.rgb = tx.rgb * (1 - soft) + (base_col * grain) * soft+ tx.total |= m+ painted = 0+ for k, tx in texs.items():+ if not tx.total.any():+ continue+ tx.px[..., :3] = tx.rgb+ base, ext = os.path.splitext(bpy.path.abspath(tx.img.filepath_raw or tx.img.filepath))+ if not os.path.basename(base):+ base = os.path.join(PROPS, "tex", f"{pid}_{k}")+ out = f"{base}_nb.png"+ nb = bpy.data.images.new(f"{k}_nb", tx.w, tx.h, alpha=True)+ nb.pixels.foreach_set(tx.px.ravel())+ nb.filepath_raw = out+ nb.file_format = "PNG"+ nb.save()+ nb.filepath = out+ for n in nodes.values():+ if n.image == tx.img:+ n.image = nb+ painted += int(tx.total.sum())+ # embossed print survives in the normal map: flatten the same texels there+ mat = next(sl.material for sl in ob.material_slots if sl.material and tx.node.name in sl.material.node_tree.nodes+ and sl.material.node_tree.nodes[tx.node.name] == tx.node)+ for n in mat.node_tree.nodes:+ if n.type == "TEX_IMAGE" and n.image and any(l.to_node.type == "NORMAL_MAP" for l in n.outputs["Color"].links):+ nw, nh = n.image.size+ npx = np.empty(nw * nh * 4, dtype=np.float32)+ n.image.pixels.foreach_get(npx)+ npx = npx.reshape(nh, nw, 4)+ ys = (np.arange(nh) * tx.h // nh)[:, None]+ xs = (np.arange(nw) * tx.w // nw)[None, :]+ mm = tx.total[ys, xs]+ npx[mm, 0:3] = (0.5, 0.5, 1.0)+ nimg = bpy.data.images.new(n.image.name + "_nb", nw, nh, alpha=True)+ nimg.colorspace_settings.name = "Non-Color"+ nimg.pixels.foreach_set(npx.ravel())+ nb_out = os.path.splitext(bpy.path.abspath(n.image.filepath_raw or n.image.filepath))[0] + "_nb.png"+ nimg.filepath_raw = nb_out+ nimg.file_format = "PNG"+ nimg.save()+ nimg.filepath = nb_out+ n.image = nimg+ ob["debranded"] = True+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(PROPS, f"{pid}.blend"))+ print(f"DEBRAND {pid}: {hits} hits, {painted} texels repainted over {len(texs)} textures")+++for pid in REGIONS:+ if only and pid not in only:+ continue+ try:+ debrand(pid)+ except Exception as e:+ print("DEBRAND FAILED", pid, repr(e))diff --git a/scenes/tokyo-electronics-repair/scripts/dress.py b/scenes/tokyo-electronics-repair/scripts/dress.pynew file mode 100644index 0000000..f22d4ea--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/dress.py@@ -0,0 +1,200 @@+"""Dress the repair shop: append prepped props and place them, big props first, then small (the video's "Dressing the Room").++blender -b scenes/tokyo-electronics-repair/repair_shell.blend --python scenes/tokyo-electronics-repair/scripts/dress.py -- <pass>+pass 1 = furniture-scale props, 2 = + bench/shelf props, 3 = + small clutter. Saves scenes/tokyo-electronics-repair/repair_dressed.blend.+Placement: x, y in metres; yaw in degrees (library props face -Y; 90 faces +X = into the room from the bench wall);+"from" is the height the drop ray starts at (just under whatever is above the support); "z" pins the height instead.+"""+import json+import math+import os+import random+import sys++import bpy+from mathutils import Vector++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+SCN = os.path.join(ROOT, "scenes", "tokyo-electronics-repair")+PASS = int(sys.argv[sys.argv.index("--") + 1]) if "--" in sys.argv else 4+random.seed(3)++BENCH, SHELF1, SHELF2 = 1.12, 2.05, 2.6 # ray start heights for the bench top, lower shelf, upper shelf+RX = 3.965 # centre x of the right-wall racks+RACK = [0.49, 0.91, 1.33, 1.75, 2.6] # RACK[i]: ray start for an item standing on rack shelf i (just under shelf i+1)++# (pass, id, x, y, yaw, kw)+LAYOUT = [+ # pass 1: big floor props+ (1, "repair_tool_chest", 1.05, 6.2, 0, {}),+ (1, "repair_crt_stack", 3.72, 5.95, -20, {"back": "x1"}),+ (1, "repair_kerosene_heater", 0.45, 5.85, 60, {}),+ (1, "repair_stool", 1.1, 2.75, 20, {}),+ (1, "repair_boxes_a", RX, 1.75, -90, {"from": 2.65}),+ (1, "repair_boxes_b", RX, 4.35, -95, {"from": 2.65}),+ (1, "repair_boxes_b", 0.55, 0.55, 160, {"name": "boxes_b_front"}),+ (1, "repair_boxes_a", 2.0, 6.17, 5, {"name": "boxes_a_back"}),+ (1, "repair_trash_bin", 0.95, 5.45, 0, {}),+ # pass 2: bench heroes+ (2, "oscilloscope", 0.32, 2.2, 108, {"from": BENCH}),+ (2, "repair_bench_psu", 0.24, 1.6, 85, {"from": BENCH}),+ (2, "helping_hands", 0.5, 2.68, 115, {"from": BENCH}),+ (2, "repair_work_lamp", 0.5, 2.86, 27, {"z": 0.88}), # clamp on the front edge right of the scope, arm reaching back-left over the helping hands, clear of the drawer cabinets+ (2, "solder_station", 0.27, 3.1, 100, {"from": BENCH}),+ (2, "boombox_open", 0.32, 3.7, 92, {"from": BENCH}),+ (2, "repair_vcr_open", 0.3, 4.3, 88, {"from": BENCH}),+ # pass 2: shelves above the bench + racks+ (2, "repair_vintage_radio", 0.16, 1.85, 90, {"from": SHELF1}),+ (2, "repair_receiver", 0.17, 2.3, 90, {"from": SHELF1}),+ (2, "repair_rice_cooker", 0.16, 3.0, 75, {"from": SHELF1}),+ (2, "repair_crt_tv", 0.17, 3.65, 85, {"from": SHELF1}),+ (2, "repair_turntable", 0.17, 4.5, 90, {"from": SHELF1}),+ (2, "repair_desk_fan", 0.16, 1.7, 110, {"from": SHELF2}),+ (2, "repair_crt_tv", 0.17, 4.75, 95, {"from": SHELF2, "name": "crt_tv_shelf2"}),+ (2, "repair_receiver", RX, 1.42, -90, {"from": RACK[0], "name": "receiver_rack"}),+ (2, "repair_vcr_open", RX, 2.0, -88, {"from": RACK[1], "name": "vcr_rack"}),+ (2, "repair_vintage_radio", RX, 3.05, -95, {"from": RACK[0], "name": "radio_rack"}),+ (2, "repair_rice_cooker", RX, 2.75, -80, {"from": RACK[2], "name": "rice_rack"}),+ (2, "repair_turntable", RX, 3.1, -90, {"from": RACK[1], "name": "turntable_rack"}),+ (2, "repair_crt_tv", RX, 4.25, -100, {"from": RACK[0], "name": "crt_rack"}),+ (2, "repair_desk_fan", RX, 1.6, -70, {"from": RACK[2], "name": "fan_rack", "scale": 0.88}),+ (2, "repair_kerosene_heater", RX, 3.45, -90, {"from": RACK[0], "name": "heater_rack", "scale": 0.84}),+ (2, "repair_cable_coils", 0.06, 5.65, 90, {"z": 1.25}),+ (2, "repair_wall_clock", 1.9, 6.47, 0, {"z": 2.08}),+ # pass 3: small clutter+ (3, "repair_multimeter_red", 0.58, 1.78, 125, {"from": BENCH}),+ (3, "repair_multimeter_yellow", 0.68, 3.42, 60, {"from": BENCH}),+ (3, "repair_parts_tray", 0.62, 4.55, 95, {"from": BENCH}),+ (3, "repair_solder_junk", 0.62, 2.3, 30, {"from": BENCH}),+ (3, "repair_mug", 0.66, 5.12, 200, {"from": BENCH}),+ (3, "repair_tool_block", 0.12, 4.7, 90, {"from": BENCH}),+ (3, "repair_mug", 0.15, 5.0, 120, {"from": SHELF1, "name": "mug_shelf"}),+ (3, "repair_parts_tray", RX, 3.4, -80, {"from": RACK[3], "name": "tray_rack"}),+ (3, "repair_multimeter_yellow", RX, 2.2, -120, {"from": RACK[3], "name": "dmm_rack"}),+ # pass 4: fill. Instances (linked duplicates) of devices waiting on every rack shelf, under the bench, on the counter+ (4, "repair_cassette_deck", RX, 1.55, -88, {"from": RACK[1], "name": "fill_receiver_1", "alt": "repair_receiver"}),+ (4, "repair_amp_black", RX, 1.95, -92, {"from": RACK[2], "name": "fill_vcr_1", "alt": "repair_vcr_open"}),+ (4, "repair_crt_monitor_beige", RX, 2.12, -85, {"from": RACK[0], "name": "fill_crt_1", "alt": "repair_crt_tv"}),+ (4, "repair_radio_cassette", RX, 1.78, -95, {"from": RACK[3], "name": "fill_radio_1", "alt": "repair_vintage_radio"}),+ (4, "repair_electric_kettle", RX, 2.66, -100, {"from": RACK[1], "name": "fill_rice_1", "alt": "repair_rice_cooker"}),+ (4, "repair_dotmatrix_printer", RX, 3.2, -90, {"from": RACK[2], "name": "fill_receiver_2", "alt": "repair_receiver"}),+ (4, "repair_crt_tv", RX, 2.85, -92, {"from": RACK[3], "name": "fill_crt_2"}),+ (4, "repair_portable_tv", RX, 2.62, -60, {"from": RACK[0], "name": "fill_fan_1", "alt": "repair_desk_fan", "scale": 0.88}),+ (4, "repair_fax_phone", RX, 4.1, -90, {"from": RACK[1], "name": "fill_vcr_2", "alt": "repair_vcr_open"}),+ (4, "repair_speaker_pair", RX, 4.35, -95, {"from": RACK[2], "name": "fill_turntable_1", "alt": "repair_turntable", "scale": 0.85}),+ (4, "repair_camcorder", RX, 4.6, -85, {"from": RACK[3], "name": "fill_radio_2", "alt": "repair_vintage_radio"}),+ (4, "repair_microwave", RX, 4.7, -90, {"from": RACK[0], "name": "fill_heater_1", "alt": "repair_kerosene_heater", "scale": 0.84}),+ (4, "repair_boxes_b", RX, 3.05, -88, {"from": 2.65, "name": "fill_boxes_rack2"}),+ (4, "repair_tv_wood", 0.3, 1.75, 95, {"from": 0.8, "name": "fill_crt_under", "alt": "repair_crt_tv"}),+ (4, "repair_karaoke_machine", 0.3, 2.5, 90, {"from": 0.8, "name": "fill_receiver_under", "alt": "repair_receiver"}),+ (4, "repair_rice_cooker", 0.3, 3.1, 70, {"from": 0.8, "name": "fill_rice_under"}),+ (4, "repair_boxes_b", 0.35, 3.85, 92, {"from": 0.8, "name": "fill_boxes_under", "scale": 0.7}),+ (4, "repair_pc_tower", 0.3, 4.75, 85, {"from": 0.8, "name": "fill_vcr_under", "alt": "repair_vcr_open"}),+ (4, "repair_multimeter_yellow", 2.98, 1.68, 150, {"from": 1.4, "name": "counter_dmm"}),+ (4, "repair_laptop_broken", 2.66, 1.78, 175, {"from": 1.4, "name": "counter_laptop"}),+ (4, "repair_parts_tray", 3.0, 2.0, 185, {"from": 1.4, "name": "counter_tray"}),+ (4, "solder_station", 0.25, 5.0, 100, {"from": BENCH, "name": "solder_station_2"}),+ (4, "repair_bench_psu", 0.2, 4.15, 92, {"from": SHELF1, "name": "psu_shelf"}),+ (4, "repair_multimeter_red", 0.55, 4.88, 140, {"from": BENCH, "name": "dmm_station2"}),+ (4, "repair_boxes_a", 1.3, 0.75, 170, {"name": "fill_boxes_front"}),+ (4, "repair_tv_wood", 3.55, 0.45, 205, {"name": "fill_crt_floor", "alt": "repair_crt_tv"}),+ (4, "repair_floor_fan", 2.75, 5.0, 30, {"name": "fill_heater_floor", "alt": "repair_kerosene_heater"}),+ (4, "repair_stool", 2.85, 2.62, -20, {"name": "counter_stool"}),+]+++def append_prop(pid):+ """Append the prop object once; later uses become linked duplicates sharing mesh + materials."""+ src = bpy.data.objects.get(f"src_{pid}")+ if src:+ return src+ path = os.path.join(SCN, "props", f"{pid}.blend")+ with bpy.data.libraries.load(path, link=False) as (fr, to):+ to.objects = [pid]+ src = to.objects[0]+ src.name = f"src_{pid}"+ lib = bpy.data.collections.get("_prop_sources") or bpy.data.collections.new("_prop_sources")+ if lib.name not in bpy.context.scene.collection.children:+ bpy.context.scene.collection.children.link(lib)+ lib.objects.link(src)+ lib.hide_render = True+ bpy.context.view_layer.layer_collection.children[lib.name].exclude = True # keep sources out of rays + renders+ return src+++def drop(ob, start_z):+ """Rest the object on the highest support under its footprint (5 rays), ignoring itself."""+ dg = bpy.context.evaluated_depsgraph_get()+ sc = bpy.context.scene+ bb = [ob.matrix_world @ Vector(c) for c in ob.bound_box]+ cx, cy = ob.location.x, ob.location.y+ ob.location.z = -100 # out of the way of its own rays+ bpy.context.view_layer.update()+ dg = bpy.context.evaluated_depsgraph_get()+ hx = (max(p.x for p in bb) - min(p.x for p in bb)) * 0.35+ hy = (max(p.y for p in bb) - min(p.y for p in bb)) * 0.35+ best = None+ for dx, dy in ((0, 0), (hx, hy), (-hx, hy), (hx, -hy), (-hx, -hy)):+ hit, loc, *_ = sc.ray_cast(dg, Vector((cx + dx, cy + dy, start_z)), Vector((0, 0, -1)))+ if hit and (best is None or loc.z > best):+ best = loc.z+ ob.location.z = best if best is not None else 0.0+ return best+++def place(pid, x, y, yaw, kw):+ src = append_prop(pid)+ ob = src.copy()+ ob.name = kw.get("name", pid)+ coll = bpy.data.collections.get("props") or bpy.data.collections.new("props")+ if coll.name not in bpy.context.scene.collection.children:+ bpy.context.scene.collection.children.link(coll)+ coll.objects.link(ob)+ s = kw.get("scale", 1.0) * random.uniform(0.97, 1.03)+ ob.scale = (s, s, s)+ ob.rotation_mode = "XYZ" # glTF imports come in as QUATERNION, which would silently ignore rotation_euler+ ob.rotation_euler = (math.radians(kw.get("pitch", 0)), 0, math.radians(yaw + random.uniform(-3, 3)))+ ob.location = (x, y, kw.get("z", 0))+ ob["placed"] = True+ ob["prop_id"] = pid+ ob["wall"] = "z" in kw+ ob["scaled"] = "scale" in kw+ bpy.context.view_layer.update()+ # snap the back against the wall it stands by: shelf props to the bench wall, rack props to the right wall+ back = kw.get("back") or ("x0" if x < 0.4 and (kw.get("from") in (SHELF1, SHELF2) or "z" in kw) else "x1" if abs(x - RX) < 0.01 else None)+ if back:+ pts = [ob.matrix_world @ Vector(c) for c in ob.bound_box]+ if back == "x0":+ ob.location.x += 0.012 - min(p.x for p in pts)+ elif back == "x1":+ ob.location.x += (4.2 - 0.012) - max(p.x for p in pts)+ bpy.context.view_layer.update()+ if "z" not in kw:+ drop(ob, kw.get("from", 2.4)) # default start stays under the ceiling conduit (2.65) and fixtures+ return ob+++TV_ON = {"repair_crt_tv", "crt_tv_shelf2"} # only these sets are left on (blue no-signal screens)++# round 2: regenerated brand-free versions that won their pick replace the texture-painted originals (object names unchanged)+_nb_path = os.path.join(SCN, "nb_swap.json")+NB_SWAP = json.load(open(_nb_path)) if os.path.exists(_nb_path) else {}++for p, pid, x, y, yaw, kw in LAYOUT:+ if p > PASS:+ continue+ if pid in NB_SWAP and os.path.exists(os.path.join(SCN, "props", f"{NB_SWAP[pid]}.blend")):+ kw = dict(kw, name=kw.get("name", pid))+ pid = NB_SWAP[pid]+ if not os.path.exists(os.path.join(SCN, "props", f"{pid}.blend")):+ if kw.get("alt") and os.path.exists(os.path.join(SCN, "props", f"{kw['alt']}.blend")):+ pid = kw["alt"] # round-2 generated prop not available (yet): fall back to the round-1 one+ else:+ print("MISSING prop", pid)+ continue+ ob = place(pid, x, y, yaw, kw)+ ob["tv_on"] = 1.0 if ob.name in TV_ON else 0.0+ print(f"PLACED {ob.name} at {tuple(round(v, 3) for v in ob.location)}")++bpy.ops.wm.save_as_mainfile(filepath=os.path.join(SCN, "repair_dressed.blend"))+print("saved dressed pass", PASS)diff --git a/scenes/tokyo-electronics-repair/scripts/dress2.py b/scenes/tokyo-electronics-repair/scripts/dress2.pynew file mode 100644index 0000000..54e3ffa--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/dress2.py@@ -0,0 +1,1144 @@+"""Round 2 densify, coarse -> fine (the video's dressing passes), on top of dress.py's layout.++blender -b scenes/tokyo-electronics-repair/repair_dressed.blend --python scenes/tokyo-electronics-repair/scripts/dress2.py -- <A|B|C> [out.blend]+ A mid props: boxed + binned repair jobs with tags on racks/shelves/floor, parts cart, second bench station extras,+ dressed sales counter (register, display case, ticket book, lamp, generic tissue box), generic spray cans and+ cup noodle (replacing branded generated ones), per-instance variation of repeated devices, street props outside.+ B small clutter: screws, loose components, PCBs, braid, flux bottles, tweezers, screwdriver sets, cups and cans,+ ashtrays, receipts, tape rolls.+ C micro / life: cables everywhere (curves with bevel, routed and dropped onto surfaces), ribbon cables, extension+ blocks, sticky notes, flyers, extra posters, price tags, peeling tape.+Each pass includes the previous ones. Everything is direct-modelled, so it runs while fal is unavailable.+Saves scenes/tokyo-electronics-repair/repair_dressed2.blend (or out.blend).+"""+import math+import os+import random+import sys++import bpy+import bmesh+from mathutils import Vector, Matrix++sys.path.insert(0, os.path.dirname(__file__))+import lib # noqa: E402+from lib import box, cylinder, plane # noqa: E402++ARGS = sys.argv[sys.argv.index("--") + 1:]+PASS = ARGS[0]+OUT = os.path.abspath(ARGS[1]) if len(ARGS) > 1 else os.path.join(lib.ROOT, "scenes", "tokyo-electronics-repair", "repair_dressed2.blend")+LEVEL = {"A": 1, "B": 2, "C": 3}[PASS]+TEX = os.path.join(lib.ROOT, "refs", "tokyo-electronics-repair", "tex")+W, D, H = 4.2, 6.5, 2.7+BZ = 0.88 # bench top+RX0, RX1 = W - 0.46, W - 0.01 # rack x span+RACK_Z = [0.1, 0.52, 0.94, 1.36, 1.78] # rack shelf top surfaces+SHELF_Z = [1.705, 2.145] # above-bench shelf tops, x 0..0.32+sc = bpy.context.scene+rnd = random.Random(11)+++def coll(name):+ return lib.collection(name)+++C_A, C_B, C_C, C_ST = (coll(n) for n in ("dress2_A_mid", "dress2_B_clutter", "dress2_C_micro", "street"))++# ---------------------------------------------------------------- materials+M = {+ "card": lib.grimy("cardboard", (0.42, 0.3, 0.17), (0.2, 0.13, 0.07), rough=(0.75, 0.9), amount=0.35, scale=4, bump=0.25),+ "card2": lib.grimy("cardboard_dark", (0.33, 0.23, 0.13), (0.15, 0.1, 0.05), rough=(0.75, 0.9), amount=0.4, scale=4, bump=0.25),+ "bin_blue": lib.grimy("bin_blue", (0.05, 0.16, 0.38), (0.05, 0.06, 0.06), rough=(0.4, 0.7), amount=0.3),+ "bin_grey": lib.grimy("bin_grey", (0.3, 0.31, 0.32), (0.1, 0.1, 0.09), rough=(0.4, 0.7), amount=0.3),+ "bin_red": lib.grimy("bin_red", (0.4, 0.04, 0.03), (0.1, 0.05, 0.04), rough=(0.4, 0.7), amount=0.3),+ "crate": lib.principled("crate_black", (0.02, 0.02, 0.02), 0.6),+ "steel": bpy.data.materials.get("shelf_steel"),+ "chrome": lib.principled("chrome_worn", (0.7, 0.7, 0.7), 0.25, 1.0),+ "rubber": lib.principled("rubber_black", (0.015, 0.015, 0.015), 0.55),+ "cable_w": lib.principled("cable_white", (0.6, 0.6, 0.56), 0.45),+ "cable_g": lib.principled("cable_grey", (0.18, 0.18, 0.18), 0.5),+ "beige": lib.grimy("beige_plastic", (0.55, 0.5, 0.4), (0.25, 0.2, 0.12), rough=(0.4, 0.6), amount=0.3),+ "dkplastic": lib.grimy("dark_plastic", (0.05, 0.05, 0.055), (0.12, 0.11, 0.1), rough=(0.35, 0.6), amount=0.3),+ "white_pl": lib.grimy("white_plastic", (0.7, 0.7, 0.66), (0.3, 0.27, 0.2), rough=(0.3, 0.5), amount=0.3),+ "wood": bpy.data.materials.get("door_wood"),+ "glass": lib.principled("case_glass", (0.95, 0.97, 0.96), 0.04, **{"Transmission Weight": 1.0}),+ "pcb": None,+ "copper": lib.principled("copper", (0.8, 0.45, 0.25), 0.35, 1.0),+ "solder": lib.principled("solder_tin", (0.6, 0.6, 0.62), 0.3, 1.0),+ "amber": lib.principled("amber_bottle", (0.55, 0.3, 0.05), 0.15, **{"Transmission Weight": 0.8}),+ "paper": lib.grimy("paper", (0.78, 0.76, 0.7), (0.4, 0.35, 0.25), rough=(0.7, 0.85), amount=0.2, bump=0.05),+ "tape_y": lib.principled("tape_yellowed", (0.75, 0.62, 0.35), 0.45, **{"Alpha": 0.85}),+ "tape_black": lib.principled("tape_black", (0.02, 0.02, 0.02), 0.35),+ "tape_kapton": lib.principled("tape_kapton", (0.75, 0.42, 0.05), 0.2, **{"Transmission Weight": 0.4}),+ "butt": lib.principled("cig_butt", (0.75, 0.55, 0.3), 0.8),+ "ash": lib.principled("ash", (0.25, 0.24, 0.23), 0.95),+ "coffee": lib.principled("coffee_can", (0.18, 0.09, 0.04), 0.35, 0.6),+ "green_shade": lib.principled("lamp_green_glass", (0.03, 0.22, 0.08), 0.15, **{"Coat Weight": 1.0}),+ "brass": lib.principled("brass", (0.7, 0.5, 0.2), 0.3, 1.0),+}+for k in ("cable_w", "cable_g", "rubber"):+ pass+# PCB: green solder mask with copper-ish traces (voronoi edges) and silkscreen speckle+pm = bpy.data.materials.get("pcb_green") or bpy.data.materials.new("pcb_green")+if not pm.get("built"):+ nt = pm.node_tree+ b = nt.nodes["Principled BSDF"]+ tc = nt.nodes.new("ShaderNodeTexCoord")+ vo = nt.nodes.new("ShaderNodeTexVoronoi")+ vo.feature = "DISTANCE_TO_EDGE"+ vo.inputs["Scale"].default_value = 60+ nt.links.new(tc.outputs["Object"], vo.inputs["Vector"])+ tr = lib._ramp(nt, vo.outputs["Distance"], [(0.0, (0.35, 0.42, 0.12)), (0.04, (0.02, 0.16, 0.05))])+ nt.links.new(tr.outputs["Color"], b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = 0.35+ nt.links.new(lib._bump(nt, vo.outputs["Distance"], 0.15), b.inputs["Normal"])+ pm["built"] = True+M["pcb"] = pm+++def img_mat(name, path, rough=0.75, alpha=False):+ return lib.image_mat(name, os.path.join(TEX, path), rough=rough, alpha=alpha)+++M["tags"] = img_mat("repair_tags", "tags_0.png", 0.8)+M["labels"] = bpy.data.materials.get("drawer_labels")+++def tinted_paper(name, col):+ """Coloured paper whose 'ink' comes from the labels sheet (handwriting), for sticky notes / flyers."""+ m = bpy.data.materials.get(name)+ if m:+ return m+ m = bpy.data.materials.new(name)+ nt = m.node_tree+ b = nt.nodes["Principled BSDF"]+ t = nt.nodes.new("ShaderNodeTexImage")+ t.image = bpy.data.images.load(os.path.join(TEX, "labels_0.png"), check_existing=True)+ col_out = lib._mix(nt, 1.0, t.outputs["Color"], col, "MULTIPLY")+ nt.links.new(col_out, b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = 0.8+ return m+++M["sticky_y"] = tinted_paper("sticky_yellow", (1.0, 0.85, 0.25))+M["sticky_p"] = tinted_paper("sticky_pink", (1.0, 0.55, 0.65))+M["sticky_b"] = tinted_paper("sticky_blue", (0.55, 0.8, 1.0))+M["flyer_y"] = tinted_paper("flyer_yellow", (0.95, 0.9, 0.55))+M["flyer_w"] = tinted_paper("flyer_white", (0.9, 0.88, 0.82))+M["price_o"] = tinted_paper("price_orange", (1.0, 0.45, 0.05))++# ---------------------------------------------------------------- helpers+++def apply_mods(ob):+ for m in list(ob.modifiers):+ with bpy.context.temp_override(object=ob, active_object=ob):+ bpy.ops.object.modifier_apply(modifier=m.name)+++def join(objs, name, c):+ objs = [o for o in objs if o]+ for o in objs:+ apply_mods(o)+ bpy.ops.object.select_all(action="DESELECT")+ for o in objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = objs[0]+ bpy.ops.object.join()+ ob = objs[0]+ ob.name = name+ lib.link(ob, c)+ bottom_origin(ob)+ return ob+++def ray_down(x, y, start, ignore=()):+ """Highest surface under (x, y) below start, ignoring objects in `ignore` (moved out of the way)."""+ moved = []+ for o in ignore:+ moved.append((o, o.location.z))+ o.location.z -= 100+ bpy.context.view_layer.update()+ dg = bpy.context.evaluated_depsgraph_get()+ hit, loc, n, i, ob, m = sc.ray_cast(dg, Vector((x, y, start)), Vector((0, 0, -1)))+ for o, z in moved:+ o.location.z = z+ if moved:+ bpy.context.view_layer.update()+ return (loc.z, ob) if hit else (0.0, None)+++def settle(ob, z):+ """Shift ob so its lowest world-space point sits at z (works whatever the origin)."""+ bpy.context.view_layer.update()+ pts = [ob.matrix_world @ Vector(cn) for cn in ob.bound_box]+ ob.location.z += z - min(p.z for p in pts)+ bpy.context.view_layer.update()+++def put(ob, x, y, start, yaw=0.0, lift=0.0):+ """Place an object on the surface under (x, y)."""+ ob.location = (x, y, -50)+ ob.rotation_euler = (ob.rotation_euler.x, ob.rotation_euler.y, math.radians(yaw))+ z, _ = ray_down(x, y, start)+ settle(ob, z + lift)+ return ob+++def bottom_origin(ob):+ """Move a mesh's origin to its bottom centre (in place)."""+ me = ob.data+ vs = [v.co for v in me.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)))+ off = Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))+ me.transform(Matrix.Translation(-off))+ bpy.context.view_layer.update()+ ob.location = ob.matrix_world @ off+ return ob+++def local_box(name, sx, sy, sz, mat, c, bevel=0.002, z0=0.0, ox=0.0, oy=0.0):+ """Box centred at (ox, oy) in local space, sitting on z0; world placement comes later via join + put."""+ return box(name, (ox - sx / 2, oy - sy / 2, z0), (ox + sx / 2, oy + sy / 2, z0 + sz), mat, c, bevel=bevel)+++def local_cyl(name, r, h, mat, c, x=0.0, y=0.0, z0=0.0, axis="Z", verts=16):+ if axis == "Z":+ return cylinder(name, (x, y, z0 + h / 2), r, h, mat, c, verts=verts)+ return cylinder(name, (x, y, z0), r, h, mat, c, axis=axis, verts=verts)+++def tag_plane(name, centre, normal, c, w=0.06, h=0.09, rot=0.0):+ """Paper repair tag from the tags sheet (random ticket)."""+ t = plane(name, centre, w, h, normal, M["tags"], c)+ cell = rnd.randrange(8)+ u, v = cell % 4, cell // 4+ lib.set_uv_rect(t, u / 4 + 0.01, 1 - (v + 1) / 2 + 0.01, (u + 1) / 4 - 0.01, 1 - v / 2 - 0.01)+ if normal in ("-Y", "Y"):+ t.rotation_euler.y = rot+ elif normal in ("-X", "X"):+ t.rotation_euler.x = rot+ else:+ t.rotation_euler.z = rot+ return t+++def cardboard_box(name, sx, sy, sz, c, open_top=False, tag_side=None):+ parts = []+ mat = M["card"] if rnd.random() < 0.6 else M["card2"]+ if open_top:+ th = 0.004+ parts += [local_box("b", sx, sy, th, mat, c, 0),+ local_box("w1", th, sy, sz, mat, c, 0, ox=-sx / 2 + th / 2), local_box("w2", th, sy, sz, mat, c, 0, ox=sx / 2 - th / 2),+ local_box("w3", sx, th, sz, mat, c, 0, oy=-sy / 2 + th / 2), local_box("w4", sx, th, sz, mat, c, 0, oy=sy / 2 - th / 2)]+ for s in (-1, 1): # flaps folded outwards+ f = local_box("flap", sx * 0.96, th, sy * 0.45, mat, c, 0)+ f.location = (0, s * sy / 2, sz)+ f.rotation_euler.x = s * math.radians(rnd.uniform(100, 135))+ parts.append(f)+ else:+ parts.append(local_box("box", sx, sy, sz, mat, c, 0.004))+ tape = local_box("tape", sx * 1.002, 0.05, 0.001, M["tape_y"], c, 0, z0=sz)+ parts.append(tape)+ ob = join(parts, name, c)+ if tag_side:+ t = tag_plane(name + "_tag", (0, 0, sz * 0.5), tag_side, c)+ t.location = ({"-Y": (rnd.uniform(-sx / 4, sx / 4), -sy / 2 - 0.0015, sz * rnd.uniform(0.35, 0.65)),+ "X": (sx / 2 + 0.0015, rnd.uniform(-sy / 4, sy / 4), sz * rnd.uniform(0.35, 0.65)),+ "-X": (-sx / 2 - 0.0015, rnd.uniform(-sy / 4, sy / 4), sz * rnd.uniform(0.35, 0.65))}[tag_side])+ t.parent = ob+ return ob+++def plastic_bin(name, sx, sy, sz, mat, c):+ th = 0.004+ parts = [local_box("b", sx, sy, th, mat, c, 0),+ local_box("w1", th, sy, sz, mat, c, 0, ox=-sx / 2 + th / 2), local_box("w2", th, sy, sz, mat, c, 0, ox=sx / 2 - th / 2),+ local_box("w3", sx, th, sz, mat, c, 0, oy=-sy / 2 + th / 2), local_box("w4", sx, th, sz * 0.7, mat, c, 0, oy=sy / 2 - th / 2)]+ return join(parts, name, c)+++def instance(src_name, name, c, scale=1.0):+ src = bpy.data.objects.get(f"src_{src_name}") or bpy.data.objects.get(f"src_{src_name}_nb") or bpy.data.objects.get(src_name)+ if src is None:+ return None+ ob = src.copy()+ ob.animation_data_clear()+ ob.name = name+ c.objects.link(ob)+ ob.rotation_mode = "XYZ"+ ob.rotation_euler = (0, 0, 0)+ ob.scale = (scale, scale, scale)+ ob.hide_render = False+ ob.hide_viewport = False+ for k in ("placed", "prop_id", "wall"):+ if k in ob:+ del ob[k]+ ob["tv_on"] = 0.0+ return ob+++def tint(ob, kind=None):+ """Per-instance colour variation read by the grime layer through Object Info > Color."""+ k = kind or rnd.choice(["yellowed", "dark", "cool", "plain"])+ ob.color = {"yellowed": (1.0, 0.93, 0.78, 1), "dark": (0.78, 0.76, 0.74, 1), "cool": (0.9, 0.95, 1.0, 1), "plain": (1, 1, 1, 1)}[k]+++# =================================================================== PASS A: mid props+def pass_a():+ c = C_A+ # --- remove nothing; vary repeated generated devices (tint + a tag) -----------------------------------+ seen = {}+ for o in [o for o in sc.objects if o.get("placed")]:+ pid = o.get("prop_id")+ seen[pid] = seen.get(pid, 0) + 1+ if seen[pid] > 1 or pid in ("repair_crt_tv", "repair_receiver", "repair_vcr_open"):+ tint(o)+ # --- racks: boxed and binned repair jobs in the gaps ----------------------------------------------------+ rack_slots = [ # (y, shelf index) gaps measured from the pass-4 layout+ (1.32, 1), (2.42, 1), (3.62, 1), (1.95, 3), (2.55, 3), (4.05, 3), (4.62, 2), (1.35, 2), (3.4, 0), (4.4, 0),+ (2.9, 2), (3.75, 2), (2.25, 3), (4.75, 3), (3.25, 3),+ ]+ for i, (y, s) in enumerate(rack_slots):+ z_cap = (RACK_Z[s + 1] if s + 1 < len(RACK_Z) else 2.3) - RACK_Z[s] - 0.03+ if rnd.random() < 0.55:+ sx, sy, sz = rnd.uniform(0.28, 0.4), rnd.uniform(0.22, 0.34), min(z_cap, rnd.uniform(0.18, 0.34))+ ob = cardboard_box(f"rack_box_{i}", sx, sy, sz, c, open_top=rnd.random() < 0.35, tag_side="-X")+ else:+ mat = rnd.choice([M["bin_blue"], M["bin_grey"], M["bin_red"]])+ sx, sy, sz = 0.36, 0.28, min(z_cap, 0.16)+ ob = plastic_bin(f"rack_bin_{i}", sx, sy, sz, mat, c)+ t = tag_plane(f"rack_bin_{i}_tag", (0, 0, 0), "-X", c)+ t.location = (-sx / 2 - 0.002, rnd.uniform(-0.08, 0.08), sz * 0.6)+ t.parent = ob+ inner = instance(rnd.choice(["repair_vintage_radio", "repair_multimeter_red", "repair_vcr_open", "repair_receiver"]), f"rack_bin_{i}_job", c, 0.62)+ if inner:+ inner.parent = ob+ inner.location = (0, 0, 0.005)+ inner.rotation_euler.z = math.radians(rnd.uniform(-20, 20) - 90)+ tint(inner)+ ob.location = (rnd.uniform(RX0 + 0.2, RX1 - 0.22), y, 0)+ put(ob, ob.location.x, y, RACK_Z[s] + 0.2, yaw=rnd.uniform(-6, 6))+ # rack tops: stacked boxes up to near the ceiling+ for i, y in enumerate([1.35, 1.8, 2.5, 3.05, 3.7, 4.3, 4.75]):+ h = 0+ for k in range(rnd.randint(1, 3)):+ sz = rnd.uniform(0.15, 0.26)+ ob = cardboard_box(f"rack_top_{i}_{k}", rnd.uniform(0.3, 0.42), rnd.uniform(0.28, 0.38), sz, c, tag_side="-X" if k == 0 else None)+ put(ob, RX0 + 0.22 + rnd.uniform(-0.02, 0.02), y, 2.55, yaw=rnd.uniform(-8, 8))+ h += sz+ if h > 0.5:+ break+ # --- above-bench shelves --------------------------------------------------------------------------------+ for i, (y, s) in enumerate([(1.35, 1), (2.05, 1), (2.55, 1), (3.3, 1), (3.95, 1), (5.05, 0), (5.2, 1), (2.6, 0), (3.35, 0)]):+ if rnd.random() < 0.5:+ ob = cardboard_box(f"shelf_box_{i}", rnd.uniform(0.2, 0.3), rnd.uniform(0.22, 0.32), rnd.uniform(0.14, 0.24) if s == 0 else rnd.uniform(0.16, 0.3), c, tag_side="X")+ else:+ ob = plastic_bin(f"shelf_bin_{i}", 0.28, 0.24, 0.13, rnd.choice([M["bin_blue"], M["bin_grey"]]), c)+ put(ob, 0.16, y, SHELF_Z[s] + (0.4 if s == 0 else 0.5), yaw=rnd.uniform(-5, 5))+ # --- under-bench: cable crate, boxes --------------------------------------------------------------------+ for i, y in enumerate([2.05, 3.45, 4.35]):+ ob = cardboard_box(f"under_box_{i}", 0.4, 0.34, rnd.uniform(0.22, 0.32), c, open_top=True, tag_side="X")+ put(ob, 0.32, y, 0.6, yaw=rnd.uniform(-10, 10))+ crate = plastic_bin("cable_crate", 0.42, 0.32, 0.26, M["crate"], c)+ put(crate, 0.33, 5.0, 0.6, yaw=88)+ # --- floor: boxes under the windows, job bins by the racks, umbrella stand by the door ---------------------+ for i, (x, y, yaw) in enumerate([(0.35, 0.35, 5), (0.75, 0.32, -4), (3.2, 0.3, 3), (3.75, 0.95, 80), (2.1, 6.2, 2)]):+ for k in range(rnd.randint(1, 3)):+ ob = cardboard_box(f"floor_box_{i}_{k}", rnd.uniform(0.35, 0.5), rnd.uniform(0.3, 0.42), rnd.uniform(0.2, 0.32), c, tag_side=("-X" if x > 2.1 else "X") if k == 0 else None)+ put(ob, x + rnd.uniform(-0.03, 0.03), y + rnd.uniform(-0.03, 0.03), 1.5, yaw=yaw + rnd.uniform(-8, 8))+ for i, (x, y) in enumerate([(3.45, 2.6), (3.5, 4.2)]):+ ob = plastic_bin(f"floor_bin_{i}", 0.42, 0.32, 0.2, rnd.choice([M["bin_blue"], M["bin_grey"]]), c)+ put(ob, x, y, 0.5, yaw=rnd.uniform(-10, 10))+ inner = instance(rnd.choice(["repair_receiver", "repair_vcr_open"]), f"floor_bin_{i}_job", c, 0.8)+ if inner:+ inner.parent = ob+ inner.location = (0, 0, 0.005)+ inner.rotation_euler.z = math.radians(-90)+ tint(inner)+ stand = local_cyl("umb_stand", 0.12, 0.45, M["steel"], c)+ parts = [stand]+ for k, (dx, dy, col) in enumerate([(0.03, 0.02, (0.85, 0.9, 0.95)), (-0.03, 0.03, (0.85, 0.9, 0.95)), (0.0, -0.04, (0.02, 0.02, 0.02))]):+ um = lib.principled(f"umbrella_{k}", col, 0.2, **({"Transmission Weight": 0.7} if col[0] > 0.5 else {}))+ bpy.ops.mesh.primitive_cone_add(vertices=8, radius1=0.06, radius2=0.015, depth=0.72, location=(dx, dy, 0.6))+ u = bpy.context.object+ u.rotation_euler = (rnd.uniform(-0.12, 0.12), rnd.uniform(-0.12, 0.12), 0)+ u.data.materials.append(um)+ lib.link(u, c)+ h = local_cyl("umb_handle", 0.008, 0.25, M["dkplastic"], c, dx, dy, 0.96)+ parts += [u, h]+ st = join(parts, "umbrella_stand", c)+ put(st, 2.9, 0.25, 1.0)+ puddle = plane("umbrella_puddle", (2.55, 0.3, 0.0015), 0.5, 0.4, "Z", lib.principled("puddle", (0.05, 0.05, 0.05), 0.02), c)+ puddle.rotation_euler.z = 0.4+ # --- parts cart ----------------------------------------------------------------------------------------+ parts = []+ for z in (0.12, 0.45, 0.78):+ parts.append(local_box(f"cart_shelf_{z}", 0.62, 0.42, 0.02, M["steel"], c, 0.001, z0=z))+ parts.append(local_box(f"cart_lip_{z}", 0.62, 0.42, 0.035, M["steel"], c, 0.001, z0=z))+ for sx_ in (-1, 1):+ for sy_ in (-1, 1):+ parts.append(local_cyl("post", 0.012, 0.75, M["steel"], c, sx_ * 0.3, sy_ * 0.2, 0.08))+ parts.append(local_cyl("caster", 0.035, 0.03, M["rubber"], c, sx_ * 0.29, sy_ * 0.19, 0.035, axis="X"))+ # hollow out the lips: replace the 0.035 boxes by thin rims+ parts = [p for p in parts if not p.name.startswith("cart_lip")]+ cart = join(parts, "parts_cart", c)+ put(cart, 1.55, 5.55, 1.5, yaw=12)+ for k, (src, dz) in enumerate([("boombox_open", 0.8), ("repair_vcr_open", 0.47)]):+ it = instance(src, f"cart_load_{k}", c, 0.62 if src == "boombox_open" else 0.9)+ if it:+ put(it, 1.55, 5.55, cart.location.z + dz + 0.25, yaw=12 + rnd.uniform(-10, 10))+ tint(it)+ cb = cardboard_box("cart_box", 0.35, 0.3, 0.22, c, open_top=True)+ put(cb, 1.52, 5.55, cart.location.z + 0.4, yaw=8)+ # --- sales counter -------------------------------------------------------------------------------------+ CZ = 0.95+ # cash register (faces the clerk, +Y)+ parts = [local_box("reg_base", 0.36, 0.38, 0.09, M["beige"], c, 0.006),+ local_box("reg_keys", 0.3, 0.17, 0.05, M["beige"], c, 0.006, z0=0.09, oy=0.06),+ local_box("reg_disp", 0.14, 0.05, 0.06, M["dkplastic"], c, 0.004, z0=0.12, oy=-0.12),+ local_box("reg_printer", 0.1, 0.12, 0.04, M["beige"], c, 0.004, z0=0.09, ox=0.11, oy=-0.07)]+ for kx in range(6):+ for ky in range(4):+ parts.append(local_box("key", 0.034, 0.03, 0.012, M["white_pl"] if (kx + ky) % 3 else M["dkplastic"], c, 0.002,+ z0=0.14, ox=-0.11 + kx * 0.044, oy=0.0 + ky * 0.037))+ reg = join(parts, "cash_register", c)+ put(reg, 3.3, 1.82, 1.5, yaw=180 + 4)+ disp = plane("register_display", (0, 0, 0), 0.12, 0.035, "Y", lib.emissive("register_vfd", (0.2, 1.0, 0.7), 1.5), c)+ disp.parent = reg+ disp.location = (0, -0.146, 0.15) # register origin is its bottom centre (join)+ # display case at the customer end of the counter+ parts = [local_box("case_base", 0.48, 0.42, 0.06, M["wood"], c, 0.003)]+ for sx_ in (-1, 1):+ for sy_ in (-1, 1):+ parts.append(local_box("case_post", 0.02, 0.02, 0.32, M["wood"], c, 0.001, z0=0.06, ox=sx_ * 0.23, oy=sy_ * 0.2))+ parts.append(local_box("case_top_frame", 0.48, 0.42, 0.02, M["wood"], c, 0.002, z0=0.38))+ case = join(parts, "display_case", c)+ glass = [local_box("cg_f", 0.44, 0.004, 0.32, M["glass"], c, 0, z0=0.06, oy=-0.2), local_box("cg_b", 0.44, 0.004, 0.32, M["glass"], c, 0, z0=0.06, oy=0.2),+ local_box("cg_l", 0.004, 0.38, 0.32, M["glass"], c, 0, z0=0.06, ox=-0.23), local_box("cg_r", 0.004, 0.38, 0.32, M["glass"], c, 0, z0=0.06, ox=0.23),+ local_box("cg_t", 0.44, 0.38, 0.004, M["glass"], c, 0, z0=0.395), local_box("cg_shelf", 0.44, 0.38, 0.005, M["glass"], c, 0, z0=0.22)]+ cg = join(glass, "display_case_glass", c)+ cg.visible_shadow = False+ put(case, 2.17, 1.83, 1.5, yaw=-3)+ cg.location = case.location + Vector((0, 0, 0.06))+ cg.rotation_euler = case.rotation_euler.copy()+ for k, (src, sc_, lx, ly, lz) in enumerate([("repair_multimeter_yellow", 0.7, -0.12, 0.0, 0.065), ("repair_multimeter_red", 0.6, 0.1, 0.02, 0.065),+ ("repair_vintage_radio", 0.42, -0.06, 0.02, 0.227), ("repair_mug", 0.0, 0, 0, 0)]):+ if sc_ == 0:+ continue+ it = instance(src, f"case_item_{k}", c, sc_)+ if it:+ it.parent = case+ it.location = (lx, ly, lz)+ it.rotation_euler.z = math.radians(180 + rnd.uniform(-20, 20))+ pt = plane(f"case_price_{k}", (0, 0, 0), 0.03, 0.02, "Y", M["price_o"], c)+ pt.parent = case+ pt.location = (lx, ly - 0.07, lz + 0.03)+ # ticket book + pen+ tb = join([local_box("tb", 0.1, 0.17, 0.02, M["paper"], c, 0.001), local_box("tb_cover", 0.102, 0.172, 0.002, M["bin_blue"], c, 0)], "ticket_book", c)+ put(tb, 2.6, 2.04, 1.5, yaw=-8)+ top = plane("ticket_book_top", (0, 0, 0.0205), 0.095, 0.165, "Z", M["tags"], c)+ lib.set_uv_rect(top, 0.0, 0.5, 0.25, 1.0)+ top.parent = tb+ top.location = (0, 0, 0.0205)+ pen = local_cyl("pen", 0.004, 0.14, M["bin_blue"], c, axis="X")+ pen.location = (2.66, 2.05, CZ + 0.026)+ pen.rotation_euler.z = 0.5+ # counter lamp (green banker lamp) at the clerk end+ parts = [local_cyl("lamp_base", 0.075, 0.02, M["brass"], c, verts=24), local_cyl("lamp_stem", 0.008, 0.3, M["brass"], c, z0=0.02)]+ bpy.ops.mesh.primitive_cylinder_add(vertices=24, radius=0.06, depth=0.24, location=(0, 0.05, 0.33))+ sh = bpy.context.object+ sh.rotation_euler = (0, math.pi / 2, 0)+ bm = bmesh.new()+ bm.from_mesh(sh.data)+ bmesh.ops.delete(bm, geom=[v for v in bm.verts if v.co.x > 0.005 and False], context="VERTS")+ bm.to_mesh(sh.data)+ bm.free()+ sh.scale = (1, 1, 0.6)+ sh.data.materials.append(M["green_shade"])+ lib.link(sh, c)+ parts.append(sh)+ lamp = join(parts, "counter_lamp", c)+ put(lamp, 3.4, 2.07, 1.5, yaw=180)+ # generic tissue box on the counter, cup noodle + spray cans replacements on the bench / shelf+ tbx = local_box("tissue", 0.24, 0.12, 0.09, tinted_paper("tissue_print", (0.85, 0.88, 0.95)), c, 0.004)+ tis = plane("tissue_puff", (0, 0, 0.1), 0.12, 0.08, "Y", M["paper"], c)+ tis.rotation_euler.z = 0.3+ tis_ob = join([tbx, tis], "tissue_box_generic", c)+ put(tis_ob, 0.16, 5.25, 1.2, yaw=95)+ cup = cylinder("cupnoodle", (0, 0, 0.055), 0.045, 0.11, lib.principled("cup_white", (0.85, 0.83, 0.78), 0.6), c, verts=24)+ bm = bmesh.new()+ bm.from_mesh(cup.data)+ for v in bm.verts:+ if v.co.z < 0:+ v.co.x *= 0.78+ v.co.y *= 0.78+ bm.to_mesh(cup.data)+ bm.free()+ band = cylinder("cup_band", (0, 0, 0.07), 0.0445, 0.03, lib.principled("cup_band_red", (0.55, 0.04, 0.03), 0.5), c, verts=24)+ lid = plane("cup_lid", (0.015, 0.0, 0.111), 0.07, 0.07, "Z", lib.principled("lid_foil", (0.75, 0.74, 0.7), 0.35, 0.7), c)+ lid.rotation_euler = (0.0, -0.5, 0.2)+ sticks = [local_box(f"chop_{k}", 0.2, 0.006, 0.005, lib.principled("chopstick", (0.75, 0.6, 0.4), 0.7), c, 0, z0=0.112, oy=k * 0.012) for k in (0, 1)]+ cn = join([cup, band, lid] + sticks, "cup_noodle_generic", c)+ put(cn, 0.62, 5.28, 1.2, yaw=30)+ can_cols = [(0.05, 0.25, 0.08), (0.75, 0.75, 0.78), (0.08, 0.12, 0.45)]+ for g, (gx, gy, gz, gname) in enumerate([(0.15, 2.65, SHELF_Z[0] + 0.3, "shelf"), (RX0 + 0.12, 1.3, RACK_Z[3] + 0.3, "rack")]):+ cans = []+ for k, col in enumerate(can_cols):+ cm = lib.grimy(f"can_paint_{k}", col, (0.15, 0.13, 0.1), rough=(0.25, 0.5), metal=0.6, amount=0.3)+ body = cylinder(f"can_{k}", (0, k * 0.07, 0.085), 0.03, 0.17, cm, c, verts=20)+ label = cylinder(f"can_label_{k}", (0, k * 0.07, 0.08), 0.0305, 0.09, lib.principled(f"can_label_{k}", (0.85, 0.82, 0.7) if k != 1 else (0.2, 0.3, 0.6), 0.5), c, verts=20)+ cap = cylinder(f"can_cap_{k}", (0, k * 0.07, 0.185), 0.026, 0.03, lib.principled(f"can_cap_{k}", ((0.6, 0.05, 0.03), (0.9, 0.9, 0.9), (0.02, 0.02, 0.02))[k], 0.4), c, verts=16)+ cans += [body, label, cap]+ straw = local_box("straw", 0.004, 0.004, 0.16, lib.principled("straw_red", (0.7, 0.02, 0.02), 0.4), c, 0, ox=0.02, oy=0.07, z0=0.2)+ straw.rotation_euler.x = 0.9+ ob = join(cans + [straw], f"spray_cans_generic_{gname}", c)+ bottom_origin(ob)+ put(ob, gx, gy, gz, yaw=rnd.uniform(-20, 20))+ # PCB vise + ring magnifier lamp at the second station+ vise = join([local_box("vise_base", 0.14, 0.1, 0.025, M["dkplastic"], c, 0.004),+ local_cyl("vise_post_l", 0.006, 0.08, M["chrome"], c, -0.06, 0, 0.025), local_cyl("vise_post_r", 0.006, 0.08, M["chrome"], c, 0.06, 0, 0.025),+ local_box("vise_jaw_l", 0.012, 0.02, 0.03, M["dkplastic"], c, 0.002, z0=0.09, ox=-0.06), local_box("vise_jaw_r", 0.012, 0.02, 0.03, M["dkplastic"], c, 0.002, z0=0.09, ox=0.06),+ local_box("vise_pcb", 0.11, 0.075, 0.0016, M["pcb"], c, 0, z0=0.105)], "pcb_vise", c)+ vise.rotation_euler.x = 0+ put(vise, 0.55, 4.72, 1.2, yaw=95)+ for k in range(10): # components on the vise board+ cc = local_cyl(f"vise_cap_{k}", rnd.uniform(0.002, 0.004), rnd.uniform(0.004, 0.01), rnd.choice([M["bin_blue"], M["dkplastic"]]), c, verts=8)+ cc.parent = vise+ cc.location = (rnd.uniform(-0.045, 0.045), rnd.uniform(-0.03, 0.03), 0.107)+ ring = [local_box("ring_base", 0.16, 0.16, 0.025, M["white_pl"], c, 0.006), local_cyl("ring_arm1", 0.008, 0.36, M["white_pl"], c, 0, 0, 0.025)]+ bpy.ops.mesh.primitive_torus_add(major_radius=0.075, minor_radius=0.018, location=(0.18, 0, 0.42))+ tor = bpy.context.object+ tor.rotation_euler = (0, math.radians(-25), 0)+ tor.data.materials.append(M["white_pl"])+ lib.link(tor, c)+ arm2 = local_box("ring_arm2", 0.2, 0.014, 0.014, M["white_pl"], c, 0.002, z0=0.38, ox=0.09)+ ring += [tor, arm2]+ rl = join(ring, "ring_lamp", c)+ lens = cylinder("ring_lamp_lens", (0, 0, 0), 0.06, 0.006, M["glass"], c, verts=32)+ lens.parent = rl+ ox = rl.location.x # join moved the origin to the bbox centre; children are given in the design frame+ lens.location = (0.18 - ox, 0, 0.42)+ lens.rotation_euler = (0, math.radians(65), 0)+ lens.visible_shadow = False+ led = lib.emissive("ring_led", (0.85, 0.92, 1.0), 6.0)+ bpy.ops.mesh.primitive_torus_add(major_radius=0.066, minor_radius=0.004, location=(0, 0, 0))+ lr = bpy.context.object+ lr.name = "ring_lamp_led"+ lr.data.materials.append(led)+ lib.link(lr, c)+ lr.parent = rl+ lr.location = (0.18 - ox, 0, 0.405)+ lr.rotation_euler = (0, math.radians(-25), 0)+ lz, _ = ray_down(0.12, 4.42, 1.2)+ rl.location = (0.12 + ox, 4.42, lz)+ # a spare fluorescent fixture over the racks, one tube left on (lights.py adds its light)+ fx = box("fixture_racks", (3.6, 2.4, H - 0.06), (4.0, 3.7, H), bpy.data.materials.get("fixture_white"), c)+ for dx in (-0.08, 0.08):+ t = cylinder(f"tube_racks_{dx}", (3.8 + dx, 3.05, H - 0.08), 0.013, 1.2, bpy.data.materials.get("fluoro_tube_off"), c, axis="Y")+ if dx > 0:+ t.name = "tube_on"+ t.data.materials.clear()+ t.data.materials.append(lib.emissive("fluoro_on", (0.82, 0.92, 1.0), 4.0))+ # clip lamp clamped to the top of the middle rack post, shade tipped down into the aisle and the rack shelves+ cx, cy, cz = RX0 + 0.02, 3.68, 1.97+ parts = [box("clip_clamp", (cx - 0.02, cy - 0.025, cz - 0.05), (cx + 0.04, cy + 0.025, cz + 0.01), M["dkplastic"], c, bevel=0.003),+ cylinder("clip_arm", (cx - 0.06, cy, cz + 0.08), 0.006, 0.2, M["chrome"], c, verts=8)]+ parts[1].rotation_euler.y = -0.6+ bpy.ops.mesh.primitive_cone_add(vertices=24, radius1=0.075, radius2=0.025, depth=0.12, end_fill_type="NOTHING", location=(cx - 0.14, cy, cz + 0.13))+ shade = bpy.context.object+ shade.rotation_euler = (0, math.radians(-50), 0)+ shade.data.materials.append(lib.principled("clip_shade_black", (0.03, 0.03, 0.03), 0.4, 0.6))+ shade.modifiers.new("solid", "SOLIDIFY").thickness = 0.002+ lib.link(shade, c)+ parts.append(shade)+ join(parts, "rack_clip_lamp", c)+ bulb = cylinder("rack_clip_bulb", (cx - 0.165, cy, cz + 0.105), 0.022, 0.03, lib.emissive("clip_bulb", (1.0, 0.82, 0.6), 25.0), c, verts=16)+ bulb.rotation_euler = (0, math.radians(-50), 0)+ cable("clip_lamp_cord", [(cx, cy, cz - 0.04), (cx + 0.02, cy + 0.05, cz - 0.3), (cx + 0.03, cy + 0.1, 1.2), (cx + 0.05, cy + 0.15, 0.5), (RX1 - 0.02, 3.4, 0.02)], 0.0025, M["rubber"], c)+ # TVs left on for glow on the racks and the counter side+ for n in ("crt_rack", "fill_crt_2"):+ o = sc.objects.get(n)+ if o:+ o["tv_on"] = 1.0+ street_props()+++def street_props():+ """3D layer between the storefront and the backdrop so moving cameras get parallax."""+ c = C_ST+ pole = cylinder("utility_pole", (3.9, -2.6, 3.0), 0.13, 6.0, lib.grimy("pole_concrete", (0.4, 0.4, 0.38), (0.15, 0.15, 0.14), amount=0.4), c, verts=16)+ for k, z in enumerate((2.0, 2.6)):+ box(f"pole_sign_{k}", (3.76, -2.62, z), (4.04, -2.6, z + 0.35), lib.principled(f"pole_sign_{k}", ((0.85, 0.75, 0.1), (0.85, 0.85, 0.85))[k], 0.5), c, bevel=0)+ # vending machine across the street: lit front panel+ vm = box("vending_machine", (-0.6, -3.6, 0.0), (0.4, -2.9, 1.83), lib.principled("vending_body", (0.75, 0.1, 0.08), 0.3), c, bevel=0.01)+ vmp = lib.emissive("vending_panel", (0.95, 0.97, 1.0), 1.2)+ vf = plane("vending_panel", (-0.1, -2.895, 1.15), 0.84, 0.95, "Y", vmp, c)+ for r in range(3):+ for k in range(6):+ bx = box(f"vm_bottle_{r}_{k}", (-0.45 + k * 0.14, -2.9, 0.82 + r * 0.32), (-0.39 + k * 0.14, -2.88, 0.98 + r * 0.32),+ lib.principled(f"vm_bottle_{(r + k) % 4}", ((0.8, 0.2, 0.1), (0.1, 0.4, 0.8), (0.9, 0.8, 0.2), (0.2, 0.6, 0.3))[(r + k) % 4], 0.3), c, bevel=0)+ # A-frame sign with a small lamp+ sign_m = lib.grimy("chalkboard", (0.03, 0.05, 0.04), (0.3, 0.3, 0.3), amount=0.5, scale=6)+ for s in (-1, 1):+ p = box(f"aframe_{s}", (1.0, -1.25, 0.0), (1.55, -1.23, 0.85), sign_m, c, bevel=0)+ p.rotation_euler.x = s * 0.18+ box("aframe_lamp", (1.24, -1.28, 0.85), (1.31, -1.2, 0.92), lib.emissive("aframe_bulb", (1.0, 0.75, 0.4), 6), c, bevel=0)+ # bicycle: two wheels + frame tubes+ bk = []+ for k, y in enumerate((-1.95, -2.95)):+ bpy.ops.mesh.primitive_torus_add(major_radius=0.33, minor_radius=0.018, location=(2.7, y, 0.35))+ wh = bpy.context.object+ wh.name = f"bike_wheel_{k}"+ wh.rotation_euler = (0, math.pi / 2, 0)+ wh.data.materials.append(M["rubber"])+ lib.link(wh, c)+ bk.append(wh)+ for a_, b_ in [((2.7, -1.95, 0.35), (2.7, -2.45, 0.85)), ((2.7, -2.95, 0.35), (2.7, -2.45, 0.85)), ((2.7, -2.45, 0.85), (2.7, -2.05, 0.95)),+ ((2.7, -2.05, 0.95), (2.7, -1.95, 0.35)), ((2.7, -2.45, 0.85), (2.7, -2.75, 0.9))]:+ av, bv = Vector(a_), Vector(b_)+ t = cylinder("bike_tube", (av + bv) / 2, 0.014, (bv - av).length, lib.principled("bike_black", (0.02, 0.02, 0.025), 0.3, 0.5), c, verts=8)+ t.rotation_mode = "QUATERNION"+ t.rotation_quaternion = (bv - av).to_track_quat("Z", "Y")+ bk.append(t)+ # (a solid basket box read as a floating crate from the street camera; dropped)+ # overhead wires+ for k, (z0, z1) in enumerate([(5.4, 5.1), (5.6, 5.3), (5.2, 4.9)]):+ cv = bpy.data.curves.new(f"wire_{k}", "CURVE")+ cv.dimensions = "3D"+ cv.bevel_depth = 0.008+ sp = cv.splines.new("BEZIER")+ sp.bezier_points.add(2)+ for i, p in enumerate([(-3, -2.6, z0), (1.0, -2.65, z0 - 0.5), (3.9, -2.6, z1)]):+ sp.bezier_points[i].co = p+ sp.bezier_points[i].handle_left_type = sp.bezier_points[i].handle_right_type = "AUTO"+ ob = bpy.data.objects.new(f"wire_{k}", cv)+ ob.data.materials.append(M["rubber"])+ c.objects.link(ob)+ # rain: thin streak quads in slabs that fall and loop (cyclic), motion blur turns them into streaks+ rain_m = bpy.data.materials.new("rain")+ nt = rain_m.node_tree+ b = nt.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (0.8, 0.85, 0.9, 1)+ b.inputs["Emission Color"].default_value = (0.6, 0.7, 0.9, 1)+ b.inputs["Emission Strength"].default_value = 0.6+ b.inputs["Alpha"].default_value = 0.35+ me = bpy.data.meshes.new("rain")+ bm = bmesh.new()+ r2 = random.Random(5)+ for i in range(1800):+ x, y, z = r2.uniform(-1.5, 5.7), r2.uniform(-4.2, -0.35), r2.uniform(0, 4.5)+ L = r2.uniform(0.12, 0.25)+ vs = [bm.verts.new((x - 0.0008, y, z)), bm.verts.new((x + 0.0008, y, z)), bm.verts.new((x + 0.0008, y, z + L)), bm.verts.new((x - 0.0008, y, z + L))]+ bm.faces.new(vs)+ bm.to_mesh(me)+ bm.free()+ me.materials.append(rain_m)+ for k in range(2):+ ro = bpy.data.objects.new(f"rain_{k}", me)+ c.objects.link(ro)+ ro.visible_shadow = False+ ro.location = (0, 0, 4.5 * k)+ ro.keyframe_insert("location", index=2, frame=1)+ ro.location.z = 4.5 * k - 4.5+ ro.keyframe_insert("location", index=2, frame=13)+ act = ro.animation_data.action+ fcs = act.layers[0].strips[0].channelbag(act.slots[0]).fcurves+ for fc in fcs:+ for kp in fc.keyframe_points:+ kp.interpolation = "LINEAR"+ fc.modifiers.new("CYCLES")+++# =================================================================== PASS B: small clutter+def scatter(name, n, area, maker, c, start, yaw_any=True):+ """Make n small parts with maker(i) and drop each onto whatever is under a random point in area=(x0,x1,y0,y1)."""+ objs = []+ for i in range(n):+ o = maker(i)+ x, y = rnd.uniform(area[0], area[1]), rnd.uniform(area[2], area[3])+ o.location = (x, y, -50)+ bpy.context.view_layer.update()+ o.rotation_euler.z = rnd.uniform(0, 6.28) if yaw_any else o.rotation_euler.z+ z, _ = ray_down(x, y, start)+ settle(o, z)+ objs.append(o)+ return objs+++def pass_b():+ c = C_B+ S = BZ + 0.35+ mats_cap = [M["bin_blue"], M["dkplastic"], lib.principled("cap_tan", (0.55, 0.45, 0.3), 0.5)]++ def screw(i):+ o = local_cyl(f"screw_{i}", 0.0012, rnd.uniform(0.005, 0.012), M["chrome"], c, axis="X", verts=6)+ o.location.z = 0.0012+ return o++ def comp(i):+ k = rnd.random()+ if k < 0.4:+ o = local_cyl(f"cap_{i}", rnd.uniform(0.002, 0.005), rnd.uniform(0.006, 0.014), rnd.choice(mats_cap), c, verts=8)+ if rnd.random() < 0.6:+ o.rotation_euler.y = math.pi / 2+ o.location.z = 0.003+ elif k < 0.75:+ o = local_cyl(f"res_{i}", 0.0012, 0.006, mats_cap[2], c, axis="X", verts=6)+ o.location.z = 0.0012+ else:+ o = local_box(f"ic_{i}", 0.009, 0.006, 0.002, M["dkplastic"], c, 0)+ return o++ # screws + components on the bench mat, around the scope/helping hands, on the second station and on the counter+ for nm, area in [("bench_a", (0.35, 0.72, 2.05, 2.95)), ("bench_b", (0.45, 0.72, 3.9, 4.9)), ("counter", (2.4, 3.2, 1.65, 2.05))]:+ objs = scatter(nm, 40, area, screw, c, S if nm != "counter" else 1.4) + scatter(nm, 45, area, comp, c, S if nm != "counter" else 1.4)+ join(objs, f"smalls_{nm}", c)+ # loose PCBs+ for i, (x, y, z0) in enumerate([(0.58, 2.88, S), (0.5, 4.45, S), (1.55, 5.62, 1.5), (2.75, 1.98, 1.4), (0.18, 3.45, SHELF_Z[0] + 0.3)]):+ pcb = local_box(f"pcb_{i}", rnd.uniform(0.08, 0.16), rnd.uniform(0.06, 0.11), 0.0016, M["pcb"], c, 0)+ parts = [pcb]+ for k in range(rnd.randint(8, 18)):+ parts.append(local_cyl("pc", rnd.uniform(0.002, 0.005), rnd.uniform(0.004, 0.012), rnd.choice(mats_cap), c, rnd.uniform(-0.035, 0.035), rnd.uniform(-0.025, 0.025), 0.0016, verts=8))+ for k in range(rnd.randint(1, 4)):+ parts.append(local_box("pic", 0.014, 0.007, 0.003, M["dkplastic"], c, 0, z0=0.0016, ox=rnd.uniform(-0.03, 0.03), oy=rnd.uniform(-0.02, 0.02)))+ ob = join(parts, f"pcb_{i}", c)+ put(ob, x, y, z0, yaw=rnd.uniform(0, 360))+ if rnd.random() < 0.5:+ ob.rotation_euler.x = rnd.uniform(-0.05, 0.05)+ # desoldering braid, flux bottles, tweezers, screwdriver set, solder spool+ braid = join([local_cyl("braid_spool", 0.022, 0.012, lib.principled("spool_green", (0.1, 0.4, 0.15), 0.5), c, verts=20),+ local_cyl("braid_copper", 0.012, 0.0125, M["copper"], c, verts=20)], "desolder_braid", c)+ put(braid, 0.45, 2.98, S)+ for i, (x, y) in enumerate([(0.52, 3.32), (0.67, 4.32)]):+ fb = join([local_cyl("flux", 0.018, 0.07, M["amber"], c, verts=16), local_cyl("flux_cap", 0.008, 0.02, M["white_pl"], c, z0=0.07, verts=12),+ local_cyl("flux_needle", 0.0012, 0.03, M["chrome"], c, z0=0.09, verts=6)], f"flux_bottle_{i}", c)+ put(fb, x, y, S)+ for i, (x, y, yaw) in enumerate([(0.68, 2.62, 30), (0.7, 2.68, 38), (0.6, 4.6, -20)]):+ tw = join([local_box("tw_a", 0.12, 0.004, 0.0015, M["chrome"], c, 0, oy=0.002), local_box("tw_b", 0.12, 0.004, 0.0015, M["chrome"], c, 0, z0=0.0016, oy=-0.002)], f"tweezers_{i}", c)+ put(tw, x, y, S, yaw=yaw)+ sd = []+ for k in range(7):+ col = [(0.7, 0.05, 0.03), (0.05, 0.2, 0.6), (0.9, 0.7, 0.05), (0.02, 0.02, 0.02)][k % 4]+ sd.append(local_cyl(f"sd_h{k}", 0.008, 0.06, lib.principled(f"sd_handle_{k % 4}", col, 0.35), c, -0.07, k * 0.022 - 0.066, 0.008, axis="X", verts=10))+ sd.append(local_cyl(f"sd_s{k}", 0.0018, 0.07, M["chrome"], c, 0.0, k * 0.022 - 0.066, 0.008, axis="X", verts=6))+ case = local_box("sd_case", 0.2, 0.17, 0.006, M["dkplastic"], c, 0.002)+ sdo = join([case] + sd, "screwdriver_set", c)+ put(sdo, 0.6, 3.75, S, yaw=-12)+ spool = join([local_cyl("sp_a", 0.035, 0.008, M["dkplastic"], c, z0=0.0, verts=24), local_cyl("sp_wire", 0.026, 0.044, M["solder"], c, z0=0.008, verts=24),+ local_cyl("sp_b", 0.035, 0.008, M["dkplastic"], c, z0=0.052, verts=24)], "solder_spool", c)+ put(spool, 0.2, 3.38, S)+ # cups, canned coffee, ashtrays, tape rolls+ for i, (x, y, z0) in enumerate([(0.68, 3.55, S), (2.8, 2.07, 1.4), (1.7, 5.45, 1.5), (0.2, 1.95, SHELF_Z[0] + 0.3)]):+ m = instance("repair_mug", f"mug_extra_{i}", c)+ if m:+ put(m, x, y, z0, yaw=rnd.uniform(0, 360))+ for i, (x, y, z0) in enumerate([(0.7, 2.0, S), (0.66, 4.98, S), (3.35, 2.08, 1.4), (1.3, 5.5, 0.6)]):+ cn = local_cyl(f"canned_coffee_{i}", 0.026, 0.11, M["coffee"], c, verts=16)+ put(cn, x, y, z0)+ if i == 3:+ cn.rotation_euler = (math.pi / 2, 0, rnd.uniform(0, 6))+ cn.location.z += 0.026+ for i, (x, y, z0) in enumerate([(0.68, 5.35, S), (3.05, 2.06, 1.4)]):+ tray = local_cyl("ashtray", 0.06, 0.025, lib.principled("ashtray_glass", (0.6, 0.65, 0.6), 0.05, **{"Transmission Weight": 0.9}), c, verts=24)+ parts = [tray, local_cyl("ash", 0.05, 0.004, M["ash"], c, z0=0.008, verts=16)]+ for k in range(rnd.randint(4, 8)):+ b = local_cyl("butt", 0.0038, rnd.uniform(0.018, 0.03), M["butt"], c, rnd.uniform(-0.03, 0.03), rnd.uniform(-0.03, 0.03), 0.014, axis="X", verts=6)+ b.rotation_euler.z = rnd.uniform(0, 6)+ parts.append(b)+ a = join(parts, f"ashtray_{i}", c)+ put(a, x, y, z0)+ for i, (x, y, z0, m) in enumerate([(0.12, 2.95, S, M["tape_black"]), (0.6, 3.15, S, M["tape_kapton"]), (2.48, 2.08, 1.4, M["tape_y"]), (0.18, 4.6, SHELF_Z[0] + 0.3, M["tape_black"])]):+ bpy.ops.mesh.primitive_torus_add(major_radius=0.026, minor_radius=0.009, location=(0, 0, 0.009))+ t = bpy.context.object+ t.name = f"tape_roll_{i}"+ t.data.materials.append(m)+ lib.link(t, c)+ put(t, x, y, z0)+ # receipts / repair slips: slightly curled paper planes in piles+ for i, (x, y, z0, n) in enumerate([(2.85, 1.72, 1.4, 6), (0.62, 1.42, S, 4), (0.55, 5.25, S, 3), (0.16, 2.3, SHELF_Z[0] + 0.3, 3)]):+ for k in range(n):+ p = plane(f"receipt_{i}_{k}", (0, 0, 0), rnd.uniform(0.07, 0.1), rnd.uniform(0.12, 0.2), "Z", M["tags"], c)+ cell = rnd.randrange(8)+ lib.set_uv_rect(p, (cell % 4) / 4, 0.5 * (1 - cell // 4), (cell % 4 + 1) / 4, 0.5 * (2 - cell // 4))+ put(p, x + rnd.uniform(-0.03, 0.03), y + rnd.uniform(-0.03, 0.03), z0, yaw=rnd.uniform(-40, 40), lift=0.0008 * (k + 1))+ p.rotation_euler.x = rnd.uniform(-0.04, 0.04)+++# =================================================================== PASS C: cables, paper, life+def cable(name, pts, r, mat, c, drop_ids=(), sag=()):+ """Bezier cable through pts. Indices in drop_ids are dropped onto the surface below (+r); indices in sag are lowered+ by the given amount to hang between neighbours."""+ pts = [Vector(p) for p in pts]+ for i in drop_ids:+ z, _ = ray_down(pts[i].x, pts[i].y, pts[i].z + 0.05)+ pts[i].z = z + r+ for i, s in sag:+ pts[i].z -= s+ cv = bpy.data.curves.new(name, "CURVE")+ cv.dimensions = "3D"+ cv.bevel_depth = r+ cv.bevel_resolution = 2+ cv.resolution_u = 10+ sp = cv.splines.new("BEZIER")+ sp.bezier_points.add(len(pts) - 1)+ for i, p in enumerate(pts):+ bp = sp.bezier_points[i]+ bp.co = p+ bp.handle_left_type = bp.handle_right_type = "AUTO"+ ob = bpy.data.objects.new(name, cv)+ cv.materials.append(mat)+ c.objects.link(ob)+ return ob+++def ribbon(name, pts, width, c):+ ob = cable(name, pts, 0.0004, lib.grimy("ribbon_grey", (0.55, 0.56, 0.58), (0.2, 0.2, 0.2), amount=0.2), c)+ ob.data.bevel_depth = 0.0+ ob.data.extrude = width / 2+ for bp in ob.data.splines[0].bezier_points:+ bp.tilt = math.pi / 2+ return ob+++def ext_block(name, x, y, z0, yaw, c, n=6):+ parts = [local_box("eb", 0.05, 0.06 * n / 2 + 0.06, 0.035, M["white_pl"], c, 0.006)]+ for k in range(n):+ parts.append(local_box("sock", 0.022, 0.026, 0.002, M["dkplastic"], c, 0, z0=0.035, oy=-0.06 * n / 4 + k * 0.03 + 0.015))+ if rnd.random() < 0.65:+ parts.append(local_box("plug", 0.03, 0.022, 0.03, rnd.choice([M["dkplastic"], M["white_pl"]]), c, 0.004, z0=0.035, oy=-0.06 * n / 4 + k * 0.03 + 0.015))+ ob = join(parts, name, c)+ put(ob, x, y, z0, yaw=yaw)+ return ob+++def bounds(name):+ o = sc.objects.get(name)+ if not o:+ return None+ pts = [o.matrix_world @ Vector(cn) for cn 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, (lo + hi) / 2+++def pass_c():+ c = C_C+ blk, wht, gry = M["rubber"], M["cable_w"], M["cable_g"]+ # extension blocks: on the bench back edge, under the bench, on the floor by the racks and the counter+ ext_block("ext_bench", 0.05, 3.85, BZ + 0.3, 0, c)+ ext_block("ext_under", 0.15, 2.6, 0.6, 5, c)+ ext_block("ext_floor_rack", 3.6, 3.0, 0.4, 85, c, 4)+ ext_block("ext_counter", 3.0, 2.3, 0.4, 20, c, 4)+ # power leads: every bench device -> back edge -> down the wall gap -> under-bench extension block+ devices = ["oscilloscope", "repair_bench_psu", "solder_station", "boombox_open", "repair_vcr_open", "solder_station_2", "repair_work_lamp", "ring_lamp", "dmm_station2"]+ for i, n in enumerate(devices):+ b = bounds(n)+ if not b:+ continue+ lo, hi, ce = b+ start = Vector((lo.x + 0.02, ce.y + rnd.uniform(-0.05, 0.05), lo.z + 0.03))+ mid_y = ce.y + rnd.uniform(-0.15, 0.15)+ pts = [start, (0.03, mid_y, BZ + 0.012), (0.012, mid_y + 0.05, BZ - 0.1), (0.015, 2.6 + rnd.uniform(-0.6, 0.6), 0.55), (0.12, 2.6 + (i - 4) * 0.03, 0.2)]+ cable(f"lead_{n}", pts, 0.0035, blk if i % 3 else gry, c, drop_ids=(1,), sag=((3, 0.0),))+ # soldering-iron cables across the mat (from the second station to a loose iron lying on the mat)+ iron = join([local_cyl("iron_grip", 0.01, 0.1, M["dkplastic"], c, axis="X"), local_cyl("iron_tip", 0.003, 0.06, M["chrome"], c, 0.08, 0, 0, axis="X")], "loose_iron", c)+ put(iron, 0.55, 4.55, BZ + 0.3, yaw=200, lift=0.01)+ s2 = bounds("solder_station_2")+ if s2:+ cable("iron_cable_2", [(s2[1].x - 0.02, s2[2].y - 0.06, s2[0].z + 0.04), (0.55, 4.85, BZ + 0.05), (0.7, 4.7, BZ + 0.05), (0.6, 4.6, BZ + 0.02)], 0.0028, M["rubber"], c, drop_ids=(1, 2))+ # test leads from the PSU and multimeters snaking across the bench+ for k, (pts, col) in enumerate([([(0.3, 1.55, 0.95), (0.5, 1.7, BZ), (0.62, 1.9, BZ), (0.55, 2.05, BZ)], (0.6, 0.03, 0.02)),+ ([(0.3, 1.62, 0.95), (0.48, 1.8, BZ), (0.66, 1.98, BZ), (0.68, 2.15, BZ)], (0.02, 0.02, 0.02)),+ ([(0.58, 5.0, BZ + 0.02), (0.7, 4.85, BZ), (0.66, 4.65, BZ)], (0.6, 0.03, 0.02))]):+ cable(f"test_lead_{k}", pts, 0.002, lib.principled(f"lead_col_{k % 2}", col, 0.4), c, drop_ids=tuple(range(1, len(pts))))+ # ribbon cables by the counter laptop and the PC side of the racks+ ribbon("ribbon_counter", [(2.5, 1.95, 1.0), (2.45, 2.02, 0.955), (2.38, 2.05, 0.955)], 0.03, c)+ ribbon("ribbon_bench", [(0.5, 4.4, BZ + 0.05), (0.62, 4.5, BZ + 0.004), (0.7, 4.42, BZ + 0.004)], 0.025, c)+ # rack devices: leads hanging off the shelf fronts+ for i, y in enumerate([1.6, 2.3, 3.1, 3.9, 4.5]):+ z = RACK_Z[i % 4] + 0.05+ cable(f"rack_hang_{i}", [(RX0 + 0.1, y, z), (RX0 - 0.01, y + 0.03, z + 0.01), (RX0 - 0.02, y + 0.06, z - 0.25 - i * 0.03), (RX0 + 0.02, y + 0.1, z + 0.01)],+ 0.003, blk if i % 2 else wht, c)+ # floor runs: rack extension block -> wall outlet; counter block -> along the floor to the bench wall+ cable("floor_run_rack", [(3.6, 3.0, 0.05), (3.4, 2.6, 0.0), (3.6, 1.8, 0.0), (4.15, 1.2, 0.0), (4.18, 1.15, 0.35)], 0.004, gry, c, drop_ids=(1, 2, 3))+ cable("floor_run_counter", [(3.0, 2.3, 0.05), (2.4, 2.6, 0.0), (1.6, 2.8, 0.0), (0.9, 2.65, 0.0), (0.15, 2.6, 0.05)], 0.004, blk, c, drop_ids=(1, 2, 3))+ cable("lamp_cord_counter", [(3.4, 2.07, 0.97), (3.48, 2.12, 0.955), (3.52, 2.15, 0.7), (3.3, 2.25, 0.0), (3.0, 2.3, 0.04)], 0.0025, blk, c, drop_ids=(1, 3))+ # cable coil drooping from the pegboard + a hanging bundle on the back wall+ for i, y in enumerate([3.6, 4.2, 4.8]):+ cable(f"peg_loop_{i}", [(0.02, y, 1.45), (0.06, y + 0.05, 1.25 - i * 0.04), (0.04, y + 0.12, 1.15), (0.02, y + 0.16, 1.45)], 0.003, [blk, wht, gry][i], c)+ # paper life: sticky notes on drawer cabinets, shelf edges, monitors; flyers on the glass; extra posters; peeling tape+ notes = [((0.177, 1.5, 1.3), "X"), ((0.177, 2.1, 1.55), "X"), ((0.177, 2.75, 1.25), "X"), ((0.325, 3.4, 1.66), "X"), ((0.325, 4.4, 2.1), "X"),+ ((0.013, 3.4, 1.4), "X"), ((0.013, 4.9, 1.3), "X"), ((W - 0.013, 5.3, 1.35), "-X")]+ for i, (p, n) in enumerate(notes):+ s = plane(f"sticky_{i}", p, 0.065, 0.065, n, rnd.choice([M["sticky_y"], M["sticky_p"], M["sticky_b"]]), c)+ cell = rnd.randrange(36)+ lib.set_uv_rect(s, (cell % 6) / 6, 1 - (cell // 6 + 1) / 6, (cell % 6 + 1) / 6, 1 - (cell // 6) / 6)+ s.rotation_euler.x += rnd.uniform(-0.15, 0.15)+ for i, (x, z, m) in enumerate([(0.35, 1.55, M["flyer_w"]), (0.9, 1.2, M["flyer_y"]), (3.0, 1.9, M["flyer_w"]), (3.7, 1.05, M["flyer_y"])]):+ f = plane(f"flyer_glass_{i}", (x, 0.004 - 0.04 + 0.009, z), 0.21, 0.3, "Y", m, c) # stuck on the inside of the glass+ cell = rnd.randrange(36)+ lib.set_uv_rect(f, (cell % 6) / 6, 1 - (cell // 6 + 1) / 6, (cell % 6 + 1) / 6, 1 - (cell // 6) / 6)+ f.rotation_euler.y = rnd.uniform(-0.06, 0.06)+ for k, (dx, dz) in enumerate([(-0.1, 0.14), (0.1, 0.14)]):+ t = plane(f"flyer_tape_{i}_{k}", (x + dx, f.location.y + 0.0006, z + dz), 0.05, 0.02, "Y", M["tape_y"], c)+ t.rotation_euler.y = rnd.uniform(-0.6, 0.6)+ pm = bpy.data.materials.get("poster_parts")+ for i, (p, n, w_, h_) in enumerate([((0.002, 6.05, 1.7), "X", 0.45, 0.6), ((0.5, D - 0.002, 1.6), "-Y", 0.42, 0.56)]):+ pp = plane(f"poster_extra_{i}", p, w_, h_, n, pm if i == 0 else M["flyer_y"], c)+ pp.rotation_euler[1 if n in ("-Y", "Y") else 0] += rnd.uniform(-0.03, 0.03)+ for k, (du, dv) in enumerate([(-1, 1), (1, 1), (1, -1)]):+ off = Vector((du * w_ / 2, 0, dv * h_ / 2)) if n in ("-Y", "Y") else Vector((0, du * w_ / 2, dv * h_ / 2))+ t = plane(f"poster_tape_{i}_{k}", Vector(p) + off + (Vector((0, -0.0008, 0)) if n == "-Y" else Vector((0.0008, 0, 0))), 0.06, 0.022, n, M["tape_y"], c)+ t.rotation_euler[1 if n in ("-Y", "Y") else 0] += du * dv * 0.7+ if k == 2: # one corner peeling away from the wall+ t.rotation_euler[2] += 0.5+ # price tags hanging off rack devices+ for i, o in enumerate([o for o in sc.objects if o.get("placed") and o.location.x > 3.5][:10]):+ lo, hi, ce = bounds(o.name)+ t = tag_plane(f"price_tag_{i}", (lo.x - 0.002, ce.y + rnd.uniform(-0.05, 0.05), lo.z + (hi.z - lo.z) * 0.6), "-X", c, 0.045, 0.07, rnd.uniform(-0.3, 0.3))+++# =================================================================== generated swaps (round-2 picks)+PROPS_DIR = os.path.join(lib.ROOT, "scenes", "tokyo-electronics-repair", "props")+++def gen_instance(pid, name, c):+ """Instance of a prepped generated prop (appended once into _prop_sources), or None if it isn't prepped."""+ src = bpy.data.objects.get(f"src_{pid}")+ if src is None:+ path = os.path.join(PROPS_DIR, f"{pid}.blend")+ if not os.path.exists(path):+ return None+ with bpy.data.libraries.load(path, link=False) as (fr, to):+ to.objects = [pid]+ src = to.objects[0]+ src.name = f"src_{pid}"+ lc = bpy.data.collections.get("_prop_sources")+ lc.objects.link(src)+ ob = src.copy()+ ob.name = name+ c.objects.link(ob)+ ob.rotation_mode = "XYZ"+ ob.rotation_euler = (0, 0, 0)+ ob.scale = (1, 1, 1)+ ob["placed"] = True+ ob["prop_id"] = pid+ ob["wall"] = False+ ob["tv_on"] = 0.0+ return ob+++def remove_tree(o):+ for ch in list(o.children):+ remove_tree(ch)+ bpy.data.objects.remove(o)+++# direct object (by name) -> generated prop; extra = other direct objects that go with it (exact names or "prefix*")+SWAPS = {+ "A": [+ ("cash_register", "repair_cash_register", 180, ()),+ ("counter_lamp", "repair_counter_lamp", 180, ()),+ ("display_case", "repair_display_case", 0, ("display_case_glass",)),+ ("parts_cart", "repair_parts_cart", 12, ("cart_load_0", "cart_load_1", "cart_box")),+ ("pcb_vise", "repair_pcb_vise", 95, ()),+ ("cable_crate", "repair_cable_crate", 90, ()),+ ("floor_bin_0", "repair_job_bin", -90, ()),+ ("floor_bin_1", "repair_job_bin", -95, ()),+ ("umbrella_stand", "repair_umbrella_stand", 0, ()), # stand moved with SWAP_POS+ ("spray_cans_generic_shelf", "repair_spray_cans_nb", 90, ()),+ ("spray_cans_generic_rack", "repair_spray_cans_nb", -90, ()),+ ("cup_noodle_generic", "repair_cup_noodle_nb", 30, ()),+ ("tissue_box_generic", "repair_tissue_box_nb", 95, ()),+ ("floor_box_2_0", "repair_storage_boxes_flat", 0, ("floor_box_2_*", "floor_box_3_*", "floor_box_4_*")),+ ("vending_machine", "repair_vending_machine", 180, ("vending_panel", "vm_bottle_*")),+ ("bike_wheel_0", "repair_bicycle", 0, ("bike_*",)), # moved: parked along the facade, clear of the street camera+ ("aframe_1", "repair_aframe_sign", 0, ("aframe_*",)),+ ],+ "B": [+ ("screwdriver_set", "repair_screwdriver_case", -12, ()),+ ("ashtray_1", "repair_ashtray", 0, ()),+ ("canned_coffee_2", "repair_canned_coffee", 20, ()),+ ("canned_coffee_3", "repair_canned_coffee", 70, ()),+ ("tape_roll_2", "repair_tape_rolls", 0, ()),+ ("flux_bottle_1", "repair_flux_bottles", 0, ()),+ ("pcb_2", "repair_pcbs_loose", 15, ()),+ ("pcb_3", "repair_pcbs_loose", -30, ()),+ ],+}+# new generated props with no direct counterpart: (pass, id, name, x, y, ray start, yaw)+ADDS = [+ ("A", "repair_desk_phone", "tool_chest_phone", 0.92, 6.2, 1.6, 10),+ ("A", "repair_hot_air_station", "hot_air_station", 1.25, 6.15, 1.6, -15),+ ("A", "repair_shop_vac", "shop_vac", 3.48, 5.22, 1.2, -30),+ ("A", "repair_step_stool", "step_stool", 2.3, 5.62, 1.2, 25),+ ("A", "repair_fume_extractor", "fume_extractor", 0.42, 5.2, BZ + 0.4, 100),+ ("B", "repair_screw_jar", "screw_jar", 0.7, 3.98, BZ + 0.35, 0),+ ("B", "repair_component_bag", "component_bag", 0.66, 4.12, BZ + 0.35, 40),+ ("B", "repair_desolder_pump", "desolder_pump", 0.7, 4.52, BZ + 0.35, 70),+ ("B", "repair_remote_controls", "remote_controls", 2.55, 1.66, 1.4, 160),+ ("B", "repair_cable_bundle", "cable_bundle", 0.4, 1.55, 0.6, 30),+ ("B", "repair_receipts", "receipts_gen", 2.86, 1.72, 1.4, 10),+ ("B", "repair_sticky_notes", "sticky_pad", 0.6, 5.42, BZ + 0.35, -20),+]+++SWAP_SCALE = {"display_case": 0.8, "floor_box_2_0": 0.75}+SWAP_POS = {"umbrella_stand": (2.55, 0.3), "floor_box_2_0": (3.05, 0.45), "bike_wheel_0": (3.15, -1.65)}+++def match(name, pats):+ return any(name == p or (p.endswith("*") and name.startswith(p[:-1])) for p in pats)+++def swap_pass(p):+ c = {"A": C_A, "B": C_B}[p]+ for direct, pid, yaw_off, extra in SWAPS[p]:+ o = sc.objects.get(direct)+ if o is None or not os.path.exists(os.path.join(PROPS_DIR, f"{pid}.blend")):+ continue+ x, y, yaw = o.location.x, o.location.y, math.degrees(o.rotation_euler.z)+ pts = [o.matrix_world @ Vector(cn) for cn in o.bound_box]+ top = max(pt.z for pt in pts)+ cx, cy = sum(pt.x for pt in pts) / 8, sum(pt.y for pt in pts) / 8+ cx, cy = SWAP_POS.get(direct, (cx, cy))+ name = o.name+ for nm in [e.name for e in sc.objects if e is not o and match(e.name, extra)]:+ e = sc.objects.get(nm) # may already be gone with a removed parent+ if e:+ remove_tree(e)+ remove_tree(o)+ g = gen_instance(pid, name, c)+ g.scale = (SWAP_SCALE.get(direct, 1.0),) * 3+ if direct in ("vending_machine", "bike_wheel_0", "aframe_1"):+ del g["placed"] # outside the room: not part of the interior validator checks+ put(g, cx, cy, top + 0.3, yaw=(yaw if direct not in ("bike_wheel_0", "aframe_1", "vending_machine") else 0) + yaw_off)+ print("SWAP", name, "->", pid)+ for q, pid, name, x, y, start, yaw in ADDS:+ if q != p:+ continue+ g = gen_instance(pid, name, c)+ if g:+ put(g, x, y, start, yaw=yaw)+ print("ADD", name, pid)+++# =================================================================== clash resolver (after swaps)+from mathutils.bvhtree import BVHTree # noqa: E402++FURN = ("shell", "bench", "drawers", "shelving", "storefront", "counter", "ceiling")+++def world_tree(o):+ dg = bpy.context.evaluated_depsgraph_get()+ eo = o.evaluated_get(dg)+ me = eo.to_mesh()+ me.transform(o.matrix_world)+ t = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])+ eo.to_mesh_clear()+ return t+++def wbb(o):+ pts = [o.matrix_world @ Vector(cn) for cn in o.bound_box]+ return (Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))),+ Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts))))+++def bb_hit(a, b):+ return not any(a[1][k] < b[0][k] or b[1][k] < a[0][k] for k in range(3))+++def resolve_clashes():+ """Move the smaller prop of every interpenetrating pair (spiral search, re-dropped) until it is clear; drop it if nothing fits."""+ props = [o for o in sc.objects if o.get("placed") and o.type == "MESH" and o.visible_get()]+ furn = [o for o in sc.objects if o.type == "MESH" and o.visible_get() and any(c.name in FURN for c in o.users_collection)+ and not o.name.startswith(("floor", "backroom", "pavement", "street", "glass", "door_leaf", "decal"))]+ trees = {o.name: (world_tree(o), wbb(o)) for o in props + furn}+ vol = lambda o: (lambda b: (b[1] - b[0]).x * (b[1] - b[0]).y * (b[1] - b[0]).z)(trees[o.name][1])+ lift = Matrix.Translation((0, 0, 0.003))++ furn_names = {f.name for f in furn}++ def clashes(o):+ """Same rules as validate.py: props vs props unlifted (> 40 pairs), props vs furniture lifted 3 mm (> 20),+ plus the float rule (support under the centre within 1 cm)."""+ t0, b0 = trees[o.name]+ dg = bpy.context.evaluated_depsgraph_get()+ eo = o.evaluated_get(dg)+ me = eo.to_mesh()+ me.transform(lift @ o.matrix_world)+ tl = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])+ eo.to_mesh_clear()+ out = []+ for n, (ot, ob) in trees.items():+ if n == o.name or not bb_hit(b0, ob):+ continue+ if n in furn_names:+ if len(tl.overlap(ot)) > 20:+ out.append(n)+ elif len(t0.overlap(ot)) > 40:+ out.append(n)+ z, sup = ray_down(o.location.x, o.location.y, b0[0].z + 0.02, ignore=(o,))+ if b0[0].z - z > 0.01:+ out.append("FLOAT")+ return out++ moved = removed = 0+ for _ in range(3):+ changed = False+ for o in sorted(props, key=vol):+ if o.name not in trees:+ continue+ hit = [n for n in clashes(o) if n == "FLOAT" or n not in [p.name for p in props] or vol(sc.objects[n]) >= vol(o)]+ if not hit:+ continue+ x0, y0 = o.location.x, o.location.y+ top = trees[o.name][1][1].z + 0.25+ ok = False+ for r in (0.04, 0.08, 0.12, 0.18, 0.25, 0.33, 0.42):+ for k in range(12):+ a = k / 12 * 6.283 + r * 7+ x, y = x0 + r * math.cos(a), y0 + r * math.sin(a)+ if not (0.02 < x < W - 0.02 and 0.05 < y < D - 0.02):+ continue+ put(o, x, y, top, yaw=math.degrees(o.rotation_euler.z))+ trees[o.name] = (world_tree(o), wbb(o))+ lo, hi = trees[o.name][1]+ if lo.x < 0 or hi.x > W or lo.y < 0 or hi.y > D or lo.z < -0.01:+ continue+ if not clashes(o):+ ok = True+ break+ if ok:+ break+ if ok:+ moved += 1+ print("RESOLVE moved", o.name, f"{math.hypot(o.location.x - x0, o.location.y - y0):.2f} m")+ else:+ print("RESOLVE removed", o.name, "clashing with", hit)+ del trees[o.name]+ remove_tree(o)+ removed += 1+ changed = True+ props = [p for p in sc.objects if p.get("placed") and p.type == "MESH" and p.visible_get()]+ if not changed:+ break+ print(f"RESOLVE {moved} moved, {removed} removed")+++# ------------------------------------------------------------------- run+pass_a()+swap_pass("A")+if LEVEL >= 2:+ pass_b()+ swap_pass("B")+if LEVEL >= 3:+ pass_c()+resolve_clashes()+n_obj = sum(1 for o in sc.objects if o.type in ("MESH", "CURVE") and not o.hide_render)+print(f"dress2 pass {PASS}: {n_obj} renderable objects")+bpy.ops.wm.save_as_mainfile(filepath=OUT)+print("saved", OUT)diff --git a/scenes/tokyo-electronics-repair/scripts/fixes.py b/scenes/tokyo-electronics-repair/scripts/fixes.pynew file mode 100644index 0000000..d07b010--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/fixes.py@@ -0,0 +1,227 @@+"""Script repairs on prepped props (the video's "AI-assisted model repair" + "PBR refinement").++blender -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/fixes.py -- [id ...]+Edits scenes/tokyo-electronics-repair/props/<id>.blend in place; run after prep.py. Fixes are keyed by prop id.+"""+import math+import os+import sys++import bpy+import numpy as np+from mathutils import Vector+from mathutils.bvhtree import BVHTree++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+PROPS = os.path.join(ROOT, "scenes", "tokyo-electronics-repair", "props")+only = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def albedo_image(ob):+ for slot in ob.material_slots:+ for n in slot.material.node_tree.nodes:+ if n.type == "TEX_IMAGE" and any(l.to_socket.name == "Base Color" for l in n.outputs["Color"].links):+ return n.image+ return None+++def front_colour_grid(ob, step=0.004):+ """Ray-cast a grid at the prop from -Y; return (x, z, hit_y, rgb) for every hit, colour read from the albedo map."""+ me = ob.data+ me.calc_loop_triangles()+ verts = [v.co.copy() for v in me.vertices]+ tris = [tuple(t.vertices) for t in me.loop_triangles]+ bvh = BVHTree.FromPolygons(verts, tris)+ uvl = me.uv_layers.active.data+ tri_uv = [[uvl[l].uv.copy() for l in t.loops] for t in me.loop_triangles]+ img = albedo_image(ob)+ w, h = img.size+ px = np.empty(w * h * 4, dtype=np.float32)+ img.pixels.foreach_get(px)+ px = px.reshape(h, w, 4)+ d = ob.dimensions+ out = []+ for x in np.arange(-d.x / 2, d.x / 2, step):+ for z in np.arange(0.002, d.z, step):+ loc, nrm, idx, dist = bvh.ray_cast(Vector((x, -1.0, z)), Vector((0, 1, 0)))+ if loc is None:+ continue+ t = me.loop_triangles[idx]+ a, b, c = (verts[i] for i in t.vertices)+ # barycentric weights for UV interpolation+ v0, v1, v2 = b - a, c - a, loc - a+ d00, d01, d11, d20, d21 = v0.dot(v0), v0.dot(v1), v1.dot(v1), v2.dot(v0), v2.dot(v1)+ den = d00 * d11 - d01 * d01 or 1e-12+ bv = (d11 * d20 - d01 * d21) / den+ bw = (d00 * d21 - d01 * d20) / den+ bu = 1 - bv - bw+ uv = tri_uv[idx][0] * bu + tri_uv[idx][1] * bv + tri_uv[idx][2] * bw+ col = px[int((uv.y % 1) * (h - 1)), int((uv.x % 1) * (w - 1)), :3]+ out.append((x, z, loc.y, col))+ return out+++def crt_material(name, tint, trace=True, strength=6.0):+ """CRT face: dark tinted glass with a phosphor graticule and a sine trace (oscilloscope), or a flat glow (TV)."""+ m = bpy.data.materials.new(name)+ nt = m.node_tree+ b = nt.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (0.01, 0.015, 0.012, 1)+ b.inputs["Roughness"].default_value = 0.08+ b.inputs["Coat Weight"].default_value = 1.0+ b.inputs["Coat Roughness"].default_value = 0.03+ tc = nt.nodes.new("ShaderNodeTexCoord")+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ nt.links.new(tc.outputs["UV"], sep.inputs["Vector"])+ glow = nt.nodes.new("ShaderNodeMath")+ if trace:+ # graticule: thin lines every 1/10 in x and 1/8 in y+ def lines(axis, n):+ mul = nt.nodes.new("ShaderNodeMath"); mul.operation = "MULTIPLY"; mul.inputs[1].default_value = n+ nt.links.new(sep.outputs[axis], mul.inputs[0])+ fr = nt.nodes.new("ShaderNodeMath"); fr.operation = "PINGPONG"; fr.inputs[1].default_value = 0.5+ nt.links.new(mul.outputs[0], fr.inputs[0])+ lt = nt.nodes.new("ShaderNodeMath"); lt.operation = "LESS_THAN"; lt.inputs[1].default_value = 0.03+ nt.links.new(fr.outputs[0], lt.inputs[0])+ return lt.outputs[0]+ grid = nt.nodes.new("ShaderNodeMath"); grid.operation = "MAXIMUM"+ nt.links.new(lines("X", 10), grid.inputs[0]); nt.links.new(lines("Y", 8), grid.inputs[1])+ # trace: |y - (0.5 + 0.28 sin(2pi*2.5x))| < 0.012+ sx = nt.nodes.new("ShaderNodeMath"); sx.operation = "MULTIPLY"; sx.inputs[1].default_value = 2 * math.pi * 2.5+ nt.links.new(sep.outputs["X"], sx.inputs[0])+ sn = nt.nodes.new("ShaderNodeMath"); sn.operation = "SINE"; nt.links.new(sx.outputs[0], sn.inputs[0])+ sa = nt.nodes.new("ShaderNodeMath"); sa.operation = "MULTIPLY_ADD"; sa.inputs[1].default_value = 0.28; sa.inputs[2].default_value = 0.5+ nt.links.new(sn.outputs[0], sa.inputs[0])+ df = nt.nodes.new("ShaderNodeMath"); df.operation = "SUBTRACT"; nt.links.new(sep.outputs["Y"], df.inputs[0]); nt.links.new(sa.outputs[0], df.inputs[1])+ ab = nt.nodes.new("ShaderNodeMath"); ab.operation = "ABSOLUTE"; nt.links.new(df.outputs[0], ab.inputs[0])+ tr = nt.nodes.new("ShaderNodeMath"); tr.operation = "SMOOTH_MIN" # soft falloff for phosphor bloom+ tr2 = nt.nodes.new("ShaderNodeMapRange"); tr2.inputs["From Min"].default_value = 0.02; tr2.inputs["From Max"].default_value = 0.0+ nt.links.new(ab.outputs[0], tr2.inputs["Value"])+ glow.operation = "MULTIPLY_ADD"+ nt.links.new(grid.outputs[0], glow.inputs[0]); glow.inputs[1].default_value = 0.12+ nt.links.new(tr2.outputs["Result"], glow.inputs[2])+ base = nt.nodes.new("ShaderNodeMath"); base.operation = "ADD"; base.inputs[1].default_value = 0.025+ nt.links.new(glow.outputs[0], base.inputs[0])+ g_out = base.outputs[0]+ else:+ nz = nt.nodes.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 400+ nt.links.new(tc.outputs["UV"], nz.inputs["Vector"])+ glow.operation = "MULTIPLY_ADD"; glow.inputs[1].default_value = 0.25; glow.inputs[2].default_value = 0.6+ nt.links.new(nz.outputs["Fac"], glow.inputs[0])+ g_out = glow.outputs[0]+ em = nt.nodes.new("ShaderNodeMath"); em.operation = "MULTIPLY"; em.inputs[1].default_value = strength+ nt.links.new(g_out, em.inputs[0])+ if not trace: # TVs: instances share this material, so the glow is switched per object by the "tv_on" property+ at = nt.nodes.new("ShaderNodeAttribute"); at.attribute_type = "OBJECT"; at.attribute_name = "tv_on"+ em2 = nt.nodes.new("ShaderNodeMath"); em2.operation = "MULTIPLY"+ nt.links.new(em.outputs[0], em2.inputs[0]); nt.links.new(at.outputs["Fac"], em2.inputs[1])+ em = em2+ b.inputs["Emission Color"].default_value = (*tint, 1)+ nt.links.new(em.outputs[0], b.inputs["Emission Strength"])+ return m+++def screen_patch(ob, rect, y, mat, name, bulge=0.004):+ """Slightly domed patch over rect=(x0, z0, x1, z1) at depth y (just in front of the hit surface), UV 0..1."""+ x0, z0, x1, z1 = rect+ me = bpy.data.meshes.new(name)+ nx, nz = 12, 10+ vs, fs, uvs = [], [], []+ for j in range(nz + 1):+ for i in range(nx + 1):+ u, v = i / nx, j / nz+ dome = bulge * (1 - (2 * u - 1) ** 2) * (1 - (2 * v - 1) ** 2)+ vs.append((x0 + (x1 - x0) * u, y - 0.0015 - dome, z0 + (z1 - z0) * v))+ for j in range(nz):+ for i in range(nx):+ a = j * (nx + 1) + i+ fs.append((a, a + 1, a + nx + 2, a + nx + 1))+ me.from_pydata(vs, [], fs)+ uv = me.uv_layers.new(name="UVMap")+ for li, l in enumerate(me.loops):+ k = l.vertex_index+ uv.data[li].uv = ((k % (nx + 1)) / nx, (k // (nx + 1)) / nz)+ for p in me.polygons:+ p.use_smooth = True+ me.materials.append(mat)+ p = bpy.data.objects.new(name, me)+ ob.users_collection[0].objects.link(p)+ return p+++def join_into(ob, part):+ bpy.ops.object.select_all(action="DESELECT")+ part.select_set(True)+ ob.select_set(True)+ bpy.context.view_layer.objects.active = ob+ bpy.ops.object.join()+++def fix_oscilloscope(ob):+ hits = front_colour_grid(ob)+ green = [(x, z, y) for x, z, y, c in hits if c[1] > c[0] + 0.06 and c[1] > c[2] + 0.02 and c[1] > 0.12]+ xs, zs, ys = zip(*green)+ # trim outliers (labels with green ink) to the dense core+ x0, x1 = np.percentile(xs, 3), np.percentile(xs, 97)+ z0, z1 = np.percentile(zs, 3), np.percentile(zs, 97)+ y = float(np.percentile(ys, 10))+ print(f"oscilloscope screen rect x {x0:.3f}..{x1:.3f} z {z0:.3f}..{z1:.3f} y {y:.3f} from {len(green)} green hits")+ join_into(ob, screen_patch(ob, (x0, z0, x1, z1), y, crt_material("scope_crt", (0.25, 1.0, 0.45)), "screen"))+++def fix_lens(ob):+ """Helping hands: the generator returned the magnifier as a solid disc; turn its inner faces into glass."""+ vs = [v.co for v in ob.data.vertices]+ top = max(v.z for v in vs)+ up = [v for v in vs if v.z > top - 0.08]+ c = Vector((sum(v.x for v in up) / len(up), sum(v.y for v in up) / len(up), sum(v.z for v in up) / len(up)))+ r = (max(v.x for v in up) - min(v.x for v in up)) / 2+ glass = bpy.data.materials.new("lens_glass")+ g = glass.node_tree.nodes["Principled BSDF"]+ g.inputs["Base Color"].default_value = (0.95, 0.97, 0.96, 1)+ g.inputs["Roughness"].default_value = 0.02+ g.inputs["Transmission Weight"].default_value = 1.0+ g.inputs["IOR"].default_value = 1.52+ ob.data.materials.append(glass)+ gi = len(ob.data.materials) - 1+ n = 0+ for p in ob.data.polygons:+ pc = p.center+ if (Vector((pc.x, 0, pc.z)) - Vector((c.x, 0, c.z))).length < r * 0.8 and abs(pc.y - c.y) < r * 0.5:+ p.material_index = gi+ n += 1+ print(f"helping_hands lens: {n} faces -> glass (centre {tuple(round(v, 3) for v in c)}, r {r:.3f})")+++def fix_crt_tv(ob):+ """Shelf CRT left on a dark blue 'no signal' screen: find the dark screen on the front, put a glowing patch on it."""+ hits = front_colour_grid(ob)+ d = ob.dimensions+ dark = [(x, z, y) for x, z, y, c in hits if sum(c) / 3 < 0.09 and abs(x) < d.x * 0.45 and z > d.z * 0.2]+ xs, zs, ys = zip(*dark)+ x0, x1 = np.percentile(xs, 10), np.percentile(xs, 90)+ z0, z1 = np.percentile(zs, 10), np.percentile(zs, 90)+ y = float(min(ys)) - 0.002 # (front is -Y) just in front of the tube's most forward point (the patch adds its own dome)+ print(f"crt screen rect x {x0:.3f}..{x1:.3f} z {z0:.3f}..{z1:.3f}")+ join_into(ob, screen_patch(ob, (x0, z0, x1, z1), y, crt_material("tv_crt", (0.12, 0.25, 1.0), trace=False, strength=0.4), "screen", 0.008))+++FIXES = {"oscilloscope": fix_oscilloscope, "helping_hands": fix_lens, "repair_crt_tv": fix_crt_tv}++for pid, fn in FIXES.items():+ if only and pid not in only:+ continue+ path = os.path.join(PROPS, f"{pid}.blend")+ if not os.path.exists(path):+ print("skip (not prepped)", pid)+ continue+ bpy.ops.wm.open_mainfile(filepath=path)+ ob = bpy.data.objects[pid]+ if ob.get("fixed"):+ print("already fixed", pid)+ continue+ fn(ob)+ ob = bpy.data.objects[pid]+ ob["fixed"] = True+ bpy.ops.wm.save_as_mainfile(filepath=path)+ print("FIXED", pid)diff --git a/scenes/tokyo-electronics-repair/scripts/gen3d.mjs b/scenes/tokyo-electronics-repair/scripts/gen3d.mjsnew file mode 100644index 0000000..3274172--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/gen3d.mjs@@ -0,0 +1,21 @@+// Run every repair prop through tripo-h31 and meshy, 12 at a time. Skips props that already have model.glb.+// node scenes/tokyo-electronics-repair/scripts/gen3d.mjs [id ...] (ids limit the run, e.g. for regenerations)+import { execFile } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+const man = JSON.parse(readFileSync('scenes/tokyo-electronics-repair/assets.json', 'utf8'));+const only = process.argv.slice(2);+mkdirSync('scenes/tokyo-electronics-repair/logs', { recursive: true });+const jobs = [];+for (const a of man.generate) {+ if (only.length && !only.includes(a.id)) continue;+ const ref = a.ref ?? `refs/tokyo-electronics-repair/props/${a.id}.json`;+ for (const m of (a.models ?? ['tripo-h31', 'meshy'])) if (!existsSync(`assets/gen/${m}/${a.id}/model.glb`)) jobs.push([m, a.id, ref]);+}+console.log(`${jobs.length} jobs`);+const run = ([m, id, ref]) => new Promise((res) => execFile('node', ['generate/fal.mjs', '3d', '--model', m, '--ref', ref, '--out', `assets/gen/${m}/${id}`], { maxBuffer: 1e7, timeout: 40 * 60_000 }, (err, out, errout) => {+ writeFileSync(`scenes/tokyo-electronics-repair/logs/gen_${m}_${id}.log`, out + errout);+ console.log(`${err ? 'FAIL' : 'ok '} ${m} ${id}${err ? ' ' + errout.slice(-200).replace(/\s+/g, ' ') : ''}`);+ res();+}));+let i = 0;+await Promise.all(Array.from({ length: +(process.env.POOL ?? 14) }, async () => { while (i < jobs.length) await run(jobs[i++]); }));diff --git a/scenes/tokyo-electronics-repair/scripts/gpu_prefs.py b/scenes/tokyo-electronics-repair/scripts/gpu_prefs.pynew file mode 100644index 0000000..806545e--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/gpu_prefs.py@@ -0,0 +1,10 @@+"""Enable OptiX for this Blender session; chain before another script: --python gpu_prefs.py --python shoot.py -- ..."""+import bpy+prefs = bpy.context.preferences.addons["cycles"].preferences+prefs.compute_device_type = "OPTIX"+prefs.get_devices()+for d in prefs.devices:+ d.use = d.type == "OPTIX"+for sc in bpy.data.scenes:+ sc.cycles.device = "GPU"+print("gpu_prefs: OPTIX on", [d.name for d in prefs.devices if d.use])diff --git a/scenes/tokyo-electronics-repair/scripts/grade.sh b/scenes/tokyo-electronics-repair/scripts/grade.shnew file mode 100644index 0000000..71c0cbb--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/grade.sh@@ -0,0 +1,14 @@+#!/usr/bin/env bash+# Final look in post (deterministic, no re-render): cool-night grade, slight chromatic aberration, vignette, grain.+# scenes/tokyo-electronics-repair/scripts/grade.sh still <in.png> <out.png>+# scenes/tokyo-electronics-repair/scripts/grade.sh clip <frames_dir> <out.mp4>+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++# lift + tint the shadows toward teal, keep warm highlights from the lamp, pull saturation slightly+GRADE="curves=r='0/0.03 0.25/0.235 0.6/0.63 1/0.98':g='0/0.035 0.25/0.25 0.6/0.62 1/0.97':b='0/0.055 0.25/0.28 0.6/0.61 1/0.94',hue=s=0.88,rgbashift=rh=-1:bh=1:edge=smear,vignette=angle=PI/4.6"+case "$1" in+ still) "$FF" -v error -y -i "$2" -vf "$GRADE,noise=alls=5:allf=u" -frames:v 1 "$3" ;;+ clip) "$FF" -v error -y -framerate 24 -i "$2/f%04d.png" -vf "$GRADE,noise=alls=7:allf=t+u,format=yuv420p" -c:v h264_nvenc -preset p7 -rc vbr -cq 18 -b:v 0 -movflags +faststart "$3" ;;+ *) echo "usage: grade.sh still|clip ..." ; exit 1 ;;+esacdiff --git a/scenes/tokyo-electronics-repair/scripts/grime.py b/scenes/tokyo-electronics-repair/scripts/grime.pynew file mode 100644index 0000000..3854959--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/grime.py@@ -0,0 +1,282 @@+"""Imperfections pass: grime and wear across every surface (the video's "realism lives in the imperfections").++blender -b <in.blend> --python scenes/tokyo-electronics-repair/scripts/grime.py -- <out.blend>+- grime_layer node group inserted before Base Color / Roughness of every surface material:+ per-instance tint (Object Info > Color), dust on up-facing surfaces broken up by noise, AO crevice dirt,+ dust raises roughness. Amount per material family.+- floor: trodden paths (door -> counter, the bench aisle, behind the counter), scuffs, dust along the walls.+- bench mat: flux burns, rosin stains. Storefront glass + CRT faces: fingerprint / smudge roughness.+- ceiling: water-stain rings. Idempotent (skips materials already carrying the group).+"""+import os+import sys++import bpy++sys.path.insert(0, os.path.dirname(__file__))+import lib # noqa: E402++out = os.path.abspath(sys.argv[sys.argv.index("--") + 1])+SKIP = ("glass", "haze", "rain", "street_backdrop", "decal", "fluoro", "crt", "vending", "lens", "clay", "puddle", "led", "vfd",+ "bulb", "tube", "backroom", "wire", "umbrella", "amber", "chrome", "copper", "solder", "brass", "aframe_bulb")+++def group():+ g = bpy.data.node_groups.get("grime_layer")+ if g:+ return g+ g = bpy.data.node_groups.new("grime_layer", "ShaderNodeTree")+ g.interface.new_socket("Color", in_out="INPUT", socket_type="NodeSocketColor")+ g.interface.new_socket("Roughness", in_out="INPUT", socket_type="NodeSocketFloat")+ g.interface.new_socket("Amount", in_out="INPUT", socket_type="NodeSocketFloat")+ g.interface.new_socket("Color", in_out="OUTPUT", socket_type="NodeSocketColor")+ g.interface.new_socket("Roughness", in_out="OUTPUT", socket_type="NodeSocketFloat")+ n, L = g.nodes, g.links+ gi, go = n.new("NodeGroupInput"), n.new("NodeGroupOutput")+ oi = n.new("ShaderNodeObjectInfo")+ tinted = lib._mix(g, 1.0, gi.outputs[0], oi.outputs["Color"], "MULTIPLY")+ geo = n.new("ShaderNodeNewGeometry")+ sep = n.new("ShaderNodeSeparateXYZ")+ L.new(geo.outputs["Normal"], sep.inputs["Vector"])+ up = n.new("ShaderNodeMapRange")+ up.inputs["From Min"].default_value, up.inputs["From Max"].default_value = 0.55, 0.95+ L.new(sep.outputs["Z"], up.inputs["Value"])+ nz = n.new("ShaderNodeTexNoise")+ nz.inputs["Scale"].default_value = 9.0+ nz.inputs["Detail"].default_value = 8+ L.new(geo.outputs["Position"], nz.inputs["Vector"])+ nr = lib._ramp(g, nz.outputs["Fac"], [(0.35, (0.25, 0.25, 0.25)), (0.7, (1, 1, 1))])+ dust = n.new("ShaderNodeMath")+ dust.operation = "MULTIPLY"+ L.new(up.outputs["Result"], dust.inputs[0])+ L.new(nr.outputs["Color"], dust.inputs[1])+ dust2 = n.new("ShaderNodeMath")+ dust2.operation = "MULTIPLY"+ L.new(dust.outputs[0], dust2.inputs[0])+ L.new(gi.outputs[2], dust2.inputs[1])+ dust3 = n.new("ShaderNodeMath")+ dust3.operation = "MULTIPLY"+ dust3.use_clamp = True+ dust3.inputs[1].default_value = 0.55+ L.new(dust2.outputs[0], dust3.inputs[0])+ dusty = lib._mix(g, dust3.outputs[0], tinted, (0.4, 0.38, 0.34))+ ao = n.new("ShaderNodeAmbientOcclusion")+ ao.samples = 8+ ao.inputs["Distance"].default_value = 0.06+ crev = n.new("ShaderNodeMapRange") # AO 1 -> 1, AO 0 -> 1 - 0.55 * amount+ L.new(ao.outputs["AO"], crev.inputs["Value"])+ lo = n.new("ShaderNodeMath")+ lo.operation = "MULTIPLY_ADD"+ lo.inputs[1].default_value = -0.55+ lo.inputs[2].default_value = 1.0+ L.new(gi.outputs[2], lo.inputs[0])+ L.new(lo.outputs[0], crev.inputs["To Min"])+ crev.inputs["To Max"].default_value = 1.0+ dirty = lib._mix(g, 1.0, dusty, crev.outputs["Result"], "MULTIPLY")+ L.new(dirty, go.inputs[0])+ rr = n.new("ShaderNodeMapRange")+ L.new(dust3.outputs[0], rr.inputs["Value"])+ rr.inputs["From Max"].default_value = 0.55+ L.new(gi.outputs[1], rr.inputs["To Min"])+ rr.inputs["To Max"].default_value = 0.9+ L.new(rr.outputs["Result"], go.inputs[1])+ return g+++def amount_for(name):+ n = name.lower()+ if any(k in n for k in ("shelf_steel", "fixture", "conduit", "cabinet", "drawer")):+ return 1.3+ if any(k in n for k in ("card", "bin_", "crate", "paper", "tags", "sticky", "flyer", "price", "poster", "calendar", "label")):+ return 0.45+ if any(k in n for k in ("bench_wood", "esd", "floor", "wall", "ceiling", "pegboard", "door")):+ return 0.5+ return 1.0+++def add_grime(m):+ nt = m.node_tree+ if nt is None or any(nd.type == "GROUP" and nd.node_tree and nd.node_tree.name == "grime_layer" for nd in nt.nodes):+ return False+ b = next((nd for nd in nt.nodes if nd.type == "BSDF_PRINCIPLED"), None)+ if b is None:+ return False+ if b.inputs["Emission Strength"].default_value > 0 or b.inputs["Emission Strength"].is_linked:+ return False+ if b.inputs["Transmission Weight"].default_value > 0.5:+ return False+ gn = nt.nodes.new("ShaderNodeGroup")+ gn.node_tree = group()+ gn.inputs["Amount"].default_value = amount_for(m.name)+ for sock, gi, go in (("Base Color", "Color", 0), ("Roughness", "Roughness", 1)):+ s = b.inputs[sock]+ if s.is_linked:+ nt.links.new(s.links[0].from_socket, gn.inputs[gi])+ else:+ gn.inputs[gi].default_value = s.default_value+ nt.links.new(gn.outputs[go], s)+ return True+++def wrap_base(m, build):+ """Insert extra colour/roughness logic for one specific material: build(nt, color_socket, rough_socket) -> (color, rough)."""+ nt = m.node_tree+ if m.get("wear"):+ return+ b = next(nd for nd in nt.nodes if nd.type == "BSDF_PRINCIPLED")+ cs = b.inputs["Base Color"].links[0].from_socket if b.inputs["Base Color"].is_linked else None+ rs = b.inputs["Roughness"].links[0].from_socket if b.inputs["Roughness"].is_linked else None+ if cs is None:+ rgb = nt.nodes.new("ShaderNodeRGB")+ rgb.outputs[0].default_value = b.inputs["Base Color"].default_value+ cs = rgb.outputs[0]+ if rs is None:+ v = nt.nodes.new("ShaderNodeValue")+ v.outputs[0].default_value = b.inputs["Roughness"].default_value+ rs = v.outputs[0]+ col, rough = build(nt, cs, rs)+ if col is not None:+ nt.links.new(col, b.inputs["Base Color"])+ if rough is not None:+ nt.links.new(rough, b.inputs["Roughness"])+ m["wear"] = True+++def band(nt, sep_x, lo, hi, soft=0.15):+ """1 inside [lo, hi] along one coordinate, soft edges."""+ a = nt.nodes.new("ShaderNodeMapRange")+ a.inputs["From Min"].default_value, a.inputs["From Max"].default_value = lo - soft, lo + soft+ nt.links.new(sep_x, a.inputs["Value"])+ b = nt.nodes.new("ShaderNodeMapRange")+ b.inputs["From Min"].default_value, b.inputs["From Max"].default_value = hi + soft, hi - soft+ nt.links.new(sep_x, b.inputs["Value"])+ m = nt.nodes.new("ShaderNodeMath")+ m.operation = "MULTIPLY"+ nt.links.new(a.outputs["Result"], m.inputs[0])+ nt.links.new(b.outputs["Result"], m.inputs[1])+ return m.outputs[0]+++def math(nt, op, a, b=None):+ m = nt.nodes.new("ShaderNodeMath")+ m.operation = op+ for i, v in enumerate((a, b)):+ if v is None:+ continue+ if isinstance(v, (int, float)):+ m.inputs[i].default_value = v+ else:+ nt.links.new(v, m.inputs[i])+ return m.outputs[0]+++def floor_build(nt, cs, rs):+ geo = nt.nodes.new("ShaderNodeNewGeometry")+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ nt.links.new(geo.outputs["Position"], sep.inputs["Vector"])+ X, Y = sep.outputs["X"], sep.outputs["Y"]+ p1 = math(nt, "MULTIPLY", band(nt, X, 1.55, 2.7), band(nt, Y, -0.5, 2.4)) # door -> counter+ p2 = math(nt, "MULTIPLY", band(nt, X, 0.85, 1.55), band(nt, Y, 1.2, 5.9)) # along the bench+ p3 = math(nt, "MULTIPLY", band(nt, X, 0.9, 3.6), band(nt, Y, 2.25, 2.95)) # behind the counter+ p4 = math(nt, "MULTIPLY", band(nt, X, 2.3, 3.4), band(nt, Y, 4.5, 6.5)) # to the back door+ path = math(nt, "MAXIMUM", math(nt, "MAXIMUM", p1, p2), math(nt, "MAXIMUM", p3, p4))+ nz = lib._noise(nt, 2.5, 6, geo.outputs["Position"])+ pn = math(nt, "MULTIPLY", path, math(nt, "MULTIPLY_ADD", nz.outputs["Fac"], 1.2) if False else nz.outputs["Fac"])+ pn = math(nt, "MULTIPLY", pn, 1.4)+ # scuffs: thin dark streaks, stretched along y+ mp = nt.nodes.new("ShaderNodeMapping")+ mp.inputs["Scale"].default_value = (30, 3, 1)+ nt.links.new(geo.outputs["Position"], mp.inputs["Vector"])+ sn = lib._noise(nt, 1.0, 3, mp.outputs["Vector"])+ scuff = lib._ramp(nt, sn.outputs["Fac"], [(0.62, (0, 0, 0)), (0.7, (1, 1, 1))])+ scuff = math(nt, "MULTIPLY", scuff.outputs["Color"], math(nt, "ADD", path, 0.25))+ # dust along the walls+ wall = math(nt, "MAXIMUM", math(nt, "MAXIMUM", band(nt, X, -1, 0.15, 0.1), band(nt, X, 4.05, 5, 0.1)), band(nt, Y, 6.3, 8, 0.12))+ col = lib._mix(nt, math(nt, "MULTIPLY", pn, 0.55), cs, (0.06, 0.055, 0.05), "MULTIPLY")+ col = lib._mix(nt, math(nt, "MULTIPLY", scuff, 0.6), col, (0.03, 0.03, 0.03))+ col = lib._mix(nt, math(nt, "MULTIPLY", wall, 0.45), col, (0.42, 0.4, 0.36))+ rough = math(nt, "SUBTRACT", rs, math(nt, "MULTIPLY", pn, 0.3))+ rough = math(nt, "ADD", rough, math(nt, "MULTIPLY", wall, 0.3))+ return col, rough+++def mat_burns(nt, cs, rs):+ tc = nt.nodes.new("ShaderNodeTexCoord")+ vo = nt.nodes.new("ShaderNodeTexVoronoi")+ vo.inputs["Scale"].default_value = 30+ nt.links.new(tc.outputs["Object"], vo.inputs["Vector"])+ burn = lib._ramp(nt, vo.outputs["Distance"], [(0.0, (1, 1, 1)), (0.09, (0, 0, 0))])+ keep = lib._noise(nt, 4, 3, tc.outputs["Object"])+ km = lib._ramp(nt, keep.outputs["Fac"], [(0.55, (0, 0, 0)), (0.6, (1, 1, 1))])+ b = math(nt, "MULTIPLY", burn.outputs["Color"], km.outputs["Color"])+ st = lib._noise(nt, 6, 6, tc.outputs["Object"])+ stain = lib._ramp(nt, st.outputs["Fac"], [(0.58, (0, 0, 0)), (0.68, (1, 1, 1))])+ col = lib._mix(nt, math(nt, "MULTIPLY", stain.outputs["Color"], 0.6), cs, (0.22, 0.12, 0.04))+ col = lib._mix(nt, b, col, (0.015, 0.01, 0.005))+ rough = math(nt, "SUBTRACT", rs, math(nt, "MULTIPLY", stain.outputs["Color"], 0.25))+ return col, rough+++def smudge_rough(base_lo, base_hi, scale=5.0):+ def build(nt, cs, rs):+ geo = nt.nodes.new("ShaderNodeNewGeometry")+ nz = lib._noise(nt, scale, 10, geo.outputs["Position"])+ r = lib._ramp(nt, nz.outputs["Fac"], [(0.45, (0, 0, 0)), (0.75, (1, 1, 1))])+ vo = nt.nodes.new("ShaderNodeTexVoronoi") # fingerprint-sized blobs+ vo.inputs["Scale"].default_value = scale * 18+ nt.links.new(geo.outputs["Position"], vo.inputs["Vector"])+ fp = lib._ramp(nt, vo.outputs["Distance"], [(0.0, (1, 1, 1)), (0.25, (0, 0, 0))])+ mask = math(nt, "MAXIMUM", r.outputs["Color"], math(nt, "MULTIPLY", fp.outputs["Color"], r.outputs["Color"]))+ mr = nt.nodes.new("ShaderNodeMapRange")+ mr.inputs["To Min"].default_value, mr.inputs["To Max"].default_value = base_lo, base_hi+ nt.links.new(mask, mr.inputs["Value"])+ return None, mr.outputs["Result"]+ return build+++def ceiling_stains(nt, cs, rs):+ geo = nt.nodes.new("ShaderNodeNewGeometry")+ nz = lib._noise(nt, 0.55, 4, geo.outputs["Position"])+ ring = lib._ramp(nt, nz.outputs["Fac"], [(0.655, (1, 1, 1)), (0.665, (0.45, 0.33, 0.2)), (0.675, (0.8, 0.68, 0.5)), (0.75, (0.88, 0.8, 0.66)), (0.8, (1, 1, 1))])+ return lib._mix(nt, 1.0, cs, ring.outputs["Color"], "MULTIPLY"), None+++n = 0+for m in bpy.data.materials:+ name = m.name.lower()+ if any(k in name for k in SKIP):+ continue+ if add_grime(m):+ n += 1+for name, fn in (("floor_vinyl", floor_build), ("esd_mat", mat_burns), ("ceiling_tile", ceiling_stains),+ ("rain_glass", smudge_rough(0.02, 0.22, 4.0)), ("scope_crt", smudge_rough(0.06, 0.4, 25.0)),+ ("tv_crt", smudge_rough(0.06, 0.4, 20.0)), ("case_glass", smudge_rough(0.03, 0.25, 12.0))):+ m = bpy.data.materials.get(name)+ if m:+ wrap_base(m, fn)+# CRT TVs: scanlines + a slow rolling bar on the no-signal glow (an evenly lit blue rectangle reads as a flat card)+tv = bpy.data.materials.get("tv_crt")+if tv and not tv.get("scan"):+ nt = tv.node_tree+ b = next(nd for nd in nt.nodes if nd.type == "BSDF_PRINCIPLED")+ src = b.inputs["Emission Strength"].links[0].from_socket+ tc = nt.nodes.new("ShaderNodeTexCoord")+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ nt.links.new(tc.outputs["UV"], sep.inputs["Vector"])+ lines = math(nt, "MULTIPLY_ADD", math(nt, "SINE", math(nt, "MULTIPLY", sep.outputs["Y"], 900.0)), 0.25)+ lines.node.inputs[1].default_value, lines.node.inputs[2].default_value = 0.25, 0.75+ fr = nt.nodes.new("ShaderNodeValue") # rolling bar position, keyed below+ roll = math(nt, "FRACT", math(nt, "ADD", sep.outputs["Y"], fr.outputs[0]))+ bar = lib._ramp(nt, roll, [(0.0, (1.35, 1.35, 1.35)), (0.12, (1, 1, 1)), (1.0, (1, 1, 1))])+ # soft vignette: sin(pi x) * sin(pi y) (a product of triangle waves shows diamond-shaped bands)+ edge = math(nt, "MULTIPLY", math(nt, "SINE", math(nt, "MULTIPLY", sep.outputs["X"], 3.14159)), math(nt, "SINE", math(nt, "MULTIPLY", sep.outputs["Y"], 3.14159)))+ vign = math(nt, "POWER", math(nt, "MAXIMUM", edge, 0.0), 0.3)+ k = math(nt, "MULTIPLY", math(nt, "MULTIPLY", lines, bar.outputs["Color"]), vign)+ nt.links.new(math(nt, "MULTIPLY", src, k), b.inputs["Emission Strength"])+ fr.outputs[0].default_value = 0.0+ fr.outputs[0].keyframe_insert("default_value", frame=1)+ fr.outputs[0].default_value = -1.0+ fr.outputs[0].keyframe_insert("default_value", frame=97)+ tv["scan"] = True+print("grime on", n, "materials")+bpy.ops.wm.save_as_mainfile(filepath=out)diff --git a/scenes/tokyo-electronics-repair/scripts/lib.py b/scenes/tokyo-electronics-repair/scripts/lib.pynew file mode 100644index 0000000..38b6bd8--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/lib.py@@ -0,0 +1,365 @@+"""Small direct-modelling + material library for the repair shop scene (Blender 5.0)."""+import math+import os+import random++import bpy+import bmesh+from mathutils import Vector++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+++def sock(node, name, kind=None):+ """Enabled input socket by name (Mix nodes have several sockets per name)."""+ for s in node.inputs:+ if s.name == name and s.enabled and (kind is None or s.type == kind):+ return s+ raise KeyError(name)+++def collection(name, parent=None):+ c = bpy.data.collections.get(name) or bpy.data.collections.new(name)+ p = parent or bpy.context.scene.collection+ if c.name not in [x.name for x in p.children]:+ p.children.link(c)+ return c+++def link(obj, coll):+ for c in obj.users_collection:+ c.objects.unlink(obj)+ coll.objects.link(obj)+ return obj+++def box(name, lo, hi, mat=None, coll=None, bevel=0.002, uv_scale=1.0):+ """Axis-aligned box from world-space corners, real geometry (no object scale), box-projected UVs in metres."""+ lo, hi = Vector(lo), Vector(hi)+ me = bpy.data.meshes.new(name)+ bm = bmesh.new()+ bmesh.ops.create_cube(bm, size=1.0)+ size = hi - lo+ for v in bm.verts:+ v.co = Vector((v.co.x * size.x, v.co.y * size.y, v.co.z * size.z))+ uv = bm.loops.layers.uv.new("UVMap")+ for f in bm.faces:+ n = f.normal+ for l in f.loops:+ co = l.vert.co + (lo + hi) / 2+ if abs(n.z) > 0.5:+ l[uv].uv = (co.x * uv_scale, co.y * uv_scale)+ elif abs(n.x) > 0.5:+ l[uv].uv = (co.y * uv_scale, co.z * uv_scale)+ else:+ l[uv].uv = (co.x * uv_scale, co.z * uv_scale)+ bm.to_mesh(me)+ bm.free()+ ob = bpy.data.objects.new(name, me)+ ob.location = (lo + hi) / 2+ (coll or bpy.context.scene.collection).objects.link(ob)+ if mat:+ me.materials.append(mat)+ if bevel > 0 and min(size) > bevel * 3:+ m = ob.modifiers.new("bevel", "BEVEL")+ m.width = bevel+ m.segments = 2+ m.limit_method = "ANGLE"+ m.harden_normals = True+ for p in me.polygons: # smooth only with a bevel + hardened normals; a smooth unbevelled slab refracts like a lens+ p.use_smooth = True+ return ob+++def cylinder(name, centre, r, h, mat=None, coll=None, axis="Z", verts=24):+ bpy.ops.mesh.primitive_cylinder_add(vertices=verts, radius=r, depth=h, location=centre)+ ob = bpy.context.object+ ob.name = name+ if axis == "X":+ ob.rotation_euler = (0, math.pi / 2, 0)+ elif axis == "Y":+ ob.rotation_euler = (math.pi / 2, 0, 0)+ if mat:+ ob.data.materials.append(mat)+ if coll:+ link(ob, coll)+ return ob+++def plane(name, centre, w, h, normal="-Y", mat=None, coll=None):+ """Upright (or flat with normal Z) textured plane, UV 0..1."""+ me = bpy.data.meshes.new(name)+ hw, hh = w / 2, h / 2+ if normal in ("-Y", "Y"):+ vs = [(-hw, 0, -hh), (hw, 0, -hh), (hw, 0, hh), (-hw, 0, hh)]+ elif normal in ("-X", "X"):+ vs = [(0, hw, -hh), (0, -hw, -hh), (0, -hw, hh), (0, hw, hh)]+ else:+ vs = [(-hw, -hh, 0), (hw, -hh, 0), (hw, hh, 0), (-hw, hh, 0)]+ if normal in ("Y", "X"):+ vs = [vs[1], vs[0], vs[3], vs[2]]+ me.from_pydata(vs, [], [(0, 1, 2, 3)])+ uv = me.uv_layers.new(name="UVMap")+ for i, l in enumerate(me.loops):+ uv.data[i].uv = [(0, 0), (1, 0), (1, 1), (0, 1)][l.vertex_index]+ ob = bpy.data.objects.new(name, me)+ ob.location = centre+ (coll or bpy.context.scene.collection).objects.link(ob)+ if mat:+ me.materials.append(mat)+ return ob+++def set_uv_rect(ob, u0, v0, u1, v1):+ uv = ob.data.uv_layers[0]+ for i, l in enumerate(ob.data.loops):+ c = [(u0, v0), (u1, v0), (u1, v1), (u0, v1)][l.vertex_index]+ uv.data[i].uv = c+++# ---------------------------------------------------------------- materials++def _new(name):+ m = bpy.data.materials.get(name)+ if m:+ return m, None+ m = bpy.data.materials.new(name)+ nt = m.node_tree+ return m, nt+++def principled(name, color, rough=0.5, metal=0.0, **kw):+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (*color, 1)+ b.inputs["Roughness"].default_value = rough+ b.inputs["Metallic"].default_value = metal+ for k, v in kw.items():+ b.inputs[k].default_value = v+ return m+++def _noise(nt, scale, detail=6, coord=None):+ n = nt.nodes.new("ShaderNodeTexNoise")+ n.inputs["Scale"].default_value = scale+ n.inputs["Detail"].default_value = detail+ if coord is not None:+ nt.links.new(coord, n.inputs["Vector"])+ return n+++def _ramp(nt, src, stops):+ r = nt.nodes.new("ShaderNodeValToRGB")+ nt.links.new(src, r.inputs["Fac"])+ els = r.color_ramp.elements+ for i, (pos, col) in enumerate(stops):+ e = els[i] if i < len(els) else els.new(pos)+ e.position = pos+ e.color = (*col, 1) if len(col) == 3 else col+ return r+++def _mix(nt, fac, a, b, blend="MIX"):+ m = nt.nodes.new("ShaderNodeMix")+ m.data_type = "RGBA"+ m.blend_type = blend+ if isinstance(fac, float):+ sock(m, "Factor", "VALUE").default_value = fac+ else:+ nt.links.new(fac, sock(m, "Factor", "VALUE"))+ for s, v in (("A", a), ("B", b)):+ if isinstance(v, tuple):+ sock(m, s, "RGBA").default_value = (*v, 1) if len(v) == 3 else v+ else:+ nt.links.new(v, sock(m, s, "RGBA"))+ return m.outputs["Result"]+++def _bump(nt, height, strength, dist=0.002):+ b = nt.nodes.new("ShaderNodeBump")+ b.inputs["Strength"].default_value = strength+ b.inputs["Distance"].default_value = dist+ nt.links.new(height, b.inputs["Height"])+ return b.outputs["Normal"]+++def grimy(name, base, grime=(0.18, 0.16, 0.13), rough=(0.45, 0.75), metal=0.0, scale=3.0, amount=0.35, bump=0.15):+ """Generic worn surface: base colour broken up by large-scale grime and fine speckle, roughness follows grime."""+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ tc = nt.nodes.new("ShaderNodeTexCoord")+ n1 = _noise(nt, scale, 8, tc.outputs["Object"])+ n2 = _noise(nt, scale * 40, 4, tc.outputs["Object"])+ r1 = _ramp(nt, n1.outputs["Fac"], [(0.45, (0, 0, 0)), (0.75, (1, 1, 1))])+ fac = _mix(nt, 0.5, r1.outputs["Color"], n2.outputs["Color"], "MULTIPLY")+ f2 = nt.nodes.new("ShaderNodeMath")+ f2.operation = "MULTIPLY"+ f2.inputs[1].default_value = amount * 2+ nt.links.new(fac, f2.inputs[0])+ col = _mix(nt, f2.outputs[0], base, grime)+ nt.links.new(col, b.inputs["Base Color"])+ mr = nt.nodes.new("ShaderNodeMapRange")+ mr.inputs["To Min"].default_value = rough[0]+ mr.inputs["To Max"].default_value = rough[1]+ nt.links.new(f2.outputs[0], mr.inputs["Value"])+ nt.links.new(mr.outputs["Result"], b.inputs["Roughness"])+ b.inputs["Metallic"].default_value = metal+ nt.links.new(_bump(nt, n2.outputs["Fac"], bump), b.inputs["Normal"])+ return m+++def wood(name, light=(0.42, 0.27, 0.15), dark=(0.2, 0.11, 0.05), scale=2.0, worn=0.3):+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ tc = nt.nodes.new("ShaderNodeTexCoord")+ mp = nt.nodes.new("ShaderNodeMapping")+ mp.inputs["Scale"].default_value = (scale * 6, scale * 0.15, scale * 6) # long streaks along Y (bench/shelf length)+ nt.links.new(tc.outputs["Object"], mp.inputs["Vector"])+ nz = _noise(nt, 4.0, 8, mp.outputs["Vector"])+ w = nt.nodes.new("ShaderNodeTexWave") # kept for the bump only+ w.wave_type = "BANDS"+ w.bands_direction = "X"+ w.inputs["Scale"].default_value = 40.0+ w.inputs["Distortion"].default_value = 1.5+ nt.links.new(mp.outputs["Vector"], w.inputs["Vector"])+ r = _ramp(nt, nz.outputs["Fac"], [(0.3, dark), (0.7, light)])+ grime = _noise(nt, 1.5, 6, tc.outputs["Object"])+ gr = _ramp(nt, grime.outputs["Fac"], [(0.5, (0, 0, 0)), (0.8, (1, 1, 1))])+ f = nt.nodes.new("ShaderNodeMath")+ f.operation = "MULTIPLY"+ f.inputs[1].default_value = worn+ nt.links.new(gr.outputs["Color"], f.inputs[0])+ col = _mix(nt, f.outputs[0], r.outputs["Color"], (0.06, 0.04, 0.025))+ nt.links.new(col, b.inputs["Base Color"])+ mr = nt.nodes.new("ShaderNodeMapRange")+ mr.inputs["To Min"].default_value = 0.35+ mr.inputs["To Max"].default_value = 0.7+ nt.links.new(nz.outputs["Fac"], mr.inputs["Value"])+ nt.links.new(mr.outputs["Result"], b.inputs["Roughness"])+ nt.links.new(_bump(nt, w.outputs["Fac"], 0.08), b.inputs["Normal"])+ return m+++def floor_tiles(name, tile=0.3, a=(0.55, 0.53, 0.47), b2=(0.33, 0.33, 0.31)):+ """Old checker vinyl floor tiles with grout, scuffs and traffic grime."""+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ tc = nt.nodes.new("ShaderNodeTexCoord")+ br = nt.nodes.new("ShaderNodeTexBrick")+ br.offset = 0.0+ br.inputs["Scale"].default_value = 1.0+ br.inputs["Brick Width"].default_value = tile+ br.inputs["Row Height"].default_value = tile+ br.inputs["Mortar Size"].default_value = 0.002+ br.inputs["Color1"].default_value = (*a, 1)+ br.inputs["Color2"].default_value = (*b2, 1)+ br.inputs["Mortar"].default_value = (0.08, 0.075, 0.07, 1)+ nt.links.new(tc.outputs["Object"], br.inputs["Vector"])+ ch = nt.nodes.new("ShaderNodeTexChecker")+ ch.inputs["Scale"].default_value = 1 / tile / 2 * 2+ ch.inputs["Color1"].default_value = (*a, 1)+ ch.inputs["Color2"].default_value = (*b2, 1)+ nt.links.new(tc.outputs["Object"], ch.inputs["Vector"])+ base = _mix(nt, br.outputs["Fac"], ch.outputs["Color"], (0.08, 0.075, 0.07))+ n1 = _noise(nt, 0.8, 8, tc.outputs["Object"])+ g = _ramp(nt, n1.outputs["Fac"], [(0.4, (0, 0, 0)), (0.75, (1, 1, 1))])+ n2 = _noise(nt, 60, 3, tc.outputs["Object"])+ col = _mix(nt, g.outputs["Color"], base, (0.12, 0.1, 0.08), "MULTIPLY")+ col = _mix(nt, 0.15, col, n2.outputs["Color"], "OVERLAY")+ nt.links.new(col, b.inputs["Base Color"])+ mr = nt.nodes.new("ShaderNodeMapRange")+ mr.inputs["To Min"].default_value = 0.25+ mr.inputs["To Max"].default_value = 0.65+ nt.links.new(n1.outputs["Fac"], mr.inputs["Value"])+ nt.links.new(mr.outputs["Result"], b.inputs["Roughness"])+ nt.links.new(_bump(nt, br.outputs["Fac"], 0.3), b.inputs["Normal"])+ return m+++def wall_paint(name, base=(0.62, 0.6, 0.55)):+ """Painted plaster: low-frequency blotches, darker grime band towards the floor."""+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ tc = nt.nodes.new("ShaderNodeTexCoord")+ n1 = _noise(nt, 1.2, 8, tc.outputs["Object"])+ n2 = _noise(nt, 25, 6, tc.outputs["Object"])+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ nt.links.new(tc.outputs["Generated"], sep.inputs["Vector"])+ band = _ramp(nt, sep.outputs["Z"], [(0.0, (1, 1, 1)), (0.25, (0, 0, 0))])+ blot = _ramp(nt, n1.outputs["Fac"], [(0.45, (0, 0, 0)), (0.8, (0.6, 0.6, 0.6))])+ fac = _mix(nt, 1.0, band.outputs["Color"], blot.outputs["Color"], "LIGHTEN")+ col = _mix(nt, fac, base, (0.3, 0.27, 0.22))+ col = _mix(nt, 0.08, col, n2.outputs["Color"], "OVERLAY")+ nt.links.new(col, b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = 0.85+ nt.links.new(_bump(nt, n2.outputs["Fac"], 0.05), b.inputs["Normal"])+ return m+++def rain_glass(name):+ """Storefront glass with beaded drops and vertical run streaks (normal-only, transmission glass)."""+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (0.9, 0.95, 0.95, 1)+ b.inputs["Roughness"].default_value = 0.03+ b.inputs["Transmission Weight"].default_value = 1.0+ b.inputs["IOR"].default_value = 1.5+ tc = nt.nodes.new("ShaderNodeTexCoord")+ vo = nt.nodes.new("ShaderNodeTexVoronoi")+ vo.feature = "SMOOTH_F1"+ vo.inputs["Scale"].default_value = 55+ vo.inputs["Randomness"].default_value = 1.0+ nt.links.new(tc.outputs["Object"], vo.inputs["Vector"])+ drops = _ramp(nt, vo.outputs["Distance"], [(0.0, (1, 1, 1)), (0.18, (0, 0, 0))])+ mp = nt.nodes.new("ShaderNodeMapping")+ mp.inputs["Scale"].default_value = (60, 60, 1.2)+ nt.links.new(tc.outputs["Object"], mp.inputs["Vector"])+ st = _noise(nt, 1.0, 2, mp.outputs["Vector"])+ streak = _ramp(nt, st.outputs["Fac"], [(0.66, (0, 0, 0)), (0.7, (0.4, 0.4, 0.4))])+ mask = _noise(nt, 3, 2, tc.outputs["Object"])+ mk = _ramp(nt, mask.outputs["Fac"], [(0.4, (0, 0, 0)), (0.6, (1, 1, 1))])+ h = _mix(nt, 1.0, drops.outputs["Color"], streak.outputs["Color"], "LIGHTEN")+ h = _mix(nt, mk.outputs["Color"], (0.0, 0.0, 0.0), h)+ nt.links.new(_bump(nt, h, 0.5, 0.002), b.inputs["Normal"])+ return m+++def image_mat(name, path, rough=0.7, emission=0.0, alpha=False, extend="REPEAT"):+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ t = nt.nodes.new("ShaderNodeTexImage")+ t.image = bpy.data.images.load(path, check_existing=True)+ t.extension = extend+ nt.links.new(t.outputs["Color"], b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = rough+ if emission:+ nt.links.new(t.outputs["Color"], b.inputs["Emission Color"])+ b.inputs["Emission Strength"].default_value = emission+ if alpha:+ nt.links.new(t.outputs["Color"], b.inputs["Alpha"]) # white-on-black decals: luminance as alpha+ return m+++def emissive(name, color, strength):+ m, nt = _new(name)+ if nt is None:+ return m+ b = nt.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (*color, 1)+ b.inputs["Emission Color"].default_value = (*color, 1)+ b.inputs["Emission Strength"].default_value = strength+ return mdiff --git a/scenes/tokyo-electronics-repair/scripts/lights.py b/scenes/tokyo-electronics-repair/scripts/lights.pynew file mode 100644index 0000000..a043e8d--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/lights.py@@ -0,0 +1,208 @@+"""Night lighting, haze, render settings and compositor for the repair shop (the video's lighting + atmosphere steps).++blender -b <in.blend> --python scenes/tokyo-electronics-repair/scripts/lights.py -- <out.blend>+Idempotent: removes its own objects (collection "night_rig") before rebuilding.+"""+import math+import os+import sys++import bpy+from mathutils import Vector++out = os.path.abspath(sys.argv[sys.argv.index("--") + 1])+sc = bpy.context.scene+W, D, H = 4.2, 6.5, 2.7++old = bpy.data.collections.get("night_rig")+if old:+ for o in list(old.objects):+ bpy.data.objects.remove(o)+ bpy.data.collections.remove(old)+rig = bpy.data.collections.new("night_rig")+sc.collection.children.link(rig)+++def light(name, kind, loc, energy, color, target=None, **kw):+ d = bpy.data.lights.new(name, kind)+ d.energy = energy+ d.color = color+ for k, v in kw.items():+ setattr(d, k, v)+ o = bpy.data.objects.new(name, d)+ rig.objects.link(o)+ o.location = loc+ o.visible_camera = o.visible_glossy = o.visible_transmission = False # light, not a visible panel in the glass+ if target is not None:+ o.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()+ return o+++# --- world: almost black, a hint of blue so shadows are not dead+w = sc.world or bpy.data.worlds.new("night")+sc.world = w+bg = w.node_tree.nodes["Background"]+bg.inputs["Color"].default_value = (0.004, 0.006, 0.012, 1)+bg.inputs["Strength"].default_value = 1.0++# --- outside: cool street spill through the storefront + two neon accents (the backdrop plane also emits)+light("street_fill", "AREA", (W / 2, -1.6, 2.4), 70, (0.55, 0.68, 1.0), (W / 2, 3.0, 0.3), shape="RECTANGLE", size=4.5, size_y=1.6)+light("neon_magenta", "AREA", (3.4, -2.4, 2.8), 55, (1.0, 0.18, 0.5), (2.6, 2.5, 0.5), size=0.8)+light("neon_cyan", "AREA", (0.7, -2.8, 2.2), 40, (0.2, 0.85, 1.0), (1.2, 3.0, 0.8), size=0.6)+light("streetlamp", "SPOT", (1.0, -3.0, 4.2), 220, (0.75, 0.82, 1.0), (1.4, 2.0, 0.0), spot_size=math.radians(55), spot_blend=0.6, shadow_soft_size=0.15)++# the street backdrop stays visible through the glass and in reflections, but must not flood the room with diffuse light+bd = sc.objects.get("street_backdrop")+if bd:+ bd.visible_diffuse = False+ bd.visible_volume_scatter = False++# --- work lamp: warm spot from the shade, plus a tiny bulb glow. Follows the dressed lamp if present.+lamp = sc.objects.get("repair_work_lamp")+shade = Vector((0.42, 2.62, 1.38))+if lamp:+ # the generated shade is a closed mesh: put the spot just under its rim, found from the vertices at the arm end+ # which end is the shade: the x-extreme farthest from the clamp (the lowest vertices)+ vs = [lamp.matrix_world @ v.co for v in lamp.data.vertices]+ zmin = min(v.z for v in vs)+ clamp_x = sum(v.x for v in vs if v.z < zmin + 0.05) / max(1, sum(1 for v in vs if v.z < zmin + 0.05))+ lo_x, hi_x = min(v.x for v in vs), max(v.x for v in vs)+ end = lo_x if abs(lo_x - clamp_x) > abs(hi_x - clamp_x) else hi_x+ sh = [v for v in vs if abs(v.x - end) < 0.17 and v.z > zmin + 0.2]+ rim = min(v.z for v in sh)+ shade = Vector((sum(v.x for v in sh) / len(sh), sum(v.y for v in sh) / len(sh), rim - 0.012))+hh = sc.objects.get("helping_hands") # keep the pool on the helping hands and the board in its clips+target = (hh.matrix_world.translation + Vector((0.0, 0.0, 0.0))) if hh else Vector((shade.x - 0.08, shade.y - 0.1, 0.88))+target = Vector((target.x - 0.04, target.y - 0.06, 0.88))+light("lamp_spot", "SPOT", shade, 40, (1.0, 0.72, 0.45), target, spot_size=math.radians(75), spot_blend=0.55, shadow_soft_size=0.025)+light("lamp_bounce", "POINT", shade + Vector((0, 0, 0.04)), 1.5, (1.0, 0.7, 0.45), shadow_soft_size=0.03)++# --- warm under-shelf strip over the back of the bench (left on, low)+# (an under-shelf strip was tried here; it only made the pegboard a hot panel)++# --- oscilloscope glow (screen emission comes from the prop fix; this adds spill on the bench)+osc = sc.objects.get("oscilloscope")+if osc:+ fwd = osc.matrix_world.to_3x3() @ Vector((0, -1, 0))+ p = osc.matrix_world @ Vector((-0.06, -0.3, 0.11))+ sp = light("scope_spill", "AREA", p, 0.6, (0.35, 1.0, 0.55), p + fwd, size=0.12)+ sp.visible_volume_scatter = False++# --- round 2 practicals: they lift the racks and counter out of black with motivated light+def bbox(name):+ o = sc.objects.get(name)+ if not o:+ return None+ pts = [o.matrix_world @ Vector(c) 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, (lo + hi) / 2+++b = bbox("counter_lamp")+if b: # green banker lamp: warm pool on the counter + a faint glow on the shade+ lo, hi, ce = b+ p = Vector((ce.x, ce.y, hi.z - 0.05))+ light("counter_lamp_spot", "SPOT", p, 9, (1.0, 0.75, 0.45), (ce.x - 0.25, ce.y - 0.2, 0.95), spot_size=math.radians(110), spot_blend=0.8, shadow_soft_size=0.03)+ light("counter_lamp_fill", "POINT", p + Vector((0, 0, 0.03)), 1.2, (0.5, 1.0, 0.6), shadow_soft_size=0.05)+b = bbox("ring_lamp_led")+if b: # ring magnifier lamp at the second station: cool LED disc+ lo, hi, ce = b+ light("ring_lamp_light", "SPOT", ce - Vector((0, 0, 0.01)), 9, (0.85, 0.92, 1.0), (ce.x + 0.05, ce.y, 0.88), spot_size=math.radians(100), spot_blend=0.9, shadow_soft_size=0.06)+b = bbox("tube_on")+if b: # one fluorescent tube left on over the racks+ lo, hi, ce = b+ t = light("tube_racks_light", "AREA", ce - Vector((0, 0, 0.03)), 13, (0.8, 0.9, 1.0), (ce.x, ce.y, 0.0), shape="RECTANGLE", size=0.06, size_y=1.2)+b = bbox("rack_clip_bulb")+if b: # clip lamp on the racks: warm cone down the rack fronts and into the aisle+ lo, hi, ce = b+ light("rack_clip_spot", "SPOT", ce, 30, (1.0, 0.8, 0.55), (3.35, 3.3, 0.55), spot_size=math.radians(105), spot_blend=0.7, shadow_soft_size=0.03)+ light("rack_clip_glow", "POINT", ce + Vector((0.03, 0, 0.03)), 0.8, (1.0, 0.8, 0.55), shadow_soft_size=0.02)+# soft bounce: what the clip lamp and tube throw back off the floor and ceiling over the rack side of the room+bo = light("rack_bounce", "AREA", (3.2, 3.2, 2.55), 11, (0.95, 0.88, 0.8), (3.2, 3.2, 0.0), shape="RECTANGLE", size=1.6, size_y=3.8)+bo.visible_glossy = False+bo.data.use_shadow = True+# the counter lamp pool bounced off the floor onto the shop side of the counter+light("counter_bounce", "AREA", (2.7, 2.75, 0.35), 4, (1.0, 0.82, 0.62), (2.7, 1.9, 0.45), shape="RECTANGLE", size=1.4, size_y=0.4)+b = bbox("vending_panel") or bbox("vending_machine")+if b:+ lo, hi, ce = b+ if not sc.objects.get("vending_panel"): # generated machine: spill from its lit front (faces +Y)+ ce = Vector((ce.x, hi.y, ce.z + 0.2))+ light("vending_spill", "AREA", ce + Vector((0, 0.15, 0)), 20, (0.85, 0.92, 1.0), (ce.x + 0.5, 3.0, 0.5), size=0.9)+b = bbox("aframe_lamp") or bbox("aframe_1")+if b:+ light("aframe_glow", "POINT", b[2] + Vector((0, 0.1, 0)), 8, (1.0, 0.7, 0.4), shadow_soft_size=0.05)+for o in sc.objects:+ if o.name.startswith("rain_"):+ o.visible_volume_scatter = False++# --- haze: one volume box over the interior+fog = bpy.data.meshes.new("haze")+import bmesh # noqa: E402++bm = bmesh.new()+bmesh.ops.create_cube(bm, size=1)+bm.to_mesh(fog)+bm.free()+fo = bpy.data.objects.new("haze", fog)+rig.objects.link(fo)+fo.location = (W / 2, D / 2 + 0.02, H / 2)+fo.scale = (W - 0.02, D - 0.06, H - 0.02)+fm = bpy.data.materials.get("haze_vol") or bpy.data.materials.new("haze_vol")+nt = fm.node_tree+for n in list(nt.nodes):+ if n.type != "OUTPUT_MATERIAL":+ nt.nodes.remove(n)+pv = nt.nodes.new("ShaderNodeVolumePrincipled")+pv.inputs["Density"].default_value = 0.018+pv.inputs["Anisotropy"].default_value = 0.35+pv.inputs["Color"].default_value = (0.85, 0.88, 0.9, 1)+nt.links.new(pv.outputs["Volume"], nt.nodes["Material Output"].inputs["Volume"])+fo.data.materials.append(fm)+fo.visible_shadow = True++# --- render settings+sc.render.engine = "CYCLES"+c = sc.cycles+c.samples = 256+c.device = "GPU"+c.use_denoising = True+c.denoiser = "OPTIX"+c.volume_step_rate = 4.0+c.max_bounces = 8+c.caustics_reflective = False+c.caustics_refractive = False+c.blur_glossy = 1.0+sc.view_settings.view_transform = "AgX"+sc.view_settings.look = "AgX - Medium High Contrast"+sc.view_settings.exposure = 0.95 # +0.5 EV over the first round-2 pass: racks and floor must read+sc.render.resolution_x, sc.render.resolution_y = 1920, 1080+sc.render.use_motion_blur = True+sc.render.motion_blur_shutter = 0.5+sc.render.fps = 24++# --- compositor: bloom on practicals + lens distortion with a little dispersion (grade/vignette/grain in ffmpeg)+ng = bpy.data.node_groups.get("repair_comp") or bpy.data.node_groups.new("repair_comp", "CompositorNodeTree")+for n in list(ng.nodes):+ ng.nodes.remove(n)+if not ng.interface.items_tree:+ ng.interface.new_socket("Image", in_out="OUTPUT", socket_type="NodeSocketColor")+rl = ng.nodes.new("CompositorNodeRLayers")+gl = ng.nodes.new("CompositorNodeGlare")+gl.inputs["Type"].default_value = "Bloom"+gl.inputs["Threshold"].default_value = 0.9+gl.inputs["Strength"].default_value = 0.35+gl.inputs["Size"].default_value = 0.6+ld = ng.nodes.new("CompositorNodeLensdist")+ld.inputs["Distortion"].default_value = -0.012+ld.inputs["Dispersion"].default_value = 0.008+go = ng.nodes.new("NodeGroupOutput")+ng.links.new(rl.outputs["Image"], gl.inputs["Image"])+ng.links.new(gl.outputs["Image"], ld.inputs["Image"])+ng.links.new(ld.outputs["Image"], go.inputs[0])+sc.compositing_node_group = ng+sc.render.use_compositing = True++bpy.ops.wm.save_as_mainfile(filepath=out)+print("lit ->", out)diff --git a/scenes/tokyo-electronics-repair/scripts/prep.py b/scenes/tokyo-electronics-repair/scripts/prep.pynew file mode 100644index 0000000..e9d43e1--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/prep.py@@ -0,0 +1,111 @@+"""Prep picked generated props into a library .blend (the video's "generated + refined" step).++blender -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/prep.py -- [id ...]+Reads scenes/tokyo-electronics-repair/assets.json + picks.json. For each pick: import GLB, join, turn so the front faces -Y,+scale to the manifest size, origin at bottom centre, decimate, downscale textures to <= 2K, save+scenes/tokyo-electronics-repair/props/<id>.blend (one collection named after the id, ready to link/append).+"""+import json+import math+import os+import sys++import bpy+from mathutils import Matrix, Vector++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+SCN = os.path.join(ROOT, "scenes", "tokyo-electronics-repair")+FRONT_YAW = {"tripo-h31": 90, "meshy": 0} # where the generator's front points (deg from -Y), see out/compare/yaw.json+MAX_TEX = 2048++man = {a["id"]: a for a in json.load(open(os.path.join(SCN, "assets.json")))["generate"]}+picks = json.load(open(os.path.join(SCN, "picks.json")))+only = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+++def tri_budget(a):+ # heroes on the bench close-up keep more detail; big background props less; tiny props least+ if a.get("hero"):+ return 200_000+ return 120_000 if a["size"] >= 0.3 else 50_000+++def prep(pid):+ a, pick = man[pid], picks[pid]+ model = pick["model"]+ glb = os.path.join(ROOT, "assets", "gen", model, pid, "model.glb")+ bpy.ops.wm.read_factory_settings(use_empty=True)+ bpy.ops.import_scene.gltf(filepath=glb)+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]+ for o in bpy.data.objects:+ o.select_set(o.type == "MESH")+ bpy.context.view_layer.objects.active = meshes[0]+ if len(meshes) > 1:+ bpy.ops.object.join()+ ob = bpy.context.view_layer.objects.active+ ob.parent = None+ ob.matrix_world = ob.matrix_world.copy()+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)+ for o in [o for o in bpy.data.objects if o is not ob]:+ bpy.data.objects.remove(o)+ # turn front to -Y, plus any per-pick extra yaw+ yaw = -math.radians(FRONT_YAW[model] + pick.get("yaw", 0))+ ob.data.transform(Matrix.Rotation(yaw, 4, "Z"))+ # scale + bottom-centre origin+ 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)))+ dims = hi - lo+ s = a["size"] / (dims.z if a["fit"] == "h" else max(dims))+ ob.data.transform(Matrix.Translation(-Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))))+ ob.data.transform(Matrix.Scale(s, 4))+ ob.location = (0, 0, 0)+ # decimate+ tris = sum(len(p.vertices) - 2 for p in ob.data.polygons)+ budget = tri_budget(a)+ if tris > budget:+ m = ob.modifiers.new("dec", "DECIMATE")+ m.ratio = budget / tris+ bpy.ops.object.modifier_apply(modifier="dec")+ for p in ob.data.polygons:+ p.use_smooth = True+ # textures <= 2K, saved next to the library file+ texdir = os.path.join(SCN, "props", "tex")+ os.makedirs(texdir, exist_ok=True)+ for i, img in enumerate(bpy.data.images):+ if img.size[0] == 0:+ continue+ if max(img.size) > MAX_TEX:+ f = MAX_TEX / max(img.size)+ img.scale(int(img.size[0] * f), int(img.size[1] * f))+ path = os.path.join(texdir, f"{pid}_{i}_{img.name.split('_')[0][:12]}.png")+ img.filepath_raw = path+ img.file_format = "PNG"+ img.save()+ img.filepath = path+ ob.name = pid+ mat_names = []+ for i, slot in enumerate(ob.material_slots):+ if slot.material:+ slot.material.name = f"{pid}_mat{i}"+ mat_names.append(slot.material.name)+ coll = bpy.data.collections.new(pid)+ bpy.context.scene.collection.children.link(coll)+ for c in ob.users_collection:+ c.objects.unlink(ob)+ coll.objects.link(ob)+ ob["source_model"] = model+ ob["tris"] = sum(len(p.vertices) - 2 for p in ob.data.polygons)+ out = os.path.join(SCN, "props", f"{pid}.blend")+ bpy.ops.wm.save_as_mainfile(filepath=out)+ d = ob.dimensions+ print(f"PREP {pid} {model} tris {tris}->{ob['tris']} dims {d.x:.2f}x{d.y:.2f}x{d.z:.2f}")+++for pid in picks:+ if only and pid not in only:+ continue+ try:+ prep(pid)+ except Exception as e:+ print("PREP FAILED", pid, repr(e))diff --git a/scenes/tokyo-electronics-repair/scripts/preview.py b/scenes/tokyo-electronics-repair/scripts/preview.pynew file mode 100644index 0000000..4ff8829--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/preview.py@@ -0,0 +1,57 @@+"""Render preview stills of a repair .blend from named cameras.++blender -b <file.blend> --python scenes/tokyo-electronics-repair/scripts/preview.py -- <out_dir> <cam1,cam2> [samples=32] [pct=50] [clay] [tag]+Run through pipeline/gpu_run.sh.+"""+import os+import sys++import bpy++args = sys.argv[sys.argv.index("--") + 1:]+out, cams = os.path.abspath(args[0]), args[1].split(",")+samples = int(args[2]) if len(args) > 2 else 32+pct = int(args[3]) if len(args) > 3 else 50+clay = len(args) > 4 and args[4] == "clay"+tag = args[5] if len(args) > 5 else ""++sc = bpy.context.scene+sc.render.engine = "CYCLES"+prefs = bpy.context.preferences.addons["cycles"].preferences+prefs.compute_device_type = "OPTIX"+prefs.get_devices()+for d in prefs.devices:+ d.use = d.type == "OPTIX"+sc.cycles.device = "GPU"+sc.cycles.samples = samples+sc.cycles.use_denoising = True+sc.render.resolution_x, sc.render.resolution_y = 1920, 1080+sc.render.resolution_percentage = pct+if clay:+ m = bpy.data.materials.new("clay_override")+ m.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.6, 0.6, 0.6, 1)+ sc.view_layers[0].material_override = m+ if sc.world is None or not sc.world.node_tree:+ w = bpy.data.worlds.new("clayworld")+ sc.world = w+ bg = sc.world.node_tree.nodes.get("Background")+ if bg:+ bg.inputs["Strength"].default_value = 1.0+ sc.view_settings.view_transform = "AgX"+ # light the clay with a sun so the shell reads even without the night rig+ if not bpy.data.objects.get("clay_fill"):+ ld = bpy.data.lights.new("clay_fill", "AREA")+ ld.shape = "RECTANGLE"+ ld.size, ld.size_y, ld.energy = 3.5, 5.5, 380+ o = bpy.data.objects.new("clay_fill", ld)+ sc.collection.objects.link(o)+ o.location = (2.1, 3.3, 2.55)+ for l in [x for x in bpy.data.objects if x.type == "LIGHT" and x is not o]:+ l.hide_render = True+ sc.render.use_compositing = False+os.makedirs(out, exist_ok=True)+for c in cams:+ sc.camera = bpy.data.objects[c]+ sc.render.filepath = os.path.join(out, f"{c}{'_clay' if clay else ''}{tag}.png")+ bpy.ops.render.render(write_still=True)+ print("wrote", sc.render.filepath)diff --git a/scenes/tokyo-electronics-repair/scripts/rebuild.sh b/scenes/tokyo-electronics-repair/scripts/rebuild.shnew file mode 100644index 0000000..295f96d--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/rebuild.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# shell -> dress (pass) -> validate -> lights. Usage: scenes/tokyo-electronics-repair/scripts/rebuild.sh [pass=3]+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++"$B" -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/build_shell.py 2>&1 | grep -E "Error|Traceback"+"$B" -b scenes/tokyo-electronics-repair/repair_shell.blend --python scenes/tokyo-electronics-repair/scripts/dress.py -- ${1:-3} 2>&1 | grep -E "MISSING|Error|Traceback"+"$B" -b scenes/tokyo-electronics-repair/repair_dressed.blend --python scenes/tokyo-electronics-repair/scripts/validate.py 2>&1 | grep -E "^(FLOAT|CLIP|OUT|SCALE|VALIDATE)|Error|Traceback"+"$B" -b scenes/tokyo-electronics-repair/repair_dressed.blend --python scenes/tokyo-electronics-repair/scripts/lights.py -- scenes/tokyo-electronics-repair/repair_lit.blend 2>&1 | grep -E "Error|Traceback"+"$B" -b scenes/tokyo-electronics-repair/repair_lit.blend --python scenes/tokyo-electronics-repair/scripts/cameras.py -- scenes/tokyo-electronics-repair/repair_final.blend 2>&1 | grep -E "Error|Traceback"+exit 0diff --git a/scenes/tokyo-electronics-repair/scripts/rebuild2.sh b/scenes/tokyo-electronics-repair/scripts/rebuild2.shnew file mode 100644index 0000000..4264a07--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/rebuild2.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash+# Round 2 build: shell -> dress (round-1 layout, pass 4) -> validate -> dress2 <A|B|C> -> grime -> lights -> cameras.+# scenes/tokyo-electronics-repair/scripts/rebuild2.sh C -> scenes/tokyo-electronics-repair/repair_final.blend+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++P=${1:-C}+"$B" -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/build_shell.py 2>&1 | grep -E "Error|Traceback"+"$B" -b scenes/tokyo-electronics-repair/repair_shell.blend --python scenes/tokyo-electronics-repair/scripts/dress.py -- 4 2>&1 | grep -E "MISSING|Error|Traceback"+"$B" -b scenes/tokyo-electronics-repair/repair_dressed.blend --python scenes/tokyo-electronics-repair/scripts/validate.py 2>&1 | grep -E "^(FLOAT|CLIP|OUT|SCALE|FURNITURE|VALIDATE)|Error|Traceback"+"$B" -b scenes/tokyo-electronics-repair/repair_dressed.blend --python scenes/tokyo-electronics-repair/scripts/dress2.py -- $P scenes/tokyo-electronics-repair/repair_dressed2.blend 2>&1 | grep -E "dress2 pass|Error|Traceback|line [0-9]+"+"$B" -b scenes/tokyo-electronics-repair/repair_dressed2.blend --python scenes/tokyo-electronics-repair/scripts/validate.py 2>&1 | grep -E "^(FLOAT|CLIP|OUT|SCALE|FURNITURE|VALIDATE)" | sed "s/^/dress2: /"+"$B" -b scenes/tokyo-electronics-repair/repair_dressed2.blend --python scenes/tokyo-electronics-repair/scripts/grime.py -- scenes/tokyo-electronics-repair/repair_grimed.blend 2>&1 | grep -E "grime on|Error|Traceback|line [0-9]+"+"$B" -b scenes/tokyo-electronics-repair/repair_grimed.blend --python scenes/tokyo-electronics-repair/scripts/lights.py -- scenes/tokyo-electronics-repair/repair_lit.blend 2>&1 | grep -E "Error|Traceback|line [0-9]+"+"$B" -b scenes/tokyo-electronics-repair/repair_lit.blend --python scenes/tokyo-electronics-repair/scripts/cameras.py -- scenes/tokyo-electronics-repair/repair_final.blend 2>&1 | grep -E "Error|Traceback|line [0-9]+"+exit 0diff --git a/scenes/tokyo-electronics-repair/scripts/refs.mjs b/scenes/tokyo-electronics-repair/scripts/refs.mjsnew file mode 100644index 0000000..2c100b3--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/refs.mjs@@ -0,0 +1,12 @@+// Generate missing GPT Image 2.5 Sunburst refs for the repair manifest, 10 at a time.+import { execFile } from 'node:child_process';+import { existsSync, readFileSync } from 'node:fs';+const REF = 'No real-world brand names or logos. Product reference photograph for 3D scanning. The entire object fully visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft even diffuse studio lighting, no harsh shadows, no other objects, no hands, realistic used and worn condition, sharp focus, true-to-life materials.';+const man = JSON.parse(readFileSync('scenes/tokyo-electronics-repair/assets.json', 'utf8'));+const jobs = man.generate.filter((a) => a.prompt !== 'existing' && !existsSync(`refs/tokyo-electronics-repair/props/${a.id}.json`))+ .map((a) => ['--variant', 'sunburst', '--quality', 'high', '--size', 'square_hd', '--out', `refs/tokyo-electronics-repair/props/${a.id}`, '--prompt', `${a.prompt} ${REF}`]);+const extra = JSON.parse(process.argv[2] ?? '[]');+for (const e of extra) if (!existsSync(`${e.out}.json`)) jobs.push(['--variant', 'sunburst', '--quality', 'high', '--size', e.size, '--out', e.out, '--prompt', e.prompt]);+const run = (args) => new Promise((res) => execFile('node', ['generate/fal.mjs', 'image', ...args], { maxBuffer: 1e7 }, (err, out, errout) => { console.log(err ? `FAIL ${args.at(-3)} ${errout.slice(-300)}` : out.trim().split('\n').at(-1)); res(); }));+let i = 0;+await Promise.all(Array.from({ length: 10 }, async () => { while (i < jobs.length) await run(jobs[i++]); }));diff --git a/scenes/tokyo-electronics-repair/scripts/render_clip.sh b/scenes/tokyo-electronics-repair/scripts/render_clip.shnew file mode 100644index 0000000..c936945--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/render_clip.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+# Render the handheld clip in 20-frame chunks, each holding the GPU lock only for its chunk, then grade + encode.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++for s in 1 21 41 61 81 101; do+ t0=$(date +%s)+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-electronics-repair/repair_final.blend --python scenes/tokyo-electronics-repair/scripts/render_frames.py -- $s $((s + 19)) ${1:-64} 100 2>&1 | grep -E "Error|Traceback"+ echo "chunk $s done in $(( $(date +%s) - t0 )) s"+ sleep 8 # let a waiting render from the other scene take the lock+done+bash scenes/tokyo-electronics-repair/scripts/grade.sh clip scenes/tokyo-electronics-repair/out/clip_frames scenes/tokyo-electronics-repair/out/clip.mp4 && echo "clip encoded"diff --git a/scenes/tokyo-electronics-repair/scripts/render_finals.sh b/scenes/tokyo-electronics-repair/scripts/render_finals.shnew file mode 100644index 0000000..196ff5d--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/render_finals.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# Final Cycles renders for round 2, back to back through the GPU queue, after the ramen scene is done+# (waits for .gpu.ramen_done, or 16:30 local time at the latest).+cd "$(dirname "$0")/../../.."+. pipeline/env.sh+until [ -e .gpu.ramen_done ] || [ "$(date +%H%M)" -ge 1630 ]; do sleep 60; done+echo "start $(date +%H:%M) (ramen_done: $([ -e .gpu.ramen_done ] && echo yes || echo no, 16:30 fallback))"++for cam in cam_wide cam_bench; do+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-electronics-repair/repair_final.blend --python scenes/tokyo-electronics-repair/scripts/preview.py -- scenes/tokyo-electronics-repair/out/raw $cam 384 100 full 2>&1 | grep -E "Traceback|wrote"+ bash scenes/tokyo-electronics-repair/scripts/grade.sh still scenes/tokyo-electronics-repair/out/raw/$cam.png scenes/tokyo-electronics-repair/out/hero_${cam#cam_}.png+done+echo "heroes done $(date +%H:%M)"+for s in s3_bench_rack_100 s4_scope_135_push s6_bench_dolly_zoom s2_shop_wide_drift s1_street_establish; do+ rm -rf scenes/tokyo-electronics-repair/out/shots/$s/frames scenes/tokyo-electronics-repair/out/shots/$s/$s.mp4 scenes/tokyo-electronics-repair/out/shots/$s/contact.png scenes/tokyo-electronics-repair/out/shots/${s}_graded.mp4+done+SHOTS="s3_bench_rack_100 s4_scope_135_push s6_bench_dolly_zoom s2_shop_wide_drift s1_street_establish" bash scenes/tokyo-electronics-repair/scripts/render_round2.sh+echo "finals done $(date +%H:%M)"diff --git a/scenes/tokyo-electronics-repair/scripts/render_frames.py b/scenes/tokyo-electronics-repair/scripts/render_frames.pynew file mode 100644index 0000000..713a173--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/render_frames.py@@ -0,0 +1,37 @@+"""Render a frame range of the handheld clip (run in chunks through pipeline/gpu_run.sh so the GPU is shared).++blender -b scenes/tokyo-electronics-repair/repair_final.blend --python scenes/tokyo-electronics-repair/scripts/render_frames.py -- <first> <last> [samples=96] [pct=100]+-> scenes/tokyo-electronics-repair/out/clip_frames/f####.png (existing frames are skipped)+"""+import os+import sys++import bpy++a = sys.argv[sys.argv.index("--") + 1:]+first, last = int(a[0]), int(a[1])+samples = int(a[2]) if len(a) > 2 else 96+pct = int(a[3]) if len(a) > 3 else 100+out = r"$ROOT_ABS\scenes\repair\out\clip_frames"+os.makedirs(out, exist_ok=True)+sc = bpy.context.scene+prefs = bpy.context.preferences.addons["cycles"].preferences+prefs.compute_device_type = "OPTIX"+prefs.get_devices()+for d in prefs.devices:+ d.use = d.type == "OPTIX"+sc.cycles.device = "GPU"+sc.cycles.samples = samples+sc.cycles.use_adaptive_sampling = True+sc.cycles.adaptive_threshold = 0.02+sc.render.resolution_percentage = pct+sc.camera = bpy.data.objects["cam_handheld"]+sc.render.use_persistent_data = True # keep BVH + textures between frames+for f in range(first, last + 1):+ path = os.path.join(out, f"f{f:04d}.png")+ if os.path.exists(path):+ continue+ sc.frame_set(f)+ sc.render.filepath = path+ bpy.ops.render.render(write_still=True)+ print("frame", f, flush=True)diff --git a/scenes/tokyo-electronics-repair/scripts/render_round2.sh b/scenes/tokyo-electronics-repair/scripts/render_round2.shnew file mode 100644index 0000000..a9e4506--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/render_round2.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+# Round 2 finals: hero stills, then every shot in 48-frame GPU chunks (~7 min) (resumable), then a graded mp4 per shot.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++if false; then # heroes rendered already; set to true to redo+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-electronics-repair/repair_final.blend --python scenes/tokyo-electronics-repair/scripts/preview.py -- scenes/tokyo-electronics-repair/out/raw cam_wide 384 100 full 2>&1 | grep -E "Traceback|wrote"+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-electronics-repair/repair_final.blend --python scenes/tokyo-electronics-repair/scripts/preview.py -- scenes/tokyo-electronics-repair/out/raw cam_bench 384 100 full 2>&1 | grep -E "Traceback|wrote"+ bash scenes/tokyo-electronics-repair/scripts/grade.sh still scenes/tokyo-electronics-repair/out/raw/cam_wide.png scenes/tokyo-electronics-repair/out/hero_wide.png+ bash scenes/tokyo-electronics-repair/scripts/grade.sh still scenes/tokyo-electronics-repair/out/raw/cam_bench.png scenes/tokyo-electronics-repair/out/hero_bench.png+ echo "heroes done"+fi+GRADE="curves=r='0/0.03 0.25/0.235 0.6/0.63 1/0.98':g='0/0.035 0.25/0.25 0.6/0.62 1/0.97':b='0/0.055 0.25/0.28 0.6/0.61 1/0.94',hue=s=0.88,vignette=angle=PI/4.6,noise=alls=6:allf=t+u,format=yuv420p"+for shot in ${SHOTS:-s3_bench_rack_100 s4_scope_135_push s6_bench_dolly_zoom s2_shop_wide_drift s5_counter_push s7_rack_tv_85 s1_street_establish}; do+ n=$(node -e "const j=require('./scenes/tokyo-electronics-repair/shots.json');console.log(j.shots.find(s=>s.name==='$shot').frames)")+ t0=$(date +%s)+ for a in $(seq 1 48 $n); do+ b=$((a + 47)); [ $b -gt $n ] && b=$n+ BLEND=${BLEND:-} bash scenes/tokyo-electronics-repair/scripts/shoot.sh --only $shot --frames $a-$b 2>&1 | grep -E "Traceback|Error:" | grep -v HIPEW+ done+ "$FF" -v error -y -framerate 24 -i scenes/tokyo-electronics-repair/out/shots/$shot/frames/%04d.png -vf "$GRADE" -c:v h264_nvenc -preset p7 -rc vbr -cq 18 -b:v 0 -movflags +faststart scenes/tokyo-electronics-repair/out/shots/${shot}_graded.mp4+ echo "$shot done ($n frames) in $(( ($(date +%s) - t0) / 60 )) min"+donediff --git a/scenes/tokyo-electronics-repair/scripts/round2_manifest.mjs b/scenes/tokyo-electronics-repair/scripts/round2_manifest.mjsnew file mode 100644index 0000000..4ca8a3a--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/round2_manifest.mjs@@ -0,0 +1,80 @@+// Round 2: append debranded replacements (*_nb) and pass A / pass B props to scenes/tokyo-electronics-repair/assets.json.+import { readFileSync, writeFileSync } from 'node:fs';+const P = 'scenes/tokyo-electronics-repair/assets.json';+const man = JSON.parse(readFileSync(P, 'utf8'));+const have = new Set(man.generate.map((a) => a.id));+const orig = Object.fromEntries(man.generate.map((a) => [a.id, a]));+const promptOf = (id) => orig[id].prompt === 'existing'+ ? JSON.parse(readFileSync(`refs/props/${id}.json`, 'utf8')).input.prompt.split(' Product reference')[0]+ : orig[id].prompt;+const NB = {+ oscilloscope: 'KOSEI', solder_station: 'HANDA-YA', boombox_open: 'SONICA', repair_multimeter_yellow: 'VOLTEK', repair_multimeter_red: 'VOLTEK',+ repair_bench_psu: 'DENKO', repair_tool_chest: 'IRONSIDE', repair_spray_cans: 'none', repair_cup_noodle: 'none', repair_boxes_b: 'none',+ repair_vcr_open: 'MIRAVISION', repair_tissue_box: 'none', repair_rice_cooker: 'HARUKA', repair_vintage_radio: 'AOZORA', repair_receiver: 'SOUNDHILL',+ repair_solder_junk: 'none', repair_laptop_broken: 'none', repair_crt_stack: 'none', repair_crt_tv: 'MIRAVISION', repair_turntable: 'SOUNDHILL',+ repair_desk_fan: 'KAZEMARU', repair_kerosene_heater: 'none',+};+const add = (a) => { if (!have.has(a.id)) { man.generate.push(a); have.add(a.id); } };+for (const [id, brand] of Object.entries(NB)) {+ const nb = id.startsWith('repair_') ? `${id}_nb` : `repair_${id}_nb`;+ const tag = brand === 'none'+ ? 'All printing and labels are generic or plain, with no real-world brand names, product names or logos.'+ : `The only brand name visible is the fictional brand "${brand}"; no real-world brand names, model names or logos anywhere.`;+ add({ id: nb, replaces: id, fit: orig[id].fit, size: orig[id].size, hero: orig[id].hero, pass: 'nb', models: ['tripo-h31', 'meshy'], prompt: `${promptOf(id)} ${tag}` });+}+const A = [+ ['repair_cassette_deck', 'max', 0.43, 'A 1980s black stereo cassette tape deck with a single tape door, VU meters and piano-key transport buttons, dusty.'],+ ['repair_amp_black', 'max', 0.43, 'A black 1990s integrated stereo amplifier with a large volume knob, small input selector knobs and a row of push buttons, scratched top.'],+ ['repair_crt_monitor_beige', 'h', 0.38, 'A beige 1990s computer CRT monitor with a deep back, curved dark screen, small tilt-swivel base, yellowed plastic, a paper repair tag taped to the side.'],+ ['repair_portable_tv', 'h', 0.24, 'A small 1980s portable black-and-white TV with a carry handle, telescopic antenna folded down and a small round speaker grille, red plastic case.'],+ ['repair_tv_wood', 'h', 0.45, 'A 1970s CRT television in a wood-grain cabinet with a rounded screen, two rotary channel dials on the right and four short legs.'],+ ['repair_speaker_pair', 'h', 0.4, 'A pair of small vintage bookshelf speakers in walnut veneer cabinets, one with its grille cloth removed showing the woofer and tweeter.'],+ ['repair_camcorder', 'max', 0.3, 'A 1990s VHS-C camcorder with a shoulder pad, side viewfinder and a cracked lens hood, black and grey plastic.'],+ ['repair_microwave', 'max', 0.5, 'A small white household microwave oven with a dial timer and a dirty glass door, a paper repair ticket taped to the door.'],+ ['repair_pc_tower', 'h', 0.42, 'A yellowed beige 1990s PC tower computer with a floppy drive and CD drive bay, side panel removed showing the motherboard and cables.'],+ ['repair_dotmatrix_printer', 'max', 0.45, 'A beige dot-matrix printer with tractor-feed perforated paper coming out the top, dusty, lid slightly open.'],+ ['repair_fax_phone', 'max', 0.32, 'A beige 1990s home fax telephone with a corded handset, a keypad and thermal paper roll slot.'],+ ['repair_radio_cassette', 'max', 0.35, 'A small silver radio cassette player with a carry handle, one round speaker, a tuning dial and a cassette door, worn.'],+ ['repair_karaoke_machine', 'h', 0.4, 'A home karaoke machine: a black box with two microphone inputs, a small built-in screen, colourful buttons, with a wired microphone resting on top.'],+ ['repair_electric_kettle', 'h', 0.25, 'A white electric hot-water pot dispenser with a push-button top and a cord, Japanese style, slightly stained.'],+ ['repair_job_bin', 'max', 0.45, 'A blue plastic storage bin holding a disassembled DVD player, loose screws in a sandwich bag and a paper repair ticket clipped to the rim.'],+ ['repair_cable_crate', 'max', 0.45, 'A black plastic milk crate overflowing with tangled power cords, AV cables, AC adapters and remote controls.'],+ ['repair_parts_bins', 'h', 0.45, 'A stack of small blue and red plastic stackable parts bins with open fronts, filled with screws, knobs and small components, handwritten labels.'],+ ['repair_parts_cart', 'h', 0.85, 'A grey steel three-tier rolling utility cart loaded with a disassembled stereo, a box of parts, cables and a coffee cup, on casters, worn.'],+ ['repair_hot_air_station', 'max', 0.3, 'A hot-air rework station: a grey control box with two digital displays and knobs, the hot-air gun resting in its holder with a coiled hose.'],+ ['repair_magnifier_lamp', 'h', 0.55, 'A white ring-light magnifier lamp on a heavy desk base with a spring arm, the round lens head tilted down, scuffed.'],+ ['repair_pcb_vise', 'max', 0.22, 'A small PCB holder vise on a weighted base clamping a green circuit board with components partly desoldered.'],+ ['repair_fume_extractor', 'h', 0.25, 'A small black desktop solder fume extractor fan with a square carbon filter on the front, on a tilting stand.'],+ ['repair_cash_register', 'max', 0.4, 'A small old electronic cash register with a cash drawer, a receipt printer, rows of keys and a small green display, plain, no brand.'],+ ['repair_desk_phone', 'max', 0.22, 'A beige office desk telephone with a coiled cord handset and a large-key keypad, yellowed.'],+ ['repair_counter_lamp', 'h', 0.42, 'A small green-shaded metal desk lamp with a weighted round base and a pull chain, worn paint.'],+ ['repair_display_case', 'max', 0.7, 'A small countertop glass display showcase with a wooden frame and sliding back doors, holding used portable cassette players, old mobile phones and calculators with price tags.'],+ ['repair_calculator', 'max', 0.17, 'A grey desktop printing calculator with a paper roll and large keys, tape curling out.'],+ ['repair_umbrella_stand', 'h', 0.7, 'A metal umbrella stand by a shop door holding three wet transparent plastic umbrellas and one black umbrella, water pooled at the base.'],+ ['repair_shop_vac', 'h', 0.55, 'A small grey wet-dry shop vacuum with a coiled hose wrapped around it, dusty.'],+ ['repair_step_stool', 'h', 0.5, 'A small aluminium two-step folding step ladder, open, paint drips on the steps.'],+ ['repair_floor_fan', 'h', 0.9, 'A tall cream-coloured pedestal electric fan with a round metal cage, standing, the cord coiled at the base.'],+ ['repair_storage_boxes_flat', 'max', 0.6, 'A stack of four flat cardboard boxes of different sizes tied with plastic string, labelled in marker, slightly crushed corners.'],+];+for (const [id, fit, size, prompt] of A) add({ id, fit, size, pass: 'A', models: ['tripo-h31', 'meshy'], prompt: `${prompt} No real-world brand names or logos.` });+const B = [+ ['repair_pcbs_loose', 'max', 0.25, 'A small pile of four loose salvaged green and brown circuit boards with components, one with burnt marks.'],+ ['repair_screw_jar', 'h', 0.11, 'A glass jar with a dented metal lid full of assorted screws, nuts and washers.'],+ ['repair_screwdriver_case', 'max', 0.24, 'An open plastic case with a precision screwdriver set and interchangeable bits, a few bits missing.'],+ ['repair_tweezers', 'max', 0.14, 'Three stainless steel precision tweezers of different tip shapes lying side by side.'],+ ['repair_ashtray', 'max', 0.14, 'A round glass ashtray with several crushed cigarette butts and ash.'],+ ['repair_tape_rolls', 'max', 0.14, 'A roll of black electrical tape, a roll of yellow kapton tape and a half-used roll of masking tape stacked loosely.'],+ ['repair_receipts', 'max', 0.22, 'A messy pile of small paper receipts and handwritten repair slips held with a black binder clip.'],+ ['repair_cable_bundle', 'max', 0.35, 'A loosely coiled bundle of black power cords tied with a red twist tie, lying on a table.'],+ ['repair_canned_coffee', 'h', 0.12, 'Two empty steel canned-coffee drink cans, one crushed, plain dark brown labels with no logos.'],+ ['repair_desolder_pump', 'max', 0.2, 'A blue and silver spring-loaded desoldering pump with a white tip.'],+ ['repair_flux_bottles', 'h', 0.11, 'Two small plastic flux dispenser bottles with needle tips and a jar of rosin flux paste, generic labels.'],+ ['repair_component_bag', 'max', 0.15, 'A small zip-lock plastic bag of electrolytic capacitors and resistors with a handwritten paper label.'],+ ['repair_ribbon_cables', 'max', 0.3, 'A few grey flat ribbon cables with black connectors, loosely folded.'],+ ['repair_extension_block', 'max', 0.32, 'A white power strip extension block with six sockets, several plugs inserted, cord coiled, dirty.'],+ ['repair_sticky_notes', 'max', 0.09, 'A pad of yellow sticky notes with handwriting on the top note and a ballpoint pen.'],+ ['repair_remote_controls', 'max', 0.22, 'Three old TV and VCR remote controls of different sizes lying together, one with its battery cover missing.'],+];+for (const [id, fit, size, prompt] of B) add({ id, fit, size, pass: 'B', models: ['tripo-p2', 'meshy'], prompt: `${prompt} No real-world brand names or logos.` });+writeFileSync(P, JSON.stringify(man, null, 1));+console.log(man.generate.length, 'props in manifest;', man.generate.filter((a) => a.pass).length, 'round-2');diff --git a/scenes/tokyo-electronics-repair/scripts/sheet.sh b/scenes/tokyo-electronics-repair/scripts/sheet.shnew file mode 100644index 0000000..c5e4053--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/sheet.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+# Review sheet: one row per prop = ref | H3.1 front | Meshy front | H3.1 back | Meshy back | H3.1 clay | Meshy clay.+# scenes/tokyo-electronics-repair/scripts/sheet.sh <out.png> <id> [id ...] (up to 4 ids)+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++out=$1; shift+img() { # compare render for a model/prop/view: repair renders first, then the original head-to-head+ local f="scenes/tokyo-electronics-repair/compare/$1/$2_$3.png"+ [ -f "$f" ] || f="out/compare/$1/$2_$3.png"+ [ -f "$f" ] || f="scenes/tokyo-electronics-repair/compare/missing.png"+ echo "$f"+}+[ -f scenes/tokyo-electronics-repair/compare/missing.png ] || "$FF" -v error -f lavfi -i color=c=black:s=300x300 -frames:v 1 scenes/tokyo-electronics-repair/compare/missing.png+args=(); f=""; rows=""; n=0; r=0+for id in "$@"; do+ ref="refs/tokyo-electronics-repair/props/${id}_0.png"; [ -f "$ref" ] || ref="refs/props/${id}_0.png"+ tiles=("$ref" "$(img tripo-h31 $id beauty)" "$(img meshy $id beauty)" "$(img tripo-h31 $id back)" "$(img meshy $id back)" "$(img tripo-h31 $id clay)" "$(img meshy $id clay)")+ row=""+ for t in "${tiles[@]}"; do args+=(-i "$t"); f+="[$n]scale=300:300[s$n];"; row+="[s$n]"; n=$((n+1)); done+ f+="${row}hstack=7[r$r];"; rows+="[r$r]"; r=$((r+1))+done+if [ $r -gt 1 ]; then f+="${rows}vstack=$r"; else f="${f%;}"; f="${f%\[r0\]}"; fi+"$FF" -v error -y "${args[@]}" -filter_complex "$f" "$out"diff --git a/scenes/tokyo-electronics-repair/scripts/shoot.sh b/scenes/tokyo-electronics-repair/scripts/shoot.shnew file mode 100644index 0000000..fe086f8--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/shoot.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+# camrig through the GPU queue with OptiX enabled. scenes/tokyo-electronics-repair/scripts/shoot.sh [shoot.py args...]+cd "$(dirname "$0")/../../.."+. pipeline/env.sh+bash pipeline/gpu_run.sh "$B" -b ${BLEND:-scenes/tokyo-electronics-repair/repair_final.blend} \+ --python scenes/tokyo-electronics-repair/scripts/gpu_prefs.py --python camera/shoot.py -- \+ --shots $ROOT_ABS/scenes/tokyo-electronics-repair/shots.json \+ --out $ROOT_ABS/scenes/tokyo-electronics-repair/out/shots "$@"diff --git a/scenes/tokyo-electronics-repair/scripts/validate.py b/scenes/tokyo-electronics-repair/scripts/validate.pynew file mode 100644index 0000000..c498c4c--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/validate.py@@ -0,0 +1,104 @@+"""Placement validator for the dressed repair shop (the video's self-correcting check).++blender -b scenes/tokyo-electronics-repair/repair_dressed.blend --python scenes/tokyo-electronics-repair/scripts/validate.py+Flags: FLOAT (bottom > 1 cm above the support under it), CLIP (two props interpenetrating by more than a sliver),+OUT (outside the room box), SCALE (dimensions off the manifest by > 25 %). Exit summary line: "VALIDATE n issues".+"""+import json+import os++import bpy+from mathutils import Vector+from mathutils.bvhtree import BVHTree++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+SCN = os.path.join(ROOT, "scenes", "tokyo-electronics-repair")+W, D, H = 4.2, 6.5, 2.7+man = {a["id"]: a for a in json.load(open(os.path.join(SCN, "assets.json")))["generate"]}+sc = bpy.context.scene+dg = bpy.context.evaluated_depsgraph_get()+props = [o for o in sc.objects if o.get("placed") and o.visible_get()]+issues = []+++def world_bb(o):+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]+ return Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))), Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))+++for o in props:+ lo, hi = world_bb(o)+ # OUT+ if lo.x < -0.02 or lo.y < -0.02 or hi.x > W + 0.02 or hi.y > D + 0.02 or hi.z > H + 0.01:+ issues.append(f"OUT {o.name} bb {tuple(round(v, 2) for v in lo)}..{tuple(round(v, 2) for v in hi)}")+ # FLOAT: cast down from just below the prop's lowest point+ if not o.get("wall"):+ # cast from just above the prop bottom with the prop moved out of the way (a thin top would be entered from below)+ z0 = o.location.z+ o.location.z = -100+ bpy.context.view_layer.update()+ dg2 = bpy.context.evaluated_depsgraph_get()+ hit, loc, n, i, ob, m = sc.ray_cast(dg2, Vector((o.location.x, o.location.y, lo.z + 0.02)), Vector((0, 0, -1)))+ o.location.z = z0+ bpy.context.view_layer.update()+ gap = (lo.z - loc.z) if hit else lo.z+ if gap > 0.01:+ issues.append(f"FLOAT {o.name} {gap * 100:.1f} cm above {ob.name if hit else 'nothing'}")+ # SCALE+ a = man.get(o.get("prop_id"))+ if a and not o.get("scaled"):+ d = o.dimensions+ got = d.z if a["fit"] == "h" else max(d)+ if abs(got / a["size"] - 1) > 0.25:+ issues.append(f"SCALE {o.name} {got:.2f} m vs {a['size']} m")++# CLIP: BVH overlap between props whose boxes intersect+trees = {}+for o in props:+ eo = o.evaluated_get(dg)+ me = eo.to_mesh()+ me.transform(o.matrix_world)+ trees[o.name] = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])+ eo.to_mesh_clear()+names = list(trees)+boxes = {o.name: world_bb(o) for o in props}+for i, a_ in enumerate(names):+ for b_ in names[i + 1:]:+ (alo, ahi), (blo, bhi) = boxes[a_], boxes[b_]+ if any(ahi[k] < blo[k] or bhi[k] < alo[k] for k in range(3)):+ continue+ pairs = trees[a_].overlap(trees[b_])+ if len(pairs) > 40:+ issues.append(f"CLIP {a_} x {b_} ({len(pairs)} tri pairs)")++# FURNITURE: real mesh intersection (BVH overlap of evaluated triangles) between every placed prop and the fixed+# furniture/shell. The prop mesh is lifted 3 mm so resting flush on its support is not a hit; anything poking into a+# shelf, cabinet, bench, rack or wall by more than that is.+FURN_COLLS = ("shell", "bench", "drawers", "shelving", "storefront", "counter", "ceiling")+furn = [o for o in sc.objects if o.type == "MESH" and o.visible_get() and any(c.name in FURN_COLLS for c in o.users_collection)+ and not o.name.startswith(("floor", "backroom", "pavement", "street", "glass", "door_leaf", "decal"))]+ftrees = {}+for f in furn:+ ef = f.evaluated_get(dg)+ me = ef.to_mesh()+ me.transform(f.matrix_world)+ ftrees[f.name] = (BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons]), world_bb(f))+ ef.to_mesh_clear()+from mathutils import Matrix # noqa: E402+for o in props:+ eo = o.evaluated_get(dg)+ me = eo.to_mesh()+ me.transform(Matrix.Translation((0, 0, 0.003)) @ o.matrix_world)+ t = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])+ eo.to_mesh_clear()+ alo, ahi = boxes[o.name]+ for fname, (ft, (blo, bhi)) in ftrees.items():+ if any(ahi[k] < blo[k] or bhi[k] < alo[k] for k in range(3)):+ continue+ pairs = t.overlap(ft)+ if len(pairs) > 20:+ issues.append(f"FURNITURE {o.name} x {fname} ({len(pairs)} tri pairs)")++for s in issues:+ print(s)+print(f"VALIDATE {len(issues)} issues over {len(props)} props")diff --git a/scenes/tokyo-electronics-repair/scripts/views.py b/scenes/tokyo-electronics-repair/scripts/views.pynew file mode 100644index 0000000..e596c45--- /dev/null+++ b/scenes/tokyo-electronics-repair/scripts/views.py@@ -0,0 +1,68 @@+"""Orthographic, bbox-fitted views of prepped props, used to locate brand marks for debranding.++blender -b --factory-startup --python scenes/tokyo-electronics-repair/scripts/views.py -- <id,id,...> [views=front,right,left,top,back]+-> scenes/tokyo-electronics-repair/debrand/<id>_<view>.png (512 px square). The image spans the prop's bbox in that view, centred:+pixel (0,0) top-left. debrand.py maps rectangles given in these images' normalised coordinates back to texels.+"""+import math+import os+import sys++import bpy+from mathutils import Vector++ROOT = os.environ.get("ANYSCENE_ROOT") or os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+PROPS = os.path.join(ROOT, "scenes", "tokyo-electronics-repair", "props")+OUT = os.environ.get("VIEWS_OUT", os.path.join(ROOT, "scenes", "tokyo-electronics-repair", "debrand"))++# view -> (camera direction it looks along, horizontal world axis, vertical world axis)+VIEWS = {+ "front": (Vector((0, 1, 0)), Vector((1, 0, 0)), Vector((0, 0, 1))),+ "back": (Vector((0, -1, 0)), Vector((-1, 0, 0)), Vector((0, 0, 1))),+ "right": (Vector((-1, 0, 0)), Vector((0, 1, 0)), Vector((0, 0, 1))),+ "left": (Vector((1, 0, 0)), Vector((0, -1, 0)), Vector((0, 0, 1))),+ "top": (Vector((0, 0, -1)), Vector((1, 0, 0)), Vector((0, 1, 0))),+}+++def frame(ob, view):+ d, h, v = VIEWS[view]+ pts = [ob.matrix_world @ Vector(c) for c in ob.bound_box]+ hs = [p.dot(h) for p in pts]+ vs = [p.dot(v) for p in pts]+ c = sum(pts, Vector()) / 8+ span = max(max(hs) - min(hs), max(vs) - min(vs)) * 1.02+ return c, span, d, h, v+++if __name__ == "__main__":+ a = sys.argv[sys.argv.index("--") + 1:]+ ids = a[0].split(",")+ views = a[1].split(",") if len(a) > 1 else ["front", "right", "left", "top", "back"]+ os.makedirs(OUT, exist_ok=True)+ for pid in ids:+ bpy.ops.wm.open_mainfile(filepath=os.path.join(PROPS, f"{pid}.blend"))+ sc = bpy.context.scene+ ob = bpy.data.objects[pid]+ sc.render.engine = "BLENDER_EEVEE"+ sc.render.resolution_x = sc.render.resolution_y = 512+ sc.view_settings.view_transform = "Standard"+ w = bpy.data.worlds.new("w")+ sc.world = w+ w.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.6+ cd = bpy.data.cameras.new("c")+ cd.type = "ORTHO"+ cam = bpy.data.objects.new("c", cd)+ sc.collection.objects.link(cam)+ sc.camera = cam+ for view in views:+ c, span, d, h, v = frame(ob, view)+ cam.location = c - d * 5+ cam.rotation_euler = d.to_track_quat("-Z", "Y" if view != "top" else "Y").to_euler()+ if view == "top":+ cam.rotation_euler = (0, 0, 0)+ cd.ortho_scale = span+ cd.clip_end = 20+ sc.render.filepath = os.path.join(OUT, f"{pid}_{view}.png")+ bpy.ops.render.render(write_still=True)+ print("VIEWS", pid)diff --git a/scenes/tokyo-electronics-repair/shots.json b/scenes/tokyo-electronics-repair/shots.jsonnew file mode 100644index 0000000..09a9874--- /dev/null+++ b/scenes/tokyo-electronics-repair/shots.json@@ -0,0 +1,521 @@+{+ "defaults": {+ "fps": 24,+ "frames": 96,+ "res": [+ 1920,+ 1080+ ],+ "aspect": "2.39",+ "samples": 96,+ "shutter": 180,+ "sensor": "s35",+ "fstop": 2.8,+ "ease": "inout",+ "handheld": 0+ },+ "shots": [+ {+ "name": "s1_street_establish",+ "move": "push_in",+ "frames": 72,+ "handheld": 0.2,+ "fstop": 2.8,+ "keys": [+ {+ "t": 0,+ "pos": [+ 1.7,+ -3.95,+ 1.55+ ],+ "aim": [+ 1.6,+ 1.8,+ 1.05+ ],+ "lens": 18+ },+ {+ "t": 1,+ "pos": [+ 1.75,+ -3.1,+ 1.5+ ],+ "aim": [+ 1.3,+ 2.2,+ 1+ ]+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "obj": "aframe_"+ },+ {+ "t": 0.3,+ "obj": "aframe_"+ },+ {+ "t": 0.85,+ "obj": "counter_lamp"+ }+ ]+ },+ "samples": 56+ },+ {+ "name": "s2_shop_wide_drift",+ "move": "truck",+ "frames": 72,+ "handheld": 0.25,+ "fstop": 4,+ "keys": [+ {+ "t": 0,+ "pos": [+ 3.5,+ 6.1,+ 1.55+ ],+ "aim": [+ 1.1,+ 1.3,+ 0.95+ ],+ "lens": 20+ },+ {+ "t": 1,+ "pos": [+ 2.75,+ 6.05,+ 1.5+ ],+ "aim": [+ 0.75,+ 1.6,+ 0.95+ ]+ }+ ],+ "focus": {+ "mode": "point",+ "pos": [+ 1.2,+ 2.8,+ 1+ ]+ },+ "samples": 56+ },+ {+ "name": "s3_bench_rack_100",+ "move": "static",+ "frames": 96,+ "handheld": 0.35,+ "fstop": 2,+ "blades": 7,+ "keys": [+ {+ "t": 0,+ "pos": [+ 1.25,+ 3.55,+ 1.08+ ],+ "aim": [+ 0.34,+ 2.2,+ 1+ ],+ "lens": 100+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "obj": "helping_hands"+ },+ {+ "t": 0.3,+ "obj": "helping_hands"+ },+ {+ "t": 0.7,+ "obj": "oscilloscope"+ }+ ]+ },+ "samples": 64+ },+ {+ "name": "s4_scope_135_push",+ "move": "push_in",+ "frames": 72,+ "handheld": 0.3,+ "fstop": 2.8,+ "keys": [+ {+ "t": 0,+ "pos": [+ 1.55,+ 2.95,+ 1.12+ ],+ "aim_obj": "oscilloscope",+ "aim_offset": [+ -0.03,+ -0.05,+ 0.03+ ],+ "lens": 135+ },+ {+ "t": 1,+ "pos": [+ 1.35,+ 2.83,+ 1.1+ ],+ "aim_obj": "oscilloscope",+ "aim_offset": [+ -0.03,+ -0.05,+ 0.03+ ]+ }+ ],+ "focus": {+ "mode": "point",+ "pos": [+ 0.46,+ 2.25,+ 1+ ]+ },+ "samples": 64+ },+ {+ "name": "s5_counter_push",+ "move": "push_in",+ "frames": 72,+ "handheld": 0.2,+ "fstop": 2.4,+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.75,+ 3.65,+ 1.4+ ],+ "aim_obj": "cash_register",+ "aim_offset": [+ -0.45,+ 0,+ 0.08+ ],+ "lens": 35+ },+ {+ "t": 1,+ "pos": [+ 2.8,+ 3.05,+ 1.3+ ],+ "aim_obj": "display_case",+ "aim_offset": [+ 0.25,+ 0,+ 0.02+ ]+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "obj": "counter_laptop"+ },+ {+ "t": 0.45,+ "obj": "counter_laptop"+ },+ {+ "t": 0.85,+ "obj": "display_case"+ }+ ]+ },+ "samples": 56+ },+ {+ "name": "s6_bench_dolly_zoom",+ "move": "dolly_zoom",+ "frames": 72,+ "fstop": 2.8,+ "handheld": 0.1,+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.3,+ 2.75,+ 1.25+ ],+ "aim_obj": "helping_hands",+ "lens": 85+ },+ {+ "t": 1,+ "pos": [+ 1.05,+ 2.72,+ 1.12+ ]+ }+ ],+ "subject": "helping_hands",+ "focus": {+ "mode": "track",+ "obj": "helping_hands"+ },+ "samples": 56+ },+ {+ "name": "s7_rack_tv_85",+ "move": "truck",+ "frames": 72,+ "handheld": 0.3,+ "fstop": 2,+ "blades": 0,+ "samples": 64,+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.7,+ 1.85,+ 1.5+ ],+ "aim_obj": "fill_crt_2",+ "aim_offset": [+ 0,+ 0.28,+ -0.02+ ],+ "lens": 50+ },+ {+ "t": 1,+ "pos": [+ 2.7,+ 2.1,+ 1.48+ ],+ "aim_obj": "fill_crt_2",+ "aim_offset": [+ 0,+ 0.22,+ -0.02+ ]+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "pos": [+ 3.73,+ 2.4,+ 1.42+ ]+ },+ {+ "t": 0.35,+ "pos": [+ 3.73,+ 2.4,+ 1.42+ ]+ },+ {+ "t": 0.75,+ "obj": "fill_crt_2"+ }+ ]+ }+ },+ {+ "name": "h1_back_to_bench",+ "move": "path",+ "frames": 216,+ "fstop": 3.2,+ "samples": 56,+ "ease": "inout",+ "handheld": {+ "profile": "walk",+ "amount": 1+ },+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.05,+ 5.3,+ 1.6+ ],+ "aim": [+ 1.6,+ 1.6,+ 1.2+ ],+ "lens": 26+ },+ {+ "t": 0.4,+ "pos": [+ 1.95,+ 4.2,+ 1.56+ ],+ "aim": [+ 2.7,+ 2.9,+ 1.15+ ]+ },+ {+ "t": 0.72,+ "pos": [+ 1.55,+ 3.35,+ 1.45+ ],+ "aim": [+ 0.7,+ 2.5,+ 1.02+ ]+ },+ {+ "t": 1,+ "pos": [+ 1.18,+ 2.98,+ 1.3+ ],+ "aim": [+ 0.42,+ 2.45,+ 0.98+ ]+ }+ ]+ },+ {+ "name": "h2_shop_walkaround",+ "move": "path",+ "frames": 312,+ "fstop": 3.2,+ "samples": 56,+ "ease": "inout",+ "handheld": {+ "profile": "walk",+ "amount": 1+ },+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.05,+ 0.62,+ 1.6+ ],+ "aim": [+ 3.75,+ 2.6,+ 1.3+ ],+ "lens": 24+ },+ {+ "t": 0.2,+ "pos": [+ 1.82,+ 1.05,+ 1.6+ ],+ "aim": [+ 3.75,+ 3.6,+ 1.2+ ]+ },+ {+ "t": 0.42,+ "pos": [+ 1.15,+ 1.3,+ 1.6+ ],+ "aim": [+ 3.1,+ 2,+ 1.3+ ]+ },+ {+ "t": 0.6,+ "pos": [+ 1.2,+ 2.4,+ 1.56+ ],+ "aim": [+ 2.75,+ 1.95,+ 1.38+ ]+ },+ {+ "t": 0.8,+ "pos": [+ 1.5,+ 3.35,+ 1.5+ ],+ "aim": [+ 0.55,+ 3.3,+ 1+ ]+ },+ {+ "t": 1,+ "pos": [+ 1.42,+ 3.75,+ 1.42+ ],+ "aim": [+ 0.5,+ 2.95,+ 0.98+ ]+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/scenes/tokyo-ramen-shop/NOTES.md b/scenes/tokyo-ramen-shop/NOTES.mdnew file mode 100644index 0000000..0d77a87--- /dev/null+++ b/scenes/tokyo-ramen-shop/NOTES.md@@ -0,0 +1,78 @@+# Ramen shop — notes++Pipeline: `assets.json` → `gen.mjs` (GPT Image 2.5 Sunburst refs + Tripo H3.1 and Meshy 7.1 for every prop)+→ `scenes/tokyo-ramen-shop/scripts/compare.py` + `review.sh` (ref | H3.1 | Meshy, front/back/clay) → `picks.json`+→ `scenes/tokyo-ramen-shop/scripts/prep.py` (→ `lib/<id>.blend`) → `scenes/tokyo-ramen-shop/scripts/build.py` (shell, dress + validate, light, post, cameras, mirror)+→ `scenes/tokyo-ramen-shop/scripts/render.py` (stills, clip chunks) → `finish.sh` (ffmpeg grade, vignette, grain, NVENC).++Rebuild and render:+```++bash pipeline/gpu_run.sh "$B" -b --factory-startup --python scenes/tokyo-ramen-shop/scripts/build.py -- --samples 256 --save --final+bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen.blend --python scenes/tokyo-ramen-shop/scripts/render.py -- stills wide,counter --samples 384+bash scenes/tokyo-ramen-shop/scripts/render_clip.sh+```+Previews: `build.py -- --preview wide,counter,kitchen,door,top [--clay] --samples 32 --tag _x` → `out/prev/`.++## Gotchas+- **matrix_world is stale** on objects created in the same script until `view_layer.update()`; the mirror pass read identity matrices and threw the whole room away.+- **Mirror without mirroring text**: layout is authored counter-on-left, then every top-level transform is conjugated `M @ mw @ F` (x-flip) so positions reflect but objects stay proper rotations; printed labels still read. Camera animation is created *after* the mirror (keyframes aren't conjugated).+- **glTF import uses quaternion rotation mode**: `rotation_euler` is silently ignored, both in prep (rotate mesh data instead) and when dressing (set `rotation_mode = "XYZ"`).+- **glTF images arrive already packed**; calling `img.pack()` again on an unmodified one (empty filepath) silently drops its data → magenta props. Only repack images you resized.+- Tripo H3.1 fronts face +X, Meshy -Y; prep turns Tripo by -90° so every prop's front is -Y.+- Generators invent depth: boxy appliances (ticket machine, fridge, boiler, gas range) get per-axis `dims` in the manifest.+- Drop-to-surface rays must start *below* the hood/shelves (default 1.3 m), or kitchen props land on top of the hood.+- Area lights shine along local -Z: `rot x +90` → +Y, `rot y -90` → +X. Two fills were pointing out of the shop.+- Hidden fill lights still show **through rough glass** unless `visible_transmission = False` too (door panes went white).+- Brick texture is 2D (ignores object Z) → use UVs on walls facing X.+- Compositor (5.0 node group): only glare + lens distortion/CA kept in Blender; an ellipse-mask vignette and colour balance produced a quarter-frame / blue-tint domain bug, so grade/vignette/grain live in `finish.sh`.+- CapCut's ffmpeg has no `eq`, `drawtext`, glob input or libx264 → `curves`/`hue` and `h264_nvenc`.+- `render.resolution_percentage` must be set to 100 explicitly (factory-empty scenes default lower).+- Validator: "floating ticket_machine 12 cm" is its raised plinth; "gas_range x stockpot" is pots seated on the burner grates (decimated meshes interpenetrate a few mm). Both accepted.+- fal: two Tripo jobs failed transiently in a 12-wide pool; a plain retry worked.++## Round 2 (densify, grime, steam, exterior, camrig shots)+Build is now `build.py` stages `shell,dress,passA,passB,passC,grime,steam,light,post`, saved to `ramen_r2.blend`;+`scenes/tokyo-ramen-shop/scripts/rebuild.sh` = build (CPU) → `bake_steam.py` (CPU, cache in `cache/r2/`) → optional GPU preview.+Process sheets per pass: `scenes/tokyo-ramen-shop/scripts/process_r2.sh` → `out/process/r2_<pass>.png` (wide + counter, lit / clay).+Shots: `shots.json` (world = post-mirror coordinates) rendered with `camera/shoot.py` → `out/shots/<shot>/`.++- **fal balance ran out** at the start of round 2 (403 "User is locked … Exhausted balance"). `round2.json` holds the+ 47 Pass A/B/C prop prompts + 16 decal/flyer/neon textures, merged into `assets.json`; `gen_retry.sh` retries every 10 min.+ Meanwhile pass A reuses/varies the round-1 picks and passes B/C are direct-modelled (paper + real Yu Gothic text objects).+- **Mirror conjugation moves origins, not vertices.** Anything built with world-space vertices and origin at 0 (noren+ panels, curves for conduit/cables/noodles) was shifted +W instead of mirrored. `mirror_x` now recentres such origins first.+- **Mantaflow `surface_distance` is effectively in cells**: 0.012 emitted only from discs wide enough to contain cell+ centres (pots yes, the bowl never). Use ~1.0. Also keep emitters well inside the domain (border cells are walls).+- `bpy.ops.fluid.free_all()` is an async job in background mode: called before `bake_all()` it ran *after* the bake and+ deleted the new cache. Clear the cache folder with `shutil.rmtree` instead.+- Negative cache frames work (`cache_frame_start = -70`): shots render frames 1..N with fully developed plumes.+- Cache paths are saved relative (`//cache/...`): copying a .blend elsewhere points it at a different cache.+- Particle `rotation_mode = "VEL"` aligns the instance's +X with velocity: lay rain-drop geometry along X.+- A SimpleDeform-bent towel exploded into a floating sheet; replaced with the hand-towel prop on the pass.+- Killing a stray background Blender was refused by the sandbox classifier; work around by writing to a new .blend+ name and cache folder rather than racing the orphan.+- **`blender -b file.blend` renders on the CPU**: Cycles device prefs are user preferences, not saved in the .blend.+ Every render from a saved file now runs `--python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py` first (OptiX). Round 1's final stills and+ clip were CPU renders (that is why they took ~9 min / ~37 s per frame); round 2's first shot chunk ran at ~8 min/frame+ for the same reason before this was caught.+- **Object motion blur on Mantaflow domains = ~290 s of Cycles sync per frame** (velocity motion built from the noise+ grids); render itself was 7 s. `emitters.no_volume_blur()` turns object blur off on the domains only (camera blur stays).+ Found by bisecting with tiny CPU renders (sync is CPU-side, so no GPU lock needed).+- Texture-driven emission on dense generated meshes made every triangle a light (545k-emitter light tree);+ `emitters.run()` sets `material.cycles.emission_sampling = "NONE"` (5.0 moved it under `.cycles`) on heavy meshes.++## Round 2b: generated props swapped in (after the fal key was replaced)+- `r2gen.py` runs post-mirror in world coordinates, so the same code patches the steam-baked `ramen_r2.blend`+ (caches untouched; backup `ramen_r2_pre_gen.blend`) and runs at the end of `build.py` (stage `r2gen`).+ `dress.place(..., MIRROR=True)` converts design coordinates (x→W−x, facing→−facing, x± walls swapped).+- `dress.pass_a2` replaces the 34 reused round-1 instances with round-2 picks (`pick(id, fallback)`); `pass_bc_gen`+ swaps generated tongs/coins/tape/power strip/cat dish/hook items/vending machine for the direct-modelled ones.+- **Brands:** several references came back with real brands (Kirkland, McCormick, Ajinomoto, Nissin, Asahi, Marlboro,+ Kirin, Sharpie, 7-Eleven, Rinnai, CHNT, FamilyMart, PayPay, Hanshin, a known anime character). Those got `_nb`+ regenerations with fictional Japanese brands (`add_nb.mjs`); `dress.BRANDED` makes the branded originals unplaceable.+ Gyoza griddle (Rinnai) and junction box (CHNT) were left out instead. Round-1 assets still carry brands+ (Kirin crate/fridge, Sapporo poster, Kikkoman/mirin bottles, rice-cooker/register logos) — not yet de-branded.+- Meshy 7.1 took ~10 min per job; 15 jobs timed out in fal.mjs. Five placed props are Tripo-only for that reason.+- Running two gen.mjs passes at once double-submits in-flight jobs (existence is checked at start): avoid.+- Decals: generated on flat black/white backgrounds, alpha keyed from luminance (`m_decal`), stuck with raycasts.diff --git a/scenes/tokyo-ramen-shop/assets.json b/scenes/tokyo-ramen-shop/assets.jsonnew file mode 100644index 0000000..0a1c86b--- /dev/null+++ b/scenes/tokyo-ramen-shop/assets.json@@ -0,0 +1,671 @@+{+ "room": {+ "width_x": 3.6,+ "depth_y": 7,+ "height_z": 2.6,+ "note": "Street/door at y=0 (front). Counter runs along y on the customer side, kitchen behind it along the right wall (x high)."+ },+ "generate": [+ {+ "id": "stockpot",+ "h": 0.42,+ "prompt": "existing"+ },+ {+ "id": "ticket_machine",+ "h": 1.55,+ "prompt": "existing",+ "dims": [+ 0.62,+ 0.46,+ 1.5+ ]+ },+ {+ "id": "condiment_caddy",+ "h": 0.17,+ "prompt": "existing"+ },+ {+ "id": "lantern",+ "h": 0.62,+ "prompt": "existing"+ },+ {+ "id": "ramen_gas_range",+ "h": 0.45,+ "prompt": "A low commercial stainless-steel gas range for ramen stock, about 45 cm tall, with two big cast-iron burner rings on top, front control knobs, grease-stained and heat-discoloured.",+ "dims": [+ 1.05,+ 0.6,+ 0.45+ ]+ },+ {+ "id": "ramen_noodle_boiler",+ "h": 0.9,+ "prompt": "A commercial ramen noodle boiler (yudemenki): a stainless-steel cabinet with a square boiling well on top holding six tebo noodle strainer baskets with long handles, control panel and knobs on the front, water stains and scale.",+ "dims": [+ 0.6,+ 0.62,+ 0.9+ ]+ },+ {+ "id": "ramen_ladle_rail",+ "m": 0.75,+ "prompt": "A stainless-steel wall rail with S-hooks holding a row of hanging kitchen tools: three ladles of different sizes, two mesh strainers, a skimmer and long chopsticks, worn and slightly greasy."+ },+ {+ "id": "ramen_bowl_stack",+ "h": 0.32,+ "prompt": "A tall stack of about eight identical white ceramic ramen bowls with a red raimon (thunder spiral) border pattern around the rim, slightly chipped."+ },+ {+ "id": "ramen_bowl_unfinished",+ "m": 0.24,+ "prompt": "A half-eaten bowl of shoyu ramen in a white bowl with red raimon rim pattern: cloudy brown broth, a few noodles, a slice of chashu and green onion bits left, a pair of wooden disposable chopsticks resting across the rim, a plastic ramen spoon in the bowl."+ },+ {+ "id": "ramen_chopstick_cup",+ "h": 0.2,+ "prompt": "A dark lacquered wooden cylindrical holder packed with about forty wooden disposable chopsticks (waribashi) standing upright."+ },+ {+ "id": "ramen_water_glass",+ "h": 0.1,+ "prompt": "A simple clear glass tumbler half full of water with a few condensation droplets, standard Japanese restaurant water glass."+ },+ {+ "id": "ramen_water_pitcher",+ "h": 0.24,+ "prompt": "A stainless-steel water pitcher with a hinged lid and handle, as used in Japanese restaurants, with water spots and fingerprints."+ },+ {+ "id": "ramen_stool",+ "h": 0.62,+ "prompt": "A round bar stool from an old ramen shop: a thick cushioned seat covered in cracked black vinyl, on a single chrome pedestal with a round footrest ring and heavy round base, worn."+ },+ {+ "id": "ramen_cutting_board",+ "m": 0.45,+ "prompt": "A worn white plastic cutting board with knife scratches and stains, a pile of finely chopped green onions and a kitchen knife on it, a few whole green onions beside."+ },+ {+ "id": "ramen_tare_containers",+ "m": 0.42,+ "prompt": "A cluster of five stainless-steel round food containers of different sizes holding ramen toppings: menma bamboo shoots, sliced chashu pork, nori sheets, soft-boiled marinated eggs, and dark shoyu tare, with tongs."+ },+ {+ "id": "ramen_rice_cooker",+ "h": 0.38,+ "prompt": "A large commercial electric rice cooker and warmer, white and stainless steel with a big domed lid and a handle, slightly yellowed, rice paddle clipped to the side."+ },+ {+ "id": "ramen_beer_crate",+ "h": 0.34,+ "prompt": "A yellow plastic Japanese beer crate holding large brown beer bottles, a few empty slots, scuffed plastic."+ },+ {+ "id": "ramen_drink_fridge",+ "h": 1.8,+ "prompt": "A narrow single-door glass-front drink refrigerator from a small Japanese restaurant, white body with a backlit header panel, shelves stocked with beer bottles, cola and oolong tea, fingerprints on the glass.",+ "dims": [+ 0.6,+ 0.62,+ 1.8+ ]+ },+ {+ "id": "ramen_maneki_neko",+ "h": 0.26,+ "prompt": "A white ceramic maneki-neko beckoning cat with a red collar and gold bell, raised left paw, holding a gold koban coin, slightly dusty."+ },+ {+ "id": "ramen_cash_register",+ "h": 0.3,+ "prompt": "An old beige electronic cash register with a small display, chunky keys, a receipt printer and a cash drawer, scuffed and yellowed."+ },+ {+ "id": "ramen_crt_tv_bracket",+ "m": 0.5,+ "prompt": "A small old 14-inch CRT television mounted on a black metal ceiling/wall bracket arm, grey plastic casing, dark screen, dusty."+ },+ {+ "id": "ramen_wall_fan",+ "h": 0.45,+ "prompt": "A wall-mounted oscillating electric fan with a white plastic grille and blades and a pull cord, slightly yellowed and dusty, shown with its wall bracket."+ },+ {+ "id": "ramen_umbrella_stand",+ "h": 0.75,+ "prompt": "A simple square stainless-steel umbrella stand holding three clear plastic vinyl umbrellas and one black umbrella, droplets of water."+ },+ {+ "id": "ramen_noodle_crates",+ "h": 0.45,+ "prompt": "A stack of three shallow wooden noodle boxes (menbako) from a noodle maker, with printed red and black Japanese lettering on the sides, the top box holding bundles of fresh ramen noodles dusted with flour."+ },+ {+ "id": "ramen_square_cans",+ "h": 0.36,+ "prompt": "Two 18-litre square metal cans (itto-kan) side by side, one with a printed label for frying oil, the other plain with a dented corner, worn and greasy."+ },+ {+ "id": "ramen_dish_rack",+ "m": 0.5,+ "prompt": "A stainless-steel wire dish drying rack holding several white ramen bowls upside down and a few small plates, water drops."+ },+ {+ "id": "ramen_apron_hook",+ "h": 0.85,+ "prompt": "A dark navy cotton work apron hanging from a single wall hook, wrinkled and slightly stained, with long ties hanging down."+ },+ {+ "id": "ramen_hand_towel",+ "m": 0.35,+ "prompt": "A loosely folded white cotton kitchen hand towel (tenugui) with faint stains, lying on a flat surface."+ },+ {+ "id": "ramen_tissue_box",+ "m": 0.25,+ "prompt": "A box of tissues inside a dark wooden tissue box cover, with a tissue pulled up out of the slot."+ },+ {+ "id": "ramen_trash_bin",+ "h": 0.45,+ "prompt": "A grey plastic kitchen trash bin with a swing lid, scuffed."+ },+ {+ "id": "ramen_soy_bottles",+ "h": 0.3,+ "prompt": "Three large plastic bottles of commercial soy sauce and mirin with Japanese labels and red caps, as kept in a ramen kitchen."+ },+ {+ "id": "ramen_kettle_pot",+ "h": 0.3,+ "prompt": "A dented aluminium yukihira saucepan and a large stainless kettle side by side, used and stained."+ },+ {+ "pass": "A",+ "id": "ramen_stockpot_tall",+ "h": 0.55,+ "prompt": "A tall dented aluminium commercial stockpot for tonkotsu broth, no lid, blackened scorched bottom and heat-stained sides, dried broth drips down the outside, heavy riveted handles."+ },+ {+ "pass": "A",+ "id": "ramen_stockpot_small",+ "h": 0.3,+ "prompt": "A small dented stainless steel stockpot with a battered lid slightly ajar, scorched base, greasy fingerprints, riveted handles."+ },+ {+ "pass": "A",+ "id": "ramen_colander",+ "m": 0.42,+ "prompt": "A large perforated stainless steel colander with two handles, water spots and scratches, sitting upright."+ },+ {+ "pass": "A",+ "id": "ramen_chashu_tray",+ "m": 0.45,+ "prompt": "A stainless steel hotel pan tray holding four rolled and tied braised chashu pork belly logs glistening in dark soy braising liquid, kitchen twine, a few slices cut."+ },+ {+ "pass": "A",+ "id": "ramen_egg_container",+ "m": 0.3,+ "prompt": "A square clear plastic food container half filled with dark soy-marinated soft-boiled ramen eggs (ajitama) in brown marinade, lid off beside it."+ },+ {+ "pass": "A",+ "id": "ramen_cleaver_board",+ "m": 0.5,+ "prompt": "A thick worn round wooden chopping block with deep knife scars and stains, a heavy Chinese cleaver lying on it, a few sliced chashu pieces."+ },+ {+ "pass": "A",+ "id": "ramen_plate_stack",+ "h": 0.14,+ "prompt": "Two stacks of small oval white gyoza plates with a thin blue line rim, slightly chipped, side by side."+ },+ {+ "pass": "A",+ "id": "ramen_flour_sacks",+ "h": 0.55,+ "prompt": "Two heavy brown paper 25 kg flour sacks for noodles leaning against each other, printed Japanese brand lettering, flour dust, slumped and folded tops."+ },+ {+ "pass": "A",+ "id": "ramen_cardboard_boxes",+ "h": 0.6,+ "prompt": "A stack of three worn cardboard supply boxes with printed Japanese food supplier logos, one open with packets visible, tape peeling, slightly crushed."+ },+ {+ "pass": "A",+ "id": "ramen_veg_crate",+ "h": 0.3,+ "prompt": "A blue plastic vegetable crate holding green cabbages, bunches of negi green onions, and onions, a few loose leaves."+ },+ {+ "pass": "A",+ "id": "ramen_shelf_jars",+ "m": 0.6,+ "prompt": "A cluttered row of kitchen pantry items on a shelf: glass jars of pickled garlic and chili oil, a can of white pepper, sesame oil bottle, a big jar of sesame seeds, plastic tubs of seasoning, all greasy and dusty, isolated group."+ },+ {+ "pass": "A",+ "id": "ramen_spice_tins",+ "m": 0.35,+ "prompt": "A cluster of round red and gold shichimi togarashi spice tins, a garlic chips jar, small white pepper shaker and a tub of minced garlic with a spoon."+ },+ {+ "pass": "A",+ "id": "ramen_menu_stand",+ "h": 0.22,+ "prompt": "A laminated ramen shop menu card with photos of ramen and Japanese text in a clear acrylic table stand, a little greasy and curled."+ },+ {+ "pass": "A",+ "id": "ramen_newspaper",+ "m": 0.42,+ "prompt": "A folded Japanese evening newspaper sports page lying flat, dense columns of Japanese text and a baseball photo, slightly crumpled and stained."+ },+ {+ "pass": "A",+ "id": "ramen_smartphone",+ "m": 0.16,+ "prompt": "A smartphone lying flat face up in a worn black case, dark screen with a small crack in the corner."+ },+ {+ "pass": "A",+ "id": "ramen_coat_hooks",+ "m": 0.95,+ "prompt": "A dark wooden wall-mounted coat hook board with five metal hooks, a navy work jacket, a beige rain jacket, and a baseball cap hanging on it, plastic shopping bag on the last hook."+ },+ {+ "pass": "A",+ "id": "ramen_gyoza_griddle",+ "m": 0.62,+ "prompt": "A commercial gas gyoza griddle with a heavy domed stainless lid with a wooden handle, burnt oil residue, dark seasoned iron plate."+ },+ {+ "pass": "A",+ "id": "ramen_bucket_strainer",+ "h": 0.5,+ "prompt": "A white plastic bucket with a large conical stainless steel soup strainer (chinois) resting on top, bone fragments and stains."+ },+ {+ "pass": "A",+ "id": "ramen_rice_sack",+ "h": 0.42,+ "prompt": "A 10 kg paper rice sack with green and red printed Japanese label, folded over at the top, standing on the floor."+ },+ {+ "pass": "A",+ "id": "ramen_wall_clock",+ "m": 0.3,+ "prompt": "A round white wall clock with black numerals and a red second hand, yellowed and greasy plastic frame."+ },+ {+ "pass": "A",+ "id": "ramen_condiment_tray2",+ "m": 0.32,+ "prompt": "A small black lacquer tray on a ramen counter holding a soy sauce dispenser, a vinegar bottle, a chili oil (rayu) bottle with red oil, a white pepper shaker and a pot of grated garlic with a tiny spoon."+ },+ {+ "pass": "A",+ "id": "ramen_beni_shoga_pot",+ "h": 0.14,+ "prompt": "A small white ceramic pot with lid ajar full of bright red pickled ginger strips (beni shoga), with small tongs."+ },+ {+ "pass": "A",+ "id": "ramen_ashtray",+ "m": 0.13,+ "prompt": "A heavy round glass ashtray with several cigarette butts and ash."+ },+ {+ "pass": "A",+ "id": "ramen_beer_bottle_glass",+ "h": 0.25,+ "prompt": "A large brown Japanese beer bottle with a paper label next to a small beer glass with a little flat beer left in it."+ },+ {+ "pass": "A",+ "id": "ramen_radio",+ "m": 0.32,+ "prompt": "An old silver and black portable AM/FM radio cassette player with a telescopic antenna, dusty and greasy."+ },+ {+ "pass": "A",+ "id": "ramen_fire_extinguisher",+ "h": 0.5,+ "prompt": "A red Japanese household fire extinguisher with a black hose and a white label with Japanese text, slightly dusty."+ },+ {+ "pass": "A",+ "id": "ramen_mop_bucket",+ "h": 0.9,+ "prompt": "A yellow commercial mop bucket with a wringer and a grey cotton mop standing in it, dirty water."+ },+ {+ "pass": "A",+ "id": "ramen_rubber_boots",+ "h": 0.36,+ "prompt": "A pair of white rubber kitchen boots standing side by side, scuffed and stained."+ },+ {+ "pass": "A",+ "id": "ramen_tebo_basket_rack",+ "m": 0.45,+ "prompt": "A stainless steel rack holding six tebo ramen noodle strainer baskets with long wooden handles, hanging and dripping."+ },+ {+ "pass": "A",+ "id": "ramen_ticket_tray",+ "m": 0.22,+ "prompt": "A small blue plastic tray holding a pile of small printed paper meal tickets (shokken) and a few coins."+ },+ {+ "pass": "A",+ "id": "ramen_vending_machine",+ "h": 1.83,+ "prompt": "A Japanese outdoor drink vending machine with a brightly backlit front showing rows of canned and bottled drinks, white and red body, buttons glowing, rain-wet, at night."+ },+ {+ "pass": "B",+ "id": "ramen_tongs",+ "m": 0.3,+ "prompt": "Two pairs of stainless steel kitchen tongs lying crossed, greasy."+ },+ {+ "pass": "B",+ "id": "ramen_towel_crumpled",+ "m": 0.32,+ "prompt": "A damp crumpled white cotton kitchen towel with brown broth stains, lying in a heap."+ },+ {+ "pass": "B",+ "id": "ramen_napkins_used",+ "m": 0.14,+ "prompt": "A few crumpled used white paper napkins with small broth stains, lying in a loose pile."+ },+ {+ "pass": "B",+ "id": "ramen_coins",+ "m": 0.1,+ "prompt": "A small loose pile of Japanese yen coins: 100 yen, 10 yen, 500 yen and 1 yen coins, lying flat."+ },+ {+ "pass": "B",+ "id": "ramen_tape_roll",+ "m": 0.1,+ "prompt": "A roll of brown packing tape and a black permanent marker lying next to it."+ },+ {+ "pass": "B",+ "id": "ramen_order_rail",+ "m": 0.6,+ "prompt": "A stainless steel kitchen order ticket rail with five handwritten paper order slips clipped into it, Japanese handwriting, greasy."+ },+ {+ "pass": "B",+ "id": "ramen_lighter_cigs",+ "m": 0.11,+ "prompt": "A crumpled Japanese cigarette pack and a cheap transparent plastic lighter lying on a counter."+ },+ {+ "pass": "B",+ "id": "ramen_tea_cup",+ "h": 0.09,+ "prompt": "A Japanese ceramic yunomi teacup with a speckled brown glaze and a little green tea left inside."+ },+ {+ "pass": "B",+ "id": "ramen_ladle_pair",+ "m": 0.4,+ "prompt": "Two used stainless steel ramen ladles (one flat-bottomed soup ladle, one small tare ladle) lying on a counter, broth residue."+ },+ {+ "pass": "B",+ "id": "ramen_garlic_press",+ "m": 0.18,+ "prompt": "A metal garlic press next to a few unpeeled garlic cloves and garlic skins."+ },+ {+ "pass": "C",+ "id": "ramen_cat_dish",+ "m": 0.32,+ "prompt": "Two small stainless steel pet bowls side by side, one with dry cat food kibble, one with water, on a worn plastic placemat."+ },+ {+ "pass": "C",+ "id": "ramen_power_strip",+ "m": 0.45,+ "prompt": "A dusty white multi-outlet power strip with four plugs inserted and tangled black and white cables coiled around it."+ },+ {+ "pass": "C",+ "id": "ramen_junction_box",+ "m": 0.2,+ "prompt": "A greasy beige electrical wall switch box with two rocker switches and a small breaker panel, cables entering from the top through grey conduit."+ },+ {+ "pass": "C",+ "id": "ramen_hook_items",+ "m": 0.45,+ "prompt": "A short wall rail with three hooks holding a ring of keys, a fly swatter and a plastic convenience-store bag."+ },+ {+ "pass": "C",+ "id": "ramen_kamidana",+ "m": 0.6,+ "prompt": "A small Shinto kamidana household shrine shelf of unpainted wood with a miniature shrine, sakaki branches in two vases, a white sake cup and paper ofuda charm, mounted high on a wall, smoky and dusty."+ },+ {+ "pass": "C",+ "id": "ramen_daruma",+ "h": 0.16,+ "prompt": "A red papier-mache daruma doll with one eye painted in, slightly faded and dusty."+ },+ {+ "pass": "nb",+ "id": "ramen_shelf_jars_nb",+ "m": 0.6,+ "prompt": "A cluttered row of kitchen pantry items on a shelf: glass jars of pickled garlic and chili oil, a can of white pepper, a sesame oil bottle, a big jar of sesame seeds, plastic tubs of seasoning, all greasy and dusty, with fictional Japanese labels such as 山田食品 and 丸金, isolated group. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_shelf_jars"+ },+ {+ "pass": "nb",+ "id": "ramen_spice_tins_nb",+ "m": 0.35,+ "prompt": "A cluster of round red and gold shichimi togarashi spice tins labelled 七味, a garlic chips jar labelled にんにく, a small white pepper shaker and a tub of minced garlic with a spoon, fictional maker name 丸金. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_spice_tins"+ },+ {+ "pass": "nb",+ "id": "ramen_cardboard_boxes_nb",+ "h": 0.6,+ "prompt": "A stack of three worn cardboard supply boxes printed with fictional Japanese food supplier names (山田食品, 丸金醤油, 大和製麺), one open with packets visible, tape peeling, slightly crushed. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_cardboard_boxes"+ },+ {+ "pass": "nb",+ "id": "ramen_flour_sacks_nb",+ "h": 0.55,+ "prompt": "Two heavy brown paper 25 kg flour sacks for noodles leaning against each other, printed with the fictional mill name 大和製粉 and 中華麺用, flour dust, slumped and folded tops. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_flour_sacks"+ },+ {+ "pass": "nb",+ "id": "ramen_beer_bottle_glass_nb",+ "h": 0.25,+ "prompt": "A large brown Japanese beer bottle with a paper label of the fictional brewery 富士ビール, next to a small beer glass with a little flat beer left in it. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_beer_bottle_glass"+ },+ {+ "pass": "nb",+ "id": "ramen_lighter_cigs_nb",+ "m": 0.11,+ "prompt": "A crumpled cigarette pack of the fictional brand 銀河 (plain design with Japanese health warning text) and a cheap transparent plastic lighter lying on a counter. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_lighter_cigs"+ },+ {+ "pass": "nb",+ "id": "ramen_vending_machine_nb",+ "h": 1.83,+ "prompt": "A Japanese outdoor drink vending machine with a brightly backlit front showing rows of canned and bottled drinks with fictional labels, white and red body with the fictional brand name さくら飲料, buttons glowing, rain-wet, at night. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_vending_machine"+ },+ {+ "pass": "nb",+ "id": "ramen_radio_nb",+ "m": 0.32,+ "prompt": "An old silver and black portable AM/FM radio cassette player with a telescopic antenna and the fictional brand name KOSEI, dusty and greasy. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_radio"+ },+ {+ "pass": "nb",+ "id": "ramen_tape_roll_nb",+ "m": 0.1,+ "prompt": "A roll of brown packing tape and an unbranded black permanent marker lying next to it. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_tape_roll"+ },+ {+ "pass": "nb",+ "id": "ramen_hook_items_nb",+ "m": 0.45,+ "prompt": "A short wall rail with three hooks holding a ring of keys, a green fly swatter and a plain white plastic shopping bag with no printing. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_hook_items"+ },+ {+ "pass": "nb",+ "id": "ramen_coat_hooks_nb",+ "m": 0.95,+ "prompt": "A dark wooden wall-mounted coat hook board with five metal hooks, a navy work jacket, a beige rain jacket, a plain baseball cap and a plain white plastic bag hanging on it, no logos. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.",+ "replaces": "ramen_coat_hooks"+ }+ ],+ "textures": [+ {+ "id": "street_backdrop",+ "size": "landscape_16_9",+ "prompt": "Photograph looking out from inside a doorway onto a narrow Tokyo back street at night in the rain: wet asphalt reflecting neon signs and vending machine light, closed shop shutters opposite, a few bicycles, power lines, out of focus, no people. Realistic phone photo, slightly underexposed."+ },+ {+ "id": "menu_plaques",+ "size": "landscape_16_9",+ "prompt": "A straight-on, flat, evenly lit photograph of a row of twelve vertical wooden menu plaques hanging side by side on a ramen shop wall, each with black brush calligraphy of a dish name and a price in red, e.g. 醤油ラーメン 八〇〇, 味噌ラーメン 九〇〇, 塩ラーメン 八五〇, チャーシュー麺 一一〇〇, つけ麺 九五〇, 餃子 四〇〇, ライス 一五〇, 味玉 一五〇, ビール 六〇〇. Aged smoky wood. Orthographic, no perspective, filling the frame."+ },+ {+ "id": "noren",+ "size": "landscape_4_3",+ "prompt": "A flat, straight-on photograph of a dark indigo cotton noren curtain for a ramen shop, three vertical panels, large white brush lettering ら~めん across them, slightly faded and stained at the bottom, evenly lit, filling the frame, no background."+ },+ {+ "id": "poster_beer",+ "size": "portrait_4_3",+ "prompt": "A faded vintage Japanese beer advertising poster from the 1980s with a smiling woman holding a beer glass and Japanese text, sun-faded, curled corners, flat straight-on photo filling the frame."+ },+ {+ "id": "calendar",+ "size": "portrait_4_3",+ "prompt": "A Japanese wall calendar from a local liquor store, October page with a big date grid and a landscape photo of Mt Fuji on top, store name printed at the bottom, flat straight-on photo filling the frame."+ },+ {+ "id": "handwritten_notice",+ "size": "portrait_4_3",+ "prompt": "A handwritten paper notice in black marker on white paper taped to a wall: 本日のスープ売り切れ次第終了 (closing when today's soup runs out), slightly wrinkled, flat straight-on photo filling the frame."+ },+ {+ "id": "street_backdrop2",+ "size": "landscape_16_9",+ "prompt": "Wide realistic night photograph straight across a narrow rainy Tokyo back street toward the shops opposite: a lit izakaya with red lanterns and a glowing noren, a bright drink vending machine, vertical neon signs in pink and cyan, a lit convenience-store window, wet asphalt with long colourful reflections and puddles, rain visible in the light, no people, slightly soft focus, vivid but realistic exposure."+ },+ {+ "id": "street_far",+ "size": "landscape_16_9",+ "prompt": "Realistic night photograph down a long rainy Tokyo alley seen from street level: rows of glowing vertical shop signs and neon receding into the distance, wet reflective ground, mist, bokeh lights, no people."+ },+ {+ "id": "neon_sign_a",+ "size": "portrait_4_3",+ "prompt": "A vertical glowing neon tube sign for a Japanese izakaya reading 居酒屋 in warm pink neon, mounted on a dark metal box, photographed at night against a pure black background, isolated."+ },+ {+ "id": "neon_sign_b",+ "size": "portrait_4_3",+ "prompt": "A vertical backlit plastic box sign for a Japanese snack bar, white panel with red and blue Japanese lettering スナック 花, glowing, photographed at night against a pure black background, isolated."+ },+ {+ "id": "decal_grease_drips",+ "size": "square_hd",+ "prompt": "Texture of brown amber cooking-grease drips and streaks running down vertically from the top edge, glossy oily runs of varying length, isolated on a pure black background, flat, seamless lighting, no other objects."+ },+ {+ "id": "decal_grease_splatter",+ "size": "square_hd",+ "prompt": "Texture of scattered brown oil splatter spots and small grease droplets of varied size, isolated on a pure white background, flat even lighting, top-down."+ },+ {+ "id": "decal_rings",+ "size": "square_hd",+ "prompt": "Texture of overlapping faint brown stain rings left by wet glasses and ramen bowls, plus a few broth drips and wipe marks, isolated on a pure white background, flat top-down."+ },+ {+ "id": "decal_floor_grime",+ "size": "square_hd",+ "prompt": "Texture of dark dirty footprint smudges, dried water marks and grime patches as seen on a restaurant floor, isolated on a pure white background, flat top-down, no floor texture."+ },+ {+ "id": "decal_fingerprints",+ "size": "square_hd",+ "prompt": "Texture of greasy fingerprints and smudges as seen on glass, faint white oily prints and wipe streaks, isolated on a pure black background, flat."+ },+ {+ "id": "stickers_sheet",+ "size": "square_hd",+ "prompt": "A flat lay of eight assorted faded worn Japanese stickers spaced apart: a cartoon ramen bowl mascot, a QR code payment sticker, a cash only sticker 現金のみ, a no smoking sign, a baseball team sticker, a beer brand sticker, a small anime character, a credit card logos strip, on a pure white background."+ },+ {+ "id": "flyer_festival",+ "size": "portrait_4_3",+ "prompt": "A slightly crumpled printed A4 Japanese local summer festival flyer 夏祭り with lanterns and fireworks illustration, dates and times, faded, flat straight-on photo filling the frame."+ },+ {+ "id": "flyer_parttime",+ "size": "portrait_4_3",+ "prompt": "A handwritten-and-printed Japanese part-time job wanted notice アルバイト募集 時給1200円, on yellowed paper with tape at the corners, flat straight-on photo filling the frame."+ },+ {+ "id": "flyer_lostcat",+ "size": "portrait_4_3",+ "prompt": "A homemade Japanese lost cat poster 迷い猫 探しています with a photo of a tabby cat and phone number tabs, faded, flat straight-on photo filling the frame."+ },+ {+ "id": "price_strips",+ "size": "landscape_16_9",+ "prompt": "A row of ten narrow vertical yellow paper strips with handwritten black marker Japanese drink names and prices (生ビール 500円, ハイボール 450円, ウーロン茶 200円...), taped side by side, curled and greasy, flat straight-on photo filling the frame."+ },+ {+ "id": "receipts",+ "size": "square_hd",+ "prompt": "Flat lay of three curled Japanese thermal paper receipts, two red paper chopstick wrappers printed おてもと, and two small handwritten order slips, spaced apart on a pure white background, top-down."+ },+ {+ "id": "poster_menu_special",+ "size": "portrait_4_3",+ "prompt": "A sun-faded hand-painted Japanese poster announcing a seasonal special ramen 冬季限定 味噌バターコーン with a photo of the ramen, curling and peeling corners, grease spots, flat straight-on photo filling the frame."+ },+ {+ "id": "stickers_sheet_nb",+ "size": "square_hd",+ "prompt": "A flat lay of eight assorted faded worn Japanese stickers spaced apart: a cartoon ramen bowl mascot, a generic QR code payment sticker reading QR決済, a cash only sticker 現金のみ, a no smoking sign, a fictional local baseball team sticker 商店街ファイターズ, a fictional beer sticker 富士ビール, a cute original cartoon cat mascot, a generic credit card icons strip with no real card logos, on a pure white background. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere."+ },+ {+ "id": "street_backdrop2_nb",+ "size": "landscape_16_9",+ "prompt": "Wide realistic night photograph straight across a narrow rainy Tokyo back street toward the shops opposite: a lit izakaya with red lanterns and a glowing noren, a bright drink vending machine, vertical neon signs in pink and cyan with fictional shop names, a lit small convenience store with a fictional sign, wet asphalt with long colourful reflections and puddles, rain visible in the light, no people, slightly soft focus, vivid but realistic exposure. All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere."+ }+ ]+}\ No newline at end of filediff --git a/scenes/tokyo-ramen-shop/picks.json b/scenes/tokyo-ramen-shop/picks.jsonnew file mode 100644index 0000000..3b6d215--- /dev/null+++ b/scenes/tokyo-ramen-shop/picks.json@@ -0,0 +1,314 @@+{+ "stockpot": {+ "model": "tripo-h31",+ "reason": "Dents are real geometry (visible in clay); Meshy smooth cylinder."+ },+ "ticket_machine": {+ "model": "tripo-h31",+ "reason": "Recessed buttons and coin unit modelled, labels legible; Meshy has dark blotches on the header."+ },+ "condiment_caddy": {+ "model": "meshy",+ "reason": "Closest to reference: chili flakes and garlic jar read; H3.1 contents muddy."+ },+ "lantern": {+ "model": "meshy",+ "reason": "Ribs in geometry, faithful kanji, lettering repeated on the back like real chochin."+ },+ "ramen_bowl_unfinished": {+ "model": "meshy",+ "reason": "Footed shallow bowl shape matches the reference; H3.1 made a tall conical bowl."+ },+ "ramen_gas_range": {+ "model": "meshy",+ "reason": "Grimier, more faithful burner texture and wider body; both modelled the grates."+ },+ "ramen_ladle_rail": {+ "model": "tripo-h31",+ "reason": "Kept the long chopsticks and greasy wear; Meshy cleaner and plainer."+ },+ "ramen_noodle_boiler": {+ "model": "tripo-h31",+ "reason": "Cleaner proportions and readable control panel; Meshy texture blown out and blotchy."+ },+ "ramen_bowl_stack": {+ "model": "meshy",+ "reason": "Wider bowls and crisper raimon rims, closer to the reference; H3.1 bowls narrow."+ },+ "ramen_cash_register": {+ "model": "meshy",+ "reason": "Sharper keys, readable display and receipt; H3.1 softer and blurrier."+ },+ "ramen_chopstick_cup": {+ "model": "tripo-h31",+ "reason": "Near tie; H3.1 has more varied chopstick heights and lacquer wear."+ },+ "ramen_crt_tv_bracket": {+ "model": "meshy",+ "reason": "Clearer screen bezel and bracket arm matching the reference."+ },+ "ramen_cutting_board": {+ "model": "meshy",+ "reason": "Chopped onion pile and knife read better; board cleaner like the reference."+ },+ "ramen_drink_fridge": {+ "model": "meshy",+ "reason": "Kirin header and stocked bottles intact; H3.1 lost the header branding."+ },+ "ramen_rice_cooker": {+ "model": "meshy",+ "reason": "Colours and Zojirushi-style panel match; H3.1 lid too dark."+ },+ "ramen_stool": {+ "model": "meshy",+ "reason": "Chrome base and footrest ring like the reference; H3.1 base dull white."+ },+ "ramen_tare_containers": {+ "model": "meshy",+ "reason": "Bigger containers with readable chashu and eggs; H3.1 dark and small contents."+ },+ "ramen_water_glass": {+ "model": "tripo-h31",+ "reason": "Faceted lower half matches the reference; becomes real glass in prep either way."+ },+ "ramen_water_pitcher": {+ "model": "meshy",+ "reason": "Spout, hinged lid and handle match the reference; H3.1 a plain cylinder."+ },+ "ramen_apron_hook": {+ "model": "tripo-h31",+ "reason": "Stains and wear match the reference; Meshy cleaner and flatter."+ },+ "ramen_beer_crate": {+ "model": "meshy",+ "reason": "Larger crate with side logo and full bottles; H3.1 smaller and plainer."+ },+ "ramen_dish_rack": {+ "model": "meshy",+ "reason": "Drip tray, plates and bowls all present; H3.1 rack cramped."+ },+ "ramen_square_cans": {+ "model": "meshy",+ "reason": "Crisp 揚げ油 label and dented corner; H3.1 label softer."+ },+ "ramen_tissue_box": {+ "model": "meshy",+ "reason": "Wood grain and bevel closer to the reference."+ },+ "ramen_umbrella_stand": {+ "model": "tripo-h31",+ "reason": "Black umbrella and clear vinyl ones read distinctly; Meshy merged them."+ },+ "ramen_wall_fan": {+ "model": "meshy",+ "reason": "Cream plastic colour and bracket match; H3.1 too white."+ },+ "ramen_hand_towel": {+ "model": "meshy",+ "reason": "Flatter, looser fold with faint stains like the reference."+ },+ "ramen_kettle_pot": {+ "model": "tripo-h31",+ "reason": "Kettle grime and dark handle closer to the reference."+ },+ "ramen_maneki_neko": {+ "model": "meshy",+ "reason": "Sharper face, larger 招財 koban; H3.1 slightly softer."+ },+ "ramen_noodle_crates": {+ "model": "meshy",+ "reason": "Larger crates, labels on both faces, 麺 roundels crisp."+ },+ "ramen_soy_bottles": {+ "model": "meshy",+ "reason": "Kikkoman / mirin labels crisp and correctly ordered."+ },+ "ramen_trash_bin": {+ "model": "meshy",+ "reason": "Grey tone and swing lid match the reference."+ },+ "ramen_chashu_tray": {+ "model": "tripo-h31",+ "reason": "Dark glossy braised logs and twine read like the reference; Meshy pork too pale."+ },+ "ramen_cleaver_board": {+ "model": "meshy",+ "reason": "Cleaner cleaver blade and sliced chashu; both carved the scarred block well."+ },+ "ramen_colander": {+ "model": "meshy",+ "reason": "Brighter brushed steel and crisp perforations; near tie."+ },+ "ramen_egg_container": {+ "model": "meshy",+ "reason": "Eggs and marinade visible through the tub, lid beside it; H3.1 eggs barely read."+ },+ "ramen_flour_sacks": {+ "model": "tripo-h31",+ "reason": "Both printed labels crisp front and back; Meshy lost the back label."+ },+ "ramen_plate_stack": {+ "model": "meshy",+ "reason": "Oval gyoza plates with blue rim like the reference; H3.1 rounder."+ },+ "ramen_shelf_jars": {+ "model": "tripo-h31",+ "reason": "Every jar and label from the reference survives; Meshy merged items into tubs."+ },+ "ramen_stockpot_small": {+ "model": "meshy",+ "reason": "Lid sits ajar with dents and scorched base; H3.1 lid too dark."+ },+ "ramen_stockpot_tall": {+ "model": "meshy",+ "reason": "Tall proportions and scorched bottom match; H3.1 squat."+ },+ "ramen_ashtray": {+ "model": "meshy",+ "reason": "Wider with visible butts; both came out opaque, glass coat added in prep."+ },+ "ramen_bucket_strainer": {+ "model": "meshy",+ "reason": "Larger chinois with handle and stained bucket, matches the reference."+ },+ "ramen_condiment_tray2": {+ "model": "tripo-h31",+ "reason": "Readable 醤油/ラー油 labels and lacquer tray; Meshy labels smeared."+ },+ "ramen_fire_extinguisher": {+ "model": "tripo-h31",+ "reason": "Front label and hose intact; Meshy label washed out."+ },+ "ramen_menu_stand": {+ "model": "tripo-h31",+ "reason": "Menu photos and prices crisp; fictional shop name 山虎."+ },+ "ramen_mop_bucket": {+ "model": "meshy",+ "reason": "Mop head and wringer complete, caution print; H3.1 lost the mop."+ },+ "ramen_newspaper": {+ "model": "tripo-h31",+ "reason": "Headline and photo legible; Meshy lost the back texture."+ },+ "ramen_rice_sack": {+ "model": "meshy",+ "reason": "Label on both faces, folded top; H3.1 back label garbled."+ },+ "ramen_smartphone": {+ "model": "tripo-h31",+ "reason": "Cracked screen and worn case like the reference."+ },+ "ramen_tongs": {+ "model": "tripo-h31",+ "reason": "Two pairs crossed as in the reference; Meshy pair merged."+ },+ "ramen_wall_clock": {+ "model": "meshy",+ "reason": "Clean dial and yellowed frame; H3.1 back is a blank disc either way."+ },+ "ramen_gyoza_griddle": {+ "model": "none",+ "reason": "Not placed: both models carry the real Rinnai brand from the reference."+ },+ "ramen_beer_bottle_glass_nb": {+ "model": "meshy",+ "reason": "De-branded 富士ビール label reads crisp; glass coat added in prep."+ },+ "ramen_cat_dish": {+ "model": "meshy",+ "reason": "Kibble and water bowls on the mat, closest colours."+ },+ "ramen_coins": {+ "model": "tripo-h31",+ "reason": "Flat pile with 100/10/1 yen faces legible."+ },+ "ramen_garlic_press": {+ "model": "tripo-h31",+ "reason": "Press with loose cloves and skins like the reference."+ },+ "ramen_ladle_pair": {+ "model": "tripo-h31",+ "reason": "Two ladles with hooked handles and residue; Meshy bowls flattened."+ },+ "ramen_power_strip": {+ "model": "tripo-h31",+ "reason": "Plugs and coiled cables intact; Meshy cables fused."+ },+ "ramen_tea_cup": {+ "model": "meshy",+ "reason": "Richer speckled glaze and green tea inside."+ },+ "ramen_ticket_tray": {+ "model": "tripo-h31",+ "reason": "Meal tickets and coins readable in the blue tray."+ },+ "ramen_spice_tins_nb": {+ "model": "tripo-h31",+ "reason": "De-branded 七味/にんにく tins and jars all legible; Meshy collapsed the cluster."+ },+ "ramen_shelf_jars_nb": {+ "model": "tripo-h31",+ "reason": "All fictional 山田食品/丸山 labels survive; Meshy dropped jars."+ },+ "ramen_cardboard_boxes_nb": {+ "model": "tripo-h31",+ "reason": "山田食品/丸金醤油/大和製麺 crisp; Meshy lettering garbled."+ },+ "ramen_flour_sacks_nb": {+ "model": "tripo-h31",+ "reason": "大和製粉 labels crisp on both sacks; Meshy front only."+ },+ "ramen_lighter_cigs_nb": {+ "model": "meshy",+ "reason": "銀河 pack and lighter, label on the front face; near tie."+ },+ "ramen_vending_machine_nb": {+ "model": "meshy",+ "reason": "さくら飲料 branding on front and side, stocked display; H3.1 side blank."+ },+ "ramen_radio_nb": {+ "model": "meshy",+ "reason": "KOSEI cassette front crisp and full back; H3.1 back muddy."+ },+ "ramen_tape_roll_nb": {+ "model": "meshy",+ "reason": "Printed core and unbranded marker; near tie."+ },+ "ramen_hook_items_nb": {+ "model": "tripo-h31",+ "reason": "Keys, fly swatter and plain bag on the rail as in the reference."+ },+ "ramen_coat_hooks_nb": {+ "model": "tripo-h31",+ "reason": "Jackets, cap and plain bag in reference order."+ },+ "ramen_kamidana": {+ "model": "meshy",+ "reason": "Shrine, sakaki vases and ofuda modelled; H3.1 back is a flat board either way."+ },+ "ramen_daruma": {+ "model": "meshy",+ "reason": "Face and 福 crisp; both backs plain."+ },+ "ramen_rubber_boots": {+ "model": "tripo-h31",+ "reason": "Only model (Meshy timed out); matches the reference closely."+ },+ "ramen_beni_shoga_pot": {+ "model": "tripo-h31",+ "reason": "Only model (Meshy timed out); pickled ginger and tongs read."+ },+ "ramen_towel_crumpled": {+ "model": "tripo-h31",+ "reason": "Only model (Meshy timed out); checked stained towel matches."+ },+ "ramen_napkins_used": {+ "model": "tripo-h31",+ "reason": "Only model (Meshy timed out); stained crumpled napkins match."+ },+ "ramen_junction_box": {+ "model": "none",+ "reason": "Not placed: breaker carries the real CHNT brand on reference and model."+ }+}\ No newline at end of filediff --git a/scenes/tokyo-ramen-shop/round2.json b/scenes/tokyo-ramen-shop/round2.jsonnew file mode 100644index 0000000..f67a44a--- /dev/null+++ b/scenes/tokyo-ramen-shop/round2.json@@ -0,0 +1,69 @@+{+ "generate": [+ {"pass":"A","id":"ramen_stockpot_tall","h":0.55,"prompt":"A tall dented aluminium commercial stockpot for tonkotsu broth, no lid, blackened scorched bottom and heat-stained sides, dried broth drips down the outside, heavy riveted handles."},+ {"pass":"A","id":"ramen_stockpot_small","h":0.3,"prompt":"A small dented stainless steel stockpot with a battered lid slightly ajar, scorched base, greasy fingerprints, riveted handles."},+ {"pass":"A","id":"ramen_colander","m":0.42,"prompt":"A large perforated stainless steel colander with two handles, water spots and scratches, sitting upright."},+ {"pass":"A","id":"ramen_chashu_tray","m":0.45,"prompt":"A stainless steel hotel pan tray holding four rolled and tied braised chashu pork belly logs glistening in dark soy braising liquid, kitchen twine, a few slices cut."},+ {"pass":"A","id":"ramen_egg_container","m":0.3,"prompt":"A square clear plastic food container half filled with dark soy-marinated soft-boiled ramen eggs (ajitama) in brown marinade, lid off beside it."},+ {"pass":"A","id":"ramen_cleaver_board","m":0.5,"prompt":"A thick worn round wooden chopping block with deep knife scars and stains, a heavy Chinese cleaver lying on it, a few sliced chashu pieces."},+ {"pass":"A","id":"ramen_plate_stack","h":0.14,"prompt":"Two stacks of small oval white gyoza plates with a thin blue line rim, slightly chipped, side by side."},+ {"pass":"A","id":"ramen_flour_sacks","h":0.55,"prompt":"Two heavy brown paper 25 kg flour sacks for noodles leaning against each other, printed Japanese brand lettering, flour dust, slumped and folded tops."},+ {"pass":"A","id":"ramen_cardboard_boxes","h":0.6,"prompt":"A stack of three worn cardboard supply boxes with printed Japanese food supplier logos, one open with packets visible, tape peeling, slightly crushed."},+ {"pass":"A","id":"ramen_veg_crate","h":0.3,"prompt":"A blue plastic vegetable crate holding green cabbages, bunches of negi green onions, and onions, a few loose leaves."},+ {"pass":"A","id":"ramen_shelf_jars","m":0.6,"prompt":"A cluttered row of kitchen pantry items on a shelf: glass jars of pickled garlic and chili oil, a can of white pepper, sesame oil bottle, a big jar of sesame seeds, plastic tubs of seasoning, all greasy and dusty, isolated group."},+ {"pass":"A","id":"ramen_spice_tins","m":0.35,"prompt":"A cluster of round red and gold shichimi togarashi spice tins, a garlic chips jar, small white pepper shaker and a tub of minced garlic with a spoon."},+ {"pass":"A","id":"ramen_menu_stand","h":0.22,"prompt":"A laminated ramen shop menu card with photos of ramen and Japanese text in a clear acrylic table stand, a little greasy and curled."},+ {"pass":"A","id":"ramen_newspaper","m":0.42,"prompt":"A folded Japanese evening newspaper sports page lying flat, dense columns of Japanese text and a baseball photo, slightly crumpled and stained."},+ {"pass":"A","id":"ramen_smartphone","m":0.16,"prompt":"A smartphone lying flat face up in a worn black case, dark screen with a small crack in the corner."},+ {"pass":"A","id":"ramen_coat_hooks","m":0.95,"prompt":"A dark wooden wall-mounted coat hook board with five metal hooks, a navy work jacket, a beige rain jacket, and a baseball cap hanging on it, plastic shopping bag on the last hook."},+ {"pass":"A","id":"ramen_gyoza_griddle","m":0.62,"prompt":"A commercial gas gyoza griddle with a heavy domed stainless lid with a wooden handle, burnt oil residue, dark seasoned iron plate."},+ {"pass":"A","id":"ramen_bucket_strainer","h":0.5,"prompt":"A white plastic bucket with a large conical stainless steel soup strainer (chinois) resting on top, bone fragments and stains."},+ {"pass":"A","id":"ramen_rice_sack","h":0.42,"prompt":"A 10 kg paper rice sack with green and red printed Japanese label, folded over at the top, standing on the floor."},+ {"pass":"A","id":"ramen_wall_clock","m":0.3,"prompt":"A round white wall clock with black numerals and a red second hand, yellowed and greasy plastic frame."},+ {"pass":"A","id":"ramen_condiment_tray2","m":0.32,"prompt":"A small black lacquer tray on a ramen counter holding a soy sauce dispenser, a vinegar bottle, a chili oil (rayu) bottle with red oil, a white pepper shaker and a pot of grated garlic with a tiny spoon."},+ {"pass":"A","id":"ramen_beni_shoga_pot","h":0.14,"prompt":"A small white ceramic pot with lid ajar full of bright red pickled ginger strips (beni shoga), with small tongs."},+ {"pass":"A","id":"ramen_ashtray","m":0.13,"prompt":"A heavy round glass ashtray with several cigarette butts and ash."},+ {"pass":"A","id":"ramen_beer_bottle_glass","h":0.25,"prompt":"A large brown Japanese beer bottle with a paper label next to a small beer glass with a little flat beer left in it."},+ {"pass":"A","id":"ramen_radio","m":0.32,"prompt":"An old silver and black portable AM/FM radio cassette player with a telescopic antenna, dusty and greasy."},+ {"pass":"A","id":"ramen_fire_extinguisher","h":0.5,"prompt":"A red Japanese household fire extinguisher with a black hose and a white label with Japanese text, slightly dusty."},+ {"pass":"A","id":"ramen_mop_bucket","h":0.9,"prompt":"A yellow commercial mop bucket with a wringer and a grey cotton mop standing in it, dirty water."},+ {"pass":"A","id":"ramen_rubber_boots","h":0.36,"prompt":"A pair of white rubber kitchen boots standing side by side, scuffed and stained."},+ {"pass":"A","id":"ramen_tebo_basket_rack","m":0.45,"prompt":"A stainless steel rack holding six tebo ramen noodle strainer baskets with long wooden handles, hanging and dripping."},+ {"pass":"A","id":"ramen_ticket_tray","m":0.22,"prompt":"A small blue plastic tray holding a pile of small printed paper meal tickets (shokken) and a few coins."},+ {"pass":"A","id":"ramen_vending_machine","h":1.83,"prompt":"A Japanese outdoor drink vending machine with a brightly backlit front showing rows of canned and bottled drinks, white and red body, buttons glowing, rain-wet, at night."},+ {"pass":"B","id":"ramen_tongs","m":0.3,"prompt":"Two pairs of stainless steel kitchen tongs lying crossed, greasy."},+ {"pass":"B","id":"ramen_towel_crumpled","m":0.32,"prompt":"A damp crumpled white cotton kitchen towel with brown broth stains, lying in a heap."},+ {"pass":"B","id":"ramen_napkins_used","m":0.14,"prompt":"A few crumpled used white paper napkins with small broth stains, lying in a loose pile."},+ {"pass":"B","id":"ramen_coins","m":0.1,"prompt":"A small loose pile of Japanese yen coins: 100 yen, 10 yen, 500 yen and 1 yen coins, lying flat."},+ {"pass":"B","id":"ramen_tape_roll","m":0.1,"prompt":"A roll of brown packing tape and a black permanent marker lying next to it."},+ {"pass":"B","id":"ramen_order_rail","m":0.6,"prompt":"A stainless steel kitchen order ticket rail with five handwritten paper order slips clipped into it, Japanese handwriting, greasy."},+ {"pass":"B","id":"ramen_lighter_cigs","m":0.11,"prompt":"A crumpled Japanese cigarette pack and a cheap transparent plastic lighter lying on a counter."},+ {"pass":"B","id":"ramen_tea_cup","h":0.09,"prompt":"A Japanese ceramic yunomi teacup with a speckled brown glaze and a little green tea left inside."},+ {"pass":"B","id":"ramen_ladle_pair","m":0.4,"prompt":"Two used stainless steel ramen ladles (one flat-bottomed soup ladle, one small tare ladle) lying on a counter, broth residue."},+ {"pass":"B","id":"ramen_garlic_press","m":0.18,"prompt":"A metal garlic press next to a few unpeeled garlic cloves and garlic skins."},+ {"pass":"C","id":"ramen_cat_dish","m":0.32,"prompt":"Two small stainless steel pet bowls side by side, one with dry cat food kibble, one with water, on a worn plastic placemat."},+ {"pass":"C","id":"ramen_power_strip","m":0.45,"prompt":"A dusty white multi-outlet power strip with four plugs inserted and tangled black and white cables coiled around it."},+ {"pass":"C","id":"ramen_junction_box","m":0.2,"prompt":"A greasy beige electrical wall switch box with two rocker switches and a small breaker panel, cables entering from the top through grey conduit."},+ {"pass":"C","id":"ramen_hook_items","m":0.45,"prompt":"A short wall rail with three hooks holding a ring of keys, a fly swatter and a plastic convenience-store bag."},+ {"pass":"C","id":"ramen_kamidana","m":0.6,"prompt":"A small Shinto kamidana household shrine shelf of unpainted wood with a miniature shrine, sakaki branches in two vases, a white sake cup and paper ofuda charm, mounted high on a wall, smoky and dusty."},+ {"pass":"C","id":"ramen_daruma","h":0.16,"prompt":"A red papier-mache daruma doll with one eye painted in, slightly faded and dusty."}+ ],+ "textures": [+ {"id":"street_backdrop2","size":"landscape_16_9","prompt":"Wide realistic night photograph straight across a narrow rainy Tokyo back street toward the shops opposite: a lit izakaya with red lanterns and a glowing noren, a bright drink vending machine, vertical neon signs in pink and cyan, a lit convenience-store window, wet asphalt with long colourful reflections and puddles, rain visible in the light, no people, slightly soft focus, vivid but realistic exposure."},+ {"id":"street_far","size":"landscape_16_9","prompt":"Realistic night photograph down a long rainy Tokyo alley seen from street level: rows of glowing vertical shop signs and neon receding into the distance, wet reflective ground, mist, bokeh lights, no people."},+ {"id":"neon_sign_a","size":"portrait_4_3","prompt":"A vertical glowing neon tube sign for a Japanese izakaya reading 居酒屋 in warm pink neon, mounted on a dark metal box, photographed at night against a pure black background, isolated."},+ {"id":"neon_sign_b","size":"portrait_4_3","prompt":"A vertical backlit plastic box sign for a Japanese snack bar, white panel with red and blue Japanese lettering スナック 花, glowing, photographed at night against a pure black background, isolated."},+ {"id":"decal_grease_drips","size":"square_hd","prompt":"Texture of brown amber cooking-grease drips and streaks running down vertically from the top edge, glossy oily runs of varying length, isolated on a pure black background, flat, seamless lighting, no other objects."},+ {"id":"decal_grease_splatter","size":"square_hd","prompt":"Texture of scattered brown oil splatter spots and small grease droplets of varied size, isolated on a pure white background, flat even lighting, top-down."},+ {"id":"decal_rings","size":"square_hd","prompt":"Texture of overlapping faint brown stain rings left by wet glasses and ramen bowls, plus a few broth drips and wipe marks, isolated on a pure white background, flat top-down."},+ {"id":"decal_floor_grime","size":"square_hd","prompt":"Texture of dark dirty footprint smudges, dried water marks and grime patches as seen on a restaurant floor, isolated on a pure white background, flat top-down, no floor texture."},+ {"id":"decal_fingerprints","size":"square_hd","prompt":"Texture of greasy fingerprints and smudges as seen on glass, faint white oily prints and wipe streaks, isolated on a pure black background, flat."},+ {"id":"stickers_sheet","size":"square_hd","prompt":"A flat lay of eight assorted faded worn Japanese stickers spaced apart: a cartoon ramen bowl mascot, a QR code payment sticker, a cash only sticker 現金のみ, a no smoking sign, a baseball team sticker, a beer brand sticker, a small anime character, a credit card logos strip, on a pure white background."},+ {"id":"flyer_festival","size":"portrait_4_3","prompt":"A slightly crumpled printed A4 Japanese local summer festival flyer 夏祭り with lanterns and fireworks illustration, dates and times, faded, flat straight-on photo filling the frame."},+ {"id":"flyer_parttime","size":"portrait_4_3","prompt":"A handwritten-and-printed Japanese part-time job wanted notice アルバイト募集 時給1200円, on yellowed paper with tape at the corners, flat straight-on photo filling the frame."},+ {"id":"flyer_lostcat","size":"portrait_4_3","prompt":"A homemade Japanese lost cat poster 迷い猫 探しています with a photo of a tabby cat and phone number tabs, faded, flat straight-on photo filling the frame."},+ {"id":"price_strips","size":"landscape_16_9","prompt":"A row of ten narrow vertical yellow paper strips with handwritten black marker Japanese drink names and prices (生ビール 500円, ハイボール 450円, ウーロン茶 200円...), taped side by side, curled and greasy, flat straight-on photo filling the frame."},+ {"id":"receipts","size":"square_hd","prompt":"Flat lay of three curled Japanese thermal paper receipts, two red paper chopstick wrappers printed おてもと, and two small handwritten order slips, spaced apart on a pure white background, top-down."},+ {"id":"poster_menu_special","size":"portrait_4_3","prompt":"A sun-faded hand-painted Japanese poster announcing a seasonal special ramen 冬季限定 味噌バターコーン with a photo of the ramen, curling and peeling corners, grease spots, flat straight-on photo filling the frame."}+ ]+}diff --git a/scenes/tokyo-ramen-shop/scripts/add_nb.mjs b/scenes/tokyo-ramen-shop/scripts/add_nb.mjsnew file mode 100644index 0000000..8fa8a63--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/add_nb.mjs@@ -0,0 +1,34 @@+// De-branded (_nb) regenerations of round-2 props/textures whose references carried real brands or characters.+import { readFileSync, writeFileSync } from 'node:fs';+const f = new URL('../assets.json', import.meta.url);+const m = JSON.parse(readFileSync(f, 'utf8'));+const NB = 'All labels use fictional Japanese brand names only; no real-world brand names, logos, store chains or trademarks anywhere.';+const props = {+ ramen_shelf_jars: 'A cluttered row of kitchen pantry items on a shelf: glass jars of pickled garlic and chili oil, a can of white pepper, a sesame oil bottle, a big jar of sesame seeds, plastic tubs of seasoning, all greasy and dusty, with fictional Japanese labels such as 山田食品 and 丸金, isolated group.',+ ramen_spice_tins: 'A cluster of round red and gold shichimi togarashi spice tins labelled 七味, a garlic chips jar labelled にんにく, a small white pepper shaker and a tub of minced garlic with a spoon, fictional maker name 丸金.',+ ramen_cardboard_boxes: 'A stack of three worn cardboard supply boxes printed with fictional Japanese food supplier names (山田食品, 丸金醤油, 大和製麺), one open with packets visible, tape peeling, slightly crushed.',+ ramen_flour_sacks: 'Two heavy brown paper 25 kg flour sacks for noodles leaning against each other, printed with the fictional mill name 大和製粉 and 中華麺用, flour dust, slumped and folded tops.',+ ramen_beer_bottle_glass: 'A large brown Japanese beer bottle with a paper label of the fictional brewery 富士ビール, next to a small beer glass with a little flat beer left in it.',+ ramen_lighter_cigs: 'A crumpled cigarette pack of the fictional brand 銀河 (plain design with Japanese health warning text) and a cheap transparent plastic lighter lying on a counter.',+ ramen_vending_machine: 'A Japanese outdoor drink vending machine with a brightly backlit front showing rows of canned and bottled drinks with fictional labels, white and red body with the fictional brand name さくら飲料, buttons glowing, rain-wet, at night.',+ ramen_radio: 'An old silver and black portable AM/FM radio cassette player with a telescopic antenna and the fictional brand name KOSEI, dusty and greasy.',+ ramen_tape_roll: 'A roll of brown packing tape and an unbranded black permanent marker lying next to it.',+ ramen_hook_items: 'A short wall rail with three hooks holding a ring of keys, a green fly swatter and a plain white plastic shopping bag with no printing.',+ ramen_coat_hooks: 'A dark wooden wall-mounted coat hook board with five metal hooks, a navy work jacket, a beige rain jacket, a plain baseball cap and a plain white plastic bag hanging on it, no logos.',+};+const tex = {+ stickers_sheet: 'A flat lay of eight assorted faded worn Japanese stickers spaced apart: a cartoon ramen bowl mascot, a generic QR code payment sticker reading QR決済, a cash only sticker 現金のみ, a no smoking sign, a fictional local baseball team sticker 商店街ファイターズ, a fictional beer sticker 富士ビール, a cute original cartoon cat mascot, a generic credit card icons strip with no real card logos, on a pure white background.',+ street_backdrop2: 'Wide realistic night photograph straight across a narrow rainy Tokyo back street toward the shops opposite: a lit izakaya with red lanterns and a glowing noren, a bright drink vending machine, vertical neon signs in pink and cyan with fictional shop names, a lit small convenience store with a fictional sign, wet asphalt with long colourful reflections and puddles, rain visible in the light, no people, slightly soft focus, vivid but realistic exposure.',+};+const ids = new Set(m.generate.map((p) => p.id));+for (const [id, prompt] of Object.entries(props)) {+ const base = m.generate.find((p) => p.id === id);+ if (!ids.has(id + '_nb')) m.generate.push({ ...base, id: id + '_nb', replaces: id, pass: 'nb', prompt: `${prompt} ${NB}` });+}+const tids = new Set(m.textures.map((t) => t.id));+for (const [id, prompt] of Object.entries(tex)) {+ const base = m.textures.find((t) => t.id === id);+ if (!tids.has(id + '_nb')) m.textures.push({ ...base, id: id + '_nb', prompt: `${prompt} ${NB}` });+}+writeFileSync(f, JSON.stringify(m, null, 2));+console.log([...Object.keys(props), ...Object.keys(tex)].map((k) => k + '_nb').join(','));diff --git a/scenes/tokyo-ramen-shop/scripts/bake_steam.py b/scenes/tokyo-ramen-shop/scripts/bake_steam.pynew file mode 100644index 0000000..8889676--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/bake_steam.py@@ -0,0 +1,33 @@+"""Bake the Mantaflow steam domains of scenes/tokyo-ramen-shop/ramen.blend (CPU) and save the .blend.++blender -b scenes/tokyo-ramen-shop/ramen.blend --python scenes/tokyo-ramen-shop/scripts/bake_steam.py -- [--res-scale 1.0] [--end 150] [--only steam_bowl]+"""+import os+import shutil+import sys+import time++import bpy++argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+scale = float(argv[argv.index("--res-scale") + 1]) if "--res-scale" in argv else 1.0+end = int(argv[argv.index("--end") + 1]) if "--end" in argv else None+only = argv[argv.index("--only") + 1].split(",") if "--only" in argv else None++for o in bpy.data.objects:+ mod = next((m for m in o.modifiers if m.type == "FLUID" and m.fluid_type == "DOMAIN"), None)+ if not mod or (only and o.name not in only):+ continue+ ds = mod.domain_settings+ if scale != 1.0:+ ds.resolution_max = max(24, int(ds.resolution_max * scale))+ if end is not None:+ ds.cache_frame_end = end+ # free_all runs as an async job that would delete the new cache after the bake, so clear the folder directly.+ shutil.rmtree(bpy.path.abspath(ds.cache_directory), ignore_errors=True)+ t0 = time.time()+ with bpy.context.temp_override(object=o, active_object=o, selected_objects=[o]):+ r = bpy.ops.fluid.bake_all()+ print(f"BAKE {o.name} res {ds.resolution_max} frames {ds.cache_frame_start}..{ds.cache_frame_end} {r} in {time.time() - t0:.0f}s", flush=True)+bpy.ops.wm.save_mainfile()+print("SAVED", bpy.data.filepath)diff --git a/scenes/tokyo-ramen-shop/scripts/bts.py b/scenes/tokyo-ramen-shop/scripts/bts.pynew file mode 100644index 0000000..1b6df84--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/bts.py@@ -0,0 +1,370 @@+"""Behind-the-scenes dollhouse clips (breakdown/SPEC.md) from breakdown/tokyo-ramen-shop/bts.blend (never saved).++blender -b breakdown/tokyo-ramen-shop/bts.blend --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/bts.py -- <clip> [--pass clay|plain|full] [--frames a-b] [--samples n] [--out dir]+clip: a_layout | b_props | c_materials | d_lighting+c_materials renders three passes (clay 1-48, plain 1-96, full 49-144) that bts_ramen.sh composites with ffmpeg.+World coordinates are post-mirror: kitchen wall at x=0, customer wall at x=W, street at y<0.+"""+import math+import os+import sys++import bpy+from mathutils import Vector++argv = sys.argv[sys.argv.index("--") + 1:]+CLIP = argv[0]+++def opt(k, d=None):+ return argv[argv.index(k) + 1] if k in argv else d+++PASS = opt("--pass", {"a_layout": "clay", "b_props": "clay", "c_materials": "full", "d_lighting": "night"}[CLIP])+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+OUT = os.path.abspath(opt("--out", os.path.join(ROOT, "breakdown", "tokyo-ramen-shop", "clips", CLIP)))+W, D, H = 3.6, 7.0, 2.6+CENTER = Vector((W / 2, D / 2, 0.55))+FRAMES = {"a_layout": 144, "b_props": 240, "c_materials": 144, "d_lighting": 240}+N = FRAMES[CLIP]+SPAN = {"a_layout": (-60, -30), "b_props": (-30, 0), "c_materials": (0, 30), "d_lighting": (30, 60)}[CLIP]+DIST, ELEV, LENS = 11.8, math.radians(40), 30++sc = bpy.context.scene+sc.animation_data_clear() # drops the handheld clip's exposure keys+sc.view_settings.exposure = 0.0+sc.frame_start, sc.frame_end = 1, N+sc.render.fps = 24+sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = 1920, 1080, 100+sc.render.use_compositing = False # no grade, no lens fx (spec)+sc.render.use_motion_blur = False+sc.render.image_settings.file_format = "PNG"+sc.render.image_settings.color_depth = "8"+sc.render.film_transparent = False++objs = list(bpy.data.objects)++# Round-1 bug in the saved scenes: the counter foot rail was placed by its end but its origin is its centre, so it+# poked ~0.7 m out through the front wall. Fixed in shell.py; patched here so the clips match the corrected build.+_rail = bpy.data.objects.get("foot_rail")+if _rail:+ bpy.context.view_layer.update()+ _lo = min((_rail.matrix_world @ Vector(c)).y for c in _rail.bound_box)+ _rail.location.y += 1.6 - _lo+++def coll_objs(name):+ c = bpy.data.collections.get(name)+ return set(c.all_objects) if c else set()+++SHELL = coll_objs("shell")+LIGHTS = {o for o in objs if o.type == "LIGHT"}+EXTERIOR = coll_objs("exterior") | {o for o in objs if o.name.startswith(("street_backdrop", "pavement", "eave", "noren", "lantern", "ramen_vending_machine", "neon_"))}+VOLUMES = {o for o in objs if o.name.startswith(("haze_volume", "kitchen_vapor", "steam_", "rain_"))}+DECALS = {o for o in objs if o.name.startswith(("decal_", "sticker_img", "price_strips", "poster_special"))}+POSTERS = {o for o in objs if o.name.split(".")[0] in ("poster_beer", "calendar", "handwritten_notice") or o.name.startswith("flyer_")}+CAMS = {o for o in objs if o.type == "CAMERA"}+++def bbox(o):+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]+ return (Vector([min(p[i] for p in pts) for i in range(3)]), Vector([max(p[i] for p in pts) for i in range(3)]))+++def key_hide(o, frame, hidden):+ o.hide_render = hidden+ o.hide_viewport = hidden+ o.keyframe_insert("hide_render", frame=frame)+ o.keyframe_insert("hide_viewport", frame=frame)+++def hide(os_):+ for o in os_:+ o.hide_render = True+ o.hide_viewport = True+++# ------------------------------------------------------------------ camera: one 120° orbit split into four clips++def angle_at(f):+ t = (f - 1) / (N - 1)+ a0, a1 = SPAN+ if CLIP == "a_layout": # ease in only+ v = 1 / 0.875+ u = v * t * t / 0.5 if t < 0.25 else v * (0.125 + (t - 0.25))+ elif CLIP == "d_lighting": # ease out only+ s = 1 - t+ v = 1 / 0.875+ u = 1 - (v * s * s / 0.5 if s < 0.25 else v * (0.125 + (s - 0.25)))+ else:+ u = t+ return math.radians(a0 + (a1 - a0) * u)+++cd = bpy.data.cameras.new("bts_cam")+cd.lens = LENS+cd.sensor_width = 36+cd.clip_start = 0.1+cd.dof.use_dof = False+cd.shift_y = -0.05 # room sits a little high in frame: bottom 140 px stays clear for captions+cam = bpy.data.objects.new("bts_cam", cd)+sc.collection.objects.link(cam)+sc.camera = cam+for f in range(1, N + 1):+ a = angle_at(f)+ pos = CENTER + Vector((math.cos(a) * math.cos(ELEV), math.sin(a) * math.cos(ELEV), math.sin(ELEV))) * DIST+ cam.location = pos+ cam.rotation_euler = (CENTER - pos).to_track_quat("-Z", "Y").to_euler()+ cam.keyframe_insert("location", frame=f)+ cam.keyframe_insert("rotation_euler", frame=f)++# ------------------------------------------------------------------ dollhouse cutaway: ceiling always, near walls per frame++# ------------------------------------------------------------------ looks+++def eevee():+ sc.render.engine = "BLENDER_EEVEE"+ ee = sc.eevee+ for attr, v in (("taa_render_samples", 32), ("use_shadows", True), ("use_raytracing", True), ("use_fast_gi", True)):+ if hasattr(ee, attr):+ setattr(ee, attr, v)+++def studio_world(color, strength):+ w = sc.world+ bg = w.node_tree.nodes["Background"]+ bg.inputs["Color"].default_value = (*color, 1)+ bg.inputs["Strength"].default_value = strength+++def add_sun(energy, rot=(50, 0, 30), size=8):+ ld = bpy.data.lights.new("bts_sun", "SUN")+ ld.energy = energy+ ld.angle = math.radians(size)+ so = bpy.data.objects.new("bts_sun", ld)+ sc.collection.objects.link(so)+ so.rotation_euler = [math.radians(v) for v in rot]+ return so+++def clay():+ m = bpy.data.materials.new("BTS_CLAY")+ m.use_nodes = True+ b = m.node_tree.nodes["Principled BSDF"]+ b.inputs["Base Color"].default_value = (0.62, 0.62, 0.6, 1)+ b.inputs["Roughness"].default_value = 0.65+ bpy.context.view_layer.material_override = m+ hide(LIGHTS | VOLUMES | DECALS | EXTERIOR)+ studio_world((0.7, 0.72, 0.76), 0.45) # dim fill + strong key: the clay needs form shading+ add_sun(4.5, rot=(48, 0, 120))+ eevee()+++def neutral():+ hide(LIGHTS | VOLUMES | EXTERIOR)+ studio_world((0.8, 0.8, 0.8), 1.1)+ add_sun(2.5)+ eevee()+ if PASS == "plain":+ hide(DECALS | POSTERS)+++def cutaway():+ """Ceiling always off; walls (and wall-mounted things) on the camera side keyed off per frame. Runs after the look,+ so anything a look already hid (exterior, volumes) stays hidden."""+ hide([o for o in objs if o.name.startswith("ceiling")])+ WALLS = { # outward normal -> shell/wall-ish objects on that side+ (1, 0): lambda lo, hi: lo.x > W - 0.25,+ (0, -1): lambda lo, hi: hi.y < 0.25,+ (0, 1): lambda lo, hi: lo.y > D - 0.25,+ }+ WALLISH = ("wall_", "front_", "wainscot", "skirting", "door", "win_", "ceiling", "eave", "noren")+ side_objs = {k: [] for k in WALLS}+ corner_objs = []+ for o in objs:+ if o.parent is not None or o.type not in ("MESH", "CURVE", "FONT") or o in VOLUMES or o.hide_render:+ continue+ lo, hi = bbox(o)+ near = [k for k, test in WALLS.items() if test(lo - Vector((0.45, 0.45, 0)), hi + Vector((0.45, 0.45, 0)))]+ if hi.z > 1.2 and len(near) == 2 and not o.name.startswith(WALLISH):+ corner_objs.append((o, near)) # tall thing in a corner (drink fridge): off once both its walls are off+ for k, test in WALLS.items():+ if not test(lo, hi):+ continue+ thin = (hi.x - lo.x if k[0] else hi.y - lo.y) < 0.3+ wall_mounted = lo.z > 0.45 and thin+ if o.name.startswith(WALLISH) or wall_mounted:+ side_objs[k].append(o)+ for k, lst in side_objs.items():+ prev = None+ for f in range(1, N + 1):+ a = angle_at(f)+ hidden = k[0] * math.cos(a) + k[1] * math.sin(a) > 0.3+ if hidden != prev:+ for o in lst:+ key_hide(o, f, hidden)+ prev = hidden+ for o in lst:+ if o.animation_data and o.animation_data.action:+ act = o.animation_data.action+ fcs = act.fcurves if hasattr(act, "fcurves") else act.layers[0].strips[0].channelbag(act.slots[0]).fcurves+ for fc in fcs:+ for kp in fc.keyframe_points:+ kp.interpolation = "CONSTANT"++ for o, ks in corner_objs:+ prev = None+ for f in range(1, N + 1):+ a = angle_at(f)+ hidden = all(k[0] * math.cos(a) + k[1] * math.sin(a) > 0.3 for k in ks)+ if hidden != prev:+ key_hide(o, f, hidden)+ prev = hidden+++# ------------------------------------------------------------------ clips+++def clip_a():+ """Shell only, pieces rising into place over the first 2 s (floor first, then by height)."""+ hide([o for o in objs if o not in SHELL and o not in CAMS] + [o for o in SHELL if o.name.startswith(("menu_plaques", "poster", "calendar", "handwritten"))])+ pieces = [o for o in SHELL if o.parent is None and not o.name.startswith(("floor", "ceiling"))]+ pieces.sort(key=lambda o: (bbox(o)[0].z, bbox(o)[0].y))+ for i, o in enumerate(pieces):+ s = 4 + int(36 * i / max(1, len(pieces) - 1))+ z = o.location.z+ o.location.z = z - 2.8+ o.keyframe_insert("location", index=2, frame=1)+ o.keyframe_insert("location", index=2, frame=s)+ o.location.z = z+ o.keyframe_insert("location", index=2, frame=s + 10)+++def clip_b():+ props = [o for o in objs if o.parent is None and o not in SHELL and o not in LIGHTS | VOLUMES | DECALS | EXTERIOR | CAMS+ and o.type in ("MESH", "CURVE", "FONT", "EMPTY") and not o.hide_render]+ props.sort(key=lambda o: -max(1e-6, (lambda lo, hi: (hi - lo).x * (hi - lo).y * (hi - lo).z)(*bbox(o))))+ n = len(props)+ for i, o in enumerate(props):+ f = 8 + int(188 * (i / max(1, n - 1)) ** 1.5) # big things spaced out first, clutter rains in at the end+ s = o.scale.copy()+ o.scale = (0, 0, 0)+ o.keyframe_insert("scale", frame=1)+ o.keyframe_insert("scale", frame=f)+ o.scale = s * 1.12+ o.keyframe_insert("scale", frame=f + 4)+ o.scale = s+ o.keyframe_insert("scale", frame=f + 6)+ print("BTS props animated", n, flush=True)+++def _mul_node(nt, sock, key_frames):+ """Insert value*k into a socket (linked or default) and key k over key_frames [(frame, value), ...]."""+ src = sock.links[0].from_socket if sock.is_linked else None+ m = nt.nodes.new("ShaderNodeMath")+ m.operation = "MULTIPLY"+ if src is not None:+ nt.links.new(src, m.inputs[0])+ else:+ m.inputs[0].default_value = sock.default_value if not hasattr(sock.default_value, "__len__") else 1.0+ nt.links.new(m.outputs[0], sock)+ for f, v in key_frames:+ m.inputs[1].default_value = v+ m.inputs[1].keyframe_insert("default_value", frame=f)+ return m+++def ramp(f0, length=8):+ return [(1, 0.0), (f0, 0.0), (f0 + length, 1.0)]+++def clip_d():+ """Textured scene in darkness; practicals, signage, street, then fills; volumetrics last."""+ sc.render.engine = "CYCLES"+ sc.cycles.samples = int(opt("--samples", 16))+ sc.cycles.use_denoising = True+ sc.cycles.denoiser = "OPTIX"+ sc.cycles.use_adaptive_sampling = True+ sc.render.use_persistent_data = True+ sc.view_settings.exposure = 0.35 # dollhouse distance: lift the night look a little+ hide([o for o in objs if o.name.startswith(("street_backdrop", "road"))])+ order = [("pendant_spot_0", 12), ("pendant_glow_0", 12), ("pendant_spot_1", 20), ("pendant_glow_1", 20),+ ("pendant_spot_2", 28), ("pendant_glow_2", 28), ("pendant_spot_3", 36), ("pendant_glow_3", 36),+ ("hood_strip", 50), ("kitchen_tube", 58), ("kitchen_tube_front", 64), ("ticket_glow", 76), ("fridge_glow", 84),+ ("lantern_light", 100), ("neon_izakaya_spill", 108), ("neon_snack_spill", 114), ("vending_glow", 120),+ ("street_lamp", 132), ("street_fill", 140), ("door_spill", 146), ("window_spill", 150), ("street_bounce", 156)]+ when = dict(order)+ for o in LIGHTS:+ if o.name.startswith("bts_"):+ continue+ f0 = when.get(o.name, 160)+ e = o.data.energy+ for f, v in ramp(f0, 10):+ o.data.energy = e * v+ o.data.keyframe_insert("energy", frame=f)+ # Emissive materials follow the light they belong to.+ owner_time = [("pendant_bulb", 12), ("ticket_machine", 76), ("ramen_drink_fridge", 84), ("lantern", 100), ("neon_izakaya", 108),+ ("neon_snack", 114), ("ramen_vending_machine", 120), ("lamp_lens", 132)]+ done = set()+ for o in objs:+ if o.type != "MESH":+ continue+ f0 = next((t for p, t in owner_time if o.name.startswith(p)), None)+ for m in o.data.materials:+ if not m or not m.node_tree or m.name in done:+ continue+ for n in m.node_tree.nodes:+ if n.type == "BSDF_PRINCIPLED":+ s = n.inputs["Emission Strength"]+ if s.is_linked or s.default_value > 0:+ _mul_node(m.node_tree, s, ramp(f0 or 60, 10))+ done.add(m.name)+ elif n.type == "EMISSION":+ _mul_node(m.node_tree, n.inputs["Strength"], ramp(f0 or 60, 10))+ done.add(m.name)+ # Volumetrics and rain last.+ vol_time = {"haze": 166, "kitchen_vapor": 174, "steam_vol": 182}+ for m in bpy.data.materials:+ if not m.node_tree:+ continue+ for n in m.node_tree.nodes:+ if n.type == "PRINCIPLED_VOLUME" and m.name in vol_time:+ _mul_node(m.node_tree, n.inputs["Density"], ramp(vol_time[m.name], 26))+ rain = bpy.data.materials.get("rain")+ if rain:+ b = next(n for n in rain.node_tree.nodes if n.type == "BSDF_PRINCIPLED")+ _mul_node(rain.node_tree, b.inputs["Alpha"], ramp(190, 24))+ _mul_node(rain.node_tree, b.inputs["Emission Strength"], ramp(190, 24))+ print("BTS lights", len(LIGHTS), "emissive mats", len(done), flush=True)+++if CLIP == "a_layout":+ clay()+ clip_a()+elif CLIP == "b_props":+ clay()+ clip_b()+elif CLIP == "c_materials":+ if PASS == "clay":+ clay()+ else:+ neutral()+elif CLIP == "d_lighting":+ clip_d()++cutaway()++a, b = (int(x) for x in opt("--frames", f"1-{N}").split("-"))+sc.frame_start, sc.frame_end = a, b+os.makedirs(OUT, exist_ok=True)+sc.render.filepath = os.path.join(OUT, "")+if "--still" in argv:+ f = int(opt("--still"))+ sc.frame_set(f)+ sc.render.filepath = os.path.join(OUT, f"still_{f:04d}.png")+ bpy.ops.render.render(write_still=True)+else:+ bpy.ops.render.render(animation=True)+print("BTS rendered", CLIP, PASS, a, b, flush=True)diff --git a/scenes/tokyo-ramen-shop/scripts/build.py b/scenes/tokyo-ramen-shop/scripts/build.pynew file mode 100644index 0000000..11b611d--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/build.py@@ -0,0 +1,195 @@+"""Build the ramen shop .blend from scratch, optionally render previews.++blender -b --factory-startup --python scenes/tokyo-ramen-shop/scripts/build.py -- [--stages shell,dress,light,post] [--preview cam1,cam2]+ [--clay] [--samples 32] [--res 960] [--save] [--out scenes/tokyo-ramen-shop/out/prev]+"""+import argparse+import math+import os+import sys++import bpy+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(__file__))+import lib # noqa: E402+import shell # noqa: E402++argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+ap = argparse.ArgumentParser()+ap.add_argument("--stages", default="shell,dress,passA,passB,passC,grime,r2gen,steam,light,post")+ap.add_argument("--preview", default="")+ap.add_argument("--clay", action="store_true")+ap.add_argument("--samples", type=int, default=32)+ap.add_argument("--res", type=int, default=960)+ap.add_argument("--save", action="store_true")+ap.add_argument("--out", default=os.path.join(lib.SCENE_DIR, "out", "prev"))+ap.add_argument("--tag", default="")+ap.add_argument("--blend", default="ramen_r2.blend", help="file name under scenes/tokyo-ramen-shop for --save")+ap.add_argument("--final", action="store_true", help="1920x1080, --samples, 16-bit PNG (for the saved .blend / stills)")+A = ap.parse_args(argv)+# Handheld clip: a slow step forward down the aisle toward the door, drifting toward the counter.+CLIP = dict(start=(0.8, 6.15, 1.52), end=(0.76, 5.35, 1.47), target=(1.5, 1.2, 1.02), lens=22, frames=120)+STAGES = A.stages.split(",")++CAMS = {+ # Wide hero from the back of the aisle toward the door, counter on the right (matches concept_wide).+ "wide": dict(loc=(0.78, 6.2, 1.5), target=(1.45, 0.6, 1.0), lens=20),+ # Seated at the counter, looking across the bowl into the kitchen pass (matches concept_detail).+ "counter": dict(loc=(0.82, 3.0, 1.36), target=(3.1, 4.6, 0.72), lens=24, focus=(1.45, 3.35, 0.95), fstop=4.0),+ # Overview for checking layout.+ "top": dict(loc=(1.8, 3.5, 9.0), target=(1.8, 3.5, 0), lens=18),+ "kitchen": dict(loc=(2.6, 0.8, 1.6), target=(3.0, 4.5, 0.9), lens=20),+ "door": dict(loc=(1.1, 2.4, 1.45), target=(1.4, -3.0, 1.3), lens=24),+}+++def reset():+ bpy.ops.wm.read_factory_settings(use_empty=True)+ sc = bpy.context.scene+ sc.render.engine = "CYCLES"+ prefs = bpy.context.preferences.addons["cycles"].preferences+ prefs.compute_device_type = "OPTIX"+ prefs.get_devices()+ for d in prefs.devices:+ d.use = d.type == "OPTIX"+ sc.cycles.device = "GPU"+ sc.cycles.use_denoising = True+ sc.cycles.denoiser = "OPTIX"+ sc.view_settings.view_transform = "AgX"+ sc.view_settings.look = "AgX - Medium High Contrast"+ sc.view_settings.exposure = -0.12+ sc.render.fps = 24+ world = bpy.data.worlds.new("world")+ sc.world = world+ world.use_nodes = True+ world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.004, 0.005, 0.007, 1)+ world.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.0+ return sc+++def add_camera(name, loc, target, lens, c):+ d = bpy.data.cameras.new(name)+ d.lens = lens+ d.sensor_width = 36+ d.clip_start = 0.02+ o = bpy.data.objects.new(name, d)+ c.objects.link(o)+ o.location = loc+ o.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()+ o["target"] = target+ return o+++def mirror_x(root):+ """Layout is authored with the counter on the camera's left; the concept has it on the right.+ Conjugate every top-level transform by an x-flip about the room centre: positions reflect, but each+ object stays a proper (non-mirrored) rotation, so printed text on props and planes still reads correctly."""+ M = Matrix.Translation((shell.W, 0, 0)) @ Matrix.Scale(-1, 4, (1, 0, 0))+ F = Matrix.Scale(-1, 4, (1, 0, 0))+ bpy.context.view_layer.update() # matrix_world is stale on new objects until the depsgraph updates+ objs = [o for o in bpy.data.objects if o.parent is None]+ # Geometry authored in world space (origin at 0: noren panels, conduit, cables, noodles) would only be shifted,+ # because the conjugation mirrors origins, not vertices. Move those origins to their bounds centre first.+ for o in objs:+ if o.type in ("MESH", "CURVE") and o.location.length < 1e-6 and o.data and o.data.users == 1:+ bb = [Vector(c) for c in o.bound_box]+ ctr = sum(bb, Vector()) / 8+ if ctr.length > 1e-4:+ o.data.transform(Matrix.Translation(-ctr))+ o.location = ctr+ bpy.context.view_layer.update()+ for o in objs:+ o.matrix_world = M @ o.matrix_world @ F+++def clay_override():+ m = lib.m_simple("CLAY", (0.5, 0.5, 0.5), 0.6)+ bpy.context.view_layer.material_override = m+ # Keep emitters and glass readable in clay: nothing else needed for a layout check.+++def main():+ sc = reset()+ root = lib.coll("ramen")+ cshell = lib.coll("shell", root)+ if "shell" in STAGES:+ shell.build(cshell)+ spots = ()+ if "dress" in STAGES:+ import dress+ import validate+ dress.build(lib.coll("props", root))+ if "passA" in STAGES:+ dress.pass_a(lib.coll("props_a", root))+ validate.run(dress.PLACED, os.path.join(lib.SCENE_DIR, "out", "validate.txt"))+ if "passB" in STAGES or "passC" in STAGES:+ import clutter+ if "passB" in STAGES:+ clutter.pass_b(lib.coll("clutter_b", root))+ if "passC" in STAGES:+ clutter.pass_c(lib.coll("clutter_c", root))+ if "steam" in STAGES:+ import steam+ steam.build(lib.coll("fx", root), *dress.steam_sources())+ if "light" in STAGES:+ import lighting+ lighting.build(lib.coll("lights", root))+ import exterior+ exterior.build(lib.coll("exterior", root))+ ccam = lib.coll("cameras", root)+ for k, v in CAMS.items():+ add_camera("cam_" + k, v["loc"], v["target"], v["lens"], ccam)+ if "post" in STAGES:+ import post+ post.build()+ if "light" not in STAGES:+ # Neutral preview light so shell/dress passes are readable.+ lib.area("prev_key", lib.coll("lights", root), (1.8, 3.5, 2.5), (0, 0, 0), 3.0, 600, size_y=6)+ sc.world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.05, 0.05, 0.055, 1)+ mirror_x(root)+ import emitters+ emitters.run()+ emitters.no_volume_blur()+ if "grime" in STAGES:+ import grime+ grime.build()+ if "r2gen" in STAGES and "light" in STAGES:+ import r2gen+ r2gen.apply() # round-2 generated props, decals and prints (post-mirror, world coordinates)+ # Cameras that need world-space targets are set up after the mirror (keyframes are not mirrored).+ import camera+ mx = lambda p: (shell.W - p[0], p[1], p[2]) # noqa: E731+ for k in ("wide", "counter"):+ focus = CAMS[k].get("focus", CAMS[k]["target"])+ camera.still_dof(bpy.data.objects["cam_" + k], mx(focus), fstop=CAMS[k].get("fstop", 2.8))+ clip = add_camera("cam_clip", mx(CLIP["start"]), mx(CLIP["target"]), CLIP["lens"], ccam)+ camera.handheld(clip, mx(CLIP["start"]), mx(CLIP["end"]), mx(CLIP["target"]), frames=CLIP["frames"], fstop=2.4)+ if A.clay:+ clay_override()+ if A.final:+ sc.cycles.samples = A.samples+ sc.cycles.adaptive_threshold = 0.02+ sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = 1920, 1080, 100+ sc.render.image_settings.file_format = "PNG"+ sc.render.image_settings.color_depth = "16"+ if A.save:+ path = os.path.join(lib.SCENE_DIR, A.blend)+ bpy.ops.wm.save_as_mainfile(filepath=path, compress=True)+ print("saved", path)+ if A.preview:+ os.makedirs(A.out, exist_ok=True)+ sc.cycles.samples = A.samples+ sc.render.resolution_x = A.res+ sc.render.resolution_y = int(A.res * 9 / 16)+ sc.render.resolution_percentage = 100+ for k in A.preview.split(","):+ sc.camera = bpy.data.objects["cam_" + k]+ if "ceiling" in bpy.data.objects:+ bpy.data.objects["ceiling"].hide_render = k == "top"+ sc.render.filepath = os.path.join(A.out, f"{k}{A.tag}.png")+ bpy.ops.render.render(write_still=True)+ print("rendered", sc.render.filepath)+++main()diff --git a/scenes/tokyo-ramen-shop/scripts/camcheck.py b/scenes/tokyo-ramen-shop/scripts/camcheck.pynew file mode 100644index 0000000..c5ddbb9--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/camcheck.py@@ -0,0 +1,63 @@+"""Camera-path clearance check: minimum distance from each shot's camera path to render-visible mesh geometry.++blender -b scenes/tokyo-ramen-shop/ramen_r2.blend --python scenes/tokyo-ramen-shop/scripts/camcheck.py -- scenes/tokyo-ramen-shop/shots.json h1_door_to_counter,h2_counter_walkaround [--min 0.25]+Samples the keyed positions (Catmull-Rom for move "path", piecewise linear otherwise); handheld shake is a few mm, ignored."""+import json+import sys++import bpy+from mathutils import Vector+from mathutils.bvhtree import BVHTree++argv = sys.argv[sys.argv.index("--") + 1:]+shots = {s["name"]: s for s in json.load(open(argv[0]))["shots"]}+names = argv[1].split(",")+MIN = float(argv[argv.index("--min") + 1]) if "--min" in argv else 0.25+SKIP = ("haze_volume", "kitchen_vapor", "steam_", "rain_", "street_backdrop", "road", "CR_")++dg = bpy.context.evaluated_depsgraph_get()+verts, polys = [], []+for o in bpy.data.objects:+ if o.type != "MESH" or o.hide_render or o.name.startswith(SKIP):+ continue+ if any(m.type == "FLUID" for m in o.modifiers):+ continue+ ev = o.evaluated_get(dg)+ me = ev.to_mesh()+ base = len(verts)+ verts += [o.matrix_world @ v.co for v in me.vertices]+ polys += [tuple(base + i for i in p.vertices) for p in me.polygons]+ ev.to_mesh_clear()+tree = BVHTree.FromPolygons(verts, polys)+++def catmull(p0, p1, p2, p3, t):+ return 0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + (-p0 + 3 * p1 - 3 * p2 + p3) * t ** 3)+++def sample(s, n=400):+ keys = sorted(s["keys"], key=lambda k: k["t"])+ P = [Vector(k["pos"]) for k in keys]+ T = [k["t"] for k in keys]+ out = []+ for i in range(n + 1):+ t = i / n+ j = max(0, min(len(T) - 2, next((k for k in range(len(T) - 1) if T[k] <= t <= T[k + 1]), len(T) - 2)))+ u = (t - T[j]) / max(1e-6, T[j + 1] - T[j])+ if s.get("move") == "path":+ p0, p3 = P[max(0, j - 1)], P[min(len(P) - 1, j + 2)]+ out.append((t, catmull(p0, P[j], P[j + 1], p3, u)))+ else:+ out.append((t, P[j].lerp(P[j + 1], u)))+ return out+++for name in names:+ s = shots[name]+ worst = (9, None, None)+ for t, p in sample(s):+ loc, nrm, idx, d = tree.find_nearest(p)+ if d is not None and d < worst[0]:+ worst = (d, t, p)+ flag = "OK" if worst[0] >= MIN else "TOO CLOSE"+ print(f"CAMCHECK {name}: min {worst[0]:.3f} m at t={worst[1]:.3f} pos {tuple(round(v, 2) for v in worst[2])} -> {flag}", flush=True)diff --git a/scenes/tokyo-ramen-shop/scripts/camera.py b/scenes/tokyo-ramen-shop/scripts/camera.pynew file mode 100644index 0000000..4df6f7f--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/camera.py@@ -0,0 +1,58 @@+"""Handheld phone-camera feel: a slow push with noise-driven shake (low-freq sway + high-freq jitter),+DOF on a focus target, motion blur and a slight exposure drift."""+import math++import bpy+from mathutils import Vector+++def _noise(fc, scale, strength, phase, depth=1):+ m = fc.modifiers.new("NOISE")+ m.scale = scale+ m.strength = strength+ m.phase = phase+ m.depth = depth+ return m+++def handheld(cam, start, end, target, frames=120, seed=3, sway=0.012, jitter=0.0025, rot_deg=0.55, fstop=2.2):+ sc = bpy.context.scene+ sc.frame_start, sc.frame_end = 1, frames+ cam.animation_data_clear()+ for f, p in ((1, start), (frames, end)):+ cam.location = p+ cam.rotation_euler = (Vector(target) - Vector(p)).to_track_quat("-Z", "Y").to_euler()+ cam.keyframe_insert("location", frame=f)+ cam.keyframe_insert("rotation_euler", frame=f)+ act = cam.animation_data.action+ fcurves = act.fcurves if hasattr(act, "fcurves") else act.layers[0].strips[0].channelbag(act.slots[0]).fcurves+ for fc in fcurves:+ for k in fc.keyframe_points:+ k.interpolation = "BEZIER"+ k.easing = "EASE_IN_OUT"+ i = fc.array_index+ if fc.data_path == "location":+ _noise(fc, 38, sway, seed * 10 + i * 3.1, depth=1)+ _noise(fc, 5, jitter, seed * 20 + i * 7.3, depth=0)+ else:+ _noise(fc, 45, math.radians(rot_deg), seed * 30 + i * 5.7, depth=1)+ _noise(fc, 6, math.radians(rot_deg * 0.18), seed * 40 + i * 2.9, depth=0)+ d = cam.data+ d.dof.use_dof = True+ d.dof.aperture_fstop = fstop+ d.dof.focus_distance = (Vector(target) - Vector(start)).length+ sc.render.use_motion_blur = True+ sc.render.motion_blur_shutter = 0.5+ # Exposure breathing like a phone's auto-exposure.+ vs = sc.view_settings+ base = vs.exposure+ for f, ev in ((1, base - 0.05), (frames * 0.45, base + 0.12), (frames, base - 0.02)):+ vs.exposure = ev+ vs.keyframe_insert("exposure", frame=int(f))+++def still_dof(cam, target, fstop=2.8):+ d = cam.data+ d.dof.use_dof = True+ d.dof.aperture_fstop = fstop+ d.dof.focus_distance = (Vector(target) - cam.matrix_world.translation).lengthdiff --git a/scenes/tokyo-ramen-shop/scripts/clutter.py b/scenes/tokyo-ramen-shop/scripts/clutter.pynew file mode 100644index 0000000..da865cc--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/clutter.py@@ -0,0 +1,481 @@+"""Pass B (small clutter) and pass C (micro / life), direct-modelled. Design coordinates (pre-mirror).++Paper things carry real Japanese text objects (Yu Gothic) so they read up close without generated textures:+flyers, price strips, receipts, order slips on a rail, chopstick wrappers, stickers on the ticket machine.+Everything that sits on something is dropped with dress._drop or stuck to a surface with a raycast."""+import math+import random++import bmesh+import bpy+from mathutils import Matrix, Vector++import dress+import shell as S+from lib import L, bsdf, m_simple, new_mat, noise, ramp, texcoord++FONT_B = "C:/Windows/Fonts/YuGothB.ttc"+FONT_R = "C:/Windows/Fonts/YuGothR.ttc"+rng = random.Random(11)+PLACED = []+++# ------------------------------------------------------------------ helpers++def _link(o, c):+ for uc in list(o.users_collection):+ uc.objects.unlink(o)+ c.objects.link(o)+ return o+++def m_paper(name, color, rough=0.85, grease=0.0):+ m, nt = new_mat(name)+ if nt:+ b = bsdf(nt)+ co = texcoord(nt)+ n = noise(nt, 18, 6, 0.6, co)+ col = ramp(nt, [(0.3, tuple(v * 0.86 for v in color)), (0.75, color)], n.outputs["Fac"])+ L(nt, col.outputs["Color"], b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = rough+ b.inputs["Subsurface Weight"].default_value = 0.15+ b.inputs["Subsurface Radius"].default_value = (0.01, 0.01, 0.01)+ if grease:+ g = ramp(nt, [(0.55, (0, 0, 0)), (0.62, (1, 1, 1))], noise(nt, 6, 3, 0.5, co).outputs["Fac"])+ from lib import mix+ L(nt, mix(nt, g.outputs["Color"], col.outputs["Color"], (color[0] * 0.75, color[1] * 0.65, color[2] * 0.45, 1)), b.inputs["Base Color"])+ return m+++INK = None+++def ink(color=(0.02, 0.02, 0.025), name="ink"):+ return m_simple(name, color, 0.6)+++def text(body, size, c, font=FONT_B, mat=None, align="CENTER"):+ cu = bpy.data.curves.new("txt", "FONT")+ cu.body = body+ cu.font = bpy.data.fonts.load(font, check_existing=True)+ cu.size = size+ cu.align_x = align+ cu.align_y = "CENTER"+ cu.space_line = 0.9+ o = bpy.data.objects.new("txt", cu)+ c.objects.link(o)+ cu.materials.append(mat or ink())+ return o+++def paper(name, w, h, c, mat, curl=0.0, corner=(1, 1), sag=0.0, res=(10, 14)):+ """Flat sheet in local XY (normal +Z), origin at its centre. curl lifts one corner; sag bows it."""+ me = bpy.data.meshes.new(name)+ bm = bmesh.new()+ uvl = bm.loops.layers.uv.new("UVMap")+ nx, ny = res+ vs = [[None] * (ny + 1) for _ in range(nx + 1)]+ for i in range(nx + 1):+ for j in range(ny + 1):+ u, v = i / nx, j / ny+ du = u if corner[0] else 1 - u+ dv = v if corner[1] else 1 - v+ k = max(0.0, (du + dv - 1.2) / 0.8)+ z = curl * k * k + sag * math.sin(math.pi * u) * 0.5+ vs[i][j] = bm.verts.new(((u - 0.5) * w, (v - 0.5) * h, z))+ for i in range(nx):+ for j in range(ny):+ f = bm.faces.new((vs[i][j], vs[i + 1][j], vs[i + 1][j + 1], vs[i][j + 1]))+ for lp, (a, b) in zip(f.loops, ((i, j), (i + 1, j), (i + 1, j + 1), (i, j + 1))):+ lp[uvl].uv = (a / nx, b / ny)+ bm.to_mesh(me)+ bm.free()+ o = bpy.data.objects.new(name, me)+ c.objects.link(o)+ me.materials.append(mat)+ for p in me.polygons:+ p.use_smooth = True+ o.modifiers.new("thick", "SOLIDIFY").thickness = 0.0004+ return o+++def add_text(parent, body, size, x, y, c, font=FONT_B, mat=None, align="CENTER"):+ t = text(body, size, c, font, mat, align)+ t.parent = parent+ t.location = (x, y, 0.0009)+ return t+++def stick(o, origin, direction, up=(0, 0, 1), offset=0.0012):+ """Raycast from origin along direction; put o's local +Z along the hit normal, local +Y toward `up`."""+ bpy.context.view_layer.update()+ dg = bpy.context.evaluated_depsgraph_get()+ # Volume boxes (room haze, kitchen vapor, steam domains) are meshes too: rays must pass through them.+ hidden = [o] + list(o.children) + [v for v in bpy.data.objects if v.name.startswith(("haze_volume", "kitchen_vapor", "steam_"))]+ for h in hidden:+ h.hide_set(True)+ dg.update()+ ok, loc, n, *_ = bpy.context.scene.ray_cast(dg, Vector(origin), Vector(direction).normalized())+ for h in hidden:+ h.hide_set(False)+ if not ok:+ print("STICK MISS", o.name, origin)+ return False+ z = n.normalized()+ y = (Vector(up) - Vector(up).dot(z) * z)+ if y.length < 1e-4:+ y = Vector((0, 1, 0)) - Vector((0, 1, 0)).dot(z) * z+ y.normalize()+ x = y.cross(z)+ o.matrix_world = Matrix.Translation(loc + z * offset) @ Matrix((x, y, z)).transposed().to_4x4()+ return True+++def lay(o, x, y, yaw, start_z=1.3):+ """Flat item: yaw about Z, dropped onto whatever is below (counter, shelf, floor)."""+ o.rotation_euler = (0, 0, math.radians(yaw))+ o.location = (x, y, 0)+ dress._drop(o, start_z)+ PLACED.append(o)+ return o+++def crumple(name, r, c, mat, squash=0.55, strength=0.35, seed=0):+ bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=4, radius=r)+ o = _link(bpy.context.object, c)+ o.name = name+ o.scale = (1.0, 0.85, squash)+ t = bpy.data.textures.new(name + "_tex", "VORONOI")+ t.noise_scale = r * 0.7+ d = o.modifiers.new("crumple", "DISPLACE")+ d.texture = t+ d.strength = r * strength+ d.texture_coords = "LOCAL"+ o.data.materials.append(mat)+ bpy.ops.object.shade_smooth()+ o.location = (0, 0, -20 - seed)+ return o+++def curve_obj(name, pts, c, mat, radius, res=8):+ cu = bpy.data.curves.new(name, "CURVE")+ cu.dimensions = "3D"+ cu.bevel_depth = radius+ cu.bevel_resolution = 3+ cu.resolution_u = res+ sp = cu.splines.new("NURBS")+ sp.points.add(len(pts) - 1)+ for p, co in zip(sp.points, pts):+ p.co = (*co, 1)+ sp.use_endpoint_u = True+ sp.order_u = min(4, len(pts))+ o = bpy.data.objects.new(name, cu)+ c.objects.link(o)+ cu.materials.append(mat)+ return o+++def catenary(a, b, sag, n=12):+ a, b = Vector(a), Vector(b)+ return [tuple(a.lerp(b, t) - Vector((0, 0, sag * 4 * t * (1 - t)))) for t in (i / (n - 1) for i in range(n))]+++# ------------------------------------------------------------------ pass B: small clutter++def coin(kind, c):+ spec = {"100": (0.0113, (0.75, 0.75, 0.74)), "500": (0.0132, (0.8, 0.68, 0.42)),+ "10": (0.0118, (0.6, 0.33, 0.18)), "1": (0.01, (0.82, 0.82, 0.82))}[kind]+ bpy.ops.mesh.primitive_cylinder_add(radius=spec[0], depth=0.0017, vertices=28)+ o = _link(bpy.context.object, c)+ o.name = "coin_" + kind+ o.data.materials.append(m_simple("coin_" + kind, spec[1], 0.32, 1.0))+ bpy.ops.object.shade_smooth()+ return o+++def noodle(c, x, y, z, seed):+ r = random.Random(seed)+ pts, p, a = [], Vector((x, y, z + 0.0012)), r.uniform(0, 6.28)+ for i in range(26):+ a += r.uniform(-0.7, 0.7)+ p = p + Vector((math.cos(a), math.sin(a), 0)) * 0.009+ pts.append(tuple(p))+ return curve_obj("dropped_noodle", pts, c, m_simple("noodle", (0.78, 0.62, 0.3), 0.35), 0.0011)+++def pass_b(c):+ PLACED.clear()+ white_paper = m_paper("paper_white", (0.86, 0.85, 0.8))+ thermal = m_paper("paper_thermal", (0.9, 0.9, 0.87), 0.5)+ cx = S.CX + 0.3+ # Chopstick wrappers (red おてもと paper), some flat, one crumpled, by the seats.+ wrap = m_paper("wrapper_red", (0.38, 0.035, 0.03), 0.6)+ white_ink = ink((0.85, 0.82, 0.75), "ink_white")+ for i, (x, y, yaw) in enumerate([(S.CX + 0.1, 3.42, 70), (S.CX + 0.22, 5.12, 100), (S.CX + 0.08, 2.18, 12)]):+ w = paper("chopstick_wrapper", 0.032, 0.2, c, wrap, curl=0.004, sag=0.003)+ add_text(w, "お\nて\nも\nと", 0.012, 0, 0.02, c, mat=white_ink)+ lay(w, x, y, yaw)+ cw = crumple("wrapper_crumpled", 0.012, c, wrap, squash=0.6, seed=1)+ lay(cw, S.CX + 0.24, 3.55, 0)+ # Used napkins.+ for i, (x, y) in enumerate([(S.CX + 0.06, 2.93), (S.CX + 0.13, 2.86), (S.CX + 0.07, 5.0), (S.CX + 0.28, 2.0)]):+ n = crumple("napkin_used", rng.uniform(0.022, 0.032), c, m_paper("napkin", (0.88, 0.86, 0.8), 0.95), seed=i + 3)+ lay(n, x, y, rng.uniform(0, 360))+ # Receipts: curled thermal paper with printed lines, one on the counter, one on the pass, one on the floor.+ for i, (x, y, yaw, z0) in enumerate([(S.CX + 0.3, 4.15, 15, 1.3), (S.PASS_X + 0.1, 2.75, -30, 1.5), (0.7, 2.9, 60, 0.6)]):+ r = paper("receipt", 0.058, 0.17, c, thermal, curl=0.02, corner=(0, 1), sag=0.012)+ add_text(r, "ラーメン一番\n─────────\n醤油ラーメン ¥800\n味玉 ¥150\n生ビール ¥500\n─────────\n合計 ¥1,450\nお預り ¥2,000\nお釣り ¥550", 0.0052, 0, 0.0, c, FONT_R, ink((0.15, 0.15, 0.16), "ink_thermal"))+ lay(r, x, y, yaw, z0)+ # Coins left on the counter by the bowl.+ for i, k in enumerate(["100", "100", "10", "500", "1", "10"]):+ co = coin(k, c)+ lay(co, S.CX + 0.27 + rng.uniform(-0.03, 0.03), 3.05 + rng.uniform(-0.03, 0.03), rng.uniform(0, 360))+ co.rotation_euler.x = math.radians(rng.uniform(-4, 4))+ # A dropped noodle by the unfinished bowl, another on the prep counter.+ noodle(c, S.CX + 0.12, 3.12, S.CH, 1)+ noodle(c, 2.05, 3.25, 0.88, 2)+ # Order slips clipped to a rail on the hood front (faces the customers).+ hx = S.W - 0.75+ from lib import box+ box("order_rail", (hx - 0.03, 3.6, 1.98), (hx, 4.9, 2.01), c, m_simple("rail_steel", (0.6, 0.6, 0.6), 0.25, 1.0), 0.003)+ slips = ["醤油 2\n味玉 1\n大盛", "味噌 1\n餃子 2", "塩 1\nライス", "つけ麺 1\n生 2", "チャーシュー 1\n替玉"]+ for i, body in enumerate(slips):+ s = paper("order_slip", 0.075, 0.11, c, m_paper("slip", (0.93, 0.92, 0.86), grease=0.4), curl=0.008, corner=(i % 2, 0))+ add_text(s, body, 0.012, 0, 0.005, c, FONT_R, ink((0.05, 0.06, 0.2), "ink_pen"))+ # Hang from the rail: sheet faces -X (customers) with text upright.+ s.matrix_world = Matrix.Translation((hx - 0.035, 3.72 + i * 0.25 + rng.uniform(-0.03, 0.03), 1.94)) @ \+ Matrix.Rotation(math.radians(-90), 4, "Z") @ Matrix.Rotation(math.radians(90), 4, "X") @ Matrix.Rotation(math.radians(rng.uniform(-6, 6)), 4, "Z")+ PLACED.append(s)+ # Spice tins and jars on the pass and back shelf.+ tin_cols = [(0.6, 0.08, 0.05), (0.75, 0.55, 0.1), (0.1, 0.25, 0.12)]+ labels = ["七味", "胡椒", "山椒"]+ for i, (x, y, z0) in enumerate([(S.PASS_X + 0.08, 3.95, 1.5), (S.PASS_X + 0.13, 4.0, 1.5), (S.W - 0.08, 2.15, 1.9), (S.W - 0.1, 6.45, 1.9)]):+ bpy.ops.mesh.primitive_cylinder_add(radius=0.022, depth=0.07, vertices=24)+ t = _link(bpy.context.object, c)+ t.name = "spice_tin"+ t.data.materials.append(m_simple("tin_" + labels[i % 3], tin_cols[i % 3], 0.35, 0.6))+ bpy.ops.object.shade_smooth()+ lay(t, x, y, rng.uniform(0, 360), z0)+ lab = text(labels[i % 3], 0.014, c, mat=ink((0.95, 0.9, 0.75), "ink_cream"))+ lab.parent = t+ lab.location = (0, -0.0225, 0.0)+ lab.rotation_euler = (math.radians(90), 0, 0)+ glass = m_simple("jar_glass", (0.95, 0.97, 0.96), 0.03, trans=1.0)+ for i, (x, y, z0, col) in enumerate([(S.W - 0.12, 2.55, 2.55, (0.75, 0.55, 0.3)), (S.W - 0.1, 6.95, 2.55, (0.55, 0.1, 0.05)), (2.3, 4.25, 1.2, (0.9, 0.85, 0.7))]):+ bpy.ops.mesh.primitive_cylinder_add(radius=0.045, depth=0.12, vertices=32)+ j = _link(bpy.context.object, c)+ j.name = "jar"+ j.data.materials.append(glass)+ bpy.ops.object.shade_smooth()+ lay(j, x, y, 0, z0)+ bpy.ops.mesh.primitive_cylinder_add(radius=0.041, depth=0.08, vertices=32)+ f = _link(bpy.context.object, c)+ f.name = "jar_fill"+ f.data.materials.append(m_simple(f"jar_fill_{i}", col, 0.7))+ f.parent = j+ f.location = (0, 0, -0.018)+ bpy.ops.mesh.primitive_cylinder_add(radius=0.047, depth=0.018, vertices=32)+ l = _link(bpy.context.object, c)+ l.name = "jar_lid"+ l.data.materials.append(m_simple("jar_lid", (0.6, 0.05, 0.04), 0.4, 0.5))+ l.parent = j+ l.location = (0, 0, 0.068)+ # Tape roll and marker by the register.+ bpy.ops.mesh.primitive_torus_add(major_radius=0.034, minor_radius=0.013, major_segments=32, minor_segments=12)+ tp = _link(bpy.context.object, c)+ tp.name = "tape_roll"+ tp.scale = (1, 1, 1.4)+ tp.data.materials.append(m_simple("packing_tape", (0.55, 0.36, 0.15), 0.25, trans=0.3))+ lay(tp, S.W - 0.45, 2.25, 0)+ # Towel folded over the pass edge: the picked hand-towel prop, laid on the pass top.+ t = dress._instance("ramen_hand_towel", c)+ if t:+ t.rotation_mode = "XYZ"+ lay(t, S.PASS_X + 0.1, 4.95, 80, 1.5)+ # Ladle and tongs on the prep counter: thin steel bars / bowls.+ steel = m_simple("utensil_steel", (0.65, 0.65, 0.66), 0.22, 1.0)+ for i, (x, y, yaw) in enumerate([(2.1, 4.25, 20), (2.15, 4.35, 35)]):+ bpy.ops.mesh.primitive_cube_add(size=1)+ tg = _link(bpy.context.object, c)+ tg.name = "tongs"+ tg.scale = (0.012, 0.26, 0.004)+ tg.data.materials.append(steel)+ lay(tg, x, y, yaw)+ return PLACED+++# ------------------------------------------------------------------ pass C: micro / life++def flyer(c, name, w, h, color, body, size, origin, direction, up=(0, 0, 1), curl=0.025, ink_col=(0.03, 0.03, 0.04), extra=None):+ f = paper(name, w, h, c, m_paper(name + "_paper", color, grease=0.4), curl=curl, corner=(rng.random() > 0.5, 1))+ add_text(f, body, size, 0, h * 0.12, c, mat=ink(ink_col, name + "_ink"))+ if extra:+ extra(f)+ stick(f, origin, direction, up)+ # Tape or pins at the top corners.+ for sx in (-1, 1):+ if rng.random() < 0.5:+ bpy.ops.mesh.primitive_uv_sphere_add(radius=0.005, segments=12, ring_count=8)+ p = _link(bpy.context.object, c)+ p.data.materials.append(m_simple("pushpin_" + str(sx), (0.8, 0.1, 0.08) if sx > 0 else (0.1, 0.3, 0.8), 0.3))+ else:+ bpy.ops.mesh.primitive_plane_add(size=1)+ p = _link(bpy.context.object, c)+ p.scale = (0.045, 0.02, 1)+ p.data.materials.append(m_simple("tape_clear", (0.85, 0.8, 0.6), 0.35, alpha=0.5))+ p.parent = f+ p.location = (sx * w * 0.42, h * 0.47, 0.0015)+ p.rotation_euler = (0, 0, math.radians(rng.uniform(-25, 25)))+ PLACED.append(f)+ return f+++def sticker(c, shape, size, color, body, txt_col, origin, direction, up=(0, 0, 1), curl=0.0):+ if shape == "circle":+ bpy.ops.mesh.primitive_circle_add(vertices=32, radius=size / 2, fill_type="NGON")+ s = _link(bpy.context.object, c)+ s.modifiers.new("thick", "SOLIDIFY").thickness = 0.0003+ else:+ s = paper("sticker", size, size * 0.62, c, None, curl=curl, res=(6, 6))+ s.data.materials.clear()+ s.name = "sticker"+ s.data.materials.append(m_simple("sticker_" + body, color, 0.45, coat=0.4))+ add_text(s, body, size * 0.22, 0, 0, c, mat=ink(txt_col, "ink_" + body))+ stick(s, origin, direction, up, 0.0008)+ PLACED.append(s)+ return s+++def pass_c(c):+ PLACED.clear()+ yellowed = (0.86, 0.8, 0.6)+ # Flyers on the customer wall (x=0, facing +X) and by the door.+ flyer(c, "flyer_parttime", 0.21, 0.297, yellowed, "アルバイト\n募集\n\n時給 1,200円〜\n深夜手当あり\n\n店主まで", 0.024,+ (0.5, 2.75, 1.42), (-1, 0, 0))+ flyer(c, "flyer_lostcat", 0.21, 0.297, (0.9, 0.9, 0.88), "迷い猫\n探しています\n\n\n\n\n茶トラ・オス\n090-XXXX-XXXX", 0.022,+ (0.5, 5.1, 1.38), (-1, 0, 0),+ extra=lambda f: _photo_block(f, c, 0.12, 0.08, 0.0, -0.005))+ flyer(c, "flyer_festival", 0.21, 0.297, (0.92, 0.55, 0.2), "夏祭り\n\n盆踊り・夜店\n8月 第一土曜\n商店街振興会", 0.026,+ (0.5, 1.62, 1.42), (-1, 0, 0), ink_col=(0.25, 0.04, 0.02))+ # Price strips (yellow paper, vertical text) on the customer wall above the wainscot rail.+ items = [("生ビール", "500円"), ("瓶ビール", "650円"), ("ハイボール", "450円"), ("日本酒", "550円"),+ ("ウーロン茶", "200円"), ("餃子", "400円"), ("チャーハン", "700円"), ("替玉", "150円")]+ for i, (name, price) in enumerate(items):+ s = paper("price_strip", 0.07, 0.36, c, m_paper("strip_yellow", (0.92, 0.78, 0.25), grease=0.5), curl=0.006, corner=(0, 0), res=(4, 12))+ add_text(s, "\n".join(name), 0.034, 0, 0.04, c)+ add_text(s, price, 0.016, 0, -0.15, c, mat=ink((0.7, 0.05, 0.03), "ink_red"))+ stick(s, (0.5, 4.12 + i * 0.085, 2.05), (-1, 0, 0))+ s.matrix_world = s.matrix_world @ Matrix.Rotation(math.radians(rng.uniform(-2, 2)), 4, "Z")+ PLACED.append(s)+ # Stickers on the ticket machine side and front (lower panel) — sticky, layered, one peeling.+ tm = bpy.data.objects.get("ticket_machine")+ if tm:+ lo, hi = dress._footprint_world(tm)+ side_x = hi.x + 0.3+ for (shape, size, col, body, tcol, y, z, curl) in [+ ("rect", 0.09, (0.85, 0.1, 0.08), "現金のみ", (1, 1, 1), lo.y + 0.12, 1.1, 0.0),+ ("circle", 0.07, (0.95, 0.8, 0.1), "千円札\nOK", (0.1, 0.1, 0.1), lo.y + 0.28, 1.05, 0.0),+ ("rect", 0.1, (0.1, 0.35, 0.75), "交通系IC\n使えません", (1, 1, 1), lo.y + 0.2, 0.85, 0.012),+ ("rect", 0.07, (0.95, 0.95, 0.92), "禁煙", (0.8, 0.05, 0.05), lo.y + 0.33, 0.7, 0.0),+ ]:+ sticker(c, shape, size, col, body, tcol, (side_x, y, z), (-1, 0, 0), curl=curl)+ front_y = hi.y + 0.3+ for (shape, size, col, body, tcol, x, z) in [+ ("rect", 0.08, (0.9, 0.9, 0.85), "食券を\nお買い求め\nください", (0.1, 0.1, 0.1), lo.x + 0.15, 0.45),+ ("circle", 0.06, (0.85, 0.15, 0.4), "PAY", (1, 1, 1), lo.x + 0.45, 0.5),+ ]:+ sticker(c, shape, size, col, body, tcol, (x, front_y, z), (0, -1, 0))+ # Conduit along the customer wall/ceiling corner and down to the ticket machine; cable to the CRT.+ pvc = m_simple("conduit_pvc", (0.55, 0.55, 0.52), 0.55)+ curve_obj("conduit_top", [(0.03, 0.3, 2.56), (0.03, 3.5, 2.56), (0.03, 6.9, 2.56)], c, pvc, 0.011)+ curve_obj("conduit_down", [(0.03, 0.3, 2.56), (0.03, 0.3, 2.0), (0.03, 0.3, 1.62)], c, pvc, 0.011)+ for y in (0.9, 1.9, 2.9, 3.9, 4.9, 5.9):+ bpy.ops.mesh.primitive_cube_add(size=1, location=(0.025, y, 2.56))+ k = _link(bpy.context.object, c)+ k.scale = (0.02, 0.025, 0.03)+ k.data.materials.append(pvc)+ black = m_simple("cable_black", (0.015, 0.015, 0.015), 0.45)+ white_cable = m_simple("cable_white", (0.7, 0.7, 0.66), 0.5)+ curve_obj("crt_cable", catenary((S.W - 0.02, 0.5, 2.5), (S.W - 0.18, 0.45, 2.15), 0.06), c, black, 0.003)+ # Cables sagging between the pendant cords (pendants are on the pass line).+ for i in range(len(S.PENDANT_Y) - 1):+ curve_obj("pendant_cable", catenary((S.CX + 0.22, S.PENDANT_Y[i], 2.58), (S.CX + 0.22, S.PENDANT_Y[i + 1], 2.58), 0.12), c, black, 0.0035)+ # Extension cord along the floor from the wall to the drink fridge, and a power strip by the rice cooker.+ curve_obj("ext_cord", [(0.03, 4.8, 0.32), (0.04, 4.9, 0.006), (0.25, 5.3, 0.006), (0.12, 5.9, 0.006), (0.3, 6.3, 0.006)], c, white_cable, 0.0035)+ bpy.ops.mesh.primitive_cube_add(size=1)+ ps = _link(bpy.context.object, c)+ ps.name = "power_strip"+ ps.scale = (0.26, 0.05, 0.03)+ ps.data.materials.append(m_simple("strip_plastic", (0.8, 0.79, 0.74), 0.5))+ lay(ps, 0.35, 6.25, 80, 0.6)+ bpy.ops.mesh.primitive_cube_add(size=1, location=(0.012, 4.8, 0.35))+ ob = _link(bpy.context.object, c)+ ob.name = "wall_outlet"+ ob.scale = (0.02, 0.07, 0.11)+ ob.data.materials.append(m_simple("outlet", (0.82, 0.8, 0.74), 0.45))+ # Cat food dish and water bowl just inside the door, on a placemat.+ mat_o = paper("cat_placemat", 0.32, 0.22, c, m_simple("placemat", (0.35, 0.55, 0.7), 0.5), res=(4, 4))+ lay(mat_o, 1.0, 0.55, 8, 0.5)+ bowl_steel = m_simple("pet_bowl", (0.7, 0.7, 0.71), 0.18, 1.0)+ for i, (dx, fill) in enumerate([(-0.075, "kibble"), (0.075, "water")]):+ bpy.ops.mesh.primitive_cone_add(vertices=40, radius1=0.05, radius2=0.068, depth=0.04, end_fill_type="NOTHING")+ b = _link(bpy.context.object, c)+ b.name = "pet_bowl"+ b.data.materials.append(bowl_steel)+ b.modifiers.new("thick", "SOLIDIFY").thickness = 0.002+ bpy.ops.object.shade_smooth()+ lay(b, 1.0 + dx, 0.55, 0, 0.5)+ bpy.ops.mesh.primitive_circle_add(vertices=40, radius=0.05, fill_type="NGON", location=(0, 0, -0.019))+ bot = _link(bpy.context.object, c)+ bot.data.materials.append(bowl_steel)+ bot.parent = b+ bot.location = (0, 0, -0.019)+ if fill == "water":+ bpy.ops.mesh.primitive_circle_add(vertices=40, radius=0.058, fill_type="NGON")+ w = _link(bpy.context.object, c)+ w.data.materials.append(m_simple("pet_water", (0.9, 0.95, 0.95), 0.02, trans=1.0, ior=1.33))+ w.parent = b+ w.location = (0, 0, -0.002)+ else:+ me = bpy.data.meshes.new("kibble")+ bm = bmesh.new()+ r = random.Random(5)+ for k in range(70):+ a, rr = r.uniform(0, 6.28), 0.05 * math.sqrt(r.random())+ bmesh.ops.create_icosphere(bm, subdivisions=1, radius=0.0045,+ matrix=Matrix.Translation((rr * math.cos(a), rr * math.sin(a), -0.012 + r.uniform(0, 0.012))) @ Matrix.Diagonal((1, 0.8, 0.6, 1)))+ bm.to_mesh(me)+ bm.free()+ kb = bpy.data.objects.new("kibble", me)+ c.objects.link(kb)+ me.materials.append(m_simple("kibble", (0.32, 0.17, 0.07), 0.6))+ kb.parent = b+ # Keys and a plastic bag on a hook by the kitchen entrance; a calendar-side hook with a fly swatter.+ hook_mat = m_simple("hook_metal", (0.3, 0.3, 0.3), 0.4, 1.0)+ # Hooks on the back wall of the kitchen (y = D, facing -Y), next to the apron.+ for i, x in enumerate((2.3, 2.42)):+ curve_obj("wall_hook", [(x, S.D - 0.005, 1.5), (x, S.D - 0.045, 1.47), (x, S.D - 0.045, 1.52)], c, hook_mat, 0.003)+ bpy.ops.mesh.primitive_torus_add(major_radius=0.014, minor_radius=0.0012, location=(2.3, S.D - 0.04, 1.45))+ kr = _link(bpy.context.object, c)+ kr.name = "key_ring"+ kr.rotation_euler = (math.radians(90), 0, 0)+ kr.data.materials.append(m_simple("key_metal", (0.75, 0.68, 0.45), 0.3, 1.0))+ for j in range(3):+ bpy.ops.mesh.primitive_cube_add(size=1, location=(2.3 + (j - 1) * 0.008, S.D - 0.04, 1.415 - j * 0.004))+ k = _link(bpy.context.object, c)+ k.scale = (0.012, 0.002, 0.05)+ k.rotation_euler = (0, math.radians((j - 1) * 14), 0)+ k.data.materials.append(m_simple("key_metal", (0.75, 0.68, 0.45), 0.3, 1.0))+ bag = crumple("plastic_bag", 0.09, c, m_simple("bag_plastic", (0.9, 0.9, 0.88), 0.3, trans=0.4), squash=1.6, strength=0.25, seed=9)+ bag.location = (2.42, S.D - 0.07, 1.34)+ bag.scale = (0.9, 0.5, 1.4)+ return PLACED+++def _photo_block(f, c, w, h, x, y):+ bpy.ops.mesh.primitive_plane_add(size=1)+ p = _link(bpy.context.object, c)+ p.scale = (w, h, 1)+ p.data.materials.append(m_simple("photo_grey", (0.35, 0.28, 0.2), 0.4))+ p.parent = f+ p.location = (x, y, 0.0008)diff --git a/scenes/tokyo-ramen-shop/scripts/compare.py b/scenes/tokyo-ramen-shop/scripts/compare.pynew file mode 100644index 0000000..a899cbe--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/compare.py@@ -0,0 +1,205 @@+"""Ramen copy of pipeline/render_compare.py: only tripo-h31 + meshy, filtered by env PROPS, 640 px / 40 spp.++blender -b --factory-startup --python pipeline/render_compare.py -- assets/gen out/compare+For every assets/gen/<model>/<prop>/model.glb writes out/compare/<model>/<prop>_{beauty,clay}.png + stats.json.+"""+import json+import math+import os+import sys++import bpy+from mathutils import Vector++ROOT, OUT = map(os.path.abspath, sys.argv[sys.argv.index("--") + 1:][:2])+HDRI = bpy.utils.system_resource("DATAFILES", path="studiolights/world/studio.exr")+RES = 640+PROBE = bool(os.environ.get("PROBE"))+# Camera azimuth offset per generator so the "front" view faces the side the reference image shows.+_yaw_path = os.path.join(OUT, "yaw.json")+YAW = json.load(open(_yaw_path)) if os.path.exists(_yaw_path) else {}+++def reset():+ bpy.ops.wm.read_factory_settings(use_empty=True)+ sc = bpy.context.scene+ sc.render.engine = "CYCLES"+ prefs = bpy.context.preferences.addons["cycles"].preferences+ prefs.compute_device_type = "OPTIX"+ prefs.get_devices()+ for d in prefs.devices:+ d.use = d.type == "OPTIX"+ sc.cycles.device = "GPU"+ sc.cycles.samples = 40+ sc.cycles.use_denoising = True+ sc.render.resolution_x = sc.render.resolution_y = RES+ sc.render.film_transparent = False+ sc.view_settings.view_transform = "AgX"+ sc.view_settings.look = "AgX - Medium High Contrast"+ world = bpy.data.worlds.new("w")+ sc.world = world+ world.use_nodes = True+ nt = world.node_tree+ env = nt.nodes.new("ShaderNodeTexEnvironment")+ env.image = bpy.data.images.load(HDRI)+ bg = nt.nodes["Background"]+ bg.inputs["Strength"].default_value = 0.6+ nt.links.new(env.outputs["Color"], bg.inputs["Color"])+ return sc+++def add_light(name, loc, 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(loc)).to_track_quat("-Z", "Y").to_euler() # area lights shine along -Z+++def import_glb(path):+ before = set(bpy.data.objects)+ bpy.ops.import_scene.gltf(filepath=path)+ meshes = [o for o in bpy.data.objects if o not in before and o.type == "MESH"]+ return meshes+++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 stats(objs, real_size):+ tris = verts = 0+ images = {}+ for o in objs:+ me = o.data+ me.calc_loop_triangles()+ tris += len(me.loop_triangles)+ verts += len(me.vertices)+ for slot in o.material_slots:+ if slot.material and slot.material.use_nodes:+ for n in slot.material.node_tree.nodes:+ if n.type == "TEX_IMAGE" and n.image:+ out = [l.to_socket.name for l in n.outputs["Color"].links]+ images[n.image.name] = {"size": list(n.image.size), "feeds": out}+ return {"tris": tris, "verts": verts, "objects": len(objs), "images": images, "size_m": [round(v, 3) for v in real_size]}+++def clay_wire(objs):+ m = bpy.data.materials.new("clay")+ m.use_nodes = True+ nt = m.node_tree+ bsdf = nt.nodes["Principled BSDF"]+ bsdf.inputs["Base Color"].default_value = (0.55, 0.55, 0.55, 1)+ bsdf.inputs["Roughness"].default_value = 0.6+ wire = nt.nodes.new("ShaderNodeWireframe")+ wire.use_pixel_size = True+ wire.inputs["Size"].default_value = 0.35+ mix = nt.nodes.new("ShaderNodeMix")+ mix.data_type = "RGBA"+ mix.inputs["A"].default_value = (0.55, 0.55, 0.55, 1)+ mix.inputs["B"].default_value = (0.08, 0.12, 0.2, 1)+ nt.links.new(wire.outputs["Fac"], mix.inputs["Factor"])+ nt.links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])+ for o in objs:+ o.data.materials.clear()+ o.data.materials.append(m)+++def render_one(glb, out_prefix):+ sc = reset()+ objs = import_glb(glb)+ lo, hi = bounds(objs)+ real = hi - lo+ # Normalize: centre on origin, rest on the floor, largest dimension 1 m (framing only; real size goes in stats).+ s = 1.0 / max(real)+ root = bpy.data.objects.new("root", None)+ sc.collection.objects.link(root)+ for o in [o for o in bpy.data.objects if o.parent is None and o is not root]:+ o.parent = root+ c = (lo + hi) / 2+ root.scale = (s, s, s)+ root.location = (-c.x * s, -c.y * s, -lo.z * s)+ bpy.context.view_layer.update()+ lo, hi = bounds(objs)+ centre = (lo + hi) / 2+ radius = (hi - lo).length / 2++ # Shadow catcher-ish floor.+ bpy.ops.mesh.primitive_plane_add(size=20)+ floor = bpy.context.object+ fm = bpy.data.materials.new("floor")+ fm.use_nodes = True+ fm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.32, 0.32, 0.33, 1)+ fm.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.8+ floor.data.materials.append(fm)++ add_light("key", (2.2, -2.6, 3.0), 260, 1.6)+ add_light("fill", (-3.0, -1.5, 1.6), 70, 2.5, (0.85, 0.9, 1.0))+ add_light("rim", (-1.0, 3.0, 2.5), 160, 1.2)++ cam_d = bpy.data.cameras.new("cam")+ cam_d.lens = 70+ cam = bpy.data.objects.new("cam", cam_d)+ sc.collection.objects.link(cam)+ sc.camera = cam+ fov = cam_d.angle+ dist = radius / math.sin(fov / 2) * 1.02++ def shoot(az_deg, el_deg, path):+ az, el = math.radians(az_deg), math.radians(el_deg)+ d = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))+ cam.location = centre + d * dist+ cam.rotation_euler = (centre - cam.location).to_track_quat("-Z", "Y").to_euler()+ sc.render.filepath = path+ bpy.ops.render.render(write_still=True)++ st = stats(objs, real)+ if PROBE: # four cardinal views to find which way a generator's "front" faces+ sc.render.resolution_x = sc.render.resolution_y = 360+ sc.cycles.samples = 16+ for az in (0, 90, 180, 270):+ shoot(az, 15, f"{out_prefix}_az{az:03d}.png")+ return st+ yaw = YAW.get(os.path.basename(os.path.dirname(out_prefix)), 0)+ shoot(yaw - 30, 18, out_prefix + "_beauty.png")+ shoot(yaw + 150, 22, out_prefix + "_back.png")+ clay_wire(objs)+ shoot(yaw - 30, 18, out_prefix + "_clay.png")+ return st+++def main():+ allstats = {}+ keep = set(os.environ["PROPS"].split(",")) if os.environ.get("PROPS") else None+ for model in [m for m in sorted(os.listdir(ROOT)) if m in ("tripo-h31", "meshy")]:+ for prop in sorted(os.listdir(os.path.join(ROOT, model))):+ if keep and prop not in keep:+ continue+ glb = os.path.join(ROOT, model, prop, "model.glb")+ if not os.path.exists(glb):+ continue+ od = os.path.join(OUT, model)+ os.makedirs(od, exist_ok=True)+ prefix = os.path.join(od, prop)+ done = prefix + ("_az270.png" if PROBE else "_clay.png")+ if os.path.exists(done) and os.path.getmtime(done) > os.path.getmtime(glb):+ print("skip", model, prop)+ continue+ print("render", model, prop, flush=True)+ try:+ allstats.setdefault(model, {})[prop] = render_one(glb, prefix)+ except Exception as e: # keep going; a broken GLB is itself a result+ allstats.setdefault(model, {})[prop] = {"error": repr(e)}+ print("FAILED", model, prop, e, flush=True)+ sp = os.path.join(OUT, "stats.json")+ old = json.load(open(sp)) if os.path.exists(sp) else {}+ for m, d in allstats.items():+ old.setdefault(m, {}).update(d)+ json.dump(old, open(sp, "w"), indent=2)+++main()diff --git a/scenes/tokyo-ramen-shop/scripts/compare_rest.sh b/scenes/tokyo-ramen-shop/scripts/compare_rest.shnew file mode 100644index 0000000..31c7bb6--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/compare_rest.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Wait for generation, then compare the remaining placed round-2 props and build one review sheet.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh+until grep -q "all done" logs/ramen_gen_fix.log; do sleep 30; done+P=ramen_vending_machine_nb,ramen_radio_nb,ramen_tape_roll_nb,ramen_hook_items_nb,ramen_coat_hooks_nb,ramen_napkins_used,ramen_towel_crumpled,ramen_junction_box,ramen_kamidana,ramen_daruma,ramen_beni_shoga_pot+PROPS=$P bash pipeline/gpu_run.sh "$B" -b --factory-startup --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/compare.py -- assets/gen scenes/tokyo-ramen-shop/compare 2>&1 | grep -cE "^render"+IFS=, read -ra A <<< "$P"+bash scenes/tokyo-ramen-shop/scripts/review.sh scenes/tokyo-ramen-shop/compare/review_r2_5.png "${A[@]:0:6}"+bash scenes/tokyo-ramen-shop/scripts/review.sh scenes/tokyo-ramen-shop/compare/review_r2_6.png "${A[@]:6:6}"+echo "COMPARED"; grep -c FAIL logs/ramen_gen_fix.logdiff --git a/scenes/tokyo-ramen-shop/scripts/dress.py b/scenes/tokyo-ramen-shop/scripts/dress.pynew file mode 100644index 0000000..8d3d4d6--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/dress.py@@ -0,0 +1,340 @@+"""Dress the ramen shop with prepped props (scenes/tokyo-ramen-shop/lib/<id>.blend). Design coordinates (pre-mirror).++place(): big props first, small last. Each prop rests on whatever is under its footprint (raycast drop),+or snaps its back against a wall, or hangs at a fixed height. Repeats share mesh data (linked duplicates).+Facing: 0 = front toward the street (-Y), 90 = toward +X, -90 = toward -X, 180 = toward the back.+"""+import math+import os+import random++import bpy+from mathutils import Vector++import shell as S+from lib import SCENE_DIR++LIB = os.path.join(SCENE_DIR, "lib")+_loaded = {}+PLACED = [] # (obj, mode) for the validator+BRANDED = {"ramen_shelf_jars", "ramen_spice_tins", "ramen_cardboard_boxes", "ramen_flour_sacks", "ramen_beer_bottle_glass",+ "ramen_lighter_cigs", "ramen_vending_machine", "ramen_radio", "ramen_tape_roll", "ramen_hook_items", "ramen_coat_hooks"}+MIRROR = False # set by patch scripts that dress the saved (already mirrored) .blend+rng = random.Random(7)+++def _load(pid):+ if pid in _loaded:+ return _loaded[pid]+ path = os.path.join(LIB, pid + ".blend")+ if not os.path.exists(path):+ print("MISSING prop", pid)+ _loaded[pid] = None+ return None+ with bpy.data.libraries.load(path, link=False) as (src, dst):+ dst.objects = list(src.objects)+ objs = [o for o in dst.objects if o]+ root = next(o for o in objs if o.name.split(".")[0] == pid)+ _loaded[pid] = (root, [o for o in objs if o is not root])+ return _loaded[pid]+++def _instance(pid, c):+ got = _load(pid)+ if not got:+ return None+ root, kids = got+ if root.users_collection:+ o = root.copy() # linked duplicate: shares mesh + materials+ c.objects.link(o)+ for k in kids:+ kk = k.copy()+ c.objects.link(kk)+ kk.parent = o+ else:+ o = root+ c.objects.link(o)+ for k in kids:+ c.objects.link(k)+ return o+++def _footprint_world(o):+ bpy.context.view_layer.update()+ pts = [o.matrix_world @ Vector(cc) for cc 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 _drop(o, start_z=3.0):+ """Lower the object onto the highest surface under its footprint (5x5 grid of downward rays)."""+ lo, hi = _footprint_world(o)+ dg = bpy.context.evaluated_depsgraph_get()+ hide = o.hide_get()+ o.hide_set(True)+ for ch in o.children:+ ch.hide_set(True)+ dg.update()+ top = None+ for i in range(5):+ for j in range(5):+ x = lo.x + (hi.x - lo.x) * (0.1 + 0.8 * i / 4)+ y = lo.y + (hi.y - lo.y) * (0.1 + 0.8 * j / 4)+ ok, loc, _n, _idx, hit, _m = bpy.context.scene.ray_cast(dg, Vector((x, y, start_z)), Vector((0, 0, -1)))+ if ok and hit is not o and (top is None or loc.z > top):+ top = loc.z+ o.hide_set(hide)+ for ch in o.children:+ ch.hide_set(False)+ if top is not None:+ o.location.z += top - lo.z + 0.0005+++def place(pid, c, x, y, z=None, facing=0.0, jitter=0.0, against=None, gap=0.01, mode="rest", scale=1.0, start_z=None):+ """mode: rest (drop onto support), hang (fixed z = bottom height). against: 'x-','x+','y-','y+' wall plane+ value is taken from x or y (the wall coordinate); the prop's back is pushed to it."""+ if pid in BRANDED:+ # Generated with real brands on the labels: only the de-branded regeneration may be placed.+ pid = pid + "_nb" if _have(pid + "_nb") else None+ if pid is None:+ return None+ if MIRROR:+ # Patching an already-mirrored scene: same design coordinates, converted the way build.mirror_x would.+ x = S.W - x+ facing = -facing+ against = {"x-": "x+", "x+": "x-"}.get(against, against)+ o = _instance(pid, c)+ if o is None:+ return None+ o.rotation_mode = "XYZ" # glTF-imported props come in quaternion mode+ o.rotation_euler = (0, 0, math.radians(facing + rng.uniform(-jitter, jitter)))+ o.scale = (scale, scale, scale)+ o.location = (x, y, 0 if z is None else z)+ if against:+ lo, hi = _footprint_world(o)+ if against == "x-":+ o.location.x += (x + gap) - lo.x+ elif against == "x+":+ o.location.x += (x - gap) - hi.x+ elif against == "y+":+ o.location.y += (y - gap) - hi.y+ elif against == "y-":+ o.location.y += (y + gap) - lo.y+ if mode == "rest":+ _drop(o, start_z if start_z is not None else 1.3) # below the hood and wall shelves+ PLACED.append((o, mode))+ return o+++def build(c):+ PLACED.clear()+ KX_TOP = 0.88+ # ---- big props+ t = place("ticket_machine", c, 0.0, 0.0, facing=180, against="x-")+ t.location.y += 0.03 - _footprint_world(t)[0].y # back against the front wall, face toward the shop+ place("ramen_drink_fridge", c, 0.0, S.D, facing=90, against="x-")+ PLACED[-1][0].location.y += (S.D - 0.03) - _footprint_world(PLACED[-1][0])[1].y # back-left corner, behind the wide camera+ place("ramen_noodle_boiler", c, S.W, 3.78, facing=-90, against="x+")+ place("ramen_gas_range", c, S.W, 4.82, facing=-90, against="x+")+ for i, y in enumerate(S.STOOL_Y):+ place("ramen_stool", c, 0.93, y, facing=rng.uniform(0, 360))+ # ---- kitchen: pots on the range, shelves, counters, floor+ place("stockpot", c, S.W - 0.36, 4.6, facing=rng.uniform(0, 360))+ place("stockpot", c, S.W - 0.36, 5.05, facing=rng.uniform(0, 360), scale=0.88)+ place("stockpot", c, S.W - 0.32, 5.75, facing=rng.uniform(0, 360), scale=0.8)+ place("ramen_ladle_rail", c, S.W, 4.75, z=1.42, facing=-90, against="x+", mode="hang")+ place("ramen_dish_rack", c, S.W, 2.55, facing=-90, against="x+")+ place("ramen_rice_cooker", c, S.W, 6.45, facing=-90, against="x+")+ place("ramen_kettle_pot", c, S.W, 1.35, facing=-80, against="x+")+ place("ramen_cash_register", c, S.W, 1.95, facing=-90, against="x+", start_z=1.5)+ for y in (1.15, 1.5):+ place("ramen_bowl_stack", c, S.W, y, facing=rng.uniform(0, 360), against="x+", start_z=1.9)+ place("ramen_bowl_stack", c, S.W, 5.75, facing=rng.uniform(0, 360), against="x+", start_z=1.9)+ place("ramen_soy_bottles", c, S.W, 2.95, facing=-90, against="x+", start_z=1.9)+ place("ramen_square_cans", c, 2.72, 5.72, facing=-90)+ place("ramen_noodle_crates", c, 2.72, S.D, facing=-90, against="y+")+ place("ramen_trash_bin", c, 2.75, 1.05, facing=-60)+ place("ramen_apron_hook", c, 2.62, S.D, z=0.95, facing=0, against="y+", mode="hang")+ # Prep counter behind the pass.+ place("ramen_cutting_board", c, 2.2, 3.0, facing=-90, jitter=8)+ place("ramen_tare_containers", c, 2.2, 3.85, facing=-90, jitter=10)+ place("ramen_bowl_stack", c, 2.22, 2.35, facing=rng.uniform(0, 360))+ place("ramen_hand_towel", c, 2.2, 4.6, facing=-90, jitter=25)+ # ---- customer counter (top at CH) and pass+ cx = S.CX + 0.3+ for y in (2.85, 4.65):+ place("condiment_caddy", c, cx, y, facing=-90, jitter=12)+ for y in (2.25, 4.05, 5.25):+ place("ramen_chopstick_cup", c, cx + 0.04, y, facing=rng.uniform(0, 360))+ place("ramen_tissue_box", c, cx, 3.84, facing=-90, jitter=6)+ place("ramen_bowl_unfinished", c, S.CX + 0.2, 3.3, facing=-60, jitter=5)+ place("ramen_water_glass", c, S.CX + 0.14, 3.6, facing=0)+ place("ramen_water_pitcher", c, cx, 5.75, facing=-120)+ place("ramen_water_glass", c, S.CX + 0.14, 5.0, facing=0)+ place("ramen_maneki_neko", c, S.PASS_X + 0.11, S.Y0 + 0.12, facing=-150, start_z=1.5)+ # ---- walls and ceiling+ place("ramen_wall_fan", c, 0.0, 3.85, z=1.8, facing=90, against="x-", mode="hang")+ place("ramen_crt_tv_bracket", c, S.W, 0.45, z=2.08, facing=180 + 35, against="x+", mode="hang")+ place("ramen_umbrella_stand", c, 1.95, 0.0, facing=20, against="y-", start_z=1.2)+ place("ramen_beer_crate", c, 0.0, 0.9, facing=90, against="x-")+ # ---- outside+ lx, ly, lz = S.LANTERN+ place("lantern", c, lx, ly, z=lz, facing=0, mode="hang")+ return PLACED+++def steam_spots():+ """(x, y, z, r) above each stockpot rim, for lighting.steam volumes."""+ out = []+ for o, _ in PLACED:+ if o.name.split(".")[0] == "stockpot":+ lo, hi = _footprint_world(o)+ out.append(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, hi.z, (hi.x - lo.x) * 0.42))+ return out+++def steam_sources():+ """Rim points for steam.build: stockpots, the noodle boiler top and the unfinished bowl (design coords)."""+ pots, boiler, bowl = steam_spots(), None, None+ for o, _ in PLACED:+ base = o.name.split(".")[0]+ if base in ("ramen_stockpot_tall", "ramen_stockpot_small"):+ lo, hi = _footprint_world(o)+ pots.append(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, hi.z, (hi.x - lo.x) * 0.42))+ elif base == "ramen_noodle_boiler":+ lo, hi = _footprint_world(o)+ boiler = ((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z + 0.86, hi.x - lo.x, hi.y - lo.y)+ elif base == "ramen_bowl_unfinished" and bowl is None:+ lo, hi = _footprint_world(o)+ bowl = ((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z + 0.09, 0.09)+ return pots, boiler, bowl+++def pass_a(c):+ """Densify pass A (mid props): more pots, bowl stacks, crates, a cluttered back shelf, more on the counter.+ Reuses the picked props with variation; round-2 generated props are placed by pass_a_gen when they exist."""+ # Kitchen floor / range zone.+ place("stockpot", c, 2.76, 1.75, facing=rng.uniform(0, 360))+ place("ramen_square_cans", c, 2.74, 2.4, facing=-80)+ place("ramen_beer_crate", c, 0.0, 0.9, facing=95, against="x-", start_z=1.0) # stacked on the first crate+ place("ramen_beer_crate", c, 0.0, 5.95, facing=88, against="x-")+ place("ramen_beer_crate", c, 0.0, 5.95, facing=92, against="x-", start_z=1.0)+ # Back counter A (x W-0.62..W, y 0.9..3.4): add tare containers; shelves above get crowded.+ place("ramen_tare_containers", c, S.W, 3.1, facing=-90, jitter=12, against="x+")+ for y in (1.2, 1.58, 1.95):+ place("ramen_bowl_stack", c, S.W, y, facing=rng.uniform(0, 360), against="x+", start_z=2.55) # upper shelf+ place("ramen_tare_containers", c, S.W, 2.35, facing=-90, against="x+", start_z=1.9)+ place("ramen_tissue_box", c, S.W, 3.25, facing=-95, against="x+", start_z=1.9)+ place("ramen_chopstick_cup", c, S.W - 0.05, 1.85, facing=0, against="x+", start_z=1.9)+ # Back counter B shelves (y 5.35..7).+ place("ramen_soy_bottles", c, S.W, 6.2, facing=-90, against="x+", start_z=1.9)+ place("ramen_tare_containers", c, S.W, 6.7, facing=-90, against="x+", start_z=1.9)+ place("stockpot", c, S.W, 6.6, facing=rng.uniform(0, 360), against="x+", start_z=2.55, scale=0.62)+ place("ramen_dish_rack", c, S.W, 5.85, facing=-90, against="x+", start_z=2.55)+ for y in (6.2, 6.33):+ place("ramen_chopstick_cup", c, S.W - 0.04, y, facing=rng.uniform(0, 360), against="x+", start_z=2.55)+ # Prep counter: small plates (scaled bowl stacks), second cutting board, a pot of tare.+ place("ramen_bowl_stack", c, 2.22, 2.65, facing=rng.uniform(0, 360), scale=0.55)+ place("ramen_bowl_stack", c, 2.3, 5.5, facing=rng.uniform(0, 360))+ place("ramen_kettle_pot", c, 2.22, 5.1, facing=-90)+ place("stockpot", c, 2.25, 6.0, facing=rng.uniform(0, 360), scale=0.58)+ # Pass top: a stack of bowls waiting, the next caddy.+ place("ramen_bowl_stack", c, S.PASS_X + 0.11, 2.1, facing=rng.uniform(0, 360), start_z=1.5)+ place("ramen_bowl_stack", c, S.PASS_X + 0.11, 2.42, facing=rng.uniform(0, 360), start_z=1.5, scale=0.85)+ # Customer counter: more condiment sets and glasses, one per seat or so.+ cx = S.CX + 0.3+ for y in (1.78, 5.48):+ place("condiment_caddy", c, cx, y, facing=-90, jitter=12)+ for y in (2.05, 4.35, 5.62):+ place("ramen_water_glass", c, S.CX + 0.13 + rng.uniform(-0.03, 0.03), y, facing=0)+ place("ramen_bowl_unfinished", c, S.CX + 0.19, 5.0 + 0.32, facing=40, jitter=10)+ # Coat hooks on the customer wall near the back: aprons/jackets hanging, a towel.+ for y in (5.55, 5.88):+ place("ramen_apron_hook", c, 0.0, y, z=0.88, facing=90, against="x-", mode="hang")+ place("ramen_hand_towel", c, 0.93, 4.9, facing=rng.uniform(0, 360), start_z=1.3) # left on a stool+++def _have(pid):+ if pid in BRANDED:+ pid = pid + "_nb"+ return os.path.exists(os.path.join(LIB, pid + ".blend"))+++def pick(pid, fallback=None):+ """Round-2 prop if it was generated and prepped, else the round-1 fallback (or skip)."""+ return pid if _have(pid) else fallback+++def pass_a2(c):+ """Pass A with round-2 picks: variety instead of copies. Same design coordinates as pass_a; steam sources+ (range pots, boiler, first bowl) are untouched so baked caches stay valid."""+ P = lambda pid, fb, *a, **k: place(pick(pid, fb), c, *a, **k) if pick(pid, fb) else None # noqa: E731+ # Kitchen floor.+ P("ramen_stockpot_tall", "stockpot", 2.76, 1.75, facing=rng.uniform(0, 360))+ place("ramen_square_cans", c, 2.74, 2.4, facing=-80)+ P("ramen_mop_bucket", None, 2.75, 6.1, facing=30)+ P("ramen_rubber_boots", None, 2.85, 0.42, facing=-20)+ P("ramen_fire_extinguisher", None, 3.5, 0.0, facing=0, against="y-")+ # Customer side floor: crates by the door, supply boxes and a rice sack by the fridge.+ place("ramen_beer_crate", c, 0.0, 0.9, facing=95, against="x-", start_z=1.0)+ P("ramen_cardboard_boxes", "ramen_beer_crate", 0.0, 5.95, facing=88, against="x-")+ P("ramen_flour_sacks", None, 0.0, 5.3, facing=90, against="x-")+ P("ramen_rice_sack", None, 0.0, 5.95, facing=75, against="x-", start_z=1.0) # on the supply boxes+ # Back counter A and its shelves.+ P("ramen_chashu_tray", "ramen_tare_containers", S.W, 3.05, facing=-90, against="x+")+ P("ramen_plate_stack", "ramen_bowl_stack", S.W, 1.2, facing=-90, against="x+", start_z=2.55)+ place("ramen_bowl_stack", c, S.W, 1.58, facing=rng.uniform(0, 360), against="x+", start_z=2.55)+ P("ramen_colander", "ramen_bowl_stack", S.W, 1.98, facing=-90, against="x+", start_z=2.55)+ P("ramen_shelf_jars", "ramen_tare_containers", S.W, 2.4, facing=-90, against="x+", start_z=1.9, scale=0.72) # fits the 0.36 m shelf gap+ P("ramen_spice_tins", "ramen_tissue_box", S.W, 3.2, facing=-95, against="x+", start_z=1.9)+ P("ramen_radio", "ramen_chopstick_cup", S.W, 1.85, facing=-90, against="x+", start_z=1.9)+ # Back counter B shelves.+ P("ramen_beni_shoga_pot", "ramen_soy_bottles", S.W, 6.2, facing=-90, against="x+", start_z=1.9)+ place("ramen_tare_containers", c, S.W, 6.7, facing=-90, against="x+", start_z=1.9)+ P("ramen_stockpot_small", "stockpot", S.W, 6.6, facing=rng.uniform(0, 360), against="x+", start_z=2.55)+ place("ramen_dish_rack", c, S.W, 5.85, facing=-90, against="x+", start_z=2.55)+ P("ramen_daruma", "ramen_chopstick_cup", S.W - 0.04, 6.25, facing=-90, against="x+", start_z=2.55)+ # Prep counter.+ P("ramen_plate_stack", "ramen_bowl_stack", 2.22, 2.65, facing=rng.uniform(0, 360))+ P("ramen_egg_container", "ramen_bowl_stack", 2.3, 5.5, facing=-90)+ P("ramen_cleaver_board", "ramen_kettle_pot", 2.2, 5.1, facing=-70)+ P("ramen_beni_shoga_pot", "stockpot", 2.25, 6.0, facing=-90)+ P("ramen_bucket_strainer", None, 2.2, 6.35, facing=30)+ P("ramen_garlic_press", None, 2.05, 3.55, facing=-60)+ # Pass top: a stack of bowls waiting, the meal tickets.+ place("ramen_bowl_stack", c, S.PASS_X + 0.11, 2.1, facing=rng.uniform(0, 360), start_z=1.5)+ P("ramen_ticket_tray", "ramen_bowl_stack", S.PASS_X + 0.11, 2.45, facing=-90, start_z=1.5)+ P("ramen_towel_crumpled", None, S.PASS_X + 0.1, 3.3, facing=20, start_z=1.5)+ # Customer counter: one more caddy of each kind, glasses, a menu per few seats, the last customer's things.+ cx = S.CX + 0.3+ place("condiment_caddy", c, cx, 1.78, facing=-90, jitter=12)+ P("ramen_condiment_tray2", "condiment_caddy", cx, 5.48, facing=-90, jitter=8)+ for y in (2.05, 4.35, 5.62):+ place("ramen_water_glass", c, S.CX + 0.13 + rng.uniform(-0.03, 0.03), y, facing=0)+ P("ramen_beer_bottle_glass", "ramen_bowl_unfinished", S.CX + 0.17, 5.25, facing=40)+ for y in (2.6, 4.55):+ P("ramen_menu_stand", None, cx + 0.02, y, facing=-90, jitter=10)+ P("ramen_smartphone", None, S.CX + 0.08, 4.62, facing=20)+ P("ramen_ashtray", None, S.CX + 0.25, 6.05, facing=0)+ P("ramen_lighter_cigs", None, S.CX + 0.13, 5.95, facing=55)+ P("ramen_tea_cup", None, S.CX + 0.08, 2.35, facing=0)+ P("ramen_napkins_used", None, S.CX + 0.08, 5.45, facing=30)+ # Walls.+ P("ramen_coat_hooks", "ramen_apron_hook", 0.0, 5.72, z=1.05, facing=90, against="x-", mode="hang")+ P("ramen_wall_clock", None, 0.0, 2.7, z=1.9, facing=90, against="x-", mode="hang")+ P("ramen_kamidana", None, 1.0, S.D, z=1.95, facing=180, against="y+", mode="hang")+ P("ramen_hook_items", None, 2.36, S.D, z=1.22, facing=180, against="y+", mode="hang")+ place("ramen_hand_towel", c, 0.93, 4.9, facing=rng.uniform(0, 360), start_z=1.3)+++def pass_bc_gen(c):+ """Generated pass B/C pieces that replace direct-modelled ones (see r2gen.props for what is removed)."""+ P = lambda pid, *a, **k: place(pid, c, *a, **k) if _have(pid) else None # noqa: E731+ P("ramen_tongs", 2.12, 4.3, facing=-60)+ P("ramen_coins", S.CX + 0.27, 3.05, facing=10)+ P("ramen_tape_roll", S.W - 0.45, 2.25, facing=-30)+ P("ramen_ladle_pair", 2.0, 5.55, facing=-90)+ P("ramen_power_strip", 0.35, 6.25, facing=80, start_z=0.6)+ P("ramen_cat_dish", 1.0, 0.55, facing=8, start_z=0.6)+ P("ramen_vending_machine", 2.025, -3.0, facing=180, start_z=0.6)diff --git a/scenes/tokyo-ramen-shop/scripts/emitters.py b/scenes/tokyo-ramen-shop/scripts/emitters.pynew file mode 100644index 0000000..d56e3e3--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/emitters.py@@ -0,0 +1,48 @@+"""Glowing textures on dense generated meshes (ticket machine, fridge, lantern) turned every triangle into a light:+a 545k-emitter light tree took ~290 s of sync per frame. Their light comes from area/point lights anyway, so+emissive materials on meshes over 2k triangles stop being sampled as lights (they still glow to the camera)."""+import bpy+++def _emissive(m):+ if not m or not m.node_tree:+ return False+ for n in m.node_tree.nodes:+ if n.type == "EMISSION":+ return True+ if n.type == "BSDF_PRINCIPLED":+ s = n.inputs["Emission Strength"]+ if s.is_linked or s.default_value > 0:+ c = n.inputs["Emission Color"]+ if c.is_linked or any(v > 0 for v in c.default_value[:3]):+ return True+ return False+++def run(min_tris=2000):+ done = []+ for o in bpy.data.objects:+ if o.type != "MESH":+ continue+ if sum(len(p.vertices) - 2 for p in o.data.polygons) < min_tris:+ continue+ for m in o.data.materials:+ if _emissive(m) and m.cycles.emission_sampling != "NONE":+ m.cycles.emission_sampling = "NONE" # lives on m.cycles in 5.0+ done.append(m.name)+ print("emitters: sampling off for", done, flush=True)+ return done+++if __name__ == "__main__":+ run()+ bpy.ops.wm.save_mainfile()+++def no_volume_blur():+ """Object motion blur on the Mantaflow domains makes Cycles build velocity motion from the noise grids:+ ~290 s of sync per frame. Camera blur stays; the steam itself just isn't motion-blurred."""+ for o in bpy.data.objects:+ if any(m.type == "FLUID" and m.fluid_type == "DOMAIN" for m in o.modifiers):+ o.cycles.use_motion_blur = False+ print("emitters: no motion blur on", o.name, flush=True)diff --git a/scenes/tokyo-ramen-shop/scripts/exterior.py b/scenes/tokyo-ramen-shop/scripts/exterior.pynew file mode 100644index 0000000..88b765c--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/exterior.py@@ -0,0 +1,199 @@+"""Street outside the shop (design coordinates; front wall at y=0, street toward -Y).++Layers for parallax: 3D near elements (vending machine, street lamp, neon signs, curb, puddles, rain)+in front of the emissive photo backdrop from shell.exterior. Lights: lamp pool on the wet street,+vending machine glow, neon spill, and cool spill in through the door glass and noren."""+import math+import os++import bpy++import shell as S+from lib import L, area, box, bsdf, cylinder, m_simple, mathn, mix, new_mat, node, noise, point, ramp, spot, texcoord++FONT = "C:/Windows/Fonts/YuGothB.ttc"+++def m_emit(name, color, strength):+ m, nt = new_mat(name)+ if nt:+ b = bsdf(nt)+ b.inputs["Base Color"].default_value = (*color, 1)+ b.inputs["Emission Color"].default_value = (*color, 1)+ b.inputs["Emission Strength"].default_value = strength+ return m+++def m_vending_front():+ """Backlit display of drinks: a grid of cells, each a random-coloured can on a white backlight."""+ m, nt = new_mat("vending_front")+ if not nt:+ return m+ uv = texcoord(nt, "UV")+ mp = nt.nodes.new("ShaderNodeMapping")+ mp.inputs["Scale"].default_value = (8.0, 5.0, 1.0)+ L(nt, uv, mp.inputs["Vector"])+ cell = nt.nodes.new("ShaderNodeVectorMath")+ cell.operation = "FLOOR"+ L(nt, mp.outputs[0], cell.inputs[0])+ frac = nt.nodes.new("ShaderNodeVectorMath")+ frac.operation = "FRACTION"+ L(nt, mp.outputs[0], frac.inputs[0])+ wn = nt.nodes.new("ShaderNodeTexWhiteNoise")+ L(nt, cell.outputs[0], wn.inputs["Vector"])+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ L(nt, frac.outputs[0], sep.inputs[0])+ # Can silhouette: narrow in x, tall in y, inside each cell.+ cx = mathn(nt, "LESS_THAN", mathn(nt, "ABSOLUTE", mathn(nt, "SUBTRACT", sep.outputs["X"], 0.5)), 0.28)+ cy = mathn(nt, "MULTIPLY", mathn(nt, "GREATER_THAN", sep.outputs["Y"], 0.18), mathn(nt, "LESS_THAN", sep.outputs["Y"], 0.86))+ can = mathn(nt, "MULTIPLY", cx, cy)+ col = mix(nt, can, (1.0, 0.98, 0.94, 1), wn.outputs["Color"])+ b = bsdf(nt)+ L(nt, col, b.inputs["Base Color"])+ L(nt, col, b.inputs["Emission Color"])+ b.inputs["Emission Strength"].default_value = 3.5+ b.inputs["Roughness"].default_value = 0.1+ return m+++def neon_text(name, text, c, loc, rot, size, color, strength, back=True):+ cu = bpy.data.curves.new(name, "FONT")+ cu.body = "\n".join(text) # one glyph per line = vertical sign+ cu.font = bpy.data.fonts.load(FONT, check_existing=True)+ cu.size = size+ cu.space_line = 0.85+ cu.align_x = "CENTER"+ cu.align_y = "CENTER"+ cu.extrude = 0.006+ cu.bevel_depth = 0.002+ o = bpy.data.objects.new(name, cu)+ c.objects.link(o)+ o.location = loc+ o.rotation_euler = rot+ cu.materials.append(m_emit(name + "_mat", color, strength))+ if back:+ n = len(text)+ h = n * size * 0.85 + size * 0.5+ w = size * 1.35+ # Text faces +Y (toward the shop), so its box sits behind it on the -Y side.+ bx = box(name + "_box", (loc[0] - w / 2, loc[1] - 0.09, loc[2] - h / 2), (loc[0] + w / 2, loc[1] - 0.012, loc[2] + h / 2), c,+ m_simple("sign_box", (0.03, 0.03, 0.035), 0.4, 0.6), 0.006)+ return o+++def m_pavement():+ m, nt = new_mat("street_wet")+ if not nt:+ return m+ co = texcoord(nt)+ base = noise(nt, 9, 10, 0.65, co)+ col = ramp(nt, [(0.3, (0.02, 0.02, 0.021)), (0.75, (0.07, 0.068, 0.065))], base.outputs["Fac"])+ pud = ramp(nt, [(0.44, (0, 0, 0)), (0.5, (1, 1, 1))], noise(nt, 0.7, 4, 0.5, co).outputs["Fac"])+ b = bsdf(nt)+ L(nt, mix(nt, pud.outputs["Color"], col.outputs["Color"], (0.008, 0.008, 0.009, 1)), b.inputs["Base Color"])+ L(nt, mix(nt, pud.outputs["Color"], (0.35, 0.35, 0.35, 1), (0.02, 0.02, 0.02, 1)), b.inputs["Roughness"])+ # Rain ripples only in the puddles.+ rip = node(nt, "ShaderNodeTexVoronoi", Scale=55.0)+ L(nt, co, rip.inputs["Vector"])+ ring = ramp(nt, [(0.0, (0, 0, 0)), (0.12, (1, 1, 1)), (0.2, (0, 0, 0))], rip.outputs["Distance"])+ h = mathn(nt, "MULTIPLY", ring.outputs["Color"], pud.outputs["Color"])+ bm = nt.nodes.new("ShaderNodeBump")+ bm.inputs["Strength"].default_value = 0.08+ L(nt, h, bm.inputs["Height"])+ bm2 = nt.nodes.new("ShaderNodeBump")+ bm2.inputs["Strength"].default_value = 0.3+ L(nt, noise(nt, 70, 8, 0.7, co).outputs["Fac"], bm2.inputs["Height"])+ L(nt, bm2.outputs[0], bm.inputs["Normal"])+ L(nt, bm.outputs[0], b.inputs["Normal"])+ return m+++def rain(c, lo=(-1.6, -2.2, 0.0), hi=(5.2, -0.25, 3.6), count=35000): # strip in front of the shop only: drops at the lens smear white+ """Rain streaks: instanced thin drops falling at ~7 m/s; motion blur (and their length) makes the streaks."""+ drop = cylinder("rain_drop", 0.0012, 0.07, c, None, loc=(0, 0, -50), verts=6)+ # Particle VEL rotation aligns the instance's +X with the velocity, so lay the drop's long axis along X.+ from mathutils import Matrix+ drop.data.transform(Matrix.Rotation(math.radians(90), 4, "Y") @ Matrix.Translation((0, 0, -0.035)))+ drop.data.materials.append(_rain_mat())+ drop.hide_render = False+ em = box("rain_emitter", (lo[0], lo[1], hi[2]), (hi[0], hi[1], hi[2] + 0.02), c, None, 0)+ # Not hide_render: that also hides the particle instances. show_instancer_for_render=False hides only the box.+ ps_mod = em.modifiers.new("rain", "PARTICLE_SYSTEM")+ ps = ps_mod.particle_system.settings+ ps.count = count+ ps.frame_start = -60+ ps.frame_end = 200+ ps.lifetime = 30+ ps.emit_from = "VOLUME"+ ps.normal_factor = 0.0+ ps.object_align_factor = (0, 0, -7.0)+ ps.effector_weights.gravity = 0.0+ ps.render_type = "OBJECT"+ ps.instance_object = drop+ ps.particle_size = 1.0+ ps.size_random = 0.5+ ps.use_rotations = True+ ps.rotation_mode = "VEL"+ ps.use_dynamic_rotation = False+ ps.physics_type = "NEWTON"+ em.show_instancer_for_render = False+ em.show_instancer_for_viewport = False+ return em+++def _rain_mat():+ m, nt = new_mat("rain")+ if nt:+ b = bsdf(nt)+ b.inputs["Base Color"].default_value = (0.8, 0.85, 0.9, 1)+ b.inputs["Roughness"].default_value = 0.05+ b.inputs["Transmission Weight"].default_value = 0.0 # transmissive drops vanished in Cycles+ b.inputs["Emission Color"].default_value = (0.75, 0.85, 1.0, 1)+ b.inputs["Emission Strength"].default_value = 1.1+ b.inputs["Alpha"].default_value = 0.3+ return m+++def build(c):+ # Ground: wet street with puddles in front of the shop, a curb and a gutter.+ pav = bpy.data.objects.get("pavement")+ if pav:+ pav.data.materials.clear()+ pav.data.materials.append(m_pavement())+ box("curb", (-2.0, -1.45, -0.12), (S.W + 2.0, -1.3, 0.02), c, m_simple("curb", (0.13, 0.125, 0.12), 0.55), 0.01)+ box("gutter", (-2.0, -1.62, -0.14), (S.W + 2.0, -1.45, -0.115), c, m_simple("gutter", (0.05, 0.05, 0.05), 0.25, 0.8), 0.003)+ box("road", (-6.0, -5.0, -0.2), (S.W + 6.0, -1.62, -0.13), c, m_pavement(), 0)++ # Vending machine across the street, facing the shop (seen through the door; parallax against the photo).+ vx0, vx1, vy0, vy1 = 1.55, 2.5, -3.35, -2.65+ box("vending_body", (vx0, vy0, -0.13), (vx1, vy1, 1.75), c, m_simple("vending_body", (0.75, 0.74, 0.72), 0.35, coat=0.6), 0.02)+ from lib import plane+ flip = (0, 0, math.radians(180)) # planes face -Y by default; these face the shop (+Y)+ plane("vending_display", 0.8, 1.0, c, m_vending_front(), loc=((vx0 + vx1) / 2, vy1 + 0.004, 0.6), rot=flip)+ plane("vending_header", 0.8, 0.18, c, m_emit("vending_header", (0.95, 0.15, 0.12), 6.0), loc=((vx0 + vx1) / 2, vy1 + 0.004, 1.48), rot=flip)+ box("vending_slot", ((vx0 + vx1) / 2 - 0.3, vy1, 0.0), ((vx0 + vx1) / 2 + 0.3, vy1 + 0.05, 0.2), c, m_simple("slot", (0.02, 0.02, 0.02), 0.4), 0.01)+ area("vending_glow", c, ((vx0 + vx1) / 2, vy1 + 0.15, 0.85), (math.radians(90), 0, 0), 0.8, 60, (0.8, 0.92, 1.0), size_y=1.2)++ # Street lamp across the gutter: a cool LED pool on the wet street.+ lx, ly = 3.2, -1.85+ cylinder("lamp_pole", 0.05, 4.3, c, m_simple("pole_grey", (0.2, 0.2, 0.19), 0.5, 0.7), loc=(lx, ly, -0.13))+ arm = box("lamp_arm", (lx - 0.9, ly - 0.03, 4.08), (lx, ly + 0.03, 4.13), c, m_simple("pole_grey", (0.2, 0.2, 0.19), 0.5, 0.7), 0.01)+ box("lamp_head", (lx - 1.15, ly - 0.12, 4.0), (lx - 0.75, ly + 0.12, 4.12), c, m_simple("pole_grey", (0.2, 0.2, 0.19), 0.5, 0.7), 0.01)+ plane("lamp_lens", 0.38, 0.22, c, m_emit("lamp_lens", (0.85, 0.92, 1.0), 40), loc=(lx - 0.95, ly - 0.11, 3.995), rot=(math.radians(90), 0, 0))+ spot("street_lamp", c, (lx - 0.95, ly, 3.95), (0, 0, 0), 1400, (0.82, 0.9, 1.0), angle=120, blend=0.5, radius=0.15)++ # Neon across the street (behind the lamp, in front of the photo): pink izakaya tube text and a box sign.+ neon_text("neon_izakaya", "居酒屋", c, (0.95, -3.5, 2.45), (math.radians(-90), 0, 0), 0.32, (1.0, 0.18, 0.45), 18)+ point("neon_izakaya_spill", c, (0.95, -3.25, 2.4), 60, (1.0, 0.25, 0.5), radius=0.3)+ neon_text("neon_snack", "スナック", c, (3.0, -3.7, 2.6), (math.radians(-90), 0, 0), 0.26, (0.3, 0.85, 1.0), 14)+ point("neon_snack_spill", c, (3.0, -3.45, 2.5), 45, (0.3, 0.8, 1.0), radius=0.3)++ # Spill into the shop: cool street light through the door glass and noren, onto the floor just inside.+ spot("door_spill", c, ((S.DOOR[0] + S.DOOR[1]) / 2, -1.6, 2.3), (math.radians(62), 0, 0), 260, (0.7, 0.82, 1.0), angle=55, blend=0.7, radius=0.4)+ spot("window_spill", c, ((S.WIN[0] + S.WIN[1]) / 2, -1.6, 2.3), (math.radians(62), 0, 0), 160, (0.75, 0.6, 1.0), angle=55, blend=0.7, radius=0.4)++ bd = bpy.data.objects.get("street_backdrop")+ if bd:+ em = next(n for n in bd.data.materials[0].node_tree.nodes if n.type == "EMISSION")+ em.inputs["Strength"].default_value = 1.1+ rain(c)diff --git a/scenes/tokyo-ramen-shop/scripts/finals_gen.sh b/scenes/tokyo-ramen-shop/scripts/finals_gen.shnew file mode 100644index 0000000..6698809--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/finals_gen.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# Re-apply round-2 generated assets to the pre-gen backup (steam caches untouched), preview, heroes, changed shots.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++cp scenes/tokyo-ramen-shop/ramen_r2_pre_gen.blend scenes/tokyo-ramen-shop/ramen_r2.blend+"$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python-expr "+import sys; sys.path.insert(0, __import__('os').environ['ANYSCENE_ROOT'] + '/scenes/tokyo-ramen-shop/scripts')+import r2gen, bpy; r2gen.apply(); bpy.ops.wm.save_mainfile(); print('PATCHED r2gen')" 2>&1 | grep -E "PATCHED|VALIDATE|^ |Traceback"+bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/render.py -- prev wide,counter,door,kitchen --tag _gen2 --samples 48 2>&1 | grep -cE "STILL"++P=scenes/tokyo-ramen-shop/out/prev+"$FF" -v error -y -i $P/wide_gen2.png -i $P/counter_gen2.png -i $P/door_gen2.png -i $P/kitchen_gen2.png -filter_complex "[0][1]hstack[a];[2][3]hstack[b];[a][b]vstack" scenes/tokyo-ramen-shop/out/process/r2_generated_props.png && echo PREVIEW+for k in wide counter; do [ -f scenes/tokyo-ramen-shop/out/hero_${k}_r2a.png ] || cp scenes/tokyo-ramen-shop/out/hero_$k.png scenes/tokyo-ramen-shop/out/hero_${k}_r2a.png; done+HEROES="wide counter" bash scenes/tokyo-ramen-shop/scripts/heroes_r2.sh+for s in lantern_rain exterior_establish counter_push door_dolly_zoom; do rm -rf scenes/tokyo-ramen-shop/out/shots/$s/frames; done+SHOTS="lantern_rain:96 exterior_establish:120 counter_push:120 door_dolly_zoom:96" bash scenes/tokyo-ramen-shop/scripts/shots_r2.sh+echo ALLDONEdiff --git a/scenes/tokyo-ramen-shop/scripts/finals_r2.sh b/scenes/tokyo-ramen-shop/scripts/finals_r2.shnew file mode 100644index 0000000..8d99d66--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/finals_r2.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++HEROES=counter bash scenes/tokyo-ramen-shop/scripts/heroes_r2.sh+bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/render.py -- prev door --tag _r2 --samples 96 --res 1280 2>&1 | grep -E "STILL|Error"+cp scenes/tokyo-ramen-shop/out/prev/door_r2.png scenes/tokyo-ramen-shop/out/process/r2_exterior_from_inside.png+bash scenes/tokyo-ramen-shop/scripts/shots_r2.shdiff --git a/scenes/tokyo-ramen-shop/scripts/finish.sh b/scenes/tokyo-ramen-shop/scripts/finish.shnew file mode 100644index 0000000..9b2f648--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/finish.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+# Finishing pass (ffmpeg): split-tone grade (warm highlights, cool shadows), gentle S-curve, soft vignette, film grain.+# scenes/tokyo-ramen-shop/scripts/finish.sh still in.png out.png+# scenes/tokyo-ramen-shop/scripts/finish.sh clip frames/%04d.png out.mp4+# Uses curves + hue for tone (no eq) and h264_nvenc for encoding.+. "$(dirname "$0")/../../../pipeline/env.sh"++GRADE="colorbalance=rs=-0.03:bs=0.05:rm=0.02:bm=-0.02:rh=0.05:gh=0.01:bh=-0.05,curves=all='0/0.012 0.25/0.22 0.6/0.63 1/0.98',hue=s=0.92,vignette=angle=PI/4.6:mode=forward"+case "$1" in+ still) "$FF" -v error -y -i "$2" -vf "$GRADE,noise=alls=6:allf=u" "$3" ;;+ clip) "$FF" -v error -y -framerate 24 -i "$2" -vf "$GRADE,noise=alls=7:allf=t+u,format=yuv420p" -c:v h264_nvenc -preset p7 -rc vbr -cq 17 -b:v 0 "$3" ;;+ *) echo "usage: finish.sh still|clip in out"; exit 1 ;;+esacdiff --git a/scenes/tokyo-ramen-shop/scripts/finish_r2.sh b/scenes/tokyo-ramen-shop/scripts/finish_r2.shnew file mode 100644index 0000000..1db549d--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/finish_r2.sh@@ -0,0 +1,28 @@+#!/usr/bin/env bash+# After finals_gen.sh: confine rain away from the lens, re-render the establishing shot, publish the .blend,+# and always raise the repair agent's GPU go-signal on exit.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh+trap 'touch .gpu.ramen_done; echo "SIGNAL .gpu.ramen_done"' EXIT++until grep -q ALLDONE logs/ramen_finals_gen.log; do sleep 30; done+"$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python-expr "+import bpy+em = bpy.data.objects['rain_emitter']+ps = em.particle_systems[0].settings+bb = [em.matrix_world @ __import__('mathutils').Vector(c) for c in em.bound_box]+y0, y1 = min(p.y for p in bb), max(p.y for p in bb)+# keep the far edge at the facade (y1), pull the near edge in to y = -2.2+k = (y1 + 2.2) / (y1 - y0)+em.scale.y *= k; em.location.y = y1 - (y1 - y0) * k / 2 - 0 if False else em.location.y+bpy.context.view_layer.update()+bb = [em.matrix_world @ __import__('mathutils').Vector(c) for c in em.bound_box]+em.location.y += y1 - max(p.y for p in bb)+ps.count = int(ps.count * k)+bpy.ops.wm.save_mainfile(); bpy.context.view_layer.update()+bb = [em.matrix_world @ __import__('mathutils').Vector(c) for c in em.bound_box]+print('RAIN y', round(min(p.y for p in bb), 2), round(max(p.y for p in bb), 2), ps.count)" 2>&1 | grep -E "RAIN|Error|Traceback"+rm -rf scenes/tokyo-ramen-shop/out/shots/exterior_establish/frames+SHOTS="exterior_establish:120" bash scenes/tokyo-ramen-shop/scripts/shots_r2.sh+cp scenes/tokyo-ramen-shop/ramen_r2.blend scenes/tokyo-ramen-shop/ramen.blend && echo "PUBLISHED ramen.blend"+echo FINISHED_R2diff --git a/scenes/tokyo-ramen-shop/scripts/gen.mjs b/scenes/tokyo-ramen-shop/scripts/gen.mjsnew file mode 100644index 0000000..51cd531--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/gen.mjs@@ -0,0 +1,52 @@+// Ramen scene generation: refs (GPT Image 2.5 Sunburst) then Tripo H3.1 + Meshy 7.1 for every prop, plus flat textures.+// node scenes/tokyo-ramen-shop/scripts/gen.mjs [--only id,id] [--models tripo-h31,meshy]+// Skips anything already on disk; re-run to fill gaps. Uses generate/fal.mjs (shared) via child processes.+import { execFile } from 'node:child_process';+import { existsSync, readFileSync } from 'node:fs';+import { promisify } from 'node:util';++const run = promisify(execFile);+const ROOT = new URL('../../..', import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1');+const M = JSON.parse(readFileSync(`${ROOT}/scenes/tokyo-ramen-shop/assets.json`, 'utf8'));+const args = Object.fromEntries(process.argv.slice(2).reduce((a, v, i, arr) => (v.startsWith('--') ? [...a, [v.slice(2), arr[i + 1]]] : a), []));+const only = args.only?.split(',');+const models = (args.models ?? 'tripo-h31,meshy').split(',');+const REF = 'Product reference photograph for 3D scanning. The entire object fully visible and centered, three-quarter front view from slightly above, plain seamless light-grey background, soft even diffuse studio lighting, no harsh shadows, no other objects, no hands, realistic used and worn condition, sharp focus, true-to-life materials.';++const fal = (...a) => run('node', ['generate/fal.mjs', ...a], { cwd: ROOT, maxBuffer: 1 << 24 });++async function pool(tasks, n) {+ const out = [];+ let i = 0;+ await Promise.all(Array.from({ length: n }, async () => {+ while (i < tasks.length) {+ const t = tasks[i++];+ try { out.push(await t()); } catch (e) { console.log('FAIL', e.message.split('\n').slice(-3).join(' | ')); }+ }+ }));+ return out;+}++const refPath = (id) => (existsSync(`${ROOT}/refs/props/${id}.json`) ? `refs/props/${id}.json` : `refs/tokyo-ramen-shop/props/${id}.json`);+const props = M.generate.filter((p) => !only || only.includes(p.id));++// Textures + refs first (fast), then 3D.+const imgTasks = [+ ...M.textures.filter((t) => (!only || only.includes(t.id)) && !existsSync(`${ROOT}/refs/tokyo-ramen-shop/tex/${t.id}_0.png`)).map((t) => async () => {+ await fal('image', '--variant', 'sunburst', '--quality', 'high', '--size', t.size, '--out', `refs/tokyo-ramen-shop/tex/${t.id}`, '--prompt', t.prompt);+ console.log('tex', t.id);+ }),+ ...props.filter((p) => p.prompt !== 'existing' && !existsSync(`${ROOT}/${refPath(p.id)}`)).map((p) => async () => {+ await fal('image', '--variant', 'sunburst', '--quality', 'high', '--size', 'square_hd', '--out', `refs/tokyo-ramen-shop/props/${p.id}`, '--prompt', `${p.prompt} ${REF}`);+ console.log('ref', p.id);+ }),+];+await pool(imgTasks, 10);++const genTasks = props.flatMap((p) => models.filter((m) => !existsSync(`${ROOT}/assets/gen/${m}/${p.id}/model.glb`)).map((m) => async () => {+ const t0 = Date.now();+ await fal('3d', '--model', m, '--ref', refPath(p.id), '--out', `assets/gen/${m}/${p.id}`);+ console.log('3d', m, p.id, Math.round((Date.now() - t0) / 1000) + 's');+}));+await pool(genTasks, +(args.pool ?? 14));+console.log('all done');diff --git a/scenes/tokyo-ramen-shop/scripts/gpu_prefs.py b/scenes/tokyo-ramen-shop/scripts/gpu_prefs.pynew file mode 100644index 0000000..855f628--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/gpu_prefs.py@@ -0,0 +1,12 @@+"""Run as the first --python: Cycles device prefs live in user preferences, not the .blend, so a plain+`blender -b scene.blend` renders on the CPU. Select OptiX GPUs and set the scene to GPU."""+import bpy++prefs = bpy.context.preferences.addons["cycles"].preferences+prefs.compute_device_type = "OPTIX"+prefs.get_devices()+for d in prefs.devices:+ d.use = d.type == "OPTIX"+for sc in bpy.data.scenes:+ sc.cycles.device = "GPU"+print("gpu_prefs:", [d.name for d in prefs.devices if d.use], flush=True)diff --git a/scenes/tokyo-ramen-shop/scripts/grime.py b/scenes/tokyo-ramen-shop/scripts/grime.pynew file mode 100644index 0000000..340f1cd--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/grime.py@@ -0,0 +1,169 @@+"""Imperfections pass (runs after the mirror; everything here is position-agnostic or uses object-local masks).++overlay() injects dirt into any Principled material in place, keeping whatever drives its Base Color:+ ao crevice / contact dirt from Ambient Occlusion (corners, under rims, around buttons)+ dust grey dust on upward-facing surfaces (top shelves, hood top, appliance tops)+ grease amber oily film + lower roughness + streaks running down (hood, backsplash, range)+ sticky patchy glossy coat (ticket machine buttons, counter caddies)+ scorch blackened bottoms (stockpots), from object-local height+Plus: greasy stainless drips on the hood front, stained grout, worn counter edges, curled posters."""+import math++import bmesh+import bpy+from mathutils import Vector++from lib import L, mathn, mix, noise, ramp, texcoord+++def _bsdf(m):+ return next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None) if m and m.node_tree else None+++def _source(nt, sock):+ """Current driver of a socket as an output socket (creates an RGB/Value node for a default value)."""+ if sock.is_linked:+ out = sock.links[0].from_socket+ nt.links.remove(sock.links[0])+ return out+ if sock.type == "RGBA":+ n = nt.nodes.new("ShaderNodeRGB")+ n.outputs[0].default_value = sock.default_value+ else:+ n = nt.nodes.new("ShaderNodeValue")+ n.outputs[0].default_value = sock.default_value+ return n.outputs[0]+++def overlay(m, ao=0.0, dust=0.0, grease=0.0, sticky=0.0, scorch=0.0, ao_dist=0.06):+ b = _bsdf(m)+ if b is None or m.get("grimed"):+ return+ m["grimed"] = True+ nt = m.node_tree+ col = _source(nt, b.inputs["Base Color"])+ rough = _source(nt, b.inputs["Roughness"])+ co = texcoord(nt, "Object")+ blot = noise(nt, 7.0, 6, 0.6, co)+ if ao:+ a = nt.nodes.new("ShaderNodeAmbientOcclusion")+ a.inputs["Distance"].default_value = ao_dist+ a.samples = 8+ dirt = mathn(nt, "MULTIPLY", mathn(nt, "SUBTRACT", 1.0, a.outputs["AO"]), mathn(nt, "ADD", 0.5, blot.outputs["Fac"]))+ col = mix(nt, mathn(nt, "MULTIPLY", dirt, ao, clamp=True), col, (0.09, 0.065, 0.04, 1), "MULTIPLY")+ if grease:+ mp = nt.nodes.new("ShaderNodeMapping")+ L(nt, co, mp.inputs["Vector"])+ mp.inputs["Scale"].default_value = (18.0, 18.0, 1.2) # vertical streaks+ streak = noise(nt, 1.0, 5, 0.6, mp.outputs[0])+ g = ramp(nt, [(0.38, (0, 0, 0)), (0.68, (1, 1, 1))], mix(nt, 0.5, streak.outputs["Fac"], blot.outputs["Fac"]))+ gk = mathn(nt, "MULTIPLY", g.outputs["Color"], grease, clamp=True)+ col = mix(nt, gk, col, (0.22, 0.13, 0.04, 1), "MULTIPLY")+ rough = mix(nt, gk, rough, (0.08, 0.08, 0.08, 1))+ b.inputs["Coat Weight"].default_value = max(b.inputs["Coat Weight"].default_value, 0.35 * grease)+ b.inputs["Coat Roughness"].default_value = 0.08+ if sticky:+ s = ramp(nt, [(0.45, (0, 0, 0)), (0.62, (1, 1, 1))], noise(nt, 11.0, 4, 0.5, co).outputs["Fac"])+ sk = mathn(nt, "MULTIPLY", s.outputs["Color"], sticky)+ rough = mix(nt, sk, rough, (0.06, 0.06, 0.06, 1))+ col = mix(nt, mathn(nt, "MULTIPLY", sk, 0.5), col, (0.55, 0.42, 0.25, 1), "MULTIPLY")+ b.inputs["Coat Weight"].default_value = max(b.inputs["Coat Weight"].default_value, 0.5 * sticky)+ if scorch:+ gen = nt.nodes.new("ShaderNodeSeparateXYZ")+ L(nt, texcoord(nt, "Generated"), gen.inputs[0])+ low = ramp(nt, [(0.0, (1, 1, 1)), (0.22, (0.4, 0.4, 0.4)), (0.4, (0, 0, 0))], gen.outputs["Z"])+ sc = mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", low.outputs["Color"], mathn(nt, "ADD", 0.4, blot.outputs["Fac"])), scorch, clamp=True)+ col = mix(nt, sc, col, (0.025, 0.018, 0.012, 1))+ rough = mix(nt, sc, rough, (0.75, 0.75, 0.75, 1))+ if dust:+ geo = nt.nodes.new("ShaderNodeNewGeometry")+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ L(nt, geo.outputs["Normal"], sep.inputs[0])+ up = ramp(nt, [(0.55, (0, 0, 0)), (0.85, (1, 1, 1))], sep.outputs["Z"])+ fine = noise(nt, 60.0, 4, 0.7, co)+ dk = mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", up.outputs["Color"], mathn(nt, "ADD", 0.35, fine.outputs["Fac"])), dust, clamp=True)+ col = mix(nt, dk, col, (0.32, 0.3, 0.27, 1))+ rough = mix(nt, dk, rough, (1, 1, 1, 1))+ L(nt, col, b.inputs["Base Color"])+ L(nt, rough, b.inputs["Roughness"])+++def mats_of(names, prefix=False):+ out = []+ for o in bpy.data.objects:+ base = o.name.split(".")[0]+ if (base in names) or (prefix and any(base.startswith(n) for n in names)):+ if o.type in ("MESH", "CURVE", "FONT"):+ out += [m for m in o.data.materials if m]+ return list(dict.fromkeys(out))+++def split_mat(objs, suffix):+ """Give these objects their own copy of their materials so an overlay does not hit shared ones."""+ for o in objs:+ for i, m in enumerate(o.data.materials):+ if m and not m.name.endswith(suffix):+ o.data.materials[i] = bpy.data.materials.get(m.name + suffix) or m.copy()+ o.data.materials[i].name = m.name + suffix+++def curl_plane(o, amount=0.05, corner=(1, 1), res=10):+ """Subdivide a 4-vertex wall poster and peel one corner off the wall (local -Y is its front)."""+ me = o.data+ if len(me.vertices) != 4:+ return+ bm = bmesh.new()+ bm.from_mesh(me)+ bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=res, use_grid_fill=True)+ xs = [v.co.x for v in bm.verts]+ zs = [v.co.z for v in bm.verts]+ for v in bm.verts:+ u = (v.co.x - min(xs)) / (max(xs) - min(xs))+ w = (v.co.z - min(zs)) / (max(zs) - min(zs))+ du = u if corner[0] else 1 - u+ dw = w if corner[1] else 1 - w+ k = max(0.0, (du + dw - 1.25) / 0.75)+ v.co.y -= amount * k * k+ bm.to_mesh(me)+ bm.free()+++def build():+ # Greasy stainless: hood, duct, backsplash heavy; shelves, counter tops and the range light.+ heavy = [bpy.data.objects[n] for n in ("hood", "hood_duct", "backsplash") if n in bpy.data.objects]+ split_mat(heavy, "_greasy")+ for m in mats_of(["hood", "hood_duct", "backsplash"]):+ overlay(m, ao=0.6, grease=1.0, dust=0.5)+ light = [o for o in bpy.data.objects if o.name.startswith(("shelf_", "back_counter", "prep_top"))]+ split_mat(light, "_used")+ for m in mats_of(["shelf_", "back_counter", "prep_top"], prefix=True):+ overlay(m, ao=0.7, grease=0.35, dust=0.9)+ # Appliances and props.+ for m in mats_of(["ramen_gas_range", "ramen_noodle_boiler"]):+ overlay(m, ao=0.8, grease=0.8)+ for m in mats_of(["stockpot"]):+ overlay(m, ao=0.5, scorch=0.9)+ for m in mats_of(["ticket_machine"]):+ overlay(m, ao=0.9, sticky=0.8, dust=0.6)+ for m in mats_of(["ramen_drink_fridge", "ramen_crt_tv_bracket", "ramen_wall_fan", "ramen_rice_cooker", "ramen_cash_register", "ramen_kettle_pot"]):+ overlay(m, ao=0.7, dust=0.8, grease=0.25)+ for m in mats_of(["condiment_caddy", "ramen_soy_bottles", "ramen_tare_containers", "ramen_water_pitcher"]):+ overlay(m, ao=0.4, sticky=0.5)+ for m in mats_of(["ramen_bowl_stack", "ramen_dish_rack", "ramen_stool", "ramen_beer_crate", "ramen_square_cans", "ramen_noodle_crates", "ramen_trash_bin"]):+ overlay(m, ao=0.6, dust=0.3)+ # Room surfaces: crevice dirt everywhere it meets something; dust on the plaque beam and pendant shades.+ for m in mats_of(["floor"]):+ overlay(m, ao=1.0, ao_dist=0.15)+ for m in mats_of(["wall_L", "wall_back", "wall_R_up", "front_a", "wainscot_L", "counter_base_long", "pass_long"]):+ overlay(m, ao=0.7, ao_dist=0.12)+ for m in mats_of(["wall_R_tile"]):+ overlay(m, ao=0.8, grease=0.7, ao_dist=0.1)+ for m in mats_of(["plaque_beam", "pendant_shade_"], prefix=True):+ overlay(m, dust=1.0, grease=0.2)+ for m in mats_of(["counter_top_long", "pass_top"]):+ overlay(m, ao=0.5, sticky=0.25)+ # Peeling posters / calendar / notice.+ for name, amt, corner in (("poster_beer", 0.06, (1, 1)), ("calendar", 0.03, (0, 0)), ("handwritten_notice", 0.04, (1, 1))):+ o = bpy.data.objects.get(name)+ if o:+ curl_plane(o, amt, corner)diff --git a/scenes/tokyo-ramen-shop/scripts/heroes_r2.sh b/scenes/tokyo-ramen-shop/scripts/heroes_r2.shnew file mode 100644index 0000000..5bc5a35--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/heroes_r2.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++for k in ${HEROES:-wide counter}; do+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/render.py -- stills $k --samples 320 2>&1 | grep -E "STILL|Error|Traceback"+ bash scenes/tokyo-ramen-shop/scripts/finish.sh still scenes/tokyo-ramen-shop/out/raw/hero_$k.png scenes/tokyo-ramen-shop/out/hero_$k.png && echo "FINISHED $k"+donediff --git a/scenes/tokyo-ramen-shop/scripts/lib.py b/scenes/tokyo-ramen-shop/scripts/lib.pynew file mode 100644index 0000000..86c49d1--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/lib.py@@ -0,0 +1,439 @@+"""Ramen scene helpers: geometry primitives and procedural materials (Blender 5.0, Cycles)."""+import math+import os++import bpy+from mathutils import Vector++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+SCENE_DIR = os.path.join(ROOT, "scenes", "tokyo-ramen-shop")+TEX = os.path.join(ROOT, "refs", "tokyo-ramen-shop", "tex")+++# ---------------------------------------------------------------- collections / objects++def coll(name, parent=None):+ c = bpy.data.collections.get(name) or bpy.data.collections.new(name)+ p = parent or bpy.context.scene.collection+ if c.name not in [x.name for x in p.children]:+ p.children.link(c)+ return c+++def link(obj, c):+ for uc in list(obj.users_collection):+ uc.objects.unlink(obj)+ c.objects.link(obj)+ return obj+++def mesh_obj(name, verts, faces, c, mat=None):+ me = bpy.data.meshes.new(name)+ me.from_pydata(verts, [], faces)+ me.update()+ o = bpy.data.objects.new(name, me)+ c.objects.link(o)+ if mat:+ me.materials.append(mat)+ return o+++def box(name, lo, hi, c, mat=None, bevel=0.004, rot_z=0.0):+ """Axis-aligned box from corner lo to corner hi (world metres), origin at its bottom centre."""+ lo, hi = Vector(lo), Vector(hi)+ s = hi - lo+ hx, hy = s.x / 2, s.y / 2+ v = [(-hx, -hy, 0), (hx, -hy, 0), (hx, hy, 0), (-hx, hy, 0), (-hx, -hy, s.z), (hx, -hy, s.z), (hx, hy, s.z), (-hx, hy, s.z)]+ f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]+ o = mesh_obj(name, v, f, c, mat)+ o.location = ((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z)+ o.rotation_euler.z = rot_z+ uv_cube(o)+ if bevel:+ m = o.modifiers.new("bevel", "BEVEL")+ m.width = bevel+ m.segments = 2+ m.limit_method = "ANGLE"+ m.harden_normals = False+ for p in o.data.polygons:+ p.use_smooth = False+ return o+++def plane(name, w, h, c, mat=None, loc=(0, 0, 0), rot=(0, 0, 0)):+ """Vertical plane w x h facing -Y in local space (so rot z=0 faces the street side), UV 0-1."""+ v = [(-w / 2, 0, 0), (w / 2, 0, 0), (w / 2, 0, h), (-w / 2, 0, h)]+ o = mesh_obj(name, v, [(0, 1, 2, 3)], c, mat)+ uv = o.data.uv_layers.new(name="UVMap")+ for i, co in enumerate([(0, 0), (1, 0), (1, 1), (0, 1)]):+ uv.data[i].uv = co+ o.location = loc+ o.rotation_euler = rot+ return o+++def cylinder(name, r, h, c, mat=None, loc=(0, 0, 0), verts=32):+ bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=h, vertices=verts, location=(loc[0], loc[1], loc[2] + h / 2))+ o = bpy.context.object+ o.name = name+ link(o, c)+ if mat:+ o.data.materials.append(mat)+ bpy.ops.object.shade_smooth()+ return o+++def uv_cube(o, scale=1.0):+ """World-size box UVs (1 UV unit = 1 m) so image textures keep real scale."""+ me = o.data+ uv = me.uv_layers.get("UVMap") or me.uv_layers.new(name="UVMap")+ for p in me.polygons:+ n = p.normal+ ax = max(range(3), key=lambda i: abs(n[i]))+ for li in p.loop_indices:+ co = me.vertices[me.loops[li].vertex_index].co+ a, b = [(1, 2), (0, 2), (0, 1)][ax]+ uv.data[li].uv = (co[a] * scale, co[b] * scale)+++# ---------------------------------------------------------------- material helpers++def new_mat(name):+ m = bpy.data.materials.get(name)+ if m:+ return m, None+ m = bpy.data.materials.new(name)+ m.use_nodes = True+ return m, m.node_tree+++def bsdf(nt):+ return nt.nodes["Principled BSDF"]+++def node(nt, kind, **inputs):+ n = nt.nodes.new(kind)+ for k, v in inputs.items():+ if k in n.inputs:+ n.inputs[k].default_value = v+ else:+ setattr(n, k, v)+ return n+++def L(nt, a, b):+ nt.links.new(a, b)+++def ramp(nt, stops, src=None):+ r = nt.nodes.new("ShaderNodeValToRGB")+ els = r.color_ramp.elements+ while len(els) > 2:+ els.remove(els[-1])+ for i, (pos, col) in enumerate(stops):+ e = els[i] if i < 2 else els.new(pos)+ e.position = pos+ e.color = col if len(col) == 4 else (*col, 1)+ if src is not None:+ L(nt, src, r.inputs["Fac"])+ return r+++def texcoord(nt, kind="Object"):+ return nt.nodes.new("ShaderNodeTexCoord").outputs[kind]+++def noise(nt, scale, detail=6, rough=0.55, coord=None, dim="3D"):+ n = node(nt, "ShaderNodeTexNoise", Scale=scale, Detail=detail, Roughness=rough)+ n.noise_dimensions = dim+ if coord is not None:+ L(nt, coord, n.inputs["Vector"])+ return n+++def bump(nt, height, strength=0.2, distance=0.01, normal=None):+ b = node(nt, "ShaderNodeBump", Strength=strength, Distance=distance)+ L(nt, height, b.inputs["Height"])+ if normal is not None:+ L(nt, normal, b.inputs["Normal"])+ return b+++def mix(nt, fac, a, b, blend="MIX"):+ m = nt.nodes.new("ShaderNodeMix")+ m.data_type = "RGBA"+ m.blend_type = blend+ for sock, val in (("Factor", fac), ("A", a), ("B", b)):+ if isinstance(val, bpy.types.NodeSocket):+ L(nt, val, m.inputs[sock])+ else:+ m.inputs[sock].default_value = val+ return m.outputs["Result"]+++def mathn(nt, op, a, b=0.0, clamp=False):+ m = nt.nodes.new("ShaderNodeMath")+ m.operation = op+ m.use_clamp = clamp+ for i, val in enumerate((a, b)):+ if isinstance(val, bpy.types.NodeSocket):+ L(nt, val, m.inputs[i])+ else:+ m.inputs[i].default_value = val+ return m.outputs[0]+++# ---------------------------------------------------------------- materials++def m_plaster(name="plaster", base=(0.62, 0.57, 0.48)):+ m, nt = new_mat(name)+ if not nt:+ return m+ co = texcoord(nt)+ n1 = noise(nt, 3.0, 8, 0.6, co)+ grime = noise(nt, 0.8, 4, 0.5, co)+ col = ramp(nt, [(0.35, (base[0] * 0.72, base[1] * 0.68, base[2] * 0.6)), (0.65, base)], n1.outputs["Fac"])+ # Smoky grime toward the ceiling (object z) mixed with low-frequency blotches.+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ L(nt, texcoord(nt, "Generated"), sep.inputs[0])+ hgt = mathn(nt, "POWER", sep.outputs["Z"], 3.0)+ gfac = mathn(nt, "MULTIPLY", mathn(nt, "ADD", hgt, mathn(nt, "MULTIPLY", grime.outputs["Fac"], 0.35)), 0.55, clamp=True)+ c2 = mix(nt, gfac, col.outputs["Color"], (0.25, 0.2, 0.14, 1), "MULTIPLY")+ b = bsdf(nt)+ L(nt, c2, b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = 0.92+ L(nt, bump(nt, noise(nt, 40, 6, 0.6, co).outputs["Fac"], 0.12, 0.004).outputs[0], b.inputs["Normal"])+ return m+++def m_wood(name, dark=(0.06, 0.03, 0.015), light=(0.2, 0.1, 0.045), along="X", scale=1.0, gloss=0.35, wear=True, fine_mix=0.35, bump_k=0.18):+ """Oiled worn wood: wave-texture grain along an axis, glossy wiped patches, cup rings (voronoi) on top."""+ m, nt = new_mat(name)+ if not nt:+ return m+ co = texcoord(nt)+ mp = nt.nodes.new("ShaderNodeMapping")+ L(nt, co, mp.inputs["Vector"])+ # Stretch the noise along the grain axis.+ s = {"X": (0.12, 3.0, 3.0), "Y": (3.0, 0.12, 3.0), "Z": (3.0, 3.0, 0.12)}[along]+ mp.inputs["Scale"].default_value = [v * scale for v in s]+ wave = node(nt, "ShaderNodeTexWave", Scale=1.6, Distortion=9.0, Detail=6.0)+ wave.wave_type = "BANDS"+ wave.bands_direction = {"X": "Y", "Y": "X", "Z": "X"}[along]+ L(nt, mp.outputs[0], wave.inputs["Vector"])+ fine = noise(nt, 30, 10, 0.7, mp.outputs[0])+ g = mix(nt, fine_mix, wave.outputs["Fac"], fine.outputs["Fac"])+ col = ramp(nt, [(0.2, dark), (0.85, light)], g)+ b = bsdf(nt)+ blot = noise(nt, 1.3, 3, 0.5, co)+ rough = ramp(nt, [(0.35, (gloss * 0.45,) * 3), (0.7, (gloss * 1.9,) * 3)], blot.outputs["Fac"]).outputs["Color"]+ base = col.outputs["Color"]+ if wear:+ # Cup rings: thin bands of voronoi distance, a few per metre.+ # Two sets: glass rings (~3.5 cm radius) and bowl rings (~6 cm), each on about half the cells.+ for sc_, band, sel in ((3.0, 0.105, 0.5), (1.7, 0.1, 0.62)):+ vor = node(nt, "ShaderNodeTexVoronoi", Scale=sc_, Randomness=1.0)+ L(nt, co, vor.inputs["Vector"])+ ring = ramp(nt, [(0.0, (0, 0, 0)), (band - 0.008, (0, 0, 0)), (band, (1, 1, 1)), (band + 0.012, (0, 0, 0))], vor.outputs["Distance"])+ rsel = ramp(nt, [(0.0, (0, 0, 0)), (sel, (0, 0, 0)), (sel + 0.02, (1, 1, 1))], vor.outputs["Color"])+ rings = mathn(nt, "MULTIPLY", ring.outputs["Color"], rsel.outputs["Color"])+ base = mix(nt, mathn(nt, "MULTIPLY", rings, 0.7), base, (0.02, 0.01, 0.005, 1))+ # Worn edges: where the bevelled normal departs from the true normal, the finish is rubbed through.+ bv = nt.nodes.new("ShaderNodeBevel")+ bv.inputs["Radius"].default_value = 0.006+ geo = nt.nodes.new("ShaderNodeNewGeometry")+ dot = nt.nodes.new("ShaderNodeVectorMath")+ dot.operation = "DOT_PRODUCT"+ L(nt, bv.outputs[0], dot.inputs[0])+ L(nt, geo.outputs["Normal"], dot.inputs[1])+ edge = ramp(nt, [(0.9, (1, 1, 1)), (0.985, (0, 0, 0))], dot.outputs["Value"])+ base = mix(nt, mathn(nt, "MULTIPLY", edge.outputs["Color"], 0.8), base, (0.36, 0.22, 0.12, 1))+ rough = mix(nt, edge.outputs["Color"], rough, (0.75, 0.75, 0.75, 1))+ # Edge wear lightens high-traffic zones (low-frequency noise).+ base = mix(nt, mathn(nt, "MULTIPLY", ramp(nt, [(0.55, (0, 0, 0)), (0.8, (1, 1, 1))], noise(nt, 2.0, 4, 0.5, co).outputs["Fac"]).outputs["Color"], 0.35), base, (0.32, 0.2, 0.11, 1))+ L(nt, base, b.inputs["Base Color"])+ L(nt, rough, b.inputs["Roughness"])+ b.inputs["Coat Weight"].default_value = 0.15+ b.inputs["Coat Roughness"].default_value = 0.25+ L(nt, bump(nt, g, bump_k, 0.002).outputs[0], b.inputs["Normal"])+ return m+++def m_concrete_wet(name="concrete_wet"):+ m, nt = new_mat(name)+ if not nt:+ return m+ co = texcoord(nt)+ n1 = noise(nt, 6, 10, 0.65, co)+ col = ramp(nt, [(0.3, (0.035, 0.034, 0.032)), (0.7, (0.11, 0.105, 0.095))], n1.outputs["Fac"])+ puddle = ramp(nt, [(0.48, (0.0,) * 3), (0.56, (1.0,) * 3)], noise(nt, 0.9, 3, 0.5, co).outputs["Fac"])+ b = bsdf(nt)+ L(nt, mix(nt, mathn(nt, "MULTIPLY", puddle.outputs["Color"], 0.5), col.outputs["Color"], (0.015, 0.015, 0.014, 1)), b.inputs["Base Color"])+ rough = mix(nt, puddle.outputs["Color"], (0.7, 0.7, 0.7, 1), (0.08, 0.08, 0.08, 1))+ L(nt, rough, b.inputs["Roughness"])+ L(nt, bump(nt, noise(nt, 60, 8, 0.7, co).outputs["Fac"], 0.25, 0.003).outputs[0], b.inputs["Normal"])+ return m+++def m_stainless(name="stainless", brushed_axis="X", smudge=0.6, dark=False):+ m, nt = new_mat(name)+ if not nt:+ return m+ co = texcoord(nt)+ mp = nt.nodes.new("ShaderNodeMapping")+ L(nt, co, mp.inputs["Vector"])+ mp.inputs["Scale"].default_value = {"X": (1, 400, 400), "Y": (400, 1, 400), "Z": (400, 400, 1)}[brushed_axis]+ brush = noise(nt, 1.0, 4, 0.5, mp.outputs[0])+ smear = noise(nt, 2.5, 6, 0.6, co)+ b = bsdf(nt)+ b.inputs["Metallic"].default_value = 1.0+ c = (0.42, 0.42, 0.43, 1) if dark else (0.62, 0.62, 0.63, 1)+ grease = ramp(nt, [(0.45, (0, 0, 0)), (0.75, (1, 1, 1))], smear.outputs["Fac"])+ L(nt, mix(nt, mathn(nt, "MULTIPLY", grease.outputs["Color"], 0.5 * smudge), c, (0.25, 0.22, 0.17, 1)), b.inputs["Base Color"])+ r = ramp(nt, [(0.0, (0.18,) * 3), (1.0, (0.42,) * 3)], mix(nt, 0.5, brush.outputs["Fac"], grease.outputs["Color"]))+ L(nt, r.outputs["Color"], b.inputs["Roughness"])+ b.inputs["Anisotropic"].default_value = 0.5+ return m+++def m_glass_rain(name="glass_rain", tint=(0.9, 0.95, 0.95)):+ """Door/window glass with raindrops (voronoi bumps) and a streaky dirty film."""+ m, nt = new_mat(name)+ if not nt:+ return m+ co = texcoord(nt)+ vor = node(nt, "ShaderNodeTexVoronoi", Scale=45.0, Randomness=1.0)+ vor.feature = "SMOOTH_F1" if hasattr(vor, "feature") else vor.feature+ L(nt, co, vor.inputs["Vector"])+ drop = ramp(nt, [(0.0, (1, 1, 1)), (0.3, (0, 0, 0))], vor.outputs["Distance"])+ mask = ramp(nt, [(0.55, (0, 0, 0)), (0.6, (1, 1, 1))], vor.outputs["Color"])+ h = mathn(nt, "MULTIPLY", drop.outputs["Color"], mask.outputs["Color"])+ b = bsdf(nt)+ b.inputs["Base Color"].default_value = (*tint, 1)+ b.inputs["Transmission Weight"].default_value = 1.0+ b.inputs["IOR"].default_value = 1.45+ film = noise(nt, 3, 6, 0.6, co)+ L(nt, ramp(nt, [(0.3, (0.02,) * 3), (0.8, (0.12,) * 3)], film.outputs["Fac"]).outputs["Color"], b.inputs["Roughness"])+ L(nt, bump(nt, h, 0.6, 0.002).outputs[0], b.inputs["Normal"])+ return m+++def m_simple(name, color, rough=0.5, metal=0.0, coat=0.0, trans=0.0, ior=1.45, emission=None, estr=0.0, alpha=1.0):+ m, nt = new_mat(name)+ if not nt:+ return m+ b = bsdf(nt)+ b.inputs["Base Color"].default_value = (*color, 1)+ b.inputs["Roughness"].default_value = rough+ b.inputs["Metallic"].default_value = metal+ b.inputs["Coat Weight"].default_value = coat+ b.inputs["Transmission Weight"].default_value = trans+ b.inputs["IOR"].default_value = ior+ b.inputs["Alpha"].default_value = alpha+ if emission:+ b.inputs["Emission Color"].default_value = (*emission, 1)+ b.inputs["Emission Strength"].default_value = estr+ return m+++def m_image(name, path, rough=0.7, emission=0.0, translucent=0.0, alpha_from_image=False, bump_strength=0.0):+ m, nt = new_mat(name)+ if not nt:+ return m+ tex = nt.nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(path, check_existing=True)+ b = bsdf(nt)+ L(nt, tex.outputs["Color"], b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = rough+ if emission:+ L(nt, tex.outputs["Color"], b.inputs["Emission Color"])+ b.inputs["Emission Strength"].default_value = emission+ if translucent:+ b.inputs["Subsurface Weight"].default_value = 0.0+ tr = nt.nodes.new("ShaderNodeBsdfTranslucent")+ L(nt, tex.outputs["Color"], tr.inputs["Color"])+ mx = nt.nodes.new("ShaderNodeMixShader")+ mx.inputs[0].default_value = translucent+ out = nt.nodes["Material Output"]+ L(nt, b.outputs[0], mx.inputs[1])+ L(nt, tr.outputs[0], mx.inputs[2])+ L(nt, mx.outputs[0], out.inputs["Surface"])+ if bump_strength:+ bw = nt.nodes.new("ShaderNodeRGBToBW")+ L(nt, tex.outputs["Color"], bw.inputs[0])+ L(nt, bump(nt, bw.outputs[0], bump_strength, 0.002).outputs[0], b.inputs["Normal"])+ return m+++def m_tile(name="tile_white"):+ m, nt = new_mat(name)+ if not nt:+ return m+ co = texcoord(nt, "UV") # brick is 2D (ignores Z of object coords), so use the world-scale box UVs+ br = node(nt, "ShaderNodeTexBrick", Scale=1.0, **{"Mortar Size": 0.012, "Brick Width": 0.1, "Row Height": 0.1})+ br.offset = 0.0+ L(nt, co, br.inputs["Vector"])+ br.inputs["Color1"].default_value = (0.78, 0.77, 0.72, 1)+ br.inputs["Color2"].default_value = (0.72, 0.71, 0.66, 1)+ br.inputs["Mortar"].default_value = (0.13, 0.1, 0.06, 1) # stained grout+ grime = noise(nt, 1.5, 5, 0.55, co)+ b = bsdf(nt)+ L(nt, mix(nt, mathn(nt, "MULTIPLY", grime.outputs["Fac"], 0.45), br.outputs["Color"], (0.35, 0.28, 0.17, 1), "MULTIPLY"), b.inputs["Base Color"])+ L(nt, ramp(nt, [(0.0, (0.08,) * 3), (1.0, (0.6,) * 3)], br.outputs["Fac"]).outputs["Color"], b.inputs["Roughness"])+ L(nt, bump(nt, mathn(nt, "SUBTRACT", 1.0, br.outputs["Fac"]), 0.4, 0.003).outputs[0], b.inputs["Normal"])+ return m+++# ---------------------------------------------------------------- lights++def area(name, c, loc, rot, size, energy, color=(1, 1, 1), shape="RECTANGLE", size_y=None, spread=180):+ d = bpy.data.lights.new(name, "AREA")+ d.shape = shape+ d.size = size+ if size_y:+ d.size_y = size_y+ d.energy = energy+ d.color = color+ d.spread = math.radians(spread)+ o = bpy.data.objects.new(name, d)+ c.objects.link(o)+ o.location = loc+ o.rotation_euler = rot+ # Fill/glow cards must not show up as white rectangles, directly or refracted through the rough door glass.+ o.visible_camera = False+ o.visible_transmission = False+ return o+++def point(name, c, loc, energy, color=(1, 0.75, 0.45), radius=0.03):+ d = bpy.data.lights.new(name, "POINT")+ d.energy = energy+ d.color = color+ d.shadow_soft_size = radius+ o = bpy.data.objects.new(name, d)+ c.objects.link(o)+ o.location = loc+ return o+++def spot(name, c, loc, rot, energy, color=(1, 0.75, 0.45), angle=110, blend=0.6, radius=0.02):+ d = bpy.data.lights.new(name, "SPOT")+ d.energy = energy+ d.color = color+ d.spot_size = math.radians(angle)+ d.spot_blend = blend+ d.shadow_soft_size = radius+ o = bpy.data.objects.new(name, d)+ c.objects.link(o)+ o.location = loc+ o.rotation_euler = rot+ return o+++def blackbody(k):+ """Approximate RGB for a colour temperature (for light colours without nodes)."""+ t = k / 100.0+ r = 255 if t <= 66 else 329.7 * (t - 60) ** -0.1332+ g = 99.47 * math.log(t) - 161.12 if t <= 66 else 288.1 * (t - 60) ** -0.0755+ b = 255 if t >= 66 else (0 if t <= 19 else 138.5 * math.log(t - 10) - 305.04)+ return tuple(max(0, min(255, x)) / 255 for x in (r, g, b))diff --git a/scenes/tokyo-ramen-shop/scripts/lighting.py b/scenes/tokyo-ramen-shop/scripts/lighting.pynew file mode 100644index 0000000..d914f00--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/lighting.py@@ -0,0 +1,103 @@+"""Night lighting for the ramen shop (design coordinates; build.py mirrors everything afterwards).++Key: warm 2700 K pendants over the counter. Kitchen: dimmer 3200 K hood strip + one ceiling tube.+Accents: ticket machine and drink fridge glow (cool), red akachochin outside, cool street fill through the glass.+Atmosphere: low-density room haze + steam volumes over the stockpots."""+import math++import bpy++import shell as S+from lib import L, area, blackbody, box, m_simple, mathn, new_mat, node, noise, point, spot, texcoord++WARM = blackbody(2600)+KITCHEN = blackbody(3300)+STREET = (0.5, 0.62, 1.0)+++def haze_material(density):+ m, nt = new_mat("haze")+ if nt:+ nt.nodes.remove(nt.nodes["Principled BSDF"])+ v = nt.nodes.new("ShaderNodeVolumePrincipled")+ v.inputs["Density"].default_value = density+ v.inputs["Anisotropy"].default_value = 0.45+ v.inputs["Color"].default_value = (0.9, 0.9, 0.92, 1)+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])+ return m+++def steam_material():+ """Wispy steam: noise density, thinning with height, drifting with the frame via the 4D W coordinate."""+ m, nt = new_mat("steam")+ if nt:+ nt.nodes.remove(nt.nodes["Principled BSDF"])+ co = texcoord(nt, "Generated")+ n = noise(nt, 4.0, 6, 0.6, co, dim="4D")+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ L(nt, co, sep.inputs[0])+ fade = mathn(nt, "SUBTRACT", 1.0, sep.outputs["Z"])+ radial = mathn(nt, "POWER", fade, 1.5)+ dens = mathn(nt, "MULTIPLY", mathn(nt, "MAXIMUM", mathn(nt, "SUBTRACT", n.outputs["Fac"], 0.45), 0.0), 30.0)+ dens = mathn(nt, "MULTIPLY", dens, radial)+ v = nt.nodes.new("ShaderNodeVolumePrincipled")+ v.inputs["Color"].default_value = (0.95, 0.95, 0.95, 1)+ v.inputs["Anisotropy"].default_value = 0.6+ L(nt, dens, v.inputs["Density"])+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])+ # Animate the noise W with the frame so steam drifts in the clip.+ fc = n.inputs["W"].driver_add("default_value")+ fc.driver.expression = "frame * 0.025"+ return m+++def build(c, haze=0.006, steam_spots=()):+ sc = bpy.context.scene+ # Pendants: a downward spot (the pool on the counter) + a weak point inside the shade for its glow.+ for i, y in enumerate(S.PENDANT_Y):+ x, z = S.CX + 0.22, 1.74+ spot(f"pendant_spot_{i}", c, (x, y, z), (0, 0, 0), 70, WARM, angle=125, blend=0.8, radius=0.03)+ point(f"pendant_glow_{i}", c, (x, y, z + 0.09), 6, WARM, radius=0.03)+ # Kitchen: strip under the hood and a single ceiling tube over the cook's aisle.+ area("hood_strip", c, (S.W - 0.38, 4.4, 1.83), (0, 0, 0), 0.12, 35, KITCHEN, size_y=1.6)+ area("kitchen_tube", c, (2.75, 4.0, 2.55), (0, 0, 0), 0.08, 14, KITCHEN, size_y=1.2)+ area("kitchen_tube_front", c, (2.75, 1.6, 2.55), (0, 0, 0), 0.08, 6, KITCHEN, size_y=1.0)+ # Ticket machine face glow (machine on the left wall near the door, facing +X).+ # Area lights shine along their local -Z: rot x +90 points +Y, rot y -90 points +X.+ area("ticket_glow", c, (0.31, 0.52, 1.15), (math.radians(90), 0, 0), 0.5, 10, (0.85, 0.92, 1.0), size_y=0.8)+ # Drink fridge glow.+ area("fridge_glow", c, (0.66, 6.68, 1.0), (0, math.radians(-90), 0), 0.45, 8, (0.88, 0.95, 1.0), size_y=1.2)+ # Red lantern outside: light source inside the paper body.+ lx, ly, lz = S.LANTERN+ point("lantern_light", c, (lx, ly, lz + 0.3), 35, (1.0, 0.22, 0.08), radius=0.12)+ # Cool street fill through the door and window, plus a faint sky.+ area("street_fill", c, (S.W / 2, -2.0, 2.2), (math.radians(70), 0, 0), 3.0, 30, STREET, size_y=1.5)+ area("street_bounce", c, (S.W / 2, -1.0, 0.1), (math.radians(100), 0, 0), 3.0, 6, (0.6, 0.65, 0.8), size_y=0.8)+ sc.world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.006, 0.008, 0.013, 1)++ # Atmosphere: haze box filling the shop interior (kept inside so the backdrop stays crisp).+ if haze:+ hz = box("haze_volume", (0.02, 0.02, 0.01), (S.W - 0.02, S.D - 0.02, S.H - 0.01), c, haze_material(haze), bevel=0)+ hz.visible_shadow = False+ sm = steam_material()+ for i, (x, y, z, r) in enumerate(steam_spots):+ bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=0.9, vertices=24, location=(x, y, z + 0.45))+ o = bpy.context.object+ o.name = f"steam_{i}"+ for uc in list(o.users_collection):+ uc.objects.unlink(o)+ c.objects.link(o)+ o.data.materials.append(sm)+ o.visible_shadow = False++ # Render settings tuned for a dark interior with volumes.+ cy = sc.cycles+ cy.max_bounces = 8+ cy.diffuse_bounces = 4+ cy.glossy_bounces = 4+ cy.transmission_bounces = 8+ cy.volume_bounces = 1+ cy.transparent_max_bounces = 8+ cy.volume_step_rate = 4.0+ cy.sample_clamp_indirect = 8.0+ cy.blur_glossy = 1.0diff --git a/scenes/tokyo-ramen-shop/scripts/pick.mjs b/scenes/tokyo-ramen-shop/scripts/pick.mjsnew file mode 100644index 0000000..d98e3df--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/pick.mjs@@ -0,0 +1,8 @@+// node scenes/tokyo-ramen-shop/scripts/pick.mjs id model "reason" [id model "reason" ...] -> merges into scenes/tokyo-ramen-shop/picks.json+import { readFileSync, writeFileSync } from 'node:fs';+const f = new URL('../picks.json', import.meta.url);+const p = JSON.parse(readFileSync(f, 'utf8'));+const a = process.argv.slice(2);+for (let i = 0; i < a.length; i += 3) p[a[i]] = { model: a[i + 1], reason: a[i + 2] };+writeFileSync(f, JSON.stringify(p, null, 2));+console.log(Object.keys(p).length, 'picks');diff --git a/scenes/tokyo-ramen-shop/scripts/post.py b/scenes/tokyo-ramen-shop/scripts/post.pynew file mode 100644index 0000000..49e1caa--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/post.py@@ -0,0 +1,37 @@+"""Compositor (Blender 5.0 node-group compositor): glare + lens distortion with chromatic aberration.+Grade, vignette and grain happen afterwards in scenes/tokyo-ramen-shop/scripts/finish.sh (ffmpeg), so they can be tuned without re-rendering."""+import bpy+++def _set(n, name, v):+ s = n.inputs.get(name)+ if s is None:+ raise KeyError(f"{n.bl_idname} has no input {name}: {[i.name for i in n.inputs]}")+ s.default_value = v+++def build(glare=0.12, distortion=-0.015, dispersion=0.01):+ sc = bpy.context.scene+ t = bpy.data.node_groups.new("ramen_post", "CompositorNodeTree")+ t.interface.new_socket("Image", in_out="OUTPUT", socket_type="NodeSocketColor")+ N, Lk = t.nodes, t.links.new+ rl = N.new("CompositorNodeRLayers")+ out = N.new("NodeGroupOutput")+ g = N.new("CompositorNodeGlare")+ _set(g, "Type", "Fog Glow")+ _set(g, "Quality", "High")+ _set(g, "Threshold", 1.0)+ _set(g, "Strength", glare)+ Lk(rl.outputs["Image"], g.inputs["Image"])+ ld = N.new("CompositorNodeLensdist")+ _set(ld, "Distortion", distortion)+ _set(ld, "Dispersion", dispersion)+ try:+ _set(ld, "Fit", True)+ except Exception:+ pass+ Lk(g.outputs["Image"], ld.inputs["Image"])+ Lk(ld.outputs["Image"], out.inputs["Image"])+ sc.compositing_node_group = t+ sc.render.use_compositing = True+ return tdiff --git a/scenes/tokyo-ramen-shop/scripts/prep.py b/scenes/tokyo-ramen-shop/scripts/prep.pynew file mode 100644index 0000000..609244e--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/prep.py@@ -0,0 +1,287 @@+"""Prep the picked generated props into scenes/tokyo-ramen-shop/lib/<id>.blend.++Per prop: import GLB -> join -> turn so its front faces -Y (Tripo fronts face +X) -> scale to the manifest size+-> origin at bottom centre -> decimate to a tri budget -> cap texture size -> material fixes (glass, glow, gloss) -> save.++blender -b --factory-startup --python scenes/tokyo-ramen-shop/scripts/prep.py -- [--only id,id]+"""+import json+import math+import os+import sys++import bpy+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(__file__))+from lib import L, SCENE_DIR, ROOT # noqa: E402++argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+ONLY = argv[argv.index("--only") + 1].split(",") if "--only" in argv else None+MAN = {p["id"]: p for p in json.load(open(os.path.join(SCENE_DIR, "assets.json")))["generate"]}+PICKS = json.load(open(os.path.join(SCENE_DIR, "picks.json")))+LIB = os.path.join(SCENE_DIR, "lib")+os.makedirs(LIB, exist_ok=True)+YAW = {"tripo-h31": -90, "meshy": 0} # degrees about Z that bring each generator's front to -Y++# Tri budgets: props the hero cameras see up close get more.+HERO = {"ramen_bowl_unfinished", "condiment_caddy", "ramen_water_glass", "ramen_chopstick_cup", "stockpot",+ "ticket_machine", "ramen_stool", "ramen_tare_containers", "ramen_cutting_board", "ramen_noodle_boiler", "lantern"}+TEX_4K = {"ticket_machine", "ramen_drink_fridge", "lantern"}+++# ------------------------------------------------------------------ material fixes++def principled(m):+ return next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)+++def base_tex(m):+ b = principled(m)+ s = b.inputs["Base Color"]+ return s.links[0].from_node if s.is_linked else None+++def fx_coat(o, w=0.5, r=0.06):+ """Glazed ceramic / lacquer: clear coat over the baked albedo."""+ for m in o.data.materials:+ b = principled(m)+ b.inputs["Coat Weight"].default_value = w+ b.inputs["Coat Roughness"].default_value = r+++def fx_glassy(o, rough=0.06):+ """Glass bottles with opaque contents baked into the texture: keep the albedo, add a glossy glass-like coat."""+ for m in o.data.materials:+ b = principled(m)+ b.inputs["Coat Weight"].default_value = 1.0+ b.inputs["Coat Roughness"].default_value = 0.02+ b.inputs["Coat IOR"].default_value = 1.5+ b.inputs["Specular IOR Level"].default_value = 0.7+ if not b.inputs["Roughness"].is_linked:+ b.inputs["Roughness"].default_value = rough+++def fx_clear_glass(o):+ """Whole object is clear glass (water glass): replace the baked material with real glass + faint tint."""+ m = bpy.data.materials.new("clear_glass")+ m.use_nodes = True+ b = principled(m)+ b.inputs["Base Color"].default_value = (0.92, 0.96, 0.95, 1)+ b.inputs["Roughness"].default_value = 0.015+ b.inputs["Transmission Weight"].default_value = 1.0+ b.inputs["IOR"].default_value = 1.5+ o.data.materials.clear()+ o.data.materials.append(m)+++def _front_mask(nt, zmin, zmax, facing=0.5):+ """1 where the surface faces local -Y (the prop's front) and object-space z is within [zmin, zmax]."""+ geo = nt.nodes.new("ShaderNodeNewGeometry")+ vt = nt.nodes.new("ShaderNodeVectorTransform")+ vt.vector_type = "NORMAL"+ vt.convert_from = "WORLD"+ vt.convert_to = "OBJECT"+ L(nt, geo.outputs["Normal"], vt.inputs[0])+ dot = nt.nodes.new("ShaderNodeVectorMath")+ dot.operation = "DOT_PRODUCT"+ dot.inputs[1].default_value = (0, -1, 0)+ L(nt, vt.outputs[0], dot.inputs[0])+ gt = nt.nodes.new("ShaderNodeMath")+ gt.operation = "GREATER_THAN"+ gt.inputs[1].default_value = facing+ L(nt, dot.outputs["Value"], gt.inputs[0])+ tc = nt.nodes.new("ShaderNodeTexCoord")+ sep = nt.nodes.new("ShaderNodeSeparateXYZ")+ L(nt, tc.outputs["Object"], sep.inputs[0])+ lo = nt.nodes.new("ShaderNodeMath")+ lo.operation = "GREATER_THAN"+ lo.inputs[1].default_value = zmin+ L(nt, sep.outputs["Z"], lo.inputs[0])+ hi = nt.nodes.new("ShaderNodeMath")+ hi.operation = "LESS_THAN"+ hi.inputs[1].default_value = zmax+ L(nt, sep.outputs["Z"], hi.inputs[0])+ a = nt.nodes.new("ShaderNodeMath")+ a.operation = "MULTIPLY"+ L(nt, lo.outputs[0], a.inputs[0])+ L(nt, hi.outputs[0], a.inputs[1])+ b = nt.nodes.new("ShaderNodeMath")+ b.operation = "MULTIPLY"+ L(nt, a.outputs[0], b.inputs[0])+ L(nt, gt.outputs[0], b.inputs[1])+ return b.outputs[0]+++def fx_front_glow(o, strength, zmin, zmax, gamma=2.2):+ """Backlit panel (ticket buttons, fridge interior): emit the albedo, brightest where the texture is light."""+ for m in o.data.materials:+ nt = m.node_tree+ tex = base_tex(m)+ b = principled(m)+ if tex is None:+ continue+ pw = nt.nodes.new("ShaderNodeMath")+ pw.operation = "POWER"+ bw = nt.nodes.new("ShaderNodeRGBToBW")+ L(nt, tex.outputs["Color"], bw.inputs[0])+ L(nt, bw.outputs[0], pw.inputs[0])+ pw.inputs[1].default_value = gamma+ mask = _front_mask(nt, zmin, zmax)+ k = nt.nodes.new("ShaderNodeMath")+ k.operation = "MULTIPLY"+ L(nt, pw.outputs[0], k.inputs[0])+ L(nt, mask, k.inputs[1])+ s = nt.nodes.new("ShaderNodeMath")+ s.operation = "MULTIPLY"+ s.inputs[1].default_value = strength+ L(nt, k.outputs[0], s.inputs[0])+ L(nt, tex.outputs["Color"], b.inputs["Emission Color"])+ L(nt, s.outputs[0], b.inputs["Emission Strength"])+++def fx_lantern(o, strength=2.2):+ """Paper lantern lit from inside: translucent paper + emission of the albedo (dark kanji stay dark)."""+ for m in o.data.materials:+ nt = m.node_tree+ tex = base_tex(m)+ b = principled(m)+ if tex is None:+ continue+ L(nt, tex.outputs["Color"], b.inputs["Emission Color"])+ b.inputs["Emission Strength"].default_value = strength+ b.inputs["Subsurface Weight"].default_value = 0.3+++def fx_glass_front(o, zmin, zmax):+ """Glass-front fridge: add a real glass pane in front of the door so it gets reflections and depth."""+ lo, hi = bounds([o])+ w = (hi.x - lo.x) * 0.82+ me = bpy.data.meshes.new("door_glass")+ y = lo.y - 0.004+ me.from_pydata([(-w / 2, y, zmin), (w / 2, y, zmin), (w / 2, y, zmax), (-w / 2, y, zmax)], [], [(0, 1, 2, 3)])+ g = bpy.data.objects.new(o.name + "_glass", me)+ bpy.context.scene.collection.objects.link(g)+ m = bpy.data.materials.new("fridge_glass")+ m.use_nodes = True+ b = principled(m)+ b.inputs["Roughness"].default_value = 0.03+ b.inputs["Transmission Weight"].default_value = 1.0+ b.inputs["Base Color"].default_value = (0.95, 0.97, 0.97, 1)+ me.materials.append(m)+ g.parent = o+++FIX = {+ "ramen_water_glass": [(fx_clear_glass, {})],+ "condiment_caddy": [(fx_glassy, {})],+ "ramen_soy_bottles": [(fx_coat, {"w": 0.6, "r": 0.1})],+ "ramen_bowl_stack": [(fx_coat, {})],+ "ramen_bowl_unfinished": [(fx_coat, {"w": 0.6, "r": 0.04})],+ "ramen_maneki_neko": [(fx_coat, {"w": 0.7, "r": 0.05})],+ "ramen_dish_rack": [(fx_coat, {"w": 0.4, "r": 0.08})],+ "ramen_chopstick_cup": [(fx_coat, {"w": 0.35, "r": 0.15})],+ "ticket_machine": [(fx_front_glow, {"strength": 3.0, "zmin": 0.62, "zmax": 1.5})],+ "ramen_drink_fridge": [(fx_front_glow, {"strength": 2.5, "zmin": 0.25, "zmax": 1.55}), (fx_glass_front, {"zmin": 0.25, "zmax": 1.5})],+ "lantern": [(fx_lantern, {})],+ "ramen_vending_machine": [(fx_front_glow, {"strength": 3.0, "zmin": 0.35, "zmax": 1.75})],+ "ramen_beer_bottle_glass": [(fx_glassy, {})],+ "ramen_ashtray": [(fx_glassy, {"rough": 0.03})],+ "ramen_shelf_jars": [(fx_glassy, {})],+ "ramen_condiment_tray2": [(fx_glassy, {})],+ "ramen_tea_cup": [(fx_coat, {"w": 0.6, "r": 0.08})],+ "ramen_beni_shoga_pot": [(fx_coat, {})],+ "ramen_plate_stack": [(fx_coat, {})],+ "ramen_daruma": [(fx_coat, {"w": 0.4, "r": 0.2})],+ "ramen_smartphone": [(fx_coat, {"w": 1.0, "r": 0.03})],+ "ramen_egg_container": [(fx_coat, {"w": 0.8, "r": 0.05})],+ "ramen_chashu_tray": [(fx_coat, {"w": 0.5, "r": 0.1})],+}+++# ------------------------------------------------------------------ geometry++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 prep(pid, model):+ bpy.ops.wm.read_factory_settings(use_empty=True)+ glb = os.path.join(ROOT, "assets", "gen", model, pid, "model.glb")+ bpy.ops.import_scene.gltf(filepath=glb)+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]+ for o in bpy.data.objects:+ o.select_set(o in meshes)+ bpy.context.view_layer.objects.active = meshes[0]+ # Bake parent transforms into the meshes, drop empties, join.+ bpy.ops.object.parent_clear(type="CLEAR_KEEP_TRANSFORM")+ for o in [o for o in bpy.data.objects if o.type != "MESH"]:+ bpy.data.objects.remove(o)+ if len(meshes) > 1:+ bpy.ops.object.join()+ o = bpy.context.view_layer.objects.active+ o.name = pid+ o.data.name = pid+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)+ # glTF imports use quaternion rotation mode, so turn the mesh data itself rather than rotation_euler.+ o.data.transform(Matrix.Rotation(math.radians(YAW[model]), 4, "Z"))+ o.data.update()+ bpy.context.view_layer.update()++ lo, hi = bounds([o])+ size = hi - lo+ spec = MAN[pid]+ s = spec["h"] / size.z if "h" in spec else spec["m"] / max(size)+ me = o.data+ centre = Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))+ if "dims" in spec:+ # Boxy appliances: generators invent the depth, so fit width/depth/height separately.+ w, d, h = spec["dims"]+ S = Matrix.Diagonal((w / size.x, d / size.y, h / size.z, 1))+ s = h / size.z+ else:+ S = Matrix.Scale(s, 4)+ me.transform(S @ Matrix.Translation(-centre))+ me.update()+ o.location = (0, 0, 0)++ me.calc_loop_triangles()+ tris = len(me.loop_triangles)+ budget = 220_000 if pid in HERO else (40_000 if max(size) * s < 0.3 else 90_000)+ if tris > budget * 1.1:+ d = o.modifiers.new("dec", "DECIMATE")+ d.ratio = budget / tris+ d.use_collapse_triangulate = True+ bpy.ops.object.modifier_apply(modifier="dec")+ for p in me.polygons:+ p.use_smooth = True++ cap = 4096 if pid in TEX_4K else 2048+ for img in bpy.data.images:+ # glTF images arrive already packed. Re-packing an unmodified one (empty filepath) silently drops+ # its data, so only resized images get packed again (from their new pixel buffer).+ if img.source == "FILE" and img.size[0] > cap:+ img.scale(cap, cap)+ img.pack()++ for fn, kw in FIX.get(pid, FIX.get(spec.get("replaces", ""), [])): # _nb variants share the original's fixes+ fn(o, **kw)+ o["source_model"] = model+ o["target"] = spec.get("h", spec.get("m"))+ me.calc_loop_triangles()+ out = os.path.join(LIB, pid + ".blend")+ bpy.ops.wm.save_as_mainfile(filepath=out, compress=True)+ lo, hi = bounds([o])+ print(f"PREP {pid} {model} tris {tris}->{len(me.loop_triangles)} size {tuple(round(v, 3) for v in (hi - lo))}", flush=True)+++for pid, pick in PICKS.items():+ if ONLY and pid not in ONLY:+ continue+ try:+ prep(pid, pick["model"])+ except Exception as e:+ print("PREP FAILED", pid, repr(e), flush=True)diff --git a/scenes/tokyo-ramen-shop/scripts/process_r2.sh b/scenes/tokyo-ramen-shop/scripts/process_r2.shnew file mode 100644index 0000000..3ed03b9--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/process_r2.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash+# Round-2 process images: wide + counter, lit and clay, after each densify pass (no steam), via the GPU queue.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++base="shell,dress"+for p in passA passB passC grime; do+ base="$base,$p"+ for clay in "" "--clay"; do+ tag="_r2_${p}${clay:+_clay}"+ bash pipeline/gpu_run.sh "$B" -b --factory-startup --python scenes/tokyo-ramen-shop/scripts/build.py -- --stages "$base,light,post" --preview wide,counter --samples 40 --res 960 --tag "$tag" $clay 2>&1 | grep -E "rendered|Error|Traceback"+ done+done++P=scenes/tokyo-ramen-shop/out/prev; O=scenes/tokyo-ramen-shop/out/process+for p in passA passB passC grime; do+ "$FF" -v error -y -i $P/wide_r2_$p.png -i $P/counter_r2_$p.png -i $P/wide_r2_${p}_clay.png -i $P/counter_r2_${p}_clay.png \+ -filter_complex "[0][1]hstack[a];[2][3]hstack[b];[a][b]vstack" $O/r2_$p.png && echo "sheet $p"+donediff --git a/scenes/tokyo-ramen-shop/scripts/r2gen.py b/scenes/tokyo-ramen-shop/scripts/r2gen.pynew file mode 100644index 0000000..0064d7a--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/r2gen.py@@ -0,0 +1,255 @@+"""Round-2 generated assets, applied to the *mirrored* scene (world coordinates), so the same code patches the saved+ramen_r2.blend (keeping its baked steam caches) and runs at the end of build.py.++textures(): brighter street backdrop, image neon signs, alpha-keyed decals (hood drips, backsplash splatter,+counter rings, floor grime, fingerprints), generated flyers / price strips / sticker sheet replacing the+text-object versions, a peeling winter-special poster.+props(): round-2 picks placed with dress.place in MIRROR mode, swapping out the reused round-1 instances."""+import math+import os+import random++import bpy+from mathutils import Matrix, Vector++import clutter+import dress+import shell as S+from lib import L, TEX, bsdf, coll, mathn, new_mat++W = S.W+rng = random.Random(23)+++def wx(design_x):+ return W - design_x+++# ------------------------------------------------------------------ materials++def _img(name):+ return bpy.data.images.load(os.path.join(TEX, f"{name}_0.png"), check_existing=True)+++def m_decal(name, tex, key="white", color_mul=(1, 1, 1), rough=0.6, gain=1.6, gloss_coat=0.0, uv_rect=None):+ """Image decal; alpha keyed from luminance: key='white' (dark marks on white) or 'black' (light marks on black)."""+ m, nt = new_mat(name)+ if not nt:+ return m+ t = nt.nodes.new("ShaderNodeTexImage")+ t.image = _img(tex)+ t.extension = "CLIP"+ if uv_rect:+ uv = nt.nodes.new("ShaderNodeTexCoord")+ mp = nt.nodes.new("ShaderNodeMapping")+ (u0, v0), (u1, v1) = uv_rect+ mp.inputs["Location"].default_value = (u0, v0, 0)+ mp.inputs["Scale"].default_value = (u1 - u0, v1 - v0, 1)+ L(nt, uv.outputs["UV"], mp.inputs["Vector"])+ L(nt, mp.outputs[0], t.inputs["Vector"])+ bw = nt.nodes.new("ShaderNodeRGBToBW")+ L(nt, t.outputs["Color"], bw.inputs[0])+ a = bw.outputs[0] if key == "black" else mathn(nt, "SUBTRACT", 1.0, bw.outputs[0])+ a = mathn(nt, "MULTIPLY", mathn(nt, "SUBTRACT", a, 0.06), gain, clamp=True)+ b = bsdf(nt)+ mul = nt.nodes.new("ShaderNodeMix")+ mul.data_type = "RGBA"+ mul.blend_type = "MULTIPLY"+ mul.inputs["Factor"].default_value = 1.0+ mul.inputs["B"].default_value = (*color_mul, 1)+ L(nt, t.outputs["Color"], mul.inputs["A"])+ L(nt, mul.outputs["Result"], b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = rough+ b.inputs["Coat Weight"].default_value = gloss_coat+ L(nt, a, b.inputs["Alpha"])+ return m+++def m_print(name, tex, rough=0.8, emission=0.0, uv_rect=None, key=None):+ """Printed paper / backlit sign: plain image material (optional emission, optional white key)."""+ m, nt = new_mat(name)+ if not nt:+ return m+ t = nt.nodes.new("ShaderNodeTexImage")+ t.image = _img(tex)+ if uv_rect:+ uv = nt.nodes.new("ShaderNodeTexCoord")+ mp = nt.nodes.new("ShaderNodeMapping")+ (u0, v0), (u1, v1) = uv_rect+ mp.inputs["Location"].default_value = (u0, v0, 0)+ mp.inputs["Scale"].default_value = (u1 - u0, v1 - v0, 1)+ L(nt, uv.outputs["UV"], mp.inputs["Vector"])+ L(nt, mp.outputs[0], t.inputs["Vector"])+ b = bsdf(nt)+ L(nt, t.outputs["Color"], b.inputs["Base Color"])+ b.inputs["Roughness"].default_value = rough+ if emission:+ L(nt, t.outputs["Color"], b.inputs["Emission Color"])+ b.inputs["Emission Strength"].default_value = emission+ if key == "white":+ bw = nt.nodes.new("ShaderNodeRGBToBW")+ L(nt, t.outputs["Color"], bw.inputs[0])+ L(nt, mathn(nt, "MULTIPLY", mathn(nt, "SUBTRACT", 0.97, bw.outputs[0]), 25.0, clamp=True), b.inputs["Alpha"])+ if key == "black":+ bw = nt.nodes.new("ShaderNodeRGBToBW")+ L(nt, t.outputs["Color"], bw.inputs[0])+ L(nt, mathn(nt, "MULTIPLY", bw.outputs[0], 6.0, clamp=True), b.inputs["Alpha"])+ return m+++def decal(c, name, mat, w, h, origin, direction, up=(0, 0, 1), spin=0.0, offset=0.0015, res=(2, 2), curl=0.0):+ p = clutter.paper(name, w, h, c, mat, curl=curl, res=res)+ for mod in list(p.modifiers):+ p.modifiers.remove(mod) # decals are zero-thickness films+ if not clutter.stick(p, origin, direction, up, offset):+ bpy.data.objects.remove(p)+ return None+ if spin:+ p.matrix_world = p.matrix_world @ Matrix.Rotation(math.radians(spin), 4, "Z")+ p.visible_shadow = False+ return p+++def _remove_with_children(o):+ for ch in list(o.children_recursive):+ bpy.data.objects.remove(ch)+ bpy.data.objects.remove(o)+++# ------------------------------------------------------------------ textures pass++def textures():+ c = coll("r2_textures", bpy.data.collections["ramen"])+ # Brighter, richer street photo behind the door/window.+ bd = bpy.data.objects.get("street_backdrop")+ if bd and os.path.exists(os.path.join(TEX, "street_backdrop2_nb_0.png")):+ for n in bd.data.materials[0].node_tree.nodes:+ if n.type == "TEX_IMAGE":+ n.image = _img("street_backdrop2_nb")+ if n.type == "EMISSION":+ n.inputs["Strength"].default_value = 1.3+ # Neon: image signs (glowing, black keyed out) in place of the text-object neon.+ for old, tex, w, h, em in (("neon_izakaya", "neon_sign_a", 0.62, 0.83, 6.0), ("neon_snack", "neon_sign_b", 0.5, 0.67, 5.0)):+ o = bpy.data.objects.get(old)+ if not o:+ continue+ loc = o.matrix_world.translation.copy()+ box = bpy.data.objects.get(old + "_box")+ bpy.data.objects.remove(o)+ if box:+ bpy.data.objects.remove(box)+ s = clutter.paper(old + "_img", w, h, c, m_print(old + "_img", tex, 0.4, emission=em, key="black"), res=(1, 1))+ for mod in list(s.modifiers):+ s.modifiers.remove(mod)+ # Face +Y (toward the shop), upright.+ # Local +Z (front) -> world +Y, local +Y (up) -> world +Z, local +X -> world -X (viewer's right).+ s.matrix_world = Matrix.Translation(loc) @ Matrix(((-1, 0, 0), (0, 0, 1), (0, 1, 0))).transposed().to_4x4()+ # Grease drips down the hood front (faces the customers: world +X at x = 0.75).+ drips = m_decal("decal_drips", "decal_grease_drips", key="black", color_mul=(0.55, 0.38, 0.18), rough=0.15, gain=2.2, gloss_coat=0.6)+ for y in (3.9, 4.9):+ decal(c, "decal_drips", drips, 1.0, 0.42, (1.3, y, 2.1), (-1, 0, 0))+ # Oil splatter on the backsplash behind the range and boiler.+ spl = m_decal("decal_splatter", "decal_grease_splatter", key="white", color_mul=(0.32, 0.24, 0.17), rough=0.25, gain=0.5, gloss_coat=0.4) # 1.4 read as orange wallpaper+ for y, z, sp in ((3.75, 1.2, 0), (4.6, 1.3, 90), (5.4, 1.15, 200)):+ decal(c, "decal_splatter", spl, 0.75, 0.75, (0.6, y, z), (-1, 0, 0), spin=sp)+ # Rings from bowls and glasses on the counter between the place settings.+ rings = m_decal("decal_rings", "decal_rings", key="white", color_mul=(0.55, 0.42, 0.3), rough=0.35, gain=0.55) # subtle+ for y in (2.55, 3.95, 4.8, 5.85):+ decal(c, "decal_rings", rings, 0.28, 0.28, (2.3, y, 1.6), (0, 0, -1), up=(1, 0, 0), spin=rng.uniform(0, 360), offset=0.0008)+ # Footprints and grime on the floor: customer aisle and kitchen aisle.+ grime = m_decal("decal_floor", "decal_floor_grime", key="white", color_mul=(0.5, 0.45, 0.4), rough=0.8, gain=1.1)+ for x, y in ((2.85, 0.9), (2.95, 2.3), (2.8, 3.9), (3.0, 5.3), (0.85, 2.2), (0.85, 4.3), (0.8, 5.9)):+ decal(c, "decal_floor", grime, 0.9, 0.9, (x, y, 0.4), (0, 0, -1), up=(0, 1, 0), spin=rng.uniform(0, 360), offset=0.0008)+ # Fingerprints on the door glass, the window and the drink fridge door.+ fp = m_decal("decal_fingerprints", "decal_fingerprints", key="black", color_mul=(0.9, 0.9, 0.9), rough=0.5, gain=0.8)+ decal(c, "decal_fp", fp, 0.35, 0.35, (2.6, 0.8, 1.15), (0, -1, 0), offset=0.004)+ decal(c, "decal_fp", fp, 0.3, 0.3, (2.15, 0.8, 1.05), (0, -1, 0), offset=0.004)+ fr = bpy.data.objects.get("ramen_drink_fridge")+ if fr:+ ctr = sum((fr.matrix_world @ Vector(cc) for cc in fr.bound_box), Vector()) / 8+ decal(c, "decal_fp", fp, 0.3, 0.3, (ctr.x - 0.8, ctr.y, 1.1), (1, 0, 0), offset=0.012)+ # Generated flyers onto the existing (curled, pinned) flyer sheets.+ for name, tex in (("flyer_parttime", "flyer_parttime"), ("flyer_lostcat", "flyer_lostcat"), ("flyer_festival", "flyer_festival")):+ f = bpy.data.objects.get(name)+ if not f:+ continue+ for ch in list(f.children):+ if ch.type == "FONT" or ch.data.materials and ch.data.materials[0].name.startswith("photo"):+ bpy.data.objects.remove(ch)+ f.data.materials.clear()+ f.data.materials.append(m_print(name + "_img", tex, 0.85))+ # Price strips: one generated strip photo in place of the eight text strips.+ strips = [o for o in bpy.data.objects if o.name.startswith("price_strip")]+ if strips:+ ctr = sum((o.matrix_world.translation for o in strips), Vector()) / len(strips)+ for o in strips:+ _remove_with_children(o)+ decal(c, "price_strips", m_print("price_strips_img", "price_strips", 0.8), 0.72, 0.405, (ctr.x - 0.5, ctr.y, ctr.z), (1, 0, 0), curl=0.01, res=(8, 4))+ # Sticker sheet: each old sticker becomes one cell of the generated sheet (4 x 2 grid), keyed off white.+ old = [o for o in bpy.data.objects if o.name.startswith("sticker")]+ cells = [((i % 4) / 4, 1 - (i // 4 + 1) / 2) for i in range(8)]+ for i, o in enumerate(old):+ mw = o.matrix_world.copy()+ _remove_with_children(o)+ (u0, v0) = cells[i % 8]+ m = m_print(f"sticker_cell{i}", "stickers_sheet_nb", 0.45, uv_rect=((u0, v0), (u0 + 0.25, v0 + 0.5)), key="white")+ s = clutter.paper(f"sticker_img{i}", 0.085, 0.17, c, m, res=(2, 2), curl=0.01 if i == 2 else 0.0)+ for mod in list(s.modifiers):+ s.modifiers.remove(mod)+ s.matrix_world = mw+ # Peeling winter-special poster on the customer wall (world x = W, facing -X).+ decal(c, "poster_special", m_print("poster_special_img", "poster_menu_special", 0.75), 0.36, 0.48, (3.0, 3.75, 1.4), (1, 0, 0), curl=0.05, res=(10, 12))+ print("r2gen: textures applied", flush=True)+++# ------------------------------------------------------------------ props pass++# Direct-modelled object name prefix -> the generated prop that replaces it (only removed if that pick exists).+REPLACED = {"tongs": "ramen_tongs", "coin_": "ramen_coins", "tape_roll": "ramen_tape_roll", "power_strip": "ramen_power_strip",+ "cat_placemat": "ramen_cat_dish", "pet_bowl": "ramen_cat_dish", "wall_hook": "ramen_hook_items",+ "key_ring": "ramen_hook_items", "plastic_bag": "ramen_hook_items", "vending_body": "ramen_vending_machine",+ "vending_display": "ramen_vending_machine", "vending_header": "ramen_vending_machine", "vending_slot": "ramen_vending_machine"}+++def props():+ import emitters+ import grime+ import validate+ root = bpy.data.collections["ramen"]+ # 1. Drop the round-1 reuse pass (props_a) and the direct-modelled pieces that now have generated versions.+ old_a = bpy.data.collections.get("props_a")+ if old_a:+ for o in list(old_a.all_objects):+ if o.name in bpy.data.objects:+ _remove_with_children(o)+ for o in list(bpy.data.objects):+ if o.name not in bpy.data.objects or o.parent is not None:+ continue+ mats = [m.name for m in o.data.materials if m] if o.type == "MESH" else []+ pid = next((v for k, v in REPLACED.items() if o.name.startswith(k)), None)+ if pid is None and "key_metal" in mats:+ pid = "ramen_hook_items"+ if pid and dress._have(pid):+ _remove_with_children(o)+ # 2. Place the round-2 picks in the mirrored scene.+ dress.MIRROR = True+ dress.PLACED.clear()+ dress.pass_a2(coll("props_a2", root))+ dress.pass_bc_gen(coll("props_bc2", root))+ placed = list(dress.PLACED)+ dress.MIRROR = False+ # 3. Same housekeeping the build does: dense emitters, grime on the new materials, validation.+ emitters.run()+ for o, _ in placed:+ for m in o.data.materials:+ if m and not m.get("grimed") and not any(k in m.name.lower() for k in ("glass", "fridge", "vending")):+ grime.overlay(m, ao=0.6, dust=0.35)+ from lib import SCENE_DIR+ validate.run(placed, os.path.join(SCENE_DIR, "out", "validate_r2gen.txt"))+ print("r2gen: props placed", len(placed), flush=True)+ return placed+++def apply():+ textures()+ props()diff --git a/scenes/tokyo-ramen-shop/scripts/rebuild.sh b/scenes/tokyo-ramen-shop/scripts/rebuild.shnew file mode 100644index 0000000..2b66b95--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/rebuild.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Build ramen.blend (CPU, no GPU lock needed), bake steam (CPU), then optional GPU preview via the queue.+# scenes/tokyo-ramen-shop/scripts/rebuild.sh [preview cams] [tag] [samples]+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++"$B" -b --factory-startup --python scenes/tokyo-ramen-shop/scripts/build.py -- --samples 256 --save --final 2>&1 | grep -E "VALIDATE|^ |Error|Traceback|line [0-9]|saved|MISSING"+"$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python scenes/tokyo-ramen-shop/scripts/bake_steam.py 2>&1 | grep -E "BAKE|Error|Traceback|SAVED"+if [ -n "$1" ]; then+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/render.py -- prev "$1" --tag "${2:-_x}" --samples "${3:-48}" 2>&1 | grep -E "STILL|Error|Traceback"+fidiff --git a/scenes/tokyo-ramen-shop/scripts/render.py b/scenes/tokyo-ramen-shop/scripts/render.pynew file mode 100644index 0000000..baa5a51--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/render.py@@ -0,0 +1,55 @@+"""Renders from the saved (steam-baked) scenes/tokyo-ramen-shop/ramen.blend.++blender -b scenes/tokyo-ramen-shop/ramen.blend --python scenes/tokyo-ramen-shop/scripts/render.py -- stills wide,counter [--samples 256]+blender -b scenes/tokyo-ramen-shop/ramen.blend --python scenes/tokyo-ramen-shop/scripts/render.py -- prev wide,counter,kitchen --tag _x [--samples 32] [--res 960] [--frame 1] [--clay]+blender -b scenes/tokyo-ramen-shop/ramen.blend --python scenes/tokyo-ramen-shop/scripts/render.py -- clip 1 30 [--samples 96]+"""+import os+import sys++import bpy++argv = sys.argv[sys.argv.index("--") + 1:]+mode = argv[0]+++def opt(k, d=None, f=str):+ return f(argv[argv.index(k) + 1]) if k in argv else d+++samples = opt("--samples", None, int)+sc = bpy.context.scene+OUT = os.path.join(os.path.dirname(bpy.data.filepath), "out")+if samples:+ sc.cycles.samples = samples+if mode in ("stills", "prev"):+ sc.frame_set(opt("--frame", 1, int))+ if mode == "prev":+ res = opt("--res", 960, int)+ sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = res, res * 9 // 16, 100+ sc.render.image_settings.color_depth = "8"+ if "--clay" in argv:+ m = bpy.data.materials.get("CLAY") or bpy.data.materials.new("CLAY")+ bpy.context.view_layer.material_override = m+ for k in argv[1].split(","):+ sc.camera = bpy.data.objects["cam_" + k]+ if mode == "prev":+ sc.render.filepath = os.path.join(OUT, "prev", f"{k}{opt('--tag', '')}.png")+ else:+ sc.render.filepath = os.path.join(OUT, "raw", f"hero_{k}.png")+ bpy.ops.render.render(write_still=True)+ print("STILL", sc.render.filepath, flush=True)+else:+ a, b = int(argv[1]), int(argv[2])+ sc.camera = bpy.data.objects["cam_clip"]+ sc.render.resolution_x, sc.render.resolution_y = 1280, 720+ sc.render.use_persistent_data = True # keep BVH + textures between frames+ sc.render.image_settings.color_depth = "8"+ for f in range(a, b + 1):+ p = os.path.join(OUT, "frames", f"{f:04d}.png")+ if os.path.exists(p):+ continue+ sc.frame_set(f)+ sc.render.filepath = p+ bpy.ops.render.render(write_still=True)+ print("FRAME", f, flush=True)diff --git a/scenes/tokyo-ramen-shop/scripts/render_bts.sh b/scenes/tokyo-ramen-shop/scripts/render_bts.shnew file mode 100644index 0000000..bc49a4c--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/render_bts.sh@@ -0,0 +1,40 @@+#!/usr/bin/env bash+# Ramen BTS dollhouse clips (breakdown/SPEC.md). Every Blender run is its own pipeline/gpu_run.sh call (GPU released between).+# bash scenes/tokyo-ramen-shop/scripts/render_bts.sh > logs/ramen_bts.log 2>&1+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++R=breakdown/tokyo-ramen-shop+CL=$R/clips+WK=$R/work+run() { local t0=$(date +%s); bash pipeline/gpu_run.sh "$B" -b "$1" --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/bts.py -- "${@:2}" 2>&1 | grep -E "BTS rendered|Error:|Traceback|line [0-9]"; echo "GPU $(( $(date +%s)-t0 ))s: ${*:2}"; }+mp4() { "$FF" -v error -y -framerate 24 -i "$CL/$1/%04d.png" -c:v h264_nvenc -preset p7 -rc vbr -cq 16 -b:v 0 -pix_fmt yuv420p "$CL/$1.mp4" && echo "MP4 $1 $(ls $CL/$1 | wc -l) frames"; }++# No-grime twin of the scene for c_materials (same build, grime overlays stubbed out, no steam).+if [ ! -f $R/plain.blend ]; then+ bash pipeline/gpu_run.sh "$B" -b --factory-startup --python-expr "+import sys; sys.path.insert(0, __import__('os').environ['ANYSCENE_ROOT'] + '/scenes/tokyo-ramen-shop/scripts')+import grime; grime.overlay = lambda *a, **k: None; grime.build = lambda: None" \+ --python scenes/tokyo-ramen-shop/scripts/build.py -- --stages shell,dress,passA,passB,passC,grime,r2gen,light,post --blend ../../breakdown/tokyo-ramen-shop/plain.blend --save 2>&1 | grep -E "saved|Error|Traceback"+fi++run $R/bts.blend a_layout && mp4 a_layout+run $R/bts.blend b_props && mp4 b_props++run $R/bts.blend c_materials --pass clay --frames 1-48 --out $WK/c_clay+run $R/plain.blend c_materials --pass plain --frames 1-96 --out $WK/c_plain+run $R/bts.blend c_materials --pass full --frames 49-144 --out $WK/c_full+rm -rf $CL/c_materials $WK/c_seg; mkdir -p $CL/c_materials $WK/c_seg+"$FF" -v error -y -framerate 24 -start_number 1 -i $WK/c_clay/%04d.png -framerate 24 -start_number 1 -i $WK/c_plain/%04d.png \+ -filter_complex "[0][1]xfade=transition=wiperight:duration=2:offset=0,format=rgb24" -frames:v 48 -start_number 1 $WK/c_seg/a%04d.png+"$FF" -v error -y -framerate 24 -start_number 49 -i $WK/c_plain/%04d.png -framerate 24 -start_number 49 -i $WK/c_full/%04d.png \+ -filter_complex "[0][1]xfade=transition=fade:duration=2:offset=0,format=rgb24" -frames:v 48 -start_number 1 $WK/c_seg/b%04d.png+i=1+for f in $WK/c_seg/a*.png $WK/c_seg/b*.png $(for n in $(seq 97 144); do printf "$WK/c_full/%04d.png " $n; done); do+ cp "$f" $CL/c_materials/$(printf %04d $i).png; i=$((i+1))+done+mp4 c_materials++for r in 1-60 61-120 121-180 181-240; do run $R/bts.blend d_lighting --frames $r --samples 12; done+mp4 d_lighting+echo BTS_DONEdiff --git a/scenes/tokyo-ramen-shop/scripts/render_clip.sh b/scenes/tokyo-ramen-shop/scripts/render_clip.shnew file mode 100644index 0000000..113e761--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/render_clip.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Render the 120-frame handheld clip in 30-frame chunks, each holding the shared GPU lock, then encode.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++for a in 1 31 61 91; do+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen.blend --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python scenes/tokyo-ramen-shop/scripts/render.py -- clip $a $((a + 29)) --samples ${SAMPLES:-40} 2>&1 | grep -E "FRAME|Error|Traceback"+done+bash scenes/tokyo-ramen-shop/scripts/finish.sh clip "scenes/tokyo-ramen-shop/out/frames/%04d.png" scenes/tokyo-ramen-shop/out/clip.mp4 && echo ENCODEDdiff --git a/scenes/tokyo-ramen-shop/scripts/review.sh b/scenes/tokyo-ramen-shop/scripts/review.shnew file mode 100644index 0000000..09e391a--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/review.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash+# Review sheet per prop: ref | H3.1 front | Meshy front | H3.1 back | Meshy back | H3.1 clay | Meshy clay.+# scenes/tokyo-ramen-shop/scripts/review.sh out.png id id id ...+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++OUT=$1; shift+C=scenes/tokyo-ramen-shop/compare+rows=()+i=0+for p in "$@"; do+ ref=refs/tokyo-ramen-shop/props/${p}_0.png; [ -f "$ref" ] || ref=refs/props/${p}_0.png+ args=(-i "$ref")+ for v in beauty back clay; do for m in tripo-h31 meshy; do+ f=$C/$m/${p}_$v.png; [ -f "$f" ] || f=$ref; args+=(-i "$f"); done; done+ "$FF" -v error -y "${args[@]}" -filter_complex "[0]scale=300:300[a];[1]scale=300:300[b];[2]scale=300:300[c];[3]scale=300:300[d];[4]scale=300:300[e];[5]scale=300:300[f];[6]scale=300:300[g];[a][b][c][d][e][f][g]hstack=7" "/tmp/ramen_row_$i.png"+ rows+=(-i "/tmp/ramen_row_$i.png"); i=$((i+1))+done+if [ $i -eq 1 ]; then cp /tmp/ramen_row_0.png "$OUT"; else "$FF" -v error -y "${rows[@]}" -filter_complex "vstack=$i" "$OUT"; fidiff --git a/scenes/tokyo-ramen-shop/scripts/shell.py b/scenes/tokyo-ramen-shop/scripts/shell.pynew file mode 100644index 0000000..1db096a--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/shell.py@@ -0,0 +1,229 @@+"""Direct-modelled ramen shop: room shell, L-counter, kitchen fixtures, door, pendants, textured planes.++Layout (metres): x 0..W left->right, y 0..D front(street)->back, z up.+Customer aisle x 0..CX along the left wall; counter top CX..CX+0.45; raised pass behind it; kitchen x KX..W.+"""+import math+import os++import bpy++from lib import (TEX, area, box, coll, cylinder, m_concrete_wet, m_glass_rain, m_image, m_plaster, m_simple,+ m_stainless, m_tile, m_wood, mesh_obj, plane, uv_cube)++W, D, H = 3.6, 7.0, 2.6+CX = 1.25 # customer side edge of counter+CT = 0.45 # counter top depth+CH = 0.90 # counter top height+PASS_X = CX + CT # raised pass ledge starts here+PASS_H = 1.0+KX = 1.95 # kitchen prep counter (inside the pass) starts+Y0, Y1 = 1.6, 6.15 # counter run along y+LEG_X0 = 0.85 # short L-leg at the back runs x LEG_X0..PASS_X+DOOR = (0.72, 1.72) # door x range in the front wall (ticket machine sits in the corner left of it)+WIN = (2.05, 3.4) # front window x range+LANTERN = (2.38, -0.36, 1.38) # bottom-centre of the akachochin hanging outside, between door and window+STOOL_Y = [1.95, 2.55, 3.15, 3.75, 4.35, 4.95, 5.55]+PENDANT_Y = [2.25, 3.45, 4.65, 5.75]+WALL_T = 0.12+++def build(c):+ mats = {+ "plaster": m_plaster("plaster", (0.42, 0.37, 0.29)),+ "ceiling": m_plaster("ceiling", (0.26, 0.23, 0.19)),+ "wainscot": m_wood("wainscot", (0.035, 0.018, 0.01), (0.11, 0.055, 0.025), along="Z", scale=1.2, gloss=0.5, wear=False),+ "counter": m_wood("counter_top", (0.045, 0.02, 0.009), (0.15, 0.075, 0.035), along="Y", scale=2.5, gloss=0.28, fine_mix=0.78, bump_k=0.035),+ "counter_base": m_wood("counter_base", (0.03, 0.015, 0.008), (0.09, 0.045, 0.02), along="Z", gloss=0.55, wear=False),+ "floor": m_concrete_wet(),+ "steel": m_stainless("stainless"),+ "steel_v": m_stainless("stainless_v", "Z", 0.9),+ "tile": m_tile(),+ "glass": m_glass_rain(),+ "frame": m_simple("alu_frame", (0.18, 0.17, 0.16), 0.45, 0.9),+ "door_wood": m_wood("door_wood", (0.05, 0.025, 0.012), (0.16, 0.08, 0.035), along="Z", gloss=0.6, wear=False),+ "black": m_simple("black_paint", (0.02, 0.02, 0.02), 0.5),+ "rubber": m_simple("rubber_mat", (0.012, 0.012, 0.012), 0.85),+ }++ # --- room+ box("floor", (0, 0, -0.1), (W, D, 0), c, mats["floor"], bevel=0)+ box("ceiling", (0, 0, H), (W, D, H + 0.1), c, mats["ceiling"], bevel=0)+ box("wall_L", (-WALL_T, 0, 0), (0, D, H), c, mats["plaster"], bevel=0)+ box("wall_back", (0, D, 0), (W, D + WALL_T, H), c, mats["plaster"], bevel=0)+ # Right wall is the kitchen wall: tile up to 1.6 m, plaster above.+ box("wall_R_tile", (W, 0, 0), (W + WALL_T, D, 1.6), c, mats["tile"], bevel=0)+ box("wall_R_up", (W, 0, 1.6), (W + WALL_T, D, H), c, mats["plaster"], bevel=0)+ # Front wall with door and window openings.+ fz = 0+ for name, x0, x1, z0, z1 in [+ ("front_a", 0, DOOR[0], 0, H), ("front_b", DOOR[1], WIN[0], 0, H), ("front_c", WIN[1], W, 0, H),+ ("front_door_head", DOOR[0], DOOR[1], 2.05, H), ("front_win_sill", WIN[0], WIN[1], 0, 0.95),+ ("front_win_head", WIN[0], WIN[1], 2.05, H),+ ]:+ box(name, (x0, -WALL_T, z0), (x1, fz, z1), c, mats["plaster"], bevel=0)+ # Wood wainscot on the customer walls.+ box("wainscot_L", (0, 0, 0), (0.02, D, 1.0), c, mats["wainscot"], bevel=0.002)+ box("wainscot_back", (0, D - 0.02, 0), (W, D, 1.0), c, mats["wainscot"], bevel=0.002)+ box("wainscot_rail_L", (0, 0, 1.0), (0.035, D, 1.04), c, mats["counter_base"], bevel=0.004)+ box("skirting_front", (0, 0, 0), (W, 0.02, 0.12), c, mats["counter_base"], bevel=0.002)++ # --- sliding door: two leaves of wood frame + rain glass+ leaf_w = (DOOR[1] - DOOR[0]) / 2 + 0.03+ # Leaf 0 slid into the wall pocket so the doorway is ~0.73 m open (the walkthrough shot passes through it).+ for i, (x0, yoff) in enumerate([(DOOR[0] - 0.5, -0.07), (DOOR[0] + leaf_w - 0.06 + 0.32, -0.035)]):+ x1 = x0 + leaf_w+ t = 0.04+ y0, y1 = yoff - t / 2, yoff + t / 2+ box(f"door{i}_stile_l", (x0, y0, 0), (x0 + 0.06, y1, 2.05), c, mats["door_wood"], 0.003)+ box(f"door{i}_stile_r", (x1 - 0.06, y0, 0), (x1, y1, 2.05), c, mats["door_wood"], 0.003)+ box(f"door{i}_rail_b", (x0, y0, 0), (x1, y1, 0.32), c, mats["door_wood"], 0.003)+ box(f"door{i}_rail_m", (x0, y0, 1.0), (x1, y1, 1.05), c, mats["door_wood"], 0.003)+ box(f"door{i}_rail_t", (x0, y0, 1.98), (x1, y1, 2.05), c, mats["door_wood"], 0.003)+ for z0, z1 in [(0.32, 1.0), (1.05, 1.98)]:+ box(f"door{i}_glass_{z0}", (x0 + 0.06, yoff - 0.004, z0), (x1 - 0.06, yoff + 0.004, z1), c, mats["glass"], 0)+ box("door_track", (DOOR[0] - 0.05, -0.12, 0), (DOOR[1] + 0.4, 0.0, 0.015), c, mats["frame"], 0.002)+ # Front window: aluminium frame + rain glass.+ box("win_glass", (WIN[0], -0.065, 0.95), (WIN[1], -0.057, 2.05), c, mats["glass"], 0)+ for name, lo, hi in [+ ("win_f_l", (WIN[0], -0.09, 0.95), (WIN[0] + 0.04, -0.03, 2.05)), ("win_f_r", (WIN[1] - 0.04, -0.09, 0.95), (WIN[1], -0.03, 2.05)),+ ("win_f_m", ((WIN[0] + WIN[1]) / 2 - 0.02, -0.09, 0.95), ((WIN[0] + WIN[1]) / 2 + 0.02, -0.03, 2.05)),+ ("win_f_b", (WIN[0], -0.09, 0.93), (WIN[1], -0.03, 0.97)), ("win_f_t", (WIN[0], -0.09, 2.03), (WIN[1], -0.03, 2.07)),+ ]:+ box(name, lo, hi, c, mats["frame"], 0.002)++ # --- L-counter (customer side): base panels + thick wood top + raised pass + footrest rail+ box("counter_base_long", (CX + 0.04, Y0, 0), (PASS_X, Y1, CH - 0.05), c, mats["counter_base"], 0.004)+ box("counter_top_long", (CX - 0.04, Y0 - 0.04, CH - 0.05), (PASS_X, Y1 + 0.04, CH), c, mats["counter"], 0.008)+ box("counter_base_leg", (LEG_X0, Y1 + 0.04, 0), (PASS_X, Y1 + 0.45, CH - 0.05), c, mats["counter_base"], 0.004)+ box("counter_top_leg", (LEG_X0 - 0.04, Y1 + 0.0, CH - 0.05), (PASS_X, Y1 + 0.49, CH), c, mats["counter"], 0.008)+ box("pass_long", (PASS_X, Y0 - 0.04, CH - 0.05), (PASS_X + 0.22, Y1 + 0.49, PASS_H), c, mats["counter_base"], 0.004)+ box("pass_top", (PASS_X - 0.02, Y0 - 0.06, PASS_H), (PASS_X + 0.24, Y1 + 0.51, PASS_H + 0.035), c, mats["counter"], 0.006)+ box("counter_end_front", (CX - 0.04, Y0 - 0.06, 0), (PASS_X + 0.22, Y0 - 0.0, CH - 0.05), c, mats["counter_base"], 0.004)+ rail = cylinder("foot_rail", 0.015, Y1 - Y0, c, mats["frame"], loc=(0, 0, 0), verts=16)+ rail.rotation_euler = (math.radians(-90), 0, 0)+ rail.location = (CX - 0.02, (Y0 + Y1) / 2, 0.22) # cylinder origin is its centre (was Y0: rail poked 0.7 m out the front wall)++ # --- kitchen: prep counter behind the pass, back counters on the right wall, gap for range + boiler+ box("prep_counter", (PASS_X + 0.22, Y0 - 0.04, 0), (KX + 0.5, Y1 + 0.49, 0.86), c, mats["steel_v"], 0.003)+ box("prep_top", (PASS_X + 0.2, Y0 - 0.06, 0.86), (KX + 0.52, Y1 + 0.51, 0.88), c, mats["steel"], 0.003)+ RX = W - 0.62+ box("back_counter_a", (RX, 0.9, 0), (W, 3.4, 0.86), c, mats["steel_v"], 0.003)+ box("back_counter_a_top", (RX - 0.02, 0.9, 0.86), (W, 3.4, 0.88), c, mats["steel"], 0.003)+ box("back_counter_b", (RX, 5.35, 0), (W, D, 0.86), c, mats["steel_v"], 0.003)+ box("back_counter_b_top", (RX - 0.02, 5.35, 0.86), (W, D, 0.88), c, mats["steel"], 0.003)+ box("backsplash", (W - 0.012, 0.9, 0.88), (W, D, 1.6), c, mats["steel_v"], 0)+ for i, z in enumerate((1.6, 1.98)):+ box(f"shelf_{i}", (W - 0.32, 0.9, z), (W, 3.4, z + 0.02), c, mats["steel"], 0.002)+ box(f"shelf_b_{i}", (W - 0.32, 5.35, z), (W, D, z + 0.02), c, mats["steel"], 0.002)+ # Extractor hood over the range + boiler zone.+ hood = box("hood", (W - 0.75, 3.35, 1.85), (W, 5.45, 2.3), c, mats["steel"], 0.004)+ box("hood_duct", (W - 0.45, 4.2, 2.3), (W - 0.1, 4.6, H), c, mats["steel"], 0.003)+ box("kitchen_mat", (KX + 0.55, 1.0, 0), (RX - 0.02, D - 0.2, 0.012), c, mats["rubber"], 0.002)++ # --- menu plaques above the pass (generated image on a plane facing customers, -X)+ plaq = os.path.join(TEX, "menu_plaques_0.png")+ if os.path.exists(plaq):+ mat = m_image("menu_plaques", plaq, rough=0.65, bump_strength=0.15)+ p = plane("menu_plaques", 3.6, 0.5, c, mat, loc=(PASS_X + 0.12, 3.85, 1.95), rot=(0, 0, math.radians(-90)))+ box("plaque_beam", (PASS_X + 0.13, Y0, 2.45), (PASS_X + 0.23, Y1 + 0.5, 2.6), c, mats["counter_base"], 0.004)+ # Wall paper: poster, calendar, notice on the left wall (facing +X).+ for name, w, h, y, z in [("poster_beer", 0.42, 0.6, 3.2, 1.35), ("calendar", 0.36, 0.52, 4.6, 1.3), ("handwritten_notice", 0.21, 0.3, 2.3, 1.45)]:+ f = os.path.join(TEX, f"{name}_0.png")+ if os.path.exists(f):+ plane(name, w, h, c, m_image(name, f, rough=0.8), loc=(0.025, y, z), rot=(0, 0, math.radians(90)))++ # --- pendant lamps (shade + bulb mesh; lights are added in lighting.py)+ shade = m_simple("lamp_shade", (0.55, 0.5, 0.42), 0.4, 0.0, coat=0.3)+ cord = m_simple("lamp_cord", (0.01, 0.01, 0.01), 0.6)+ for i, y in enumerate(PENDANT_Y):+ z = 1.72+ bpy.ops.mesh.primitive_cone_add(vertices=40, radius1=0.17, radius2=0.04, depth=0.14, end_fill_type="NOTHING", location=(CX + 0.22, y, z + 0.07))+ s = bpy.context.object+ s.name = f"pendant_shade_{i}"+ for uc in list(s.users_collection):+ uc.objects.unlink(s)+ c.objects.link(s)+ s.data.materials.append(shade)+ sol = s.modifiers.new("thick", "SOLIDIFY")+ sol.thickness = 0.003+ bpy.ops.object.shade_smooth()+ cylinder(f"pendant_cord_{i}", 0.003, H - z - 0.14, c, cord, loc=(CX + 0.22, y, z + 0.14), verts=8)+ bpy.ops.mesh.primitive_uv_sphere_add(radius=0.035, location=(CX + 0.22, y, z + 0.06))+ b = bpy.context.object+ b.name = f"pendant_bulb_{i}"+ for uc in list(b.users_collection):+ uc.objects.unlink(b)+ c.objects.link(b)+ b.data.materials.append(m_simple("bulb", (1, 0.8, 0.55), 0.3, emission=(1.0, 0.62, 0.3), estr=60))+ exterior(c)+ return mats+++def exterior(c):+ """Street outside: generated rainy-street photo as an emissive backdrop, wet pavement strip, noren over the door."""+ import bmesh+ from lib import L, bsdf, new_mat, node+ f = os.path.join(TEX, "street_backdrop_0.png")+ if os.path.exists(f):+ m, nt = new_mat("street_backdrop")+ if nt:+ tex = nt.nodes.new("ShaderNodeTexImage")+ tex.image = bpy.data.images.load(f, check_existing=True)+ mp = nt.nodes.new("ShaderNodeMapping")+ uvn = nt.nodes.new("ShaderNodeTexCoord")+ L(nt, uvn.outputs["UV"], mp.inputs["Vector"])+ # Crop the door frames at the image edges: use the middle 56% horizontally.+ mp.inputs["Location"].default_value = (0.22, 0.0, 0)+ mp.inputs["Scale"].default_value = (0.56, 1.0, 1)+ L(nt, mp.outputs[0], tex.inputs["Vector"])+ em = nt.nodes.new("ShaderNodeEmission")+ em.inputs["Strength"].default_value = 0.35+ L(nt, tex.outputs["Color"], em.inputs["Color"])+ L(nt, em.outputs[0], nt.nodes["Material Output"].inputs["Surface"])+ nt.nodes.remove(bsdf(nt))+ # The cropped image is ~square (0.56 * 16/9), so a square plane keeps it unstretched; horizon near eye height.+ plane("street_backdrop", 7.5, 7.5, c, m, loc=(W / 2, -4.5, -2.2), rot=(0, 0, math.radians(180)))+ box("pavement", (-2, -4.5, -0.12), (W + 2, -WALL_T, -0.02), c, m_concrete_wet("pavement_wet"), bevel=0)+ box("eave", (-0.5, -0.9, 2.25), (W + 0.5, -WALL_T, 2.32), c, m_simple("eave", (0.05, 0.05, 0.05), 0.6), bevel=0.004)++ # Noren: three panels over the doorway, hanging from a pole, with gentle procedural folds.+ nf = os.path.join(TEX, "noren_0.png")+ if os.path.exists(nf):+ mat = m_image("noren", nf, rough=0.9, translucent=0.4)+ span = DOOR[1] - DOOR[0] + 0.2+ h = 0.78+ panel_w = span / 3 - 0.01+ for i in range(3):+ x0 = DOOR[0] - 0.1 + i * (span / 3)+ me = bpy.data.meshes.new(f"noren_{i}")+ bm = bmesh.new()+ nu, nv = 24, 30+ uvl = bm.loops.layers.uv.new("UVMap")+ vs = [[None] * (nv + 1) for _ in range(nu + 1)]+ for a in range(nu + 1):+ for b in range(nv + 1):+ u, v = a / nu, b / nv+ x = x0 + u * panel_w+ z = 2.12 - (1 - v) * h+ fold = 0.018 * math.sin(u * math.pi * 5 + i * 1.7) * (1 - v) ** 0.7+ sway = 0.03 * (1 - v) ** 2+ vs[a][b] = bm.verts.new((x, -0.2 + fold - sway, z))+ for a in range(nu):+ for b in range(nv):+ face = bm.faces.new((vs[a][b], vs[a + 1][b], vs[a + 1][b + 1], vs[a][b + 1]))+ for lp, (ua, vb) in zip(face.loops, [(a, b), (a + 1, b), (a + 1, b + 1), (a, b + 1)]):+ # Each panel shows its third of the noren image.+ # Panel i shows third (2 - i): build.py mirrors whole panels, which reverses their order.+ lp[uvl].uv = ((2 - i + ua / nu * (panel_w / (span / 3))) / 3, vb / nv)+ bm.to_mesh(me)+ bm.free()+ o = bpy.data.objects.new(f"noren_{i}", me)+ c.objects.link(o)+ me.materials.append(mat)+ o.modifiers.new("solid", "SOLIDIFY").thickness = 0.002+ for p in me.polygons:+ p.use_smooth = True+ pole = cylinder("noren_pole", 0.012, span + 0.2, c, m_simple("pole", (0.1, 0.07, 0.04), 0.5), verts=12)+ pole.rotation_euler = (0, math.radians(90), 0)+ pole.location = ((DOOR[0] + DOOR[1]) / 2, -0.2, 2.13) # cylinder origin is its centrediff --git a/scenes/tokyo-ramen-shop/scripts/shots_r2.sh b/scenes/tokyo-ramen-shop/scripts/shots_r2.shnew file mode 100644index 0000000..b8ba736--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/shots_r2.sh@@ -0,0 +1,15 @@+#!/usr/bin/env bash+# Final camrig renders, 24-frame chunks per GPU-queue call; then my grade/vignette/grain pass → <shot>_graded.mp4.+cd "$(dirname "$0")/../../.."+. pipeline/env.sh++J=$ROOT_ABS/scenes/tokyo-ramen-shop/shots.json+O=$ROOT_ABS/scenes/tokyo-ramen-shop/out/shots+for spec in ${SHOTS:-bowl_insert:96 stockpot_insert:120 lantern_rain:96 exterior_establish:120 counter_push:120 door_dolly_zoom:96}; do+ s=${spec%%:*}; n=${spec##*:}+ for ((a=1; a<=n; a+=24)); do+ b=$((a+23)); [ $b -gt $n ] && b=$n+ bash pipeline/gpu_run.sh "$B" -b scenes/tokyo-ramen-shop/ramen_r2.blend --python scenes/tokyo-ramen-shop/scripts/gpu_prefs.py --python camera/shoot.py -- --shots $J --out $O --only $s --frames $a-$b 2>&1 | grep -E "camrig: (final|$s)|Error:|Traceback" | grep -v "Not freed"+ done+ bash scenes/tokyo-ramen-shop/scripts/finish.sh clip "scenes/tokyo-ramen-shop/out/shots/$s/frames/%04d.png" "scenes/tokyo-ramen-shop/out/shots/$s/${s}_graded.mp4" && echo "GRADED $s"+donediff --git a/scenes/tokyo-ramen-shop/scripts/steam.py b/scenes/tokyo-ramen-shop/scripts/steam.pynew file mode 100644index 0000000..a85cc1c--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/steam.py@@ -0,0 +1,179 @@+"""Steam and vapor (design coordinates; build.py mirrors afterwards, the bake runs on the saved .blend).++Mantaflow gas domains:+ steam_range over the range + noodle boiler, under the hood (hood is a collision effector, open top)+ steam_bowl a small one over the unfinished bowl on the counter+Emitters are hidden discs just below each rim; flow density is broken up by an animated clouds texture so the+plumes come out in wisps instead of a solid column. Bake with scenes/tokyo-ramen-shop/scripts/bake_steam.py (CPU, cache in+scenes/tokyo-ramen-shop/cache/). The cache starts at PREROLL so plumes are fully developed at frame 1 (shots render 1..N).++Plus kitchen_vapor: a drifting low-density noise volume in the kitchen that the pendants and hood strip pick up."""+import math+import os++import bpy++import shell as S+from lib import L, SCENE_DIR, mathn, new_mat, noise, texcoord++PREROLL = -70+END = 300 # covers the ~11 s handheld walkthroughs+CACHE = os.path.join(SCENE_DIR, "cache", "r2") # round 2; round-1 caches stay in cache/+++def _box_mesh(name, lo, hi, c):+ bpy.ops.mesh.primitive_cube_add(size=1)+ o = bpy.context.object+ o.name = name+ for uc in list(o.users_collection):+ uc.objects.unlink(o)+ c.objects.link(o)+ o.scale = [hi[i] - lo[i] for i in range(3)]+ o.location = [(hi[i] + lo[i]) / 2 for i in range(3)]+ bpy.context.view_layer.objects.active = o+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ return o+++def steam_material(name="steam_vol", density=8.0):+ m, nt = new_mat(name)+ if nt:+ nt.nodes.remove(nt.nodes["Principled BSDF"])+ v = nt.nodes.new("ShaderNodeVolumePrincipled")+ v.inputs["Color"].default_value = (0.92, 0.92, 0.92, 1)+ v.inputs["Density"].default_value = density+ v.inputs["Density Attribute"].default_value = "density"+ v.inputs["Anisotropy"].default_value = 0.55 # forward scatter: glows when backlit by the hood strip+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])+ return m+++def _domain(name, lo, hi, res, c, noise_scale=2):+ o = _box_mesh(name, lo, hi, c)+ mod = o.modifiers.new("Fluid", "FLUID")+ mod.fluid_type = "DOMAIN"+ ds = mod.domain_settings+ ds.domain_type = "GAS"+ ds.resolution_max = res+ ds.time_scale = 1.0+ ds.use_adaptive_timesteps = True+ ds.cfl_condition = 3.0+ ds.alpha = -0.15 # density sinks a little (steam is moist), heat carries it up+ ds.beta = 1.6+ ds.vorticity = 0.25+ ds.use_dissolve_smoke = True+ ds.dissolve_speed = 60+ ds.use_dissolve_smoke_log = True+ ds.use_collision_border_top = False+ ds.use_noise = True+ ds.noise_scale = noise_scale+ ds.noise_strength = 1.2+ ds.noise_pos_scale = 1.6+ ds.cache_type = "ALL"+ ds.cache_data_format = "OPENVDB"+ ds.cache_directory = os.path.join(CACHE, name)+ ds.cache_frame_start = PREROLL+ ds.cache_frame_end = END+ o.data.materials.append(steam_material())+ o.visible_shadow = False+ o.display_type = "WIRE"+ return o+++def _clouds(name, size=0.06):+ t = bpy.data.textures.get(name) or bpy.data.textures.new(name, "CLOUDS")+ t.noise_scale = size+ t.noise_depth = 3+ t.contrast = 1.6+ return t+++def _emitter(name, x, y, z, r, c, density=0.55, temp=2.0, tex=None, vel=0.25):+ bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=0.012, vertices=24, location=(x, y, z))+ o = bpy.context.object+ o.name = name+ for uc in list(o.users_collection):+ uc.objects.unlink(o)+ c.objects.link(o)+ mod = o.modifiers.new("Fluid", "FLUID")+ mod.fluid_type = "FLOW"+ fs = mod.flow_settings+ fs.flow_type = "SMOKE"+ fs.flow_behavior = "INFLOW"+ fs.flow_source = "MESH"+ fs.surface_distance = 1.0 # effectively in cells: 0.012 only emitted from discs wide enough to contain cell centres+ fs.density = density+ fs.temperature = temp+ fs.smoke_color = (0.95, 0.95, 0.95)+ fs.subframes = 1+ fs.use_initial_velocity = True+ fs.velocity_normal = vel+ if tex:+ fs.use_texture = True+ fs.noise_texture = tex+ fs.texture_map_type = "AUTO"+ fs.texture_size = 1.0+ # Scroll the texture so the puffs change over time.+ d = fs.driver_add("texture_offset")+ d.driver.expression = "frame * 0.018"+ o.hide_render = True+ o.display_type = "WIRE"+ return o+++def build(c, pots, boiler, bowl):+ """pots: [(x, y, rim_z, r)], boiler: (x, y, top_z, w, d) or None, bowl: (x, y, rim_z, r) or None."""+ tex = _clouds("steam_puffs")+ # Floor well below the pot rims (pots sit in the burner grates, rims ~0.76-0.9 m): emitters must not touch the border cells.+ dom = _domain("steam_range", (S.W - 0.85, 3.3, 0.6), (S.W - 0.015, 6.15, 2.25), 200, c)+ # Only pots on the range / back counter inside the domain steam (shelf and floor pots are cold).+ pots = [p for p in pots if S.W - 0.85 < p[0] and 3.3 < p[1] < 6.15 and p[2] < 1.6]+ for i, (x, y, z, r) in enumerate(pots):+ _emitter(f"steam_src_pot{i}", x, y, z - 0.03, r * 0.85, c, density=1.0 - 0.15 * i, temp=2.2, tex=tex)+ if boiler:+ x, y, z, w, d = boiler+ for j, dy in enumerate((-0.12, 0.12)):+ _emitter(f"steam_src_boiler{j}", x - 0.04, y + dy, z - 0.02, 0.11, c, density=0.8, temp=2.6, tex=tex, vel=0.4)+ # The hood is a collision object for the range domain (steam pools under it and rolls out the front).+ hood = bpy.data.objects.get("hood")+ if hood:+ m = hood.modifiers.new("Fluid", "FLUID")+ m.fluid_type = "EFFECTOR"+ m.effector_settings.effector_type = "COLLISION"+ if bowl:+ x, y, z, r = bowl+ _domain("steam_bowl", (x - 0.24, y - 0.24, z - 0.12), (x + 0.24, y + 0.24, z + 0.6), 110, c)+ _emitter("steam_src_bowl", x, y, z - 0.035, r * 0.7, c, density=0.6, temp=1.6, tex=_clouds("steam_puffs_bowl", 0.03), vel=0.08)+ kitchen_vapor(c)+ return dom+++def kitchen_vapor(c, density=0.035):+ """Drifting vapor layer in the kitchen, thicker toward the hood and the ceiling."""+ m, nt = new_mat("kitchen_vapor")+ if nt:+ nt.nodes.remove(nt.nodes["Principled BSDF"])+ co = texcoord(nt, "Object")+ mp = nt.nodes.new("ShaderNodeMapping")+ L(nt, co, mp.inputs["Vector"])+ mp.inputs["Scale"].default_value = (1.0, 1.0, 1.6)+ n = noise(nt, 1.8, 4, 0.55, mp.outputs[0], dim="4D")+ n.inputs["W"].driver_add("default_value").driver.expression = "frame * 0.006"+ # Slow upward drift of the pattern.+ mp.inputs["Location"].driver_add("default_value", 2).driver.expression = "-frame * 0.002"+ wisps = mathn(nt, "MAXIMUM", mathn(nt, "SUBTRACT", n.outputs["Fac"], 0.42), 0.0)+ gen = nt.nodes.new("ShaderNodeSeparateXYZ")+ L(nt, texcoord(nt, "Generated"), gen.inputs[0])+ up = mathn(nt, "POWER", gen.outputs["Z"], 1.5)+ # Toward the hood wall: +X in design space, but the mirror only moves objects, so it ends up at generated X=0.+ side = mathn(nt, "POWER", mathn(nt, "SUBTRACT", 1.0, gen.outputs["X"]), 2.0)+ k = mathn(nt, "MULTIPLY", mathn(nt, "MULTIPLY", wisps, mathn(nt, "ADD", up, side)), density * 14)+ v = nt.nodes.new("ShaderNodeVolumePrincipled")+ v.inputs["Color"].default_value = (0.9, 0.9, 0.9, 1)+ v.inputs["Anisotropy"].default_value = 0.5+ L(nt, mathn(nt, "ADD", k, density * 0.25), v.inputs["Density"])+ L(nt, v.outputs[0], nt.nodes["Material Output"].inputs["Volume"])+ o = _box_mesh("kitchen_vapor", (S.PASS_X + 0.25, 0.9, 1.0), (S.W - 0.02, S.D - 0.05, S.H - 0.02), c)+ o.data.materials.append(m)+ o.visible_shadow = False+ return odiff --git a/scenes/tokyo-ramen-shop/scripts/validate.py b/scenes/tokyo-ramen-shop/scripts/validate.pynew file mode 100644index 0000000..4a65aa3--- /dev/null+++ b/scenes/tokyo-ramen-shop/scripts/validate.py@@ -0,0 +1,85 @@+"""Placement validator: floating props, interpenetration between props, out-of-room, scale sanity.+Runs after every dressing pass (design coordinates, before the mirror) and writes a report."""+import itertools+import json+import os++import bpy+from mathutils import Vector+from mathutils.bvhtree import BVHTree++import shell as S+from lib import SCENE_DIR++OUTSIDE_OK = {"lantern", "ramen_vending_machine_nb"}+++def _bounds(o):+ pts = [o.matrix_world @ Vector(c) for c in o.bound_box]+ return (Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))),+ Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts))))+++def _bvh(o, dg):+ ev = o.evaluated_get(dg)+ me = ev.to_mesh()+ me.transform(o.matrix_world)+ t = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])+ ev.to_mesh_clear()+ return t+++def run(placed, report_path):+ bpy.context.view_layer.update()+ dg = bpy.context.evaluated_depsgraph_get()+ man = {p["id"]: p for p in json.load(open(os.path.join(SCENE_DIR, "assets.json")))["generate"]}+ issues = []+ objs = [o for o, _ in placed]+ for o, mode in placed:+ pid = o.name.split(".")[0]+ lo, hi = _bounds(o)+ # Floating: ray down from just above the bottom centre must hit something within 1.5 cm.+ if mode == "rest":+ hide = o.hide_get()+ o.hide_set(True)+ dg.update()+ gaps = []+ # Include near-corner rays so props on legs or feet are not reported as floating.+ for fx, fy in ((0.5, 0.5), (0.3, 0.3), (0.7, 0.7), (0.3, 0.7), (0.7, 0.3), (0.06, 0.06), (0.94, 0.94), (0.06, 0.94), (0.94, 0.06)):+ p = Vector((lo.x + (hi.x - lo.x) * fx, lo.y + (hi.y - lo.y) * fy, lo.z + 0.003))+ ok, loc, *_ = bpy.context.scene.ray_cast(dg, p, Vector((0, 0, -1)))+ gaps.append((p.z - loc.z) if ok else 9.0)+ o.hide_set(hide)+ if min(gaps) > 0.015:+ issues.append(f"FLOATING {o.name}: {min(gaps) * 100:.1f} cm above support")+ # Out of room.+ if pid not in OUTSIDE_OK and (lo.x < -0.02 or hi.x > S.W + 0.02 or lo.y < -0.02 or hi.y > S.D + 0.02 or hi.z > S.H + 0.01):+ issues.append(f"OUT_OF_ROOM {o.name}: x {lo.x:.2f}..{hi.x:.2f} y {lo.y:.2f}..{hi.y:.2f} z top {hi.z:.2f}")+ # Scale sanity against the manifest (instances may be scaled on purpose).+ spec = man.get(pid)+ if spec:+ size = hi - lo+ dims = o.dimensions # local box x scale, so a rotated prop is not over-measured+ got = dims.z if "h" in spec else max(dims)+ want = (spec.get("h") or spec.get("m")) * o.scale.x+ if abs(got - want) / want > 0.15:+ issues.append(f"SCALE {o.name}: {got:.2f} m vs {want:.2f} m")+ # Interpenetration between props whose boxes overlap.+ trees = {}+ for a, b in itertools.combinations(objs, 2):+ la, ha = _bounds(a)+ lb, hb = _bounds(b)+ if any(ha[i] < lb[i] or hb[i] < la[i] for i in range(3)):+ continue+ ta = trees.get(a.name) or trees.setdefault(a.name, _bvh(a, dg))+ tb = trees.get(b.name) or trees.setdefault(b.name, _bvh(b, dg))+ n = len(ta.overlap(tb))+ if n > 40:+ issues.append(f"INTERSECT {a.name} x {b.name}: {n} face pairs")+ os.makedirs(os.path.dirname(report_path), exist_ok=True)+ with open(report_path, "w") as f:+ f.write("\n".join(issues) or "OK")+ print(f"VALIDATE {len(issues)} issues -> {report_path}")+ for i in issues:+ print(" ", i)+ return issuesdiff --git a/scenes/tokyo-ramen-shop/shots.json b/scenes/tokyo-ramen-shop/shots.jsonnew file mode 100644index 0000000..e413223--- /dev/null+++ b/scenes/tokyo-ramen-shop/shots.json@@ -0,0 +1,626 @@+{+ "defaults": {+ "fps": 24,+ "res": [+ 1280,+ 536+ ],+ "aspect": "2.39",+ "samples": 48,+ "shutter": 180,+ "sensor": "s35",+ "fstop": 2.8,+ "ease": "inout",+ "handheld": 0.2+ },+ "shots": [+ {+ "name": "exterior_establish",+ "frames": 120,+ "move": "push_in",+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.9,+ -3.1,+ 1.28+ ],+ "aim": [+ 2.4,+ 3,+ 1.08+ ],+ "lens": 24+ },+ {+ "t": 1,+ "pos": [+ 2.55,+ -1.45,+ 1.22+ ],+ "aim": [+ 2.4,+ 3,+ 1.05+ ],+ "lens": 24+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "obj": "lantern"+ },+ {+ "t": 0.35,+ "obj": "lantern"+ },+ {+ "t": 0.85,+ "pos": [+ 2.38,+ -0.2,+ 1.6+ ]+ }+ ]+ },+ "fstop": 2,+ "handheld": 0.3,+ "lens_fx": {+ "distortion": 0.012,+ "dispersion": 0.012,+ "glare": "fog"+ }+ },+ {+ "name": "lantern_rain",+ "frames": 96,+ "move": "static",+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.95,+ -2.65,+ 1.55+ ],+ "aim": [+ 1.6,+ -0.3,+ 1.62+ ],+ "lens": 45+ }+ ],+ "focus": {+ "mode": "track",+ "obj": "lantern"+ },+ "fstop": 1.8,+ "handheld": 0.35,+ "blades": 7,+ "lens_fx": {+ "distortion": 0.005,+ "dispersion": 0.015,+ "glare": "fog"+ }+ },+ {+ "name": "stockpot_insert",+ "frames": 120,+ "move": "push_in",+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.75,+ 3.55,+ 1.5+ ],+ "aim": [+ 0.36,+ 4.8,+ 0.86+ ],+ "lens": 70+ },+ {+ "t": 1,+ "pos": [+ 2.6,+ 3.62,+ 1.48+ ],+ "aim": [+ 0.36,+ 4.8,+ 0.88+ ],+ "lens": 70+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "obj": "stockpot"+ },+ {+ "t": 0.4,+ "obj": "stockpot"+ },+ {+ "t": 0.7,+ "obj": "stockpot.001"+ }+ ]+ },+ "fstop": 2.8,+ "handheld": 0.15,+ "lens_fx": {+ "distortion": 0,+ "dispersion": 0.01,+ "glare": "fog"+ }+ },+ {+ "name": "bowl_insert",+ "frames": 96,+ "move": "static",+ "keys": [+ {+ "t": 0,+ "pos": [+ 3.2,+ 2.3,+ 1.42+ ],+ "aim_obj": "ramen_bowl_unfinished",+ "aim_offset": [+ 0,+ 0,+ 0.07+ ],+ "lens": 100+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "obj": "ramen_bowl_unfinished"+ },+ {+ "t": 0.45,+ "obj": "ramen_bowl_unfinished"+ },+ {+ "t": 0.75,+ "obj": "ramen_water_glass"+ }+ ]+ },+ "fstop": 2,+ "handheld": 0.12,+ "lens_fx": {+ "distortion": 0,+ "dispersion": 0.01,+ "glare": "fog"+ }+ },+ {+ "name": "counter_push",+ "frames": 120,+ "move": "push_in",+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.68,+ 1.45,+ 1.13+ ],+ "aim": [+ 2,+ 5.6,+ 0.98+ ],+ "lens": 32+ },+ {+ "t": 1,+ "pos": [+ 2.64,+ 2.5,+ 1.1+ ],+ "aim": [+ 2,+ 5.6,+ 0.96+ ],+ "lens": 32+ }+ ],+ "focus": {+ "mode": "track",+ "obj": "ramen_bowl_unfinished"+ },+ "fstop": 2.4,+ "handheld": 0.2,+ "lens_fx": {+ "distortion": 0.01,+ "dispersion": 0.01,+ "glare": "fog"+ }+ },+ {+ "name": "door_dolly_zoom",+ "frames": 96,+ "move": "dolly_zoom",+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.55,+ 4.6,+ 1.42+ ],+ "aim": [+ 2.38,+ 0,+ 1.3+ ],+ "lens": 50+ },+ {+ "t": 1,+ "pos": [+ 2.5,+ 2.6,+ 1.4+ ]+ }+ ],+ "subject": [+ 2.38,+ 0,+ 1.3+ ],+ "focus": {+ "mode": "point",+ "pos": [+ 2.38,+ 0,+ 1.35+ ]+ },+ "fstop": 2.8,+ "handheld": 0.15,+ "lens_fx": {+ "distortion": 0.008,+ "dispersion": 0.012,+ "glare": "fog"+ }+ },+ {+ "name": "h1_door_to_counter",+ "frames": 264,+ "move": "path",+ "ease": "inout",+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.48,+ -1.35,+ 1.5+ ],+ "aim": [+ 2.42,+ 3,+ 1.2+ ],+ "lens": 24+ },+ {+ "t": 0.16,+ "pos": [+ 2.48,+ -0.62,+ 1.15+ ],+ "aim": [+ 2.45,+ 2,+ 1.12+ ],+ "lens": 24+ },+ {+ "t": 0.24,+ "pos": [+ 2.48,+ -0.2,+ 1.05+ ],+ "aim": [+ 2.5,+ 2,+ 1.15+ ],+ "lens": 24+ },+ {+ "t": 0.32,+ "pos": [+ 2.52,+ 0.35,+ 1.32+ ],+ "aim": [+ 3.25,+ 0.75,+ 1.1+ ],+ "lens": 24+ },+ {+ "t": 0.42,+ "pos": [+ 2.85,+ 1.05,+ 1.48+ ],+ "aim": [+ 2.6,+ 4,+ 1+ ],+ "lens": 24+ },+ {+ "t": 0.6,+ "pos": [+ 2.97,+ 2.3,+ 1.5+ ],+ "aim": [+ 2.1,+ 5.2,+ 1+ ],+ "lens": 24+ },+ {+ "t": 0.8,+ "pos": [+ 2.97,+ 3.35,+ 1.47+ ],+ "aim": [+ 1.6,+ 4.6,+ 1.05+ ],+ "lens": 24+ },+ {+ "t": 1,+ "pos": [+ 2.78,+ 3.95,+ 1.2+ ],+ "aim": [+ 0.4,+ 4.65,+ 1.15+ ],+ "lens": 24+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "pos": [+ 2.38,+ -0.2,+ 1.6+ ]+ },+ {+ "t": 0.08,+ "pos": [+ 2.38,+ -0.2,+ 1.55+ ]+ },+ {+ "t": 0.18,+ "pos": [+ 2.3,+ 1.6,+ 1.05+ ]+ },+ {+ "t": 0.32,+ "obj": "ticket_machine"+ },+ {+ "t": 0.45,+ "pos": [+ 2.1,+ 3.2,+ 1+ ]+ },+ {+ "t": 0.75,+ "pos": [+ 2.1,+ 4.6,+ 1+ ]+ },+ {+ "t": 1,+ "obj": "stockpot"+ }+ ]+ },+ "fstop": 3.2,+ "handheld": {+ "profile": "walk",+ "amount": 1+ },+ "lens_fx": {+ "distortion": 0.012,+ "dispersion": 0.012,+ "glare": "fog"+ }+ },+ {+ "name": "h2_counter_walkaround",+ "frames": 264,+ "move": "path",+ "ease": "inout",+ "keys": [+ {+ "t": 0,+ "pos": [+ 3,+ 2.3,+ 1.52+ ],+ "aim": [+ 3.6,+ 3.1,+ 1.55+ ],+ "lens": 28+ },+ {+ "t": 0.25,+ "pos": [+ 2.95,+ 2.6,+ 1.52+ ],+ "aim": [+ 2,+ 3.3,+ 2.15+ ],+ "lens": 28+ },+ {+ "t": 0.5,+ "pos": [+ 2.92,+ 3.1,+ 1.48+ ],+ "aim": [+ 2.2,+ 4.2,+ 1+ ],+ "lens": 28+ },+ {+ "t": 0.75,+ "pos": [+ 2.88,+ 3.6,+ 1.45+ ],+ "aim": [+ 2.1,+ 4.8,+ 0.95+ ],+ "lens": 28+ },+ {+ "t": 1,+ "pos": [+ 2.8,+ 3.92,+ 1.42+ ],+ "aim": [+ 0.4,+ 4.8,+ 1.05+ ],+ "lens": 28+ }+ ],+ "focus": {+ "mode": "rack",+ "keys": [+ {+ "t": 0,+ "pos": [+ 3.6,+ 3,+ 1.55+ ]+ },+ {+ "t": 0.25,+ "pos": [+ 1.95,+ 3.3,+ 2.15+ ]+ },+ {+ "t": 0.5,+ "pos": [+ 2.15,+ 4.1,+ 0.95+ ]+ },+ {+ "t": 0.75,+ "pos": [+ 2.1,+ 4.8,+ 0.95+ ]+ },+ {+ "t": 1,+ "obj": "stockpot"+ }+ ]+ },+ "fstop": 2.8,+ "handheld": {+ "profile": "walk",+ "amount": 1+ },+ "lens_fx": {+ "distortion": 0.01,+ "dispersion": 0.01,+ "glare": "fog"+ }+ }+ ]+}\ No newline at end of file