Single place to convert your 2D floor plans to 3d model (no LLM)
Python
"""plan JSON -> furnished 3D house -> baked lighting -> web model (house.glb + lightmaps + meta.json).
Run: blender -b --factory-startup -P planto3d/blender/gen.py -- plan.json OUTDIR [--quality draft|high] [--no-bake]
Progress lines: 'PROGRESS <0-100> <message>' on stdout (read by the server)."""
import json, math, os, shutil, sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path[:0] = [HERE, os.path.join(HERE, "..")]
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
PLAN, JOB = os.path.abspath(argv[0]), os.path.abspath(argv[1])
QUALITY = argv[argv.index("--quality") + 1] if "--quality" in argv else "high"
BAKE = "--no-bake" not in argv
os.makedirs(JOB, exist_ok=True)
import bpy # noqa: E402
import lib # noqa: E402
from lib import ASSETS, MATS, collection, disjoint, mat, mesh_from_boxes, overlap, scene, set_level, subtract_all # noqa: E402
import furniture # noqa: E402
from furniture import build, ceiling_light, done, hang_light, item, p_cyl, p_pleats, place, tree # noqa: E402
import furnish # noqa: E402
from quantities import FLOOR_MAT, TILE_H, opening_heights, zone_at # noqa: E402 (shared with the quantities sheet)
import themes # noqa: E402
def progress(p, msg):
print(f"PROGRESS {int(p)} {msg}", flush=True)
plan = json.load(open(PLAN))
H, SLAB = plan.get("floor_height", 10.0), plan.get("slab", 0.5)
FFH = H + SLAB
lib.WALL_H = H
floors = plan["floors"]
NF = len(floors)
T = themes.load(plan.get("theme")) # furniture, decor, colours and floors of the interior theme
furniture.T = T
progress(2, "building walls")
mat("tile", tex="large_floor_tiles_02", tile=1.5)
mat("pavers", tex="herringbone_pavement", tile=1.6)
mat("asphalt", tex="asphalt_02", tile=4.0)
mat("footpath", tex="square_concrete_pavers", tile=1.5)
mat("pebbles", tex="dry_river_pebbles", tile=0.8)
mat("terrace", tex="concrete_tiles", tile=1.5)
mat("turf", tex="leafy_grass", tile=1.0, tint=(0.5, 0.75, 0.35))
mat("exterior", (0.93, 0.91, 0.87), 0.9, tex="white_plaster_02", tile=2.5, albedo=False)
mat("cushion", rough=0.95, tex="caban", tile=0.5, tint=(0.55, 0.45, 0.35))
OPEN_SKY = {"open", "garden", "yard"} # no slab above these
FINISHES = themes.FINISHES # the walkthrough can swap these
def linear(hexc): # "#rrggbb" (sRGB) -> Blender's linear colour values
return tuple(v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 for v in (int(hexc[i:i + 2], 16) / 255 for i in (1, 3, 5)))
wall_hex = plan.get("wall_color") or T["wall"] # picked on the review page, else the theme's; absent = lib's warm white
if wall_hex:
MATS["wall"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (*linear(wall_hex), 1)
# ------------------------------------------------------------------ helpers
def window_parts(windows):
"""frame + glass boxes for (x0,x1,y0,y1,sill,head) given at exact wall thickness."""
out = []
for x0, x1, y0, y1, s, h in windows:
fr = 0.18
if (x1 - x0) > (y1 - y0):
ym = (y0 + y1) / 2
t0, t1 = ym - 0.1, ym + 0.1
out += [(x0, x1, t0, t1, s, s + fr, "frame"), (x0, x1, t0, t1, h - fr, h, "frame"),
(x0, x0 + fr, t0, t1, s, h, "frame"), (x1 - fr, x1, t0, t1, s, h, "frame")]
n = max(1, round((x1 - x0) / 2.5))
out += [(x0 + (x1 - x0) * i / n - fr / 2, x0 + (x1 - x0) * i / n + fr / 2, t0, t1, s, h, "frame") for i in range(1, n)]
out.append((x0, x1, ym - 0.01, ym + 0.01, s, h, "glass"))
else:
xm = (x0 + x1) / 2
t0, t1 = xm - 0.1, xm + 0.1
out += [(t0, t1, y0, y1, s, s + fr, "frame"), (t0, t1, y0, y1, h - fr, h, "frame"),
(t0, t1, y0, y0 + fr, s, h, "frame"), (t0, t1, y1 - fr, y1, s, h, "frame")]
n = max(1, round((y1 - y0) / 2.5))
out += [(t0, t1, y0 + (y1 - y0) * i / n - fr / 2, y0 + (y1 - y0) * i / n + fr / 2, s, h, "frame") for i in range(1, n)]
out.append((xm - 0.01, xm + 0.01, y0, y1, s, h, "glass"))
return out
def bbox_of(rs):
return (min(r[0] for r in rs), max(r[1] for r in rs), min(r[2] for r in rs), max(r[3] for r in rs))
def boxes_minus(base, holes):
return disjoint(subtract_all([base], holes))
CURTAIN_ROOMS = {"bedroom", "living", "dining", "study", "room", "dress", "puja"}
def curtains(f, items):
"""linen curtains on a brass rod at each full-size window of a living room or bedroom, on the room side.
Floor length, unless furniture stands in front of the window: then they stop above the sill."""
for o in f["openings"]:
if o["type"] != "window":
continue
sill, head = opening_heights(f, o)
if sill >= 5: # high ventilator or bathroom window
continue
x0, x1, y0, y1 = o["rect"]
along_x = o["axis"] == "x"
a0, a1 = (x0, x1) if along_x else (y0, y1)
for side in (-1, 1):
face = (y0 if side < 0 else y1) if along_x else (x0 if side < 0 else x1)
probe = (((x0 + x1) / 2, face + side), (face + side, (y0 + y1) / 2))[not along_x]
zn = zone_at(f, *probe)
if not zn or zn["type"] not in CURTAIN_ROOMS:
continue
plane = face + side * 0.3
strip = (a0 - 0.6, a1 + 0.6, *sorted((face, face + side * 1.2)))
if not along_x:
strip = (strip[2], strip[3], strip[0], strip[1])
blocked = any(it.get("box") and overlap((*strip, 0, 1), (*it["box"], 0, 1)) for it in items)
bottom = sill - 0.3 if blocked else 0.1
rod = min(head + 0.6, lib.WALL_H - 0.3)
c = (a0 + a1) / 2
# past the window edge by 0.6 ft, unless a door or another window is right there
line = lambda q: (q["rect"][2] + q["rect"][3]) / 2 if along_x else (q["rect"][0] + q["rect"][1]) / 2
near = [(q["rect"][0], q["rect"][1]) if along_x else (q["rect"][2], q["rect"][3]) for q in f["openings"]
if q is not o and q["axis"] == o["axis"] and abs(line(q) - line(o)) < 0.3] # same wall
ext = [0.05 if any(a0 - 0.8 <= e <= a0 + 0.01 for _, e in near) else 0.6,
0.05 if any(a1 - 0.01 <= e <= a1 + 0.8 for e, _ in near) else 0.6]
r = item("curtain", c if along_x else plane, plane if along_x else c, 0 if along_x else 90)
lo, hi = a0 - ext[0] - c, a1 + ext[1] - c # rod ends, local x
p_cyl(r, "curtain_rod", 0.05, 0.05, hi - lo + 0.2, "brass", (lo - 0.1, 0, rod), rot=(0, 90, 0), segs=12)
for e in (lo - 0.1, hi + 0.1):
p_cyl(r, "rod_end", 0.1, 0.1, 0.12, "brass", (e - 0.06, 0, rod), rot=(0, 90, 0), segs=12)
pw = max(1.3, (a1 - a0) * 0.3)
for e, s_ in ((lo, 1), (hi, -1)): # each panel gathered at one end of the rod
p_pleats(r, "curtain", pw, rod - bottom, "curtain", (e + s_ * pw / 2, 0, bottom))
done(r, collide=False)
# ------------------------------------------------------------------ stairs
def stair_parts(f, rise):
"""flights + landing from the detected tread runs. The flight next to the UP word starts at floor level
at its UP end; the next flight starts where the previous one ended (dog-leg). -> (boxes, meta)"""
fl = [dict(s) for s in f["stairs"]]
if not fl:
return [], []
up = [s for s in fl if s["up"]] or fl[:1]
order = [up[0]] + [s for s in fl if s is not up[0]]
boxes, meta = [], []
z = 0.0
prev_end = None
per = rise / len(order)
for k, s in enumerate(order):
x0, x1, y0, y1 = s["rect"]
ax = 0 if s["axis"] == "x" else 1 # direction of travel along x or y
lo, hi = (x0, x1) if ax == 0 else (y0, y1)
if k == 0:
# start at the end nearest to the UP word
w = next((p for p in s["words"] if p[0].startswith("UP")), None)
pos = (w[1], w[2]) if w else ((x0 + x1) / 2, (y0 + y1) / 2)
start = lo if abs(pos[ax] - lo) < abs(pos[ax] - hi) else hi
else:
start = lo if abs(prev_end - lo) < abs(prev_end - hi) else hi
d = 1 if start == lo else -1
n = max(3, s["steps"])
run = (hi - lo) / n
for i in range(n):
a = start + d * i * run
b = a + d * run
a, b = min(a, b), max(a, b)
zt = z + per * (i + 1) / n
zb = max(0.0, z + per * i / n - 0.6) # a 0.6 ft waist, not solid to the floor: the flight of the storey
bx = (a, b, y0, y1, zb, zt) if ax == 0 else (x0, x1, a, b, zb, zt) # above stands over this one
boxes.append((*bx, "stair"))
end = start + d * (hi - lo)
meta.append(dict(rect=[x0, x1, y0, y1], axis=s["axis"], start=start, dir=d, z0=z, z1=z + per))
z += per
prev_end = end
# landing beyond this flight's end, across the whole stair, if another flight follows
if k + 1 < len(order):
sb = bbox_of([q["rect"] for q in order])
depth = (y1 - y0) if ax == 0 else (x1 - x0)
if ax == 0:
L = (end, end + d * depth) if d > 0 else (end + d * depth, end)
lb = (max(L[0], sb[0] - depth), min(L[1], sb[1] + depth), sb[2], sb[3])
else:
L = (end, end + d * depth) if d > 0 else (end + d * depth, end)
lb = (sb[0], sb[1], max(L[0], sb[2] - depth), min(L[1], sb[3] + depth))
boxes.append((*lb, z - 0.5, z, "stair"))
meta.append(dict(rect=list(lb), landing=True, z0=z, z1=z))
return boxes, meta
LIGHT_ROOMS = {"living", "dining", "bedroom", "study", "dress", "passage"} # where a theme hangs its own light
# ------------------------------------------------------------------ the theme's colours on the built-in pieces
PAINT = dict(wood=("teak", "wall_accent"), cabinet=("laminate_w", "painted_wood"), fabric=("velvet", "velvet_head", "cushion", "linen_sofa"),
curtain=("curtain",), rug=("rug", "rug_round"), accent=("jacquard", "throw", "quilt"))
for key, names in PAINT.items():
if T["colours"].get(key):
rgb = linear(T["colours"][key])
for n in names: # made again in the theme's colour (and texture), keeping the weave or grain
sp = dict(lib.SPEC[n], **({"tex": T["tex"][key]} if key in T.get("tex", {}) else {}))
if sp["tex"] and sp["albedo"]:
sp.update(grey=True, tint=tuple(min(1.0, c / 0.8) for c in rgb)) # (the grey photo averages 0.8)
else:
sp["color"] = rgb
mat(n, **sp)
# ------------------------------------------------------------------ build each storey
COLLIDERS, META_FLOORS, LAMPS = [], [], []
by_floor = {}
def new_objects(before):
return [o for o in bpy.data.objects if o not in before]
bboxes = [bbox_of([w[:4] for w in f["walls"]]) for f in floors]
stair_box_prev = None
for k, f in enumerate(floors):
z = k * FFH
set_level(z)
before = set(bpy.data.objects)
low_h = 5.0 if k == 0 else 3.5
cuts, wins, door_list = [], [], []
for o in f["openings"]:
x0, x1, y0, y1 = o["rect"]
s, hd = opening_heights(f, o)
if o["axis"] == "x":
c = (x0, x1, y0 - 0.06, y1 + 0.06, s, hd)
else:
c = (x0 - 0.06, x1 + 0.06, y0, y1, s, hd)
cuts.append(c)
if o["type"] == "window":
wins.append((x0, x1, y0, y1, s, hd))
else:
door_list.append(o)
walls_f = [list(w) for w in f["walls"]]
# a wall standing in a doorway (a double line in the drawing) blocks the door: cut the door's path through it
path = [(r[0] - 1.5, r[1] + 1.5, r[2] + 0.15, r[3] - 0.15, -1, 2) if o["axis"] == "y" else
(r[0] + 0.15, r[1] - 0.15, r[2] - 1.5, r[3] + 1.5, -1, 2) for o in f["openings"] if o["type"] != "window" for r in [o["rect"]]]
walls_f = [[*b[:4], w[4]] for w in walls_f for b in subtract_all([(*w[:4], 0, 1)], path)
if b[1] - b[0] > 0.05 and b[3] - b[2] > 0.05]
if f["stairs"]:
fb = bbox_of([s["rect"] for s in f["stairs"]])
ax = f["stairs"][0]["axis"]
for w in walls_f: # low walls in the stair band (mid wall, landing edges) stop where the flights stop
cx, cy = (w[0] + w[1]) / 2, (w[2] + w[3]) / 2
in_band = (fb[2] - 0.2 <= cy <= fb[3] + 0.2 and fb[0] - 6 <= cx <= fb[1] + 6) if ax == "x" else \
(fb[0] - 0.2 <= cx <= fb[1] + 0.2 and fb[2] - 6 <= cy <= fb[3] + 6)
if w[4] and in_band:
if ax == "x":
w[0], w[1] = max(w[0], fb[0]), min(w[1], fb[1])
else:
w[2], w[3] = max(w[2], fb[2]), min(w[3], fb[3])
walls_f = [w for w in walls_f if w[1] - w[0] > 0.05 and w[3] - w[2] > 0.05]
# a mid wall drawn dashed comes in pieces: join low pieces on one line with small gaps
merged = True
while merged:
merged = False
for a in walls_f:
for b in walls_f:
if a is b or not (a[4] and b[4]):
continue
if ax == "x" and abs(a[2] - b[2]) < 0.1 and abs(a[3] - b[3]) < 0.1 and -0.05 < b[0] - a[1] < 1.0:
a[1] = b[1]; walls_f.remove(b); merged = True; break
if ax == "y" and abs(a[0] - b[0]) < 0.1 and abs(a[1] - b[1]) < 0.1 and -0.05 < b[2] - a[3] < 1.0:
a[3] = b[3]; walls_f.remove(b); merged = True; break
if merged:
break
f["walls"] = walls_f
wb = [(*w[:4], 0, (low_h if w[4] else H)) for w in f["walls"]]
# detected openings are gaps between walls: fill the wall below the sill and above the head (lintel)
for o, c in zip(f["openings"], cuts):
r = o["rect"]
touching = [w for w in f["walls"] if w[0] <= r[1] + 0.3 and r[0] <= w[1] + 0.3 and w[2] <= r[3] + 0.3 and r[2] <= w[3] + 0.3]
top = H if any(not w[4] for w in touching) or not touching else low_h
if c[4] > 0:
wb.append((*r, 0, c[4]))
if c[5] < top:
wb.append((*r, c[5], top))
wb = disjoint(subtract_all(wb, cuts))
mesh_from_boxes(f"walls_{k}", [(*b, "wall") for b in wb])
parts = window_parts(wins)
mesh_from_boxes(f"window_frames_{k}", [b for b in parts if b[6] == "frame"], bevel=0.005)
mesh_from_boxes(f"glass_{k}", [b for b in parts if b[6] == "glass"])
# door frames only: leaves of neighbouring doors swing into each other and hide side doors
frames = []
for o in door_list:
x0, x1, y0, y1 = o["rect"]
t = 0.25
if o["axis"] == "x":
frames += [(x0, x0 + t, y0, y1, 0, 7, "teak"), (x1 - t, x1, y0, y1, 0, 7, "teak"), (x0, x1, y0, y1, 7 - t, 7, "teak")]
else:
frames += [(x0, x1, y0, y0 + t, 0, 7, "teak"), (x0, x1, y1 - t, y1, 0, 7, "teak"), (x0, x1, y0, y1, 7 - t, 7, "teak")]
mesh_from_boxes(f"door_frames_{k}", frames, bevel=0.004)
# floors per zone (none over the stairwell coming up from below)
fl = []
well = [(*stair_box_prev, -9, 99)] if stair_box_prev else []
for i, zn in enumerate(f["rooms"]):
m = zn.get("floor") or T["floors"].get(zn["type"]) or FLOOR_MAT.get(zn["type"], "tile") # review page, theme, type
if m in FINISHES: # the room's own copy, so the walkthrough can change this floor alone (it finds it by name)
MATS[f"floor_{k}_{i}"] = MATS[m].copy()
MATS[f"floor_{k}_{i}"].name = f"floor_{k}_{i}"
MATS[f"floor_{k}_{i}"]["finish"], m = m, f"floor_{k}_{i}"
fl += [(*b[:4], -0.02, 0.0, m) for r in zn["rects"] for b in subtract_all([(*r, -0.02, 0.0)], well)]
mesh_from_boxes(f"floor_{k}", fl)
# wall tiles to TILE_H (7 ft) in toilets
# (the room's cells stop a little short of the wall face, so door holes are widened across for the tiles,
# and edges shared by two slices of the same room are not walls)
tiles = []
door_holes = [(c[0] - 0.6, c[1] + 0.6, c[2], c[3], c[4], c[5]) if o["axis"] == "y" else
(c[0], c[1], c[2] - 0.6, c[3] + 0.6, c[4], c[5]) for o, c in zip(f["openings"], cuts)]
for zn in f["rooms"]:
if zn["type"] != "toilet":
continue
for r in zn["rects"]:
x0, x1, y0, y1 = r
tt = 0.03
own = [(q[0] - 0.05, q[1] + 0.05, q[2] - 0.05, q[3] + 0.05, -1, 99) for q in zn["rects"] if q is not r]
tiles += subtract_all([(x0, x1, y0, y0 + tt, 0, TILE_H), (x0, x1, y1 - tt, y1, 0, TILE_H),
(x0, x0 + tt, y0, y1, 0, TILE_H), (x1 - tt, x1, y0, y1, 0, TILE_H)], own)
if tiles:
mesh_from_boxes(f"toilet_tiles_{k}", [(*b, "walltile") for b in disjoint(subtract_all(tiles, door_holes))])
# slab under this storey (k >= 1): the plan outline minus open-to-sky zones and the stairwell below
bb = bboxes[k]
holes = [(*r, -9, 99) for zn in f["rooms"] if zn["type"] in OPEN_SKY for r in zn["rects"]]
if k == 0:
mesh_from_boxes("plinth", [(bb[0] - 0.2, bb[1] + 0.2, bb[2] - 0.2, bb[3] + 0.2, -0.6, -0.02, "concrete")])
else:
prev = floors[k - 1]
# open only where it is open on both storeys: a court over a room is that room's ceiling, a room over a
# court stands on the slab
rooms = lambda fl: [(*r, -9, 99) for zn in fl["rooms"] if zn["type"] not in OPEN_SKY for r in zn["rects"]]
holes = subtract_all(holes, rooms(prev)) + subtract_all(
[(*r, -9, 99) for zn in prev["rooms"] if zn["type"] in OPEN_SKY for r in zn["rects"]], rooms(f))
sb = stair_box_prev
if sb:
holes.append((*sb, -9, 99))
mesh_from_boxes(f"slab_{k}", [(*b[:4], -SLAB, -0.02, "ceiling") for b in boxes_minus((*bb, -SLAB, -0.02), holes)])
# stairs rising from this storey
sboxes, smeta = stair_parts(f, FFH)
if sboxes:
mesh_from_boxes(f"stairs_{k}", sboxes)
stair_box_prev = bbox_of([b[:4] for b in sboxes])
stair_top = [q for q in smeta if not q.get("landing")][-1]
else:
stair_box_prev = None
items = furnish.floor_items(plan, f)
for it in items:
try:
build(it)
except Exception as e: # one bad item must not stop the build
print("ITEM FAILED", it["fn"], e, flush=True)
if items:
curtains(f, items)
# lamps (emissive panel + area light for the bake) in roofed rooms
for zn in f["rooms"]:
if zn["type"] not in furnish.INDOOR and zn["type"] not in ("balcony", "parking", "stair"):
continue
x0, x1, y0, y1 = furnish.max_rect(zn["rects"]) or max(zn["rects"], key=lambda r: (r[1] - r[0]) * (r[3] - r[2]))
if (x1 - x0) * (y1 - y0) < 6:
continue
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
if themes.has(T, "light") and zn["type"] in LIGHT_ROOMS and (x1 - x0) * (y1 - y0) >= 40:
hang_light(T["slots"]["light"], cx, cy)
else:
ceiling_light(cx, cy, 0.7)
LAMPS.append((cx, cy, z + H - 0.25, (x1 - x0) * (y1 - y0), zn["type"]))
by_floor[k] = new_objects(before)
# walker data (metres): full-height and low walls block, openings do not
F_ = lib.F
m = lambda r: [round(v * F_, 3) for v in r[:4]]
META_FLOORS.append(dict(
name=f.get("name", f"Floor {k}"), z=round(z * F_, 3), height=round(H * F_, 3),
colliders=[m(b) for b in subtract_all([(*w[:4], 0, 1) for w in f["walls"]],
[(c[0], c[1], c[2], c[3], 0, 1) for c in cuts if c[4] < 1])],
windows=[m(c) for c in cuts if c[4] >= 1], # gaps between the walls too, but with glass: they block like walls
rooms=[dict(label=zn.get("label") or zn["type"].title(), type=zn["type"], rects=[m(r) for r in zn["rects"]], i=i,
**({"floor": MATS[f"floor_{k}_{i}"]["finish"]} if f"floor_{k}_{i}" in MATS else {}))
for i, zn in enumerate(f["rooms"]) if zn["type"] not in ("duct",)],
stairs=[dict(s, rect=m(s["rect"]), z0=round((z + s["z0"]) * F_, 3), z1=round((z + s["z1"]) * F_, 3),
**({"start": round(s["start"] * F_, 3)} if "start" in s else {})) for s in smeta],
))
progress(5 + 25 * (k + 1) / NF, f"built {f.get('name', k)}")
# ------------------------------------------------------------------ roof + parapet + stair cabin (mumty)
top = NF * FFH
set_level(top)
before = set(bpy.data.objects)
bb = bboxes[-1]
holes = [(*r, -9, 99) for zn in floors[-1]["rooms"] if zn["type"] in OPEN_SKY for r in zn["rects"]]
# the slab is plaster underneath (the top storey's ceiling) and tiled on top (the terrace); open over the stairs
well = [(*stair_box_prev, -9, 99)] if stair_box_prev else []
mesh_from_boxes("roof", [(*b[:4], z0, z1, m) for b in boxes_minus((*bb, -SLAB, 0.0), holes + well)
for z0, z1, m in ((-SLAB, -0.04, "ceiling"), (-0.04, 0.0, "terrace"))])
t = 0.33
parapet = disjoint(subtract_all([ # (none along open courtyards)
(bb[0], bb[1], bb[2], bb[2] + t, 0, 3.5), (bb[0], bb[1], bb[3] - t, bb[3], 0, 3.5),
(bb[0], bb[0] + t, bb[2], bb[3], 0, 3.5), (bb[1] - t, bb[1], bb[2], bb[3], 0, 3.5)],
[(h[0] - t, h[1] + t, h[2] - t, h[3] + t, -9, 99) for h in holes]
# (none where the stair cabin's own wall stands: the two faces in one place bake black)
+ ([(stair_box_prev[0] - t, stair_box_prev[1] + t, stair_box_prev[2] - t, stair_box_prev[3] + t, -9, 99)] if stair_box_prev else [])))
mesh_from_boxes("parapet", [(*b, "exterior") for b in parapet])
roof_block = parapet + holes # walker on the terrace: the parapet, the cabin and the courtyards stop you
if stair_box_prev: # the top storey's stairs reach the roof: a small cabin over them with a door
x0, x1, y0, y1 = stair_box_prev
walls_m = disjoint([(x0 - t, x1 + t, y0 - t, y0, 0, 8), (x0 - t, x1 + t, y1, y1 + t, 0, 8),
(x0 - t, x0, y0, y1, 0, 8), (x1, x1 + t, y0, y1, 0, 8)])
# the door where the last flight comes up, so you walk straight out onto the roof
q = stair_top
end = q["start"] + q["dir"] * ((q["rect"][1] - q["rect"][0]) if q["axis"] == "x" else (q["rect"][3] - q["rect"][2]))
door = (end - 1, end + 1, *q["rect"][2:], -1, 7) if q["axis"] == "x" else (*q["rect"][:2], end - 1, end + 1, -1, 7)
ax = 0 if q["axis"] == "x" else 2
if not bb[ax] + t < end + q["dir"] * 1.5 < bb[ax + 1] - t: # it would open over the roof's edge: a side door
cx = (x0 + x1) / 2
door = (cx - 1.5, cx + 1.5, y1 - 1, y1 + 1, -1, 7)
walls_m = subtract_all(walls_m, [door])
roof_block += [b for b in walls_m if b[4] < 1] # (not the lintel over the door)
mesh_from_boxes("mumty", [(*b, "exterior") for b in walls_m] + [(x0 - t, x1 + t, y0 - t, y1 + t, 8, 8.5, "slab")])
by_floor[NF] = new_objects(before)
# ------------------------------------------------------------------ site: ground, road, trees, lamps
set_level(0)
before = set(bpy.data.objects)
X0, X1 = min(b[0] for b in bboxes), max(b[1] for b in bboxes)
Y0, Y1 = min(b[2] for b in bboxes), max(b[3] for b in bboxes)
mesh_from_boxes("ground", [(X0 - 60, X1 + 60, Y0 - 12, Y1 + 60, -0.65, -0.62, "turf")])
mesh_from_boxes("road", [(X0 - 60, X1 + 60, Y0 - 34, Y0 - 12, -0.62, -0.6, "asphalt"),
(X0 - 60, X1 + 60, Y0 - 12, Y0 - 6, -0.62, -0.45, "footpath")])
mesh_from_boxes("apron", [(X0 - 0.2, X1 + 0.2, Y0 - 6, Y0 - 0.2, -0.62, -0.58, "pavers")])
site = new_objects(before)
for k, (tx, ty, sz) in enumerate(((X0 - 16, Y0 - 8.5, 1.0), (X1 + 16, Y0 - 8.5, 0.85), (X0 - 20, Y1 - 10, 1.2),
(X1 + 22, Y1 - 4, 1.0), ((X0 + X1) / 2 + 20, Y0 - 40, 1.1), ((X0 + X1) / 2 - 25, Y0 - 42, 0.9))):
tree(tx, ty, sz, seed=k + 1)
place("street_lamp_01", (X0 + X1) / 2 - 12, Y0 - 9.5, 90, collide=False)
trees = [o for o in new_objects(before) if o not in site]
progress(32, "lighting")
# ------------------------------------------------------------------ lights + world
world = bpy.data.worlds.new("sky")
scene.world = world
world.use_nodes = True
wn = world.node_tree
env = wn.nodes.new("ShaderNodeTexEnvironment")
env.image = bpy.data.images.load(os.path.join(ASSETS, "hdri", "sky.hdr"))
wn.links.new(env.outputs["Color"], wn.nodes["Background"].inputs["Color"])
wn.nodes["Background"].inputs["Strength"].default_value = 1.0
sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN"))
sun.data.energy = 4.0
sun.data.angle = math.radians(1.5)
sun.rotation_euler = (math.radians(52), 0, math.radians(-28))
collection("lights").objects.link(sun)
for cx, cy, zz, a, typ in LAMPS:
L = bpy.data.lights.new("lamp", "AREA")
L.energy = (14 if typ in furnish.INDOOR else 8) * a * lib.F * lib.F
L.size, L.shape = 0.6, "SQUARE"
L.color = (1.0, 0.9, 0.78)
o = bpy.data.objects.new("lamp", L)
o.location = (cx * lib.F, cy * lib.F, zz * lib.F)
collection("lights").objects.link(o)
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(JOB, "house.blend"))
progress(35, "model built")
# ------------------------------------------------------------------ bake + export
import bake # noqa: E402
# imported models (scans, uploads) get a light map of their own per storey: their many small faces crowd the walls'
# map (blurry walls) and can make its unwrap fail. Baked first: joining keeps their world place before their parents go.
model_meshes = {o.data for objs in [*furniture.PROTO.values(), *furniture.UPLOADS.values()] if objs for o in objs if o.type == "MESH"}
groups = {}
for k, objs in by_floor.items():
models = [o for o in objs if o.type == "MESH" and o.data in model_meshes]
if models:
groups[f"level_{k}_models"] = models
groups[f"level_{k}"] = [o for o in objs if o not in models]
groups["site"] = site
res = bake.bake_and_export(groups, unbaked=trees, out=JOB, quality=QUALITY, do_bake=BAKE, progress=progress)
# the floor textures the walkthrough's Finishes panel can lay (tile = metres per repeat, as the UVs were made)
os.makedirs(os.path.join(JOB, "finishes"), exist_ok=True)
finishes = {}
for n in FINISHES:
shutil.copy(os.path.join(ASSETS, "textures", MATS[n]["tex"], "diff.jpg"), os.path.join(JOB, "finishes", n + ".jpg"))
finishes[n] = dict(file=f"finishes/{n}.jpg", tile=MATS[n]["tile"])
meta = dict(version=1, floors=META_FLOORS, roof_z=round(top * lib.F, 3), eye=1.6,
roof=dict(colliders=[[round(v * lib.F, 3) for v in b[:4]] for b in roof_block]),
bounds=[round(v * lib.F, 3) for v in (X0, X1, Y0, Y1)], finishes=finishes, **res)
with open(os.path.join(JOB, "meta.json"), "w") as fh:
json.dump(meta, fh)
progress(100, "done")
print("GEN OK", flush=True)
os._exit(0)