Skip to content

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

Python

Download the walkthrough as a self-contained website

23f200563997ab2634707a
diff --git a/README.md b/README.md
index 876d035..ecc15f7 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,7 @@ python server.py
| **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 |
+| **Website** | The walkthrough as a static website in a zip, to share without this server (see below) |
| **Furniture models in the review page** | **Change furniture models** opens the furniture page in a window, so you can swap a model and then build |
### Your own furniture
@@ -160,6 +161,7 @@ sequenceDiagram
| `POST /api/jobs/{id}/plan` | Save an edited plan. `"furnish": false` builds empty rooms |
| `POST /api/jobs/{id}/build` | Body `{ "quality": "draft" \| "high" }`. Builds run one at a time |
| `POST /api/jobs/{id}/export` | Packs the Blender file. Returns `{ url }` of the zip |
+| `POST /api/jobs/{id}/site` | Packs the walkthrough as a static website. Returns `{ url }` of the zip |
| `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 |
@@ -168,6 +170,14 @@ sequenceDiagram
To let people correct the plan first, show `/web/edit.html?job={id}` in the iframe instead of building straight away.
+### Share the walkthrough without the server
+
+The server has no login, so do not open it to the internet for clients. Instead press **Website** in the walkthrough
+(or `POST /api/jobs/{id}/site`): the zip holds the viewer, the three.js files it needs and the house, nothing else
+(not the PDF, not the plan). Unzip it onto any static host (Netlify, GitHub Pages, your own web server) and send the
+link. To try it locally, run `python3 -m http.server` in the unzipped folder; opening `index.html` straight from the
+disk does not load the viewer's modules. Recordings there are saved as the browser makes them (MP4 or WebM).
+
## Project layout
```
diff --git a/server.py b/server.py
index 6fd9918..f6eb63c 100644
--- a/server.py
+++ b/server.py
@@ -3,7 +3,7 @@ Standard library only. Run: python3 server.py [--port 8080] [--host 127.0.0.1] [
Builds run one at a time in Blender (GPU) in a background thread; progress is polled by the pages.
--cors lets pages on another site call the API from the browser (ORIGIN such as https://example.com, or *).
There is no login: run it on a trusted network, or behind your own backend or proxy."""
-import importlib, json, os, queue, re, shutil, subprocess, sys, threading, time, traceback, uuid, zipfile
+import importlib, json, os, posixpath, queue, re, shutil, subprocess, sys, threading, time, traceback, uuid, zipfile
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, unquote
@@ -53,7 +53,7 @@ def read_status(jid):
# ------------------------------------------------------------------ system check and the materials download
_blender = None # Blender's version, read once ("" = not found)
assets_job = dict(running=False, done=0, total=0, failed=[])
-export_lock = threading.Lock()
+export_lock, site_lock = threading.Lock(), threading.Lock() # the site zip takes a second: it must not wait for a Blender pack
def system():
@@ -107,6 +107,59 @@ def export_blend(jid):
return f"/jobs/{jid}/house_blender.zip"
+def three_files():
+ """the three.js files the viewer loads: what view.js and walk.js import from three, and what those import in turn"""
+ def deps(text, here):
+ for s in re.findall(r"\b(?:from|import)\s*['\"]([^'\"]+)['\"]", text):
+ if s == "three":
+ yield "build/three.module.js"
+ elif s.startswith("three/addons/"):
+ yield "examples/jsm/" + s[13:]
+ elif s.startswith(".") and here is not None:
+ yield posixpath.normpath(posixpath.join(here, s))
+ todo, seen = [f for w in ("view.js", "walk.js") for f in deps(open(os.path.join(WEB, w)).read(), None)], set()
+ while todo:
+ f = todo.pop()
+ if f not in seen and os.path.isfile(os.path.join(THREE, f)): # (an example in a doc comment may name a file that is not there)
+ seen.add(f)
+ todo += deps(open(os.path.join(THREE, f)).read(), posixpath.dirname(f))
+ # DRACOLoader fetches its decoder at run time (the WebAssembly one, as every browser with import maps has it)
+ return sorted(seen) + ["examples/jsm/libs/draco/draco_wasm_wrapper.js", "examples/jsm/libs/draco/draco_decoder.wasm"]
+
+
+def export_site(jid):
+ """jobs/<id>/house_site.zip: the walkthrough as a static website for any web host, without this server (made once
+ per build). Only the house itself leaves the job folder: never the client's PDF, the plan or the logs."""
+ d = jdir(jid)
+ glb, out = os.path.join(d, "house.glb"), os.path.join(d, "house_site.zip")
+ if not os.path.exists(glb):
+ raise ValueError("build the 3D house first")
+ srcs = [glb, os.path.join(d, "meta.json")] + [os.path.join(WEB, f) for f in ("view.html", "view.js", "walk.js", "style.css")]
+ with site_lock:
+ if not os.path.exists(out) or os.path.getmtime(out) < max(map(os.path.getmtime, srcs)): # a new build or a new viewer
+ meta = json.load(open(os.path.join(d, "meta.json")))
+ house = ["meta.json", "house.glb"] + [os.path.basename(f) for f in (meta.get("lightmaps") or {}).values()]
+ # view.html with three.js next to it; view.js finds no ?job= and reads the house from ./house/
+ page = open(os.path.join(WEB, "view.html")).read().replace('"/three/', '"./three/')
+ with zipfile.ZipFile(out + ".part", "w", zipfile.ZIP_DEFLATED) as z:
+ z.writestr("index.html", page)
+ for f in ("view.js", "walk.js", "style.css"):
+ z.write(os.path.join(WEB, f), f)
+ for f in three_files():
+ z.write(os.path.join(THREE, f), "three/" + f)
+ for f in house: # already compressed (Draco, WebP)
+ z.write(os.path.join(d, f), "house/" + f, zipfile.ZIP_STORED)
+ z.writestr("README.txt", "3D walkthrough - made by PlanTo3D.\n\n"
+ "Put this folder on any static web host (Netlify, GitHub Pages, your own server) and open index.html.\n"
+ "To try it on your computer, run a web server in this folder, for example\n"
+ " python3 -m http.server 8000\n"
+ "and open http://localhost:8000/ . Opening index.html straight from the disk does not work:\n"
+ "browsers do not load the viewer's modules from file:// pages.\n\n"
+ "Viewer: three.js (MIT). Textures and models are CC0, from polyhaven.com.\n")
+ os.replace(out + ".part", out)
+ return f"/jobs/{jid}/house_site.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, tried=False)
@@ -379,11 +432,15 @@ class H(BaseHTTPRequestHandler):
status(jid, name=name, stage="uploaded", progress=0, message="Uploaded", created=time.time())
threading.Thread(target=run_detect, args=(jid,), daemon=True).start()
return self.send(200, {"id": jid})
- m = re.match(r"^/api/jobs/([a-f0-9]{12})/(plan|build|export)$", p)
+ m = re.match(r"^/api/jobs/([a-f0-9]{12})/(plan|build|export|site)$", p)
if m and os.path.isdir(jdir(m.group(1))):
jid, what = m.groups()
if what == "export":
return self.send(200, {"url": export_blend(jid)})
+ if what == "site":
+ if (read_status(jid) or {}).get("stage") in BUSY: # half old, half new files: and it would be kept
+ return self.send(409, {"error": "this plan is being read or built"})
+ return self.send(200, {"url": export_site(jid)})
req = json.loads(self.body() or b"{}")
if not isinstance(req, dict):
raise ValueError("expected a JSON object")
diff --git a/tests/test_server.py b/tests/test_server.py
index 6b2d201..8b5cc6e 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -1,7 +1,7 @@
"""The server's guards, without Blender: files outside the web folders stay hidden, a plan that is being read or built
cannot be changed or deleted, bad request bodies get an answer, and a cover sheet before the plan is not taken for a
scan. python3 tests/test_server.py"""
-import json, os, shutil, subprocess, sys, tempfile, threading, urllib.error, urllib.request
+import json, os, shutil, subprocess, sys, tempfile, threading, urllib.error, urllib.request, zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
@@ -43,9 +43,24 @@ try:
assert call("POST", f"/api/jobs/{done}/plan", b'{"floors": [{"name": "G"}]}')[0] == 200
assert json.load(open(os.path.join(server.jdir(done), "plan.json")))["floors"][0]["name"] == "G"
assert call("POST", f"/api/jobs/{done}/export")[0] == 400 # nothing built yet
+ assert call("POST", f"/api/jobs/{done}/site")[0] == 400 # nothing built yet
assert call("DELETE", f"/api/jobs/{done}")[0] == 200 and not os.path.exists(server.jdir(done))
print("ok server: hidden files, busy plans, bad bodies")
+ # the website zip: the viewer, the three.js it loads and the house, and nothing else from the job folder
+ built = job("done")
+ for f, data in (("meta.json", b'{"lightmaps": {"bake_level_0": "lm_bake_level_0.webp"}}'), ("house.glb", b"glTF"),
+ ("lm_bake_level_0.webp", b"RIFF"), ("source.pdf", b"%PDF"), ("plan.json", b"{}")):
+ open(os.path.join(server.jdir(built), f), "wb").write(data)
+ code, body = call("POST", f"/api/jobs/{built}/site")
+ assert code == 200, body
+ names = zipfile.ZipFile(os.path.join(server.jdir(built), "house_site.zip")).namelist()
+ for f in ("index.html", "view.js", "walk.js", "three/build/three.module.js", "three/examples/jsm/libs/draco/draco_decoder.wasm",
+ "house/meta.json", "house/house.glb", "house/lm_bake_level_0.webp"):
+ assert f in names, f
+ assert not [f for f in names if f.endswith(("source.pdf", "plan.json", "status.json"))], names
+ print("ok server: website zip")
+
# a title sheet with no drawing before the plan: the plan on page 2 is found, and its page is the one drawn
cover = os.path.join(server.JOBS, "cover.pdf")
open(cover, "wb").write(M.pdf_page(b""))
diff --git a/web/view.html b/web/view.html
index b477759..57c652b 100644
--- a/web/view.html
+++ b/web/view.html
@@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>3D Walkthrough</title>
-<link rel="stylesheet" href="/web/style.css?v=2">
+<link rel="stylesheet" href="style.css?v=2">
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #111; touch-action: none; }
canvas { display: block; }
@@ -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">Home</a><span id="fps"></span></div>
-<script type="module" src="/web/view.js"></script>
+<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><button id="site" title="Download this walkthrough as a website for any web host (.zip)">Website</button><a href="/" id="newplan" style="color:#ccc;font-size:13px">Home</a><span id="fps"></span></div>
+<script type="module" src="view.js"></script>
</body>
</html>
diff --git a/web/view.js b/web/view.js
index cda1c98..0420850 100644
--- a/web/view.js
+++ b/web/view.js
@@ -4,11 +4,12 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
-import * as walk from '/web/walk.js';
+import * as walk from './walk.js'; // relative: the same file serves the downloaded website
const $ = (id) => document.getElementById(id);
const job = new URLSearchParams(location.search).get('job');
-const base = `/jobs/${job}/`;
+const site = !job; // the downloaded website (no server): the house is in ./house/ and there is no /api
+const base = site ? './house/' : `/jobs/${job}/`;
const WALK = 1.5, RUN = 3.0;
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
@@ -25,7 +26,7 @@ const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 0.05, 4
const env = new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(), 0.04).texture;
const meta = await fetch(base + 'meta.json').then((r) => r.json());
-const draco = new DRACOLoader().setDecoderPath('/three/examples/jsm/libs/draco/');
+const draco = new DRACOLoader().setDecoderPath((site ? '.' : '') + '/three/examples/jsm/libs/draco/');
const gltf = await new GLTFLoader().setDRACOLoader(draco).loadAsync(base + 'house.glb', (e) => {
if (e.total) $('status').textContent = `Loading model… ${Math.round(100 * e.loaded / e.total)}%`;
});
@@ -286,6 +287,7 @@ function toggleRec() {
$('rec').classList.remove('live');
const blob = new Blob(chunks, { type: REC_TYPE });
if (REC_TYPE.includes('mp4')) return save(blob, 'mp4');
+ if (site) return save(blob, 'webm');
$('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)
@@ -310,6 +312,22 @@ $('blend').onclick = async () => { // the server packs the textures into
b.disabled = false;
b.textContent = 'Blender file';
};
+$('site').onclick = async () => { // the walkthrough as a static website, for clients who cannot reach this server
+ const b = $('site');
+ b.disabled = true;
+ b.textContent = 'Preparing…';
+ try {
+ const r = await fetch(`/api/jobs/${job}/site`, { method: 'POST' }), j = await r.json();
+ if (!r.ok) throw new Error(j.error);
+ const a = document.createElement('a');
+ a.href = j.url;
+ a.download = 'house-website.zip';
+ a.click();
+ } catch (e) { alert(e.message || 'Could not prepare the website.'); }
+ b.disabled = false;
+ b.textContent = 'Website';
+};
+if (site) ['blend', 'site', 'newplan'].forEach((id) => $(id).remove());
$('shot').onclick = screenshot;
$('rec').onclick = toggleRec;
$('rec').hidden = !REC_TYPE; // this browser cannot record video
@@ -359,7 +377,7 @@ if (q.get('pose')) {
$('overlay').style.display = 'none';
}
if (q.get('top') !== null) { toggleTop(); showLevels(+q.get('top') || 0); }
-if (q.get('embed') !== null) $('newplan').remove(); // inside another site's page there is no "new plan" to go to
+if (q.get('embed') !== null) $('newplan')?.remove(); // inside another site's page there is no "new plan" to go to
// recording hook: draw one frame at a pose (metres, radians) and return it as a JPEG data URL
window.__frame = (x, y, z, yaw, pitch) => {
renderer.setAnimationLoop(null);