Skip to content

Single place to convert your 2D floor plans to 3d model (no LLM)

Python
12.6 KB
Raw Blame
"""Blender building blocks used by gen.py and furniture.py: materials and box meshes (units: feet).
Textures and models come from ../assets (python3 fetch_assets.py)."""
import bpy, bmesh, os
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))

ASSETS = os.path.join(os.path.dirname(HERE), "assets")
F = 0.3048  # feet -> metres
WALL_H = 10.0   # floor-to-ceiling, feet
LEVEL = 0.0     # z of the floor being furnished (feet); set with set_level() for upper storeys


def set_level(z):
    global LEVEL
    LEVEL = z

bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.unit_settings.system = "METRIC"

# ---------------------------------------------------------------- materials
MATS, SPEC = {}, {}


def tex_node(nt, path, non_color=False):
    n = nt.nodes.new("ShaderNodeTexImage")
    n.image = bpy.data.images.load(path, check_existing=True)
    if non_color:
        n.image.colorspace_settings.name = "Non-Color"
    return n


def _grey(img):
    """the photo's weave and shading without its colour (mean brightness 0.8), so a tint can set any colour"""
    if img.name + "_grey" in bpy.data.images:       # one copy per photo, however many colours use it
        return bpy.data.images[img.name + "_grey"]
    w, h = img.size
    px = np.empty(w * h * 4, np.float32)
    img.pixels.foreach_get(px)
    px = px.reshape(-1, 4)
    lum = px[:, :3] @ np.array([0.2126, 0.7152, 0.0722], np.float32)
    lum = np.clip(lum * (0.8 / max(float(lum.mean()), 1e-3)), 0, 1)
    out = bpy.data.images.new(img.name + "_grey", w, h)
    rgba = np.ones((w * h, 4), np.float32)
    rgba[:, :3] = lum[:, None]
    out.pixels.foreach_set(rgba.ravel())
    out.pack()
    return out


