manifoldx on the web: one Python app, a browser target, and run --web
An app written once in Python against manifoldx runs in a browser tab with no JavaScript of its own. The export runs the app's setup in Python, writes the scene as glTF and the live state as JSON, and transpiles the code that runs every frame into JavaScript that drives a small manifoldx runtime over three.js. manifoldx run --web does the same on every save, so an app is developed in the browser the way manifoldx run develops it in a window.
01What this delivers
Today an app that wants a browser version keeps two copies of its logic: the Python that the desktop viewer runs, and a hand port in JavaScript, kept equal by golden files. The first consumer, a campus viewer, ports its terrain, collision, picking and camera rig line by line (216 lines of JS) and hand-writes the rest of the page around manifoldx's glTF export (about 400 more lines). A second app, a virtual trade fair, uses manifoldx only to model and export GLBs and writes all its behaviour in 1,800 lines of three.js. After this work, neither keeps JavaScript of its own.
Two throwaway spikes measured the approach on the first consumer before this spec was written:
The first spike, a 593-line transpiler with a 29-line runtime, turned the app's geometry, rig and terrain modules into JS that passes the same golden tests as the hand port. The second ran the real app through its startup in Python, saved its state to JSON, loaded that state into the transpiled JS, and replayed one scripted input on both sides: clicks that picked five buildings, 76 material swaps, 370 frames of walking, pointer capture and release. Mode, selection, panel text and every engine call matched; positions agreed to 3.6e-15 and the camera exactly. Breaking the generated code, the camera's float32 or the scene's solids each showed up in the comparison.
02Decisions
| decision | what | why | by |
|---|---|---|---|
| no app JavaScript | An app is Python only. Nothing an app author writes is JavaScript. | Two copies of logic drift; golden files only catch the drift they sample. | maintainer |
| transpile, not Pyodide | A subset of Python becomes JavaScript at export time. | Small output that starts at once; the shader transpiler already proves the approach in this repo. | maintainer |
| first consumer | The campus viewer is the first app to drop its JS; the trade fair follows. | It already measures parity against its desktop viewer, so every step has a check. | maintainer |
| a dev loop in the browser | manifoldx run --web re-exports on save and the open tab takes the new version. | The browser is where the app is developed, not only where it ships. | maintainer |
| split by reach | Code reached from systems, event handlers and GUI getters is transpiled; everything else is setup and runs in Python at export. | Setup loads files, builds meshes and talks to the GPU; none of that needs to run in a browser. It is exactly what the glTF export report lists as dropped today. | agent |
| outside the subset fails | Code that is reached and cannot be transpiled stops the export with file.py:line and the construct. | The current export silently drops systems; a silent drop on the web would be a wrong app. | agent |
| types decide | Types come first from annotations, then from the live objects after setup (each field's type is the type of the value it holds), then from inference over locals. An expression whose type is still unknown and matters (an operator, a method call) stops the export and asks for an annotation. A value may be one of several app classes; hasattr and isinstance tell them apart. | The first consumer has one annotated function in 44, so annotations alone would not let it transpile unchanged. The live objects exist anyway, because the snapshot walks them. The spikes guessed by name instead: a field called parts on one class pulled in another class's parts. | agent |
| the glTF export grows | export_gltf writes each node's entity index and each material's id in extras, and writes every registered material, used or not. The desktop renderer and ECS do not change. | The runtime resolves handles by those ids, and a material that no entity uses at startup (a highlight) is still needed by set_material. Additive, so existing exports stay valid. | agent |
| consumers may change | The first consumer edits its code to adopt the APIs of section 09. A pattern the second consumer also uses becomes a subset feature; a one-off becomes an edit in the app. | The subset grows by what real apps need, not by every construct one app happens to use. | agent |
| state as a snapshot | After setup, the app objects the browser code reaches are written to JSON by type, with only the fields it reaches; manifoldx objects travel as handles. | The browser gets the setup's result without running it, and shared objects stay shared. | agent |
| three.js renders | The browser runtime draws the exported glTF with three.js. | The glTF export exists, three.js is vendored by both apps already, and the campus viewer draws 166,000 triangles at 60 fps on a 2015 integrated GPU with it. | agent |
| dtypes carry over | Where manifoldx holds float32 (the camera), the runtime holds float32 too (Float32Array, Math.fround). | The camera's forward vector is np.float32 and flows into app math; without float32 in JS the camera drifted 7.6e-6 in the spike. | agent |
| only engine.state survives a reload | Under run --web, as under run, a save rebuilds the app and keeps engine.state. | The same app code then behaves the same in a window and in a tab, and the tab protocol stays one JSON round trip. An app keeps its place across saves by keeping it in engine.state: the first consumer moves its camera there in slice 4. | maintainer |
| parity by replay | The check for every slice is one scripted input run through the Python app and the exported app, compared frame by frame. | The spike's replay caught every break it was given; golden files cover only what they sample. | agent |
03How it fits
The pieces are new modules in a manifoldx.web package, a runtime shipped as static files inside the wheel, and two commands. Nothing changes in the renderer, the ECS or the desktop path. The existing pieces it builds on are Engine.export_gltf and its report (gltf/engine_export.py), the reloader (hot.py), the dev server (devchannel.py) and the shader transpiler (compute/transpile.py). The web transpiler has its own type model and may reuse small helpers from the shader transpiler; refactoring that module is out of scope, because its type environment holds WGSL types for one class and its uniforms.
04The transpiler
Input: the app's modules (those hot.py already counts as the app's own) and the roots. Output: one ES module per Python module, holding only what the roots reach.
Roots and reach
The roots are every function registered with engine.system, every handler registered with engine.on except startup, and every getter or callback a GUI widget holds (a ValueDisplay's getter, a Button's handler). Reach follows calls and attribute reads through types: a method is included when a reached expression calls it on a value of its class. Module constants are included when reached. Constructors are not, unless reached code builds an object: objects made at setup arrive through the snapshot.
The subset
What the spikes needed, with the semantics each one has to keep. The builder extends it as the second consumer asks; each addition gets a test that runs it in Python and in Node.
| Python | JavaScript | the trap |
|---|---|---|
functions, methods, dataclasses, classes with __call__, closures, lambdas, @property | functions, classes, arrows, getters | A callable instance must stay callable: the runtime wraps it in a function that carries the object. |
%, //, chained comparisons | runtime mod, Math.floor, && | Python's % takes the divisor's sign. |
and, or, not, if x | runtime truthy, or_, and_ | An empty list or dict is false in Python and true in JS; and/or return an operand. Plain && only when both sides are known booleans. |
| keyword arguments, defaults | positional, placed by the callee's signature | Needs the callee's signature, including from other modules. |
hasattr(x, "f"), isinstance(x, AppClass) | "f" in x, x instanceof AppClass | Only against the app's own classes, whose instances the snapshot builds with the transpiled prototypes. |
small numpy vectors: np.array, zeros, + - * / with broadcast, slices, linalg.norm, np.arange | arrays and runtime v* helpers; Float32Array for float32 | np.arange is start + i * step, not a running sum; += writes in place in numpy and must too when the array is shared. |
math: radians, degrees, trig, hypot, inf | Math and runtime helpers | CPython multiplies by a precomputed constant in radians; x * Math.PI / 180 rounds differently. |
lists, tuples, dicts with string keys, sets, comprehensions, in, len, min/max(key=), any, next, dict.get, list + and * | arrays, objects, Set, runtime helpers | + on lists concatenates: the transpiler must know the type. |
f-strings with :.Nf, str.lower and the like, textwrap.wrap | template literals, runtime fmt, wrap | toFixed breaks exact ties upward and Python to even; str(3.0) is "3.0". The runtime ports these, not the app. |
Outside the subset, for now: isinstance against library types, getattr, exceptions, generators that stay lazy, **kwargs, dicts with non-string keys, slices with steps, numpy over component arrays (see non-goals), and any import that is not math, numpy, textwrap or the app's own modules. A setup-only import (json, pathlib, a GUI library) is fine as long as reached code never names it.
Errors and source maps
The transpiler emits a source map per module, so a JS exception in the tab shows the Python file and line, and the dev overlay can quote the Python source. An unsupported construct reports the root that reached it as well as its own line, because the reader needs to know why setup code is being transpiled.
05The state snapshot
After setup has run (the first frame's startup included), the exporter walks the app objects that reached code reads, starting from the roots' owners (a bound method's self, a closure's cells, module globals the roots read).
- An object of an app class is written as its type and the fields reached code reads. Another field is left out, which also keeps setup-only data (file paths, raw JSON) out of the page.
- An object reached twice is written once and referenced, so identity survives: in the first consumer, the rig's
groundand the scene'sterrainare one object. - numpy arrays keep their dtype (
float32becomesFloat32Array). Tuples become arrays, string-keyed dicts objects, setsSets. - A manifoldx object becomes a handle the runtime resolves: the engine, a material, a GUI widget, an entity. Materials and entities resolve to the glTF's nodes and materials by the ids
export_gltfwrites in extras (see decisions). The per-node names and extras an app passes toexport_gltftoday become engine settings, soexport --webcan apply them when it capturesengine.run(); the builder names them. - What cannot cross stops the export with its path from the root: a function that is not reached code, a dict with integer keys, an object of a library class.
In the browser, the runtime builds each object without running its constructor (Object.create on the transpiled class), then fills the fields. The spike's snapshot of the first consumer was 0.25 MB; the export gzips it with the rest.
06The browser runtime
manifoldx.js implements the engine surface that reached code calls, with manifoldx's names, so the transpiled code calls engine.input.just_pressed("Tab") unchanged. It loads scene.glb with three.js, applies the scene extras the export writes (sun, sky, fog, shadow settings) once with a calibration that lives in manifoldx, loads state.json, and runs the systems every animation frame with dt.
first consumer's surface
input: pressed_keys, just_pressed, mouse_delta, is_mouse_pressed, just_mouse_pressed, viewport_size, capture_pointer. camera: position, target, near, far, get_forward. gui: Panel, Text, ValueDisplay, pointer_over_gui. engine.set_material, w, h, state.
later, as apps ask
Events with payloads (emit), entity transforms written by systems (the trade fair's walkers), skinned meshes and clips once the export writes them (#82), Button, Slider, Toggle, sounds.
The GUI draws as HTML elements over the canvas, laid out by the same anchor, offset and style values the Python widgets hold. Pixel equality with the desktop GUI is not a goal; the text and the layout are.
Visual parity with the desktop renderer is measured, not assumed: the export test renders a frame headless in Python and in Chromium from the same view, and the mean colour per channel must stay within a threshold. The first consumer found three.js's sky 8 to 16% darker at the same intensity and corrected it in its own JS; that correction moves into the runtime.
07export --web
manifoldx export --web app.py out/ # a static folder any web server can serve manifoldx export --web -m pkg.main out/
out/ index.html the canvas, a progress bar, the runtime's bootstrap manifoldx.js the runtime vendor/three/ pinned, minified, so the folder works offline scene.glb the scene, meshopt-compressed when gltf-transform is present state.json the snapshot app/*.js, pyrt.js the transpiled modules and their helpers report.json what was transpiled, what stayed setup, what failed
The app keeps calling engine.run() or engine.cli() as on the desktop; the command runs the app until that call, as manifoldx export does today, then runs one frame headless so startup fires.
08run --web
manifoldx run --web app.py # serves on 127.0.0.1 and prints the URL manifoldx run --web app.py -- --level 3
It reuses the reloader's watching rules and the dev server. On a save:
the tab sends its engine.state
The server asks the open tab for engine.state and waits a short time for it. Without a tab, the last state it received is used.
setup reruns in Python with that state
As under run, the app's modules are dropped and rerun until engine.run(), then startup fires on one headless frame.
export into a new version folder
The glTF is written only when its content hash changed, so a code-only edit skips it. The transpiled modules and the snapshot are always written.
the tab swaps
The server pushes the version over the dev channel. The tab imports the new modules, loads the new snapshot, keeps the three.js scene when the hash did not change, and resumes. The page itself does not reload.
Errors behave as under run. An edit that fails to load or to transpile leaves the running version in the tab with an overlay naming the Python line. An exception in a frame pauses the app with the Python traceback from the source map; the next save resumes it.
The agent commands work against the tab: manifoldx look returns the tab's last frame, state and set read and patch the tab's engine.state, emit fires an event in the tab, log includes the tab's console.
try itWhat the tab shows for each kind of save. Sample scene, no real app.
18.0 m (levels)
WALK (Tab: fly)
09Engine APIs it needs
The first consumer reaches into private manifoldx state in three places. Transpiled code cannot do that, so each becomes public API, on the desktop and in the runtime:
| API | replaces | note |
|---|---|---|
engine.set_material(entity, material) | writing the material id into engine.store._components["Material"] | The runtime maps it to the glTF node's material. Related: #56. |
engine.input.capture_pointer(on) | setting the glfw cursor mode on the canvas's private window | The browser's Pointer Lock API; it needs a user gesture, which a click gives. |
engine.input.viewport_size | reading input._viewport_size | Exists; the app reads the private name only because it reports (0, 0) before the first resize. |
10Delivery
Each slice ends with the first consumer working one step further, checked by replay.
transpiler
manifoldx.web.transpile with types, reach, source maps and errors. Done when the first consumer's geometry, rig and terrain modules transpile unchanged and pass its golden tests in Node.
snapshot and headless runtime
The snapshot, the runtime without rendering, the replay harness, and the three APIs of section 09. Done when a scripted session replays in Node with no mismatch, in CI: manifoldx's CI replays a new public example app (walk, pick, select, a GUI panel, no textures, so setup runs on the offscreen backend CI already uses); the first consumer's CI replays the consumer, whose code is private.
export --web
three.js rendering from the glTF and its extras, the HTML GUI, browser input. Done when the first consumer's web build comes from export --web and its hand-written JS is deleted.
run --web
The dev loop of section 08 with the overlay and the agent commands. Done when a save in the first consumer shows in an open tab with engine.state kept, and the consumer's camera, moved into engine.state, stays where it was.
second consumer
The trade fair: entity transforms written by systems, events, more widgets. Specced after slice 4.
11Testing
- Every construct of the subset has a test that runs a snippet in Python and its transpiled form in Node and compares the results exactly, or to a stated tolerance where float formatting differs.
- The replay harness is part of manifoldx: it takes an app, a script of input frames and a list of values to trace, runs both sides and reports the first mismatch. The public example's script is a fixture in manifoldx; the first consumer keeps its own script in its repository.
- Each check is shown to fail: a test that breaks the generated code, the float32 handling or the snapshot must see the replay report a mismatch.
- Visual parity: one headless frame per side, mean colour per channel within a threshold.
- Node is a test dependency only. A machine without Node can still export, and skips these tests with a message.
12Non-goals
- Running Python in the browser (Pyodide). Reconsider only if the subset turns out too small for real apps.
- A WebGPU renderer that reuses manifoldx's WGSL shaders. It would make the desktop and web pictures equal by construction, and is the natural next step once WebGPU is available in the browsers the apps target; not in this work.
- Systems that run vectorised numpy over component arrays. They need a different translation (loops over typed arrays, or the WGSL compute transpiler on WebGPU) and get their own spec.
- Arbitrary Python, exceptions as control flow, the standard library beyond what the runtime ports.
- Pixel equality of the GUI with the desktop.
- Packaged desktop and mobile builds (#93's other targets).
13Open questions
- How fast a save must show. The first consumer's first frame took 27.5 s, mostly loading meshes and textures. The reloader's rule (cache heavy work in
engine.state) applies, but the export may still need a GPU device for textures. Slice 4 measures a reload of the first consumer and reports it before tuning. - Where the runtime is developed. As plain ES modules inside the Python package, tested with
node --test, or as a separate package. This spec assumes the first; the builder may change it if the runtime grows past a few thousand lines.