Three Slicer runs a real desktop slicing kernel inside a browser tab. Not a reimplementation in JavaScript, and not a server that slices for you — the same C++ that OrcaSlicer runs, compiled to WebAssembly with Emscripten. This is the log of what that cost.
A slicer is not one algorithm. It is a stack of them, each with decades of edge cases baked in: variable-width wall generation (Arachne), tree support growth, multi-material segmentation per layer, a prime tower that has to reconcile purge volumes between tool changes, pressure equalization, arc fitting, and a G-code time estimator that models the firmware's own acceleration planner. Reimplementing that in JavaScript gets you something that produces plausible toolpaths and prints badly.
So the rule for this project was set first and never relaxed: everything above the driver
layer is upstream verbatim. Arachne's WallToolPaths, the beading strategies,
the fill patterns, PressureEqualizer, GCodeProcessor,
WipeTower, MultiMaterialSegmentation — those files are the OrcaSlicer
files. Resin support points, the support tree and the pad are PrusaSlicer 2.9.6 files, and a test
fails the build if any of them drifts from its recorded upstream hash.
That rule is what makes the interesting part interesting. Every problem below is a problem at the seam — where upstream code expects an environment that a browser tab does not have.
Upstream code is written against upstream's object graph. MultiMaterialSegmentation.cpp,
for example, takes a PrintObject — which transitively wants a Print, a
config store, layer ranges, regions, and the slicing state machine that produced them. Pulling that
in means pulling in most of the application.
The port draws the line one level lower. The algorithm files stay verbatim; only their
drivers are rewritten to take plain data. Segmentation now receives the sliced contour of
every layer plus the painted facets from the triangle selector, through a small bridge
(segment_prepare / segment_regions). Same for Arachne, fills, the wipe
tower and the G-code processor: each has exactly one bridge translation unit sitting between the
kernel and upstream, and nothing else crosses.
This has consequences you only discover by running it. Segmentation is a whole-object pass, so the
multi-material path must slice every layer up front rather than lazily — and then reuse
those contours, or the model gets sliced twice. And a painted flat face reaches the print only
through segmentation_top_and_bottom_layers, because a horizontal facet cuts no slicing
plane at all: skip that pass as an optimization and a painted top surface silently comes out in the
wrong material.
Upstream files include upstream headers by path. Where the real header drags in the world,
the port puts a stub of the same name earlier on the include path — boost/log,
cereal, the SVG debug writer, Flow, parts of PrintConfig.
Each stub directory is scoped to the compile group that needs it, so the same symbol is never
defined two ways in one link.
This trick has one sharp edge worth naming: withccachein the loop, adding a new shadow header does not change any source file's own text, so cached objects for the old include resolution get silently reused and link cleanly against the wrong header. OneCCACHE_RECACHE=1run after introducing a shadow. It cost an afternoon to learn.
Slic3r-family code parallelizes with Intel TBB: tbb::parallel_for over layer ranges,
concurrent_vector, enumerable_thread_specific, task_group.
There is no TBB for wasm32.
The port supplies TBB's surface as headers of its own. The first version was entirely serial —
parallel_for(r, f) is just f(r), which is a legal implementation of a
parallel loop and produces bit-identical results. That alone got the kernel running.
Real threading came back later, opt-in and narrow. Inside an explicitly enabled scope, the
blocked_range overload splits across std::threads:
const size_t chunk = std::max<size_t>(1, n / (nt * 4));
std::atomic<size_t> next{0};
auto work = [&]{
for (;;) {
size_t lo = next.fetch_add(chunk);
if (lo >= n) break;
size_t hi = lo + chunk < n ? lo + chunk : n;
f(blocked_range<I>(b + (I)lo, b + (I)hi));
}
};
Three details in that snippet are scars, not style:
top_contact_layers reached 2.75x on 14 threads while the structurally identical
base_layers hit 10x. Work stealing fixed it.
std::thread construction is wrapped in try/catch. Emscripten returns
workers to its pool asynchronously, so a momentary exhaustion makes pthread_create
return EAGAIN and the constructor throws. Dying there would be absurd; the caller and
the already-started workers absorb the remaining chunks instead, with identical results.
task_group stayed serial. It was implicated in a crash, the benefit was small, and a
parallel primitive you cannot prove deterministic is not worth the debugging budget it will demand
later.
A small thing with a large user-facing effect: the serial path also has to tick the progress counter. It initially did not, and since tree support deliberately runs serial, a tree-support slice sat at exactly 36% for 71.5 seconds out of 76 on a 53.9MB plate. Nothing was wrong. It read as a total freeze anyway.
WebAssembly threads need SharedArrayBuffer, which needs cross-origin isolation, which
needs the host to send two headers:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
A library cannot require that of the sites that embed it. require-corp breaks any
third-party image or iframe the host has not explicitly opted in, so demanding it as a condition of
installation is a non-starter.
So the kernel is built twice — once plain, once with -pthread — and the worker picks at
load time:
const isolated = typeof crossOriginIsolated !== 'undefined' && crossOriginIsolated
if (isolated) {
try { return await (await import('./slicer_core.mt.js')).default() }
catch (e) { /* SAB blocked, pool refused — fall through */ }
}
return await (await import('./slicer_core.js')).default()
An isolated host gets threads (measured 2.2x on the layer pass); everyone else gets a single-threaded
kernel with zero configuration. The dynamic import() means bundlers emit both as
separate chunks and only one is ever fetched. The failure path matters as much as the fast path: an
environment can be cross-origin-isolated and still refuse the thread pool, and a slicer that
throws there instead of falling back is a slicer that works on your machine.
The one thing the fallback must not do is stay quiet. mt versus st is a 2x difference in how long a user waits, so which kernel loaded is logged once — with an off switch, since a product embedding the viewer should not have to explain the host's console output to its own users.
The kernel is compiled in groups, each partially linked with em++ -r into one object
before the final link. Groups exist because they need different flags: the CGAL-touching sources
need -DCGAL_DISABLE_GMP=1 (the GMP auto-detect otherwise emits __gmpn_*
references that no wasm build provides), the SGI tessellator is C and must go through
emcc rather than em++, and NLopt is pinned to Prusa's exact 2.5.0.
Everything is wrapped in ccache; an unchanged-TU rebuild drops from minutes to tens of
seconds, which matters more than it sounds when the feedback loop is a full kernel rebuild.
Final link flags worth explaining:
| Flag | Why |
|---|---|
SINGLE_FILE=1 | The single-threaded build only: its wasm is inlined into the JS. Self-contained on any static host, no MIME configuration, no second fetch from inside a worker. The threaded build ships slicer_core.mt.wasm beside its glue instead, because every pthread worker loads the glue itself: inlined, each of the ~16 workers per kernel held about 60MB of V8 heap for bytes it never reads, and Chrome keeps every V8 heap of a tab in one 4GB region, so three kernels slicing at once crashed the tab. Split, a pthread worker holds about 1MB. |
MODULARIZE=1 | The kernel is a library, not a page. Callers get a factory, not global side effects. |
ALLOW_MEMORY_GROWTH=1 | Model size is unbounded and unknown at load time. Emscripten warns about combining this with pthreads; it is functionally valid and was kept on measurement. |
ENVIRONMENT=web,worker,node | The same build runs headless in Node, which is what makes the invariant suite possible at all. |
-O2, not -O3 | Measured on an Arachne + support workload: -O3 -msimd128 gave 5183ms against -O2's 5149ms — noise — for +9% binary size. -flto crashes wasm-ld outright in combination with the partial-link groups. |
That -O3 row is the one to take away. Optimization flags on a wasm build are an
empirical question, not a ladder you climb. The intuition that more optimization is more speed
cost 300KB of download for nothing measurable.
wasm32 addresses 4GB, and a browser tab will not give you that anyway. A large plate sliced the original way held the full G-code plus the full toolpath array resident in the heap at once and died.
The fix was to invert the flow. The kernel takes a layer sink; each layer is emitted as it is
produced, transferred to the main thread immediately (the Float32Array buffers are
moved, so the worker's copy is released at once), and freed from the wasm heap. The final message
carries statistics only. Peak resident memory stops scaling with model size and starts scaling with
one layer.
The toolpath stream itself is packed for the same reason. Each segment carries a role field, and
the extruder index rides in that field's spare high bits (role + tool * 16) rather than
in a ninth float. Roles only reach 11, so the bits are free — and the segment stream is the largest
array the viewer holds, where a ninth float is a flat +12.5% for one small integer. Every reader
masks: & 15 for the role, >>> 4 for the tool.
Every change above is a change to code whose correct output nobody can eyeball. A wall is 0.03mm off; you will find out when the print fails.
So the project's real safety net is a byte-identical gate. A fixed model is sliced on default paths and the G-code is dumped; the dump before a change and the dump after must differ by zero bytes. Alongside it, an invariant suite of 120-plus checks asserts properties the output must hold rather than exact bytes, and a generated parameter reference fails the build when the documented kernel parameter table drifts from the actual reader call sites in the C++.
The gate is what allows aggressive work. Restoring threading, restructuring memory, adding multi-material — each landed with the proof that the default output did not move. It also caught the class of bug that a port produces most: a feature that changes behavior by existing. Multi-material had to keep producing pre-feature output under three conditions (no painted facets, no per-extruder arrays, support filament 0), and it does so by omission — the parameter derivation leaves those keys out of the object entirely rather than filling in defaults, because the schema default and the kernel default genuinely disagree for several keys. Filling one in would silently reslice every existing caller's model.
Resin (mSLA) came later, as a second technology rather than a variant, with the support point generator, support tree and pad ported verbatim from PrusaSlicer 2.9.6.
Parts of that chain are not ported yet — hollowing and drain holes, organic support trees. Those return a typed refusal code, checked both at the entry gate and at the request layer. The temptation in a port is always to answer approximately: slice it solid and call it hollow, emit a scene lifted by the elevation when the pad failed to generate. Both produce a file that looks right and prints wrong, which is worse than an error, because an error is discovered in a second and a bad print is discovered in nine hours.
parallel_for is a valid parallel_for. Threading added afterward, under a
determinism requirement, is debuggable; threading present from the start is a permanent suspect.-O3, SIMD and LTO all cost something and here
two of the three returned nothing or crashed.The result is at slicer.kimgh06.com/slice — open an STL, OBJ, 3MF or STEP file and it slices to G-code in the tab, with nothing uploaded anywhere. The same engine is on npm as three-slicer if you want it in your own app, and the integration demos show four ways to embed it.