Slicers: Cura, PrusaSlicer, OrcaSlicer and the slicing algorithm
📍 Where we are: Part III · The Software Stack — Chapter 6 of 16. The machine stack (frame, firmware, electronics) is behind us; now we move up to the software that tells it what to do, starting with the slicer.
Imagine cutting a loaf of bread into very thin slices, then tracing the outline of every slice with a pen and filling the middle with a zig-zag scribble. Hand those drawings, one after another, to a robot that squeezes plastic along every line, and the loaf is rebuilt from the bottom up. A slicer is the program that does the cutting and the drawing, and then writes the robot's instructions (G-code) in the language the firmware understands.
What this chapter covers
We follow a model through a slicer in four steps: cut the mesh into layers, turn each cross-section into closed outlines, fill the outlines with perimeters and infill, and write the result as G-code. Then we look at the open-source slicer family and how it split into forks, the settings that matter most, how to script a slicer, and finish with a short Python program, which we ran, that slices a 20 mm cube from scratch.
From mesh to layers
A slicer's input is usually a triangle mesh, such as an STL file (more on formats in File formats and open data). The surface is a bag of triangles; the slicer needs the solid's cross-section at many heights. A 2003 review of slicing in layered manufacturing already distinguished slicing tessellated models from slicing the original CAD model [1] (a 1994 paper gives an earlier overview of slicing procedures for generating layers from a CAD model [2]), and efficient triangle-mesh slicing has its own research literature (for example a 2017 paper that describes an asymptotically optimal algorithm for slicing a triangle mesh with parallel planes) [3]. For the wider picture, a 2017 survey classifies the geometric algorithms of the whole preparation pipeline, from mesh repair to toolpaths and machine instructions, and lists open problems [4].
The core idea fits in one sentence: for a chosen height z, find every triangle edge that crosses the plane at z, compute the crossing point, and connect the crossing points of each triangle into a short line segment. Do that for all triangles and you have a pile of segments lying in the plane. Because the mesh is a closed surface, the segments chain end to end into closed loops, called contours. The outer contour is the part's outline; contours nested inside it are holes.
Two details cause most of the trouble in practice:
- Heights. Layers are not cut at the layer's top or bottom, because a vertex can sit exactly on that plane and make the crossing test ambiguous. Our code below cuts in the middle of each layer. Real slicers also deal with variable layer heights and with first-layer settings.
- Broken meshes. If the mesh has holes, flipped triangles or self-intersections, the segments do not close into loops. Production slicers repair or tolerate such input; our code simply stops with an error.
From outlines to toolpaths
A contour is not yet something a nozzle can follow. The nozzle deposits a road of finite width, so the slicer must decide where the road's centre should run.
- Perimeters (walls). The outermost road runs half a line width inside the contour, then further walls are offset inward. Offsetting a polygon is a computational geometry problem in its own right; libraries such as Clipper2 provide polygon union, difference and offsetting for this kind of work [5].
- Infill. The space inside the innermost wall is filled with a pattern (lines, grid, gyroid, honeycomb and others), at a chosen density, to save material and time. Infill is also the stage where adjacent layers are made to interlock or not.
- Top and bottom skins. Layers near the top and bottom surface get solid fill so the surface is closed.
- Supports. Overhanging regions are detected by comparing a layer with the one below it, and support structures are generated underneath. Book 2 treats the physics in Orientation, supports and build preparation.
- Ordering. Finally the slicer orders the roads: walls before or after infill, where the seam (the start and end of a closed loop) goes, and how to travel between roads without crossing the outside wall.
A newer example of how this step evolves is variable-width perimeters. Constant-width inward offsets over- or under-fill the middle of thin features; a 2020 paper proposed generating toolpaths whose bead widths adapt to the local thickness, and validated the idea statistically on a set of 3D models and physically on an off-the-shelf FDM printer [6]. Prusa's documentation credits the Cura team with implementing this approach as "Arachne", based on that paper, and says Prusa ported it to PrusaSlicer 2.5.0, where its release notes list it among the headline features [7] [8].
Writing G-code
The last step converts every road to text. A straight move is one line. In Marlin's documentation, G1 queues a linear move; X, Y, Z are target coordinates, E is the extruder position, and F is the feedrate in current units per minute (millimetres per minute by default) [9]. A typical extruding move looks like G1 X50 Y25.3 E22.4 F3000. The extruded length E for each move is computed from the road's width, the layer height and the filament diameter, so that the volume of filament pushed in matches the volume of the deposited road.
The open-source slicer family
A slicer turns a mesh into layers, outlines, toolpaths and G-code (top); the major open-source slicers form two main lineages (bottom).
Original diagram by the authors, created with AI assistance.
| Slicer | Licence (as stated in its repository) | Lineage and notes |
|---|---|---|
| Slic3r | open source (Bambu Studio's repository describes it as AGPL-3.0) | Started in 2011 within the RepRap community; created by Alessandro Ranellucci [10]; RepRap itself, a freely distributed replicating rapid prototyper, is described by its originators in [11] |
| PrusaSlicer | AGPL-3.0 | "Originally based on Slic3r"; developed by Prusa Research [12] |
| Bambu Studio | AGPL-3.0 | Descends from PrusaSlicer and Slic3r; its optional network plugin uses non-free libraries [13] |
| OrcaSlicer | AGPL-3.0 | Began by drawing on Bambu Studio, PrusaSlicer and ideas from Cura and SuperSlicer; has a built-in calibration suite [14] |
| Cura | LGPL-3.0 | Python and QML GUI on the Uranium framework [15] |
| CuraEngine | AGPL-3.0 | C++ console application that converts models to G-code; described as a replacement for the older Skeinforge engine [16] |
Two things to notice. First, the Slic3r family is a chain of forks under the same AGPL-3.0 licence, which requires derived software to be released under the same terms [14]. Second, Cura separates the user interface from the slicing engine, so the engine can be run from the command line or embedded in other programs [16].
Settings that matter
Reviews of FDM research examine which process parameters significantly affect part quality and how to optimise them [17]; the table lists the ones a slicer exposes.
| Setting | What it controls | Trade-off |
|---|---|---|
| Layer height | Thickness of each layer | Smaller gives smoother surfaces but many more layers and a longer print |
| Line (extrusion) width | Width of each road | Often set near the nozzle diameter; the slicer uses it to compute E |
| Wall count | Number of perimeters | More walls add strength and cost time |
| Infill density and pattern | Fill inside the walls | Higher density adds weight and time |
| Print speed and acceleration | How fast roads are laid down | Limited by the hotend's melt rate and by the firmware |
| Temperatures | Nozzle and bed | Set by the filament; see Firmware for how the firmware holds them |
| Supports | Structures under overhangs | Trade support removal and surface quality against printability |
| Seam position | Where loops start and stop | Visible as a line on the surface |
Slicers such as OrcaSlicer ship calibration prints for temperature, flow ratio, pressure advance, retraction and volumetric speed [18]. Pressure advance compensates for the elasticity of the filament path: Marlin's version, Linear Advance, is switched on in firmware and given a K factor with M900 Kxx; the documentation describes K as the filament compression needed per 1 mm/s of extrusion speed and says the value comes from a calibration pattern and typically differs between direct-drive and Bowden setups [19]. Treat the output of such calibrations as measurement of your printer and material, not as universal numbers.
Scripting and post-processing
Slicers are programmable at the edges, which is where open-source tooling pays off. In PrusaSlicer, the Output options page has a "Post-processing scripts" setting; each script receives the path of a temporary G-code file as its last argument and edits it in place, and the environment carries values such as SLIC3R_PP_HOST and SLIC3R_PP_OUTPUT_NAME [20]. Cura's repository contains a post-processing plugin with a Python Script base class [21]; I confirmed the files exist but did not run a Cura script for this chapter. Typical uses are inserting a pause at a given layer, stamping a print time into the filename, or rewriting commands for a firmware dialect.
A runnable slicer in under 100 lines
The program below uses only the Python standard library. It builds a 20 mm cube as 12 triangles, cuts it at the middle of each 0.2 mm layer, chains the segments into loops, checks the loop area, then writes one outline plus sparse horizontal infill for each layer. It is an illustration, not a slicer: no wall inset, retraction, travel optimisation, supports, cooling or top and bottom skins.
import math
SIZE, LAYER_H, LINE_W, FIL_D = 20.0, 0.2, 0.4, 1.75
SPACING = 2.0 # infill line spacing in mm
def cube_mesh(s):
v = [(x, y, z) for z in (0, s) for y in (0, s) for x in (0, s)]
quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
tris = []
for a, b, c, d in quads:
tris += [(v[a], v[b], v[c]), (v[a], v[c], v[d])]
return tris
def slice_triangle(tri, z):
"""Return the segment where plane Z=z cuts the triangle, or None."""
pts = []
for p, q in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
if (p[2] - z) * (q[2] - z) < 0: # edge strictly crosses the plane
t = (z - p[2]) / (q[2] - p[2])
pts.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
return tuple(pts) if len(pts) == 2 else None
def chain(segments):
"""Join unordered segments into closed loops by matching rounded endpoints."""
key = lambda p: (round(p[0], 6), round(p[1], 6))
ends = {}
for i, (a, b) in enumerate(segments):
ends.setdefault(key(a), []).append(i)
ends.setdefault(key(b), []).append(i)
used, loops = set(), []
for i in range(len(segments)):
if i in used:
continue
used.add(i)
a, b = segments[i]
loop = [a, b]
while key(loop[-1]) != key(loop[0]):
nxt = [j for j in ends[key(loop[-1])] if j not in used]
if not nxt:
raise ValueError("open contour: mesh is not watertight at this height")
j = nxt[0]
used.add(j)
p, q = segments[j]
loop.append(q if key(p) == key(loop[-1]) else p)
loops.append(loop[:-1])
return loops
def area(loop):
return 0.5 * sum(loop[i][0] * loop[(i + 1) % len(loop)][1] - loop[(i + 1) % len(loop)][0] * loop[i][1]
for i in range(len(loop)))
def infill_lines(loops, y0, y1, spacing):
"""Horizontal scanlines clipped to the polygon with the even-odd rule."""
lines, y, flip = [], y0 + spacing / 2, False
while y < y1:
xs = []
for lp in loops:
for i in range(len(lp)):
(ax, ay), (bx, by) = lp[i], lp[(i + 1) % len(lp)]
if (ay <= y < by) or (by <= y < ay):
xs.append(ax + (y - ay) / (by - ay) * (bx - ax))
xs.sort()
for k in range(0, len(xs) - 1, 2):
seg = (xs[k] + LINE_W, xs[k + 1] - LINE_W) # stay clear of the wall
if seg[0] < seg[1]:
lines.append(((seg[1], y), (seg[0], y)) if flip else ((seg[0], y), (seg[1], y)))
flip = not flip
y += spacing
return lines
def main():
tris = cube_mesh(SIZE)
k_e = LAYER_H * LINE_W / (math.pi * (FIL_D / 2) ** 2) # mm filament per mm of path
out, e, n_layers = ["G21", "G90", "M82", "G92 E0"], 0.0, round(SIZE / LAYER_H)
for n in range(n_layers):
z_cut = (n + 0.5) * LAYER_H # mid-layer: no vertex lies on the plane
segs = [s for t in tris if (s := slice_triangle(t, z_cut))]
loops = chain(segs)
assert len(loops) == 1 and abs(abs(area(loops[0])) - SIZE ** 2) < 1e-6
z = (n + 1) * LAYER_H
out.append(f"; layer {n} z={z:.2f}")
paths = [lp + [lp[0]] for lp in loops] + [[a, b] for a, b in infill_lines(loops, 0, SIZE, SPACING)]
for path in paths:
out.append(f"G0 X{path[0][0]:.3f} Y{path[0][1]:.3f} Z{z:.2f} F6000")
for p, q in zip(path, path[1:]):
e += math.dist(p, q) * k_e
out.append(f"G1 X{q[0]:.3f} Y{q[1]:.3f} E{e:.4f} F1800")
open("cube.gcode", "w").write("\n".join(out) + "\n")
print(f"{n_layers} layers, {len(out)} G-code lines, {e:.1f} mm of filament")
main()
Run status: executed with Python 3.14 (standard library only). It printed 100 layers, 3004 G-code lines, 904.7 mm of filament; the assertion that each layer is one loop of area 400 mm² passed on all 100 layers. The G-code was not run on a printer or in a G-code viewer. Read the program in four parts: slice_triangle is the plane-crossing test, chain builds loops, infill_lines is a scanline fill, and main converts each path to G0 (travel) and G1 (extruding) moves.
Try changing SPACING, or replace cube_mesh with a mesh read from an ASCII STL and see which models raise the open-contour error.
Why it matters
The slicer is where a design becomes a physical result, and in the open ecosystem it is the part you can read, fork and script. Understanding the algorithm explains why a thin wall disappears, why a seam shows, and why a broken mesh fails.
In the real world
Most desktop-printer users pick one of the Slic3r-lineage slicers or Cura, and the forks differ more in defaults, calibration tools and printer integration than in the core idea. When something prints badly, ask three questions in order: is the mesh closed, are the settings sensible for this material, and does the G-code match what the firmware expects?
Key terms
- Slicer — software that converts a 3D model into layers and then into G-code toolpaths.
- Contour — a closed outline produced where the slicing plane cuts the mesh; holes are inner contours.
- Perimeter (wall) — a road that follows the contour, offset inward by half a line width or more.
- Infill — the pattern that fills the interior of a part at a chosen density.
- Seam — the point where a closed loop starts and ends, often visible on the surface.
- Watertight mesh — a closed surface with no holes or gaps, needed for reliable slicing.
- G-code — the text instruction language (for example
G1 X50 Y25.3 E22.4 F3000) that firmware executes. - Post-processing script — a program a slicer runs on the finished G-code to modify it.
- Fork — a copy of a project that continues independently under its licence.
Where this leads
Slicers consume a model; the next chapter shows how to make one in code. Continue with Open CAD and code-driven design.