Skip to content

armgit / viz3d

Public Imported from GitHub
0

An AI agent skill that turns any subject into a 3D film or app

Add build-house-from-plan plugin

Nguyen Xuan An404e2724641c
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 947205d..df52fcc 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -15,6 +15,11 @@
"name": "build-minecraft-model-from-image",
"source": "./plugins/build-minecraft-model-from-image",
"description": "Turn a picture of an object into a Minecraft-style 3D model of clean cuboids with pixel textures"
+ },
+ {
+ "name": "build-house-from-plan",
+ "source": "./plugins/build-house-from-plan",
+ "description": "Turn a 2D house plan into a photoreal 3D house, checked against the drawing"
}
]
}
diff --git a/README.md b/README.md
index b168d1f..9c4fa3c 100644
--- a/README.md
+++ b/README.md
@@ -182,6 +182,21 @@ Photo credits for the picture above and the skill's `examples/`: kettle and armc
(armchair photo by Gerald E Jones), CC BY 4.0. Rubber duck by Julian Lupyan, CC0. Fire hydrant by Tournasol7, CC BY 4.0.
All from Wikimedia Commons.
+**build-house-from-plan** turns a 2D house plan into a photoreal 3D house. The agent reads the walls, doors, windows and
+scale off the drawing into a plan file. A check overlays the built walls on the drawing's ink and fails when they do not
+line up. The house gets measured wall thickness, real frames and glass, CC0 scanned materials and real furniture models,
+and renders in Blender Cycles. You get stills, a film of the walls rising off the drawing, and whole streets. It needs
+Python through [uv](https://docs.astral.sh/uv/), Blender 5.x and a GPU.
+
+![From a public domain drawing to a house and a street](docs/images/house-from-plan.jpg)
+
+```text
+/plugin install build-house-from-plan@codepawl
+```
+
+The plans behind the picture are public domain: Historic American Buildings Survey and Historic American Engineering
+Record sheets from the Library of Congress, and a USDA plan. Furniture includes CC BY models listed in the skill's example.
+
## Contributing
Faults you saw, new looks, example topics and harness adapters are welcome. Read
diff --git a/docs/images/house-from-plan.jpg b/docs/images/house-from-plan.jpg
new file mode 100644
index 0000000..f5cd0f1
Binary files /dev/null and b/docs/images/house-from-plan.jpg differ
diff --git a/plugins/build-house-from-plan/.claude-plugin/plugin.json b/plugins/build-house-from-plan/.claude-plugin/plugin.json
new file mode 100644
index 0000000..9176113
--- /dev/null
+++ b/plugins/build-house-from-plan/.claude-plugin/plugin.json
@@ -0,0 +1,20 @@
+{
+ "name": "build-house-from-plan",
+ "version": "0.1.0",
+ "description": "Turn a 2D house plan into a photoreal 3D house in Blender Cycles, checked by overlaying the build on the drawing, with stills, a build-up film and whole streets.",
+ "author": {
+ "name": "CodePawl",
+ "url": "https://codepawl.com"
+ },
+ "homepage": "https://github.com/codepawl/viz3d",
+ "repository": "https://github.com/codepawl/viz3d",
+ "license": "MIT",
+ "keywords": [
+ "3d",
+ "architecture",
+ "floor-plan",
+ "blender",
+ "cycles",
+ "photoreal"
+ ]
+}
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/SKILL.md b/plugins/build-house-from-plan/skills/build-house-from-plan/SKILL.md
new file mode 100644
index 0000000..1510cfd
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/SKILL.md
@@ -0,0 +1,62 @@
+---
+name: build-house-from-plan
+description: Turn a 2D house plan into a photoreal 3D house in Blender Cycles, checked by overlaying the build on the drawing. Stills, a film of the walls rising off the drawing, and whole streets of houses. Use for a floor plan, a house plan or a blueprint that should become a real-looking 3D house or street.
+license: MIT
+---
+
+# Build a photoreal 3D house from a 2D plan
+
+A plan file is read off the drawing, checked against the drawing, built with real wall thickness and real frames, then
+dressed with scanned materials and models and rendered in Cycles. The drawing stays the judge: nothing ships unless the
+built floor plan lands on its ink.
+
+## Order of work
+
+1. **Find the sheet and its sources.** Licence-clear plan, plus photos of the same building or its type and period.
+ Read `references/read-plan.md` in full: sources, calibration, reading order, the table of what may be inferred.
+2. **Write `plan.json`.** `references/plan-format.md` holds every key. Read the sections you need. Everything not read
+ off the drawing goes in `provenance.inferred`, and the final report repeats that list.
+3. **Check before building.** Stop and fix on any failure:
+ ```bash
+ uv run --no-project --with pillow --with numpy --with scipy python scripts/plan_check.py check plan.json
+ uv run --no-project --with pillow --with numpy --with scipy python scripts/plan_check.py overlay plan.json
+ ```
+4. **Build.** One Blender at a time:
+ ```bash
+ blender -b --factory-startup -t 6 -P scripts/build_house.py -- plan.json out/house.blend
+ ```
+ It writes the as-built section next to the blend. Score it with `plan_check.py asbuilt <section.json>`.
+5. **Preview small.** `--samples 48 --scale 50`, then look at every shot beside the reference photos:
+ ```bash
+ blender -b out/house.blend -t 6 -P scripts/render_house.py -- plan.json out/preview --samples 48 --scale 50
+ ```
+6. **Hunt what looks fake.** Read `references/realism-faults.md` before judging: the faults this pipeline actually
+ produced, how each one looked and what fixed it. Add each new fault there the same turn.
+7. **Final.** 1920x1080 at about 512 samples, each still at full size beside a real photo. Look at each one.
+8. **Films.** `--film <name>`. A `build_up` film rises the walls off the sheet itself. Streets: "Streets" in
+ `references/plan-format.md`.
+
+## Hard rules
+
+- Gate: at least 0.70 of wall faces within 7 cm of ink, best-fit offset at most 16 cm, a clear win over a 50 cm shifted
+ control, on both the plan and the as-built section. A fail means the plan or the build is wrong. Never loosen it.
+- Sizes are measured or printed, never guessed by eye: wall thickness, ceiling height, sill and head. A height the drawing
+ does not give is inferred from the type and period and listed as inferred.
+- Roof and facade without elevation drawings are inferred. Say so in the report.
+- Real materials only: Poly Haven or ambientCG scans with their true tile size. No flat colour on a visible surface.
+- Furniture comes from real PBR models placed by how the room is used, with walking space kept and fronts facing the
+ room. `scripts/fetch_assets.py` downloads the CC0 scans, `scripts/find_objaverse.py` and `scripts/fetch_objaverse.py` find and fetch CC BY models.
+- Credit every CC BY model and every source sheet in `CREDITS.md` beside the plan.
+- Check orientation on a grid (`scripts/preview_assets.py`) before placing a new model. Check native size too, since
+ Objaverse models come in odd units.
+
+## Speed
+
+A glTF import is the slow step, so `build_house.py` caches each model as a linked `.blend` in the asset library
+(`HOUSE_ASSET_LIBRARY`, default `~/house-assets`). Avoid scanned pines and firs: their importer takes many minutes. Grass and trees take long to
+sync, so renders keep persistent data between shots. Any step over 5 minutes gets profiled and fixed.
+
+## Done means
+
+Check, overlay and as-built gates pass and are quoted with their numbers. Interior and exterior stills hold up at full
+size beside real photos. The report states what was sourced, what was inferred and what still looks weak.
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/examples/cabin-plan.json b/plugins/build-house-from-plan/skills/build-house-from-plan/examples/cabin-plan.json
new file mode 100644
index 0000000..c49197d
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/examples/cabin-plan.json
@@ -0,0 +1,971 @@
+{
+ "name": "Cedar Pass Lodge, Cabin 22",
+ "units": "ft",
+ "source": {
+ "image": "source/plan_sheet.png",
+ "url": "https://commons.wikimedia.org/wiki/File:First_floor_plan,_building_section,_west_elevation,_south_elevation,_baseboard_profile,_crown_molding_profile,_window_and_door_details_-_Cedar_Pass_Lodge,_Cabin_22,_20681_South_Dakota_Highway_240,_Interior,_Jackson_County,_SD_HABS_SD-25-Q_(sheet_1_of_1).png",
+ "license": "Public domain: Historic American Buildings Survey, National Park Service"
+ },
+ "calibration": {
+ "pairs": [
+ {
+ "px": [
+ 2265,
+ 2470
+ ],
+ "plan": [
+ 0,
+ 0
+ ]
+ },
+ {
+ "px": [
+ 3904,
+ 2470
+ ],
+ "plan": [
+ 16.375,
+ 0
+ ]
+ },
+ {
+ "px": [
+ 3904,
+ 1036
+ ],
+ "plan": [
+ 16.375,
+ 14.375
+ ]
+ },
+ {
+ "px": [
+ 2265,
+ 1036
+ ],
+ "plan": [
+ 0,
+ 14.375
+ ]
+ }
+ ]
+ },
+ "provenance": {
+ "sourced": [
+ "Walls, door, windows, bathroom fixtures, porch deck and roof overhang outline (HABS first floor plan, dimensioned)",
+ "Ceiling 7'-9 3/4\", sill 3'-0 5/8\", window height 3'-0\", door 6'-7 1/8\", eave and ridge heights above grade (section and elevations)",
+ "Gable roof with the ridge parallel to the front, wood shingles, stucco walls, boarded interior walls (elevations and section)"
+ ],
+ "inferred": [
+ "Colours: stucco, trim and shingle colours are chosen, the sheet is black and white",
+ "Basin shown as a pedestal model where the plan draws a small vanity",
+ "Closet behind the shower is closed off; the plan gives it no door swing",
+ "Beds, nightstand, chair and rug; the plan draws no loose furniture",
+ "Ground: mown grass and trees instead of the real Badlands prairie",
+ "Exterior board-and-batten paint: the sheet shows the plan only, finish taken from the period type"
+ ]
+ },
+ "printed_dimensions": [
+ {
+ "label": "width 16-4 1/2",
+ "a": [
+ 0,
+ 0
+ ],
+ "b": [
+ 16.375,
+ 0
+ ],
+ "value": 16.375
+ },
+ {
+ "label": "depth 14-4 1/2",
+ "a": [
+ 16.375,
+ 0
+ ],
+ "b": [
+ 16.375,
+ 14.375
+ ],
+ "value": 14.375
+ },
+ {
+ "label": "porch 3-5 5/8",
+ "a": [
+ 0,
+ -3.47
+ ],
+ "b": [
+ 0,
+ 0
+ ],
+ "value": 3.47
+ }
+ ],
+ "levels": {
+ "floor": 0.0,
+ "ceiling": 7.81
+ },
+ "style": {
+ "siding": "batten",
+ "wall_base": "stucco_cream",
+ "window_material": "trim_white",
+ "interior_wall": "cabin_boards",
+ "interior_trim": "trim_white",
+ "reveal": "trim_white",
+ "end_cap": "stucco_cream",
+ "door_material": "door_green",
+ "soffit": "trim_white",
+ "fascia": "trim_white",
+ "corner_board": 0.0,
+ "exterior_casing": 0.3,
+ "interior_casing": 0.28,
+ "baseboard": 0.35,
+ "siding_material": "boards_painted",
+ "batten_material": "boards_painted"
+ },
+ "walls": [
+ {
+ "id": "front",
+ "a": [
+ 0.24,
+ 0.24
+ ],
+ "b": [
+ 16.13,
+ 0.24
+ ],
+ "t": 0.48,
+ "kind": "ext",
+ "outside": -1,
+ "top": "roof"
+ },
+ {
+ "id": "east",
+ "a": [
+ 16.13,
+ 0.24
+ ],
+ "b": [
+ 16.13,
+ 14.13
+ ],
+ "t": 0.48,
+ "kind": "ext",
+ "outside": -1,
+ "top": "roof"
+ },
+ {
+ "id": "rear",
+ "a": [
+ 16.13,
+ 14.13
+ ],
+ "b": [
+ 0.24,
+ 14.13
+ ],
+ "t": 0.48,
+ "kind": "ext",
+ "outside": -1,
+ "top": "roof"
+ },
+ {
+ "id": "west",
+ "a": [
+ 0.24,
+ 14.13
+ ],
+ "b": [
+ 0.24,
+ 0.24
+ ],
+ "t": 0.48,
+ "kind": "ext",
+ "outside": -1,
+ "top": "roof"
+ },
+ {
+ "id": "bath_w",
+ "a": [
+ 10.49,
+ 14.13
+ ],
+ "b": [
+ 10.49,
+ 6.7
+ ],
+ "t": 0.42,
+ "kind": "int"
+ },
+ {
+ "id": "bath_diag",
+ "a": [
+ 10.49,
+ 6.7
+ ],
+ "b": [
+ 12.47,
+ 4.6
+ ],
+ "t": 0.25,
+ "kind": "int"
+ },
+ {
+ "id": "bath_s",
+ "a": [
+ 12.47,
+ 4.6
+ ],
+ "b": [
+ 16.13,
+ 4.6
+ ],
+ "t": 0.25,
+ "kind": "int"
+ },
+ {
+ "id": "closet_s",
+ "a": [
+ 10.49,
+ 11.25
+ ],
+ "b": [
+ 13.31,
+ 11.25
+ ],
+ "t": 0.16,
+ "kind": "int"
+ },
+ {
+ "id": "closet_e",
+ "a": [
+ 13.31,
+ 11.25
+ ],
+ "b": [
+ 13.31,
+ 14.13
+ ],
+ "t": 0.16,
+ "kind": "int"
+ }
+ ],
+ "openings": [
+ {
+ "id": "w_front",
+ "wall": "front",
+ "kind": "window",
+ "from": 6.68,
+ "to": 9.8,
+ "sill": 3.05,
+ "head": 6.05,
+ "sash": "double_hung",
+ "panes_x": 1,
+ "panes_y": 2
+ },
+ {
+ "id": "d_front",
+ "wall": "front",
+ "kind": "door",
+ "from": 11.11,
+ "to": 13.75,
+ "sill": 0,
+ "head": 6.6,
+ "panels": "sheathing",
+ "swing": 1,
+ "hinge": "end",
+ "open": 78,
+ "hardware": "brass"
+ },
+ {
+ "id": "w_rear",
+ "wall": "rear",
+ "kind": "window",
+ "from": 6.74,
+ "to": 9.84,
+ "sill": 3.05,
+ "head": 6.05,
+ "sash": "double_hung",
+ "panes_x": 1,
+ "panes_y": 2
+ },
+ {
+ "id": "w_bath",
+ "wall": "east",
+ "kind": "window",
+ "from": 6.4,
+ "to": 8.58,
+ "sill": 3.05,
+ "head": 6.05,
+ "sash": "double_hung",
+ "panes_x": 1,
+ "panes_y": 2
+ },
+ {
+ "id": "d_bath",
+ "wall": "bath_diag",
+ "kind": "door",
+ "from": 0.45,
+ "to": 2.5,
+ "sill": 0,
+ "head": 6.6,
+ "panels": "slab",
+ "swing": -1,
+ "hinge": "start",
+ "open": 85,
+ "material": "trim_white"
+ }
+ ],
+ "rooms": [
+ {
+ "name": "Bedroom",
+ "kind": "bedroom",
+ "floor": "oak_floor",
+ "ceiling": 7.81,
+ "crown": 0.25,
+ "poly": [
+ [
+ 0.48,
+ 0.48
+ ],
+ [
+ 15.89,
+ 0.48
+ ],
+ [
+ 15.89,
+ 4.47
+ ],
+ [
+ 12.35,
+ 4.47
+ ],
+ [
+ 10.28,
+ 6.62
+ ],
+ [
+ 10.28,
+ 13.89
+ ],
+ [
+ 0.48,
+ 13.89
+ ]
+ ]
+ },
+ {
+ "name": "Bathroom",
+ "kind": "bath",
+ "floor": "tile_white",
+ "ceiling": 7.81,
+ "poly": [
+ [
+ 12.59,
+ 4.73
+ ],
+ [
+ 15.89,
+ 4.73
+ ],
+ [
+ 15.89,
+ 13.89
+ ],
+ [
+ 13.39,
+ 13.89
+ ],
+ [
+ 13.39,
+ 11.33
+ ],
+ [
+ 10.7,
+ 11.33
+ ],
+ [
+ 10.7,
+ 6.78
+ ]
+ ]
+ },
+ {
+ "name": "Closet",
+ "kind": "closet",
+ "floor": "oak_floor",
+ "ceiling": 7.81,
+ "no_access": true,
+ "poly": [
+ [
+ 10.7,
+ 11.33
+ ],
+ [
+ 13.23,
+ 11.33
+ ],
+ [
+ 13.23,
+ 13.89
+ ],
+ [
+ 10.7,
+ 13.89
+ ]
+ ]
+ }
+ ],
+ "slabs": [
+ {
+ "poly": [
+ [
+ 0,
+ 0
+ ],
+ [
+ 16.375,
+ 0
+ ],
+ [
+ 16.375,
+ 14.375
+ ],
+ [
+ 0,
+ 14.375
+ ]
+ ],
+ "z": -0.02,
+ "t": 1.2,
+ "material": "concrete_floor",
+ "side_material": "stone_rubble"
+ },
+ {
+ "poly": [
+ [
+ -0.21,
+ -3.47
+ ],
+ [
+ 16.1,
+ -3.47
+ ],
+ [
+ 16.1,
+ 0
+ ],
+ [
+ -0.21,
+ 0
+ ]
+ ],
+ "z": -0.08,
+ "t": 0.9,
+ "material": "pine_boards",
+ "side_material": "pine_boards"
+ }
+ ],
+ "roof": {
+ "planes": [
+ {
+ "name": "front",
+ "corners": [
+ [
+ -1.0,
+ -1.29,
+ 7.73
+ ],
+ [
+ 17.37,
+ -1.29,
+ 7.73
+ ],
+ [
+ 17.37,
+ 7.19,
+ 12.09
+ ],
+ [
+ -1.0,
+ 7.19,
+ 12.09
+ ]
+ ],
+ "cover": "shingle",
+ "thickness": 0.14,
+ "exposure": 0.42,
+ "course": 0.5,
+ "fascia_depth": 0.45,
+ "fascia": "trim_white",
+ "rafters": {
+ "spacing": 2.0,
+ "first": 0.7,
+ "w": 0.125,
+ "d": 0.36,
+ "material": "trim_white"
+ }
+ },
+ {
+ "name": "rear",
+ "corners": [
+ [
+ -1.0,
+ 15.7,
+ 7.73
+ ],
+ [
+ 17.37,
+ 15.7,
+ 7.73
+ ],
+ [
+ 17.37,
+ 7.19,
+ 12.09
+ ],
+ [
+ -1.0,
+ 7.19,
+ 12.09
+ ]
+ ],
+ "cover": "shingle",
+ "thickness": 0.14,
+ "exposure": 0.42,
+ "course": 0.5,
+ "fascia_depth": 0.45,
+ "fascia": "trim_white",
+ "rafters": {
+ "spacing": 2.0,
+ "first": 0.7,
+ "w": 0.125,
+ "d": 0.36,
+ "material": "trim_white"
+ }
+ }
+ ]
+ },
+ "boxes": [
+ {
+ "origin": [
+ 13.39,
+ 11.33,
+ 0
+ ],
+ "x": [
+ 2.5,
+ 0,
+ 0
+ ],
+ "y": [
+ 0,
+ 0.08,
+ 0
+ ],
+ "z": [
+ 0,
+ 0,
+ 0.5
+ ],
+ "material": "trim_white"
+ },
+ {
+ "origin": [
+ 13.39,
+ 11.33,
+ 0
+ ],
+ "x": [
+ 2.5,
+ 0,
+ 0
+ ],
+ "y": [
+ 0,
+ 2.56,
+ 0
+ ],
+ "z": [
+ 0,
+ 0,
+ 0.12
+ ],
+ "material": "counter_laminate"
+ }
+ ],
+ "curtains": [
+ {
+ "a": [
+ 13.4,
+ 11.4
+ ],
+ "b": [
+ 15.85,
+ 11.4
+ ],
+ "z0": 0.3,
+ "z1": 6.6,
+ "material": "curtain_plain",
+ "folds": 9
+ }
+ ],
+ "rugs": [
+ {
+ "a": [
+ 5.2,
+ 3.6
+ ],
+ "b": [
+ 9.8,
+ 11.2
+ ],
+ "material": "fabric_rug"
+ }
+ ],
+ "furnish": [
+ {
+ "asset": "obj:b0aa0259376b435fab6645365a7fbd87",
+ "at": [
+ 3.95,
+ 10.7
+ ],
+ "rot": 90,
+ "fit_w": 6.6,
+ "name": "bed_rear"
+ },
+ {
+ "asset": "obj:b0aa0259376b435fab6645365a7fbd87",
+ "at": [
+ 3.95,
+ 4.9
+ ],
+ "rot": 90,
+ "fit_w": 6.6,
+ "name": "bed_front"
+ },
+ {
+ "asset": "ph:ClassicNightstand_01",
+ "at": [
+ 1.35,
+ 7.8
+ ],
+ "rot": 90,
+ "fit_h": 2.0,
+ "name": "nightstand"
+ },
+ {
+ "asset": "ph:vintage_oil_lamp",
+ "at": [
+ 1.35,
+ 7.8
+ ],
+ "z": 2.02,
+ "rot": 0,
+ "fit_h": 1.3,
+ "name": "oil_lamp"
+ },
+ {
+ "asset": "ph:Rockingchair_01",
+ "at": [
+ 9.0,
+ 2.2
+ ],
+ "rot": -30,
+ "name": "rocker"
+ },
+ {
+ "asset": "ph:side_table_01",
+ "at": [
+ 14.6,
+ 1.9
+ ],
+ "rot": 0,
+ "fit_h": 1.9,
+ "name": "side_table"
+ },
+ {
+ "asset": "ph:hanging_picture_frame_01",
+ "at": [
+ 10.2,
+ 8.8
+ ],
+ "z": 4.1,
+ "rot": 90,
+ "fit_h": 1.6,
+ "name": "picture"
+ },
+ {
+ "asset": "obj:24d1b493899d407780140688abae19bc",
+ "at": [
+ 11.8,
+ 9.77
+ ],
+ "rot": 90,
+ "fit_h": 2.5,
+ "name": "toilet"
+ },
+ {
+ "asset": "obj:901084912a1b41758dc8b892b25ac46d",
+ "at": [
+ 14.35,
+ 5.75
+ ],
+ "rot": 180,
+ "fit_h": 2.9,
+ "name": "basin"
+ },
+ {
+ "asset": "ph:painted_wooden_chair_02",
+ "at": [
+ 8.0,
+ -1.9
+ ],
+ "rot": 10,
+ "name": "porch_chair"
+ }
+ ],
+ "lamps": [],
+ "site": {
+ "hdri": "kloofendal_48d_partly_cloudy_puresky",
+ "sun": {
+ "azimuth": 318,
+ "elevation": 40,
+ "strength": 4.2
+ },
+ "ground_level": -0.68,
+ "centre": [
+ 8,
+ 6
+ ],
+ "flat_radius": 26,
+ "ground_size": 2600,
+ "grass_radius": 150,
+ "grass_density": 90,
+ "grass_scale": 1.0,
+ "no_grass": [],
+ "paths": [
+ {
+ "poly": [
+ [
+ 10.6,
+ -3.6
+ ],
+ [
+ 14.0,
+ -3.6
+ ],
+ [
+ 14.6,
+ -60.0
+ ],
+ [
+ 10.0,
+ -60.0
+ ]
+ ],
+ "material": "gravel_path"
+ }
+ ],
+ "plants": [
+ {
+ "asset": "ph:island_tree_01",
+ "at": [
+ -46,
+ 30
+ ],
+ "rot": 40,
+ "fit_h": 30
+ },
+ {
+ "asset": "ph:tree_small_02",
+ "at": [
+ 46,
+ 34
+ ],
+ "rot": 120,
+ "fit_h": 20
+ }
+ ],
+ "treeline": [
+ {
+ "radius": 300,
+ "count": 110,
+ "heights": [
+ 45,
+ 85
+ ],
+ "assets": [
+ "ph:island_tree_01",
+ "ph:island_tree_02",
+ "ph:tree_small_02"
+ ]
+ },
+ {
+ "radius": 900,
+ "count": 260,
+ "heights": [
+ 55,
+ 95
+ ],
+ "assets": [
+ "ph:island_tree_01",
+ "ph:island_tree_02",
+ "ph:tree_small_02"
+ ]
+ }
+ ]
+ },
+ "shots": [
+ {
+ "name": "ext_front",
+ "kind": "exterior",
+ "pos": [
+ 32,
+ -26,
+ 4.6
+ ],
+ "look": [
+ 8,
+ 6,
+ 5.8
+ ],
+ "lens": 34,
+ "exposure": 0.0
+ },
+ {
+ "name": "int_bedroom",
+ "kind": "interior",
+ "pos": [
+ 9.7,
+ 13.3,
+ 4.8
+ ],
+ "look": [
+ 1.5,
+ 4.5,
+ 3.6
+ ],
+ "lens": 22
+ },
+ {
+ "name": "int_bath",
+ "kind": "interior",
+ "pos": [
+ 11.4,
+ 6.9,
+ 4.8
+ ],
+ "look": [
+ 15.5,
+ 12.6,
+ 3.0
+ ],
+ "lens": 20
+ },
+ {
+ "name": "cutaway",
+ "kind": "exterior",
+ "pos": [
+ 28,
+ -24,
+ 30
+ ],
+ "look": [
+ 8,
+ 7,
+ 0
+ ],
+ "lens": 40,
+ "level": false,
+ "cut": 7.0,
+ "exposure": 0.0
+ }
+ ],
+ "films": [
+ {
+ "name": "rise",
+ "frames": 264,
+ "lens": 34,
+ "level": false,
+ "exposure": 0.0,
+ "build_up": {},
+ "path": [
+ {
+ "pos": [
+ 8.184999999999999,
+ 6.585000000000001,
+ 34
+ ],
+ "look": [
+ 8.184999999999999,
+ 7.1850000000000005,
+ 0
+ ]
+ },
+ {
+ "pos": [
+ 10.0902,
+ 4.530200000000001,
+ 32.64
+ ],
+ "look": [
+ 8.184999999999999,
+ 7.1850000000000005,
+ 0
+ ]
+ },
+ {
+ "pos": [
+ 14.8532,
+ -2.1068000000000016,
+ 29.24
+ ],
+ "look": [
+ 8.184999999999999,
+ 7.1850000000000005,
+ 0
+ ]
+ },
+ {
+ "pos": [
+ 18.90175,
+ -7.7482500000000005,
+ 25.16
+ ],
+ "look": [
+ 8.184999999999999,
+ 7.1850000000000005,
+ 0.5
+ ]
+ },
+ {
+ "pos": [
+ 22.9503,
+ -13.3897,
+ 17.0
+ ],
+ "look": [
+ 8.0925,
+ 6.5925,
+ 2.32
+ ]
+ },
+ {
+ "pos": [
+ 32,
+ -26,
+ 4.6
+ ],
+ "look": [
+ 8,
+ 6,
+ 5.8
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/references/plan-format.md b/plugins/build-house-from-plan/skills/build-house-from-plan/references/plan-format.md
new file mode 100644
index 0000000..9dac1b0
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/references/plan-format.md
@@ -0,0 +1,113 @@
+# Plan file format
+
+`plan.json` is the only input to the build. `scripts/plan_check.py` validates it. Worked example:
+`examples/cabin-plan.json`, a one-room cabin from a public domain HABS sheet.
+
+<!-- skill-navigation:start -->
+- [Plan file format](#plan-file-format)
+- [Frame](#frame)
+- [Walls](#walls)
+- [Levels](#levels)
+- [Openings](#openings)
+- [Rooms](#rooms)
+- [Roof and frame](#roof-and-frame)
+- [Fitted and furnished](#fitted-and-furnished)
+- [Site, shots, films](#site-shots-films)
+- [Streets](#streets)
+- [Gates](#gates)
+<!-- skill-navigation:end -->
+
+## Frame
+
+`units` is `ft` or `m`. Every length in the file uses it. Origin is usually the outer front-left corner, x along the
+front, y into the house, z up from the finished floor. `calibration.pairs` lists at least 3 `{px, plan}` pairs in
+source image pixels. They fit an affine, so a drawing scanned with different x and y scale still lines up.
+`ink_threshold` overrides the automatic ink level. `source` needs `image`, `url`, `license`.
+`printed_dimensions` lists at least 3 `{label, a, b, value}` copied from the drawing or scale bar.
+`provenance.sourced` and `provenance.inferred` are required: every roof, facade, height and finish you did not read
+goes in `inferred`, and the report repeats that list.
+
+## Walls
+
+`{id, a, b, t, kind: "ext"|"int", outside: 1|-1, top: "roof", h, z0, free_end, dashed}`. `a` and `b` are the
+centreline. `outside` says which side of the a-to-b direction faces out: +1 is its left, so a counter-clockwise outer
+loop uses -1. Without `top: "roof"` a wall stops at `h` or `levels.ceiling`. `free_end` marks a stub that touches
+nothing. `dashed` marks walls the drawing shows dashed (later or removed): they are built but not scored. Ends resolve
+themselves: at an L the earlier wall runs through and the later one butts. At a T the stem butts.
+
+## Levels
+
+For more than one storey, rooms take `level` and `floor_z`. Walls take `level` (or `levels: [1, 2]`) and `z0`. A sheet
+that draws the upper floor beside the first uses `calibration.level_offsets: {"2": [dx, dy]}` in plan units, so each
+wall is scored against its own drawing. `style.roof_union: true` makes a wall top the highest plane above it, for
+crossing gables. The as-built section is taken 1.6 m above each wall's own `z0`.
+
+## Openings
+
+`{id, wall, kind: "window"|"door"|"cased"|"fireplace", from, to, sill, head}`, distances along the wall from `a`.
+Stacked storeys may share `from`/`to` when their heights do not overlap.
+Windows: `sash: "fixed"|"double_hung"`, `sections`, `panes_x`, `panes_y`, `transom_at`, `shutters` (leaf width).
+Doors: `panels: "slab"|"six"|"four"|"two"|"sheathing"`, `leaves`, `swing` (+1|-1 side), `hinge: "start"|"end"`, `open`
+(degrees), `material`, `frame_material`, `hardware`. Fireplaces: `room_side`, `depth`, `firebox` (real recess depth), `brick`, `hearth`, `surround`.
+
+## Rooms
+
+`{name, kind, poly, floor, wall, ceiling, ceiling_material, baseboard, crown, chair_rail, trim, open_edges, open_to,
+no_access}`. `poly` runs along the finished wall faces. No `ceiling` means open to the roof. `open_edges` lists polygon
+edge indices with no wall (edge i runs from point i to i+1). `open_to` names rooms joined with no door.
+`no_access` marks a closed cupboard. The check walks doors, cased openings and `open_to` from outside.
+
+## Roof and frame
+
+`roof.planes[]`: `{corners, cover: "shingle"|"roll"|"none", thickness, exposure, course, fascia_depth, fascia, under,
+top_material, rafters: {spacing, first, w, d, material}}`. `corners` are the deck underside in this order: eave start,
+eave end, ridge end, ridge start, each `[x, y, z]`, overhang included. Walls with `top: "roof"` rise to the lowest plane
+above them, which also makes the gable fill. `beams[]`: `{a, b, w, d, material}` where `a`, `b` are bottom-centre
+points. `posts[]`: `{at, w, d, z0, z1, material}`. `chimneys[]`: `{at, w, d, z0, z1, material, cap_material, flue, cap}`.
+`slabs[]`: `{poly, z, t, material, side_material}`.
+`style`: `siding: "clapboard"|"batten"`, `siding_material`, `batten_material`, `exposure`, `wall_base`, `interior_wall`,
+`interior_trim`, `window_material`, `door_material`, `reveal`, `end_cap`, `soffit`, `fascia`, `corner_board`,
+`corner_material`, `exterior_casing`, `interior_casing`, `baseboard`, `shutter_material`.
+Material names live in `TEXTURED_MATERIALS` and `PLAIN_MATERIALS` in `scripts/house_core.py`: add a line there with the
+Poly Haven or ambientCG folder and real tile size for a new finish.
+
+## Fitted and furnished
+
+`casework[]`: `{kind: "base"|"wall", a, b, depth, z0, z1, doors, side, counter, material, hardware}`. Doors face the
+left of a-to-b when `side` is 1. `stairs[]`: `{start, heading, width, run, rise, steps, z0, material, riser_material}`.
+`panelling[]`: `{a, b, z0, z1, cols, rows, side, material, stile, offset}`. `curtains[]`: `{a, b, z0, z1, folds, material}`.
+`rugs[]`: `{a, b, material}`. `boxes[]`: `{origin, x, y, z, material}` for shelves and anything plain.
+`furnish[]`: `{asset, at, rot, z, scale, fit_w, fit_h, fit_max, fit_size: [x, y, z], hang, part, paint, name}`. `paint` puts every part of a model in one named material, for models with missing textures. `fit_size` stretches
+to a measured size, `hang` is the gap below the ceiling for a pendant, `part` keeps one model from a file that holds a
+row of variants (Poly Haven plants). At `rot: 0` a model's front faces -y, so it faces `(sin rot, -cos rot)`. `asset` is `ph:<Poly Haven id>` (from
+the asset library's `models` folder) or `obj:<Objaverse uid>` (from `site.objaverse_folder`). `at` is the footprint centre. `lamps[]`:
+`{at, z, watts, kind, colour, soft}`.
+
+## Site, shots, films
+
+`site`: `hdri`, `sun: {azimuth, elevation, strength, angle, colour}`, `sky_strength`, `sky_clamp`, `centre`,
+`flat_radius`, `ground_size`, `ground`, `grass_radius`, `grass_density`, `grass_scale`, `paths[]`, `no_grass[]`,
+`plants[]` (same keys as `furnish`), `treeline: {count, radius, assets}` or a list of those for several rings, `window_sky` (brightness of the lamp filling each window on interior shots, default 1.0), `ground_level`, `objaverse_folder`. Azimuth is degrees from +x, counter-clockwise. The sky's own
+sun is turned to match and clamped, so the lamp casts the sharp shadow.
+`shots[]`: `{name, kind: "interior"|"exterior", pos, look, lens, exposure, meter, meter_target, level, cut}`. Interiors meter
+themselves to a median (`meter_target`, default 0.26) the way a camera does; `exposure` adds stops on top. `level` (default on) keeps
+verticals vertical with lens shift. `cut` slices the house at that height above the floor, caps the walls in dark
+poché and hides the roof and ceilings. `films[]`: `{name, frames, path: [{pos, look}], lens, exposure, cut, interior, level, build_up}`.
+`build_up: {walls: [start, end], roof: [start, end], furnish: [start, end]}` (fractions of the film) lays the source sheet
+on the floor, aligned by the calibration pairs, grows the walls off its lines from the centre out, lands the roof and
+brings in the furniture.
+
+## Streets
+
+`scripts/build_street.py <street.json> <out.blend>` sets finished houses along a road. Keys: `units`, `house_types:
+{name: {plan, blend}}` (paths relative to the file), `lots: [{type, at, rot}]`, `paints: {material: [[position, [r, g, b]]]}`
+(per-lot colour multiply), `surfaces: [{poly, material, z}]` for road, pavements and drives, then `site`, `shots`, `films`
+as above. Render with `render_house.py` as for a house.
+
+## Gates
+
+`plan_check.py check` needs walls joined, openings on their wall, no overlaps, plausible door and window sizes, room
+edges on walls, every room reachable, printed dimensions matched within 10 cm and provenance filled in.
+`overlay` and `asbuilt` score the fraction of wall faces with ink within 7 cm, require a score of at least 0.70, a
+best-fit offset of at most 16 cm over a 60 cm sweep, and a clear win over a 50 cm shifted control. They write
+`check_plan_overlay.png` and `check_asbuilt_overlay.png` next to the plan.
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/references/read-plan.md b/plugins/build-house-from-plan/skills/build-house-from-plan/references/read-plan.md
new file mode 100644
index 0000000..acfa2ad
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/references/read-plan.md
@@ -0,0 +1,61 @@
+# Reading a house plan into `plan.json`
+
+You read the drawing yourself, with your eyes, in crops. No detector or vectoriser: scans have stains, dimension lines and
+lettering across the walls, and a wrong wall that looks plausible costs more than the reading does.
+
+## Reading map
+
+- Get a drawing worth reading: "Sources". Fix the scale: "Calibrate".
+- Walls, openings, rooms in order: "Read". What to do with what the plan does not say: "Infer and state it".
+
+## Sources
+
+Licence first, then resolution. What worked:
+
+- HABS and HAER on Wikimedia Commons or the Library of Congress (public domain): the full TIF is 5000-10000 px, walls measured,
+ and the same record often holds 1930s photographs and elevations. Search `<place> HABS` and read the sheet list.
+- USDA farmhouse plans from the 1950s-60s (public domain): printed dimensions, sections, room names, furniture drawn in.
+- A sheet under 3000 px across a whole house is too coarse for wall thickness. Look for the TIF.
+- Save the sheet untouched as `<project>/source/`, and record its URL and licence in `source`.
+
+Pick a sheet with a floor plan **and**, if you can, an elevation and a section. Each one saved turns inferred items into sourced.
+
+## Calibrate
+
+1. Find the scale bar and the longest printed dimensions. Open crops at their ends and write down exact pixels.
+2. Use at least 3 `{px, plan}` pairs far apart, ideally four outer corners. Scans stretch: x and y often differ by a percent, so
+ the affine matters. Never derive the scale from one dimension.
+3. Copy at least 3 `printed_dimensions` that are not the ones you calibrated on, and let `plan_check.py check` compare them.
+4. Choose the origin at the outer front-left corner, and `units` as the drawing's own (feet stay feet: `26'-0"` is 26).
+
+## Read
+
+Open crops at 100%, one wing at a time, with 10-15% overlap. Do not read a whole sheet downsized: thin partitions vanish.
+
+1. **Outer walls**, a counter-clockwise loop on the wall centreline. Thickness is measured from the ink, not assumed: a 1670
+ frame house and a 1958 stud wall differ by a factor of three.
+2. **Inner walls** next, joined to the wall they meet. Dashed lines are later or removed walls: mark them `dashed`.
+3. **Openings** by wall, as distances from `a`. A swing arc gives the hinge and side. Two parallel lines across a wall with no arc
+ are a window. Read its sash from the elevation or photos. Note what the arc's absence means, for example a drawing
+ that gives no swing for a closet door: put that under `provenance.inferred`.
+4. **Stairs**: count treads, read the arrow. **Fireplaces**: the hatched mass is the chimney.
+5. **Rooms**: names as lettered. Polygon on the finished faces. Mark open edges, cupboards with `no_access`.
+6. **Fixtures** drawn in the plan (tub, sink, range, cabinets) go in at their drawn place. That is sourced, not furnishing.
+7. Run `check`, then `overlay`, and open `check_plan_overlay.png` at full size. Fix the plan, not the threshold. A wall whose faces
+ score low is usually a wrong thickness or a wall on the wrong side of its ink.
+
+## Infer and state it
+
+A floor plan does not say these. Decide each one and list it in `provenance.inferred`, and repeat that list in the report:
+
+| Question | Where the answer comes from, best first |
+|---|---|
+| Roof shape, pitch, ridge | section sheet, elevation, photo, then the era and region |
+| Ceiling and storey heights | section, elevation, printed note, then 2.4 m modern or 2.1-2.3 m pre-1800 |
+| Facade cladding, its exposure | elevation note, photo, then era and region |
+| Window sash and panes | elevation, photo, then era |
+| Colours and finishes | photo (black and white gives value only), then era |
+| Furniture | fixtures from the plan first, then the room's use and era |
+| Upper storeys with no plan | exterior shell only, say so |
+
+Era and region matter more than taste: a 1958 USDA farm cottage gets battens and roll roofing, not a stone chimney.
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/references/realism-faults.md b/plugins/build-house-from-plan/skills/build-house-from-plan/references/realism-faults.md
new file mode 100644
index 0000000..4fb09e9
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/references/realism-faults.md
@@ -0,0 +1,81 @@
+# Faults that make a built house look fake
+
+Each entry was seen on a real render from this pipeline. Read the group you are judging, then look for it at full size.
+
+## Reading map
+
+- Light: "Light". Walls and roof: "Surfaces". Lawn and sky: "Site". Inside: "Rooms". Numbers wrong: "Build".
+
+## Light
+
+- **Rooms dark, needing 8 stops.** Refractive glass with caustics off drops every bounce that crosses it. Only camera rays
+ see real glass now, the rest pass a clear tint. Measured on the cottage living room: median 0.0002 to 0.0016.
+- **A room lit flat and grey.** The sun missed every window you can see. Set `site.sun.azimuth` so sun lands on the walls in
+ the hero shot and through a window in the main room.
+- **Walls smeared like foil, half the room black.** Too few light paths find a window, and the denoiser paints over the gaps.
+ Sky portals did not help, flipped or not (Holten hall median stayed 0). A soft lamp filling each window, hidden from the
+ camera, took the median to 0.0064 and the mean from 0.002 to 0.012. Tune it with `site.window_sky`.
+- **Interior exposure guessed per shot.** Rooms differ by stops. Interiors meter themselves. Leave `exposure` for taste.
+- **Exterior with a black side.** Sun behind the visible faces. Turn the sun, not the exposure.
+
+- **White rectangles over the view in a window.** The window lamp shows in the glass. Hide it from glossy and transmission
+ rays as well as the camera.
+
+## Surfaces
+
+- **Inside walls read as grey concrete or foil.** Scanned plaster keeps its blotches at any tile size, and from inside a room
+ they fill the frame. A painted wall is a plain colour drifting by a few percent. Use `wall_paint` or `wall_paint_old`, or
+ real boards where the house had them.
+- **A model comes out pure white.** Its textures are missing. Give the item `paint` with a material name.
+
+- **Siding a dark chocolate block.** Scanned plank textures are dark before any tint. Lift the tint and desaturate, then
+ compare with a photo of the same material in daylight.
+- **Wood floor with narrow modern strips in an old house.** Pick wide boards and check tile size against the room.
+- **Rug or curtain reads as plastic.** Textile set with no fibre detail. Use a real fabric scan at a small tile (0.2 m for
+ linen) and pale tint.
+- **Roof reads as a flat colour.** Too small a shingle texture, seen as noise from far away. Keep real shingle courses in
+ the mesh and let the texture add wear.
+- **Fireplace as a painted box.** Give it a real `firebox` depth, brick inside, hearth, mantel and tools.
+
+## Site
+
+- **Lawn as a green sheet.** Flat texture from any low angle. Use tufted grass by instancing, a ground texture beneath, and
+ density falling with distance.
+- **Path as a smooth plank.** A strip with straight edges and big tile. Use uneven edges, conform it to the ground, use a
+ smaller tile or a worn dirt-and-grass scan.
+- **White patches on grass, a pale strip at the horizon.** The scanned ground's roughness map mirrors the sky at low angles.
+ The ground is now matte, with no roughness map.
+- **Grass growing through a road or floor.** Excluding it per blade took 1287 s on the street. A 4 m grid of polygons took
+ 127 s and looks the same.
+- **Empty strip at the horizon.** The ground ends in clean sky. Add a treeline of 110 or more trees, set `ground_size`
+ well past it. Use a list of rings when one ring leaves gaps.
+- **Disc edge in a high aerial.** The ground has an end. Keep the camera low enough that the treeline hides it.
+- **Pines and firs.** The scanned pine takes many minutes to import. Use broadleaf trees unless the place demands them.
+- **House floating or sunk.** Set `site.ground_level` from the drawing's steps, and let the plinth show.
+
+## Rooms
+
+- **Sofa or chairs facing the wall.** Model orientation assumed. At `rot: 0` a model's front faces -y. Check on the grid
+ with `preview_assets.py` before placing.
+- **A model at the wrong size.** Objaverse units vary. Always use `fit_w`, `fit_h` or `fit_size` with a measured size.
+- **A row of plants in one pot.** Poly Haven plant files hold several variants. Use `part` to keep one.
+- **Modern fridge in a 1950s kitchen.** Pick period models and look at them beside a photo of the period. Search by several
+ words ("vintage", "retro", the maker).
+- **A washing machine with its door open, a toilet with a broken lid.** Scanned or sculpted models carry odd states. Look at
+ the model before placing it.
+- **Empty rooms.** A room with one object reads as a game level. Add curtains, a rug, a lamp and what the room is used for.
+- **Beds floating, models the wrong size.** A linked model's matrix is stale until `view_layer.update()`, so its bounding box
+ lies. Update before measuring.
+- **Black or blank slab filling part of the frame.** The camera stands inside a wall or behind a door leaf. Check every shot
+ in a preview before a final render.
+- **Upper floor hiding the room in a cutaway, or one cut ignored.** Cuts must slice `floors` as well as walls. Shots run
+ uncut first, then highest cut down, and recut when the height changes.
+
+## Build
+
+- **As-built score below the plan score.** Wall ends or a stub misread. Open `check_asbuilt_overlay.png` and read which
+ wall is off.
+- **Door check failing on an upper floor.** A door's head is measured from its own sill.
+- **Build over 5 minutes.** glTF import. Models cache as linked `.blend` files after their first import.
+- **Film over 20 s a frame at 20 samples.** Writing `hide_render` or a scale that did not change still tags the scene, and
+ Cycles rebuilds it. The build-up film writes only values that changed.
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/build_house.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/build_house.py
new file mode 100644
index 0000000..eb1b185
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/build_house.py
@@ -0,0 +1,729 @@
+"""Build a house from a checked plan file into a .blend, with an as-built wall section for the overlay check.
+
+Run: blender -b --factory-startup -P build_house.py -- <plan.json> <output.blend>
+The plan format is in ../references/plan-format.md.
+"""
+
+import json
+import math
+import pathlib
+import random
+import sys
+import time
+
+import bpy
+from mathutils import Vector, noise
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
+
+import house_core # noqa: E402
+import house_parts # noqa: E402
+from house_core import MeshBatch, section_segments # noqa: E402
+
+METRES_PER_UNIT = {"m": 1.0, "ft": 0.3048}
+SECTION_HEIGHT_METRES = 1.6
+LENGTH_KEYS = {
+ "a", "b", "t", "h", "z0", "z1", "from", "to", "at", "width", "sill", "head", "poly", "corners", "thickness",
+ "spacing", "w", "d", "first", "start_inset", "x_min", "x_max", "start", "run", "rise", "depth", "ceiling", "floor_z",
+ "baseboard", "crown", "chair_rail", "transom_at", "shutters", "fascia_depth", "exposure", "course", "cap", "flue",
+ "nose_start", "nose_end", "toe", "stile", "offset", "fit_w", "fit_h", "fit_max", "z", "pos", "look", "grass_radius",
+ "radius", "path", "no_grass", "fit_size", "ground_level", "heights", "ground_size", "reach", "side_offset", "section_z", "centre", "flat_radius", "origin", "x", "y",
+}
+KEEP_AS_IS = {"px", "plan_px", "sun", "pairs", "printed_dimensions", "calibration", "source", "provenance", "furnish_notes", "style"}
+
+
+def convert_lengths(value, scale, key=None):
+ """Turn every length in the plan into metres, leaving counts, names and angles alone."""
+ if isinstance(value, dict):
+ return {name: (item if name in KEEP_AS_IS else convert_lengths(item, scale, name)) for name, item in value.items()}
+ if isinstance(value, list):
+ return [convert_lengths(item, scale, key) for item in value]
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and key in LENGTH_KEYS:
+ return value * scale
+ return value
+
+
+def load_plan(path):
+ raw = json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
+ scale = METRES_PER_UNIT[raw.get("units", "m")]
+ plan = convert_lengths(raw, scale)
+ plan["levels"] = {name: length * scale for name, length in raw["levels"].items()}
+ style = dict(raw.get("style", {}))
+ for key in ("exterior_casing", "interior_casing", "corner_board", "baseboard"):
+ if key in style:
+ style[key] = style[key] * scale
+ plan["style"] = style
+ plan["_folder"] = pathlib.Path(path).resolve().parent
+ return plan
+
+
+def new_collection(name):
+ collection = bpy.data.collections.new(name)
+ bpy.context.scene.collection.children.link(collection)
+ return collection
+
+
+def build_floors(plan, collection):
+ batch = MeshBatch("floors", 11)
+ levels = plan["levels"]
+ style = plan["style"]
+ floor_z = levels.get("floor", 0.0)
+ for room in plan["rooms"]:
+ material = room.get("floor", style.get("floor", "oak_floor"))
+ outline = room["poly"]
+ points = [Vector((point[0], point[1], floor_z + room.get("floor_z", 0.0))) for point in outline]
+ batch.uv_offset = (batch.random.uniform(0, 9), batch.random.uniform(0, 9))
+ batch.add_face(points, material, uvs=[(point[0], point[1]) for point in outline])
+ batch.uv_offset = (0, 0)
+ for slab in plan.get("slabs", []):
+ batch.add_prism(slab["poly"], slab["z"] - slab.get("t", 0.1), slab["z"], slab.get("side_material", slab["material"]), material_top=slab["material"])
+ batch.finish(collection)
+
+
+def build_ceilings(plan, collection):
+ batch = MeshBatch("ceilings", 12)
+ floor_z = plan["levels"].get("floor", 0.0)
+ for room in plan["rooms"]:
+ height = room.get("ceiling")
+ if height is None:
+ continue
+ points = [Vector((point[0], point[1], floor_z + height)) for point in reversed(room["poly"])]
+ batch.add_face(points, room.get("ceiling_material", plan["style"].get("ceiling", "ceiling_paint")), uvs=[(point[0], point[1]) for point in reversed(room["poly"])])
+ batch.finish(collection)
+
+
+def build_structure(plan, structure, collections):
+ style = plan["style"]
+ reveal = style.get("reveal", style["interior_wall"])
+ for wall in structure.walls:
+ batch = MeshBatch(f"wall_{wall.id}", hash(wall.id) & 0xffff)
+ house_parts.build_wall(structure, wall, batch, reveal)
+ batch.finish(collections["walls"])
+
+ siding = MeshBatch("siding", 21)
+ trim = MeshBatch("trim", 22)
+ glass = MeshBatch("glazing", 23)
+ hardware = MeshBatch("hardware", 24)
+ siding_kind = style.get("siding", "clapboard")
+ siding_material = style.get("siding_material", "siding_white")
+ for wall in structure.walls:
+ if not wall.outside_side:
+ house_parts.build_baseboards(structure, wall, trim)
+ continue
+ house_parts.build_baseboards(structure, wall, trim)
+ if siding_kind == "clapboard":
+ house_parts.siding_clapboard(structure, wall, siding, siding_material, style.get("exposure", house_parts.BOARD_EXPOSURE_CLAPBOARD))
+ elif siding_kind == "batten":
+ house_parts.siding_board_batten(structure, wall, siding, siding_material, style.get("batten_material", siding_material))
+ house_parts.build_corner_boards(structure, wall, trim, style.get("corner_material", style.get("window_material", "trim_white")))
+ for wall in structure.walls:
+ for opening in wall.openings:
+ kind = opening.get("kind")
+ if kind == "window":
+ house_parts.build_window(structure, wall, opening, trim, glass)
+ elif kind in ("door", "cased"):
+ house_parts.build_door(structure, wall, opening, trim, hardware)
+ elif kind == "fireplace":
+ house_parts.build_fireplace(structure, wall, opening, trim)
+ siding.finish(collections["facade"])
+ trim.finish(collections["facade"], bevel=0.0022)
+ glass.finish(collections["facade"])
+ hardware.finish(collections["facade"], smooth=True)
+
+ roof_collection = collections["roof"]
+ deck = MeshBatch("roof_deck", 31)
+ covering = MeshBatch("roof_cover", 32)
+ carpentry = MeshBatch("roof_carpentry", 33)
+ for plane in structure.roof_planes:
+ house_parts.build_roof_plane(plane.data, plane, deck, covering, carpentry, style)
+ deck.finish(roof_collection)
+ covering.finish(roof_collection)
+ carpentry.finish(roof_collection, bevel=0.003)
+
+ timber = MeshBatch("timber", 34)
+ for beam in plan.get("beams", []):
+ house_parts.build_beam(timber, beam)
+ for post in plan.get("posts", []):
+ house_parts.build_post(timber, post)
+ timber.finish(collections["frame"], bevel=0.003)
+
+ upper = MeshBatch("chimneys", 35)
+ for chimney in plan.get("chimneys", []):
+ house_parts.build_chimney(upper, chimney)
+ upper.finish(roof_collection)
+
+ fitted = MeshBatch("casework", 41)
+ fitted_hardware = MeshBatch("casework_hardware", 42)
+ for unit in plan.get("casework", []):
+ house_parts.build_casework(fitted, fitted_hardware, unit, style)
+ for stair in plan.get("stairs", []):
+ house_parts.build_stairs(fitted, stair, style.get("stair", "old_floor"))
+ for panel in plan.get("panelling", []):
+ house_parts.build_panelling(fitted, panel)
+ for shelf in plan.get("boxes", []):
+ fitted.uv_offset = (fitted.random.uniform(0, 6), fitted.random.uniform(0, 6))
+ origin = Vector(shelf["origin"])
+ fitted.add_box(origin, Vector(shelf["x"]), Vector(shelf["y"]), Vector(shelf["z"]), shelf["material"])
+ fitted.uv_offset = (0, 0)
+ fitted.finish(collections["fitted"], bevel=0.0015)
+ fitted_hardware.finish(collections["fitted"], smooth=True)
+
+ fabric = MeshBatch("fabric", 51)
+ for curtain in plan.get("curtains", []):
+ house_parts.build_curtain(fabric, curtain, curtain.get("material", "curtain_plain"))
+ for rug in plan.get("rugs", []):
+ x0, y0 = rug["a"]
+ x1, y1 = rug["b"]
+ z = plan["levels"].get("floor", 0.0)
+ outline = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
+ fabric.add_prism(outline, z, z + 0.012, rug.get("material", "fabric_rug"))
+ fabric_object = fabric.finish(collections["fitted"], smooth=True)
+ return fabric_object
+
+
+def asset_path(plan, asset):
+ kind, name = asset.split(":", 1)
+ if kind == "ph":
+ root = house_core.LIBRARY / "models" / name
+ matches = sorted(root.glob("*.gltf"))
+ return matches[0] if matches else None
+ if kind == "obj":
+ library = plan.get("site", {}).get("objaverse_folder", "../_lib/objaverse")
+ return plan["_folder"] / library / f"{name}.glb"
+ raise KeyError(asset)
+
+
+_asset_cache = {}
+
+
+def bounding_box(objects):
+ corners = []
+ for item in objects:
+ if item.type != "MESH":
+ continue
+ for corner in item.bound_box:
+ corners.append(item.matrix_world @ Vector(corner))
+ if not corners:
+ return Vector((0, 0, 0)), Vector((0, 0, 0))
+ low = Vector((min(c.x for c in corners), min(c.y for c in corners), min(c.z for c in corners)))
+ high = Vector((max(c.x for c in corners), max(c.y for c in corners), max(c.z for c in corners)))
+ return low, high
+
+
+def keep_one_part(imported, part):
+ """Poly Haven plant sets lay their variants out in a row: keep one mesh, numbered from low x to high x."""
+ meshes = [item for item in imported if item.type == "MESH"]
+ meshes.sort(key=lambda item: bounding_box([item])[0].x)
+ chosen = meshes[part % len(meshes)]
+ world = chosen.matrix_world.copy()
+ chosen.parent = None
+ chosen.matrix_world = world
+ for item in imported:
+ if item is not chosen:
+ bpy.data.objects.remove(item)
+ bpy.context.view_layer.update()
+ return [chosen]
+
+
+def cache_file(asset, part):
+ return house_core.LIBRARY / "blender_cache" / f"{asset.replace(':', '_')}_{part}.blend"
+
+
+def write_asset_cache(path, cached):
+ """A glTF import takes minutes for a scanned tree; a linked .blend takes a moment and adds nothing to the house file."""
+ existing = set(bpy.data.objects)
+ started = time.perf_counter()
+ bpy.ops.import_scene.gltf(filepath=str(path))
+ imported = [item for item in bpy.data.objects if item not in existing]
+ bpy.context.view_layer.update()
+ print(f"imported {path.name}: {sum(1 for item in imported if item.type == 'MESH')} meshes, {time.perf_counter() - started:.1f} s", flush=True)
+ return imported
+
+
+def load_asset(plan, asset, library_collection, part=None):
+ cache_key = (asset, part)
+ if cache_key in _asset_cache:
+ return _asset_cache[cache_key]
+ path = asset_path(plan, asset)
+ if path is None or not path.exists():
+ print("MISSING ASSET", asset)
+ _asset_cache[cache_key] = None
+ return None
+ cached = cache_file(asset, part)
+ if not cached.exists():
+ imported = write_asset_cache(path, cached)
+ if part is not None:
+ imported = keep_one_part(imported, part)
+ cached.parent.mkdir(parents=True, exist_ok=True)
+ bpy.data.libraries.write(str(cached), set(imported), fake_user=True)
+ for item in imported:
+ bpy.data.objects.remove(item)
+ bpy.data.batch_remove([block for block in bpy.data.meshes if block.users == 0])
+ with bpy.data.libraries.load(str(cached), link=True) as (source, target):
+ target.objects = source.objects
+ linked = [item for item in target.objects if item is not None]
+ collection = bpy.data.collections.new(f"asset_{asset.replace(':', '_')}_{part}")
+ library_collection.children.link(collection)
+ for item in linked:
+ collection.objects.link(item)
+ # Linked objects keep stale world matrices until the depsgraph runs; without this, sizes come out wrong and beds float.
+ bpy.context.view_layer.update()
+ low, high = bounding_box(linked)
+ collection.instance_offset = ((low.x + high.x) / 2, (low.y + high.y) / 2, low.z)
+ _asset_cache[cache_key] = (collection, high - low)
+ return _asset_cache[cache_key]
+
+
+def overhead_height(plan, x, y):
+ """Lowest ceiling or roof underside above a point, for hanging a lamp from it."""
+ heights = []
+ for plane in plan.get("roof", {}).get("planes", []):
+ height = house_parts.RoofPlane(plane).height_at(x, y)
+ if height is not None:
+ heights.append(height)
+ for room in plan["rooms"]:
+ if room.get("ceiling") and house_parts.inside_polygon((x, y), room["poly"]):
+ heights.append(plan["levels"].get("floor", 0.0) + room["ceiling"])
+ return min(heights) if heights else plan["levels"].get("floor", 0.0) + plan["levels"].get("ceiling", 2.4)
+
+
+_painted_cache = {}
+
+
+def painted_copy(collection, material_name, library_collection):
+ """A model whose own materials are bad or missing, every part in one of ours. The linked data stays untouched."""
+ cache_key = (collection.name, material_name)
+ if cache_key in _painted_cache:
+ return _painted_cache[cache_key]
+ painted = bpy.data.collections.new(f"{collection.name}_{material_name}")
+ library_collection.children.link(painted)
+ material = house_core.get_material(material_name)
+ for source in collection.objects:
+ part = source.copy()
+ painted.objects.link(part)
+ for slot in part.material_slots:
+ slot.link = "OBJECT"
+ slot.material = material
+ painted.instance_offset = collection.instance_offset
+ _painted_cache[cache_key] = painted
+ return painted
+
+
+def place_asset(plan, item, library_collection, target_collection, report, on_ground=False):
+ loaded = load_asset(plan, item["asset"], library_collection, item.get("part"))
+ if loaded is None:
+ return None
+ collection, size = loaded
+ if "paint" in item:
+ collection = painted_copy(collection, item["paint"], library_collection)
+ scale = item.get("scale", 1.0)
+ if "fit_w" in item and max(size.x, size.y) > 0:
+ scale = item["fit_w"] / max(size.x, size.y)
+ if "fit_h" in item and size.z > 0:
+ scale = item["fit_h"] / size.z
+ if "fit_max" in item and max(size) > 0:
+ scale = item["fit_max"] / max(size)
+ scales = Vector((scale, scale, scale))
+ if "fit_size" in item:
+ scales = Vector((item["fit_size"][axis] / size[axis] for axis in range(3)))
+ instance = bpy.data.objects.new(item.get("name", collection.name), None)
+ instance.instance_type = "COLLECTION"
+ instance.instance_collection = collection
+ x, y = item["at"]
+ height = item.get("z", plan["levels"].get("floor", 0.0))
+ if on_ground:
+ height = site_ground_z(plan, x, y) + item.get("z", 0.0)
+ if item.get("hang"):
+ height = overhead_height(plan, x, y) - size.z * scales.z
+ instance.location = (x, y, height)
+ instance.rotation_euler = (0, 0, math.radians(item.get("rot", 0)))
+ instance.scale = scales
+ target_collection.objects.link(instance)
+ placed_size = Vector((size[axis] * scales[axis] for axis in range(3)))
+ report["placed"].append({"asset": item["asset"], "at": [round(x, 2), round(y, 2)], "z": round(height, 2), "size_m": [round(value, 2) for value in placed_size]})
+ return instance, placed_size
+
+
+def footprint_corners(item, size):
+ x, y = item["at"]
+ angle = math.radians(item.get("rot", 0))
+ cosine = math.cos(angle)
+ sine = math.sin(angle)
+ corners = []
+ for sign_x, sign_y in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
+ local_x = sign_x * size.x / 2
+ local_y = sign_y * size.y / 2
+ corners.append((x + local_x * cosine - local_y * sine, y + local_x * sine + local_y * cosine))
+ return corners
+
+
+def furniture_clashes(structure, item, size):
+ """Walls the footprint of a floor-standing piece runs through, ignoring anything under 8 cm of overlap."""
+ corners = footprint_corners(item, size)
+ clashes = []
+ for wall in structure.walls:
+ inside_points = 0
+ for corner in corners:
+ along = (Vector(corner) - wall.a).dot(wall.direction)
+ across = abs((Vector(corner) - wall.a).dot(wall.normal))
+ if wall.s0 <= along <= wall.s1 and across < wall.t / 2 - 0.08:
+ inside_points += 1
+ if inside_points:
+ clashes.append(wall.id)
+ return clashes
+
+
+def furnish(plan, structure, collections, report):
+ library_collection = collections["library"]
+ for item in plan.get("furnish", []):
+ placed = place_asset(plan, item, library_collection, collections["furnish"], report)
+ if placed is None:
+ report["missing"].append(item["asset"])
+ continue
+ _, size = placed
+ if item.get("z") is None or item.get("z", 0) < 0.05:
+ clashes = furniture_clashes(structure, item, size)
+ if clashes:
+ report["clashes"].append({"asset": item["asset"], "walls": clashes})
+ for item in plan.get("site", {}).get("plants", []):
+ placed = place_asset(plan, item, library_collection, collections["site"], report, on_ground=True)
+ if placed is None:
+ report["missing"].append(item["asset"])
+ for item in treeline_items(plan):
+ place_asset(plan, item, library_collection, collections["site"], report, on_ground=True)
+
+
+def treeline_items(plan):
+ """A ring of trees far enough out to close the horizon; azimuths in `skip` stay open as views."""
+ line = plan.get("site", {}).get("treeline")
+ if not line:
+ return []
+ if isinstance(line, list):
+ return [item for ring in line for item in treeline_ring(plan, ring)]
+ return treeline_ring(plan, line)
+
+
+def treeline_ring(plan, line):
+ generator = random.Random(11 + int(line["radius"]))
+ centre = plan["site"].get("centre", [0, 0])
+ low_height, high_height = line.get("heights", [10.0, 20.0])
+ items = []
+ for index in range(line.get("count", 60)):
+ azimuth = 360.0 * (index + generator.uniform(-0.3, 0.3)) / line.get("count", 60)
+ if any(start <= azimuth % 360 <= end for start, end in line.get("skip", [])):
+ continue
+ reach = line["radius"] * generator.uniform(0.9, 1.45)
+ items.append({
+ "asset": generator.choice(line["assets"]),
+ "at": [centre[0] + reach * math.cos(math.radians(azimuth)), centre[1] + reach * math.sin(math.radians(azimuth))],
+ "rot": generator.uniform(0, 360),
+ "fit_h": generator.uniform(low_height, high_height),
+ })
+ return items
+
+
+def ground_height(x, y, keep_flat_polygon_centre, flat_radius):
+ distance_from_house = math.hypot(x - keep_flat_polygon_centre[0], y - keep_flat_polygon_centre[1])
+ fade = min(1.0, max(0.0, (distance_from_house - flat_radius) / 30.0))
+ rolling = noise.noise(Vector((x * 0.035, y * 0.035, 3.1))) * 1.6
+ lumps = noise.noise(Vector((x * 0.6, y * 0.6, 9.4))) * 0.035
+ return rolling * fade + lumps
+
+
+def site_ground_z(plan, x, y):
+ site = plan.get("site", {})
+ level = site.get("ground_level", -0.03)
+ return level + ground_height(x, y, site.get("centre", [0, 0]), site.get("flat_radius", 14.0))
+
+
+def build_path(path, plan, batch):
+ """A four-cornered path follows the ground in short strips, with slightly uneven edges."""
+ corners = [Vector((point[0], point[1])) for point in path["poly"]]
+ length = max((corners[1] - corners[2]).length, (corners[0] - corners[3]).length)
+ strips = max(2, int(length / 0.5))
+ material = path.get("material", "gravel_path")
+ rows = []
+ for strip in range(strips + 1):
+ fraction = strip / strips
+ left = corners[0].lerp(corners[3], fraction)
+ right = corners[1].lerp(corners[2], fraction)
+ wobble_left = noise.noise(Vector((left.x * 1.3, left.y * 1.3, 4.0))) * 0.08
+ wobble_right = noise.noise(Vector((right.x * 1.3, right.y * 1.3, 7.0))) * 0.08
+ across = (right - left).normalized()
+ left = left + across * wobble_left
+ right = right + across * wobble_right
+ rows.append([Vector((point.x, point.y, site_ground_z(plan, point.x, point.y) + path.get("rise", 0.035))) for point in (left, right)])
+ for strip in range(strips):
+ quad = [rows[strip][0], rows[strip][1], rows[strip + 1][1], rows[strip + 1][0]]
+ batch.add_face(quad, material, uvs=[(point.x, point.y) for point in quad])
+
+
+def matte_ground(ground):
+ """Soil has no sheen. A scanned roughness map left in place mirrors the sky at grazing angles as white patches."""
+ for material in ground.data.materials:
+ surface = next((node for node in material.node_tree.nodes if node.type == "BSDF_PRINCIPLED"), None)
+ if surface is None:
+ continue
+ for link in list(surface.inputs["Roughness"].links):
+ material.node_tree.links.remove(link)
+ surface.inputs["Roughness"].default_value = 0.95
+ surface.inputs["Specular IOR Level"].default_value = 0.15
+
+
+def build_ground(plan, collection):
+ site = plan.get("site", {})
+ size = site.get("ground_size", 180.0)
+ centre = site.get("centre", [0, 0])
+ resolution = 260
+ batch = MeshBatch("ground", 61)
+ material = site.get("ground", "grass_ground")
+ grid = []
+ start = len(batch.vertices)
+ for row in range(resolution + 1):
+ for column in range(resolution + 1):
+ x = centre[0] - size / 2 + size * column / resolution
+ y = centre[1] - size / 2 + size * row / resolution
+ batch.vertices.append(Vector((x, y, site_ground_z(plan, x, y))))
+ grid.append((x, y))
+ for row in range(resolution):
+ for column in range(resolution):
+ first = start + row * (resolution + 1) + column
+ indices = [first, first + 1, first + resolution + 2, first + resolution + 1]
+ uvs = [grid[index - start] for index in indices]
+ batch.add_face([batch.vertices[index] for index in indices], material, uvs=uvs, indices=indices)
+ ground = batch.finish(collection, smooth=True)
+ matte_ground(ground)
+
+ paths = MeshBatch("paths", 62)
+ for path in site.get("paths", []):
+ build_path(path, plan, paths)
+ paths.finish(collection)
+ return ground
+
+
+def make_grass_material():
+ """Blades get their colour per tuft plus a slow patchy drift, and let some light through."""
+ material = bpy.data.materials.new("grass_blade")
+ material.use_nodes = True
+ tree = material.node_tree
+ tree.nodes.clear()
+ output = tree.nodes.new("ShaderNodeOutputMaterial")
+ info = tree.nodes.new("ShaderNodeObjectInfo")
+ ramp = tree.nodes.new("ShaderNodeValToRGB")
+ stops = ramp.color_ramp.elements
+ stops[0].position = 0.0
+ stops[0].color = (0.045, 0.075, 0.022, 1)
+ stops[1].position = 1.0
+ stops[1].color = (0.19, 0.16, 0.06, 1)
+ middle = stops.new(0.55)
+ middle.color = (0.085, 0.115, 0.035, 1)
+ geometry = tree.nodes.new("ShaderNodeNewGeometry")
+ patches = tree.nodes.new("ShaderNodeTexNoise")
+ patches.inputs["Scale"].default_value = 0.22
+ patches.inputs["Detail"].default_value = 3.0
+ blend = tree.nodes.new("ShaderNodeMath")
+ blend.operation = "MULTIPLY_ADD"
+ blend.inputs[1].default_value = 0.45
+ tree.links.new(geometry.outputs["Position"], patches.inputs["Vector"])
+ tree.links.new(info.outputs["Random"], blend.inputs[0])
+ tree.links.new(patches.outputs["Fac"], blend.inputs[2])
+ tree.links.new(blend.outputs[0], ramp.inputs["Fac"])
+ surface = tree.nodes.new("ShaderNodeBsdfPrincipled")
+ surface.inputs["Roughness"].default_value = 0.5
+ surface.inputs["Specular IOR Level"].default_value = 0.35
+ through = tree.nodes.new("ShaderNodeBsdfTranslucent")
+ mix = tree.nodes.new("ShaderNodeMixShader")
+ mix.inputs[0].default_value = 0.3
+ tree.links.new(ramp.outputs["Color"], surface.inputs["Base Color"])
+ tree.links.new(ramp.outputs["Color"], through.inputs["Color"])
+ tree.links.new(surface.outputs[0], mix.inputs[1])
+ tree.links.new(through.outputs[0], mix.inputs[2])
+ tree.links.new(mix.outputs[0], output.inputs["Surface"])
+ return material
+
+
+def make_grass_tuft(name, seed, material, collection):
+ """One tuft of curved tapered blades about 10 cm tall; the tuft is repeated, never the single blade."""
+ generator = random.Random(seed)
+ vertices = []
+ faces = []
+ for _ in range(26):
+ base_angle = generator.uniform(0, 2 * math.pi)
+ base_reach = generator.uniform(0.0, 0.075)
+ root = Vector((math.cos(base_angle) * base_reach, math.sin(base_angle) * base_reach, 0.0))
+ bend_angle = generator.uniform(0, 2 * math.pi)
+ bend = Vector((math.cos(bend_angle), math.sin(bend_angle), 0.0))
+ side = Vector((-bend.y, bend.x, 0.0))
+ height = generator.uniform(0.06, 0.15)
+ lean = generator.uniform(0.2, 0.7) * height
+ half_width = generator.uniform(0.0022, 0.0042)
+ first = len(vertices)
+ segments = 4
+ for segment in range(segments + 1):
+ fraction = segment / segments
+ centre = root + Vector((0, 0, height * fraction)) + bend * (lean * fraction * fraction)
+ width = half_width * (1.0 - fraction ** 2.2)
+ vertices.append(centre + side * width)
+ vertices.append(centre - side * width)
+ for segment in range(segments):
+ low = first + segment * 2
+ faces.append((low, low + 1, low + 3, low + 2))
+ mesh = bpy.data.meshes.new(name)
+ mesh.from_pydata([tuple(vertex) for vertex in vertices], [], faces)
+ mesh.polygons.foreach_set("use_smooth", [True] * len(faces))
+ mesh.materials.append(material)
+ tuft = bpy.data.objects.new(name, mesh)
+ collection.objects.link(tuft)
+ return tuft
+
+
+GRASS_GRID_METRES = 4.0
+
+
+def polygon_grid(polygons):
+ """Polygons by the grid cells their bounds touch: testing a whole street's outlines per tuft took 20 minutes."""
+ grid = {}
+ for polygon in polygons:
+ xs = [point[0] for point in polygon]
+ ys = [point[1] for point in polygon]
+ for column in range(int(min(xs) // GRASS_GRID_METRES), int(max(xs) // GRASS_GRID_METRES) + 1):
+ for row in range(int(min(ys) // GRASS_GRID_METRES), int(max(ys) // GRASS_GRID_METRES) + 1):
+ grid.setdefault((column, row), []).append(polygon)
+ return grid
+
+
+def scatter_grass(plan, collection, library_collection):
+ site = plan.get("site", {})
+ radius = site.get("grass_radius", 0.0)
+ if radius <= 0:
+ return
+ prototypes = bpy.data.collections.new("grass_prototypes")
+ library_collection.children.link(prototypes)
+ grass_material = make_grass_material()
+ for seed in range(4):
+ make_grass_tuft(f"tuft_{seed}", seed, grass_material, prototypes)
+ exclusions = [room["poly"] for room in plan["rooms"]]
+ exclusions += [slab["poly"] for slab in plan.get("slabs", [])]
+ exclusions += [path["poly"] for path in site.get("paths", [])]
+ exclusions += site.get("no_grass", [])
+ keep_out = polygon_grid(exclusions)
+ centre = site.get("centre", [0, 0])
+ density = site.get("grass_density", 90.0)
+ full_density_reach = radius * 0.4
+ generator = random.Random(5)
+ wanted = int(math.pi * radius * radius * density)
+ points = []
+ rotations = []
+ scales = []
+ for _ in range(wanted):
+ reach = radius * math.sqrt(generator.random())
+ # Further out fewer tufts stand in for more grass, each one bigger.
+ spread = max(1.0, reach / full_density_reach)
+ if generator.random() > 1.0 / (spread * spread):
+ continue
+ angle = generator.random() * 2 * math.pi
+ x = centre[0] + reach * math.cos(angle)
+ y = centre[1] + reach * math.sin(angle)
+ cell = (int(x // GRASS_GRID_METRES), int(y // GRASS_GRID_METRES))
+ if any(house_parts.inside_polygon((x, y), polygon) for polygon in keep_out.get(cell, ())):
+ continue
+ points.append((x, y, site_ground_z(plan, x, y) - 0.005))
+ rotations.append((generator.uniform(-0.15, 0.15), generator.uniform(-0.15, 0.15), generator.random() * 6.283))
+ scale = generator.uniform(0.75, 1.3) * site.get("grass_scale", 1.0) * spread
+ scales.append((scale, scale, generator.uniform(0.85, 1.25) * site.get("grass_scale", 1.0) * math.sqrt(spread)))
+ mesh = bpy.data.meshes.new("grass_points")
+ mesh.from_pydata(points, [], [])
+ rotation_attribute = mesh.attributes.new("grass_rotation", "FLOAT_VECTOR", "POINT")
+ scale_attribute = mesh.attributes.new("grass_scale", "FLOAT_VECTOR", "POINT")
+ for index in range(len(points)):
+ rotation_attribute.data[index].vector = rotations[index]
+ scale_attribute.data[index].vector = scales[index]
+ carrier = bpy.data.objects.new("grass", mesh)
+ collection.objects.link(carrier)
+ tree = bpy.data.node_groups.new("grass_scatter", "GeometryNodeTree")
+ tree.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")
+ tree.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")
+ group_in = tree.nodes.new("NodeGroupInput")
+ group_out = tree.nodes.new("NodeGroupOutput")
+ on_points = tree.nodes.new("GeometryNodeInstanceOnPoints")
+ on_points.inputs["Pick Instance"].default_value = True
+ info = tree.nodes.new("GeometryNodeCollectionInfo")
+ info.inputs["Collection"].default_value = prototypes
+ info.inputs["Separate Children"].default_value = True
+ info.inputs["Reset Children"].default_value = True
+ random_index = tree.nodes.new("FunctionNodeRandomValue")
+ random_index.data_type = "INT"
+ random_index.inputs["Min"].default_value = 0
+ random_index.inputs["Max"].default_value = 100
+ rotation = tree.nodes.new("GeometryNodeInputNamedAttribute")
+ rotation.data_type = "FLOAT_VECTOR"
+ rotation.inputs["Name"].default_value = "grass_rotation"
+ scale_node = tree.nodes.new("GeometryNodeInputNamedAttribute")
+ scale_node.data_type = "FLOAT_VECTOR"
+ scale_node.inputs["Name"].default_value = "grass_scale"
+ tree.links.new(group_in.outputs[0], on_points.inputs["Points"])
+ tree.links.new(info.outputs[0], on_points.inputs["Instance"])
+ tree.links.new(random_index.outputs[0], on_points.inputs["Instance Index"])
+ tree.links.new(rotation.outputs["Attribute"], on_points.inputs["Rotation"])
+ tree.links.new(scale_node.outputs["Attribute"], on_points.inputs["Scale"])
+ tree.links.new(on_points.outputs[0], group_out.inputs[0])
+ modifier = carrier.modifiers.new("scatter", "NODES")
+ modifier.node_group = tree
+ print(f"grass: {len(points)} tufts")
+
+
+def write_section(plan, collections, output_path):
+ segments = {}
+ bpy.context.view_layer.update()
+ base_by_object = {f"wall_{wall['id']}": wall.get("z0", plan["levels"].get("floor", 0.0)) for wall in plan["walls"]}
+ for item in collections["walls"].objects:
+ found = section_segments(item, base_by_object.get(item.name, 0.0) + SECTION_HEIGHT_METRES)
+ if found:
+ segments[item.name] = found
+ output_path.write_text(json.dumps({"height": SECTION_HEIGHT_METRES, "segments": segments}), encoding="utf-8")
+ print("wrote", output_path)
+
+
+def main():
+ arguments = sys.argv[sys.argv.index("--") + 1:]
+ plan = load_plan(arguments[0])
+ output = pathlib.Path(arguments[1]).resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ collections = {name: new_collection(name) for name in ("walls", "floors", "ceilings", "facade", "roof", "frame", "fitted", "furnish", "site", "library")}
+ structure = house_parts.Structure(plan)
+ clock = time.perf_counter()
+
+ def phase_done(name):
+ nonlocal clock
+ print(f"phase {name}: {time.perf_counter() - clock:.1f} s", flush=True)
+ clock = time.perf_counter()
+
+ build_floors(plan, collections["floors"])
+ build_ceilings(plan, collections["ceilings"])
+ build_structure(plan, structure, collections)
+ phase_done("structure")
+ report = {"placed": [], "clashes": [], "missing": []}
+ furnish(plan, structure, collections, report)
+ phase_done("furnish")
+ build_ground(plan, collections["site"])
+ phase_done("ground")
+ scatter_grass(plan, collections["site"], collections["library"])
+ phase_done("grass")
+ layer_collection = bpy.context.view_layer.layer_collection.children["library"]
+ layer_collection.exclude = True
+ write_section(plan, collections, output.with_name(output.stem + "_section.json"))
+ output.with_name(output.stem + "_build_report.json").write_text(json.dumps(report, indent=1), encoding="utf-8")
+ for clash in report["clashes"]:
+ print("CLASH", clash)
+ for missing in report["missing"]:
+ print("MISSING", missing)
+ bpy.ops.wm.save_as_mainfile(filepath=str(output))
+ phase_done("save")
+ print("saved", output)
+
+
+
+# build_street.py imports this module; every other way in is a build.
+if __name__ != "build_house":
+ main()
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/build_street.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/build_street.py
new file mode 100644
index 0000000..3369155
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/build_street.py
@@ -0,0 +1,152 @@
+"""Set finished houses along a street: one appended copy per house type, instanced per lot, each with its own paint.
+
+Run: blender -b --factory-startup -P build_street.py -- <street.json> <output.blend>
+The street format is in ../references/plan-format.md, section "Streets".
+"""
+
+import json
+import math
+import pathlib
+import sys
+
+import bpy
+from mathutils import Matrix, Vector
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
+
+import build_house # noqa: E402
+import house_core # noqa: E402
+from house_core import MeshBatch # noqa: E402
+
+HOUSE_COLLECTIONS = ("walls", "floors", "ceilings", "facade", "roof", "frame", "fitted", "furnish")
+# Paint per lot comes from Object Info > Random, which differs per collection instance.
+DEFAULT_PAINTS = {
+ "siding_white": [(0.0, (1.0, 1.0, 1.0)), (0.45, (1.0, 0.95, 0.82)), (0.62, (0.82, 0.90, 0.88)), (0.78, (0.98, 0.86, 0.72)), (0.9, (0.78, 0.82, 0.92))],
+ "shingle_asphalt": [(0.0, (1.0, 1.0, 1.0)), (0.35, (0.72, 0.68, 0.64)), (0.7, (1.25, 1.2, 1.15))],
+}
+
+
+def append_house(blend_path, name, library):
+ """One copy of a built house in a collection whose origin is the plan's origin."""
+ with bpy.data.libraries.load(str(blend_path), link=False) as (source, target):
+ target.collections = [item for item in source.collections if item in HOUSE_COLLECTIONS]
+ house = bpy.data.collections.new(f"house_{name}")
+ library.children.link(house)
+ for collection in target.collections:
+ if collection is not None:
+ house.children.link(collection)
+ return house
+
+
+def add_paint_variation(material_name, stops):
+ """Multiply a material's base colour by a colour picked per lot."""
+ material = bpy.data.materials.get(material_name)
+ if material is None or not material.use_nodes:
+ return
+ tree = material.node_tree
+ surface = next((node for node in tree.nodes if node.type == "BSDF_PRINCIPLED"), None)
+ if surface is None:
+ return
+ base_input = surface.inputs["Base Color"]
+ if not base_input.links:
+ return
+ source_socket = base_input.links[0].from_socket
+ info = tree.nodes.new("ShaderNodeObjectInfo")
+ ramp = tree.nodes.new("ShaderNodeValToRGB")
+ ramp.color_ramp.interpolation = "CONSTANT"
+ elements = ramp.color_ramp.elements
+ elements[0].position = stops[0][0]
+ elements[0].color = (*stops[0][1], 1)
+ elements[1].position = stops[1][0]
+ elements[1].color = (*stops[1][1], 1)
+ for position, colour in stops[2:]:
+ extra = elements.new(position)
+ extra.color = (*colour, 1)
+ multiply = tree.nodes.new("ShaderNodeMix")
+ multiply.data_type = "RGBA"
+ multiply.blend_type = "MULTIPLY"
+ multiply.inputs[0].default_value = 1.0
+ tree.links.new(info.outputs["Random"], ramp.inputs["Fac"])
+ tree.links.new(source_socket, multiply.inputs[6])
+ tree.links.new(ramp.outputs["Color"], multiply.inputs[7])
+ tree.links.new(multiply.outputs[2], base_input)
+
+
+def place_house(house, name, lot, scale, target):
+ instance = bpy.data.objects.new(name, None)
+ instance.instance_type = "COLLECTION"
+ instance.instance_collection = house
+ instance.location = (lot["at"][0] * scale, lot["at"][1] * scale, 0.0)
+ instance.rotation_euler = (0, 0, math.radians(lot.get("rot", 0)))
+ target.objects.link(instance)
+ return instance
+
+
+def lot_footprints(plan_slabs, lot):
+ """Slab outlines of one lot in street metres, for keeping grass out."""
+ angle = math.radians(lot.get("rot", 0))
+ rotation = Matrix.Rotation(angle, 2)
+ origin = Vector(lot["at"])
+ outlines = []
+ for slab in plan_slabs:
+ outlines.append([list(origin + rotation @ Vector(point)) for point in slab["poly"]])
+ return outlines
+
+
+def build_strips(street, collection):
+ """Road, pavements and drives: flat polygons just above the ground."""
+ batch = MeshBatch("street_surfaces", 71)
+ for surface in street.get("surfaces", []):
+ height = surface.get("z", 0.0)
+ points = [Vector((point[0], point[1], height)) for point in surface["poly"]]
+ batch.add_face(points, surface["material"], uvs=[(point[0], point[1]) for point in surface["poly"]])
+ batch.finish(collection)
+
+
+def main():
+ arguments = sys.argv[sys.argv.index("--") + 1:]
+ street_path = pathlib.Path(arguments[0]).resolve()
+ output = pathlib.Path(arguments[1]).resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ raw = json.loads(street_path.read_text(encoding="utf-8"))
+ scale = build_house.METRES_PER_UNIT[raw.get("units", "ft")]
+ street = build_house.convert_lengths(raw, scale)
+ street["levels"] = {"floor": 0.0, "ceiling": 2.4}
+ street["_folder"] = street_path.parent
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ library = build_house.new_collection("library")
+ site = build_house.new_collection("site")
+ lots = build_house.new_collection("lots")
+ keep_out = []
+ for type_name, house_type in raw["house_types"].items():
+ blend_path = (street_path.parent / house_type["blend"]).resolve()
+ plan_path = (street_path.parent / house_type["plan"]).resolve()
+ house_plan = build_house.load_plan(plan_path)
+ house = append_house(blend_path, type_name, library)
+ for index, lot in enumerate(raw["lots"]):
+ if lot["type"] != type_name:
+ continue
+ place_house(house, f"lot_{type_name}_{index}", lot, scale, lots)
+ metric_lot = {"at": [lot["at"][0] * scale, lot["at"][1] * scale], "rot": lot.get("rot", 0)}
+ keep_out += lot_footprints(house_plan.get("slabs", []), metric_lot)
+ for material_name, stops in raw.get("paints", DEFAULT_PAINTS).items():
+ add_paint_variation(material_name, stops)
+ street.setdefault("rooms", [])
+ street["slabs"] = [{"poly": outline} for outline in keep_out]
+ street["site"].setdefault("paths", [])
+ street["site"]["no_grass"] = street["site"].get("no_grass", []) + [surface["poly"] for surface in street.get("surfaces", [])]
+ report = {"placed": [], "clashes": [], "missing": []}
+ for item in street["site"].get("plants", []) + build_house.treeline_items(street):
+ build_house.place_asset(street, item, library, site, report, on_ground=True)
+ build_strips(street, site)
+ build_house.build_ground(street, site)
+ build_house.scatter_grass(street, site, library)
+ bpy.context.view_layer.layer_collection.children["library"].exclude = True
+ for missing in report["missing"]:
+ print("MISSING", missing)
+ bpy.ops.wm.save_as_mainfile(filepath=str(output))
+ print("saved", output, "lots", len(raw["lots"]))
+
+
+if __name__ != "build_street":
+ main()
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fetch_assets.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fetch_assets.py
new file mode 100644
index 0000000..5fae168
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fetch_assets.py
@@ -0,0 +1,129 @@
+"""Download what a plan needs from Poly Haven and ambientCG (both CC0) into the asset library.
+
+Run: uv run --no-project python fetch_assets.py plan.json
+The library is HOUSE_ASSET_LIBRARY, or the default named in house_core.py. Objaverse models (`obj:`) use fetch_objaverse.py.
+"""
+
+import ast
+import io
+import json
+import os
+import pathlib
+import sys
+import urllib.error
+import urllib.request
+import zipfile
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+SCRIPTS = pathlib.Path(__file__).resolve().parent
+HEADERS = {"User-Agent": "house-from-plan-fetch/1.0"}
+TEXTURE_MAPS = {"Diffuse": "diff", "nor_gl": "nor_gl", "Rough": "rough", "Displacement": "disp", "AO": "ao"}
+DEFAULT_HDRI = "kloofendal_48d_partly_cloudy_puresky"
+
+
+def library_folder():
+ source = (SCRIPTS / "house_core.py").read_text(encoding="utf-8")
+ for line in source.splitlines():
+ if line.startswith("LIBRARY = "):
+ default_library = line
+ break
+ configured = os.environ.get("HOUSE_ASSET_LIBRARY")
+ if configured:
+ return pathlib.Path(configured)
+ namespace = {"pathlib": pathlib, "os": os}
+ exec(default_library, namespace)
+ return namespace["LIBRARY"]
+
+
+def texture_folders():
+ tree = ast.parse((SCRIPTS / "house_core.py").read_text(encoding="utf-8"))
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and node.targets[0].id == "TEXTURED_MATERIALS":
+ table = ast.literal_eval(node.value)
+ return sorted({entry[0] for entry in table.values()})
+ raise SystemExit("TEXTURED_MATERIALS not found")
+
+
+def fetch_bytes(url):
+ request = urllib.request.Request(url, headers=HEADERS)
+ with urllib.request.urlopen(request, timeout=180) as response:
+ return response.read()
+
+
+def fetch_json(url):
+ return json.loads(fetch_bytes(url))
+
+
+def save(url, target):
+ if target.exists():
+ return
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(fetch_bytes(url))
+
+
+def fetch_texture_ambientcg(name, folder):
+ data = fetch_bytes(f"https://ambientcg.com/get?file={name}_2K-JPG.zip")
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ archive.extractall(folder)
+
+
+def fetch_texture(name, library):
+ folder = library / "textures" / name
+ if folder.exists() and any(folder.iterdir()):
+ return
+ folder.mkdir(parents=True, exist_ok=True)
+ try:
+ files = fetch_json(f"https://api.polyhaven.com/files/{name}")
+ except urllib.error.HTTPError:
+ fetch_texture_ambientcg(name, folder)
+ print("ambientCG", name)
+ return
+ for key, short in TEXTURE_MAPS.items():
+ entry = files.get(key)
+ if entry:
+ save(entry["2k"]["jpg"]["url"], folder / f"{name}_{short}_2k.jpg")
+ print("Poly Haven texture", name)
+
+
+def fetch_model(name, library):
+ folder = library / "models" / name
+ if list(folder.glob("*.gltf")):
+ return
+ gltf = fetch_json(f"https://api.polyhaven.com/files/{name}")["gltf"]["2k"]["gltf"]
+ save(gltf["url"], folder / f"{name}_2k.gltf")
+ for relative, entry in gltf["include"].items():
+ save(entry["url"], folder / relative)
+ print("Poly Haven model", name)
+
+
+def fetch_hdri(name, library):
+ target = library / "hdri" / f"{name}_2k.hdr"
+ if target.exists():
+ return
+ save(fetch_json(f"https://api.polyhaven.com/files/{name}")["hdri"]["2k"]["hdr"]["url"], target)
+ print("Poly Haven HDRI", name)
+
+
+def plan_models(plan):
+ site = plan.get("site", {})
+ items = plan.get("furnish", []) + site.get("plants", [])
+ names = {item["asset"].split(":", 1)[1] for item in items if item["asset"].startswith("ph:")}
+ for asset in site.get("treeline", {}).get("assets", []):
+ if asset.startswith("ph:"):
+ names.add(asset.split(":", 1)[1])
+ return sorted(names)
+
+
+def main():
+ plan = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
+ library = library_folder()
+ for name in texture_folders():
+ fetch_texture(name, library)
+ for name in plan_models(plan):
+ fetch_model(name, library)
+ fetch_hdri(plan.get("site", {}).get("hdri", DEFAULT_HDRI), library)
+ print("library ready:", library)
+
+
+main()
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fetch_objaverse.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fetch_objaverse.py
new file mode 100644
index 0000000..250cbb9
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fetch_objaverse.py
@@ -0,0 +1,30 @@
+"""Download Objaverse 1.0 objects by uid into <folder>/<uid>.glb (Hugging Face mirror, no login).
+
+Run: uv run --no-project python fetch_objaverse.py <folder> <uid> [<uid> ...]
+"""
+
+import gzip
+import json
+import os
+import sys
+import urllib.request
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+REPOSITORY_URL = "https://huggingface.co/datasets/allenai/objaverse/resolve/main/"
+
+
+def main():
+ folder = sys.argv[1]
+ uids = sys.argv[2:]
+ os.makedirs(folder, exist_ok=True)
+ with urllib.request.urlopen(REPOSITORY_URL + "object-paths.json.gz", timeout=300) as response:
+ object_paths = json.loads(gzip.decompress(response.read()))
+ for uid in uids:
+ relative_path = object_paths[uid]
+ target_path = os.path.join(folder, uid + ".glb")
+ urllib.request.urlretrieve(REPOSITORY_URL + relative_path, target_path)
+ print(uid, relative_path, os.path.getsize(target_path))
+
+
+main()
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/find_objaverse.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/find_objaverse.py
new file mode 100644
index 0000000..44123c4
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/find_objaverse.py
@@ -0,0 +1,72 @@
+"""Search Objaverse 1.0 metadata (Sketchfab models with their licenses, mirrored on Hugging Face, no login)
+for objects whose name, tags or description match a pattern. Shards are streamed and not kept on disk.
+
+Run: uv run --no-project python find_objaverse.py "godzilla|gojira|kaiju" results.json
+"""
+
+import gzip
+import json
+import re
+import sys
+import time
+import urllib.request
+from concurrent.futures import ThreadPoolExecutor
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+BASE_URL = "https://huggingface.co/datasets/allenai/objaverse/resolve/main/metadata/000-{:03d}.json.gz"
+SHARD_COUNT = 160
+DOWNLOAD_ATTEMPTS = 4
+
+
+def download_shard(shard_index):
+ for attempt in range(1, DOWNLOAD_ATTEMPTS + 1):
+ try:
+ with urllib.request.urlopen(BASE_URL.format(shard_index), timeout=120) as response:
+ return json.loads(gzip.decompress(response.read()))
+ except OSError:
+ if attempt == DOWNLOAD_ATTEMPTS:
+ raise
+ time.sleep(attempt * 3)
+
+
+def search_shard(shard_index, pattern):
+ records = download_shard(shard_index)
+ matches = []
+ for uid, record in records.items():
+ tags = " ".join(tag.get("name", "") for tag in record.get("tags", []))
+ text = " ".join([record.get("name", ""), tags, record.get("description", "") or ""])
+ if not pattern.search(text):
+ continue
+ matches.append({
+ "uid": uid,
+ "shard": shard_index,
+ "name": record.get("name"),
+ "author": (record.get("user") or {}).get("username"),
+ "license": record.get("license"),
+ "faces": record.get("faceCount"),
+ "animations": record.get("animationCount"),
+ "likes": record.get("likeCount"),
+ "views": record.get("viewCount"),
+ "url": record.get("viewerUrl"),
+ "tags": tags,
+ })
+ return matches
+
+
+def main():
+ pattern = re.compile(sys.argv[1], re.IGNORECASE)
+ output_path = sys.argv[2]
+ found = []
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ for shard_matches in pool.map(lambda index: search_shard(index, pattern), range(SHARD_COUNT)):
+ found.extend(shard_matches)
+ found.sort(key=lambda match: match["likes"] or 0, reverse=True)
+ with open(output_path, "w", encoding="utf-8") as output_file:
+ json.dump(found, output_file, indent=1, ensure_ascii=False)
+ for match in found[:60]:
+ print(match["likes"], match["faces"], match["animations"], match["license"], match["name"], match["author"], match["url"])
+ print("TOTAL", len(found))
+
+
+main()
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/house_core.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/house_core.py
new file mode 100644
index 0000000..7dc5dc6
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/house_core.py
@@ -0,0 +1,484 @@
+"""Materials and mesh batching for build_house.py. Runs inside Blender."""
+
+import os
+import pathlib
+import random
+
+import bmesh
+import bpy
+from mathutils import Vector
+
+RESOLUTION_SUFFIX = "2k"
+LIBRARY = pathlib.Path(os.environ.get("HOUSE_ASSET_LIBRARY", pathlib.Path.home() / "house-assets"))
+
+# name: (Poly Haven or ambientCG folder, metres per tile, tint, desaturate, bump strength, roughness scale)
+TEXTURED_MATERIALS = {
+ "siding_white": ("distressed_painted_planks", 1.6, (0.92, 0.90, 0.85), 1.0, 0.25, 0.9),
+ "board_redwood": ("oak_wood_planks", 2.0, (0.62, 0.47, 0.35), 0.65, 0.6, 1.0),
+ "grass_path": ("grass_path_2", 3.0, (0.8, 0.76, 0.7), 0.0, 1.0, 1.0),
+ "shingle_wood": ("weathered_planks", 2.0, (0.62, 0.60, 0.56), 0.75, 0.8, 1.0),
+ "roll_roofing": ("roof_3", 2.0, (0.50, 0.50, 0.50), 0.5, 0.8, 1.0),
+ "oak_floor": ("plank_flooring_04", 2.0, (0.95, 0.88, 0.80), 0.0, 0.3, 0.75),
+ "old_floor": ("old_wood_floor", 2.5, (0.88, 0.78, 0.68), 0.0, 0.45, 0.85),
+ "concrete_floor": ("concrete_floor_painted", 2.0, (0.75, 0.74, 0.72), 0.3, 0.3, 0.8),
+ "wallboard": ("plastered_wall", 8.0, (0.86, 0.84, 0.78), 0.9, 0.01, 1.0),
+ "plaster_old": ("plastered_wall_03", 8.0, (0.83, 0.80, 0.72), 0.9, 0.03, 1.0),
+ "cabin_boards": ("raw_plank_wall", 2.0, (0.72, 0.62, 0.50), 0.4, 0.8, 1.0),
+ "pine_boards": ("raw_plank_wall", 2.0, (0.92, 0.72, 0.52), 0.1, 0.4, 0.85),
+ "dark_timber": ("dark_wooden_planks", 2.0, (0.55, 0.42, 0.32), 0.1, 0.5, 0.9),
+ "tile_white": ("square_tiles", 1.2, (0.92, 0.92, 0.90), 1.0, 0.5, 0.5),
+ "brick_painted": ("painted_worn_brick", 1.8, (0.88, 0.86, 0.82), 0.6, 0.8, 1.0),
+ "brick_red": ("red_brick", 2.0, (0.75, 0.70, 0.66), 0.1, 0.8, 1.0),
+ "brick_dark": ("red_brick", 2.0, (0.30, 0.25, 0.22), 0.3, 0.8, 1.0),
+ "shingle_asphalt": ("roof_3", 1.6, (0.34, 0.34, 0.35), 0.8, 0.8, 1.6),
+ "stucco_cream": ("painted_plaster_wall", 1.2, (0.88, 0.82, 0.70), 0.7, 0.9, 1.0),
+ "boards_painted": ("distressed_painted_planks", 1.6, (0.88, 0.86, 0.78), 1.0, 0.2, 0.9),
+ "stone_rubble": ("rustic_stone_wall_02", 2.0, (0.72, 0.70, 0.66), 0.3, 1.0, 1.0),
+ "grass_ground": ("Grass004", 2.5, (0.50, 0.52, 0.36), 0.0, 0.6, 1.0),
+ "road_asphalt": ("asphalt_02", 4.0, (0.62, 0.61, 0.6), 0.0, 1.0, 1.0),
+ "pavement_concrete": ("concrete_floor_worn_001", 3.0, (0.8, 0.78, 0.74), 0.0, 0.9, 1.0),
+ "gravel_path": ("gravel_ground_01", 2.0, (0.72, 0.68, 0.62), 0.0, 1.0, 1.0),
+ "fabric_linen": ("hessian_230", 0.1, (1.0, 0.97, 0.90), 0.9, 0.12, 1.0),
+ "fabric_rug": ("dirty_carpet", 1.0, (1.5, 1.15, 0.9), 0.2, 0.7, 1.0),
+}
+
+# name: (base colour, roughness, metallic)
+PLAIN_MATERIALS = {
+ "trim_white": ((0.78, 0.76, 0.71), 0.42, 0.0),
+ "curtain_plain": ((0.70, 0.66, 0.56), 0.92, 0.0),
+ "ceiling_paint": ((0.76, 0.74, 0.68), 0.75, 0.0),
+ "wall_paint": ((0.74, 0.71, 0.63), 0.62, 0.0),
+ "wall_paint_old": ((0.72, 0.67, 0.56), 0.7, 0.0),
+ "chair_green": ((0.035, 0.07, 0.05), 0.42, 0.0),
+ "trim_cream": ((0.70, 0.66, 0.56), 0.48, 0.0),
+ "shutter_black": ((0.012, 0.014, 0.015), 0.42, 0.0),
+ "door_green": ((0.03, 0.075, 0.055), 0.38, 0.0),
+ "cabinet_birch": ((0.56, 0.40, 0.24), 0.40, 0.0),
+ "counter_laminate": ((0.60, 0.58, 0.53), 0.30, 0.0),
+ "porcelain": ((0.80, 0.80, 0.78), 0.12, 0.0),
+ "chrome": ((0.78, 0.78, 0.78), 0.12, 1.0),
+ "brass": ((0.62, 0.44, 0.18), 0.32, 1.0),
+ "iron_black": ((0.02, 0.02, 0.02), 0.55, 0.9),
+ "aluminium_dull": ((0.48, 0.48, 0.47), 0.48, 1.0),
+ "wall_section": ((0.018, 0.018, 0.02), 0.8, 0.0),
+ "lamp_shade": ((0.75, 0.70, 0.58), 0.6, 0.0),
+ "bedding": ((0.62, 0.60, 0.55), 0.85, 0.0),
+ "towel": ((0.42, 0.50, 0.50), 0.95, 0.0),
+ "soot": ((0.008, 0.007, 0.007), 0.95, 0.0),
+ "putty": ((0.40, 0.38, 0.34), 0.7, 0.0),
+}
+
+
+def find_texture(folder, kinds):
+ """First file in a texture folder whose name carries one of the map kinds."""
+ root = LIBRARY / "textures" / folder
+ if not root.exists():
+ return None
+ candidates = [path for path in root.rglob("*") if path.suffix.lower() in (".jpg", ".png", ".exr")]
+ for kind in kinds:
+ for path in candidates:
+ if kind in path.stem.lower():
+ return path
+ return None
+
+
+def add_image_node(tree, path, colour):
+ node = tree.nodes.new("ShaderNodeTexImage")
+ node.image = bpy.data.images.load(str(path), check_existing=True)
+ node.image.colorspace_settings.name = "sRGB" if colour else "Non-Color"
+ return node
+
+
+def make_textured_material(name):
+ folder, tile_metres, tint, desaturate, bump_strength, roughness_scale = TEXTURED_MATERIALS[name]
+ material = bpy.data.materials.new(name)
+ material.use_nodes = True
+ tree = material.node_tree
+ shader = tree.nodes["Principled BSDF"]
+ coordinates = tree.nodes.new("ShaderNodeUVMap")
+ mapping = tree.nodes.new("ShaderNodeMapping")
+ mapping.inputs["Scale"].default_value = (1 / tile_metres, 1 / tile_metres, 1)
+ tree.links.new(coordinates.outputs["UV"], mapping.inputs["Vector"])
+
+ diffuse_path = find_texture(folder, ("_diff", "color"))
+ if diffuse_path is None:
+ print("MISSING TEXTURE", folder)
+ shader.inputs["Base Color"].default_value = (*tint, 1)
+ return material
+ diffuse = add_image_node(tree, diffuse_path, True)
+ tree.links.new(mapping.outputs["Vector"], diffuse.inputs["Vector"])
+
+ saturation = tree.nodes.new("ShaderNodeHueSaturation")
+ saturation.inputs["Saturation"].default_value = 1 - desaturate
+ tree.links.new(diffuse.outputs["Color"], saturation.inputs["Color"])
+
+ tint_node = tree.nodes.new("ShaderNodeMix")
+ tint_node.data_type = "RGBA"
+ tint_node.blend_type = "MULTIPLY"
+ tint_node.inputs["Factor"].default_value = 1.0
+ tint_node.inputs["B"].default_value = (*tint, 1)
+ tree.links.new(saturation.outputs["Color"], tint_node.inputs["A"])
+
+ # Large soft patches plus per-piece variation keep repeats from showing.
+ noise = tree.nodes.new("ShaderNodeTexNoise")
+ noise.inputs["Scale"].default_value = 0.9
+ noise.inputs["Detail"].default_value = 5
+ tree.links.new(coordinates.outputs["UV"], noise.inputs["Vector"])
+ ramp = tree.nodes.new("ShaderNodeMapRange")
+ ramp.inputs["From Min"].default_value = 0.3
+ ramp.inputs["From Max"].default_value = 0.7
+ ramp.inputs["To Min"].default_value = 0.86
+ ramp.inputs["To Max"].default_value = 1.08
+ tree.links.new(noise.outputs["Fac"], ramp.inputs["Value"])
+ patches = tree.nodes.new("ShaderNodeVectorMath")
+ patches.operation = "SCALE"
+ tree.links.new(tint_node.outputs["Result"], patches.inputs[0])
+ tree.links.new(ramp.outputs["Result"], patches.inputs["Scale"])
+
+ variation = tree.nodes.new("ShaderNodeVertexColor")
+ variation.layer_name = "variation"
+ piece = tree.nodes.new("ShaderNodeVectorMath")
+ piece.operation = "MULTIPLY"
+ tree.links.new(patches.outputs["Vector"], piece.inputs[0])
+ tree.links.new(variation.outputs["Color"], piece.inputs[1])
+ tree.links.new(piece.outputs["Vector"], shader.inputs["Base Color"])
+
+ rough_path = find_texture(folder, ("_rough", "roughness"))
+ arm_path = find_texture(folder, ("_arm",))
+ roughness_scale_node = tree.nodes.new("ShaderNodeMath")
+ roughness_scale_node.operation = "MULTIPLY"
+ roughness_scale_node.inputs[1].default_value = roughness_scale
+ if rough_path is not None:
+ rough = add_image_node(tree, rough_path, False)
+ tree.links.new(mapping.outputs["Vector"], rough.inputs["Vector"])
+ tree.links.new(rough.outputs["Color"], roughness_scale_node.inputs[0])
+ tree.links.new(roughness_scale_node.outputs["Value"], shader.inputs["Roughness"])
+ elif arm_path is not None:
+ arm = add_image_node(tree, arm_path, False)
+ tree.links.new(mapping.outputs["Vector"], arm.inputs["Vector"])
+ split = tree.nodes.new("ShaderNodeSeparateColor")
+ tree.links.new(arm.outputs["Color"], split.inputs["Color"])
+ tree.links.new(split.outputs["Green"], roughness_scale_node.inputs[0])
+ tree.links.new(roughness_scale_node.outputs["Value"], shader.inputs["Roughness"])
+
+ normal_path = find_texture(folder, ("_nor_gl", "normalgl", "_nor"))
+ if normal_path is not None:
+ normal_image = add_image_node(tree, normal_path, False)
+ tree.links.new(mapping.outputs["Vector"], normal_image.inputs["Vector"])
+ normal_map = tree.nodes.new("ShaderNodeNormalMap")
+ normal_map.inputs["Strength"].default_value = bump_strength
+ tree.links.new(normal_image.outputs["Color"], normal_map.inputs["Color"])
+ tree.links.new(normal_map.outputs["Normal"], shader.inputs["Normal"])
+ return material
+
+
+def make_plain_material(name):
+ colour, roughness, metallic = PLAIN_MATERIALS[name]
+ material = bpy.data.materials.new(name)
+ material.use_nodes = True
+ tree = material.node_tree
+ shader = tree.nodes["Principled BSDF"]
+ shader.inputs["Metallic"].default_value = metallic
+ coordinates = tree.nodes.new("ShaderNodeTexCoord")
+ # Scanned plaster reads as grey concrete from inside a room, so a painted wall is a colour that drifts a little.
+ tone = tree.nodes.new("ShaderNodeTexNoise")
+ tone.inputs["Scale"].default_value = 1.2
+ tone.inputs["Detail"].default_value = 4
+ tree.links.new(coordinates.outputs["Object"], tone.inputs["Vector"])
+ tone_range = tree.nodes.new("ShaderNodeMapRange")
+ tone_range.inputs["From Min"].default_value = 0.3
+ tone_range.inputs["From Max"].default_value = 0.7
+ tone_range.inputs["To Min"].default_value = 0.95
+ tone_range.inputs["To Max"].default_value = 1.03
+ tree.links.new(tone.outputs["Fac"], tone_range.inputs["Value"])
+ tinted = tree.nodes.new("ShaderNodeVectorMath")
+ tinted.operation = "SCALE"
+ tinted.inputs[0].default_value = colour
+ tree.links.new(tone_range.outputs["Result"], tinted.inputs["Scale"])
+ tree.links.new(tinted.outputs["Vector"], shader.inputs["Base Color"])
+ # Paint is never perfect: wide roughness drift and a fine orange peel.
+ drift = tree.nodes.new("ShaderNodeTexNoise")
+ drift.inputs["Scale"].default_value = 3.0
+ drift.inputs["Detail"].default_value = 6
+ tree.links.new(coordinates.outputs["Object"], drift.inputs["Vector"])
+ ramp = tree.nodes.new("ShaderNodeMapRange")
+ ramp.inputs["From Min"].default_value = 0.3
+ ramp.inputs["From Max"].default_value = 0.7
+ ramp.inputs["To Min"].default_value = roughness * 0.8
+ ramp.inputs["To Max"].default_value = min(1.0, roughness * 1.25)
+ tree.links.new(drift.outputs["Fac"], ramp.inputs["Value"])
+ tree.links.new(ramp.outputs["Result"], shader.inputs["Roughness"])
+ peel = tree.nodes.new("ShaderNodeTexNoise")
+ peel.inputs["Scale"].default_value = 500.0
+ peel.inputs["Detail"].default_value = 3
+ tree.links.new(coordinates.outputs["Object"], peel.inputs["Vector"])
+ bump = tree.nodes.new("ShaderNodeBump")
+ bump.inputs["Strength"].default_value = 0.03
+ bump.inputs["Distance"].default_value = 0.002
+ tree.links.new(peel.outputs["Fac"], bump.inputs["Height"])
+ tree.links.new(bump.outputs["Normal"], shader.inputs["Normal"])
+ return material
+
+
+def make_glass_material():
+ material = bpy.data.materials.new("glass")
+ material.use_nodes = True
+ tree = material.node_tree
+ output = tree.nodes["Material Output"]
+ shader = tree.nodes["Principled BSDF"]
+ shader.inputs["Base Color"].default_value = (0.96, 0.98, 0.97, 1)
+ shader.inputs["Roughness"].default_value = 0.0
+ shader.inputs["IOR"].default_value = 1.5
+ shader.inputs["Transmission Weight"].default_value = 1.0
+ # Only the camera sees real glass. With caustics off, a bounce that crosses refractive glass is dropped,
+ # which cost the rooms 10 times their daylight (measured on the cottage living room).
+ path = tree.nodes.new("ShaderNodeLightPath")
+ transparent = tree.nodes.new("ShaderNodeBsdfTransparent")
+ transparent.inputs["Color"].default_value = (0.92, 0.93, 0.92, 1)
+ mix = tree.nodes.new("ShaderNodeMixShader")
+ tree.links.new(path.outputs["Is Camera Ray"], mix.inputs["Fac"])
+ tree.links.new(transparent.outputs["BSDF"], mix.inputs[1])
+ tree.links.new(shader.outputs["BSDF"], mix.inputs[2])
+ tree.links.new(mix.outputs["Shader"], output.inputs["Surface"])
+ return material
+
+
+def make_lamp_material(strength):
+ material = bpy.data.materials.new(f"lamp_{strength}")
+ material.use_nodes = True
+ tree = material.node_tree
+ shader = tree.nodes["Principled BSDF"]
+ shader.inputs["Emission Color"].default_value = (1.0, 0.78, 0.55, 1)
+ shader.inputs["Emission Strength"].default_value = strength
+ return material
+
+
+_material_cache = {}
+
+
+def get_material(name):
+ if name in _material_cache:
+ return _material_cache[name]
+ if name in TEXTURED_MATERIALS:
+ material = make_textured_material(name)
+ elif name in PLAIN_MATERIALS:
+ material = make_plain_material(name)
+ elif name == "glass":
+ material = make_glass_material()
+ elif name.startswith("lamp_"):
+ material = make_lamp_material(float(name.split("_")[1]))
+ else:
+ raise KeyError(f"unknown material {name}")
+ _material_cache[name] = material
+ return material
+
+
+class MeshBatch:
+ """Collects quads and boxes per material and turns them into one Blender object."""
+
+ def __init__(self, name, seed=1):
+ self.name = name
+ self.vertices = []
+ self.faces = []
+ self.face_uvs = []
+ self.face_materials = []
+ self.face_variation = []
+ self.material_names = []
+ self.random = random.Random(seed)
+ self.uv_offset = (0.0, 0.0)
+ self.variation = 1.0
+
+ def material_index(self, material_name):
+ if material_name not in self.material_names:
+ self.material_names.append(material_name)
+ return self.material_names.index(material_name)
+
+ def add_face(self, points, material_name, uvs=None, indices=None):
+ if indices is None:
+ start = len(self.vertices)
+ self.vertices.extend(Vector(point) for point in points)
+ indices = list(range(start, start + len(points)))
+ if uvs is None:
+ uvs = world_uvs(points)
+ self.faces.append(indices)
+ self.face_uvs.append([(uv[0] + self.uv_offset[0], uv[1] + self.uv_offset[1]) for uv in uvs])
+ self.face_materials.append(self.material_index(material_name))
+ self.face_variation.append(self.variation)
+
+ def add_box(self, origin, axis_x, axis_y, axis_z, material_name, skip=()):
+ """Box with one corner at origin and edges along the three axis vectors, sharing vertices so bevels work."""
+ origin = Vector(origin)
+ axis_x = Vector(axis_x)
+ axis_y = Vector(axis_y)
+ axis_z = Vector(axis_z)
+ start = len(self.vertices)
+ corners = [
+ origin,
+ origin + axis_x,
+ origin + axis_x + axis_y,
+ origin + axis_y,
+ origin + axis_z,
+ origin + axis_x + axis_z,
+ origin + axis_x + axis_y + axis_z,
+ origin + axis_y + axis_z,
+ ]
+ self.vertices.extend(corners)
+ sides = {
+ "bottom": (0, 3, 2, 1),
+ "top": (4, 5, 6, 7),
+ "front": (0, 1, 5, 4),
+ "right": (1, 2, 6, 5),
+ "back": (2, 3, 7, 6),
+ "left": (3, 0, 4, 7),
+ }
+ # Grain follows the longest edge of each face.
+ for side_name, side in sides.items():
+ if side_name in skip:
+ continue
+ points = [corners[index] for index in side]
+ self.add_face(points, material_name, uvs=long_edge_uvs(points), indices=[start + index for index in side])
+
+ def add_prism(self, outline, z_bottom, z_top, material_name, material_top=None):
+ """Vertical extrusion of a closed outline given as (x, y) points counter-clockwise."""
+ start = len(self.vertices)
+ count = len(outline)
+ for point in outline:
+ self.vertices.append(Vector((point[0], point[1], z_bottom)))
+ for point in outline:
+ self.vertices.append(Vector((point[0], point[1], z_top)))
+ top_points = [Vector((point[0], point[1], z_top)) for point in outline]
+ self.add_face(top_points, material_top or material_name, uvs=[(point[0], point[1]) for point in outline], indices=[start + count + index for index in range(count)])
+ bottom_points = [Vector((point[0], point[1], z_bottom)) for point in reversed(outline)]
+ bottom_indices = [start + count - 1 - index for index in range(count)]
+ self.add_face(bottom_points, material_name, uvs=[(point[0], point[1]) for point in reversed(outline)], indices=bottom_indices)
+ for index in range(count):
+ following = (index + 1) % count
+ points = [self.vertices[start + index], self.vertices[start + following], self.vertices[start + count + following], self.vertices[start + count + index]]
+ self.add_face(points, material_name, indices=[start + index, start + following, start + count + following, start + count + index])
+
+ def add_cylinder(self, base, top, radius, material_name, sides=20, cap=True, radius_top=None):
+ base = Vector(base)
+ top = Vector(top)
+ axis = (top - base).normalized()
+ helper = Vector((1, 0, 0)) if abs(axis.x) < 0.9 else Vector((0, 1, 0))
+ side_x = axis.cross(helper).normalized()
+ side_y = axis.cross(side_x).normalized()
+ import math
+
+ radius_end = radius if radius_top is None else radius_top
+ start = len(self.vertices)
+ for index in range(sides):
+ angle = 2 * math.pi * index / sides
+ radial = side_x * math.cos(angle) + side_y * math.sin(angle)
+ self.vertices.append(base + radial * radius)
+ for index in range(sides):
+ angle = 2 * math.pi * index / sides
+ radial = side_x * math.cos(angle) + side_y * math.sin(angle)
+ self.vertices.append(top + radial * radius_end)
+ for index in range(sides):
+ following = (index + 1) % sides
+ indices = [start + index, start + following, start + sides + following, start + sides + index]
+ uvs = [(index / sides, 0), ((index + 1) / sides, 0), ((index + 1) / sides, 1), (index / sides, 1)]
+ self.add_face([self.vertices[i] for i in indices], material_name, uvs=uvs, indices=indices)
+ if cap:
+ top_indices = [start + sides + index for index in range(sides)]
+ self.add_face([self.vertices[i] for i in top_indices], material_name, uvs=[(0, 0)] * sides, indices=top_indices)
+ bottom_indices = [start + sides - 1 - index for index in range(sides)]
+ self.add_face([self.vertices[i] for i in bottom_indices], material_name, uvs=[(0, 0)] * sides, indices=bottom_indices)
+
+ def finish(self, collection, bevel=0.0, smooth=False, segments=2):
+ if not self.faces:
+ return None
+ mesh = bpy.data.meshes.new(self.name)
+ mesh.from_pydata([tuple(vertex) for vertex in self.vertices], [], self.faces)
+ uv_layer = mesh.uv_layers.new(name="UVMap")
+ variation_layer = mesh.color_attributes.new("variation", "FLOAT_COLOR", "CORNER")
+ loop_index = 0
+ for polygon_index, polygon in enumerate(mesh.polygons):
+ polygon.material_index = self.face_materials[polygon_index]
+ uvs = self.face_uvs[polygon_index]
+ shade = self.face_variation[polygon_index]
+ for corner, loop in enumerate(polygon.loop_indices):
+ uv_layer.data[loop].uv = uvs[corner]
+ variation_layer.data[loop].color = (shade, shade, shade, 1)
+ polygon.use_smooth = smooth or bevel > 0
+ loop_index += 1
+ for material_name in self.material_names:
+ mesh.materials.append(get_material(material_name))
+ mesh.validate()
+ mesh.update()
+ created = bpy.data.objects.new(self.name, mesh)
+ collection.objects.link(created)
+ if bevel > 0:
+ modifier = created.modifiers.new("edge_wear", "BEVEL")
+ modifier.width = bevel
+ modifier.segments = segments
+ modifier.limit_method = "ANGLE"
+ modifier.angle_limit = 0.6
+ modifier.harden_normals = True
+ modifier.miter_outer = "MITER_ARC"
+ return created
+
+
+def world_uvs(points):
+ """Metric UVs from the face plane, with the horizontal direction as U on walls."""
+ a = Vector(points[0])
+ b = Vector(points[1])
+ c = Vector(points[-1])
+ normal = (b - a).cross(c - a)
+ if normal.length < 1e-9:
+ return [(point[0], point[1]) for point in points]
+ normal.normalize()
+ if abs(normal.z) > 0.9:
+ return [(point[0], point[1]) for point in points]
+ horizontal = Vector((-normal.y, normal.x, 0))
+ if horizontal.length < 1e-6:
+ horizontal = Vector((1, 0, 0))
+ horizontal.normalize()
+ upward = normal.cross(horizontal).normalized()
+ if upward.z < 0:
+ upward = -upward
+ return [(Vector(point).dot(horizontal), Vector(point).dot(upward)) for point in points]
+
+
+def long_edge_uvs(points):
+ """Metric UVs with U along the longer edge of a quad."""
+ a = Vector(points[0])
+ b = Vector(points[1])
+ d = Vector(points[-1])
+ if (b - a).length >= (d - a).length:
+ axis_u = (b - a).normalized()
+ else:
+ axis_u = (d - a).normalized()
+ normal = (b - a).cross(d - a)
+ if normal.length < 1e-9:
+ return [(0, 0)] * len(points)
+ axis_v = normal.normalized().cross(axis_u).normalized()
+ return [(Vector(point).dot(axis_u), Vector(point).dot(axis_v)) for point in points]
+
+
+def section_segments(mesh_object, height):
+ """Cut one object's final mesh with a horizontal plane and return its edges as (x0, y0, x1, y1)."""
+ graph = bpy.context.evaluated_depsgraph_get()
+ evaluated = mesh_object.evaluated_get(graph)
+ mesh = evaluated.to_mesh()
+ work = bmesh.new()
+ work.from_mesh(mesh)
+ work.transform(mesh_object.matrix_world)
+ result = bmesh.ops.bisect_plane(
+ work,
+ geom=work.verts[:] + work.edges[:] + work.faces[:],
+ plane_co=(0, 0, height),
+ plane_no=(0, 0, 1),
+ clear_inner=False,
+ clear_outer=False,
+ )
+ segments = []
+ for element in result["geom_cut"]:
+ if isinstance(element, bmesh.types.BMEdge):
+ start = element.verts[0].co
+ end = element.verts[1].co
+ segments.append((round(start.x, 4), round(start.y, 4), round(end.x, 4), round(end.y, 4)))
+ work.free()
+ evaluated.to_mesh_clear()
+ return segments
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/house_parts.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/house_parts.py
new file mode 100644
index 0000000..ba5c1a7
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/house_parts.py
@@ -0,0 +1,1010 @@
+"""Walls, openings, siding, roof, stairs and casework for build_house.py. All sizes in metres. Runs inside Blender."""
+
+import math
+
+from mathutils import Vector
+
+from house_core import MeshBatch
+
+BOARD_EXPOSURE_CLAPBOARD = 0.093
+JOINT_GAP = 0.0015
+
+
+def v2(point):
+ return Vector((point[0], point[1]))
+
+
+def inside_polygon(point, polygon):
+ inside = False
+ count = len(polygon)
+ for index in range(count):
+ x_a, y_a = polygon[index][0], polygon[index][1]
+ x_b, y_b = polygon[(index + 1) % count][0], polygon[(index + 1) % count][1]
+ if (y_a > point[1]) != (y_b > point[1]) and point[0] < (x_b - x_a) * (point[1] - y_a) / (y_b - y_a) + x_a:
+ inside = not inside
+ return inside
+
+
+class RoofPlane:
+ def __init__(self, data):
+ self.data = data
+ self.corners = [Vector(corner) for corner in data["corners"]]
+ edge_one = self.corners[1] - self.corners[0]
+ edge_two = self.corners[3] - self.corners[0]
+ self.normal = edge_one.cross(edge_two).normalized()
+ if self.normal.z < 0:
+ self.normal = -self.normal
+
+ def height_at(self, x, y):
+ """Underside height at a point, or None when the point is outside this plane."""
+ if not inside_polygon((x, y), self.corners):
+ return None
+ origin = self.corners[0]
+ return origin.z - (self.normal.x * (x - origin.x) + self.normal.y * (y - origin.y)) / self.normal.z
+
+
+class Wall:
+ def __init__(self, data):
+ self.data = data
+ self.id = data["id"]
+ self.a = v2(data["a"])
+ self.b = v2(data["b"])
+ self.t = data["t"]
+ self.kind = data.get("kind", "int")
+ self.length = (self.b - self.a).length
+ self.direction = (self.b - self.a).normalized()
+ self.normal = Vector((-self.direction.y, self.direction.x))
+ self.s0 = 0.0
+ self.s1 = self.length
+ self.openings = []
+ self.outside_side = data.get("outside")
+
+ def at(self, along, offset=0.0, z=0.0):
+ flat = self.a + self.direction * along + self.normal * offset
+ return Vector((flat.x, flat.y, z))
+
+
+def resolve_junctions(walls):
+ """Each wall end runs through to the far face of the wall it meets, or stops at the near face."""
+ for index, wall in enumerate(walls):
+ for end_name in ("a", "b"):
+ point = wall.a if end_name == "a" else wall.b
+ for other_index, other in enumerate(walls):
+ if other is wall:
+ continue
+ to_point = point - other.a
+ along = to_point.dot(other.direction)
+ across = abs(to_point.dot(other.normal))
+ if along < -0.08 or along > other.length + 0.08 or across > other.t / 2 + 0.05:
+ continue
+ sine = abs(wall.direction.x * other.direction.y - wall.direction.y * other.direction.x)
+ if sine < 0.2:
+ continue
+ at_other_end = along < 0.08 or along > other.length - 0.08
+ signed = to_point.dot(other.normal)
+ runs_through = at_other_end and index < other_index
+ facing = -wall.direction if end_name == "b" else wall.direction
+ # Distance from this wall's end to the plane of the other wall's face along this wall's axis.
+ heading = facing.dot(other.normal)
+ near_plane = other.t / 2 if heading < 0 else -other.t / 2
+ far_plane = -near_plane
+ target_plane = far_plane if runs_through else near_plane
+ travel = (target_plane - signed) / heading if abs(heading) > 1e-6 else 0.0
+ if end_name == "a":
+ wall.s0 = min(wall.s0, travel) if runs_through else max(wall.s0, travel)
+ else:
+ wall.s1 = max(wall.s1, wall.length - travel) if runs_through else min(wall.s1, wall.length - travel)
+
+
+class Structure:
+ """Plan geometry shared by the part builders."""
+
+ def __init__(self, plan):
+ self.plan = plan
+ self.walls = [Wall(data) for data in plan["walls"]]
+ self.by_id = {wall.id: wall for wall in self.walls}
+ self.roof_planes = [RoofPlane(data) for data in plan.get("roof", {}).get("planes", [])]
+ resolve_junctions(self.walls)
+ for opening in plan.get("openings", []):
+ wall = self.by_id[opening["wall"]]
+ if "from" not in opening:
+ opening["from"] = opening["at"] - opening["width"] / 2
+ opening["to"] = opening["at"] + opening["width"] / 2
+ wall.openings.append(opening)
+ for wall in self.walls:
+ wall.openings.sort(key=lambda opening: opening["from"])
+ self.rooms = plan.get("rooms", [])
+
+ def room_at(self, point):
+ for room in self.rooms:
+ if inside_polygon(point, room["poly"]):
+ return room
+ return None
+
+ def roof_under(self, x, y):
+ heights = []
+ for plane in self.roof_planes:
+ height = plane.height_at(x, y)
+ if height is not None:
+ heights.append(height)
+ if not heights:
+ return None
+ # Crossing roofs enclose their union; a stepped roof like a lean-to closes under the lowest plane.
+ return max(heights) if self.plan["style"].get("roof_union") else min(heights)
+
+ def wall_top(self, wall, along):
+ fallback = wall.data.get("h", self.plan["levels"]["ceiling"])
+ if wall.data.get("top") != "roof":
+ return fallback
+ point = wall.at(along)
+ height = self.roof_under(point.x, point.y)
+ return (height - 0.005) if height is not None else fallback
+
+ def side_material(self, wall, along, side):
+ """Finish on one face of a wall, from the room behind that face or the wall's exterior finish."""
+ offset = side * (wall.t / 2 + 0.12)
+ point = wall.at(along, offset)
+ room = self.room_at((point.x, point.y))
+ if room is not None:
+ return room.get("wall", self.plan["style"]["interior_wall"]), room
+ return self.plan["style"].get("wall_base", "putty"), None
+
+
+def top_breaks(structure, wall):
+ """Places along a wall where its top height changes slope."""
+ breaks = {wall.s0, wall.s1}
+ if wall.data.get("top") != "roof":
+ return breaks
+ step = 0.05
+ along = wall.s0
+ previous_slope = None
+ while along + step < wall.s1:
+ slope = structure.wall_top(wall, along + step) - structure.wall_top(wall, along)
+ if previous_slope is not None and abs(slope - previous_slope) > 1e-4:
+ breaks.add(along)
+ previous_slope = slope
+ along += step
+ return breaks
+
+
+def build_wall(structure, wall, batch, reveal_material):
+ floor_z = structure.plan["levels"].get("floor", 0.0)
+ base_z = wall.data.get("z0", floor_z)
+ breaks = top_breaks(structure, wall)
+ for opening in wall.openings:
+ breaks.add(max(wall.s0, opening["from"]))
+ breaks.add(min(wall.s1, opening["to"]))
+ stations = sorted(breaks)
+ half = wall.t / 2
+ for left, right in zip(stations, stations[1:]):
+ if right - left < 1e-4:
+ continue
+ middle = (left + right) / 2
+ top_left = structure.wall_top(wall, left)
+ top_right = structure.wall_top(wall, right)
+ cells = []
+ holes = sorted(
+ (opening for opening in wall.openings if opening["from"] <= middle <= opening["to"]),
+ key=lambda opening: opening.get("sill", 0.0),
+ )
+ if not holes:
+ cells.append((base_z, base_z, top_left, top_right))
+ else:
+ cursor = base_z
+ for hole in holes:
+ sill = hole.get("sill", 0.0) + floor_z
+ if sill > cursor + 1e-4:
+ cells.append((cursor, cursor, sill, sill))
+ cursor = hole["head"] + floor_z
+ if cursor < min(top_left, top_right) - 1e-4:
+ cells.append((cursor, cursor, top_left, top_right))
+ material_positive, _ = structure.side_material(wall, middle, 1)
+ material_negative, _ = structure.side_material(wall, middle, -1)
+ for bottom_left, bottom_right, upper_left, upper_right in cells:
+ batch.add_face(
+ [
+ wall.at(left, -half, bottom_left),
+ wall.at(right, -half, bottom_right),
+ wall.at(right, -half, upper_right),
+ wall.at(left, -half, upper_left),
+ ],
+ material_negative,
+ )
+ batch.add_face(
+ [
+ wall.at(right, half, bottom_right),
+ wall.at(left, half, bottom_left),
+ wall.at(left, half, upper_left),
+ wall.at(right, half, upper_right),
+ ],
+ material_positive,
+ )
+ batch.add_face(
+ [wall.at(left, -half, upper_left), wall.at(right, -half, upper_right), wall.at(right, half, upper_right), wall.at(left, half, upper_left)],
+ reveal_material,
+ )
+ batch.add_face(
+ [wall.at(left, half, bottom_left), wall.at(right, half, bottom_right), wall.at(right, -half, bottom_right), wall.at(left, -half, bottom_left)],
+ reveal_material,
+ )
+ # Ends of the wall.
+ end_material = material_for_end(structure, wall)
+ top_start = structure.wall_top(wall, wall.s0)
+ top_end = structure.wall_top(wall, wall.s1)
+ batch.add_face([wall.at(wall.s0, half, base_z), wall.at(wall.s0, -half, base_z), wall.at(wall.s0, -half, top_start), wall.at(wall.s0, half, top_start)], end_material)
+ batch.add_face([wall.at(wall.s1, -half, base_z), wall.at(wall.s1, half, base_z), wall.at(wall.s1, half, top_end), wall.at(wall.s1, -half, top_end)], end_material)
+ # Jambs of each opening.
+ for opening in wall.openings:
+ sill = opening.get("sill", 0.0) + floor_z
+ head = opening["head"] + floor_z
+ start = max(wall.s0, opening["from"])
+ finish = min(wall.s1, opening["to"])
+ batch.add_face([wall.at(start, -half, sill), wall.at(start, half, sill), wall.at(start, half, head), wall.at(start, -half, head)], reveal_material)
+ batch.add_face([wall.at(finish, half, sill), wall.at(finish, -half, sill), wall.at(finish, -half, head), wall.at(finish, half, head)], reveal_material)
+
+
+def material_for_end(structure, wall):
+ return structure.plan["style"].get("end_cap", structure.plan["style"]["interior_wall"])
+
+
+def outer_offset(wall):
+ return wall.outside_side * wall.t / 2
+
+
+def open_spans(wall, z_low, z_high, floor_z, margin, start=None, finish=None):
+ """Stretches of a wall's length not interrupted by an opening within a band of height."""
+ start = wall.s0 if start is None else start
+ finish = wall.s1 if finish is None else finish
+ spans = []
+ cursor = start
+ for opening in wall.openings:
+ sill = opening.get("sill", 0.0) + floor_z
+ head = opening["head"] + floor_z
+ if z_high <= sill - margin or z_low >= head + margin:
+ continue
+ left = opening["from"] - margin
+ right = opening["to"] + margin
+ if left > cursor:
+ spans.append((cursor, min(left, finish)))
+ cursor = max(cursor, right)
+ if cursor < finish:
+ spans.append((cursor, finish))
+ return [span for span in spans if span[1] - span[0] > 0.015]
+
+
+def siding_clapboard(structure, wall, batch, material, exposure=BOARD_EXPOSURE_CLAPBOARD, thickness=0.014):
+ floor_z = structure.plan["levels"].get("floor", 0.0)
+ side = wall.outside_side
+ outer = outer_offset(wall)
+ base = wall.data.get("z0", floor_z)
+ casing_margin = structure.plan["style"].get("exterior_casing", 0.09)
+ highest = max(structure.wall_top(wall, wall.s0 + fraction * (wall.s1 - wall.s0)) for fraction in (0, 0.25, 0.5, 0.75, 1))
+ z_low = base
+ while z_low < highest:
+ z_high = z_low + exposure
+ for span_start, span_end in open_spans(wall, z_low, z_high, floor_z, casing_margin):
+ along = span_start
+ while along < span_end:
+ piece = batch.random.uniform(1.8, 4.2)
+ piece_end = min(span_end, along + piece)
+ if span_end - piece_end < 0.5:
+ piece_end = span_end
+ clip_start, clip_end = clip_under_top(structure, wall, along, piece_end, z_high)
+ if clip_end - clip_start > 0.02:
+ batch.uv_offset = (batch.random.uniform(0, 8), batch.random.uniform(0, 8))
+ batch.variation = batch.random.uniform(0.93, 1.04)
+ butt = side * thickness
+ feather = side * 0.003
+ bottom_a = wall.at(clip_start + JOINT_GAP, outer + butt, z_low)
+ bottom_b = wall.at(clip_end - JOINT_GAP, outer + butt, z_low)
+ top_a = wall.at(clip_start + JOINT_GAP, outer + feather, z_high + 0.002)
+ top_b = wall.at(clip_end - JOINT_GAP, outer + feather, z_high + 0.002)
+ under_a = wall.at(clip_start + JOINT_GAP, outer, z_low)
+ under_b = wall.at(clip_end - JOINT_GAP, outer, z_low)
+ face = [bottom_a, bottom_b, top_b, top_a] if side < 0 else [bottom_b, bottom_a, top_a, top_b]
+ lip = [under_a, under_b, bottom_b, bottom_a] if side < 0 else [under_b, under_a, bottom_a, bottom_b]
+ batch.add_face(face, material)
+ batch.add_face(lip, material)
+ end_face = [under_a, bottom_a, top_a] if side < 0 else [bottom_a, under_a, top_a]
+ batch.add_face(end_face, material)
+ end_face = [bottom_b, under_b, top_b] if side < 0 else [under_b, bottom_b, top_b]
+ batch.add_face(end_face, material)
+ along = piece_end
+ z_low = z_high
+ batch.variation = 1.0
+ batch.uv_offset = (0, 0)
+
+
+def clip_under_top(structure, wall, start, finish, z_high):
+ """Shorten a horizontal board so its top stays under a sloped wall top."""
+ if wall.data.get("top") != "roof":
+ return start, finish
+ step = 0.04
+ clipped_start = start
+ while clipped_start < finish and structure.wall_top(wall, clipped_start) < z_high:
+ clipped_start += step
+ clipped_end = finish
+ while clipped_end > clipped_start and structure.wall_top(wall, clipped_end) < z_high:
+ clipped_end -= step
+ return clipped_start, clipped_end
+
+
+def siding_board_batten(structure, wall, batch, board_material, batten_material, spacing=0.3, batten_width=0.05, batten_depth=0.019):
+ floor_z = structure.plan["levels"].get("floor", 0.0)
+ side = wall.outside_side
+ outer = outer_offset(wall)
+ base = wall.data.get("z0", floor_z) - 0.12
+ casing_margin = structure.plan["style"].get("exterior_casing", 0.09)
+ along = wall.s0 + spacing / 2
+ while along < wall.s1:
+ top = structure.wall_top(wall, along)
+ z_low = base
+ bands = [(z_low, top)]
+ for opening in wall.openings:
+ if opening["from"] - casing_margin - batten_width < along < opening["to"] + casing_margin + batten_width:
+ sill = opening.get("sill", 0.0) + floor_z - casing_margin
+ head = opening["head"] + floor_z + casing_margin
+ updated = []
+ for band_low, band_high in bands:
+ if band_low < sill:
+ updated.append((band_low, min(band_high, sill)))
+ if band_high > head:
+ updated.append((max(band_low, head), band_high))
+ bands = updated
+ for band_low, band_high in bands:
+ if band_high - band_low < 0.03:
+ continue
+ batch.uv_offset = (batch.random.uniform(0, 8), batch.random.uniform(0, 8))
+ batch.variation = batch.random.uniform(0.88, 1.08)
+ origin = wall.at(along - batten_width / 2, outer, band_low)
+ axis_x = wall.at(along + batten_width / 2, outer, band_low) - origin
+ axis_y = Vector((wall.normal.x * side * batten_depth, wall.normal.y * side * batten_depth, 0))
+ axis_z = Vector((0, 0, band_high - band_low))
+ if side > 0:
+ batch.add_box(origin, axis_x, axis_y, axis_z, batten_material, skip=("bottom",))
+ else:
+ batch.add_box(origin + axis_y, axis_x, -axis_y, axis_z, batten_material, skip=("bottom",))
+ along += spacing
+ batch.variation = 1.0
+ batch.uv_offset = (0, 0)
+
+
+def add_rail(batch, wall, start, finish, offset, depth_from, depth_to, z_low, z_high, material):
+ """Box aligned with a wall: along start..finish, across offset+depth_from..offset+depth_to, between two heights."""
+ origin = wall.at(start, offset + min(depth_from, depth_to), z_low)
+ axis_x = wall.at(finish, 0, 0) - wall.at(start, 0, 0)
+ span = abs(depth_to - depth_from)
+ axis_y = Vector((wall.normal.x * span, wall.normal.y * span, 0))
+ axis_z = Vector((0, 0, z_high - z_low))
+ batch.add_box(origin, axis_x, axis_y, axis_z, material)
+
+
+def build_window(structure, wall, opening, trim, glass):
+ style = structure.plan["style"]
+ floor_z = structure.plan["levels"].get("floor", 0.0)
+ material = opening.get("frame_material", style.get("window_material", "trim_white"))
+ sill = opening.get("sill", 0.0) + floor_z
+ head = opening["head"] + floor_z
+ start = opening["from"]
+ finish = opening["to"]
+ side = wall.outside_side if wall.outside_side else -1
+ half = wall.t / 2
+ frame_thickness = 0.035
+ plane_outer = side * (half - 0.03)
+ # Frame lining the whole reveal.
+ add_rail(trim, wall, start, start + frame_thickness, 0, -half, half, sill, head, material)
+ add_rail(trim, wall, finish - frame_thickness, finish, 0, -half, half, sill, head, material)
+ add_rail(trim, wall, start, finish, 0, -half, half, head - frame_thickness, head, material)
+ add_rail(trim, wall, start, finish, 0, -half, half, sill, sill + frame_thickness, material)
+ # Sill with a nose past the wall face on both sides.
+ casing = style.get("exterior_casing", 0.09)
+ add_rail(trim, wall, start - casing - 0.02, finish + casing + 0.02, side * half, 0, side * 0.045, sill - 0.04, sill, material)
+ # Casing outside and inside.
+ outside_depth = side * 0.022
+ add_rail(trim, wall, start - casing, start, side * half, 0, outside_depth + side * 0.01, sill, head + casing, material)
+ add_rail(trim, wall, finish, finish + casing, side * half, 0, outside_depth + side * 0.01, sill, head + casing, material)
+ add_rail(trim, wall, start - casing - 0.015, finish + casing + 0.015, side * half, 0, outside_depth + side * 0.03, head + casing - 0.02, head + casing + 0.03, material)
+ inside_material = opening.get("casing_material", style.get("interior_trim", material))
+ inside_casing = style.get("interior_casing", 0.075)
+ add_rail(trim, wall, start - inside_casing, start, -side * half, 0, -side * 0.018, sill, head + inside_casing, inside_material)
+ add_rail(trim, wall, finish, finish + inside_casing, -side * half, 0, -side * 0.018, sill, head + inside_casing, inside_material)
+ add_rail(trim, wall, start - inside_casing, finish + inside_casing, -side * half, 0, -side * 0.018, head, head + inside_casing, inside_material)
+ add_rail(trim, wall, start - inside_casing - 0.02, finish + inside_casing + 0.02, -side * half, 0, -side * 0.035, sill - 0.025, sill, inside_material)
+
+ sash_kind = opening.get("sash", "fixed")
+ inner_start = start + frame_thickness
+ inner_finish = finish - frame_thickness
+ inner_sill = sill + frame_thickness
+ inner_head = head - frame_thickness
+ panes_across = opening.get("panes_x", 1)
+ panes_up = opening.get("panes_y", 1)
+ sections = opening.get("sections", 1)
+ section_width = (inner_finish - inner_start) / sections
+ for section in range(sections):
+ left = inner_start + section * section_width
+ right = left + section_width
+ if sash_kind == "double_hung":
+ meeting = (inner_sill + inner_head) / 2
+ add_sash(trim, glass, wall, left, right, inner_sill, meeting + 0.015, plane_outer - side * 0.075, panes_across, panes_up, material)
+ add_sash(trim, glass, wall, left, right, meeting - 0.015, inner_head, plane_outer - side * 0.03, panes_across, panes_up, material)
+ else:
+ add_sash(trim, glass, wall, left, right, inner_sill, inner_head, plane_outer - side * 0.04, panes_across, panes_up, material)
+ if opening.get("transom_at") is not None:
+ rail_z = opening["transom_at"] + floor_z
+ add_rail(trim, wall, inner_start, inner_finish, plane_outer - side * 0.04, -0.022, 0.022, rail_z - 0.02, rail_z + 0.02, material)
+ if opening.get("shutters"):
+ build_shutter(trim, wall, start - casing - opening["shutters"], start - casing - 0.005, side * half + side * 0.012, sill, head + casing * 0.4, style.get("shutter_material", "shutter_black"), side)
+ build_shutter(trim, wall, finish + casing + 0.005, finish + casing + opening["shutters"], side * half + side * 0.012, sill, head + casing * 0.4, style.get("shutter_material", "shutter_black"), side)
+
+
+def add_sash(trim, glass, wall, left, right, bottom, top, plane, panes_across, panes_up, material):
+ stile = 0.042
+ depth = 0.032
+ add_rail(trim, wall, left, left + stile, plane, -depth / 2, depth / 2, bottom, top, material)
+ add_rail(trim, wall, right - stile, right, plane, -depth / 2, depth / 2, bottom, top, material)
+ add_rail(trim, wall, left + stile, right - stile, plane, -depth / 2, depth / 2, top - stile, top, material)
+ add_rail(trim, wall, left + stile, right - stile, plane, -depth / 2, depth / 2, bottom, bottom + stile * 1.3, material)
+ glass_left = left + stile
+ glass_right = right - stile
+ glass_bottom = bottom + stile * 1.3
+ glass_top = top - stile
+ muntin = 0.016
+ for index in range(1, panes_across):
+ along = glass_left + (glass_right - glass_left) * index / panes_across
+ add_rail(trim, wall, along - muntin / 2, along + muntin / 2, plane, -0.011, 0.011, glass_bottom, glass_top, material)
+ for index in range(1, panes_up):
+ height = glass_bottom + (glass_top - glass_bottom) * index / panes_up
+ add_rail(trim, wall, glass_left, glass_right, plane, -0.011, 0.011, height - muntin / 2, height + muntin / 2, material)
+ add_rail(glass, wall, glass_left - 0.004, glass_right + 0.004, plane, -0.002, 0.002, glass_bottom - 0.004, glass_top + 0.004, "glass")
+
+
+def build_shutter(trim, wall, start, finish, offset, bottom, top, material, side):
+ stile = 0.038
+ depth = 0.024
+ add_rail(trim, wall, start, start + stile, offset, 0, side * depth, bottom, top, material)
+ add_rail(trim, wall, finish - stile, finish, offset, 0, side * depth, bottom, top, material)
+ add_rail(trim, wall, start + stile, finish - stile, offset, 0, side * depth, bottom, bottom + stile * 1.5, material)
+ add_rail(trim, wall, start + stile, finish - stile, offset, 0, side * depth, top - stile * 1.5, top, material)
+ middle = (bottom + top) / 2
+ add_rail(trim, wall, start + stile, finish - stile, offset, 0, side * depth, middle - stile * 0.7, middle + stile * 0.7, material)
+ # Louvres: thin slats tilted out of plumb.
+ slat_pitch = 0.038
+ height = bottom + stile * 1.5
+ while height < top - stile * 1.5 - slat_pitch:
+ if abs(height + slat_pitch / 2 - middle) > stile * 0.7 + slat_pitch / 2:
+ lean = Vector((wall.normal.x * side * 0.012, wall.normal.y * side * 0.012, 0))
+ origin = wall.at(start + stile, offset + side * 0.006, height)
+ axis_x = wall.at(finish - stile, 0, 0) - wall.at(start + stile, 0, 0)
+ axis_y = lean + Vector((0, 0, slat_pitch * 0.9))
+ axis_z = Vector((0, 0, 0.006))
+ trim.add_box(origin, axis_x, axis_y, axis_z, material)
+ height += slat_pitch
+
+
+def build_door(structure, wall, opening, trim, hardware):
+ style = structure.plan["style"]
+ floor_z = structure.plan["levels"].get("floor", 0.0)
+ start = opening["from"]
+ finish = opening["to"]
+ head = opening["head"] + floor_z
+ half = wall.t / 2
+ lining = 0.02
+ frame_material = opening.get("frame_material", style.get("interior_trim", "trim_white"))
+ add_rail(trim, wall, start, start + lining, 0, -half, half, floor_z, head, frame_material)
+ add_rail(trim, wall, finish - lining, finish, 0, -half, half, floor_z, head, frame_material)
+ add_rail(trim, wall, start, finish, 0, -half, half, head - lining, head, frame_material)
+ casing = style.get("interior_casing", 0.075)
+ for side in (-1, 1):
+ is_outer = wall.outside_side == side
+ material = style.get("window_material", frame_material) if is_outer else frame_material
+ width = style.get("exterior_casing", 0.09) if is_outer else casing
+ add_rail(trim, wall, start - width, start, side * half, 0, side * 0.018, floor_z, head + width, material)
+ add_rail(trim, wall, finish, finish + width, side * half, 0, side * 0.018, floor_z, head + width, material)
+ add_rail(trim, wall, start - width, finish + width, side * half, 0, side * 0.018, head, head + width, material)
+ if opening.get("kind") != "door" or opening.get("leaf") == "none":
+ return
+ leaves = opening.get("leaves", 1)
+ clear_start = start + lining
+ clear_finish = finish - lining
+ leaf_width = (clear_finish - clear_start) / leaves
+ for leaf_index in range(leaves):
+ leaf_start = clear_start + leaf_index * leaf_width
+ hinge_at_start = opening.get("hinge", "start") == "start" if leaves == 1 else leaf_index == 0
+ swing_side = opening.get("swing", -1 if wall.outside_side is None else -wall.outside_side)
+ open_degrees = opening.get("open", 0)
+ build_door_leaf(structure, wall, opening, trim, hardware, leaf_start, leaf_width - 0.003, floor_z + 0.005, head - lining - 0.003, hinge_at_start, swing_side, open_degrees)
+
+
+def build_door_leaf(structure, wall, opening, trim, hardware, start, width, bottom, top, hinge_at_start, swing_side, open_degrees):
+ style = structure.plan["style"]
+ material = opening.get("material", style.get("door_material", "trim_white"))
+ thickness = 0.038
+ plane = swing_side * (wall.t / 2 - thickness)
+ hinge_along = start if hinge_at_start else start + width
+ hinge = wall.at(hinge_along, plane, 0)
+ angle = math.radians(open_degrees) * swing_side * (1 if hinge_at_start else -1)
+ cosine = math.cos(angle)
+ sine = math.sin(angle)
+ direction_along = wall.direction * (1 if hinge_at_start else -1)
+ normal = wall.normal
+
+ def rotate(flat):
+ return Vector((flat.x * cosine - flat.y * sine, flat.x * sine + flat.y * cosine, 0))
+
+ axis_width = rotate(Vector((direction_along.x, direction_along.y, 0)))
+ axis_depth = rotate(Vector((normal.x, normal.y, 0)))
+
+ def box(u_low, u_high, depth_low, depth_high, z_low, z_high, box_material):
+ origin = hinge + axis_width * u_low + axis_depth * depth_low + Vector((0, 0, z_low))
+ trim.add_box(origin, axis_width * (u_high - u_low), axis_depth * (depth_high - depth_low), Vector((0, 0, z_high - z_low)), box_material)
+
+ kind = opening.get("panels", "slab")
+ total_height = top - bottom
+ depth_low = -thickness / 2
+ depth_high = thickness / 2
+ if kind == "slab":
+ box(0, width, depth_low, depth_high, bottom, top, material)
+ elif kind == "sheathing":
+ boards = max(3, int(width / 0.12))
+ for index in range(boards):
+ u_low = width * index / boards + 0.001
+ u_high = width * (index + 1) / boards - 0.001
+ trim.variation = trim.random.uniform(0.9, 1.05)
+ trim.uv_offset = (trim.random.uniform(0, 5), trim.random.uniform(0, 5))
+ box(u_low, u_high, depth_low, depth_high, bottom, top, material)
+ trim.variation = 1.0
+ trim.uv_offset = (0, 0)
+ box(0.02, width - 0.02, depth_high, depth_high + 0.02, bottom + total_height * 0.18, bottom + total_height * 0.18 + 0.13, material)
+ box(0.02, width - 0.02, depth_high, depth_high + 0.02, bottom + total_height * 0.78, bottom + total_height * 0.78 + 0.13, material)
+ else:
+ rows = {"six": [(0.0, 0.33), (0.33, 0.78), (0.78, 1.0)], "four": [(0.0, 0.42), (0.42, 1.0)], "two": [(0.0, 0.5), (0.5, 1.0)]}[kind]
+ columns = 1 if kind == "two" else 2
+ stile = 0.105
+ rail = 0.105
+ muntin = 0.09
+ box(0, stile, depth_low, depth_high, bottom, top, material)
+ box(width - stile, width, depth_low, depth_high, bottom, top, material)
+ inner_width = width - 2 * stile
+ inner_height = total_height - rail * (len(rows) + 1)
+ pane_width = (inner_width - muntin * (columns - 1)) / columns
+ height = bottom
+ box(stile, width - stile, depth_low, depth_high, height, height + rail * 1.35, material)
+ height += rail * 1.35
+ for row_index, (low, high) in enumerate(rows):
+ pane_height = inner_height * (high - low) - (rail * 0.35 if row_index == 0 else 0)
+ for column in range(columns):
+ u_low = stile + column * (pane_width + muntin)
+ u_high = u_low + pane_width
+ if column < columns - 1:
+ box(u_high, u_high + muntin, depth_low, depth_high, height, height + pane_height, material)
+ add_raised_panel(trim, hinge, axis_width, axis_depth, u_low, u_high, height, height + pane_height, thickness, material)
+ height += pane_height
+ box(stile, width - stile, depth_low, depth_high, height, height + rail, material)
+ height += rail
+ # Knob on both faces.
+ knob_u = width - 0.06
+ knob_z = bottom + 0.95
+ for face in (-1, 1):
+ rose = hinge + axis_width * knob_u + axis_depth * (face * thickness / 2) + Vector((0, 0, knob_z))
+ outward = axis_depth * face
+ hardware.add_cylinder(rose, rose + outward * 0.008, 0.028, opening.get("hardware", "brass"), sides=20)
+ hardware.add_cylinder(rose + outward * 0.008, rose + outward * 0.045, 0.009, opening.get("hardware", "brass"), sides=14)
+ hardware.add_cylinder(rose + outward * 0.045, rose + outward * 0.068, 0.024, opening.get("hardware", "brass"), sides=20, radius_top=0.019)
+ for fraction in (0.12, 0.5, 0.88):
+ hinge_centre = hinge + axis_depth * (swing_side * 0.019) + Vector((0, 0, bottom + total_height * fraction))
+ hardware.add_cylinder(hinge_centre - Vector((0, 0, 0.045)), hinge_centre + Vector((0, 0, 0.045)), 0.007, opening.get("hardware", "brass"), sides=10)
+
+
+def add_raised_panel(trim, hinge, axis_width, axis_depth, u_low, u_high, z_low, z_high, thickness, material):
+ """Fielded door panel: flat field standing proud of a sloped margin, on both faces."""
+ margin = 0.035
+ for face in (-1, 1):
+ def point(u, z, depth):
+ return hinge + axis_width * u + axis_depth * (face * depth) + Vector((0, 0, z))
+
+ groove = thickness / 2 - 0.012
+ field = thickness / 2 - 0.004
+ outer = [point(u_low, z_low, groove), point(u_high, z_low, groove), point(u_high, z_high, groove), point(u_low, z_high, groove)]
+ inner = [
+ point(u_low + margin, z_low + margin, field),
+ point(u_high - margin, z_low + margin, field),
+ point(u_high - margin, z_high - margin, field),
+ point(u_low + margin, z_high - margin, field),
+ ]
+ order = [0, 1, 2, 3] if face * axis_depth.dot(axis_width.cross(Vector((0, 0, 1)))) < 0 else [3, 2, 1, 0]
+ for index in range(4):
+ first = order[index]
+ second = order[(index + 1) % 4]
+ trim.add_face([outer[first], outer[second], inner[second], inner[first]], material)
+ trim.add_face([inner[order[0]], inner[order[1]], inner[order[2]], inner[order[3]]], material)
+
+
+def build_baseboards(structure, wall, trim):
+ floor_z = wall.data.get("z0", structure.plan["levels"].get("floor", 0.0))
+ half = wall.t / 2
+ style = structure.plan["style"]
+ for side in (-1, 1):
+ if wall.outside_side == side:
+ continue
+ spans = open_spans(wall, floor_z, floor_z + 0.1, floor_z, 0.0)
+ for span_start, span_end in spans:
+ door_margin_low = span_start
+ door_margin_high = span_end
+ for opening in wall.openings:
+ if abs(opening["to"] - span_start) < 0.001:
+ door_margin_low = span_start + style.get("interior_casing", 0.075)
+ if abs(opening["from"] - span_end) < 0.001:
+ door_margin_high = span_end - style.get("interior_casing", 0.075)
+ middle = (door_margin_low + door_margin_high) / 2
+ _, room = structure.side_material(wall, middle, side)
+ if room is None or door_margin_high - door_margin_low < 0.02:
+ continue
+ height = room.get("baseboard", style.get("baseboard", 0.1))
+ if height <= 0:
+ continue
+ material = room.get("trim", style.get("interior_trim", "trim_white"))
+ add_rail(trim, wall, door_margin_low, door_margin_high, side * half, 0, side * 0.016, floor_z, floor_z + height, material)
+ crown = room.get("crown", 0.0)
+ ceiling = room.get("ceiling")
+ if crown > 0 and ceiling is not None:
+ add_rail(trim, wall, door_margin_low, door_margin_high, side * half, 0, side * 0.03, floor_z + ceiling - crown, floor_z + ceiling, material)
+ rail_height = room.get("chair_rail", 0.0)
+ if rail_height > 0:
+ for rail_start, rail_end in open_spans(wall, floor_z + rail_height, floor_z + rail_height + 0.07, floor_z, 0.08, door_margin_low, door_margin_high):
+ add_rail(trim, wall, rail_start, rail_end, side * half, 0, side * 0.022, floor_z + rail_height, floor_z + rail_height + 0.07, material)
+
+
+def build_corner_boards(structure, wall, trim, material):
+ width = structure.plan["style"].get("corner_board", 0.11)
+ if width <= 0 or not wall.outside_side:
+ return
+ outer = outer_offset(wall)
+ floor_z = structure.plan["levels"].get("floor", 0.0)
+ side = wall.outside_side
+ base = wall.data.get("z0", floor_z)
+ for start, finish in ((wall.s0, wall.s0 + width), (wall.s1 - width, wall.s1)):
+ top = min(structure.wall_top(wall, start), structure.wall_top(wall, finish))
+ add_rail(trim, wall, start, finish, outer, 0, side * 0.026, base - 0.02, top, material)
+
+
+def build_roof_plane(plane_data, roof_plane, deck, covering, carpentry, style):
+ corners = roof_plane.corners
+ normal = roof_plane.normal
+ thickness = plane_data.get("thickness", 0.04)
+ cover = plane_data.get("cover", "shingle")
+ material_under = plane_data.get("under", style.get("soffit", "pine_boards"))
+ lower = list(corners)
+ upper = [corner + normal * thickness for corner in corners]
+ deck.add_face(list(reversed(lower)), material_under)
+ deck.add_face(upper, plane_data.get("top", "putty"))
+ count = len(corners)
+ for index in range(count):
+ following = (index + 1) % count
+ deck.add_face([lower[index], lower[following], upper[following], upper[index]], material_under)
+
+ eave_a, eave_b, ridge_b, ridge_a = corners
+ fascia_material = plane_data.get("fascia", style.get("fascia", style.get("window_material", "trim_white")))
+ fascia_depth = plane_data.get("fascia_depth", 0.14)
+ if fascia_depth > 0:
+ drop = Vector((0, 0, -fascia_depth + thickness))
+ run = eave_b - eave_a
+ out = (eave_a - ridge_a).normalized()
+ out.z = 0
+ out.normalize()
+ carpentry.add_box(eave_a + drop + out * 0.0, run, out * 0.03, Vector((0, 0, fascia_depth + 0.012)), fascia_material)
+ for start, finish in ((eave_a, ridge_a), (eave_b, ridge_b)):
+ rake_run = finish - start
+ side_out = (start - (eave_b if start == eave_a else eave_a))
+ side_out.z = 0
+ side_out.normalize()
+ carpentry.add_box(start + Vector((0, 0, -fascia_depth + thickness)), rake_run, side_out * 0.03, Vector((0, 0, fascia_depth + 0.012)), fascia_material)
+ if cover == "shingle":
+ cover_shingles(eave_a, eave_b, ridge_a, ridge_b, normal, thickness, covering, plane_data)
+ elif cover == "roll":
+ cover_roll(eave_a, eave_b, ridge_a, ridge_b, normal, thickness, covering, plane_data)
+
+ rafters = plane_data.get("rafters")
+ if rafters:
+ spacing = rafters["spacing"]
+ width = rafters.get("w", 0.05)
+ depth = rafters.get("d", 0.14)
+ material = rafters.get("material", "pine_boards")
+ run_x = eave_b - eave_a
+ total = run_x.length
+ axis_along = run_x.normalized()
+ along = rafters.get("first", spacing / 2)
+ while along < total:
+ start_point = eave_a + axis_along * along
+ end_point = ridge_a + (ridge_b - ridge_a).normalized() * along
+ start_point = start_point + (end_point - start_point).normalized() * rafters.get("start_inset", 0.0)
+ if rafters.get("x_min", -1e9) <= start_point.x <= rafters.get("x_max", 1e9):
+ carpentry.uv_offset = (carpentry.random.uniform(0, 6), carpentry.random.uniform(0, 6))
+ carpentry.variation = carpentry.random.uniform(0.9, 1.05)
+ carpentry.add_box(start_point - axis_along * (width / 2) - normal * depth, end_point - start_point, axis_along * width, normal * depth, material)
+ along += spacing
+ carpentry.variation = 1.0
+ carpentry.uv_offset = (0, 0)
+
+
+def cover_shingles(eave_a, eave_b, ridge_a, ridge_b, normal, thickness, covering, plane_data):
+ material = plane_data.get("top_material", "shingle_wood")
+ exposure = plane_data.get("exposure", 0.125)
+ length_along = (eave_b - eave_a).length
+ axis_along = (eave_b - eave_a).normalized()
+ slope = (ridge_a - eave_a).length
+ axis_up = (ridge_a - eave_a).normalized()
+ base = eave_a + normal * thickness - axis_up * 0.03
+ row = 0
+ height = 0.0
+ while height < slope:
+ along = -covering.random.uniform(0, 0.12)
+ while along < length_along:
+ width = covering.random.uniform(0.09, 0.26)
+ end_along = min(length_along, along + width)
+ start_along = max(0.0, along)
+ if end_along - start_along > 0.01:
+ lift = covering.random.uniform(0.008, 0.016)
+ skew = covering.random.uniform(-0.006, 0.006)
+ bottom = height + covering.random.uniform(-0.006, 0.006)
+ top = min(slope + 0.02, height + exposure * 2.2)
+ covering.uv_offset = (covering.random.uniform(0, 8), covering.random.uniform(0, 8))
+ covering.variation = covering.random.uniform(0.62, 1.15)
+ gap = 0.0025
+ lower_left = base + axis_along * (start_along + gap) + axis_up * bottom + normal * lift
+ lower_right = base + axis_along * (end_along - gap) + axis_up * (bottom + skew) + normal * lift
+ upper_left = base + axis_along * (start_along + gap) + axis_up * top + normal * 0.002
+ upper_right = base + axis_along * (end_along - gap) + axis_up * top + normal * 0.002
+ under_left = base + axis_along * (start_along + gap) + axis_up * bottom
+ under_right = base + axis_along * (end_along - gap) + axis_up * (bottom + skew)
+ covering.add_face([lower_left, lower_right, upper_right, upper_left], material, uvs=[(0, 0), (end_along - start_along, 0), (end_along - start_along, top - bottom), (0, top - bottom)])
+ covering.add_face([under_left, under_right, lower_right, lower_left], material, uvs=[(0, 0), (end_along - start_along, 0), (end_along - start_along, 0.015), (0, 0.015)])
+ covering.add_face([under_left, lower_left, upper_left], material, uvs=[(0, 0), (0, 0.015), (0.2, 0.015)])
+ covering.add_face([lower_right, under_right, upper_right], material, uvs=[(0, 0), (0, 0.015), (0.2, 0.015)])
+ along += width
+ row += 1
+ height += exposure
+ covering.variation = 1.0
+ covering.uv_offset = (0, 0)
+
+
+def cover_roll(eave_a, eave_b, ridge_a, ridge_b, normal, thickness, covering, plane_data):
+ material = plane_data.get("top_material", "roll_roofing")
+ course = plane_data.get("course", 0.86)
+ length_along = (eave_b - eave_a).length
+ axis_along = (eave_b - eave_a).normalized()
+ slope = (ridge_a - eave_a).length
+ axis_up = (ridge_a - eave_a).normalized()
+ base = eave_a + normal * thickness
+ height = -0.02
+ while height < slope:
+ top = min(slope + 0.02, height + course + 0.08)
+ covering.uv_offset = (covering.random.uniform(0, 8), covering.random.uniform(0, 8))
+ covering.variation = covering.random.uniform(0.85, 1.05)
+ lower_left = base + axis_up * height + normal * 0.006
+ lower_right = lower_left + axis_along * length_along
+ upper_left = base + axis_up * top + normal * 0.003
+ upper_right = upper_left + axis_along * length_along
+ under_left = base + axis_up * height
+ under_right = under_left + axis_along * length_along
+ covering.add_face([lower_left, lower_right, upper_right, upper_left], material)
+ covering.add_face([under_left, under_right, lower_right, lower_left], material)
+ height += course
+ covering.variation = 1.0
+ covering.uv_offset = (0, 0)
+
+
+def build_beam(batch, data):
+ start = Vector(data["a"])
+ end = Vector(data["b"])
+ width = data.get("w", 0.1)
+ depth = data.get("d", 0.2)
+ material = data.get("material", "pine_boards")
+ run = end - start
+ side = run.cross(Vector((0, 0, 1)))
+ if side.length < 1e-6:
+ side = Vector((1, 0, 0))
+ side.normalize()
+ up = side.cross(run).normalized()
+ if up.z < 0:
+ up = -up
+ batch.uv_offset = (batch.random.uniform(0, 6), batch.random.uniform(0, 6))
+ batch.add_box(start - side * (width / 2), run, side * width, up * depth, material)
+ batch.uv_offset = (0, 0)
+
+
+def build_post(batch, data):
+ x_size = data.get("w", 0.1)
+ y_size = data.get("d", x_size)
+ x, y = data["at"]
+ origin = Vector((x - x_size / 2, y - y_size / 2, data["z0"]))
+ batch.uv_offset = (batch.random.uniform(0, 6), batch.random.uniform(0, 6))
+ batch.add_box(origin, Vector((x_size, 0, 0)), Vector((0, y_size, 0)), Vector((0, 0, data["z1"] - data["z0"])), data.get("material", "pine_boards"))
+ batch.uv_offset = (0, 0)
+
+
+def build_stairs(batch, data, default_material):
+ start = Vector((data["start"][0], data["start"][1], data["z0"]))
+ heading = math.radians(data["heading"])
+ forward = Vector((math.cos(heading), math.sin(heading), 0))
+ across = Vector((-forward.y, forward.x, 0))
+ width = data["width"]
+ run = data["run"]
+ rise = data["rise"]
+ material = data.get("material", default_material)
+ riser_material = data.get("riser_material", material)
+ for step in range(data["steps"]):
+ tread_origin = start + forward * (run * step) + across * 0 + Vector((0, 0, rise * (step + 1)))
+ batch.add_box(tread_origin - Vector((0, 0, 0.022)) - forward * 0.02, forward * (run + 0.02), across * width, Vector((0, 0, 0.026)), material)
+ batch.add_box(start + forward * (run * step) + Vector((0, 0, rise * step)), forward * 0.018, across * width, Vector((0, 0, rise - 0.022)), riser_material)
+ length = run * data["steps"]
+ height = rise * data["steps"]
+ for side in (0, width - 0.03):
+ stringer_origin = start + across * side
+ outline = [
+ stringer_origin,
+ stringer_origin + forward * length,
+ stringer_origin + forward * length + Vector((0, 0, height + 0.1)),
+ stringer_origin + Vector((0, 0, 0.12)),
+ ]
+ thick = across * 0.03
+ batch.add_face([outline[0], outline[1], outline[2], outline[3]], material)
+ batch.add_face([point + thick for point in reversed(outline)], material)
+
+
+def build_casework(batch, hardware, data, style):
+ start = Vector((data["a"][0], data["a"][1], 0))
+ end = Vector((data["b"][0], data["b"][1], 0))
+ run = end - start
+ length = run.length
+ along = run.normalized()
+ outward = Vector((-along.y, along.x, 0)) * data.get("side", 1)
+ depth = data.get("depth", 0.58)
+ bottom = data.get("z0", 0.0)
+ top = data.get("z1", 0.86)
+ material = data.get("material", "cabinet_birch")
+ doors = data.get("doors", max(1, round(length / 0.5)))
+ toe = data.get("toe", 0.1 if data.get("kind") == "base" else 0.0)
+ carcass_depth = depth - 0.022
+ batch.uv_offset = (batch.random.uniform(0, 6), batch.random.uniform(0, 6))
+ batch.add_box(start + Vector((0, 0, bottom + toe)), along * length, outward * carcass_depth, Vector((0, 0, top - bottom - toe)), material)
+ if toe > 0:
+ batch.add_box(start + Vector((0, 0, bottom)), along * length, outward * (carcass_depth - 0.05), Vector((0, 0, toe)), "soot")
+ door_width = length / doors
+ gap = 0.003
+ frame = 0.055
+ for index in range(doors):
+ door_start = start + along * (door_width * index + gap)
+ width = door_width - 2 * gap
+ low = bottom + toe + gap
+ high = top - gap
+ plane = outward * carcass_depth
+ thick = outward * 0.018
+ z_size = Vector((0, 0, high - low))
+ origin = door_start + plane + Vector((0, 0, low))
+ batch.variation = batch.random.uniform(0.92, 1.05)
+ batch.add_box(origin, along * frame, thick, z_size, material)
+ batch.add_box(origin + along * (width - frame), along * frame, thick, z_size, material)
+ batch.add_box(origin + along * frame, along * (width - 2 * frame), thick, Vector((0, 0, frame)), material)
+ batch.add_box(origin + along * frame + Vector((0, 0, high - low - frame)), along * (width - 2 * frame), thick, Vector((0, 0, frame)), material)
+ batch.add_box(origin + along * frame + Vector((0, 0, frame)), along * (width - 2 * frame), outward * 0.008, Vector((0, 0, high - low - 2 * frame)), material)
+ batch.variation = 1.0
+ pull_along = width - 0.03 if index % 2 == 0 else 0.03
+ pull_height = low + (0.75 * (high - low) if data.get("kind") == "base" else 0.2 * (high - low))
+ pull_low = origin + along * pull_along + thick + Vector((0, 0, pull_height - low - 0.05))
+ pull_high = pull_low + Vector((0, 0, 0.1))
+ hardware.add_cylinder(pull_low + outward * 0.022, pull_high + outward * 0.022, 0.005, data.get("hardware", "aluminium_dull"), sides=10)
+ hardware.add_cylinder(pull_low, pull_low + outward * 0.024, 0.004, data.get("hardware", "aluminium_dull"), sides=8)
+ hardware.add_cylinder(pull_high, pull_high + outward * 0.024, 0.004, data.get("hardware", "aluminium_dull"), sides=8)
+ batch.uv_offset = (0, 0)
+ if data.get("counter"):
+ nose = 0.03
+ counter_material = data.get("counter_material", style.get("counter", "counter_laminate"))
+ batch.add_box(start - along * data.get("nose_start", 0.0) + Vector((0, 0, top)), along * (length + data.get("nose_start", 0.0) + data.get("nose_end", 0.0)), outward * (depth + nose), Vector((0, 0, 0.032)), counter_material)
+ splash_thickness = -outward * 0.0 + outward * 0.012
+ batch.add_box(start + Vector((0, 0, top + 0.032)), along * length, splash_thickness, Vector((0, 0, 0.1)), counter_material)
+
+
+def build_curtain(batch, data, material):
+ start = Vector((data["a"][0], data["a"][1], 0))
+ end = Vector((data["b"][0], data["b"][1], 0))
+ run = end - start
+ along = run.normalized()
+ across = Vector((-along.y, along.x, 0))
+ length = run.length
+ folds = data.get("folds", max(3, int(length / 0.14)))
+ depth = data.get("depth", 0.045)
+ z_low = data["z0"]
+ z_high = data["z1"]
+ steps = folds * 8
+ rows = 10
+ grid = []
+ for row in range(rows + 1):
+ fraction = row / rows
+ height = z_low + (z_high - z_low) * fraction
+ points = []
+ for step in range(steps + 1):
+ position = step / steps
+ wobble = math.sin(position * folds * 2 * math.pi + 0.8 * math.sin(position * 13.0))
+ flare = depth * (1.0 + 0.5 * (1 - fraction)) * (0.75 + 0.25 * math.sin(position * 7.0 + fraction * 1.4))
+ points.append(start + along * (length * position) + across * (wobble * flare) + Vector((0, 0, height)))
+ grid.append(points)
+ for row in range(rows):
+ for step in range(steps):
+ uvs = [(step * length / steps, row * 0.25), ((step + 1) * length / steps, row * 0.25), ((step + 1) * length / steps, (row + 1) * 0.25), (step * length / steps, (row + 1) * 0.25)]
+ batch.add_face([grid[row][step], grid[row][step + 1], grid[row + 1][step + 1], grid[row + 1][step]], material, uvs=uvs)
+
+
+def build_chimney(batch, data):
+ x_centre, y_centre = data["at"]
+ half_x = data["w"] / 2
+ half_y = data["d"] / 2
+ outline = [(x_centre - half_x, y_centre - half_y), (x_centre + half_x, y_centre - half_y), (x_centre + half_x, y_centre + half_y), (x_centre - half_x, y_centre + half_y)]
+ material = data.get("material", "brick_red")
+ batch.add_prism(outline, data["z0"], data["z1"], material, material_top="soot")
+ cap = data.get("cap", 0.05)
+ grow = 0.035
+ outline_cap = [(x_centre - half_x - grow, y_centre - half_y - grow), (x_centre + half_x + grow, y_centre - half_y - grow), (x_centre + half_x + grow, y_centre + half_y + grow), (x_centre - half_x - grow, y_centre + half_y + grow)]
+ batch.add_prism(outline_cap, data["z1"] - cap * 3, data["z1"] - cap, data.get("cap_material", material), material_top="soot")
+ flue = data.get("flue", 0.18)
+ outline_flue = [(x_centre - flue, y_centre - flue), (x_centre + flue, y_centre - flue), (x_centre + flue, y_centre + flue), (x_centre - flue, y_centre + flue)]
+ batch.add_prism(outline_flue, data["z1"], data["z1"] + 0.09, data.get("flue_material", "soot"), material_top="soot")
+
+
+def build_panelling(batch, data):
+ """Raised wall panels on a flat stretch: rails, stiles and fields sitting proud of the wall."""
+ start = Vector((data["a"][0], data["a"][1], 0))
+ end = Vector((data["b"][0], data["b"][1], 0))
+ along = (end - start).normalized()
+ length = (end - start).length
+ outward = Vector((-along.y, along.x, 0)) * data.get("side", 1)
+ material = data.get("material", "trim_cream")
+ z_low = data["z0"]
+ z_high = data["z1"]
+ columns = data.get("cols", 3)
+ rows = data.get("rows", 2)
+ stile = data.get("stile", 0.09)
+ depth = 0.018
+ origin = start + Vector((0, 0, z_low)) + outward * data.get("offset", 0.0)
+ pane_width = (length - stile * (columns + 1)) / columns
+ pane_height = (z_high - z_low - stile * (rows + 1)) / rows
+ for column in range(columns + 1):
+ batch.add_box(origin + along * (column * (pane_width + stile)), along * stile, outward * depth, Vector((0, 0, z_high - z_low)), material)
+ for row in range(rows + 1):
+ batch.add_box(origin + Vector((0, 0, row * (pane_height + stile))), along * length, outward * depth, Vector((0, 0, stile)), material)
+ for column in range(columns):
+ for row in range(rows):
+ low = origin + along * (stile + column * (pane_width + stile)) + Vector((0, 0, stile + row * (pane_height + stile)))
+ margin = 0.03
+ corners_outer = [low, low + along * pane_width, low + along * pane_width + Vector((0, 0, pane_height)), low + Vector((0, 0, pane_height))]
+ field_origin = low + along * margin + Vector((0, 0, margin)) + outward * (depth * 0.8)
+ corners_inner = [field_origin, field_origin + along * (pane_width - 2 * margin), field_origin + along * (pane_width - 2 * margin) + Vector((0, 0, pane_height - 2 * margin)), field_origin + Vector((0, 0, pane_height - 2 * margin))]
+ order = (0, 1, 2, 3) if data.get("side", 1) < 0 else (3, 2, 1, 0)
+ for index in range(4):
+ first = order[index]
+ second = order[(index + 1) % 4]
+ batch.add_face([corners_outer[first], corners_outer[second], corners_inner[second], corners_inner[first]], material)
+ batch.add_face([corners_inner[index] for index in order], material)
+
+
+def build_fireplace(structure, wall, opening, batch):
+ """Firebox behind a wall opening: brick back and cheeks, soot inside, hearth stone on the floor, plain surround."""
+ floor_z = structure.plan["levels"].get("floor", 0.0)
+ side = opening.get("room_side", 1)
+ depth = opening.get("depth", 0.55)
+ start = opening["from"]
+ finish = opening["to"]
+ head = opening["head"] + floor_z
+ half = wall.t / 2
+ material = opening.get("brick", "brick_red")
+ firebox = opening.get("firebox", 0.5)
+ add_rail(batch, wall, start, finish, -side * firebox, 0, -side * 0.08, floor_z, head + 0.25, material)
+ add_rail(batch, wall, start, start + 0.08, 0, -side * firebox, side * half, floor_z, head, material)
+ add_rail(batch, wall, finish - 0.08, finish, 0, -side * firebox, side * half, floor_z, head, material)
+ add_rail(batch, wall, start, finish, 0, -side * firebox, side * half, head - 0.1, head, "soot")
+ add_rail(batch, wall, start, finish, 0, -side * firebox, side * half, floor_z, floor_z + 0.03, opening.get("hearth", "stone_rubble"))
+ add_rail(batch, wall, start - 0.25, finish + 0.25, side * half, 0, side * depth, floor_z, floor_z + 0.03, opening.get("hearth", "stone_rubble"))
+ add_rail(batch, wall, start, finish, 0, -side * half, side * half, floor_z, floor_z + 0.03, opening.get("hearth", "stone_rubble"))
+ trim_material = opening.get("surround", "trim_cream")
+ add_rail(batch, wall, start - 0.14, start, side * half, 0, side * 0.03, floor_z, head + 0.14, trim_material)
+ add_rail(batch, wall, finish, finish + 0.14, side * half, 0, side * 0.03, floor_z, head + 0.14, trim_material)
+ add_rail(batch, wall, start - 0.14, finish + 0.14, side * half, 0, side * 0.03, head, head + 0.14, trim_material)
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/plan_check.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/plan_check.py
new file mode 100644
index 0000000..9aa602f
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/plan_check.py
@@ -0,0 +1,525 @@
+"""Check a house plan file and overlay it, or the built model, on the source drawing.
+
+Run with: uv run --no-project --with pillow --with numpy --with scipy python plan_check.py <command> plan.json
+
+Commands:
+ check validate the plan file: walls, openings, rooms, circulation, printed dimensions, provenance
+ overlay draw the plan on the source image and score it against the ink
+ asbuilt <section.json> score the wall section cut from the built Blender model, and draw it on the source image
+Exit code 0 means every gate passed. Paths in the plan resolve from the plan file's folder.
+"""
+
+import json
+import math
+import pathlib
+import sys
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+METRES_PER_UNIT = {"m": 1.0, "ft": 0.3048}
+MINIMUM_SCORE = 0.70
+MAXIMUM_BEST_OFFSET_METRES = 0.16
+MAXIMUM_CALIBRATION_ERROR_METRES = 0.12
+DIMENSION_TOLERANCE_METRES = 0.10
+SWEEP_REACH_METRES = 0.60
+SWEEP_STEP_METRES = 0.04
+INK_TOLERANCE_METRES = 0.07
+
+
+def load_plan(plan_path):
+ plan_path = pathlib.Path(plan_path)
+ plan = json.loads(plan_path.read_text(encoding="utf-8"))
+ plan["_folder"] = plan_path.parent
+ plan["_scale"] = METRES_PER_UNIT[plan.get("units", "m")]
+ return plan
+
+
+def distance(point_a, point_b):
+ return math.hypot(point_a[0] - point_b[0], point_a[1] - point_b[1])
+
+
+def closest_on_segment(point, start, end):
+ delta_x = end[0] - start[0]
+ delta_y = end[1] - start[1]
+ length_squared = delta_x * delta_x + delta_y * delta_y
+ if length_squared == 0:
+ return start, 0.0
+ fraction = ((point[0] - start[0]) * delta_x + (point[1] - start[1]) * delta_y) / length_squared
+ fraction = max(0.0, min(1.0, fraction))
+ return (start[0] + fraction * delta_x, start[1] + fraction * delta_y), fraction
+
+
+def point_in_polygon(point, polygon):
+ inside = False
+ count = len(polygon)
+ for index in range(count):
+ x_a, y_a = polygon[index]
+ x_b, y_b = polygon[(index + 1) % count]
+ crosses = (y_a > point[1]) != (y_b > point[1])
+ if crosses and point[0] < (x_b - x_a) * (point[1] - y_a) / (y_b - y_a) + x_a:
+ inside = not inside
+ return inside
+
+
+def polygon_area(polygon):
+ total = 0.0
+ count = len(polygon)
+ for index in range(count):
+ x_a, y_a = polygon[index]
+ x_b, y_b = polygon[(index + 1) % count]
+ total += x_a * y_b - x_b * y_a
+ return abs(total) / 2
+
+
+def wall_frame(wall):
+ start, end = wall["a"], wall["b"]
+ length = distance(start, end)
+ direction = ((end[0] - start[0]) / length, (end[1] - start[1]) / length)
+ normal = (-direction[1], direction[0])
+ return start, direction, normal, length
+
+
+def opening_range(opening):
+ if "from" in opening:
+ return opening["from"], opening["to"]
+ half_width = opening["width"] / 2
+ return opening["at"] - half_width, opening["at"] + half_width
+
+
+def wall_levels(wall):
+ """Storeys a wall stands on: an outer wall may run through several, numbered from 1."""
+ return wall.get("levels") or [wall.get("level", 1)]
+
+
+def room_at(plan, point, level=1):
+ for room in plan.get("rooms", []):
+ if room.get("level", 1) == level and point_in_polygon(point, room["poly"]):
+ return room["name"]
+ return None
+
+
+def check_walls(plan, faults):
+ scale = plan["_scale"]
+ walls = plan.get("walls", [])
+ identifiers = [wall["id"] for wall in walls]
+ for identifier in identifiers:
+ if identifiers.count(identifier) > 1:
+ faults.append(f"wall id {identifier} is used twice")
+ for wall in walls:
+ if distance(wall["a"], wall["b"]) * scale < 0.05:
+ faults.append(f"wall {wall['id']} has no length")
+ thickness = wall["t"] * scale
+ if not 0.04 <= thickness <= 1.2:
+ faults.append(f"wall {wall['id']} is {thickness:.2f} m thick; expected 0.04 to 1.2")
+ if wall.get("free_end"):
+ continue
+ for end_name in ("a", "b"):
+ joined = False
+ for other in walls:
+ if other is wall or not set(wall_levels(wall)) & set(wall_levels(other)):
+ continue
+ nearest, _ = closest_on_segment(wall[end_name], other["a"], other["b"])
+ reach = other["t"] / 2 + 0.12 / scale
+ if distance(wall[end_name], nearest) <= reach:
+ joined = True
+ break
+ if not joined:
+ faults.append(f"wall {wall['id']} end {end_name} touches nothing (mark free_end if it stands alone)")
+
+
+def check_openings(plan, faults):
+ scale = plan["_scale"]
+ walls = {wall["id"]: wall for wall in plan.get("walls", [])}
+ per_wall = {}
+ for opening in plan.get("openings", []):
+ wall = walls.get(opening["wall"])
+ if wall is None:
+ faults.append(f"opening {opening['id']} names missing wall {opening['wall']}")
+ continue
+ start_along, end_along = opening_range(opening)
+ length = distance(wall["a"], wall["b"])
+ if start_along < -0.001 or end_along > length + 0.001 or end_along <= start_along:
+ faults.append(f"opening {opening['id']} runs {start_along:.2f}..{end_along:.2f} on a wall {length:.2f} long")
+ width_metres = (end_along - start_along) * scale
+ head_metres = opening.get("head", 0) * scale
+ sill_metres = opening.get("sill", 0) * scale
+ kind = opening.get("kind")
+ if kind == "door" and not 0.40 <= width_metres <= 2.2:
+ faults.append(f"door {opening['id']} is {width_metres:.2f} m wide")
+ if kind == "door" and not 1.45 <= head_metres - sill_metres <= 2.7:
+ faults.append(f"door {opening['id']} is {head_metres - sill_metres:.2f} m tall")
+ if kind == "window" and head_metres <= sill_metres:
+ faults.append(f"window {opening['id']} head is at or under its sill")
+ per_wall.setdefault(opening["wall"], []).append((start_along, end_along, opening["id"], opening.get("sill", 0), opening.get("head", 0)))
+ for wall_id, spans in per_wall.items():
+ for index, first in enumerate(spans):
+ for second in spans[index + 1:]:
+ overlap_along = first[0] < second[1] - 0.001 and second[0] < first[1] - 0.001
+ overlap_height = first[3] < second[4] and second[3] < first[4]
+ if overlap_along and overlap_height:
+ faults.append(f"openings {first[2]} and {second[2]} overlap on wall {wall_id}")
+
+
+def check_rooms(plan, faults):
+ scale = plan["_scale"]
+ walls = plan.get("walls", [])
+ for room in plan.get("rooms", []):
+ polygon = room["poly"]
+ area = polygon_area(polygon) * scale * scale
+ if area < 0.15:
+ faults.append(f"room {room['name']} has area {area:.2f} m2")
+ printed = room.get("area_printed")
+ if printed is not None and abs(area - printed * scale * scale) > 0.1 * printed * scale * scale:
+ faults.append(f"room {room['name']} area {area:.1f} m2 differs from printed {printed}")
+ open_edges = set(room.get("open_edges", []))
+ count = len(polygon)
+ for index in range(count):
+ if index in open_edges:
+ continue
+ start, end = polygon[index], polygon[(index + 1) % count]
+ middle = ((start[0] + end[0]) / 2, (start[1] + end[1]) / 2)
+ bounded = False
+ for wall in walls:
+ if room.get("level", 1) not in wall_levels(wall):
+ continue
+ nearest, _ = closest_on_segment(middle, wall["a"], wall["b"])
+ if distance(middle, nearest) <= wall["t"] / 2 + 0.2 / scale:
+ bounded = True
+ break
+ if not bounded:
+ faults.append(f"room {room['name']} edge {index} has no wall under it (list it in open_edges if open)")
+
+
+def check_circulation(plan, faults):
+ scale = plan["_scale"]
+ rooms = plan.get("rooms", [])
+ if not rooms:
+ faults.append("plan has no rooms")
+ return
+ walls = {wall["id"]: wall for wall in plan.get("walls", [])}
+ links = {room["name"]: set() for room in rooms}
+ links["outside"] = set()
+ for opening in plan.get("openings", []):
+ if opening.get("kind") not in ("door", "cased") or opening["wall"] not in walls:
+ continue
+ wall = walls[opening["wall"]]
+ start, direction, normal, _ = wall_frame(wall)
+ start_along, end_along = opening_range(opening)
+ middle_along = (start_along + end_along) / 2
+ reach = wall["t"] / 2 + 0.25 / scale
+ centre = (start[0] + direction[0] * middle_along, start[1] + direction[1] * middle_along)
+ level = opening.get("level", wall_levels(wall)[0])
+ left_room = room_at(plan, (centre[0] + normal[0] * reach, centre[1] + normal[1] * reach), level) or "outside"
+ right_room = room_at(plan, (centre[0] - normal[0] * reach, centre[1] - normal[1] * reach), level) or "outside"
+ links[left_room].add(right_room)
+ links[right_room].add(left_room)
+ for room in rooms:
+ for neighbour in room.get("open_to", []):
+ links[room["name"]].add(neighbour)
+ links.setdefault(neighbour, set()).add(room["name"])
+ reached = {"outside"}
+ frontier = ["outside"]
+ while frontier:
+ current = frontier.pop()
+ for neighbour in links.get(current, ()):
+ if neighbour not in reached:
+ reached.add(neighbour)
+ frontier.append(neighbour)
+ for room in rooms:
+ if room["name"] not in reached and not room.get("no_access"):
+ faults.append(f"room {room['name']} cannot be reached from outside (mark no_access for a closed cupboard)")
+
+
+def check_dimensions(plan, faults):
+ scale = plan["_scale"]
+ dimensions = plan.get("printed_dimensions", [])
+ if len(dimensions) < 3:
+ faults.append("list at least 3 printed_dimensions (or scale bar lengths) to tie the plan to the drawing")
+ for dimension in dimensions:
+ measured = distance(dimension["a"], dimension["b"]) * scale
+ printed = dimension["value"] * scale
+ if abs(measured - printed) > DIMENSION_TOLERANCE_METRES:
+ faults.append(f"dimension {dimension.get('label')}: plan {measured:.2f} m, printed {printed:.2f} m")
+
+
+def check_provenance(plan, faults):
+ provenance = plan.get("provenance", {})
+ if not provenance.get("sourced"):
+ faults.append("provenance.sourced is empty: say what the drawing gave")
+ if not provenance.get("inferred"):
+ faults.append("provenance.inferred is empty: say what you inferred (roof, facade, heights, finishes)")
+ source = plan.get("source", {})
+ for key in ("image", "url", "license"):
+ if not source.get(key):
+ faults.append(f"source.{key} is missing")
+
+
+def run_check(plan):
+ faults = []
+ check_walls(plan, faults)
+ check_openings(plan, faults)
+ check_rooms(plan, faults)
+ check_circulation(plan, faults)
+ check_dimensions(plan, faults)
+ check_provenance(plan, faults)
+ print(f"{len(plan.get('walls', []))} walls, {len(plan.get('openings', []))} openings, {len(plan.get('rooms', []))} rooms")
+ for fault in faults:
+ print("FAULT", fault)
+ print("check", "FAILED" if faults else "passed")
+ return not faults
+
+
+def fit_affine(pairs):
+ import numpy
+
+ plan_points = numpy.array([[pair["plan"][0], pair["plan"][1], 1.0] for pair in pairs])
+ pixel_points = numpy.array([pair["px"] for pair in pairs], dtype=float)
+ solution, _, _, _ = numpy.linalg.lstsq(plan_points, pixel_points, rcond=None)
+ residuals = plan_points @ solution - pixel_points
+ return solution, numpy.sqrt((residuals ** 2).sum(axis=1).mean())
+
+
+def to_pixels(matrix, point):
+ return (
+ matrix[0][0] * point[0] + matrix[1][0] * point[1] + matrix[2][0],
+ matrix[0][1] * point[0] + matrix[1][1] * point[1] + matrix[2][1],
+ )
+
+
+def load_ink(plan):
+ import numpy
+ from PIL import Image
+ from scipy import ndimage
+
+ Image.MAX_IMAGE_PIXELS = None
+ image = Image.open(plan["_folder"] / plan["source"]["image"]).convert("L")
+ grey = numpy.asarray(image, dtype=float)
+ threshold = plan.get("calibration", {}).get("ink_threshold")
+ if threshold is None:
+ threshold = (numpy.percentile(grey, 2) + numpy.percentile(grey, 60)) / 2
+ ink = grey < threshold
+ distance_to_ink = ndimage.distance_transform_edt(~ink)
+ return image, ink, distance_to_ink
+
+
+def score_samples(samples_by_group, matrix, distance_to_ink, pixels_per_metre, shift=(0.0, 0.0)):
+ """Fraction of sample points with ink within the tolerance, per group and overall."""
+ import numpy
+
+ height, width = distance_to_ink.shape
+ tolerance_pixels = INK_TOLERANCE_METRES * pixels_per_metre
+ group_scores = {}
+ total_hits = 0
+ total_count = 0
+ for group, points in samples_by_group.items():
+ hits = 0
+ for point in points:
+ pixel = to_pixels(matrix, (point[0] + shift[0], point[1] + shift[1]))
+ column = int(pixel[0])
+ row = int(pixel[1])
+ if 0 <= row < height and 0 <= column < width and distance_to_ink[row, column] <= tolerance_pixels:
+ hits += 1
+ group_scores[group] = hits / max(1, len(points))
+ total_hits += hits
+ total_count += len(points)
+ return total_hits / max(1, total_count), group_scores
+
+
+def sample_segment(start, end, step, offset=0.0):
+ length = distance(start, end)
+ count = max(2, int(length / step))
+ normal = (-(end[1] - start[1]) / max(length, 1e-9), (end[0] - start[0]) / max(length, 1e-9))
+ return [
+ (
+ start[0] + (end[0] - start[0]) * index / (count - 1) + normal[0] * offset,
+ start[1] + (end[1] - start[1]) * index / (count - 1) + normal[1] * offset,
+ )
+ for index in range(count)
+ ]
+
+
+def sheet_offset(plan, wall):
+ """Upper floors are drawn beside the first floor on the sheet: how far, in plan units."""
+ offsets = plan.get("calibration", {}).get("level_offsets", {})
+ return offsets.get(str(wall_levels(wall)[0]), [0.0, 0.0])
+
+
+def wall_face_samples(plan):
+ """Sample points on each wall's faces, skipping its openings, in plan units."""
+ scale = plan["_scale"]
+ step = 0.05 / scale
+ openings_by_wall = {}
+ for opening in plan.get("openings", []):
+ openings_by_wall.setdefault(opening["wall"], []).append(opening_range(opening))
+ samples = {}
+ for wall in plan["walls"]:
+ if wall.get("dashed"):
+ continue
+ start, direction, normal, length = wall_frame(wall)
+ sheet_x, sheet_y = sheet_offset(plan, wall)
+ start = (start[0] + sheet_x, start[1] + sheet_y)
+ points = []
+ along = 0.0
+ while along <= length:
+ blocked = any(left < along < right for left, right in openings_by_wall.get(wall["id"], []))
+ if not blocked:
+ for side in (-1, 1):
+ offset = side * wall["t"] / 2
+ points.append((start[0] + direction[0] * along + normal[0] * offset, start[1] + direction[1] * along + normal[1] * offset))
+ along += step
+ samples[wall["id"]] = points
+ return samples
+
+
+def sweep_best_offset(samples, matrix, distance_to_ink, pixels_per_metre, scale):
+ best_score = -1.0
+ best_shift = (0.0, 0.0)
+ reach = int(SWEEP_REACH_METRES / SWEEP_STEP_METRES)
+ thinned = {group: points[::3] for group, points in samples.items()}
+ for step_x in range(-reach, reach + 1):
+ for step_y in range(-reach, reach + 1):
+ shift = (step_x * SWEEP_STEP_METRES / scale, step_y * SWEEP_STEP_METRES / scale)
+ score, _ = score_samples(thinned, matrix, distance_to_ink, pixels_per_metre, shift)
+ better = score > best_score + 1e-6
+ nearer = abs(score - best_score) <= 1e-6 and math.hypot(*shift) < math.hypot(*best_shift)
+ if better or nearer:
+ best_score = score
+ best_shift = shift
+ return best_score, (best_shift[0] * scale, best_shift[1] * scale)
+
+
+def report_score(label, samples, matrix, distance_to_ink, pixels_per_metre, plan):
+ scale = plan["_scale"]
+ score, group_scores = score_samples(samples, matrix, distance_to_ink, pixels_per_metre)
+ best_score, best_offset = sweep_best_offset(samples, matrix, distance_to_ink, pixels_per_metre, scale)
+ far_shift = (0.5 / scale, 0.5 / scale)
+ shifted_score, _ = score_samples(samples, matrix, distance_to_ink, pixels_per_metre, far_shift)
+ print(f"{label}: {score:.3f} of faces on ink; 0.5 m shifted control {shifted_score:.3f}")
+ print(f" best offset {best_offset[0]:+.2f}, {best_offset[1]:+.2f} m scoring {best_score:.3f}")
+ worst = sorted(group_scores.items(), key=lambda item: item[1])[:6]
+ print(" worst:", ", ".join(f"{group} {value:.2f}" for group, value in worst))
+ passed = score >= MINIMUM_SCORE
+ passed = passed and math.hypot(*best_offset) <= MAXIMUM_BEST_OFFSET_METRES
+ passed = passed and score > shifted_score + 0.1
+ print(f" {label}", "passed" if passed else "FAILED")
+ return passed
+
+
+def calibrated(plan):
+ scale = plan["_scale"]
+ matrix, rms_pixels = fit_affine(plan["calibration"]["pairs"])
+ pixels_per_metre = math.hypot(matrix[0][0], matrix[0][1]) / scale
+ error_metres = rms_pixels / pixels_per_metre
+ print(f"calibration: {pixels_per_metre:.1f} px per metre, error {error_metres * 100:.1f} cm")
+ return matrix, pixels_per_metre, error_metres <= MAXIMUM_CALIBRATION_ERROR_METRES
+
+
+def crop_box(plan, matrix, margin_units):
+ corners = []
+ for wall in plan["walls"]:
+ corners.append(to_pixels(matrix, (wall["a"][0], wall["a"][1])))
+ corners.append(to_pixels(matrix, (wall["b"][0], wall["b"][1])))
+ margin = margin_units * math.hypot(matrix[0][0], matrix[0][1])
+ return (
+ int(min(corner[0] for corner in corners) - margin),
+ int(min(corner[1] for corner in corners) - margin),
+ int(max(corner[0] for corner in corners) + margin),
+ int(max(corner[1] for corner in corners) + margin),
+ )
+
+
+def save_overlay(plan, image, layer, matrix, name):
+ from PIL import Image
+
+ base = image.convert("RGBA")
+ merged = Image.alpha_composite(base, layer)
+ box = crop_box(plan, matrix, 2.0 / plan["_scale"])
+ box = (max(0, box[0]), max(0, box[1]), min(merged.width, box[2]), min(merged.height, box[3]))
+ merged = merged.crop(box).convert("RGB")
+ merged.thumbnail((2400, 2400))
+ target = plan["_folder"] / name
+ merged.save(target)
+ print("wrote", target)
+
+
+def run_overlay(plan):
+ from PIL import Image, ImageDraw
+
+ matrix, pixels_per_metre, calibration_ok = calibrated(plan)
+ image, _, distance_to_ink = load_ink(plan)
+ samples = wall_face_samples(plan)
+ passed = report_score("plan overlay", samples, matrix, distance_to_ink, pixels_per_metre, plan) and calibration_ok
+ layer = Image.new("RGBA", image.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(layer)
+ for wall in plan["walls"]:
+ start, direction, normal, _ = wall_frame(wall)
+ half = wall["t"] / 2
+ end = wall["b"]
+ corners = [
+ (start[0] + normal[0] * half, start[1] + normal[1] * half),
+ (end[0] + normal[0] * half, end[1] + normal[1] * half),
+ (end[0] - normal[0] * half, end[1] - normal[1] * half),
+ (start[0] - normal[0] * half, start[1] - normal[1] * half),
+ ]
+ draw.polygon([to_pixels(matrix, corner) for corner in corners], fill=(230, 20, 120, 110))
+ walls = {wall["id"]: wall for wall in plan["walls"]}
+ for opening in plan.get("openings", []):
+ wall = walls[opening["wall"]]
+ start, direction, normal, _ = wall_frame(wall)
+ left, right = opening_range(opening)
+ half = wall["t"] / 2
+ corners = []
+ for along, side in ((left, 1), (right, 1), (right, -1), (left, -1)):
+ corners.append((start[0] + direction[0] * along + normal[0] * side * half, start[1] + direction[1] * along + normal[1] * side * half))
+ colour = (20, 110, 240, 170) if opening.get("kind") == "window" else (20, 200, 90, 170)
+ draw.polygon([to_pixels(matrix, corner) for corner in corners], fill=colour)
+ save_overlay(plan, image, layer, matrix, "check_plan_overlay.png")
+ print("overlay", "passed" if passed else "FAILED")
+ return passed
+
+
+def run_asbuilt(plan, section_path):
+ from PIL import Image, ImageDraw
+
+ scale = plan["_scale"]
+ matrix, pixels_per_metre, calibration_ok = calibrated(plan)
+ image, _, distance_to_ink = load_ink(plan)
+ section = json.loads(pathlib.Path(section_path).read_text(encoding="utf-8"))
+ samples = {}
+ layer = Image.new("RGBA", image.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(layer)
+ dashed = {f"wall_{wall['id']}" for wall in plan["walls"] if wall.get("dashed")}
+ walls_by_group = {f"wall_{wall['id']}": wall for wall in plan["walls"]}
+ for group, segments in section["segments"].items():
+ if group in dashed:
+ continue
+ sheet_x, sheet_y = sheet_offset(plan, walls_by_group[group]) if group in walls_by_group else (0.0, 0.0)
+ points = []
+ for segment in segments:
+ start = (segment[0] / scale + sheet_x, segment[1] / scale + sheet_y)
+ end = (segment[2] / scale + sheet_x, segment[3] / scale + sheet_y)
+ draw.line([to_pixels(matrix, start), to_pixels(matrix, end)], fill=(230, 20, 120, 255), width=max(3, int(pixels_per_metre * 0.02)))
+ points.extend(sample_segment(start, end, 0.05 / scale))
+ samples[group] = points
+ passed = report_score("as-built section", samples, matrix, distance_to_ink, pixels_per_metre, plan) and calibration_ok
+ save_overlay(plan, image, layer, matrix, "check_asbuilt_overlay.png")
+ print("as-built", "passed" if passed else "FAILED")
+ return passed
+
+
+def main():
+ command = sys.argv[1]
+ plan = load_plan(sys.argv[2])
+ if command == "check":
+ passed = run_check(plan)
+ elif command == "overlay":
+ passed = run_overlay(plan)
+ elif command == "asbuilt":
+ passed = run_asbuilt(plan, sys.argv[3])
+ else:
+ print(__doc__)
+ passed = False
+ sys.exit(0 if passed else 1)
+
+
+main()
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/preview_assets.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/preview_assets.py
new file mode 100644
index 0000000..3c348a4
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/preview_assets.py
@@ -0,0 +1,101 @@
+"""Render a labelled grid of candidate models and print their native sizes, to look at them before placing them.
+
+Run: blender -b --factory-startup -P preview_assets.py -- <output.png> <objaverse-folder> <asset> [<asset> ...]
+Assets are ph:<Poly Haven id> or obj:<Objaverse uid>. Cells read left to right, top to bottom, in the order given.
+"""
+
+import math
+import os
+import pathlib
+import sys
+
+import bpy
+from mathutils import Vector
+
+LIBRARY = pathlib.Path(os.environ.get("HOUSE_ASSET_LIBRARY", pathlib.Path.home() / "house-assets"))
+CELL_SPACING = 2.4
+COLUMNS = 5
+
+
+def asset_file(asset, objaverse_folder):
+ kind, name = asset.split(":", 1)
+ if kind == "ph":
+ matches = sorted((LIBRARY / "models" / name).glob("*.gltf"))
+ return matches[0] if matches else None
+ return pathlib.Path(objaverse_folder) / f"{name}.glb"
+
+
+def place_in_cell(asset, index, objaverse_folder):
+ path = asset_file(asset, objaverse_folder)
+ if path is None or not path.exists():
+ print(f"{index:2d} {asset} MISSING")
+ return
+ existing = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=str(path))
+ imported = [item for item in bpy.data.objects if item not in existing]
+ bpy.context.view_layer.update()
+ corners = [item.matrix_world @ Vector(corner) for item in imported if item.type == "MESH" for corner in item.bound_box]
+ low = Vector((min(c.x for c in corners), min(c.y for c in corners), min(c.z for c in corners)))
+ high = Vector((max(c.x for c in corners), max(c.y for c in corners), max(c.z for c in corners)))
+ size = high - low
+ triangles = sum(len(item.data.polygons) for item in imported if item.type == "MESH")
+ print(f"{index:2d} {asset} size_m x={size.x:.2f} y={size.y:.2f} z={size.z:.2f} faces={triangles}")
+ scale = 1.9 / max(size)
+ holder = bpy.data.objects.new(f"holder_{index}", None)
+ bpy.context.scene.collection.objects.link(holder)
+ roots = [item for item in imported if item.parent is None]
+ centre = (low + high) / 2
+ for root in roots:
+ root.parent = holder
+ root.location = root.location - Vector((centre.x, centre.y, low.z))
+ holder.scale = (scale, scale, scale)
+ holder.location = ((index % COLUMNS) * CELL_SPACING, -(index // COLUMNS) * CELL_SPACING, 0)
+
+
+def main():
+ arguments = sys.argv[sys.argv.index("--") + 1:]
+ output = arguments[0]
+ objaverse_folder = arguments[1]
+ assets = arguments[2:]
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ for index, asset in enumerate(assets):
+ place_in_cell(asset, index, objaverse_folder)
+ rows = math.ceil(len(assets) / COLUMNS)
+ bpy.ops.mesh.primitive_plane_add(size=60, location=(CELL_SPACING * 2, -CELL_SPACING * (rows - 1) / 2, 0))
+ world = bpy.data.worlds.new("studio")
+ world.use_nodes = True
+ world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.8, 0.8, 0.8, 1)
+ world.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.0
+ bpy.context.scene.world = world
+ sun = bpy.data.lights.new("sun", "SUN")
+ sun.energy = 2.5
+ sun.angle = 0.3
+ lamp = bpy.data.objects.new("sun", sun)
+ bpy.context.scene.collection.objects.link(lamp)
+ lamp.rotation_euler = (0.8, 0.2, 0.6)
+ camera_data = bpy.data.cameras.new("camera")
+ camera_data.type = "ORTHO"
+ camera_data.ortho_scale = max(COLUMNS, rows * 4 / 3) * CELL_SPACING * 1.05
+ camera = bpy.data.objects.new("camera", camera_data)
+ bpy.context.scene.collection.objects.link(camera)
+ middle = Vector((CELL_SPACING * (COLUMNS - 1) / 2, -CELL_SPACING * (rows - 1) / 2, 0.7))
+ camera.location = middle + Vector((-14, -24, 16))
+ camera.rotation_euler = (middle - camera.location).to_track_quat("-Z", "Y").to_euler()
+ scene = bpy.context.scene
+ scene.camera = camera
+ scene.render.engine = "CYCLES"
+ preferences = bpy.context.preferences.addons["cycles"].preferences
+ preferences.compute_device_type = "OPTIX"
+ preferences.get_devices()
+ for device in preferences.devices:
+ device.use = device.type == "OPTIX"
+ scene.cycles.device = "GPU"
+ scene.cycles.samples = 32
+ scene.cycles.use_denoising = True
+ scene.render.resolution_x = 1600
+ scene.render.resolution_y = 1200
+ scene.render.filepath = output
+ bpy.ops.render.render(write_still=True)
+
+
+main()
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/render_house.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/render_house.py
new file mode 100644
index 0000000..bf94a76
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/render_house.py
@@ -0,0 +1,680 @@
+"""Render stills, a cutaway or a walkthrough from a house .blend made by build_house.py.
+
+Run: blender -b <house.blend> -P render_house.py -- <plan.json> <output-folder> [--shots a,b] [--samples N]
+ [--scale 50] [--film name] [--frames N]
+Shots and walks are listed in the plan. Paths are written by Cycles with OptiX, denoised with OIDN.
+"""
+
+import json
+import math
+import os
+import pathlib
+import sys
+import tempfile
+
+import bmesh
+import bpy
+from mathutils import Matrix, Vector
+
+METRES_PER_UNIT = {"m": 1.0, "ft": 0.3048}
+LIBRARY = pathlib.Path(os.environ.get("HOUSE_ASSET_LIBRARY", pathlib.Path.home() / "house-assets"))
+# Scene-linear median an interior shot is metered to: a little above mid grey, because rooms are mostly pale.
+INTERIOR_METER_TARGET = 0.2
+
+
+options_plan_folder = "."
+
+
+def read_arguments():
+ arguments = sys.argv[sys.argv.index("--") + 1:]
+ options = {"plan": arguments[0], "out": arguments[1], "shots": None, "samples": 512, "scale": 100, "film": None, "frames": None}
+ index = 2
+ while index < len(arguments):
+ name = arguments[index].lstrip("-")
+ value = arguments[index + 1]
+ options[name] = value
+ index += 2
+ return options
+
+
+def setup_cycles(samples, scale_percent):
+ scene = bpy.context.scene
+ scene.render.engine = "CYCLES"
+ cycles = scene.cycles
+ preferences = bpy.context.preferences.addons["cycles"].preferences
+ preferences.compute_device_type = "OPTIX"
+ preferences.get_devices()
+ for device in preferences.devices:
+ device.use = device.type == "OPTIX"
+ cycles.device = "GPU"
+ cycles.samples = samples
+ cycles.use_adaptive_sampling = True
+ cycles.adaptive_threshold = 0.012
+ cycles.use_denoising = True
+ cycles.denoiser = "OPENIMAGEDENOISE"
+ cycles.denoising_input_passes = "RGB_ALBEDO_NORMAL"
+ cycles.denoising_use_gpu = True
+ cycles.max_bounces = 10
+ cycles.diffuse_bounces = 8
+ cycles.glossy_bounces = 4
+ cycles.transmission_bounces = 8
+ cycles.transparent_max_bounces = 8
+ cycles.sample_clamp_indirect = 8.0
+ cycles.caustics_reflective = False
+ cycles.caustics_refractive = False
+ cycles.blur_glossy = 0.5
+ scene.render.resolution_x = 1920
+ scene.render.resolution_y = 1080
+ scene.render.resolution_percentage = scale_percent
+ # Grass and scanned trees take minutes to sync; keep them between shots.
+ scene.render.use_persistent_data = True
+ scene.render.image_settings.file_format = "PNG"
+ scene.render.image_settings.color_mode = "RGB"
+ scene.render.film_transparent = False
+ scene.view_settings.view_transform = "AgX"
+ scene.view_settings.look = "AgX - Medium High Contrast"
+
+
+def find_sun_azimuth(image):
+ """Azimuth of the brightest spot in an equirectangular sky, in radians, measured as world rotation zero sees it."""
+ import numpy
+
+ width, height = image.size
+ pixels = numpy.empty(width * height * 4, dtype=numpy.float32)
+ image.pixels.foreach_get(pixels)
+ pixels = pixels.reshape(height, width, 4)
+ luminance = pixels[:, :, 0] * 0.2 + pixels[:, :, 1] * 0.7 + pixels[:, :, 2] * 0.1
+ row, column = numpy.unravel_index(numpy.argmax(luminance), luminance.shape)
+ return (column / width) * 2 * math.pi
+
+
+def setup_world(site):
+ world = bpy.data.worlds.new("sky")
+ bpy.context.scene.world = world
+ world.use_nodes = True
+ tree = world.node_tree
+ background = tree.nodes["Background"]
+ coordinates = tree.nodes.new("ShaderNodeTexCoord")
+ mapping = tree.nodes.new("ShaderNodeMapping")
+ environment = tree.nodes.new("ShaderNodeTexEnvironment")
+ hdri = site.get("hdri", "kloofendal_48d_partly_cloudy_puresky")
+ matches = sorted((LIBRARY / "hdri").glob(f"{hdri}_*k.hdr"))
+ environment.image = bpy.data.images.load(str(matches[-1]), check_existing=True)
+ tree.links.new(coordinates.outputs["Generated"], mapping.inputs["Vector"])
+ tree.links.new(mapping.outputs["Vector"], environment.inputs["Vector"])
+ # The sky's own sun is clamped away so that the sun lamp alone casts the sharp shadow.
+ clamp = tree.nodes.new("ShaderNodeVectorMath")
+ clamp.operation = "MINIMUM"
+ clamp.inputs[1].default_value = (site.get("sky_clamp", 12.0),) * 3
+ tree.links.new(environment.outputs["Color"], clamp.inputs[0])
+ tree.links.new(clamp.outputs["Vector"], background.inputs["Color"])
+ background.inputs["Strength"].default_value = site.get("sky_strength", 1.0)
+
+ sun_data = site.get("sun", {})
+ azimuth = math.radians(sun_data.get("azimuth", 135.0))
+ elevation = math.radians(sun_data.get("elevation", 40.0))
+ hdri_sun = find_sun_azimuth(environment.image)
+ # In Blender's equirect mapping, u = 0.5 looks along -Y; the texture rotates opposite the world.
+ sky_azimuth = hdri_sun - math.pi / 2
+ mapping.inputs["Rotation"].default_value[2] = sky_azimuth - azimuth
+ sun = bpy.data.lights.new("sun", "SUN")
+ sun.energy = sun_data.get("strength", 4.5)
+ sun.angle = math.radians(sun_data.get("angle", 1.2))
+ sun.color = sun_data.get("colour", (1.0, 0.93, 0.84))
+ lamp = bpy.data.objects.new("sun", sun)
+ bpy.context.scene.collection.objects.link(lamp)
+ direction = Vector((math.cos(elevation) * math.cos(azimuth), math.cos(elevation) * math.sin(azimuth), math.sin(elevation)))
+ lamp.rotation_euler = direction.to_track_quat("Z", "Y").to_euler()
+
+
+def add_lamps(plan, scale):
+ floor = plan["levels"].get("floor", 0.0) * scale
+ for index, lamp in enumerate(plan.get("lamps", [])):
+ kind = lamp.get("kind", "POINT")
+ data = bpy.data.lights.new(f"lamp_{index}", kind)
+ data.energy = lamp.get("watts", 25)
+ data.color = lamp.get("colour", (1.0, 0.72, 0.46))
+ if kind == "POINT":
+ data.shadow_soft_size = lamp.get("soft", 0.06)
+ created = bpy.data.objects.new(f"lamp_{index}", data)
+ bpy.context.scene.collection.objects.link(created)
+ created.location = (lamp["at"][0] * scale, lamp["at"][1] * scale, floor + lamp["z"] * scale)
+
+
+DEFAULT_WINDOW_SKY = 1.0
+
+
+def add_window_portals(plan, scale):
+ """A soft lamp filling each window with the sky's brightness, seen only by what the window lights.
+
+ Sky portals changed nothing here, even flipped (measured on the Holten hall), so rooms depended on stray bounces
+ finding a window: 1 pixel in 2 stayed black at 32 samples and the denoiser smeared walls into foil.
+ """
+ sky_radiance = plan.get("site", {}).get("window_sky", DEFAULT_WINDOW_SKY)
+ walls = {wall["id"]: wall for wall in plan["walls"]}
+ floor = plan["levels"].get("floor", 0.0) * scale
+ created = []
+ for opening in plan.get("openings", []):
+ if opening.get("kind") != "window":
+ continue
+ wall = walls[opening["wall"]]
+ side = wall.get("outside")
+ if not side:
+ continue
+ start = Vector(wall["a"]) * scale
+ end = Vector(wall["b"]) * scale
+ direction = (end - start).normalized()
+ normal = Vector((-direction.y, direction.x))
+ left = opening["from"] if "from" in opening else opening["at"] - opening["width"] / 2
+ right = opening["to"] if "to" in opening else opening["at"] + opening["width"] / 2
+ middle = start + direction * ((left + right) / 2 * scale)
+ sill = opening.get("sill", 0.0) * scale + floor
+ head = opening["head"] * scale + floor
+ data = bpy.data.lights.new(f"portal_{opening['id']}", "AREA")
+ data.shape = "RECTANGLE"
+ data.size = (right - left) * scale
+ data.size_y = head - sill
+ data.energy = sky_radiance * (right - left) * scale * (head - sill) * math.pi
+ data.color = (0.95, 0.97, 1.0)
+ portal = bpy.data.objects.new(data.name, data)
+ bpy.context.scene.collection.objects.link(portal)
+ outward = normal * side
+ position = middle - outward * (wall["t"] * scale / 2 + 0.03)
+ portal.location = (position.x, position.y, (sill + head) / 2)
+ inward = Vector((-outward.x, -outward.y, 0))
+ portal.rotation_euler = (-inward).to_track_quat("Z", "Y").to_euler()
+ portal.visible_camera = False
+ # Seen in the panes, these show as white rectangles over the view outside.
+ portal.visible_glossy = False
+ portal.visible_transmission = False
+ created.append(portal)
+ return created
+
+
+def apply_cut(height, plan):
+ """Slice everything at a height, cap the wall cuts in dark poché, hide what stands above."""
+ section_material = bpy.data.materials.get("wall_section")
+ if section_material is None:
+ section_material = bpy.data.materials.new("wall_section")
+ section_material.use_nodes = True
+ section_material.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.012, 0.012, 0.014, 1)
+ graph = bpy.context.evaluated_depsgraph_get()
+ # Upper storeys' floors go too, or they lie over the rooms the cut is meant to show.
+ names = ("walls", "floors", "facade", "frame", "fitted")
+ for name in names:
+ for item in list(bpy.data.collections[name].objects):
+ if item.type != "MESH":
+ continue
+ evaluated = item.evaluated_get(graph)
+ mesh = bpy.data.meshes.new_from_object(evaluated)
+ work = bmesh.new()
+ work.from_mesh(mesh)
+ result = bmesh.ops.bisect_plane(
+ work,
+ geom=work.verts[:] + work.edges[:] + work.faces[:],
+ plane_co=(0, 0, height),
+ plane_no=(0, 0, 1),
+ clear_outer=True,
+ )
+ if name == "walls":
+ cut_edges = [element for element in result["geom_cut"] if isinstance(element, bmesh.types.BMEdge)]
+ filled = bmesh.ops.holes_fill(work, edges=cut_edges, sides=64)
+ if section_material.name not in [slot.name for slot in mesh.materials if slot]:
+ mesh.materials.append(section_material)
+ index = len(mesh.materials) - 1
+ for face in filled["faces"]:
+ face.material_index = index
+ work.to_mesh(mesh)
+ work.free()
+ item.modifiers.clear()
+ item.data = mesh
+ for name in ("roof", "ceilings"):
+ bpy.data.collections[name].hide_render = True
+ for item in bpy.data.collections["furnish"].objects:
+ if item.location.z > height:
+ item.hide_render = True
+ for item in bpy.data.objects:
+ if item.type == "LIGHT" and item.name.startswith("lamp_"):
+ item.hide_render = True
+
+
+def camera_for(shot, scale, name="camera"):
+ data = bpy.data.cameras.new(name)
+ data.lens = shot.get("lens", 28)
+ data.sensor_width = 36
+ data.clip_start = 0.05
+ data.clip_end = 900
+ created = bpy.data.objects.new(name, data)
+ bpy.context.scene.collection.objects.link(created)
+ aim_camera(created, shot, scale)
+ bpy.context.scene.camera = created
+ return created
+
+
+def aim_camera(camera, shot, scale):
+ """Point a camera; with level on, verticals stay vertical and the view height comes from lens shift."""
+ position = Vector(shot["pos"]) * scale
+ target = Vector(shot["look"]) * scale
+ camera.location = position
+ view = target - position
+ data = camera.data
+ if shot.get("level", True):
+ flat = Vector((view.x, view.y, 0))
+ distance = flat.length
+ aspect = 16 / 9
+ data.shift_y = (view.z / distance) * data.lens / data.sensor_width * aspect / aspect
+ view = flat
+ else:
+ data.shift_y = 0
+ camera.rotation_euler = view.to_track_quat("-Z", "Y").to_euler()
+
+
+def meter_pixels():
+ """A small, fast, linear render of the current view."""
+ import numpy
+
+ scene = bpy.context.scene
+ settings = scene.render.image_settings
+ saved = (scene.render.resolution_percentage, scene.cycles.samples, scene.cycles.use_denoising, settings.file_format, settings.color_mode, settings.color_depth, scene.render.filepath)
+ scene.render.resolution_percentage = 12
+ scene.cycles.samples = 24
+ scene.cycles.use_denoising = False
+ settings.file_format = "OPEN_EXR"
+ settings.color_mode = "RGB"
+ settings.color_depth = "32"
+ meter_path = pathlib.Path(tempfile.gettempdir()) / f"house_meter_{os.getpid()}.exr"
+ scene.render.filepath = str(meter_path)
+ bpy.ops.render.render(write_still=True)
+ image = bpy.data.images.load(str(meter_path))
+ width, height = image.size
+ pixels = numpy.empty(width * height * image.channels, dtype=numpy.float32)
+ image.pixels.foreach_get(pixels)
+ pixels = pixels.reshape(height, width, image.channels)
+ bpy.data.images.remove(image)
+ meter_path.unlink(missing_ok=True)
+ scene.render.resolution_percentage, scene.cycles.samples, scene.cycles.use_denoising, settings.file_format, settings.color_mode, settings.color_depth, scene.render.filepath = saved
+ return pixels
+
+
+def meter_exposure(target):
+ """Stops that bring the median of the view to a target level, the way a camera meters a room."""
+ import numpy
+
+ pixels = meter_pixels()
+ luminance = pixels[:, :, 0] * 0.2126 + pixels[:, :, 1] * 0.7152 + pixels[:, :, 2] * 0.0722
+ median = max(float(numpy.median(luminance)), 1e-4)
+ stops = max(-3.0, min(8.0, math.log2(target / median)))
+ print(f"metered median {median:.4f}, {stops:+.2f} stops", flush=True)
+ return stops
+
+
+def render_to(path):
+ bpy.context.scene.render.filepath = str(path)
+ bpy.ops.render.render(write_still=True)
+ print("rendered", path, flush=True)
+
+
+def catmull(points, fraction):
+ count = len(points)
+ position = fraction * (count - 1)
+ index = min(int(position), count - 2)
+ local = position - index
+ p0 = points[max(0, index - 1)]
+ p1 = points[index]
+ p2 = points[index + 1]
+ p3 = points[min(count - 1, index + 2)]
+ return 0.5 * ((2 * p1) + (p2 - p0) * local + (2 * p0 - 5 * p1 + 4 * p2 - p3) * local ** 2 + (3 * p1 - p0 - 3 * p2 + p3) * local ** 3)
+
+
+def eased(fraction):
+ return fraction * fraction * (3 - 2 * fraction)
+
+
+SHEET_MAX_PIXELS = 6000
+
+
+def plan_sheet_corners(plan, scale):
+ """World corners of the source sheet, from the same pixel-to-plan pairs the overlay check uses."""
+ import numpy
+
+ pairs = plan["calibration"]["pairs"]
+ plan_points = numpy.array([[pair["plan"][0], pair["plan"][1], 1.0] for pair in pairs])
+ pixel_points = numpy.array([pair["px"] for pair in pairs], dtype=float)
+ to_pixels, _, _, _ = numpy.linalg.lstsq(plan_points, pixel_points, rcond=None)
+ linear = to_pixels[:2, :2].T
+ offset = to_pixels[2, :2]
+ inverse = numpy.linalg.inv(linear)
+ source = pathlib.Path(options_plan_folder) / plan["source"]["image"]
+ image = bpy.data.images.load(str(source), check_existing=True)
+ width, height = image.size
+ if max(width, height) > SHEET_MAX_PIXELS:
+ shrink = SHEET_MAX_PIXELS / max(width, height)
+ image.scale(int(width * shrink), int(height * shrink))
+ # The fit above is in the original pixels, so corners stay computed from the original size.
+ # Image rows run down, UV rows run up.
+ corners = []
+ for pixel, uv in (((0, height), (0, 0)), ((width, height), (1, 0)), ((width, 0), (1, 1)), ((0, 0), (0, 1))):
+ planned = inverse @ (numpy.array(pixel, dtype=float) - offset)
+ corners.append((Vector((planned[0] * scale, planned[1] * scale, 0.0)), uv))
+ return image, corners
+
+
+def add_plan_sheet(plan, scale, shift=(0.0, 0.0)):
+ """The drawing itself lying on a clean floor, lined up with the walls that will rise from it."""
+ image, corners = plan_sheet_corners(plan, scale)
+ floor_level = plan["levels"].get("floor", 0.0) * scale + 0.004
+ shifted = [(corner + Vector((shift[0], shift[1], floor_level)), uv) for corner, uv in corners]
+ mesh = bpy.data.meshes.new("plan_sheet")
+ mesh.from_pydata([tuple(corner) for corner, _ in shifted], [], [(0, 1, 2, 3)])
+ uv_layer = mesh.uv_layers.new(name="UVMap")
+ for index, (_, uv) in enumerate(shifted):
+ uv_layer.data[index].uv = uv
+ material = bpy.data.materials.new("plan_paper")
+ material.use_nodes = True
+ tree = material.node_tree
+ surface = tree.nodes["Principled BSDF"]
+ texture = tree.nodes.new("ShaderNodeTexImage")
+ texture.image = image
+ tree.links.new(texture.outputs["Color"], surface.inputs["Base Color"])
+ surface.inputs["Roughness"].default_value = 0.85
+ surface.inputs["Specular IOR Level"].default_value = 0.2
+ mesh.materials.append(material)
+ sheet = bpy.data.objects.new("plan_sheet", mesh)
+ bpy.context.scene.collection.objects.link(sheet)
+ table_mesh = bpy.data.meshes.new("studio_floor")
+ size = 500.0
+ # Below the plinth, so concrete slabs and porches do not melt into a pale floor at the same height.
+ table_level = plan.get("site", {}).get("ground_level", -1.0) * scale
+ table_mesh.from_pydata([(-size, -size, table_level), (size, -size, table_level), (size, size, table_level), (-size, size, table_level)], [], [(0, 1, 2, 3)])
+ table_material = bpy.data.materials.new("studio_white")
+ table_material.use_nodes = True
+ table_material.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.82, 0.81, 0.79, 1)
+ table_material.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.7
+ table_mesh.materials.append(table_material)
+ table = bpy.data.objects.new("studio_floor", table_mesh)
+ bpy.context.scene.collection.objects.link(table)
+
+
+FLOOR_FADE_METRES = (35.0, 120.0)
+FLOOR_PROBE_POSITION = (150.0, 150.0, 12.0)
+
+
+def measure_floor_colour(camera):
+ """The colour the studio floor renders to, read straight down at an empty patch of it."""
+ import numpy
+
+ saved_location = camera.location.copy()
+ saved_rotation = camera.rotation_euler.copy()
+ camera.location = FLOOR_PROBE_POSITION
+ camera.rotation_euler = (0.0, 0.0, 0.0)
+ bpy.context.view_layer.update()
+ pixels = meter_pixels()
+ camera.location = saved_location
+ camera.rotation_euler = saved_rotation
+ colour = [float(numpy.median(pixels[:, :, channel])) for channel in range(3)]
+ print("studio floor colour", colour, flush=True)
+ return colour
+
+
+def camera_only_colour(tree, shader_output, surface_input, colour, fade_output=None):
+ """Replace what the camera sees with a flat colour, keeping the same light for everything else."""
+ is_camera = tree.nodes.new("ShaderNodeLightPath")
+ mix = tree.nodes.new("ShaderNodeMixShader")
+ flat = tree.nodes.new("ShaderNodeEmission")
+ flat.inputs["Color"].default_value = (*colour, 1.0)
+ if fade_output is None:
+ tree.links.new(is_camera.outputs["Is Camera Ray"], mix.inputs[0])
+ else:
+ both = tree.nodes.new("ShaderNodeMath")
+ both.operation = "MULTIPLY"
+ tree.links.new(is_camera.outputs["Is Camera Ray"], both.inputs[0])
+ tree.links.new(fade_output, both.inputs[1])
+ tree.links.new(both.outputs[0], mix.inputs[0])
+ tree.links.new(shader_output, mix.inputs[1])
+ tree.links.new(flat.outputs[0], mix.inputs[2])
+ tree.links.new(mix.outputs[0], surface_input)
+
+
+def melt_studio_horizon(colour):
+ """No horizon in the build-up: the floor fades into a background of its own colour, so no sky strip cuts the frame."""
+ floor_tree = bpy.data.materials["studio_white"].node_tree
+ geometry = floor_tree.nodes.new("ShaderNodeNewGeometry")
+ distance = floor_tree.nodes.new("ShaderNodeVectorMath")
+ distance.operation = "LENGTH"
+ floor_tree.links.new(geometry.outputs["Position"], distance.inputs[0])
+ fade = floor_tree.nodes.new("ShaderNodeMapRange")
+ fade.interpolation_type = "SMOOTHSTEP"
+ fade.inputs["From Min"].default_value = FLOOR_FADE_METRES[0]
+ fade.inputs["From Max"].default_value = FLOOR_FADE_METRES[1]
+ floor_tree.links.new(distance.outputs["Value"], fade.inputs["Value"])
+ floor_output = floor_tree.nodes["Material Output"]
+ floor_surface = floor_tree.nodes["Principled BSDF"]
+ camera_only_colour(floor_tree, floor_surface.outputs[0], floor_output.inputs["Surface"], colour, fade.outputs[0])
+ world_tree = bpy.context.scene.world.node_tree
+ world_output = world_tree.nodes["World Output"]
+ world_background = world_tree.nodes["Background"]
+ camera_only_colour(world_tree, world_background.outputs[0], world_output.inputs["Surface"], colour)
+
+
+def smooth_window(value, start, end):
+ fraction = max(0.0, min(1.0, (value - start) / max(end - start, 1e-5)))
+ return fraction * fraction * (3 - 2 * fraction)
+
+
+TRACE_WIDTH_METRES = 0.14
+
+
+def set_hidden(item, hidden):
+ # Writing these unchanged still tags the depsgraph, and Cycles then rebuilds the scene for the frame.
+ if item.hide_render != hidden:
+ item.hide_render = hidden
+
+
+def set_scale_z(item, value):
+ if abs(item.scale.z - value) > 1e-5:
+ item.scale.z = value
+
+
+def set_location_z(item, value):
+ if abs(item.location.z - value) > 1e-5:
+ item.location.z = value
+
+
+RISING_ORDER = ("walls", "facade", "frame", "fitted")
+ROOF_DROP_METRES = 4.0
+DEFAULT_STAGES = {"trace": [0.06, 0.24], "walls": [0.24, 0.46], "sheet": [0.46, 0.56], "furnish": [0.56, 0.76], "roof": [0.78, 0.92]}
+
+
+def add_trace_line(wall, scale, height, material):
+ """A glowing strip along one wall's centreline, grown from its start by scaling along x."""
+ start = Vector(wall["a"]) * scale
+ end = Vector(wall["b"]) * scale
+ length = (end - start).length
+ half_width = TRACE_WIDTH_METRES / 2
+ mesh = bpy.data.meshes.new(f"trace_{wall['id']}")
+ mesh.from_pydata([(0, -half_width, 0), (length, -half_width, 0), (length, half_width, 0), (0, half_width, 0)], [], [(0, 1, 2, 3)])
+ mesh.materials.append(material)
+ line = bpy.data.objects.new(mesh.name, mesh)
+ line.location = (start.x, start.y, height)
+ line.rotation_euler = (0, 0, math.atan2(end.y - start.y, end.x - start.x))
+ bpy.context.scene.collection.objects.link(line)
+ return line
+
+
+class BuildUp:
+ """Lines trace over the drawing, walls grow off them, the paper fades to floor, furniture arrives, the roof lands."""
+
+ def __init__(self, plan, scale, stages):
+ self.stages = {**DEFAULT_STAGES, **stages}
+ floor = plan["levels"].get("floor", 0.0) * scale
+ bpy.context.view_layer.layer_collection.children["site"].exclude = True
+ self.rising = []
+ for order, name in enumerate(RISING_ORDER):
+ members = [item for item in bpy.data.collections[name].all_objects if item.name != "fabric"]
+ for index, item in enumerate(members):
+ self.rising.append((item, (order + index / max(1, len(members))) / len(RISING_ORDER)))
+ self.floors = list(bpy.data.collections["floors"].all_objects)
+ self.roof = [(item, item.location.z) for item in bpy.data.collections["roof"].all_objects]
+ self.ceilings = list(bpy.data.collections["ceilings"].all_objects)
+ self.furnish = list(bpy.data.collections["furnish"].all_objects)
+ # Rugs and curtains share one mesh and arrive with the furniture, not with the walls.
+ self.fabric = bpy.data.objects.get("fabric")
+ self.furnish_scale = {item.name: item.scale.copy() for item in self.furnish}
+ self.sheet_surface = bpy.data.materials["plan_paper"].node_tree.nodes["Principled BSDF"]
+ self.sheet = bpy.data.objects["plan_sheet"]
+ trace_material = bpy.data.materials.new("trace_glow")
+ trace_material.use_nodes = True
+ surface = trace_material.node_tree.nodes["Principled BSDF"]
+ surface.inputs["Base Color"].default_value = (1.0, 0.14, 0.01, 1)
+ surface.inputs["Emission Color"].default_value = (1.0, 0.14, 0.01, 1)
+ surface.inputs["Emission Strength"].default_value = 2.4
+ ground_floor_walls = [wall for wall in plan["walls"] if wall.get("level", 1) == 1 and not wall.get("dashed")]
+ self.traces = [add_trace_line(wall, scale, floor + 0.012, trace_material) for wall in ground_floor_walls]
+
+ def apply_trace(self, value):
+ start, end = self.stages["trace"]
+ walls_start, walls_end = self.stages["walls"]
+ count = len(self.traces)
+ for index, line in enumerate(self.traces):
+ line_start = start + (end - start) * 0.7 * index / max(1, count - 1)
+ growth = smooth_window(value, line_start, line_start + (end - start) * 0.3)
+ if abs(line.scale.x - max(growth, 0.001)) > 1e-5:
+ line.scale.x = max(growth, 0.001)
+ set_hidden(line, growth <= 0.001 or value > walls_start + (walls_end - walls_start) * 0.5)
+
+ def apply_walls(self, value):
+ start, end = self.stages["walls"]
+ local = (value - start) / max(end - start, 1e-5)
+ stagger = 0.35
+ for item, delay in self.rising:
+ growth = smooth_window(local, delay * stagger, delay * stagger + (1 - stagger))
+ set_hidden(item, growth <= 0.001)
+ set_scale_z(item, max(growth, 0.001))
+
+ def apply_sheet(self, value):
+ start, end = self.stages["sheet"]
+ opacity = 1.0 - smooth_window(value, start, end)
+ if abs(self.sheet_surface.inputs["Alpha"].default_value - opacity) > 1e-5:
+ self.sheet_surface.inputs["Alpha"].default_value = opacity
+ set_hidden(self.sheet, opacity <= 0.001)
+ for item in self.floors:
+ set_hidden(item, value < start)
+
+ def apply_furnish(self, value):
+ start, end = self.stages["furnish"]
+ count = max(1, len(self.furnish) - 1)
+ if self.fabric is not None:
+ set_hidden(self.fabric, value < start)
+ for index, item in enumerate(self.furnish):
+ item_start = start + (end - start) * 0.7 * index / count
+ growth = smooth_window(value, item_start, item_start + (end - start) * 0.3)
+ set_hidden(item, growth <= 0.001)
+ wanted = self.furnish_scale[item.name] * max(growth, 0.001)
+ if (item.scale - wanted).length > 1e-5:
+ item.scale = wanted
+
+ def apply_roof(self, value):
+ start, end = self.stages["roof"]
+ drop = 1.0 - smooth_window(value, start, end)
+ for item, resting_height in self.roof:
+ set_hidden(item, value < start)
+ set_location_z(item, resting_height + drop * drop * ROOF_DROP_METRES)
+ for item in self.ceilings:
+ set_hidden(item, value < end)
+
+ def apply(self, value):
+ self.apply_trace(value)
+ self.apply_walls(value)
+ self.apply_sheet(value)
+ self.apply_furnish(value)
+ self.apply_roof(value)
+
+
+def render_film(plan, film, scale, out_folder, frame_limit):
+ frames = int(frame_limit or film["frames"])
+ folder = out_folder / film["name"]
+ folder.mkdir(parents=True, exist_ok=True)
+ bpy.context.scene.cycles.use_animated_seed = False
+ bpy.context.scene.render.use_persistent_data = True
+ positions = [Vector(point["pos"]) for point in film["path"]]
+ targets = [Vector(point["look"]) for point in film["path"]]
+ shot = {"pos": film["path"][0]["pos"], "look": film["path"][0]["look"], "lens": film.get("lens", 24), "level": film.get("level", True)}
+ camera = camera_for(shot, scale)
+ stops_at_points = None
+ if film.get("interior"):
+ stops_at_points = []
+ for point in film["path"]:
+ aim_camera(camera, {"pos": point["pos"], "look": point["look"], "level": film.get("level", True)}, scale)
+ bpy.context.view_layer.update()
+ stops_at_points.append(meter_exposure(film.get("meter_target", INTERIOR_METER_TARGET)) + film.get("exposure", 0.0))
+ build_up = None
+ if film.get("build_up") is not None:
+ add_plan_sheet(plan, scale)
+ build_up = BuildUp(plan, scale, film["build_up"])
+ melt_studio_horizon(measure_floor_colour(camera))
+ for frame in range(frames):
+ target_path = folder / f"f{frame:04d}.png"
+ if target_path.exists():
+ continue
+ if build_up is not None:
+ build_up.apply(frame / max(1, frames - 1))
+ fraction = eased(frame / max(1, frames - 1))
+ now = {"pos": list(catmull(positions, fraction)), "look": list(catmull(targets, fraction)), "level": film.get("level", True)}
+ aim_camera(camera, now, scale)
+ bpy.context.view_layer.update()
+ if stops_at_points:
+ place = fraction * (len(stops_at_points) - 1)
+ index = min(int(place), len(stops_at_points) - 2)
+ local = place - index
+ bpy.context.scene.view_settings.exposure = stops_at_points[index] * (1 - local) + stops_at_points[index + 1] * local
+ render_to(target_path)
+
+
+def main():
+ options = read_arguments()
+ plan_path = pathlib.Path(options["plan"])
+ global options_plan_folder
+ options_plan_folder = str(plan_path.resolve().parent)
+ plan = json.loads(plan_path.read_text(encoding="utf-8"))
+ scale = METRES_PER_UNIT[plan.get("units", "m")]
+ out_folder = pathlib.Path(options["out"])
+ out_folder.mkdir(parents=True, exist_ok=True)
+ setup_cycles(int(options["samples"]), int(options["scale"]))
+ site = plan.get("site", {})
+ setup_world(site)
+ add_lamps(plan, scale)
+ portals = add_window_portals(plan, scale)
+ wanted = options["shots"].split(",") if options["shots"] else None
+ cut_applied = None
+ if options["film"]:
+ film = next(item for item in plan["films"] if item["name"] == options["film"])
+ if film.get("cut"):
+ apply_cut(plan["levels"].get("floor", 0.0) * scale + film["cut"] * scale, plan)
+ for portal in portals:
+ portal.hide_render = not film.get("interior", False)
+ bpy.context.scene.view_settings.exposure = film.get("exposure", 0.0)
+ render_film(plan, film, scale, out_folder, options["frames"])
+ return
+ shots = plan.get("shots", [])
+ # Cuts only remove, so uncut shots go first and then the highest cut down.
+ shots = sorted(shots, key=lambda shot: -shot["cut"] if shot.get("cut") else float("-inf"))
+ for shot in shots:
+ if wanted and shot["name"] not in wanted:
+ continue
+ kind = shot.get("kind", "exterior")
+ for portal in portals:
+ portal.hide_render = kind != "interior"
+ if shot.get("cut") and shot["cut"] != cut_applied:
+ apply_cut(plan["levels"].get("floor", 0.0) * scale + shot["cut"] * scale, plan)
+ cut_applied = shot["cut"]
+ camera_for(shot, scale, shot["name"])
+ bpy.context.view_layer.update()
+ bpy.context.scene.view_settings.exposure = 0.0
+ stops = shot.get("exposure", 0.0)
+ if shot.get("meter", kind == "interior"):
+ stops += meter_exposure(shot.get("meter_target", INTERIOR_METER_TARGET))
+ bpy.context.scene.view_settings.exposure = stops
+ render_to(out_folder / f"{shot['name']}.png")
+
+
+main()