# How the G-code Skill Generates FDM Output for 3D Printing

> Learn how the G-code skill generates FDM output for 3D printing using earthtojake/text-to-cad. Discover slicer backends, validate profiles, convert meshes, and execute slice commands.

- Repository: [earthtojake/text-to-cad](https://github.com/earthtojake/text-to-cad)
- Tags: how-to-guide
- Published: 2026-07-31

---

**The G-code skill in earthtojake/text-to-cad generates FDM output by discovering available slicer backends, validating printer profiles, converting meshes to STL when necessary, executing slice commands via subprocess calls, and validating the resulting G-code against motion bounds and supported commands.**

The `text-to-cad` repository provides a comprehensive workbench for converting textual descriptions into CAD models and manufacturable outputs. The **G-code skill** bridges the gap between mesh geometry and physical fabrication by generating FDM G-code ready for 3D printers through a structured pipeline implemented in Python.

## Backend Discovery and Profile Configuration

The pipeline begins with system discovery and profile validation to ensure the target printer characteristics are properly defined.

### Slicer Backend Detection

Before generating G-code, the skill identifies available slicing engines on the host system. The `discover_backends()` function in [`skills/gcode/scripts/gcode_tool.py`](https://github.com/earthtojake/text-to-cad/blob/main/skills/gcode/scripts/gcode_tool.py) searches for installed executables including `orcaslicer`, `prusa-slicer`, and `curaengine`, while `discover_bambu_studio()` handles detection of Bambu Studio installations. These functions return a list of available backends the system can utilize for FDM output generation.

### Profile Validation

Printer settings are defined via JSON profiles that specify backend selection, native slicer configurations, machine dimensions, and filament temperatures. The `load_profile()` function validates every field through numeric checks, absolute path verification, and motion bound validation before returning a `GCodeProfile` dataclass. This ensures that subsequent slicing operations respect the physical constraints of the target 3D printer.

## Input Inspection and Mesh Conversion

Once the backend is configured, the skill processes incoming geometry files to determine the required conversion steps.

### File Format Detection

The `inspect_input()` function examines file extensions to classify inputs as directly sliceable meshes (`.stl`, `.obj`, `.3mf`) or formats requiring conversion (`.ply`, `.glb`, `.gltf`). It also identifies pre-sliced Bambu `.gcode.3mf` files. Unsupported formats such as STEP, DXF, or robot-description files trigger a `GCodeToolError` with specific remediation hints, preventing invalid processing attempts early in the pipeline.

### Converting Non-STL Meshes

When `inspection.needs_stl_conversion` returns true, the `convert_mesh_to_stl()` function utilizes the `trimesh` library to write a temporary `.converted.stl` file. This conversion step ensures compatibility with traditional slicer backends that expect STL input, allowing the G-code skill to handle modern mesh formats without requiring native support from every slicing engine.

## Slicing Execution Pipeline

With validated profiles and prepared meshes, the system constructs and executes the actual slicing operation.

### Building the Slice Plan

The `build_slice_plan()` function assembles a complete command-line invocation for the chosen backend, incorporating the profile's native settings and filament configurations along with the (potentially converted) mesh path. This plan records conversion details and specifies the expected output path for the generated G-code file, providing a reproducible blueprint of the slicing operation.

### Running the Slicer

Execution occurs through `execute_slice()`, which invokes the slicer via `subprocess.run()` while capturing stdout and stderr streams. The function supports dry-run mode for testing command construction without execution and verifies that the slicer produced the expected `.gcode` file. Upon success, it returns the generated file's size and absolute path, completing the FDM output generation phase.

## G-code Validation and Safety Checks

Post-slice validation ensures the generated instructions are safe and compatible with the target hardware.

### Static Analysis

The `validate_gcode_file()` function performs line-by-line parsing of the generated G-code, checking supported commands and enforcing motion bounds defined in the printer profile. It detects missing extrusion moves, out-of-bounds coordinates, and other potential print failures, emitting results as either JSON or human-readable text. This static validation prevents sending dangerous commands to physical 3D printers.

## Command-Line Interface

The skill exposes its functionality through a unified CLI entry point defined in the `main()` function, which builds an `argparse` parser with four primary sub-commands: `discover`, `inspect`, `slice`, and `validate`. Users invoke these commands to drive any stage of the pipeline directly from the terminal.

```bash

# Discover available slicer backends

python -m skills.gcode.scripts.gcode_tool discover

# Inspect a mesh before slicing

python -m skills.gcode.scripts.gcode_tool inspect --input part.stl --json

# Slice with dry-run to preview the command

python -m skills.gcode.scripts.gcode_tool slice \
  --input part.stl \
  --output part.gcode \
  --profile my_printer_profile.json \
  --dry-run

# Execute the actual slice

python -m skills.gcode.scripts.gcode_tool slice \
  --input part.stl \
  --output part.gcode \
  --profile my_printer_profile.json \
  --execute

# Validate generated G-code

python -m skills.gcode.scripts.gcode_tool validate \
  --gcode part.gcode \
  --profile my_printer_profile.json --json

```

### Programmatic Usage

Developers can integrate the pipeline directly into Python applications:

```python
from pathlib import Path
from skills.gcode.scripts import gcode_tool as g
import argparse

# Load printer profile

profile = g.load_profile(Path("my_profile.json"))

# Inspect input format

inspection = g.inspect_input(Path("gear.glb"))

# Build and execute slice plan

plan = g.build_slice_plan(
    argparse.Namespace(
        input=str(inspection.path),
        output="gear.gcode",
        profile=str(profile.native_config),
        backend="orcaslicer",
        execute=True,
        dry_run=False
    ),
    search_path=None
)
ret_code, result = g.execute_slice(plan)

```

## Summary

- The **G-code skill** discovers available slicer backends (`orcaslicer`, `prusa-slicer`, `curaengine`) through `discover_backends()` before processing begins.
- Input files undergo inspection via `inspect_input()` to determine if conversion is needed, with `trimesh` handling non-STL formats.
- The `build_slice_plan()` and `execute_slice()` functions in [`skills/gcode/scripts/gcode_tool.py`](https://github.com/earthtojake/text-to-cad/blob/main/skills/gcode/scripts/gcode_tool.py) construct and run slicer commands via subprocess calls.
- Generated FDM output passes through `validate_gcode_file()` to enforce motion bounds and verify supported G-code commands.
- Users interact with the system through CLI sub-commands (`discover`, `inspect`, `slice`, `validate`) or direct Python API calls.

## Frequently Asked Questions

### What slicer backends does the G-code skill support?

The skill supports `orcaslicer`, `prusa-slicer`, `curaengine`, and optionally Bambu Studio. The `discover_backends()` function automatically detects installed executables on the host system, while `discover_bambu_studio()` specifically handles Bambu Studio detection.

### Why does the skill convert PLY and GLB files to STL?

Traditional slicer backends typically require STL input. When `inspect_input()` identifies `.ply`, `.glb`, or `.gltf` files, `convert_mesh_to_stl()` uses the `trimesh` library to create temporary STL files, ensuring compatibility with slicers while allowing the skill to accept modern mesh formats.

### How does the validation step protect my 3D printer?

The `validate_gcode_file()` function parses G-code line-by-line to verify that all coordinates remain within the motion bounds defined in the printer profile and that only supported commands are present. This prevents out-of-bounds movements and unrecognized instructions that could damage hardware or ruin prints.

### Can I use the G-code skill programmatically without the CLI?

Yes. The [`gcode_tool.py`](https://github.com/earthtojake/text-to-cad/blob/main/gcode_tool.py) module exposes functions like `load_profile()`, `inspect_input()`, `build_slice_plan()`, and `execute_slice()` that can be imported directly into Python scripts. This allows integration into automated workflows or custom applications without shelling out to the command line.