Files
busbar-designer/app.py
T
wenil 102cfcee64 tracks: new /tracks generator for IKEA Lillabo / Brio train tracks
Wraps torwanbukaj/ikea-brio-others-compatible-train-tracks-generator
( https://github.com/torwanbukaj/... ) as a third generator alongside
holder and the universal scad playground.

Approach
--------
The upstream .scad ships as "library + one active example call". Used
include<> (rather than use<>) so the library's top-level globals
(track_width, plug/nest dimensions, $fn = 150, etc.) are available
to the modules — `use<>` does NOT propagate variables. Commented out
the upstream `track_tester();` call so include<> doesn't also emit
the tester geometry every time.

Per-render the backend builds a tiny wrapper SCAD on the fly:

    include <scad/train_tracks.scad>
    track(length=100, end1="plug", end2="nest", cutout=true, ...);

and hands it to holder.render_source().

Part types exposed (9)
----------------------
- tester        Calibration block (15-60mm)
- track         Straight (length + chamfers + grooves + plug/nest ends)
- arc           Curved (radius + angle, IKEA/Brio/J'adore radii in help text)
- dogbone       Nest-nest connector
- intersection  Crossing (angle + 2 lengths + 4 ends)
- switch        Turnout (left/right radius+angle, straight branch, common end)
- snake         S-curve (raised default target_length to 200 — the upstream
                modules's natural curvy-span at angle=45/radius=86 is ~150
                and the assert fires below that)
- adapter       BRIO <-> IKEA system adapter (plug + nest side)
- bridge        Multi-part (overview/ground/slope/pillar — value_map
                translates the UI labels to the int 0..3 the SCAD wants)

Files
-----
- scad/train_tracks.scad      Downloaded upstream (57 999 bytes), only
                              modification is the // before the top-level
                              track_tester() call.
- tracks.py                   PART_SCHEMAS dict, build_wrapper_scad,
                              render() that delegates to render_source.
- app.py                      GET /api/tracks/params, POST /api/tracks/render,
                              GET /tracks page route.
- static/tracks.html          Page with part selector + dynamic param form +
                              shared viewer markup. Reuses holder.css.
- static/js/tracks-app.js     Controller. Switching the part select redraws
                              the form (each part has its own schema).
                              Ctrl+Enter renders, Cancel uses AbortController.

Nav
---
Tracks link added to topbar on holder / index / scad.

Smoke test
----------
All 9 parts render with default params on the Manifold backend in
under 0.5s each (output sizes 440 KB - 1.8 MB).
2026-05-25 13:38:29 +03:00

312 lines
8.9 KiB
Python

"""Flask entrypoint for Busbar Designer.
Serves the static frontend, the /api/export/<fmt> CAD endpoints (build123d →
STEP/DXF/SVG), and the /api/projects, /api/presets, /api/snapshots persistence
endpoints (SQLite via storage.py).
Run:
python app.py
"""
from __future__ import annotations
import json
import os
import sys
import traceback
from flask import Flask, Response, jsonify, request, send_from_directory
from busbar_export import WRITERS
import storage
import holder
import tracks
APP_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(APP_DIR, "static")
app = Flask(__name__, static_folder=STATIC_DIR, static_url_path="")
storage.init_db()
# ---------------------------------------------------------------------------
# Static + health
# ---------------------------------------------------------------------------
@app.get("/")
def index():
return send_from_directory(STATIC_DIR, "index.html")
@app.get("/holder")
def holder_page():
return send_from_directory(STATIC_DIR, "holder.html")
@app.get("/scad")
def scad_page():
"""Universal OpenSCAD renderer (paste any source, get STL)."""
return send_from_directory(STATIC_DIR, "scad.html")
@app.get("/tracks")
def tracks_page():
"""Wooden-train track generator (IKEA Lillabo / Brio compatible)."""
return send_from_directory(STATIC_DIR, "tracks.html")
@app.get("/api/health")
def health():
return jsonify({"status": "ok", "openscad": holder.openscad_available()})
# ---------------------------------------------------------------------------
# Hex holder designer (OpenSCAD-backed)
# ---------------------------------------------------------------------------
@app.get("/api/holder/params")
def holder_params():
"""Schema for the parameter form + their defaults."""
return jsonify({
"params": holder.schema_dict(),
"defaults": holder.default_params(),
"max_cells": holder.MAX_CELLS,
})
def _stl_response(data: bytes, dims: dict, filename: str) -> Response:
return Response(
data,
mimetype="model/stl",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"X-Holder-Dimensions": json.dumps(dims),
"Access-Control-Expose-Headers": "X-Holder-Dimensions",
},
)
@app.post("/api/holder/render")
def holder_render():
"""Render STL for the bundled hex holder with parameter overrides."""
body = request.get_json(silent=True) or {}
try:
data, dims = holder.render_stl(body.get("params", {}))
except ValueError as e:
return jsonify({"error": str(e)}), 400
except (FileNotFoundError, RuntimeError) as e:
return jsonify({"error": str(e)}), 500
return _stl_response(data, dims, "hex_holder.stl")
@app.get("/api/holder/source")
def holder_source():
"""Return the bundled hex_cell.scad text (for editor pre-population)."""
try:
return Response(holder.bundled_source(), mimetype="text/plain; charset=utf-8")
except FileNotFoundError as e:
return jsonify({"error": str(e)}), 500
@app.get("/api/tracks/params")
def tracks_params():
return jsonify(tracks.schema_dict())
@app.post("/api/tracks/render")
def tracks_render():
body = request.get_json(silent=True) or {}
part = body.get("part")
params = body.get("params") or {}
try:
data, dims = tracks.render(part, params)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except (FileNotFoundError, RuntimeError) as e:
return jsonify({"error": str(e)}), 500
return _stl_response(data, dims, f"track_{part or 'part'}.stl")
@app.post("/api/scad/render")
def scad_render():
"""Render arbitrary user-supplied OpenSCAD source (no holder schema).
Body: {"source": "...", "params": {optional -D overrides}}
"""
body = request.get_json(silent=True) or {}
source = body.get("source")
params = body.get("params") # may be None
try:
data, dims = holder.render_source(source, params)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except (FileNotFoundError, RuntimeError) as e:
return jsonify({"error": str(e)}), 500
return _stl_response(data, dims, "rendered.stl")
@app.post("/api/holder/cells")
def holder_cells():
"""Cell-center coordinates for the supplied parameters (no OpenSCAD needed)."""
body = request.get_json(silent=True) or {}
try:
cells = holder.compute_cells(body.get("params", {}))
except ValueError as e:
return jsonify({"error": str(e)}), 400
return jsonify({"cells": cells, "count": len(cells)})
# ---------------------------------------------------------------------------
# CAD export (unchanged contract)
# ---------------------------------------------------------------------------
@app.post("/api/export/<fmt>")
def export(fmt: str):
fmt = fmt.lower()
if fmt not in WRITERS:
return jsonify({"error": f"unsupported format: {fmt}"}), 400
payload = request.get_json(silent=True) or {}
writer, mimetype, ext = WRITERS[fmt]
try:
data = writer(payload)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except Exception as e:
traceback.print_exc()
return jsonify({"error": f"{type(e).__name__}: {e}"}), 500
filename = f"busbars.{ext}"
return Response(
data,
mimetype=mimetype,
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
# ---------------------------------------------------------------------------
# Projects
# ---------------------------------------------------------------------------
@app.get("/api/projects")
def projects_index():
return jsonify(storage.list_projects())
@app.post("/api/projects")
def projects_create():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "Untitled").strip() or "Untitled"
data = body.get("data") or {}
pid = storage.create_project(name, data)
return jsonify({"id": pid, "name": name})
@app.get("/api/projects/<int:pid>")
def projects_show(pid: int):
p = storage.get_project(pid)
if p is None:
return jsonify({"error": "not found"}), 404
return jsonify(p)
@app.put("/api/projects/<int:pid>")
def projects_update(pid: int):
body = request.get_json(silent=True) or {}
ok = storage.update_project(
pid,
name=body.get("name"),
data=body.get("data"),
snapshot=bool(body.get("snapshot", False)),
note=body.get("note"),
)
if not ok:
return jsonify({"error": "not found"}), 404
return jsonify({"ok": True})
@app.delete("/api/projects/<int:pid>")
def projects_delete(pid: int):
storage.delete_project(pid)
return jsonify({"ok": True})
# ---------------------------------------------------------------------------
# Snapshots
# ---------------------------------------------------------------------------
@app.get("/api/projects/<int:pid>/snapshots")
def snapshots_index(pid: int):
return jsonify(storage.list_snapshots(pid))
@app.get("/api/snapshots/<int:sid>")
def snapshot_show(sid: int):
snap = storage.get_snapshot(sid)
if snap is None:
return jsonify({"error": "not found"}), 404
return jsonify(snap)
@app.post("/api/snapshots/<int:sid>/restore")
def snapshot_restore(sid: int):
if not storage.restore_snapshot(sid):
return jsonify({"error": "not found"}), 404
return jsonify({"ok": True})
# ---------------------------------------------------------------------------
# Presets
# ---------------------------------------------------------------------------
@app.get("/api/presets")
def presets_index():
return jsonify(storage.list_presets())
@app.post("/api/presets")
def presets_create():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "").strip()
if not name:
return jsonify({"error": "name required"}), 400
pid = storage.create_preset(name, body.get("params") or {})
if pid is None:
return jsonify({"error": "name already in use"}), 409
return jsonify({"id": pid, "name": name})
@app.put("/api/presets/<int:pid>")
def presets_update(pid: int):
body = request.get_json(silent=True) or {}
ok = storage.update_preset(pid, name=body.get("name"), params=body.get("params"))
if not ok:
return jsonify({"error": "not found or name conflict"}), 404
return jsonify({"ok": True})
@app.delete("/api/presets/<int:pid>")
def presets_delete(pid: int):
storage.delete_preset(pid)
return jsonify({"ok": True})
# ---------------------------------------------------------------------------
# Boot
# ---------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
host = os.environ.get("HOST", "127.0.0.1")
debug = os.environ.get("FLASK_DEBUG", "1") == "1"
print(f" * Busbar Designer running on http://{host}:{port}", file=sys.stderr)
app.run(host=host, port=port, debug=debug)