The G-code coders module provides methods for generating G-code commands for 3D printing. All commands follow the Marlin G-code specification.
The coders module (src/slicer/gcode/coders.coffee) contains all G-code generation methods used by the slicer. These methods generate properly formatted G-code strings that can be sent to Marlin-compatible 3D printers.
Polyslice allows you to configure the decimal precision for G-code output. This can significantly reduce file sizes while maintaining practical printing accuracy.
const slicer = new Polyslice({
coordinatePrecision: 3, // Decimal places for X, Y, Z (default: 3)
extrusionPrecision: 5, // Decimal places for E values (default: 5)
feedratePrecision: 0 // Decimal places for F values (default: 0)
});| Parameter | Default | Resolution | Rationale |
|---|---|---|---|
coordinatePrecision |
3 | 0.001mm (1 micron) | Far exceeds typical printer accuracy (~0.01-0.1mm) |
extrusionPrecision |
5 | 0.00001mm | Balances precision with file size |
feedratePrecision |
0 | 1 mm/min | Integer speeds are adequate for motion control |
Using default precision settings can reduce G-code file sizes by 20-30% compared to unlimited precision:
// Example: Sphere with 16x16 segments
// High precision (10 decimals): 1,336,825 bytes
// Default precision (3/5/0): 981,842 bytes (-26.6%)
// Low precision (2/3/0): 851,836 bytes (-36.3%)You can adjust precision at any time using setter methods:
slicer.setCoordinatePrecision(2); // Lower precision = smaller files
slicer.setExtrusionPrecision(4);
slicer.setFeedratePrecision(1);
// Valid range: 0-10 decimal placesNote: Trailing zeros are automatically removed for cleaner output.
G-code commands are typically accessed through the Polyslice instance:
const Polyslice = require("@jgphilpott/polyslice");
const slicer = new Polyslice({
nozzleTemperature: 200,
bedTemperature: 60,
fanSpeed: 100
});
// Generate G-code commands
let gcode = "";
gcode += slicer.codeAutohome(); // G28 - Home all axes
gcode += slicer.codeNozzleTemperature(200, true); // M109 R200 - Wait for nozzle temp
gcode += slicer.codeBedTemperature(60, true); // M190 R60 - Wait for bed temp
gcode += slicer.codeLinearMovement(10, 10, 0.2, 0.5, 1500); // G1 X10 Y10 Z0.2 E0.5 F1500
console.log(gcode);// Travel move (G0) - no extrusion
slicer.codeLinearMovement(x, y, z, null, feedrate);
// Print move (G1) - with extrusion
slicer.codeLinearMovement(x, y, z, extrude, feedrate, power);Parameters:
x,y,z: Target coordinates (optional)extrude: Extrusion amount in mm (optional, null for travel)feedrate: Feed rate in mm/min (optional)power: Laser power for CNC (optional)
Example:
slicer.codeLinearMovement(50, 50, 0.2, 0.5, 1200);
// Output: G1 X50 Y50 Z0.2 E0.5 F1200slicer.codeArcMovement(direction, x, y, z, extrude, feedrate, power, xOffset, yOffset, radius, circles);Parameters:
direction: "clockwise" (G2) or "counterclockwise" (G3)x,y,z: Target coordinatesextrude,feedrate,power: Movement parametersxOffset,yOffset: Arc center offset (I, J parameters)radius: Arc radius (R parameter, alternative to I/J)circles: Number of full circles (P parameter)
slicer.codeBézierMovement(controlPoints);Parameters:
controlPoints: Array of control point objects with:xOffsetStart,yOffsetStart: Start control point offset (I, J)xOffsetEnd,yOffsetEnd: End control point offset (P, Q)
Marlin Documentation: M104, M109
// Set temperature without waiting (M104)
slicer.codeNozzleTemperature(200, false);
// Output: M104 S200
// Set temperature and wait (M109)
slicer.codeNozzleTemperature(200, true);
// Output: M109 R200Parameters:
temp: Target temperature in Celsius (or null to use slicer setting)wait: Whether to wait for temperature (true = M109, false = M104)index: Tool index for multi-extruder (optional)
Marlin Documentation: M140, M190
// Set temperature without waiting (M140)
slicer.codeBedTemperature(60, false);
// Output: M140 S60
// Set temperature and wait (M190)
slicer.codeBedTemperature(60, true);
// Output: M190 R60Marlin Documentation: M106, M107
// Turn fan on at percentage (M106)
slicer.codeFanSpeed(100); // M106 S255
slicer.codeFanSpeed(50); // M106 S128
// Turn fan off (M107)
slicer.codeFanSpeed(0); // M107Parameters:
speed: Fan speed percentage (0-100)index: Fan index for multi-fan systems (optional)
// Home all axes
slicer.codeAutohome(); // G28
// Home specific axes
slicer.codeAutohome(true, false, true); // G28 X ZParameters:
x,y,z: Home specific axes (optional)skip: Skip if already homed (O parameter)raise: Raise Z after homing (R parameter)leveling: Restore leveling state (L parameter)
// Set current position
slicer.codeSetPosition(0, 0, 0, 0); // G92 X0 Y0 Z0 E0
// Reset extruder position only
slicer.codeSetPosition(null, null, null, 0); // G92 E0// Absolute positioning (G90)
slicer.codePositioningMode(true);
// Relative positioning (G91)
slicer.codePositioningMode(false);// Absolute extrusion (M82)
slicer.codeExtruderMode(true);
// Relative extrusion (M83)
slicer.codeExtruderMode(false);slicer.codeWorkspacePlane("XY"); // G17
slicer.codeWorkspacePlane("XZ"); // G18
slicer.codeWorkspacePlane("YZ"); // G19slicer.codeLengthUnit("millimeters"); // G21
slicer.codeLengthUnit("inches"); // G20slicer.codeTemperatureUnit("celsius"); // M149 C
slicer.codeTemperatureUnit("fahrenheit"); // M149 F
slicer.codeTemperatureUnit("kelvin"); // M149 K// Retract using slicer settings
slicer.codeRetract();
// Retract with custom settings
slicer.codeRetract(5, 45); // 5mm at 45mm/s
// Output: G1 E-5 F2700// Unretract using slicer settings
slicer.codeUnretract();
// Unretract with custom settings
slicer.codeUnretract(5, 45); // 5mm at 45mm/s
// Output: G1 E5 F2700slicer.codeWait(); // M400// Non-interruptible dwell (G4)
slicer.codeDwell(1000, false); // G4 P1000 (1 second)
// Interruptible pause (M0)
slicer.codeDwell(1000, true, "Press button to continue");slicer.codeMessage("Printing layer 1"); // M117 Printing layer 1slicer.codeTone(1000, 500); // M300 P1000 S500 (1 second at 500Hz)// Disable all steppers
slicer.codeDisableSteppers(); // M84
// Disable specific steppers
slicer.codeDisableSteppers(true, true, false, true); // M84 X Y Eslicer.codeShutdown(); // M112slicer.codeInterrupt(); // M108Marlin Documentation: M114, M154
// Single position report (M114)
slicer.codePositionReport(false);
// Auto position reporting (M154)
slicer.codePositionReport(true, 1); // Report every 1 secondMarlin Documentation: M105, M155
// Single temperature report (M105)
slicer.codeTemperatureReport(false);
// Auto temperature reporting (M155)
slicer.codeTemperatureReport(true, 1); // Report every 1 secondslicer.codeFanReport(true, 1); // M123 S1slicer.codeSDReport(true, 1); // M27 S1slicer.codeProgressReport(50, 120); // M73 P50 R120 (50%, 120 min remaining)slicer.codeFirmwareReport(); // M115Generates the initialization sequence before printing:
slicer.codePrePrint();Includes:
- Metadata header comment
- Start heating nozzle and bed (parallel)
- Autohome while heating
- Raise Z to protect bed during heating
- Wait for temperatures
- Set extrusion mode
- Set workspace plane and units
- Print test strip (if enabled)
- Reset extruder position
- Initial retraction
Generates the cleanup sequence after printing:
slicer.codePostPrint();Includes:
- Turn off fan
- Smart wipe nozzle (if enabled, with retraction to prevent stringing)
- Raise Z (with retraction if wipe disabled)
- Present print (home X/Y)
- Turn off heaters
- Disable steppers (except Z)
- Play completion tone (if enabled)
The smart wipe feature (enabled by default) intelligently moves the nozzle away from the print before raising the Z axis, preventing marks or filament threads on the finished part.
Configuration:
const slicer = new Polyslice({
wipeNozzle: true, // Enable/disable wipe (default: true)
smartWipeNozzle: true // Use smart wipe vs simple X+5, Y+5 (default: true)
});
// Or using setters
slicer.setWipeNozzle(true);
slicer.setSmartWipeNozzle(true);How It Works:
When smart wipe is enabled:
- Analyzes the last print position and mesh boundaries
- Calculates the shortest path away from the mesh
- Moves the nozzle beyond the mesh boundary (3mm backoff)
- Retracts filament during the wipe move to prevent oozing
- Raises Z without additional retraction
When smart wipe is disabled (or mesh data unavailable):
- Falls back to simple relative move: X+5, Y+5
- No retraction during wipe
- Retraction happens during Z raise
Example G-code Output:
With smart wipe enabled:
; Smart Wipe Nozzle (with retraction)
G1 X0 Y4.2 E-1 F3000
; Raise Z
G1 Z10 F2400With smart wipe disabled:
; Wipe Nozzle
G0 X5 Y5 F3000
; Retract and Raise Z
G1 Z10 E-2 F2400Benefits:
- Prevents wipe moves that land on flat surfaces of the print
- Reduces stringing by retracting during wipe
- Automatically adapts to different mesh geometries
- Safe fallback when mesh data is unavailable
Generates a comment header with print information:
slicer.codeMetadata();Output example:
; Generated by Polyslice
; Version: 26.1.1
; Timestamp: 2024-01-15T10:30:00.000Z
; Repository: https://github.com/jgphilpott/polyslice
; Printer: Ender3
; Filament: Generic PLA (pla)
; Nozzle Temp: 200°C
; Bed Temp: 60°C
; Layer Height: 0.2mm
; Total Layers: 50
; Filament Length: 209.21mm
; Material Volume: 503.2mm³
; Material Weight: 0.62g
; Estimated Print Time: 00:04:36Print Statistics
The metadata header includes comprehensive print statistics calculated during slicing:
| Field | Description | Notes |
|---|---|---|
| Total Layers | Number of layers in the print | Always included after slicing |
| Filament Length | Total filament consumed (mm) | Calculated from cumulative extrusion |
| Material Volume | Volume of material (mm³) | Calculated using filament diameter |
| Material Weight | Weight of material (grams) | Requires filament density (from Filament config) |
| Estimated Print Time | Total print time (HH:MM:SS) | Includes heating time (~30s nozzle, ~60s bed) |
Print Time Calculation
The estimated print time is calculated by:
- Parsing all movement commands (G0, G1, G2, G3) and calculating distance/speed
- Parsing dwell commands (G4) for explicit delays
- Adding estimated heating times for M109/M190 commands
- Summing all time components
Material Calculations
Material statistics are calculated as follows:
// Filament length = cumulative extrusion (E values)
filamentLength = slicer.totalFilamentLength;
// Volume = π × (diameter/2)² × length
filamentRadius = filamentDiameter / 2;
volume = Math.PI × filamentRadius² × filamentLength;
// Weight = volume (cm³) × density (g/cm³)
weight = (volume / 1000) × filamentDensity;Usage with Filament Configuration
To get accurate material weight, use a Filament configuration:
const Filament = require('@jgphilpott/polyslice/src/config/filament/filament');
const filament = new Filament('GenericPLA'); // Includes density: 1.24 g/cm³
const slicer = new Polyslice({
filament: filament,
metadata: true
});
const gcode = slicer.slice(mesh);
// Metadata will include material weight calculationDisabling Metadata
You can disable metadata generation to reduce G-code file size:
const slicer = new Polyslice({
metadata: false // Disable metadata header completely
});Individual Metadata Field Controls
Each metadata field can be individually enabled or disabled (all default to true):
const slicer = new Polyslice({
metadata: true, // Enable metadata header
// Configuration fields (all default to true)
metadataVersion: false, // Hide version number
metadataTimestamp: false, // Hide timestamp
metadataRepository: false, // Hide repository URL
metadataPrinter: true, // Show printer info
metadataFilament: true, // Show filament info
metadataNozzleTemp: true, // Show nozzle temperature
metadataBedTemp: true, // Show bed temperature
metadataLayerHeight: true, // Show layer height
// Statistics fields (all default to true)
metadataTotalLayers: true, // Show layer count
metadataFilamentLength: true, // Show filament usage
metadataMaterialVolume: true, // Show material volume
metadataMaterialWeight: true, // Show material weight
metadataPrintTime: true // Show estimated time
});Note: The title "Generated by Polyslice" is always included when metadata is enabled, as it serves as a marker for the metadata block.
Example: Minimal Metadata
Create a minimal metadata header with only the essentials:
const slicer = new Polyslice({
metadata: true,
metadataVersion: false,
metadataTimestamp: false,
metadataRepository: false,
metadataPrinter: false,
metadataFilament: false,
metadataNozzleTemp: false,
metadataBedTemp: false,
metadataLayerHeight: false,
metadataTotalLayers: true, // Keep layer count
metadataFilamentLength: true, // Keep filament usage
metadataMaterialVolume: false,
metadataMaterialWeight: false,
metadataPrintTime: true // Keep print time
});
// Produces:
// ; Generated by Polyslice
// ; Total Layers: 50
// ; Filament Length: 209.21mm
// ; Estimated Print Time: 00:04:36Generates a test strip to verify extrusion before printing:
slicer.codeTestStrip(length, width, height);Prints two parallel lines at the front of the build plate to verify filament flow and bed adhesion.
| Command | Description | Parameters |
|---|---|---|
| G0 | Rapid move | X Y Z F |
| G1 | Linear move | X Y Z E F |
| G2 | Clockwise arc | X Y Z E F I J R P |
| G3 | Counter-clockwise arc | X Y Z E F I J R P |
| G4 | Dwell | P (ms) or S (sec) |
| G5 | Bézier curve | I J P Q X Y |
| G17 | XY plane | - |
| G18 | XZ plane | - |
| G19 | YZ plane | - |
| G20 | Inches | - |
| G21 | Millimeters | - |
| G28 | Home | X Y Z O R L |
| G90 | Absolute positioning | - |
| G91 | Relative positioning | - |
| G92 | Set position | X Y Z E |
| M0 | Unconditional stop | - |
| M27 | SD status | S C |
| M73 | Progress | P R |
| M82 | Absolute extrusion | - |
| M83 | Relative extrusion | - |
| M84 | Disable steppers | X Y Z E |
| M104 | Set nozzle temp | S T |
| M105 | Temperature report | T R |
| M106 | Fan on | S P |
| M107 | Fan off | P |
| M108 | Break/resume | - |
| M109 | Wait nozzle temp | R S T |
| M112 | Emergency stop | - |
| M114 | Position report | R D E |
| M115 | Firmware info | - |
| M117 | LCD message | string |
| M123 | Fan report | S |
| M140 | Set bed temp | S |
| M149 | Temperature units | C F K |
| M154 | Auto position report | S |
| M155 | Auto temp report | S |
| M190 | Wait bed temp | R S T |
| M300 | Tone | P S |
| M400 | Wait for moves | - |