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).
The CSS rule `.scad-panel { display: flex }` was overriding the HTML
`hidden` attribute (CSS specificity beats the user-agent rule on the
attribute). Effect: the Close button set hidden=true but the panel
stayed visible, and the panel was visible on first load too.
- Explicit `.scad-panel[hidden] { display: none }` rule restores the
intended behaviour: Close hides, initial load is hidden.
- Default height 45% -> 30%, with min-height 180px so the editor
isn't cramped even on small viewports.
Phase 2 — SCAD editor on /holder
================================
Some adjustments need more control than the parameter form gives
(e.g. tweaking the .scad logic itself). A collapsible CodeMirror-based
editor now slides up from the bottom of the viewport when you click
the "</> Source" button at the bottom-right.
- holder.html / holder.css: editor panel, toggle button, Reset and
Close buttons. CodeMirror 5 loaded from cdnjs (single CSS + JS
pair, clike mode for syntax highlighting since OpenSCAD is C-like).
- holder-app.js: lazy-initialises the editor on first show, fetches
bundled source from /api/holder/source, tracks whether the editor
content has been modified ("modified" tag in the panel title).
When the editor is visible AND content differs from bundled,
_doRender() switches from /api/holder/render -> /api/scad/render
with {source, params}. Cell-count cap doesn't apply in that mode
(the source may not even use the holder schema).
Phase 3 — Universal OpenSCAD playground at /scad
================================================
A standalone page for rendering arbitrary OpenSCAD. Paste code, click
Render (or Ctrl+Enter), see STL in the same Three.js viewer the
holder uses. Useful for prototyping new generators before wiring
them into a parameter form.
- New page: static/scad.html + scad.css + js/scad-app.js. Reuses
holder-viewer.js (the Three.js scene module is generic enough).
- "Load example" populates a 6-hole rounded bracket so new users
can verify the renderer works in two clicks.
- Same progress UI (elapsed timer + indeterminate bar + Cancel
via AbortController) as /holder.
- Top nav now has Holder / Busbars / SCAD on every page.
Backend (shared by phase 2 & 3)
================================
- holder.py: split _run_openscad() out of render_stl(). New
render_source(source, params=None) writes the source to a temp
file and renders it; enforces MAX_SOURCE_BYTES (default 512 KB)
and RENDER_TIMEOUT but skips the cell-count cap. New bundled_source()
returns the hex_cell.scad text for editor pre-population.
- app.py: GET /api/holder/source returns the bundled .scad text.
POST /api/scad/render takes {source, params?} and returns STL +
X-Holder-Dimensions header. ValueError -> 400, RuntimeError -> 500.
_stl_response() factored out so both render endpoints emit the same
headers consistently.
The bundled hex_cell.scad has many more knobs than the dozen we used to
expose (box clearances, cap/box wall, vertical stacking, busbar template,
etc). Maintaining a hand-curated PARAMS list in Python next to a SCAD file
that already documents every variable inline was always going to drift.
Sync + auto-extract approach:
- scad/hex_cell.scad: replace with the upstream master file from
Albert Phan's Hex-Cell-Holder fork (adds the BUSBAR TEMPLATE section
and the "busbar template" part option).
- holder.py: PARAMS now built at import time by _scan_scad(), which
regexes top-level `name = literal; // help` lines into Param entries
up until the // END OF CONFIGURATION marker. Scan handles bool /
number / string literals; derived expressions and helper variables
are skipped automatically.
- Manual maps stay small and explicit: _SELECT_OPTIONS for the few
string-enum params (part, pack_style, box_style, template_outline,
template_hole_style, etc.), _GROUP_RULES for UI sectioning, and
_NUMBER_HINTS for sensible min/max/step on the most-tweaked numbers.
UI:
- holder-app.js: extra GROUP_ORDER / GROUP_LABELS for the new
sections (cap, box, insulator, bolts, wires, stacking, template,
advanced). Group titles are now click-to-collapse; the advanced
groups start collapsed so the form isn't a wall of inputs on load.
- holder.css: caret marker on the group title, smooth rotate on
collapse, hides the body via .collapsed class.
Net effect: every variable in the .scad — including the new busbar
template knobs — is editable from the page, with helpful comments
copied straight from the .scad source.
The hex_cell.scad echoes its computed dimensions (pack_height_holder,
total_*_holder, box_total_*) to stderr. Capture those and surface them
in the viewer so the user can sanity-check whether the assembled
battery will fit in a target case.
Backend:
- holder.py: render_stl() now returns (stl_bytes, dims) where dims is
a {name: float} dict parsed from openscad ECHO lines.
- app.py: /api/holder/render emits the dims dict as an
X-Holder-Dimensions response header (JSON) with the matching
Access-Control-Expose-Headers entry so fetch() can read it under
any proxy / future CORS setup.
Viewer (holder-viewer.js):
- New setGhostBox(name, {w,d,h}, {visible,color}) and clearGhostBox(name)
helpers. Each ghost is a Group of a translucent BoxGeometry mesh +
matching EdgesGeometry wireframe, positioned to match how the STL
mesh is placed (centred XY, bottom on Z=0).
UI (holder.html / holder.css):
- New "Fit check" panel under Status with two sections:
• Show max bounding box (auto, from ECHO — defaults to box_total_*
dims, falls back to total_*_holder + pack_height_holder).
• Show enclosure (manual W × D × H inputs in mm).
- Verdict line under the enclosure inputs: "✓ fits" green or
"✗ too small — battery won't fit" red.
Controller (holder-app.js):
- Reads X-Holder-Dimensions after each render, updates the max-box
ghost in blue, prints the dimensions label.
- Watches enclosure inputs + toggles, drives the enclosure ghost
(green if it fits, red if smaller than the max box on any axis).
- Fit comparison is orientation-independent in the XY plane (sorted
W,D pair) but strict on Z (height).
User-triggered 120x120 = 14400 cells, which produces huge STL/long
renders. Total cells is the right metric (CSG cost scales with count,
not max axis), so cap by N = rows*cols (or rows*(rows+1)/2 for tria
style). 1000 covers any realistic pack (e.g. 20x50) while blocking
accidental misuse.
Backend:
- holder.py: MAX_CELLS env-tunable (default 1000); expected_cell_count
and _check_cell_limit raise ValueError on exceed; both
compute_cells() and render_stl() call it up-front.
- app.py: /api/holder/render now returns 400 on ValueError (not 500)
so the frontend can distinguish bad input from server failure.
/api/holder/params now publishes max_cells alongside the schema.
Frontend:
- holder-app.js: reads max_cells from the params endpoint; status
shows "N cells / over limit (1000)" in red and disables the
Render and "Design busbars" buttons when exceeded.
- holder.css: .topbar-status.over-limit style (red, bold).
- Replace debounced auto-render-on-param-change with an explicit Render
button. Param changes mark the button "dirty" (accent ring); user clicks
Render to drive a render. A Cancel button (AbortController) appears
while a render is in flight.
- Add indeterminate progress bar with elapsed-time counter in the status
panel. Real OpenSCAD --progress streaming can come later.
- Bump OPENSCAD_TIMEOUT default 60s -> 300s and gunicorn --timeout
120s -> 300s. The 60s cap was misclassified by the frontend as
"OpenSCAD not installed" because the error string contained the word
"openscad" -- which the JS matched too greedily.
- Frontend error classifier now distinguishes "binary not found",
"timed out", and "geometry empty" cases and only shows the
install-OpenSCAD hint for the real not-found case.
Server-side OpenSCAD renders STL from bundled hex_cell.scad with parameter
overrides via -D. Frontend is a Three.js viewer with auto-form generated
from /api/holder/params. 'Design busbars →' button posts the computed
cell coordinates to /api/projects and redirects to the busbar editor with
the holder cells pre-loaded.
- holder.py: openscad subprocess wrapper + compute_cells()
(Python mirror of get_hex_center_points_*)
- scad/hex_cell.scad: verbatim copy of Addy/Hex-Cell-Holder source
- app.py: /holder route + /api/holder/{params,render,cells}
- static/holder.html etc: parameter form + Three.js STL viewer
- Dockerfile / install.sh: apt install openscad
- static/index.html: nav link Holder ↔ Busbars in topbar