Skip to content

armgit / viz3d

Public Imported from GitHub
0

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

build-house-from-plan 0.2.0: mixed-unit reconciliation and equipment fit check for fit-outs

Nguyen Xuan An862ca780d42b
diff --git a/plugins/build-house-from-plan/.claude-plugin/plugin.json b/plugins/build-house-from-plan/.claude-plugin/plugin.json
index 4b6b9c1..6e17987 100644
--- a/plugins/build-house-from-plan/.claude-plugin/plugin.json
+++ b/plugins/build-house-from-plan/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "build-house-from-plan",
- "version": "0.1.3",
- "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.",
+ "version": "0.2.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. Fit-outs too: reconciles sheets in metres and feet, checks equipment with its clearances and shows clashes in 3D with a coordination table.",
"author": {
"name": "CodePawl",
"url": "https://codepawl.com"
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
index 2067b37..b8ef66a 100644
--- 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
@@ -1,6 +1,6 @@
---
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, "từ house plan làm nhà 3D", "bản vẽ thành nhà 3D", "dựng nhà từ mặt bằng", "nhà 3D từ bản vẽ".
+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. Fit-outs too: reconciles sheets written in metres and feet, checks equipment with its clearances and shows clashes in 3D with a coordination table. Use for a floor plan, a house plan, a blueprint or a shop, café, brewery or kitchen fit-out that should become a real-looking 3D house or street, "từ house plan làm nhà 3D", "bản vẽ thành nhà 3D", "dựng nhà từ mặt bằng", "nhà 3D từ bản vẽ".
license: MIT
---
@@ -23,12 +23,15 @@ built floor plan lands on its ink.
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
```
+ Fit-out with equipment or sheets in mixed units (m, mm, ft-in): read `references/fit-out.md` and run
+ `uv run --no-project --with pillow python scripts/fitout_check.py all plan.json` for the unit reconciliation and
+ coordination tables. Fix unit faults before building; clashes then show in 3D as red volumes.
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:
+5. **Preview small.** `--samples 48 --scale 50` (`--size 1080x1350` for a portrait frame), 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
```
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/examples/fitout-fixture.json b/plugins/build-house-from-plan/skills/build-house-from-plan/examples/fitout-fixture.json
new file mode 100644
index 0000000..eebc4c4
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/examples/fitout-fixture.json
@@ -0,0 +1,43 @@
+{
+ "units": "m",
+ "fitout_title": "Test roastery: coordination",
+ "unit_tolerance_m": 0.02,
+ "fit_tight_m": 0.10,
+ "levels": {"floor": 0.0, "ceiling": 3.2},
+ "sheets": [
+ {"id": "A-101", "name": "Architect floor plan", "default_unit": "mm"},
+ {"id": "M-201", "name": "Equipment supplier layout", "default_unit": "in"}
+ ],
+ "dimensions": [
+ {"id": "room_width", "label": "Roastery clear width", "sheet": "A-101", "text": "6100", "a": [0, 4], "b": [6.1, 4]},
+ {"id": "room_width", "sheet": "M-201", "text": "20'-0\" (6.40 m)"},
+ {"id": "room_depth", "label": "Roastery clear depth", "sheet": "A-101", "text": "8.00 m"},
+ {"id": "room_depth", "sheet": "M-201", "text": "26' 3\""},
+ {"id": "ceiling", "label": "Ceiling height", "sheet": "A-101", "text": "3200 mm"},
+ {"id": "ceiling", "sheet": "M-201", "text": "10'-6\""},
+ {"id": "door", "label": "Loading door", "sheet": "A-101", "text": "1000"},
+ {"id": "door", "sheet": "M-201", "text": "39 3/8\""}
+ ],
+ "walls": [
+ {"id": "S", "a": [-0.1, -0.1], "b": [6.2, -0.1], "t": 0.2, "kind": "ext", "outside": -1},
+ {"id": "E", "a": [6.2, -0.1], "b": [6.2, 8.1], "t": 0.2, "kind": "ext", "outside": -1},
+ {"id": "N", "a": [6.2, 8.1], "b": [-0.1, 8.1], "t": 0.2, "kind": "ext", "outside": -1},
+ {"id": "W", "a": [-0.1, 8.1], "b": [-0.1, -0.1], "t": 0.2, "kind": "ext", "outside": -1}
+ ],
+ "openings": [
+ {"id": "D1", "wall": "S", "kind": "door", "from": 2.0, "to": 3.0, "sill": 0, "head": 2.4, "swing": 1}
+ ],
+ "rooms": [
+ {"name": "Roastery", "kind": "work", "poly": [[0, 0], [6.1, 0], [6.1, 8], [0, 8]], "ceiling": 3.2}
+ ],
+ "equipment": [
+ {"id": "R1", "name": "Roaster 15 kg", "room": "Roastery", "at": [5.075, 5.0], "rot": -90,
+ "size": ["2.10 m", "1.45 m", "2.35 m"], "clear": {"front": "1.0 m", "back": "600 mm", "left": "18\"", "right": "0.45 m", "top": "0.6 m"}},
+ {"id": "C1", "name": "Cooling tray", "room": "Roastery", "at": [2.6, 5.2], "rot": -90,
+ "size": [1.2, 1.2, 1.0], "clear": {"front": 0.9}},
+ {"id": "G1", "name": "Green bean rack", "room": "Roastery", "at": [0.7, 3.0], "rot": 90,
+ "size": ["9'", "42\"", "8'"], "clear": {"front": "4'"}},
+ {"id": "P1", "name": "Packing bench", "room": "Roastery", "at": [3.0, 7.5], "rot": 0,
+ "size": ["2.4 m", "0.75 m", "0.9 m"], "clear": {"front": "0.9 m", "back": "50 mm"}}
+ ]
+}
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/references/fit-out.md b/plugins/build-house-from-plan/skills/build-house-from-plan/references/fit-out.md
new file mode 100644
index 0000000..be52565
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/references/fit-out.md
@@ -0,0 +1,74 @@
+# Fit-out: mixed units and equipment fit
+
+For a shop, café, roastery, brewery, workshop or kitchen fit-out: several sheets from different hands (architect, equipment
+supplier, MEP), dimensions written in m, mm, ft-in and inches, and equipment that has to fit with its service space.
+`scripts/fitout_check.py` reconciles the units, then checks each item against its room, the doors, the ceiling and the
+other items. It runs on plain Python (pillow only for the card) and needs no Blender.
+
+## Reading map
+
+- Keys to add to `plan.json`: "Sheets and dimensions", "Equipment".
+- What the check does and how it rates: "Units check", "Fit check".
+- Commands, outputs and the 3D highlight: "Run it".
+
+## Sheets and dimensions
+
+`sheets[]`: `{id, name, default_unit}`. `default_unit` (`m`, `mm`, `cm`, `ft`, `in`) is how the sheet writes a bare
+number: an architect's `6100` is millimetres, a US supplier's `48` is inches.
+
+`dimensions[]`: `{id, sheet, text, label, a, b}`. Copy `text` exactly as written on that sheet. The same physical
+dimension read off several sheets shares one `id`. Readable forms: `6.10 m`, `6100 mm`, `610 cm`, `6100` (sheet default),
+`20'-0"`, `20' 0"`, `13'-9 1/2"`, `165"`, `5 ft 6 in`, and a written conversion beside the value, `20'-0" (6.40 m)` or
+`6.10 m [20'-0"]`. On one reading, `a` and `b` are the two plan points the dimension spans (finished faces, plan units):
+the check then compares the built geometry with what the drawings say.
+
+`unit_tolerance_m` (default 0.02) is how far two readings may differ before they conflict.
+
+## Equipment
+
+`equipment[]`: `{id, name, room, at, rot, size: [w, d, h], clear: {front, back, left, right, top}, z0, asset, asset_rot, paint, material, fit_size}`.
+`at` is the footprint centre. At `rot: 0` the front faces -y, as for `furnish`. Lengths are plan-unit numbers or strings
+with a unit (`"42\""`, `"600 mm"`), so a supplier's imperial cut sheet goes in as written. Clearances come from the
+maker's installation manual: service access, door swing of the unit, combustibles distance for a roaster or oven,
+hood or flue space in `top`. Write the manual's numbers, never a guess, and note the manual in `CREDITS.md`.
+`asset` (`ph:` or `obj:`) builds the real model stretched to `size` (`fit_size: false` keeps its own proportions);
+`asset_rot` turns a model whose front is not -y (check on the `preview_assets.py` grid), `paint` as for `furnish`;
+without an asset the item is a plain box in `material` (a name from `house_core.py`); `material: "none"` draws
+only its zones, for an item dressed from several `furnish` models (a pallet with sacks on it).
+`fit_tight_m` (default 0.10) is the margin under which an item is "tight".
+
+## Units check
+
+Each reading becomes metres. A written conversion that disagrees with its own value by more than the tolerance is a
+**wrong conversion**: the value is kept, the conversion is dropped and named. Readings of one `id` that still disagree
+are a **conflict**: the smallest is used for fit checks (the safe side) until a person settles it. A dimension whose
+`a`-`b` distance in the plan differs from the resolved value is **model off**: the plan was drawn from the wrong
+number, so fix the walls and rooms, then rerun.
+
+## Fit check
+
+Every item is checked for: footprint inside its room, each service zone inside its room, footprint clear of each door's
+swing and 0.9 m approach on both faces, footprint and each zone clear of every other item's footprint, and height plus
+`top` under the room's `ceiling` (or `levels.ceiling`). Service zones may overlap each other: a shared aisle is normal.
+The margin is the tightest of those checks in metres. Below zero is **clash**, below `fit_tight_m` **tight**, else
+**fits**. The report names the binding check, so the fix is obvious: move the item, swap the model, or change the room.
+
+## Run it
+
+```bash
+uv run --no-project --with pillow python scripts/fitout_check.py all plan.json
+```
+
+`units` or `fit` alone skip the card. Outputs beside the plan: `fitout_units.md` (reconciliation table),
+`fitout_coordination.md` (one row per item: status mark, margin, binding check, action), `fitout_card.png` (the same
+as a card with shape-coded marks: circle fits, triangle tight, square clash) and `fitout_report.json`. Exit 1 on any
+unit fault or clash. Fix the plan and rerun before modelling further, unless the clash is the point of the piece.
+
+`build_house.py` reads `fitout_report.json`: it builds the equipment into `furnish` and each service zone into a
+`fitout` collection, a floor patch in green or amber, and a red volume up to the clear height where a zone clashes (a cut trims it 2 cm above the wall poché, so it reads as
+red across the wall it runs into). Shots and films
+show them unless they set `fit_zones: false`. A `build_up` film brings the zones in after the equipment lands. Rerun
+`fitout_check.py` before every build, since the builder trusts the report as it is.
+
+Tests: `uv run --no-project --with pillow python scripts/test_fitout_check.py` on `examples/fitout-fixture.json`, a
+roastery whose supplier sheet writes `20'-0" (6.40 m)` and whose roaster was laid out for 6.40 m.
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
index 9dac1b0..fb8bd46 100644
--- 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
@@ -83,6 +83,8 @@ row of variants (Poly Haven plants). At `rot: 0` a model's front faces -y, so it
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}`.
+Fit-outs add `sheets[]`, `dimensions[]` and `equipment[]`: `references/fit-out.md`.
+
## Site, shots, films
`site`: `hdri`, `sun: {azimuth, elevation, strength, angle, colour}`, `sky_strength`, `sky_clamp`, `centre`,
@@ -90,7 +92,7 @@ the asset library's `models` folder) or `obj:<Objaverse uid>` (from `site.objave
`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
+themselves to a median (`meter_target`, default 0.26) the way a camera does; `exposure` adds stops on top. `fit_zones: false` hides equipment service zones. `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
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
index eb1b185..7c23cbd 100644
--- 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
@@ -393,6 +393,50 @@ def furnish(plan, structure, collections, report):
place_asset(plan, item, library_collection, collections["site"], report, on_ground=True)
+FIT_FLOOR_PATCH_METRES = 0.012
+
+
+def build_equipment(plan, collections, report):
+ """Equipment from `fitout_report.json` (written by fitout_check.py, already in metres), each service zone
+ a tinted volume in its status colour: green fits, amber tight, red clash. A clash zone stands to the clear height."""
+ report_path = plan["_folder"] / "fitout_report.json"
+ if not report_path.exists():
+ return
+ fit = json.loads(report_path.read_text(encoding="utf-8"))
+ floor = plan["levels"].get("floor", 0.0)
+ plain = MeshBatch("equipment_plain", 61)
+ zones = MeshBatch("fit_zones", 62)
+ for row in fit.get("equipment", []):
+ footprint = row["footprint_m"]
+ width, depth, height = row["size_m"]
+ bottom = floor + row["z0_m"]
+ centre = [sum(point[axis] for point in footprint) / 4 for axis in range(2)]
+ if row.get("asset"):
+ # A model whose front is not -y turns by asset_rot; a quarter turn swaps its native x and y.
+ asset_rot = row.get("asset_rot", 0)
+ item = {"asset": row["asset"], "at": centre, "rot": row["rot"] + asset_rot, "z": bottom, "name": row["id"]}
+ if row.get("paint"):
+ item["paint"] = row["paint"]
+ if row.get("fit_size", True):
+ quarter_turn = round(asset_rot / 90) % 2 == 1
+ item["fit_size"] = [depth, width, height] if quarter_turn else [width, depth, height]
+ if place_asset(plan, item, collections["library"], collections["furnish"], report) is None:
+ report["missing"].append(row["asset"])
+ elif row.get("material") != "none":
+ plain.add_prism(footprint, bottom, bottom + height, row.get("material") or "aluminium_dull")
+ failing = {problem["check"].split(" ")[0] for problem in row["problems"] if problem["status"] == "clash"}
+ for side, zone in row["zones_m"].items():
+ status = row["status"] if side in failing or row["status"] != "clash" else "fits"
+ # A clash stands to the clear height, so a cut shows it crossing the wall it runs into.
+ top = floor + plan["levels"].get("ceiling", bottom + height) if status == "clash" else floor + FIT_FLOOR_PATCH_METRES
+ zones.add_prism(zone, floor + 0.002, top, f"fit_{status}")
+ report.setdefault("fit", []).append({"id": row["id"], "status": row["status"], "margin_m": row["margin_m"]})
+ if plain.faces:
+ plain.finish(collections["furnish"], bevel=0.004)
+ if zones.faces:
+ zones.finish(collections["fitout"])
+
+
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")
@@ -690,7 +734,7 @@ def main():
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")}
+ collections = {name: new_collection(name) for name in ("walls", "floors", "ceilings", "facade", "roof", "frame", "fitted", "furnish", "fitout", "site", "library")}
structure = house_parts.Structure(plan)
clock = time.perf_counter()
@@ -705,6 +749,7 @@ def main():
phase_done("structure")
report = {"placed": [], "clashes": [], "missing": []}
furnish(plan, structure, collections, report)
+ build_equipment(plan, collections, report)
phase_done("furnish")
build_ground(plan, collections["site"])
phase_done("ground")
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fitout_check.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fitout_check.py
new file mode 100644
index 0000000..71dc451
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/fitout_check.py
@@ -0,0 +1,507 @@
+"""Fit-out checks for a plan with equipment: mixed units across sheets, then each item against its room.
+
+ fitout_check.py units plan.json reconcile every written dimension to metres, flag conflicts
+ fitout_check.py fit plan.json place each equipment item with its clearances, rate fits / tight / clash
+ fitout_check.py all plan.json both, plus the coordination card (needs pillow)
+
+Writes `fitout_units.md`, `fitout_coordination.md`, `fitout_report.json` and `fitout_card.png` next to the plan.
+`build_house.py` reads `fitout_report.json` to build the equipment and colour each clearance zone by its status.
+Exit code 1 when a dimension conflict or an equipment clash is found. Keys: references/fit-out.md.
+"""
+
+import json
+import math
+import pathlib
+import re
+import statistics
+import sys
+
+METRES_PER = {"m": 1.0, "mm": 0.001, "cm": 0.01, "ft": 0.3048, "in": 0.0254}
+UNIT_WORDS = {
+ "m": "m", "metre": "m", "metres": "m", "meter": "m", "meters": "m",
+ "mm": "mm", "cm": "cm",
+ "ft": "ft", "foot": "ft", "feet": "ft", "'": "ft", "′": "ft",
+ "in": "in", "inch": "in", "inches": "in", '"': "in", "″": "in",
+}
+DEFAULT_TOLERANCE_M = 0.02
+DEFAULT_TIGHT_M = 0.10
+DOOR_APPROACH_M = 0.9
+SAMPLE_STEP_M = 0.05
+TOUCH_EPSILON_M = 0.0005 # a zone that only touches a wall reads -1e-16 from float noise
+
+FEET_INCHES = re.compile(
+ r"^(?P<feet>\d+(?:\.\d+)?)\s*(?:'|′|ft|feet|foot)\s*-?\s*"
+ r"(?:(?P<inches>\d+(?:\.\d+)?)?(?:\s+(?P<num>\d+)/(?P<den>\d+))?\s*(?:\"|″|in|inch|inches)?)?$"
+)
+NUMBER_WITH_UNIT = re.compile(r"^(?P<value>\d+(?:\.\d+)?)\s*(?:(?P<num>\d+)/(?P<den>\d+))?\s*(?P<unit>[a-z'\"′″]*)$")
+DUAL = re.compile(r"^(?P<first>[^(\[]+?)\s*[(\[](?P<second>[^)\]]+)[)\]]\s*$")
+
+
+# ---------------------------------------------------------------- reading lengths
+
+
+def parse_length(text, default_unit=None):
+ """Metres from one written length: 6.10 m, 6100 mm, 20'-0", 13' 9 1/2", 165", 5 ft 6 in, or a bare number."""
+ cleaned = text.strip().lower().replace("’", "'").replace("”", '"').replace(",", "")
+ cleaned = re.sub(r"(\d)\s*ft\s+(\d)", r"\1' \2", cleaned)
+ feet_match = FEET_INCHES.match(cleaned)
+ if feet_match:
+ feet = float(feet_match["feet"])
+ inches = float(feet_match["inches"] or 0)
+ if feet_match["num"]:
+ inches += int(feet_match["num"]) / int(feet_match["den"])
+ return (feet * 12 + inches) * METRES_PER["in"]
+ number_match = NUMBER_WITH_UNIT.match(cleaned)
+ if not number_match:
+ raise ValueError(f"cannot read a length from {text!r}")
+ value = float(number_match["value"])
+ if number_match["num"]:
+ value += int(number_match["num"]) / int(number_match["den"])
+ unit_word = number_match["unit"]
+ if not unit_word:
+ if default_unit is None:
+ raise ValueError(f"{text!r} has no unit and its sheet sets no default_unit")
+ unit_word = default_unit
+ if unit_word not in UNIT_WORDS:
+ raise ValueError(f"unknown unit {unit_word!r} in {text!r}")
+ return value * METRES_PER[UNIT_WORDS[unit_word]]
+
+
+def read_dimension_text(text, default_unit):
+ """One reading, or a primary value with its written conversion: `20'-0" (6.40 m)` or `6.10 m [20'-0"]`."""
+ dual_match = DUAL.match(text.strip())
+ if dual_match:
+ return parse_length(dual_match["first"], default_unit), parse_length(dual_match["second"], default_unit)
+ return parse_length(text, default_unit), None
+
+
+def length_in_metres(value, plan_unit):
+ """A plan value: a number in the plan's own units, or a string that carries its unit."""
+ if isinstance(value, str):
+ return parse_length(value, plan_unit)
+ return value * METRES_PER[plan_unit]
+
+
+def format_metres(metres):
+ return f"{metres:.3f} m"
+
+
+# ---------------------------------------------------------------- unit reconciliation
+
+
+def reconcile_units(plan):
+ """Group readings of the same dimension across sheets, drop wrong conversions, flag disagreements."""
+ plan_unit = plan.get("units", "m")
+ tolerance = plan.get("unit_tolerance_m", DEFAULT_TOLERANCE_M)
+ default_unit_by_sheet = {sheet["id"]: sheet.get("default_unit") for sheet in plan.get("sheets", [])}
+ readings_by_id = {}
+ for dimension in plan.get("dimensions", []):
+ default_unit = default_unit_by_sheet.get(dimension["sheet"])
+ primary, written_conversion = read_dimension_text(dimension["text"], default_unit)
+ reading = {
+ "sheet": dimension["sheet"],
+ "text": dimension["text"],
+ "metres": primary,
+ "label": dimension.get("label", dimension["id"]),
+ "faults": [],
+ }
+ if written_conversion is not None and abs(written_conversion - primary) > tolerance:
+ reading["faults"].append(
+ f"wrong conversion on {dimension['sheet']}: {dimension['text']} is {format_metres(primary)}, "
+ f"written as {format_metres(written_conversion)} ({(written_conversion - primary) * 1000:+.0f} mm)"
+ )
+ readings_by_id.setdefault(dimension["id"], {"readings": [], "measure": None})
+ readings_by_id[dimension["id"]]["readings"].append(reading)
+ if "a" in dimension and "b" in dimension:
+ readings_by_id[dimension["id"]]["measure"] = (dimension["a"], dimension["b"])
+
+ rows = []
+ for dimension_id, group in readings_by_id.items():
+ readings = group["readings"]
+ values = [reading["metres"] for reading in readings]
+ resolved = statistics.median(values)
+ spread = max(values) - min(values)
+ faults = [fault for reading in readings for fault in reading["faults"]]
+ status = "ok"
+ if faults:
+ status = "wrong conversion"
+ if spread > tolerance:
+ status = "conflict"
+ faults.append(
+ "sheets disagree by " + f"{spread * 1000:.0f} mm: "
+ + ", ".join(f"{reading['sheet']} {format_metres(reading['metres'])}" for reading in readings)
+ )
+ resolved = min(values)
+ row = {
+ "id": dimension_id,
+ "label": readings[0]["label"],
+ "readings": [{"sheet": r["sheet"], "text": r["text"], "metres": round(r["metres"], 4)} for r in readings],
+ "resolved_m": round(resolved, 4),
+ "status": status,
+ "faults": faults,
+ }
+ if group["measure"]:
+ start, end = group["measure"]
+ modelled = math.dist(start, end) * METRES_PER[plan_unit]
+ row["modelled_m"] = round(modelled, 4)
+ if abs(modelled - resolved) > tolerance:
+ row["status"] = "model off"
+ row["faults"].append(
+ f"plan geometry measures {format_metres(modelled)}, drawings say {format_metres(resolved)} "
+ f"({(modelled - resolved) * 1000:+.0f} mm): rebuild the plan from the resolved value"
+ )
+ rows.append(row)
+ return rows
+
+
+def units_markdown(rows):
+ lines = [
+ "| Dimension | Readings | Resolved | Status | Note |",
+ "| --- | --- | --- | --- | --- |",
+ ]
+ for row in rows:
+ readings = "<br>".join(f"{r['sheet']}: `{r['text']}` = {r['metres']:.3f} m" for r in row["readings"])
+ note = "<br>".join(row["faults"]) or "all sheets agree"
+ lines.append(f"| {row['label']} | {readings} | {row['resolved_m']:.3f} m | {row['status']} | {note} |")
+ return "\n".join(lines) + "\n"
+
+
+# ---------------------------------------------------------------- geometry
+
+
+def rectangle(centre, half_width, half_depth, angle, offset=(0.0, 0.0)):
+ """Corners of a rectangle in local x (width) and y (depth), rotated about `centre`; `offset` moves it locally."""
+ 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 = offset[0] + sign_x * half_width
+ local_y = offset[1] + sign_y * half_depth
+ corners.append((centre[0] + local_x * cosine - local_y * sine, centre[1] + local_x * sine + local_y * cosine))
+ return corners
+
+
+def edges(polygon):
+ return [(polygon[index], polygon[(index + 1) % len(polygon)]) for index in range(len(polygon))]
+
+
+def segment_distance(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
+ fraction = 0.0
+ if length_squared > 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 math.dist(point, (start[0] + fraction * delta_x, start[1] + fraction * delta_y))
+
+
+def inside(point, polygon):
+ crossings = False
+ for start, end in edges(polygon):
+ if (start[1] > point[1]) != (end[1] > point[1]):
+ x_at = start[0] + (point[1] - start[1]) * (end[0] - start[0]) / (end[1] - start[1])
+ if point[0] < x_at:
+ crossings = not crossings
+ return crossings
+
+
+def outline_samples(polygon):
+ samples = []
+ for start, end in edges(polygon):
+ steps = max(1, int(math.dist(start, end) / SAMPLE_STEP_M))
+ for step in range(steps):
+ fraction = step / steps
+ samples.append((start[0] + fraction * (end[0] - start[0]), start[1] + fraction * (end[1] - start[1])))
+ return samples
+
+
+def signed_distance_to_outline(point, polygon):
+ """Positive inside the polygon, negative outside, in the polygon's units."""
+ nearest = min(segment_distance(point, start, end) for start, end in edges(polygon))
+ return nearest if inside(point, polygon) else -nearest
+
+
+def containment_margin(shape, room):
+ """How far the shape stays inside the room: negative is how far it pokes out."""
+ return min(signed_distance_to_outline(point, room) for point in outline_samples(shape))
+
+
+def separation(shape_a, shape_b):
+ """Gap between two convex shapes along the best separating axis; negative is the overlap depth."""
+ best = -math.inf
+ for polygon in (shape_a, shape_b):
+ for start, end in edges(polygon):
+ axis_x = -(end[1] - start[1])
+ axis_y = end[0] - start[0]
+ length = math.hypot(axis_x, axis_y)
+ if length == 0:
+ continue
+ axis_x /= length
+ axis_y /= length
+ projections_a = [point[0] * axis_x + point[1] * axis_y for point in shape_a]
+ projections_b = [point[0] * axis_x + point[1] * axis_y for point in shape_b]
+ gap = max(min(projections_b) - max(projections_a), min(projections_a) - max(projections_b))
+ best = max(best, gap)
+ return best
+
+
+# ---------------------------------------------------------------- equipment fit
+
+
+def room_by_name(plan, name):
+ for room in plan.get("rooms", []):
+ if room["name"] == name:
+ return room
+ raise KeyError(f"equipment names room {name!r}, which the plan does not have")
+
+
+def equipment_shapes(item, plan_unit):
+ """Footprint and clearance zones in metres. At rot 0 the front faces -y, as for `furnish`."""
+ width, depth, height = (length_in_metres(value, plan_unit) for value in item["size"])
+ clear = {side: length_in_metres(value, plan_unit) for side, value in item.get("clear", {}).items()}
+ centre = [length_in_metres(value, plan_unit) for value in item["at"]]
+ angle = math.radians(item.get("rot", 0))
+ half_width = width / 2
+ half_depth = depth / 2
+ zones = {}
+ if clear.get("front"):
+ zones["front"] = rectangle(centre, half_width, clear["front"] / 2, angle, (0, -half_depth - clear["front"] / 2))
+ if clear.get("back"):
+ zones["back"] = rectangle(centre, half_width, clear["back"] / 2, angle, (0, half_depth + clear["back"] / 2))
+ if clear.get("left"):
+ zones["left"] = rectangle(centre, clear["left"] / 2, half_depth, angle, (-half_width - clear["left"] / 2, 0))
+ if clear.get("right"):
+ zones["right"] = rectangle(centre, clear["right"] / 2, half_depth, angle, (half_width + clear["right"] / 2, 0))
+ return {
+ "footprint": rectangle(centre, half_width, half_depth, angle),
+ "zones": zones,
+ "size_m": [width, depth, height],
+ "top_clear_m": clear.get("top", 0.0),
+ "z0_m": length_in_metres(item.get("z0", 0), plan_unit),
+ }
+
+
+def door_zones(plan, plan_unit):
+ """For each door: the leaf's swing square on its swing side and the approach strip on both faces."""
+ walls = {wall["id"]: wall for wall in plan.get("walls", [])}
+ zones = []
+ for opening in plan.get("openings", []):
+ if opening["kind"] not in ("door", "cased"):
+ continue
+ wall = walls[opening["wall"]]
+ start = [length_in_metres(value, plan_unit) for value in wall["a"]]
+ end = [length_in_metres(value, plan_unit) for value in wall["b"]]
+ length = math.dist(start, end)
+ direction = ((end[0] - start[0]) / length, (end[1] - start[1]) / length)
+ normal = (-direction[1], direction[0])
+ thickness = length_in_metres(wall.get("t", 0.1), plan_unit)
+ low = length_in_metres(opening["from"], plan_unit)
+ high = length_in_metres(opening["to"], plan_unit)
+ leaf = (high - low) / max(1, opening.get("leaves", 1))
+ middle = (low + high) / 2
+ centre = (start[0] + direction[0] * middle, start[1] + direction[1] * middle)
+ angle = math.atan2(direction[1], direction[0])
+ for side in (1, -1):
+ reach = DOOR_APPROACH_M
+ if opening["kind"] == "door" and opening.get("swing", 1) == side:
+ reach = max(reach, leaf)
+ offset_along_normal = side * (thickness / 2 + reach / 2)
+ zones.append({
+ "door": opening["id"],
+ "shape": rectangle(
+ (centre[0] + normal[0] * offset_along_normal, centre[1] + normal[1] * offset_along_normal),
+ (high - low) / 2, reach / 2, angle,
+ ),
+ })
+ return zones
+
+
+def ceiling_height(plan, room, plan_unit):
+ value = room.get("ceiling", plan.get("levels", {}).get("ceiling"))
+ if value is None:
+ return None
+ return length_in_metres(value, plan_unit)
+
+
+def rate(margin, tight):
+ if margin < -TOUCH_EPSILON_M:
+ return "clash"
+ if margin < tight:
+ return "tight"
+ return "fits"
+
+
+def check_equipment(plan):
+ plan_unit = plan.get("units", "m")
+ tight = plan.get("fit_tight_m", DEFAULT_TIGHT_M)
+ items = plan.get("equipment", [])
+ shapes = {item["id"]: equipment_shapes(item, plan_unit) for item in items}
+ doors = door_zones(plan, plan_unit)
+ rows = []
+ for item in items:
+ shape = shapes[item["id"]]
+ room = room_by_name(plan, item["room"])
+ room_polygon = [[length_in_metres(value, plan_unit) for value in point] for point in room["poly"]]
+ checks = []
+ checks.append(("footprint inside the room", containment_margin(shape["footprint"], room_polygon)))
+ for side, zone in shape["zones"].items():
+ checks.append((f"{side} service zone inside the room", containment_margin(zone, room_polygon)))
+ for door in doors:
+ checks.append((f"footprint clear of door {door['door']} swing and approach", separation(shape["footprint"], door["shape"])))
+ for other in items:
+ if other["id"] == item["id"]:
+ continue
+ other_shape = shapes[other["id"]]
+ checks.append((f"footprint clear of {other['id']}", separation(shape["footprint"], other_shape["footprint"])))
+ for side, zone in shape["zones"].items():
+ checks.append((f"{side} service zone clear of {other['id']}", separation(zone, other_shape["footprint"])))
+ ceiling = ceiling_height(plan, room, plan_unit)
+ if ceiling is not None:
+ top = shape["z0_m"] + shape["size_m"][2] + shape["top_clear_m"]
+ checks.append(("height with top clearance under the ceiling", ceiling - top))
+ # Far-apart objects say nothing: keep what binds, then report the tightest.
+ worst_name, worst_margin = min(checks, key=lambda check: check[1])
+ problems = [
+ {"check": name, "margin_m": round(margin, 3), "status": rate(margin, tight)}
+ for name, margin in sorted(checks, key=lambda check: check[1])
+ if margin < tight
+ ]
+ rows.append({
+ "id": item["id"],
+ "name": item.get("name", item["id"]),
+ "room": item["room"],
+ "status": rate(worst_margin, tight),
+ "margin_m": round(worst_margin, 3),
+ "binding": worst_name,
+ "problems": problems,
+ "footprint_m": [[round(value, 4) for value in point] for point in shape["footprint"]],
+ "zones_m": {side: [[round(value, 4) for value in point] for point in zone] for side, zone in shape["zones"].items()},
+ "z0_m": round(shape["z0_m"], 4),
+ "size_m": [round(value, 4) for value in shape["size_m"]],
+ "rot": item.get("rot", 0),
+ "asset": item.get("asset"),
+ "asset_rot": item.get("asset_rot", 0),
+ "paint": item.get("paint"),
+ "material": item.get("material"),
+ "fit_size": item.get("fit_size", True),
+ })
+ return rows
+
+
+def coordination_markdown(rows):
+ marks = {"fits": "✓ fits", "tight": "▲ tight", "clash": "✕ clash"}
+ lines = [
+ "| Item | Room | Status | Margin | Binding check | Action |",
+ "| --- | --- | --- | --- | --- | --- |",
+ ]
+ for row in rows:
+ action = "none"
+ if row["status"] == "clash":
+ action = f"move or resize: {-row['margin_m'] * 1000:.0f} mm short"
+ elif row["status"] == "tight":
+ action = "confirm on site"
+ lines.append(
+ f"| {row['id']} {row['name']} | {row['room']} | {marks[row['status']]} | "
+ f"{row['margin_m'] * 1000:+.0f} mm | {row['binding']} | {action} |"
+ )
+ return "\n".join(lines) + "\n"
+
+
+# ---------------------------------------------------------------- card
+
+
+def draw_card(units_rows, equipment_rows, output_path, title):
+ """A coordination card: unit faults first, then each item with a shape-coded status mark."""
+ from PIL import Image, ImageDraw, ImageFont
+
+ def font(size, bold=False):
+ for name in (("arialbd.ttf", "DejaVuSans-Bold.ttf") if bold else ("arial.ttf", "DejaVuSans.ttf")):
+ try:
+ return ImageFont.truetype(name, size)
+ except OSError:
+ continue
+ return ImageFont.load_default()
+
+ ink = (28, 30, 34)
+ muted = (110, 114, 122)
+ paper = (246, 245, 241)
+ row_fill = (236, 234, 228)
+ colours = {"fits": (46, 125, 80), "tight": (196, 130, 20), "clash": (200, 50, 45)}
+ width = 1600
+ row_height = 64
+ unit_faults = [row for row in units_rows if row["status"] != "ok"]
+ height = 260 + row_height * (len(unit_faults) + len(equipment_rows)) + (120 if unit_faults else 0)
+ image = Image.new("RGB", (width, height), paper)
+ draw = ImageDraw.Draw(image)
+ draw.text((72, 64), title, font=font(52, bold=True), fill=ink)
+ cursor = 160
+
+ def mark(status, x, y):
+ colour = colours[status]
+ if status == "fits":
+ draw.ellipse((x, y, x + 30, y + 30), fill=colour)
+ draw.line((x + 8, y + 16, x + 13, y + 22, x + 23, y + 9), fill=paper, width=4)
+ elif status == "tight":
+ draw.polygon((x + 15, y, x + 30, y + 30, x, y + 30), fill=colour)
+ else:
+ draw.rectangle((x, y, x + 30, y + 30), fill=colour)
+ draw.line((x + 8, y + 8, x + 22, y + 22), fill=paper, width=4)
+ draw.line((x + 22, y + 8, x + 8, y + 22), fill=paper, width=4)
+
+ if unit_faults:
+ draw.text((72, cursor), "Units", font=font(30, bold=True), fill=ink)
+ cursor += 56
+ for row in unit_faults:
+ draw.rounded_rectangle((60, cursor, width - 60, cursor + row_height - 10), 12, fill=row_fill)
+ mark("clash", 84, cursor + 13)
+ draw.text((136, cursor + 14), row["label"], font=font(28, bold=True), fill=ink)
+ draw.text((560, cursor + 16), row["faults"][0][:78], font=font(24), fill=muted)
+ cursor += row_height
+ cursor += 24
+ draw.text((72, cursor), "Equipment", font=font(30, bold=True), fill=ink)
+ cursor += 56
+ for row in equipment_rows:
+ draw.rounded_rectangle((60, cursor, width - 60, cursor + row_height - 10), 12, fill=row_fill)
+ mark(row["status"], 84, cursor + 13)
+ draw.text((136, cursor + 14), f"{row['id']} {row['name']}", font=font(28, bold=True), fill=ink)
+ draw.text((700, cursor + 14), f"{row['margin_m'] * 1000:+.0f} mm", font=font(28, bold=True), fill=colours[row["status"]])
+ draw.text((860, cursor + 16), row["binding"][:52], font=font(24), fill=muted)
+ cursor += row_height
+ image.save(output_path)
+
+
+# ---------------------------------------------------------------- entry
+
+
+def main():
+ command, plan_path = sys.argv[1], pathlib.Path(sys.argv[2])
+ plan = json.loads(plan_path.read_text(encoding="utf-8"))
+ folder = plan_path.resolve().parent
+ report_path = folder / "fitout_report.json"
+ report = json.loads(report_path.read_text(encoding="utf-8")) if report_path.exists() else {}
+ failed = False
+ if command in ("units", "all"):
+ units_rows = reconcile_units(plan)
+ report["units"] = units_rows
+ (folder / "fitout_units.md").write_text(units_markdown(units_rows), encoding="utf-8")
+ for row in units_rows:
+ print(f"UNITS {row['status']:<16} {row['label']}: {row['resolved_m']:.3f} m")
+ for fault in row["faults"]:
+ print(f" {fault}")
+ failed |= any(row["status"] != "ok" for row in units_rows)
+ if command in ("fit", "all"):
+ equipment_rows = check_equipment(plan)
+ report["equipment"] = equipment_rows
+ (folder / "fitout_coordination.md").write_text(coordination_markdown(equipment_rows), encoding="utf-8")
+ for row in equipment_rows:
+ print(f"FIT {row['status']:<6} {row['margin_m'] * 1000:+6.0f} mm {row['id']} {row['name']}: {row['binding']}")
+ failed |= any(row["status"] == "clash" for row in equipment_rows)
+ if command == "all":
+ draw_card(report["units"], report["equipment"], folder / "fitout_card.png", plan.get("fitout_title", "Coordination"))
+ report_path.write_text(json.dumps(report, indent=1), encoding="utf-8")
+ sys.exit(1 if failed else 0)
+
+
+if __name__ == "__main__":
+ 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
index bfe8efb..ee06012 100644
--- 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
@@ -40,6 +40,8 @@ TEXTURED_MATERIALS = {
"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),
+ "corrugated_metal": ("corrugated_iron", 1.6, (0.78, 0.80, 0.82), 0.6, 0.9, 0.9),
+ "concrete_slab": ("concrete_floor_02", 3.0, (0.82, 0.80, 0.77), 0.3, 0.4, 0.75),
}
# name: (base colour, roughness, metallic)
@@ -66,6 +68,7 @@ PLAIN_MATERIALS = {
"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),
+ "stainless": ((0.62, 0.62, 0.60), 0.26, 1.0),
}
@@ -253,6 +256,29 @@ def make_lamp_material(strength):
return material
+FIT_ZONE_COLOURS = {
+ "fit_fits": (0.10, 0.62, 0.30),
+ "fit_tight": (1.0, 0.55, 0.05),
+ "fit_clash": (1.0, 0.08, 0.04),
+}
+
+
+def make_fit_zone_material(name):
+ """A see-through tinted volume that glows a little, so a service zone reads in any light."""
+ colour = FIT_ZONE_COLOURS[name]
+ material = bpy.data.materials.new(name)
+ material.use_nodes = True
+ material.blend_method = "BLEND"
+ tree = material.node_tree
+ shader = tree.nodes["Principled BSDF"]
+ shader.inputs["Base Color"].default_value = (*colour, 1)
+ shader.inputs["Emission Color"].default_value = (*colour, 1)
+ shader.inputs["Emission Strength"].default_value = 0.8 if name == "fit_clash" else 0.08
+ shader.inputs["Alpha"].default_value = 0.42 if name == "fit_clash" else 0.22
+ shader.inputs["Roughness"].default_value = 0.6
+ return material
+
+
_material_cache = {}
@@ -267,6 +293,8 @@ def get_material(name):
material = make_glass_material()
elif name.startswith("lamp_"):
material = make_lamp_material(float(name.split("_")[1]))
+ elif name in FIT_ZONE_COLOURS:
+ material = make_fit_zone_material(name)
else:
raise KeyError(f"unknown material {name}")
_material_cache[name] = 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
index 9aa602f..0a37bf0 100644
--- 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
@@ -144,8 +144,9 @@ def check_openings(plan, faults):
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")
+ leaf_metres = width_metres / max(1, opening.get("leaves", 1))
+ if kind == "door" and not 0.40 <= leaf_metres <= 1.3:
+ faults.append(f"door {opening['id']} has {leaf_metres:.2f} m leaves")
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:
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
index 07d4dff..9e994d9 100644
--- 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
@@ -27,7 +27,7 @@ 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}
+ options = {"plan": arguments[0], "out": arguments[1], "shots": None, "samples": 512, "scale": 100, "film": None, "frames": None, "size": "1920x1080"}
index = 2
while index < len(arguments):
name = arguments[index].lstrip("-")
@@ -37,7 +37,7 @@ def read_arguments():
return options
-def setup_cycles(samples, scale_percent):
+def setup_cycles(samples, scale_percent, size="1920x1080"):
scene = bpy.context.scene
scene.render.engine = "CYCLES"
cycles = scene.cycles
@@ -63,8 +63,9 @@ def setup_cycles(samples, scale_percent):
cycles.caustics_reflective = False
cycles.caustics_refractive = False
cycles.blur_glossy = 0.5
- scene.render.resolution_x = 1920
- scene.render.resolution_y = 1080
+ width, height = (int(value) for value in size.lower().split("x"))
+ scene.render.resolution_x = width
+ scene.render.resolution_y = height
scene.render.resolution_percentage = scale_percent
# Grass and scanned trees take minutes to sync; keep them between shots.
scene.render.use_persistent_data = True
@@ -230,6 +231,12 @@ def apply_cut(height, plan):
item.data = mesh
for name in ("roof", "ceilings"):
bpy.data.collections[name].hide_render = True
+ # Clash volumes stop just above the cut, a red patch over the poché of the wall they run into.
+ fitout = bpy.data.collections.get("fitout")
+ if fitout is not None:
+ for item in fitout.objects:
+ for vertex in item.data.vertices:
+ vertex.co.z = min(vertex.co.z, height + 0.02)
for item in bpy.data.collections["furnish"].objects:
if item.location.z > height:
item.hide_render = True
@@ -517,6 +524,8 @@ class BuildUp:
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)
+ fitout = bpy.data.collections.get("fitout")
+ self.fit_zones = list(fitout.all_objects) if fitout else []
# 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}
@@ -572,6 +581,9 @@ class BuildUp:
wanted = self.furnish_scale[item.name] * max(growth, 0.001)
if (item.scale - wanted).length > 1e-5:
item.scale = wanted
+ # Service zones land once the equipment stands, so the clash is the last thing to appear.
+ for item in self.fit_zones:
+ set_hidden(item, value < end)
def apply_roof(self, value):
start, end = self.stages["roof"]
@@ -630,6 +642,13 @@ def render_film(plan, film, scale, out_folder, frame_limit):
render_to(target_path)
+def show_fit_zones(wanted):
+ """Equipment service zones from fitout_check.py: on unless a shot or film sets `fit_zones: false`."""
+ fitout = bpy.data.collections.get("fitout")
+ if fitout is not None:
+ fitout.hide_render = not wanted
+
+
def main():
options = read_arguments()
plan_path = pathlib.Path(options["plan"])
@@ -639,7 +658,7 @@ def main():
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"]))
+ setup_cycles(int(options["samples"]), int(options["scale"]), options["size"])
site = plan.get("site", {})
setup_world(site)
add_lamps(plan, scale)
@@ -653,6 +672,7 @@ def main():
for portal in portals:
portal.hide_render = not film.get("interior", False)
bpy.context.scene.view_settings.exposure = film.get("exposure", 0.0)
+ show_fit_zones(film.get("fit_zones", True))
render_film(plan, film, scale, out_folder, options["frames"])
return
shots = plan.get("shots", [])
@@ -668,6 +688,7 @@ def main():
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"]
+ show_fit_zones(shot.get("fit_zones", True))
camera_for(shot, scale, shot["name"])
bpy.context.view_layer.update()
bpy.context.scene.view_settings.exposure = 0.0
diff --git a/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/test_fitout_check.py b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/test_fitout_check.py
new file mode 100644
index 0000000..9ff4c31
--- /dev/null
+++ b/plugins/build-house-from-plan/skills/build-house-from-plan/scripts/test_fitout_check.py
@@ -0,0 +1,153 @@
+"""Tests for fitout_check.py on examples/fitout-fixture.json, which plants one wrong conversion.
+
+ uv run --no-project --with pillow python scripts/test_fitout_check.py
+"""
+
+import copy
+import json
+import pathlib
+import sys
+import tempfile
+import unittest
+
+SCRIPTS = pathlib.Path(__file__).resolve().parent
+sys.path.insert(0, str(SCRIPTS))
+
+import fitout_check # noqa: E402
+
+FIXTURE = SCRIPTS.parent / "examples" / "fitout-fixture.json"
+
+
+def load_fixture():
+ return json.loads(FIXTURE.read_text(encoding="utf-8"))
+
+
+def by_id(rows):
+ return {row["id"]: row for row in rows}
+
+
+class ParseLength(unittest.TestCase):
+ def test_written_forms(self):
+ cases = {
+ "6.10 m": 6.10, "6100 mm": 6.10, "610 cm": 6.10, "4.2m": 4.2,
+ "20'-0\"": 6.096, "20' 0\"": 6.096, "20'": 6.096, "20 ft": 6.096,
+ "13'-9 1/2\"": 4.2037, "165\"": 4.191, "165 in": 4.191, "5 ft 6 in": 1.6764,
+ "39 3/8\"": 1.0001, "1,200 mm": 1.2, "20′-0″": 6.096,
+ }
+ for text, metres in cases.items():
+ with self.subTest(text=text):
+ self.assertAlmostEqual(fitout_check.parse_length(text), metres, places=3)
+
+ def test_bare_number_uses_sheet_default(self):
+ self.assertAlmostEqual(fitout_check.parse_length("6100", "mm"), 6.1)
+ self.assertAlmostEqual(fitout_check.parse_length("48", "in"), 1.2192)
+ with self.assertRaises(ValueError):
+ fitout_check.parse_length("6100")
+
+ def test_dual_annotation(self):
+ primary, written = fitout_check.read_dimension_text("20'-0\" (6.40 m)", None)
+ self.assertAlmostEqual(primary, 6.096, places=3)
+ self.assertAlmostEqual(written, 6.40)
+ primary, written = fitout_check.read_dimension_text("6.10 m [20'-0\"]", None)
+ self.assertAlmostEqual(written, 6.096, places=3)
+
+ def test_garbage_is_refused(self):
+ for text in ("about six metres", "6.1 parsecs", ""):
+ with self.subTest(text=text), self.assertRaises(ValueError):
+ fitout_check.parse_length(text, "m")
+
+
+class Units(unittest.TestCase):
+ def test_planted_wrong_conversion_is_caught(self):
+ rows = by_id(fitout_check.reconcile_units(load_fixture()))
+ width = rows["room_width"]
+ self.assertEqual(width["status"], "wrong conversion")
+ self.assertIn("6.096 m, written as 6.400 m", width["faults"][0])
+ self.assertAlmostEqual(width["resolved_m"], 6.098, places=3)
+
+ def test_agreeing_sheets_pass(self):
+ rows = by_id(fitout_check.reconcile_units(load_fixture()))
+ for dimension_id in ("room_depth", "ceiling", "door"):
+ with self.subTest(dimension_id=dimension_id):
+ self.assertEqual(rows[dimension_id]["status"], "ok")
+
+ def test_real_conflict_is_flagged_and_resolved_low(self):
+ plan = load_fixture()
+ plan["dimensions"].append({"id": "room_depth", "sheet": "M-201", "text": "27'"})
+ depth = by_id(fitout_check.reconcile_units(plan))["room_depth"]
+ self.assertEqual(depth["status"], "conflict")
+ self.assertAlmostEqual(depth["resolved_m"], 8.0, places=3)
+
+ def test_model_built_from_the_wrong_conversion_is_flagged(self):
+ plan = load_fixture()
+ plan["dimensions"][0]["b"] = [6.4, 4]
+ width = by_id(fitout_check.reconcile_units(plan))["room_width"]
+ self.assertEqual(width["status"], "model off")
+ self.assertIn("+302 mm", width["faults"][-1])
+
+
+class Fit(unittest.TestCase):
+ def test_roaster_laid_out_for_the_wrong_width_clashes(self):
+ rows = by_id(fitout_check.check_equipment(load_fixture()))
+ roaster = rows["R1"]
+ self.assertEqual(roaster["status"], "clash")
+ self.assertEqual(roaster["binding"], "back service zone inside the room")
+ self.assertAlmostEqual(roaster["margin_m"], -0.30, places=2)
+
+ def test_same_layout_fits_in_the_room_it_was_drawn_for(self):
+ plan = load_fixture()
+ plan["rooms"][0]["poly"] = [[0, 0], [6.4, 0], [6.4, 8], [0, 8]]
+ roaster = by_id(fitout_check.check_equipment(plan))["R1"]
+ self.assertNotEqual(roaster["status"], "clash")
+
+ def test_other_items(self):
+ rows = by_id(fitout_check.check_equipment(load_fixture()))
+ self.assertEqual(rows["C1"]["status"], "fits")
+ self.assertEqual(rows["G1"]["status"], "fits")
+ self.assertEqual(rows["P1"]["status"], "tight")
+ self.assertAlmostEqual(rows["P1"]["margin_m"], 0.075, places=3)
+
+ def test_ceiling_and_door(self):
+ plan = load_fixture()
+ plan["rooms"][0]["ceiling"] = 2.8
+ roaster = by_id(fitout_check.check_equipment(plan))["R1"]
+ names = [problem["check"] for problem in roaster["problems"]]
+ self.assertIn("height with top clearance under the ceiling", names)
+ plan = load_fixture()
+ plan["equipment"][1]["at"] = [2.45, 0.9]
+ tray = by_id(fitout_check.check_equipment(plan))["C1"]
+ self.assertEqual(tray["status"], "clash")
+ self.assertIn("door D1", tray["binding"])
+
+
+class Outputs(unittest.TestCase):
+ def test_all_writes_tables_card_and_fails(self):
+ with tempfile.TemporaryDirectory() as folder:
+ plan_path = pathlib.Path(folder) / "plan.json"
+ plan_path.write_text(json.dumps(load_fixture()), encoding="utf-8")
+ sys.argv = ["fitout_check.py", "all", str(plan_path)]
+ with self.assertRaises(SystemExit) as stopped:
+ fitout_check.main()
+ self.assertEqual(stopped.exception.code, 1)
+ for name in ("fitout_units.md", "fitout_coordination.md", "fitout_report.json", "fitout_card.png"):
+ self.assertTrue((pathlib.Path(folder) / name).exists(), name)
+ table = (pathlib.Path(folder) / "fitout_coordination.md").read_text(encoding="utf-8")
+ self.assertIn("✕ clash", table)
+ self.assertIn("300 mm short", table)
+
+ def test_clean_plan_passes(self):
+ plan = copy.deepcopy(load_fixture())
+ plan["dimensions"][1]["text"] = "20'-0\" (6.10 m)"
+ plan["equipment"][0]["at"] = [4.775, 5.0]
+ plan["equipment"][1]["at"] = [2.3, 5.2]
+ with tempfile.TemporaryDirectory() as folder:
+ plan_path = pathlib.Path(folder) / "plan.json"
+ plan_path.write_text(json.dumps(plan), encoding="utf-8")
+ sys.argv = ["fitout_check.py", "all", str(plan_path)]
+ with self.assertRaises(SystemExit) as stopped:
+ fitout_check.main()
+ self.assertEqual(stopped.exception.code, 0)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=1)