Single place to convert your 2D floor plans to 3d model (no LLM)
Python
Video and debugging tools
23f2005639bf24577793d4
diff --git a/tools/dbg_plan.py b/tools/dbg_plan.pynew file mode 100644index 0000000..efc63aa--- /dev/null+++ b/tools/dbg_plan.py@@ -0,0 +1,32 @@+"""draw a plan JSON over its PDF page: python3 tools/dbg_plan.py plan.pdf plan.json out.png"""+import json, os, sys, random+sys.path[:0] = [os.path.dirname(os.path.abspath(__file__)), os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")]+import debug_draw, detect, vector # noqa: E402++pdf, js, out = sys.argv[1:4]+P = json.load(open(js))+s = P["scale_pt_per_ft"]+layers = []+COL = dict(door=(0, 170, 0, 200), window=(0, 90, 255, 200), opening=(255, 200, 0, 220))+for f in P["floors"]:+ X0, Y1 = f["origin_pt"]+ R = lambda r: (X0 + r[0] * s, X0 + r[1] * s, Y1 - r[3] * s, Y1 - r[2] * s)+ random.seed(1)+ for rm in f["rooms"]:+ c = (random.randint(60, 230), random.randint(60, 230), random.randint(60, 230), 90)+ layers.append(("rect", [R(q) for q in rm["rects"]], c))+ q = R(rm["rects"][0])+ layers.append(("text", [(q[0] + 2, q[2] + 2, f'{rm["type"]} {rm["area"]:.0f}')], (0, 0, 0, 255)))+ layers.append(("rect", [R(w) for w in f["walls"] if not w[4]], (255, 0, 0, 170)))+ layers.append(("rect", [R(w) for w in f["walls"] if w[4]], (255, 0, 255, 170)))+ for t, c in COL.items():+ layers.append(("rect", [R(o["rect"]) for o in f["openings"] if o["type"] == t], c))+ layers.append(("rect", [R(st["rect"]) for st in f["stairs"]], (120, 60, 0, 120)))+ import furnish+ its = [i for i in furnish.furnish_floor(f) if i["box"][1] > i["box"][0]]+ layers.append(("rect", [R(i["box"]) for i in its], (40, 40, 40, 150)))+ layers.append(("text", [(R(i["box"])[0] + 1, (R(i["box"])[2] + R(i["box"])[3]) / 2, i["fn"][:6]) for i in its], (255, 255, 0, 255)))+if len(sys.argv) > 4:+ p = vector.read_page(pdf)+ layers.append(("circle", [(a[0], a[1], a[2]) for a in detect.arcs(p["curves"]) if a[2] < 60], (0, 160, 160, 255)))+debug_draw.draw(pdf, layers, out, dpi=130)diff --git a/tools/debug_draw.py b/tools/debug_draw.pynew file mode 100644index 0000000..275f1bd--- /dev/null+++ b/tools/debug_draw.py@@ -0,0 +1,36 @@+"""Overlay detection results on the rendered PDF page (for checking the detector by eye)."""+import subprocess, tempfile, os+from PIL import Image, ImageDraw+++def page_image(pdf, page=1, dpi=150):+ d = tempfile.mkdtemp()+ subprocess.run(["pdftocairo", "-png", "-r", str(dpi), "-f", str(page), "-l", str(page), "-singlefile",+ pdf, os.path.join(d, "p")], check=True)+ return Image.open(os.path.join(d, "p.png")).convert("RGB")+++def draw(pdf, layers, out, page=1, dpi=150, crop=None):+ """layers: list of (kind, items, color) with kind 'rect' (x0,x1,y0,y1) | 'line' (x0,y0,x1,y1) | 'text' (x,y,s)+ in page points."""+ im = page_image(pdf, page, dpi)+ im = Image.blend(im, Image.new("RGB", im.size, "white"), 0.55)+ ov = Image.new("RGBA", im.size, (0, 0, 0, 0))+ g = ImageDraw.Draw(ov)+ k = dpi / 72+ for kind, items, col in layers:+ for it in items:+ if kind == "rect":+ x0, x1, y0, y1 = it[:4]+ g.rectangle([x0 * k, y0 * k, x1 * k, y1 * k], fill=col)+ elif kind == "line":+ g.line([it[0] * k, it[1] * k, it[2] * k, it[3] * k], fill=col, width=2)+ elif kind == "text":+ g.text((it[0] * k, it[1] * k), it[2], fill=col)+ elif kind == "circle":+ cx, cy, r = it[:3]+ g.ellipse([(cx - r) * k, (cy - r) * k, (cx + r) * k, (cy + r) * k], outline=col, width=2)+ im = Image.alpha_composite(im.convert("RGBA"), ov).convert("RGB")+ if crop:+ im = im.crop([v * k for v in crop])+ im.save(out)diff --git a/tools/fill_frames.py b/tools/fill_frames.pynew file mode 100644index 0000000..1d07381--- /dev/null+++ b/tools/fill_frames.py@@ -0,0 +1,15 @@+"""Fill frames skipped by a --step 2 render: each missing f_N.jpg = average of its two neighbours.+python3 tools/fill_frames.py FRAMES_DIR"""+import os, sys+from PIL import Image+d = sys.argv[1]+f = lambda i: os.path.join(d, f"f_{i:05d}.jpg")+last = max(int(n[2:7]) for n in os.listdir(d) if n.startswith("f_"))+filled = 0+for i in range(1, last):+ if not os.path.exists(f(i)) and os.path.exists(f(i - 1)) and os.path.exists(f(i + 1)):+ Image.blend(Image.open(f(i - 1)), Image.open(f(i + 1)), 0.5).save(f(i), quality=94)+ filled += 1+missing = [i for i in range(last + 1) if not os.path.exists(f(i))]+assert not missing, f"still missing {missing[:10]}"+print("filled", filled, "frames, sequence 0 ..", last, "complete")diff --git a/tools/record.mjs b/tools/record.mjsnew file mode 100644index 0000000..3c81099--- /dev/null+++ b/tools/record.mjs@@ -0,0 +1,40 @@+// Record a walkthrough from the viewer: node tools/record.mjs <job> <frames.json> <out_dir> [http://127.0.0.1:8080]+// Needs a Chromium / Chrome binary: set CHROME to its path (default: chromium on PATH).+// Headless Chromium on the GPU (ANGLE over EGL); each frame is drawn by window.__frame and saved as JPEG.+import { spawn } from 'node:child_process';+import fs from 'node:fs';+const [job, framesFile, out, base = 'http://127.0.0.1:8080'] = process.argv.slice(2);+const frames = JSON.parse(fs.readFileSync(framesFile, 'utf8'));+const CH = process.env.CHROME || 'chromium';+const port = 9400 + Math.floor(Math.random() * 400);+const ch = spawn(CH, ['--headless=new', '--no-sandbox', `--remote-debugging-port=${port}`, '--window-size=1280,720',+ '--hide-scrollbars', '--use-angle=gl-egl', '--ignore-gpu-blocklist', '--enable-gpu', 'about:blank'], { stdio: 'ignore' });+const sleep = (t) => new Promise((r) => setTimeout(r, t));+let targets;+for (let i = 0; i < 100 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); } catch { await sleep(200); } }+const ws = new WebSocket(targets.find((t) => t.type === 'page').webSocketDebuggerUrl);+await new Promise((r) => ws.addEventListener('open', r));+let id = 0; const pend = new Map();+ws.addEventListener('message', (e) => { const m = JSON.parse(e.data); if (m.id && pend.has(m.id)) { pend.get(m.id)(m); pend.delete(m.id); } });+const cdp = (method, params = {}) => new Promise((r) => { const i = ++id; pend.set(i, r); ws.send(JSON.stringify({ id: i, method, params })); });+const ev = async (expr) => (await cdp('Runtime.evaluate', { expression: expr, returnByValue: true })).result?.result?.value;+const [x0, y0] = frames[0];+await cdp('Page.navigate', { url: `${base}/web/view.html?job=${job}&pose=${x0},${y0},0,0,0` });+for (let i = 0; i < 600 && !(await ev('!!window.__ready')); i++) await sleep(200);+console.log('renderer', await ev(`(() => { const g = document.createElement('canvas').getContext('webgl2'); const d = g.getExtension('WEBGL_debug_renderer_info'); return g.getParameter(d.UNMASKED_RENDERER_WEBGL); })()`));+// exact 1280x720 drawing size (headless window chrome eats some of --window-size)+await cdp('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false });+await ev('dispatchEvent(new Event("resize"))');+await sleep(1500); // textures finish uploading+fs.mkdirSync(out, { recursive: true });+const t0 = Date.now();+for (let i = 0; i < frames.length; i++) {+ const [x, y, yaw, pitch] = frames[i];+ const url = await ev(`__frame(${x}, ${y}, 0, ${yaw}, ${pitch})`);+ if (!url) throw new Error(`frame ${i} failed`);+ fs.writeFileSync(`${out}/f_${String(i).padStart(5, '0')}.jpg`, Buffer.from(url.split(',')[1], 'base64'));+ if (i % 500 === 0) console.log(`frame ${i}/${frames.length} ${((Date.now() - t0) / 1000).toFixed(0)} s`);+}+console.log(`done ${frames.length} frames in ${((Date.now() - t0) / 1000).toFixed(1)} s`);+ch.kill();+process.exit(0);diff --git a/tools/retime.py b/tools/retime.pynew file mode 100644index 0000000..9d83576--- /dev/null+++ b/tools/retime.py@@ -0,0 +1,31 @@+"""Speed up the start of a rendered tour without re-rendering: frames before UNTIL seconds play SPEED x faster,+easing back to 1x over the last EASE seconds; room times in timeline.json shift to match.+python3 tools/retime.py SRC_RENDER_DIR DST_RENDER_DIR UNTIL SPEED [EASE] (then tools/titles.py on DST)"""+import json, os, sys++src, dst, until, speed = sys.argv[1], sys.argv[2], float(sys.argv[3]), float(sys.argv[4])+ease = float(sys.argv[5]) if len(sys.argv) > 5 else 6.0+tl = json.load(open(os.path.join(src, "timeline.json")))+fps = tl["fps"]+names = sorted(n for n in os.listdir(os.path.join(src, "frames")) if n.startswith("f_"))+end, e0 = until * fps, (until - ease) * fps++picks, pos = [], 0.0+while round(pos) < int(end):+ picks.append(round(pos))+ u = min(max((pos - e0) / (end - e0), 0), 1) # 0 before the ease, 1 at the end+ pos += speed + (1 - speed) * u * u * (3 - 2 * u) # smoothstep from SPEED to 1x+picks += range(int(end), len(names))+assert picks == sorted(picks) and picks[-1] == len(names) - 1++out = os.path.join(dst, "frames")+os.makedirs(out, exist_ok=True)+for n in os.listdir(out):+ os.remove(os.path.join(out, n))+for k, i in enumerate(picks):+ os.symlink(os.path.abspath(os.path.join(src, "frames", names[i])), os.path.join(out, f"f_{k:05d}.jpg"))+shift = (len(names) - len(picks)) / fps+tl["rooms"] = [[t if t < 1 else round(t - shift, 2), r] for t, r in tl["rooms"]]+tl["duration"] = len(picks) / fps+json.dump(tl, open(os.path.join(dst, "timeline.json"), "w"), indent=1)+print(f"opening {until:.1f}s -> {until - shift:.1f}s, video {len(names) / fps:.1f}s -> {tl['duration']:.1f}s")diff --git a/tools/titles.py b/tools/titles.pynew file mode 100644index 0000000..140b5e4--- /dev/null+++ b/tools/titles.py@@ -0,0 +1,59 @@+"""Room titles in the style of the reference tour (small spaced kicker, big thin uppercase name, mono caption),+then the final MP4. python3 tools/titles.py RENDER_DIR TITLES.json OUT.mp4+TITLES.json: {"opening": [kicker, title, caption], "closing": [...], "rooms": {"ROOM KEY": [kicker, title, caption], ...}}+RENDER_DIR has frames/f_#####.jpg and timeline.json (written by blender/cinema.py)."""+import json, os, subprocess, sys++R, spec, out = sys.argv[1], json.load(open(sys.argv[2])), sys.argv[3]+tl = json.load(open(os.path.join(R, "timeline.json")))+fps, dur = tl["fps"], tl["duration"]+W, H = 1920, 1080+t = lambda s: f"{int(s // 3600)}:{int(s % 3600 // 60):02d}:{s % 60:05.2f}"+ass = ["[Script Info]", "ScriptType: v4.00+", f"PlayResX: {W}", f"PlayResY: {H}", "WrapStyle: 2", "",+ "[V4+ Styles]",+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, "+ "Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",+ "Style: Kick, Noto Sans Medium, 22, &H00F0F4F7, &H00FFFFFF, &H00000000, &H78000000, 0, 0, 0, 0, 100, 100, 6, 0, 1, 0, 1, 7, 0, 0, 0, 1",+ "Style: Title, Noto Sans Light, 104, &H00FFFFFF, &H00FFFFFF, &H00000000, &H70000000, 0, 0, 0, 0, 100, 100, 1, 0, 1, 0, 2, 7, 0, 0, 0, 1",+ "Style: Cap, DejaVu Sans Mono, 20, &H00E6EBEE, &H00FFFFFF, &H00000000, &H78000000, 0, 0, 0, 0, 100, 100, 5, 0, 1, 0, 1, 7, 0, 0, 0, 1",+ "", "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"]+++def card(a, b, kicker, title, caption, side):+ """one title card from a to b seconds; side 'l' / 'r' / 'c' like the reference's alternating placement"""+ lines = title.split("\n")+ an = {"l": 7, "r": 9, "c": 8}[side]+ x = {"l": 110, "r": W - 110, "c": W // 2}[side]+ y = 330 if side != "c" else 380+ tag = lambda dy, d0: (f"{{\\an{an}\\move({x},{y + dy + 26},{x},{y + dy},{d0},{d0 + 700})"+ f"\\fad({300 + d0},450)}}")+ ass.append(f"Dialogue: 2, {t(a)}, {t(b)}, Kick,, 0, 0, 0,, {tag(-52, 0)}{kicker.upper()}")+ for k, ln in enumerate(lines):+ ass.append(f"Dialogue: 2, {t(a)}, {t(b)}, Title,, 0, 0, 0,, {tag(k * 108, 120 + 80 * k)}{ln.upper()}")+ if caption:+ ass.append(f"Dialogue: 2, {t(a)}, {t(b)}, Cap,, 0, 0, 0,, {tag(len(lines) * 108 + 22, 320)}{caption.upper()}")+++op = spec["opening"]+card(0.6, 6.5, *op, "c")+seen, rooms = {}, []+for s, r in tl["rooms"]: # a name met twice (second suite's bath) may have its own entry "NAME#2"+ seen[r] = seen.get(r, 0) + 1+ key = f"{r}#{seen[r]}" if f"{r}#{seen[r]}" in spec["rooms"] else r+ if key in spec["rooms"] and s > 1:+ rooms.append((s, key))+for k, (s, r) in enumerate(rooms):+ nxt = rooms[k + 1][0] if k + 1 < len(rooms) else dur+ cat, title, cap = spec["rooms"][r]+ card(s + 0.4, min(s + 4.6, nxt - 0.2), f"{k + 1:02d} / {cat}", title, cap, "lr"[k % 2])+cl = spec["closing"]+card(dur - 4.8, dur - 0.3, *cl, "c")+sub = os.path.join(R, "titles.ass")+open(sub, "w").write("\n".join(ass) + "\n")++vf = (f"subtitles={sub},vignette=angle=0.35,fade=in:0:{int(fps * 1.2)},"+ f"fade=out:st={dur - 1.2:.2f}:d=1.2,format=yuv420p")+subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-framerate", str(fps),+ "-i", os.path.join(R, "frames", "f_%05d.jpg"), "-vf", vf, "-c:v", "libx264", "-preset", "slow",+ "-crf", "18", "-movflags", "+faststart", out], check=True)+print("wrote", out)diff --git a/tools/tour.py b/tools/tour.pynew file mode 100644index 0000000..9fc23d7--- /dev/null+++ b/tools/tour.py@@ -0,0 +1,86 @@+"""Plan a continuous walking tour (stop - turn - walk, with a slow look-around in each room).+python3 tools/tour.py meta.json waypoints.json out_dir -> out_dir/frames.json, out_dir/labels.ass+waypoints.json: [[x, y, look], ...] in metres; look = seconds to pan around the room at that point (0 = none)."""+import json, math, sys++FPS, SPEED, TURN, PITCH = 30, 1.0, math.radians(75), math.radians(-6) # m/s, rad/s+++def ease(t):+ return t * t * (3 - 2 * t)+++def tour(wps):+ """-> frames [(x, y, yaw, pitch)]"""+ out = []+ x, y = wps[0][:2]+ yaw = math.atan2(-(wps[1][0] - x), wps[1][1] - y)++ def turn_to(target):+ nonlocal yaw+ d = (target - yaw + math.pi) % (2 * math.pi) - math.pi+ n = max(1, int(abs(d) / TURN * FPS))+ y0 = yaw+ for i in range(1, n + 1):+ out.append((x, y, y0 + d * ease(i / n), PITCH))+ yaw = y0 + d++ for k, (tx, ty, look) in enumerate(wps[1:], 1):+ dx, dy = tx - x, ty - y+ L = math.hypot(dx, dy)+ if L < 0.05:+ continue+ head = math.atan2(-dx, dy)+ d = abs((head - yaw + math.pi) % (2 * math.pi) - math.pi)+ if d > math.radians(25):+ turn_to(head)+ n = max(2, int(L / SPEED * FPS))+ x0, y0, yaw0 = x, y, yaw+ dh = (head - yaw0 + math.pi) % (2 * math.pi) - math.pi+ for i in range(1, n + 1):+ t = i / n+ s = t if 0.15 < t < 0.85 else ease(t) # gentle start / stop+ x, y = x0 + dx * s, y0 + dy * s+ out.append((x, y, yaw0 + dh * min(1, t * 3), PITCH))+ yaw = yaw0 + dh+ if look: # pan left, right, back to the heading+ base, n = yaw, int(look * FPS)+ for i in range(1, n + 1):+ t = i / n+ out.append((x, y, base + math.radians(70) * math.sin(2 * math.pi * ease(t)), PITCH))+ return out+++def room_at(meta, x, y):+ for r in meta["floors"][0]["rooms"]:+ for q in r["rects"]:+ if q[0] - 0.05 <= x <= q[1] + 0.05 and q[2] - 0.05 <= y <= q[3] + 0.05:+ return "BEDROOM" if r["label"].startswith("BED ROOM") else r["label"].split(" ")[0]+ return None+++if __name__ == "__main__":+ meta = json.load(open(sys.argv[1]))+ wps = json.load(open(sys.argv[2]))+ frames = tour(wps)+ od = sys.argv[3]+ json.dump(frames, open(f"{od}/frames.json", "w"))+ # room captions (ASS subtitles): one event per run of frames in the same room+ names = {"FAMILY": "Family hall", "MAID": "Maid room", "BEDROOM": "Bedroom", "BATH": "Bath", "DRESS": "Dressing",+ "KITCHEN": "Kitchen", "STORE": "Store", "LOBBY": "Lobby", "GARDEN": "Garden", "ENTRANCE": "Entrance"}+ lab, ev, start = None, [], 0+ for i, (x, y, *_ ) in enumerate(frames + [(-99, -99, 0, 0)]):+ r = room_at(meta, x, y) if i < len(frames) else "END"+ r = r or lab+ if r != lab:+ if lab:+ ev.append((start / FPS, i / FPS, names.get(lab, lab.title())))+ lab, start = r, i+ t = lambda s: f"{int(s // 3600)}:{int(s % 3600 // 60):02d}:{s % 60:05.2f}"+ ass = ["[Script Info]", "ScriptType: v4.00+", "PlayResX: 1280", "PlayResY: 720", "",+ "[V4+ Styles]", "Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginV",+ "Style: Room, Noto Sans, 34, &H00FFFFFF, &H00000000, &H80000000, 1, 1, 2, 1, 7, 40, 36", "",+ "[Events]", "Format: Layer, Start, End, Style, Text"]+ ass += [f"Dialogue: 0, {t(a)}, {t(b)}, Room, {{\\fad(300,300)}}{n}" for a, b, n in ev if b - a > 0.6]+ open(f"{od}/labels.ass", "w").write("\n".join(ass) + "\n")+ print(len(frames), "frames", round(len(frames) / FPS, 1), "s;", [n for _, _, n in ev])