Single place to convert your 2D floor plans to 3d model (no LLM)
Python
Own furniture models, MP4 recordings, sample button, delete, Home links
23f2005639c4f62db5d12d
diff --git a/README.md b/README.mdindex 00790e4..c10cf25 100644--- a/README.md+++ b/README.md@@ -67,7 +67,9 @@ Then drop `examples/sample_plan.pdf` on the page.| **Top view** (T) | The house from above, one storey at a time || **Map** (M) | Room names, stairs, where you stand and look || **Screenshot** (P) | PNG of about 4K size |-| **Record** (R) | Video of your walk, MP4 or WebM |+| **Record** (R) | Video of your walk as MP4 (browsers that record WebM are converted on the server; needs ffmpeg) |+| **Your own furniture** | The Furniture models page shows each item and lets you replace it with your `.glb` model |+| **Sample plan, delete** | "Try the sample plan" on the home page; every plan in the list has Delete || **Blender file** | The house as one `.blend` with every texture packed inside, in a zip |## Build time and accuracy@@ -129,6 +131,8 @@ sequenceDiagram| `GET /web/view.html?job={id}` | The walkthrough. `&embed` hides the link back to the upload page || `GET /web/edit.html?job={id}` | The review page || `GET /api/jobs` | The 30 most recent plans |+| `DELETE /api/jobs/{id}` | Delete a plan and its house |+| `GET /api/furniture` | Replaceable items; `POST /api/furniture/{name}` (a `.glb`) replaces one, `DELETE` restores it |To let people correct the plan first, show `/web/edit.html?job={id}` in the iframe instead of building straight away.@@ -139,6 +143,7 @@ server.py web server and build queue (standard library only)detect.py plan PDF -> plan JSONvector.py PDF lines, curves, fills and words (poppler)furnish.py furniture rules (pure Python)+catalog.py furniture that can be replaced by your own modelsfetch_assets.py downloads the CC0 textures, models and skyblender/ gen.py (build), bake.py (light maps), lib.py (parts), cinema.py (video renderer)web/ home, review and walkthrough pages@@ -171,7 +176,7 @@ CHROME=/path/to/chromium node tests/test_site.mjs examples/sample_plan.pdf http:- **Labels in English**, sizes in feet and inches. Without size labels the scale is a guess and must be set on the review page.- **Wall groups.** If the drawing's walls fall into groups whose outlines do not overlap, the detector reads them as separate plans and can drop a part of the house.- **No login.** Anyone who can reach the server can upload, build and read every plan. Keep it on a trusted network or behind your own backend. `--cors *` lets any website call it from the visitor's browser: name your origin instead.-- **Disk.** Plans are never deleted; a built house takes about 10 to 70 MB in `jobs/`.+- **Disk.** Plans stay until you delete them; a built house takes about 10 to 70 MB in `jobs/`.## Creditsdiff --git a/blender/gen.py b/blender/gen.pyindex ae11272..30e296a 100644--- a/blender/gen.py+++ b/blender/gen.py@@ -15,6 +15,8 @@ import bpy # noqa: E402from lib import * # noqa: E402,F401import lib # noqa: E402import furnish # noqa: E402+from catalog import CATALOG # noqa: E402+from mathutils import Vector # noqa: E402def progress(p, msg):@@ -283,6 +285,39 @@ def model(name, x, y, rot=0, z=0.0, scale=1.0):place(name, x, y, rot, z=z, scale=scale, collide=False)+def custom(it):+ """the person's own model (assets/custom/<fn>.glb) in place of a built-in item, fitted to the item's footprint"""+ path = os.path.join(ASSETS, "custom", it["fn"] + ".glb")+ x0, x1, y0, y1 = it.get("box") or (0, 0, 0, 0)+ if it["fn"] not in CATALOG or not os.path.exists(path) or x1 - x0 < 0.1 or y1 - y0 < 0.1:+ return False+ before = set(bpy.data.objects)+ bpy.ops.import_scene.gltf(filepath=path) # shortcut: imported once per item, fine for a house; cache if plans grow huge+ new = [o for o in bpy.data.objects if o not in before]+ bpy.context.view_layer.update()+ pts = [o.matrix_world @ Vector(c) for o in new if o.type == "MESH" for c in o.bound_box]+ if not pts:+ return False+ lo = Vector([min(p[i] for p in pts) for i in range(3)])+ hi = Vector([max(p[i] for p in pts) for i in range(3)])+ rot = it["args"][2]+ bw, bd = ((y1 - y0), (x1 - x0)) if round(rot) % 180 == 90 else ((x1 - x0), (y1 - y0))+ s = min(bw * lib.F / max(hi.x - lo.x, 1e-6), bd * lib.F / max(hi.y - lo.y, 1e-6))+ root = bpy.data.objects.new(f"custom_{it['fn']}", None)+ collection("furniture").objects.link(root)+ for o in new:+ for c in list(o.users_collection):+ c.objects.unlink(o)+ collection("furniture").objects.link(o)+ if o.parent is None:+ o.location -= Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z)) # centred, standing on the floor+ o.parent = root+ root.scale = (s, s, s)+ root.rotation_euler = (0, 0, math.radians(rot))+ root.location = ((x0 + x1) / 2 * lib.F, (y0 + y1) / 2 * lib.F, lib.LEVEL * lib.F)+ return True++CALLS = dict(bathtub=bathtub, round_rug=round_rug, model=model, bed=bed, nightstand=nightstand, wardrobe=wardrobe, desk=desk, wc2=wc2, vanity=vanity,shower2=lambda x, y, rot: shower2(x, y, rot), geyser=lambda x, y, rot: geyser(x, y, rot),kitchen_run=kitchen_run, chimney=chimney, wall_cab2=wall_cab2, fridge2=fridge2, washer2=washer2,@@ -421,7 +456,7 @@ for k, f in enumerate(floors):items = [] if plan.get("furnish") is False else f.get("items") or furnish.furnish_floor(f)for it in items:try:- CALLS[it["fn"]](*it["args"], **it["kw"])+ custom(it) or CALLS[it["fn"]](*it["args"], **it["kw"])except Exception as e: # one bad item must not stop the buildprint("ITEM FAILED", it["fn"], e, flush=True)# lamps (emissive panel + area light for the bake) in roofed roomsdiff --git a/blender/thumbs.py b/blender/thumbs.pynew file mode 100644index 0000000..672ad8a--- /dev/null+++ b/blender/thumbs.py@@ -0,0 +1,25 @@+"""Pictures of the furniture for the furniture page: blender -b PREVIEW/house.blend -P blender/thumbs.py -- OUT_DIR+(house.blend = gen.py run on catalog.preview_plan(); one PNG per item, named after it)."""+import bpy, os, sys+from mathutils import Vector+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))+from catalog import CATALOG, CELL # noqa: E402++out, F = sys.argv[sys.argv.index("--") + 1], 0.3048+sc = bpy.context.scene+sc.render.engine = "BLENDER_WORKBENCH"+sc.display.shading.light, sc.display.shading.color_type = "STUDIO", "TEXTURE"+sc.display.shading.show_shadows = True+sc.render.resolution_x, sc.render.resolution_y = 480, 360+cam = bpy.data.objects.new("thumb", bpy.data.cameras.new("thumb"))+sc.collection.objects.link(cam)+cam.data.lens = 26+sc.camera = cam+for k, (fn, (_, w, d, _kw)) in enumerate(CATALOG.items()):+ c = Vector(((k + 0.5) * CELL, CELL / 2, 2.2)) * F+ back = max(w, d) * 0.7 + 4.5 # feet: far enough to fit the item+ cam.location = c + Vector((back * 0.55, -back, 3.2)) * F+ cam.rotation_euler = (c - cam.location).to_track_quat("-Z", "Y").to_euler()+ sc.render.filepath = os.path.join(out, fn + ".png")+ bpy.ops.render.render(write_still=True)+print("THUMBS OK", flush=True)diff --git a/catalog.py b/catalog.pynew file mode 100644index 0000000..a1363f1--- /dev/null+++ b/catalog.py@@ -0,0 +1,24 @@+"""Furniture that can be replaced by your own model: name -> (label, width, depth in feet, extra arguments).+A file assets/custom/<name>.glb takes the place of the built-in item in every later build: it is scaled to the item's+footprint and stood on the floor. Model it with +Y up and its front facing +Z (the glTF standard)."""+CATALOG = {+ "bed": ("Bed", 5.0, 6.6, {}), "nightstand": ("Nightstand", 1.6, 1.5, {}), "wardrobe": ("Wardrobe", 6.0, 2.0, {}),+ "desk": ("Desk", 4.0, 2.0, {}), "sofa": ("Sofa", 7.0, 3.0, {}), "coffee_table": ("Coffee table", 3.6, 2.0, {}),+ "tv_unit": ("TV unit", 5.0, 1.4, {}), "dining_set": ("Dining set", 6.0, 6.4, {}), "fridge2": ("Fridge", 3.0, 2.4, {}),+ "washer2": ("Washing machine", 2.0, 2.0, {}), "wc2": ("WC", 1.5, 2.3, {}), "vanity": ("Basin", 2.6, 1.7, {}),+ "puja_mandir": ("Mandir", 3.6, 1.5, {}), "plant": ("Plant", 1.5, 1.5, {}),+}+CELL = 20.0 # the preview scene: one item in the middle of each 20 ft cell of a long room+++def preview_plan():+ """a plan with every item standing in a row, used to render the pictures on the furniture page"""+ n, t = len(CATALOG), 0.75+ L = n * CELL+ items = [dict(fn=fn, args=[k * CELL + CELL / 2, CELL / 2, 0], kw=kw, solid=False, room="",+ box=[k * CELL + CELL / 2 - w / 2, k * CELL + CELL / 2 + w / 2, CELL / 2 - d / 2, CELL / 2 + d / 2])+ for k, (fn, (_, w, d, kw)) in enumerate(CATALOG.items())]+ walls = [[0, L, 0, t, 0], [0, L, CELL - t, CELL, 0], [0, t, 0, CELL, 0], [L - t, L, 0, CELL, 0]]+ return dict(version=1, units="ft", floor_height=10.0, slab=0.5, floors=[dict(+ name="Preview", level=0, size=[L, CELL], walls=walls, openings=[], stairs=[], labels=[], items=items,+ rooms=[dict(type="living", label="", rects=[[t, L - t, t, CELL - t]], area=L * CELL)])])diff --git a/server.py b/server.pyindex acdde82..4d78ef2 100644--- a/server.py+++ b/server.py@@ -12,11 +12,11 @@ JOBS = os.path.join(HERE, "jobs")WEB = os.path.join(HERE, "web")THREE = os.path.join(HERE, "node_modules", "three")BLENDER = shutil.which("blender") or "blender"-MAX_UPLOAD = 60 * 1024 * 1024+MAX_UPLOAD = 200 * 1024 * 1024 # plans are small; recordings sent for MP4 conversion are notBUILD_TIMEOUT = 2 * 3600 # seconds; a high-quality build of a large house takes well under an hourID = re.compile(r"^[a-f0-9]{12}$")sys.path.insert(0, HERE)-import detect, fetch_assets, vector # noqa: E402+import catalog, detect, fetch_assets, vector # noqa: E402os.makedirs(JOBS, exist_ok=True)builds = queue.Queue()@@ -105,6 +105,49 @@ def export_blend(jid):return f"/jobs/{jid}/house_blender.zip"+# ------------------------------------------------------------------ your own furniture models+CUSTOM, THUMBS = os.path.join(fetch_assets.ROOT, "custom"), os.path.join(fetch_assets.ROOT, "thumbs")+thumbs_job = dict(running=False, again=False)+++def render_thumbs():+ """pictures of every replaceable item as it will be built now (built-in or your model): a small house with all of+ them in a row is built without baking, then photographed. Runs again if a model changed meanwhile."""+ try:+ while True:+ thumbs_job["again"] = False+ os.makedirs(THUMBS, exist_ok=True)+ with open(os.path.join(THUMBS, "plan.json"), "w") as fh:+ json.dump(catalog.preview_plan(), fh)+ subprocess.run([BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",+ os.path.join(THUMBS, "plan.json"), THUMBS, "--no-bake"], capture_output=True, timeout=1800)+ subprocess.run([BLENDER, "-b", os.path.join(THUMBS, "house.blend"), "-P", os.path.join(HERE, "blender", "thumbs.py"),+ "--", THUMBS], capture_output=True, timeout=600)+ if not thumbs_job["again"]:+ break+ except Exception:+ traceback.print_exc()+ finally:+ thumbs_job["running"] = False+++def refresh_thumbs():+ with lock:+ if thumbs_job["running"]:+ thumbs_job["again"] = True+ return+ thumbs_job["running"] = True+ threading.Thread(target=render_thumbs, daemon=True).start()+++def furniture():+ if not thumbs_job["running"] and not all(os.path.exists(os.path.join(THUMBS, f"{fn}.png")) for fn in catalog.CATALOG):+ refresh_thumbs()+ return dict(rendering=thumbs_job["running"], items=[+ dict(fn=fn, label=label, custom=os.path.exists(os.path.join(CUSTOM, f"{fn}.glb")),+ thumb=os.path.exists(os.path.join(THUMBS, f"{fn}.png"))) for fn, (label, *_) in catalog.CATALOG.items()])++# ------------------------------------------------------------------ pipeline stepsdef run_detect(jid):d = jdir(jid)@@ -203,6 +246,7 @@ class H(BaseHTTPRequestHandler):if CORS:self.send_header("Access-Control-Allow-Origin", CORS)self.send_header("Access-Control-Allow-Headers", "Content-Type, X-Filename")+ self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE")def do_OPTIONS(self): # the browser's question before a cross-site POSTself.send_response(204)@@ -220,7 +264,7 @@ class H(BaseHTTPRequestHandler):self.send_header("Content-Type", TYPES.get(ext, "application/octet-stream"))self.send_header("Content-Length", str(size))# job outputs change on every rebuild: never let the browser show a stale house- fresh = ext in (".json", ".html", ".js", ".css") or "/jobs/" in path.replace(os.sep, "/")+ fresh = ext in (".json", ".html", ".js", ".css", ".png") or "/jobs/" in path.replace(os.sep, "/")self.send_header("Cache-Control", "no-cache" if fresh else "max-age=3600")self.cors()self.end_headers()@@ -234,6 +278,12 @@ class H(BaseHTTPRequestHandler):return self.file(os.path.join(WEB, "index.html"), WEB)if p.startswith("/web/"):return self.file(os.path.join(WEB, p[5:]), WEB)+ if p.startswith("/examples/"):+ return self.file(os.path.join(HERE, "examples", p[10:]), os.path.join(HERE, "examples"))+ if p.startswith("/thumbs/"):+ return self.file(os.path.join(THUMBS, p[8:]), THUMBS)+ if p == "/api/furniture":+ return self.send(200, furniture())if p.startswith("/three/"):return self.file(os.path.join(THREE, p[7:]), THREE)if p.startswith("/jobs/"):@@ -262,12 +312,50 @@ class H(BaseHTTPRequestHandler):def body(self):n = int(self.headers.get("Content-Length") or 0)if not 0 <= n <= MAX_UPLOAD:- raise ValueError("file too large (60 MB max)")+ raise ValueError("file too large (200 MB max)")return self.rfile.read(n)+ def do_DELETE(self):+ p = urlparse(self.path).path+ m = re.match(r"^/api/jobs/([a-f0-9]{12})$", p)+ if m and os.path.isdir(jdir(m.group(1))):+ if (read_status(m.group(1)) or {}).get("stage") in ("building", "queued"):+ return self.send(409, {"error": "This plan is being built. Delete it when the build has finished."})+ shutil.rmtree(jdir(m.group(1)))+ return self.send(200, {"ok": True})+ m = re.match(r"^/api/furniture/(\w+)$", p)+ if m and m.group(1) in catalog.CATALOG: # back to the built-in item+ for f in (os.path.join(CUSTOM, m.group(1) + ".glb"), os.path.join(THUMBS, m.group(1) + ".png")):+ if os.path.exists(f):+ os.remove(f)+ refresh_thumbs()+ return self.send(200, {"ok": True})+ self.send(404, {"error": "not found"})+def do_POST(self):p = urlparse(self.path).pathtry:+ m = re.match(r"^/api/furniture/(\w+)$", p)+ if m and m.group(1) in catalog.CATALOG: # your model for this item, as a .glb file+ data = self.body()+ if not data.startswith(b"glTF"):+ return self.send(400, {"error": "Please upload a .glb file (binary glTF)."})+ os.makedirs(CUSTOM, exist_ok=True)+ with open(os.path.join(CUSTOM, m.group(1) + ".glb"), "wb") as fh:+ fh.write(data)+ if os.path.exists(os.path.join(THUMBS, m.group(1) + ".png")):+ os.remove(os.path.join(THUMBS, m.group(1) + ".png"))+ refresh_thumbs()+ return self.send(200, {"ok": True})+ if p == "/api/mp4": # a WebM recording in, the same video as MP4 out+ if not shutil.which("ffmpeg"):+ return self.send(501, {"error": "ffmpeg is not installed on the server"})+ r = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", "pipe:0", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",+ "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-movflags", "frag_keyframe+empty_moov", "-f", "mp4", "pipe:1"],+ input=self.body(), capture_output=True, timeout=600)+ if r.returncode or not r.stdout:+ return self.send(500, {"error": "the recording could not be converted"})+ return self.send(200, r.stdout, "video/mp4")if p == "/api/materials": # start the Poly Haven download (the home page's button)with lock:start = not assets_job["running"]diff --git a/web/edit.html b/web/edit.htmlindex ec5bacd..ab91c19 100644--- a/web/edit.html+++ b/web/edit.html@@ -38,6 +38,7 @@</head><body><header>+ <a href="/" title="Back to the home page">Home</a><h2 id="title">Review</h2><div class="tabs" id="tabs"></div><span class="muted" id="scale"></span>diff --git a/web/furniture.html b/web/furniture.htmlnew file mode 100644index 0000000..16d2acf--- /dev/null+++ b/web/furniture.html@@ -0,0 +1,56 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Furniture models</title>+<link rel="stylesheet" href="/web/style.css?v=2">+</head>+<body class="home">+<main class="wrap" style="max-width:960px">+ <p class="brand"><a href="/" style="color:inherit;text-decoration:none">PlanTo3D</a> · <a href="/">Home</a></p>+ <h1>Furniture models</h1>+ <p class="muted">Each picture shows the item as houses are built with it now. Replace any of them with your own+ <code>.glb</code> model: it is scaled to the item's footprint and stood on the floor. Model it with +Y up and its+ front facing +Z. Houses already built keep their furniture until you build them again.</p>+ <p id="state" class="muted" role="status"></p>+ <div class="furn" id="list"></div>+ <input type="file" id="file" accept=".glb,model/gltf-binary" hidden>+</main>+<script>+const $ = (id) => document.getElementById(id);+const el = (tag, cls, text) => { const e = document.createElement(tag); e.className = cls; e.textContent = text; return e; };+let target = null;+async function load() {+ const f = await fetch('/api/furniture').then((r) => r.json());+ $('state').textContent = f.rendering ? 'Drawing the pictures… (about a minute)' : '';+ $('list').replaceChildren(...f.items.map((it) => {+ const fig = document.createElement('figure');+ if (it.thumb) { const im = new Image(); im.src = `/thumbs/${it.fn}.png?${Date.now()}`; im.alt = it.label; fig.append(im); }+ else fig.append(el('div', 'wait', 'Drawing…'));+ const cap = document.createElement('figcaption');+ const pick = el('button', 'more', it.custom ? 'Change model' : 'Use my model');+ pick.onclick = () => { target = it.fn; $('file').click(); };+ cap.append(el('b', '', it.label), el('span', 'chip' + (it.custom ? ' ok' : ''), it.custom ? 'Your model' : 'Built-in'), pick);+ if (it.custom) {+ const back = el('button', 'more', 'Back to built-in');+ back.onclick = async () => { await fetch(`/api/furniture/${it.fn}`, { method: 'DELETE' }); load(); };+ cap.append(back);+ }+ fig.append(cap);+ return fig;+ }));+ if (f.rendering) setTimeout(load, 3000);+}+$('file').onchange = async (e) => {+ const file = e.target.files[0];+ e.target.value = '';+ if (!file) return;+ const r = await fetch(`/api/furniture/${target}`, { method: 'POST', body: file });+ if (!r.ok) alert((await r.json()).error);+ load();+};+load();+</script>+</body>+</html>diff --git a/web/index.html b/web/index.htmlindex 8a54ab7..e8f2750 100644--- a/web/index.html+++ b/web/index.html@@ -20,6 +20,7 @@<span>or click to choose · CAD-exported PDF</span></label><p id="msg" role="status"></p>+ <p class="links"><button class="more" id="sample">Try the sample plan</button> · <a href="/web/furniture.html">Furniture models</a></p><p class="steps" id="steps">Detect → Review → Build → Walk</p><section class="setup" id="setup" hidden>@@ -57,6 +58,10 @@ async function upload(f) {}}$('file').onchange = (e) => upload(e.target.files[0]);+$('sample').onclick = async () => { // the made-up drawing that ships with the project+ const pdf = await fetch('/examples/sample_plan.pdf').then((r) => r.blob());+ upload(new File([pdf], 'sample_plan.pdf', { type: 'application/pdf' }));+};['dragenter', 'dragover'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('over'); }));['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('over'); }));drop.addEventListener('drop', (e) => upload(e.dataTransfer.files[0]));@@ -140,6 +145,13 @@ fetch('/api/jobs').then((r) => r.json()).then((jobs) => {const [label, cls] = STAGE[j.stage] || [j.stage, ''];row.append(a, el('span', `chip ${cls}`, label));if (done) { const e = el('a', 'edit', 'Edit'); e.href = `/web/edit.html?job=${j.id}`; row.append(e); }+ const del = el('button', 'more del', 'Delete');+ del.onclick = async () => {+ if (!confirm(`Delete "${j.name || j.id}" and its 3D house? This cannot be undone.`)) return;+ const r = await fetch(`/api/jobs/${j.id}`, { method: 'DELETE' });+ if (r.ok) row.remove(); else alert((await r.json()).error);+ };+ row.append(del);$('jobs').append(row);}if (jobs.length > 5) {diff --git a/web/style.css b/web/style.cssindex 62ad890..f20888d 100644--- a/web/style.css+++ b/web/style.css@@ -54,7 +54,17 @@ h1 { font-size: 28px; margin: 0 0 6px; }.chip.ok { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }.chip.bad { color: var(--bad); background: color-mix(in srgb, var(--bad) 12%, transparent); }.more { margin-top: 10px; background: none; border: 0; color: var(--accent); cursor: pointer; padding: 4px 0; font-size: 14px; }+.links { text-align: center; margin: 4px 0 0; font-size: 14px; color: var(--muted); }+.links .more, .job .del { margin: 0; }+.job .del { font-size: 13px; color: var(--bad); }.empty { padding: 16px 14px; color: var(--muted); font-size: 14px; }+.furn { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 14px; margin-top: 20px; }+.furn figure { margin: 0; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }+.furn img, .furn .wait { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; background: var(--bg); }+.furn .wait { display: grid; place-items: center; color: var(--muted); font-size: 13px; }+.furn figcaption { padding: 10px 12px; display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; }+.furn b { flex: 1 1 100%; }+.furn .more { margin: 0; font-size: 13px; }@media (max-width: 560px) { .wrap { padding-top: 32px; } }.bar { height: 8px; background: var(--line); border-radius: 4px; overflow: hidden; }.bar > i { display: block; height: 100%; background: var(--accent); width: 0; transition: width .4s; }diff --git a/web/view.html b/web/view.htmlindex 084e011..b477759 100644--- a/web/view.html+++ b/web/view.html@@ -48,7 +48,7 @@</div><div id="room"></div><div id="cross"></div>-<div id="bar"><button id="topbtn">Top view</button><span id="floors"></span><button id="shot" title="Save a picture of this view (P)">Screenshot</button><button id="rec" title="Record a video of your walk (R)">Record</button><button id="blend" title="Download this house as a Blender file (.zip)">Blender file</button><a href="/" id="newplan" style="color:#ccc;font-size:13px">New plan</a><span id="fps"></span></div>+<div id="bar"><button id="topbtn">Top view</button><span id="floors"></span><button id="shot" title="Save a picture of this view (P)">Screenshot</button><button id="rec" title="Record a video of your walk (R)">Record</button><button id="blend" title="Download this house as a Blender file (.zip)">Blender file</button><a href="/" id="newplan" style="color:#ccc;font-size:13px">Home</a><span id="fps"></span></div><script type="module" src="/web/view.js"></script></body></html>diff --git a/web/view.js b/web/view.jsindex 57f96d3..25ef7fc 100644--- a/web/view.js+++ b/web/view.js@@ -283,7 +283,12 @@ function toggleRec() {rec = null;$('rec').textContent = 'Record';$('rec').classList.remove('live');- save(new Blob(chunks, { type: REC_TYPE }), REC_TYPE.includes('mp4') ? 'mp4' : 'webm');+ const blob = new Blob(chunks, { type: REC_TYPE });+ if (REC_TYPE.includes('mp4')) return save(blob, 'mp4');+ $('rec').textContent = 'Converting…'; // this browser records WebM: the server turns it into MP4+ fetch('/api/mp4', { method: 'POST', body: blob }).then((r) => (r.ok ? r.blob() : Promise.reject()))+ .then((mp4) => save(mp4, 'mp4'), () => save(blob, 'webm')) // (no ffmpeg on the server: keep the WebM)+ .finally(() => { $('rec').textContent = 'Record'; });};rec.start(1000);$('rec').classList.add('live');