def _brushed():
    """brushed stainless steel: fine streaks along u (no such photo on Poly Haven)"""
    rnd = np.random.default_rng(7)
    n = 512
    rows = rnd.normal(0, 1, (n, 1)) * 0.035 + rnd.normal(0, 1, (n, n)) * 0.012
    k = np.ones(48, np.float32) / 48            # smear the speckle along u into streaks
    rows = np.array([np.convolve(np.tile(r, 2), k, "same")[n // 2:n // 2 + n] for r in rows])
    v = np.clip(0.72 + rows, 0, 1).astype(np.float32)
    img = bpy.data.images.new("brushed_steel", n, n)
    img.pixels.foreach_set(np.stack([v, v, v * 1.01, np.ones_like(v)], -1).clip(0, 1).ravel())
    img.pack()
    return img


def mat(name, color=(0.8, 0.8, 0.8), rough=0.5, metal=0.0, tex=None, tile=1.0, alpha=1.0,
        emit=0.0, tint=None, albedo=True, grey=False, image=None):
    """tile = metres covered by one texture repeat (UVs are written in metres / tile).
    grey: drop the photo's own colour so tint is the colour; image: a generated image as the albedo."""
    if image is None:          # how it was made, so a theme can make it again in its own colour (gen.py repaint)
        SPEC[name] = dict(color=color, rough=rough, metal=metal, tex=tex, tile=tile, alpha=alpha, emit=emit, tint=tint,
                          albedo=albedo, grey=grey)
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    nt = m.node_tree
    p = nt.nodes["Principled BSDF"]
    p.inputs["Base Color"].default_value = (*color, 1)
    p.inputs["Roughness"].default_value = rough
    p.inputs["Metallic"].default_value = metal
    if tex:
        d = os.path.join(ASSETS, "textures", tex)
        if albedo and os.path.exists(os.path.join(d, "diff.jpg")):   # albedo=False: bump only (smooth paint)
            t = tex_node(nt, os.path.join(d, "diff.jpg"))
            if grey:
                t.image = _grey(t.image)
            if tint:  # multiply albedo by a tint colour
                mix = nt.nodes.new("ShaderNodeMix")
                mix.data_type = "RGBA"
                mix.blend_type = "MULTIPLY"
                mix.inputs["Factor"].default_value = 1.0
                nt.links.new(t.outputs["Color"], mix.inputs[6])
                mix.inputs[7].default_value = (*tint, 1)
                nt.links.new(mix.outputs[2], p.inputs["Base Color"])
            else:
                nt.links.new(t.outputs["Color"], p.inputs["Base Color"])
        if os.path.exists(os.path.join(d, "rough.jpg")):
            r = tex_node(nt, os.path.join(d, "rough.jpg"), True)
            nt.links.new(r.outputs["Color"], p.inputs["Roughness"])
        if os.path.exists(os.path.join(d, "nor.jpg")):
            n = tex_node(nt, os.path.join(d, "nor.jpg"), True)
            nm = nt.nodes.new("ShaderNodeNormalMap")
            nt.links.new(n.outputs["Color"], nm.inputs["Color"])
            nt.links.new(nm.outputs["Normal"], p.inputs["Normal"])
    if image:
        t = nt.nodes.new("ShaderNodeTexImage")
        t.image = image
        nt.links.new(t.outputs["Color"], p.inputs["Base Color"])
    if alpha < 1:
        p.inputs["Alpha"].default_value = alpha
        if hasattr(m, "surface_render_method"):
            m.surface_render_method = "BLENDED"
        if hasattr(m, "blend_method"):
            try:
                m.blend_method = "BLEND"
            except Exception:
                pass
    if emit:
        p.inputs["Emission Color"].default_value = (*color, 1)
        p.inputs["Emission Strength"].default_value = emit
    m["tile"] = tile
    if tex:
        m["tex"] = tex
    MATS[name] = m
    return m


mat("wall", (0.86, 0.80, 0.70), 0.9, tex="white_plaster_02", tile=1.5, albedo=False)   # warm off-white paint
mat("wall_accent", rough=0.5, tex="american_walnut_veneer", tile=1.2, tint=(0.62, 0.42, 0.28))             # wood panel behind beds
mat("ceiling", (0.95, 0.94, 0.91), 0.95, tex="white_plaster_02", tile=2.0, albedo=False)
mat("exterior", (0.88, 0.78, 0.62), 0.95, tex="white_plaster_02", tile=2.5, albedo=False)
mat("slab", (0.6, 0.6, 0.58), 0.9)
mat("marble", tex="marble_01", tile=1.2)
mat("wood", tex="laminate_floor_02", tile=2.0)
mat("bathtile", tex="anti_skid_tiles", tile=0.6)
mat("walltile", tex="long_white_tiles", tile=0.9)
mat("terracotta", tex="terracotta_floor_tiles", tile=1.2)
mat("concrete", tex="concrete_floor", tile=2.0)
mat("grass", tex="leafy_grass", tile=1.5, tint=(0.55, 0.8, 0.4))
mat("granite", rough=0.15, tex="marble_01", tile=1.5, tint=(0.12, 0.11, 0.11))   # black marble slab
mat("stone_top", rough=0.2, tex="terrazzo_tiles", tile=0.9, grey=True, tint=(0.36, 0.35, 0.34))   # speckled granite worktop
mat("stone_wall", rough=0.2, tex="marble_01", tile=1.0, tint=(0.95, 0.93, 0.9))
mat("pebble_floor", rough=0.7, tex="dry_river_pebbles", tile=0.6)
mat("marble_top", rough=0.15, tex="marble_01", tile=1.0)
mat("stair", (0.62, 0.58, 0.52), 0.4, tex="granite_tile", tile=1.0)
mat("glass", (0.75, 0.85, 0.9), 0.05, alpha=0.18)
mat("frame", (0.92, 0.92, 0.92), 0.4)                 # uPVC/powder-coated window frames
mat("steel", (0.75, 0.75, 0.77), 0.25, 1.0)
mat("teak", rough=0.4, tex="black_walnut_veneer_01", tile=1.0, tint=(0.5, 0.3, 0.18))
mat("laminate_w", rough=0.4, tex="oak_veneer_01", tile=1.2)
mat("white_gloss", (0.93, 0.93, 0.92), 0.15)
mat("ceramic", (0.97, 0.97, 0.96), 0.08)
mat("sheet", rough=0.9, tex="stretch_poplin", tile=0.35, grey=True, tint=(1.0, 0.99, 0.97))
mat("duvet", rough=0.95, tex="waffle_pique_cotton", tile=0.3, grey=True, tint=(0.93, 0.9, 0.85))
mat("throw", rough=1.0, tex="knitted_fleece", tile=0.35, grey=True, tint=(0.62, 0.34, 0.24))
mat("velvet", rough=0.8, tex="velour_velvet", tile=0.5, grey=True, tint=(0.3, 0.42, 0.4))
mat("velvet_head", rough=0.8, tex="velour_velvet", tile=0.5, grey=True, tint=(0.62, 0.55, 0.48))
mat("jacquard", rough=0.9, tex="quatrefoil_jacquard_fabric", tile=0.35, grey=True, tint=(0.95, 0.72, 0.35))
mat("boucle", rough=1.0, tex="wool_boucle", tile=0.4, grey=True, tint=(0.95, 0.92, 0.86))
mat("fabric_blanket", rough=0.9, tex="floral_jacquard", tile=0.6, tint=(1.0, 0.75, 0.7))
mat("rug", rough=1.0, tex="hessian_380", tile=0.8, tint=(0.9, 0.75, 0.6))
mat("curtain", rough=0.9, tex="rough_linen", tile=0.6, grey=True, tint=(0.95, 0.9, 0.8))
mat("black", (0.02, 0.02, 0.02), 0.3)
mat("screen", (0.01, 0.01, 0.015), 0.05)
mat("light", (1.0, 0.95, 0.85), 0.5, emit=6.0)
mat("appliance", (0.8, 0.8, 0.82), 0.3, 0.8)
mat("steel_brushed", rough=0.3, metal=0.9, image=_brushed(), tile=0.6)
# the themes' own pieces (blender/gen.py repaints the coloured ones in a theme's colours)
mat("parquet", rough=0.35, tex="herringbone_parquet", tile=1.4)                        # floor finish
mat("matte_white", (0.9, 0.89, 0.87), 0.55)                                           # handleless doors
mat("painted_wood", rough=0.7, tex="distressed_painted_planks", tile=1.6, grey=True, tint=(0.82, 0.86, 0.78))
mat("painted_light", rough=0.7, tex="distressed_painted_planks", tile=1.6, grey=True, tint=(1.0, 0.98, 0.93))
mat("raw_planks", rough=0.8, tex="dark_wooden_planks", tile=1.2)
mat("linen_sofa", rough=0.95, tex="rough_linen", tile=0.5, grey=True, tint=(0.82, 0.8, 0.77))
mat("quilt", rough=0.95, tex="gingham_check", tile=0.5, grey=True, tint=(0.75, 0.42, 0.36))

# ---------------------------------------------------------------- geometry helpers
COLL = {}


def collection(name):
    if name not in COLL:
        c = bpy.data.collections.new(name)
        scene.collection.children.link(c)
        COLL[name] = c
    return COLL[name]


def mesh_from_boxes(name, boxes, coll="arch", bevel=0.0, seg=2):
    """boxes: list of (x0,x1,y0,y1,z0,z1,matname) in FEET (object-local). One object, multi-material."""
    me = bpy.data.meshes.new(name)
    bm = bmesh.new()
    uv = bm.loops.layers.uv.new("UVMap")
    mat_names = []
    for b in boxes:
        x0, x1, y0, y1, z0, z1, mn = b
        if x1 - x0 < 1e-4 or y1 - y0 < 1e-4 or z1 - z0 < 1e-4:
            continue
        if mn not in mat_names:
            mat_names.append(mn)
        mi = mat_names.index(mn)
        tile = MATS[mn]["tile"]
        v = [bm.verts.new((x * F, y * F, z * F)) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)]
        # v index = z*4 + y*2 + x
        quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
        for q in quads:
            try:
                f = bm.faces.new([v[i] for i in q])
            except ValueError:
                continue
            f.material_index = mi
            f.normal_update()
            n = f.normal
            ax = max(range(3), key=lambda i: abs(n[i]))
            a, c = [(1, 2), (0, 2), (0, 1)][ax]
            for lp in f.loops:
                co = lp.vert.co
                lp[uv].uv = (co[a] / tile, co[c] / tile)
    bm.to_mesh(me)
    bm.free()
    for mn in mat_names:
        me.materials.append(MATS[mn])
    ob = bpy.data.objects.new(name, me)
    ob.location.z = LEVEL * F
    collection(coll).objects.link(ob)
    if bevel:
        md = ob.modifiers.new("bevel", "BEVEL")
        md.width = bevel
        md.segments = seg
        md.limit_method = "ANGLE"
    return ob


def overlap(a, b):
    return all(a[2 * i] < b[2 * i + 1] - 1e-6 and b[2 * i] < a[2 * i + 1] - 1e-6 for i in range(3))


def subtract(a, b):
    """axis-aligned box difference a - b -> list of boxes (6-tuples)."""
    if not overlap(a, b):
        return [a]
    out, a = [], list(a)
    for ax in range(3):
        lo, hi = 2 * ax, 2 * ax + 1
        if a[lo] < b[lo]:
            p = a.copy(); p[hi] = b[lo]; out.append(tuple(p)); a[lo] = b[lo]
        if a[hi] > b[hi]:
            p = a.copy(); p[lo] = b[hi]; out.append(tuple(p)); a[hi] = b[hi]
    return out


def subtract_all(boxes, cutters):
    for c in cutters:
        boxes = [p for b in boxes for p in subtract(b, c)]
    return boxes


def disjoint(boxes):
    """remove overlaps so no two boxes share coincident faces (avoids z-fighting / black Cycles faces)."""
    out = []
    for b in boxes:
        out += subtract_all([b], list(out))
    return out


# self-check of the box difference
_t = subtract((0, 4, 0, 1, 0, 10), (1, 2, -1, 2, 0, 7))
_d = disjoint([(0, 2, 0, 1, 0, 1), (1, 3, 0, 1, 0, 1)])
assert abs(sum((b[1]-b[0])*(b[3]-b[2])*(b[5]-b[4]) for b in _d) - 3) < 1e-9, _d
assert abs(sum((b[1]-b[0])*(b[3]-b[2])*(b[5]-b[4]) for b in _t) - (40 - 7)) < 1e-9, _t

# furniture materials (blender/furniture.py)
mat("chrome", (0.92, 0.92, 0.94), 0.06, 1.0)
mat("mirror", (0.96, 0.96, 0.96), 0.0, 1.0)
mat("black_glass", (0.01, 0.01, 0.012), 0.04)
mat("brass", (0.85, 0.62, 0.28), 0.25, 1.0)
mat("cast_iron", (0.03, 0.03, 0.03), 0.55, 0.6)
mat("iron", (0.04, 0.04, 0.04), 0.5, 0.7)
mat("quartz", rough=0.12, tex="marble_01", tile=1.4, tint=(1.0, 0.98, 0.95))
mat("towel", rough=1.0, tex="cotton_jersey", tile=0.3, tint=(0.55, 0.62, 0.68))
mat("led", (1.0, 0.86, 0.66), 0.5, emit=8.0)
mat("plastic_white", (0.9, 0.9, 0.88), 0.35)
mat("water", (0.55, 0.7, 0.75), 0.02, alpha=0.5)
mat("blue_accent", (0.1, 0.35, 0.75), 0.3)
mat("foliage", rough=0.9, tex="leafy_grass", tile=0.6, tint=(0.35, 0.55, 0.25))
mat("bark", (0.25, 0.18, 0.12), 0.9)
mat("rug_round", rough=1.0, tex="caban", tile=0.9, tint=(0.86, 0.83, 0.78))