kicad monkey v2026.11.30
On This Page (17)

Fab & KiCadFabView

Fab and KiCadFabView (along with the pure-Rust kicad-monkey-fab FabViewData engine) are the single canonical PCB fabrication and board-rendering geometry surface in kicad-monkey and kicad-cruncher. Call pcb.fab(...) (or Fab.from_pcb(pcb, ...)) to build a shared Fab context once, then emit Gerber X2/X1, Excellon NC Drill, IPC-2581 Rev B, PCB SVG, Pick and Place CSV, BOM CSV, and AP242/AP214 Micro-STEP — or query the normalized board geometry directly with fab.view(...). The same FabView geometry also backs kcr pcb-svg, kcr toon, and kcr vdoc in both Python and Rust so manufacturing deliverables, baked documentation layers, and visual review SVGs never drift.

Why KiCadFabView Exists

KiCad's Plotter IR is designed for pixel-faithful schematic, symbol, and documentation rendering, whereas manufacturing and board-rendering workflows require exact analytic geometry: closed board profiles and interior cutouts, padstack shapes (circle, rect, oval, roundrect, chamfered_rect, trapezoid, custom), plated and non-plated drill spans, oval/routed slots, tented/untented via mask openings, filled zones, component properties, and net ownership.

KiCadFabView normalizes the board once into whole-nanometre (int), +Y-up canonical geometry and shares that draw stage across every writer and board renderer:

text
                  ┌────────────────────┐
                  │      KiCadPcb      │
                  │  (.kicad_pcb +     │
                  │   variant / props) │
                  └─────────┬──────────┘
                            │  pcb.fab(**context)
                            ▼
                  ┌────────────────────┐
                  │ Shared KiCadFabView│
                  │ (stackup, lands,   │
                  │  strokes, zones,   │
                  │  holes, slots,     │
                  │  profile, 17 virt) │
                  └───┬───┬───┬───┬───┬┘
     ┌────────────────┘   │   │   │   └────────────────────┐
     ▼                    ▼   ▼   ▼                        ▼
to_gerbers()      to_nc_drill() to_ipc2581()         to_svg() / to_layer_svgs()
(Gerber X2/X1     (Excellon     (IPC-2581B           kcr pcb-svg / kcr toon
 + virtual)        + G85 slots)  .cvg XML)           kcr vdoc / to_pnp() /
                                                     to_bom() / to_micro_step()

Key design principles:

  1. Single analytic draw stage: Every writer and board renderer (fab, vdoc, pcb-svg, toon) lowers directly from the same normalized KiCadFabView / FabViewData; no consumer re-parses .kicad_pcb S-expressions or invents divergent mask expansions, pad rotations, or virtual-layer rules.
  2. Shared work: Calling fab.to_gerbers(), fab.to_nc_drill(), fab.to_ipc2581(), fab.to_svg(), and fab.to_micro_step() on one Fab reuses the same normalized view.
  3. In-memory first: Every to_* method (except to_micro_step(path)) returns a FabOutput in memory. Nothing touches disk until you call output.write(directory).
  4. Calibrated against kicad-cli: Copper, solder mask, solder paste, Edge.Cuts board outlines/cutouts, and PTH/NPTH drills + G85 slots are verified by pixel-aligned raster comparison against kicad-cli across both synthetic test fixtures and complex multi-layer boards (up to 12 layers).
  5. Zero native CAD runtime required: Every writer — in both pure Python (kicad-monkey) and pure Rust (kicad-monkey-fab) — runs headlessly without launching KiCad.

Quick Start

python
from kicad_monkey import KiCadPcb
from kicad_monkey.fab import CutoutLayerOptions, VirtualLayerOptions

pcb = KiCadPcb.from_file("board.kicad_pcb")

# Build one shared Fab context
fab = pcb.fab(variant="Proto")

# Emit multiple manufacturing and review outputs from the same draw
gerbers = fab.to_gerbers(
    virtual_layers=("CUTOUTS", "PIN1_TOP", "DIODES_TOP", "ASSEMBLY_OUTLINES_TOP"),
    profile_cutouts=True,
    virtual_options=VirtualLayerOptions(
        cutouts=CutoutLayerOptions(hatch_pitch_mm=1.0, label="CUTOUT"),
    ),
)
drill = fab.to_nc_drill()
ipc = fab.to_ipc2581(virtual_layers=("CUTOUTS", "PIN1_TOP"))
svg = fab.to_svg(layers=("PROFILE", "TOP", "DRILLS", "PIN1_TOP", "DIODES_TOP"))
pnp = fab.to_pnp(units="mm")
bom = fab.to_bom()

# Inspect diagnostics before writing
for diag in gerbers.diagnostics:
    print(diag.severity, diag.code, diag.message)

# Write to disk (raises FileExistsError if a target exists unless overwrite=True)
gerbers.write("out/gerber")
drill.write("out/gerber")
ipc.write("out/ipc2581")
svg.write("out/svg")
pnp.write("out/assembly")
bom.write("out/assembly")

# Pure-Python AP242/AP214 Micro-STEP extrusion
stats = fab.to_micro_step("out/board_micro.step")
print(f"Wrote {stats.solid_count} instanced solids")

Fab.from_pcb(pcb, *, variant=None, stem=None, moment=None) accepts the same keyword-only variant and stem arguments as pcb.fab(*, variant=None, stem=None), plus an optional moment recorded in view.context().

Context Options (pcb.fab(...) / Fab.from_pcb(...))

OptionTypeDefaultMeaning
variantstr | NoneNoneOptional KiCad assembly variant name; marks variant-excluded components as DNP (fitted=False).
stemstr | Noneboard filename stemDefault file name stem shared by all to_* outputs unless overridden per call.
momentdatetime | Nonecurrent UTC time(Keyword-only on Fab.from_pcb(...)) Context timestamp recorded in view.context(); for deterministic Gerber .CreationDate and IPC-2581 history headers, pass creation_date="..." to to_gerbers() / to_ipc2581().

Working With FabOutput And FabFile

Every to_* method returns a FabOutput, a read-only Mapping[str, FabFile] ordered by file name:

python
gerbers = fab.to_gerbers()
print(gerbers.status)  # "written", "partial", or "empty"

for name, file in gerbers.items():
    print(name, file.key, file.role, file.status, file.count, len(file.data))

# Read decoded text directly (UTF-8)
top_copper = gerbers["board.GTL"].text

# Single-file outputs (to_ipc2581, to_pnp, to_bom)
pnp_file = next(iter(fab.to_pnp().values()))
print(pnp_file.name, pnp_file.count)
csv_text = pnp_file.text

# Inspect intentionally skipped layers
for skipped in gerbers.omitted:
    print(skipped.output, skipped.files, skipped.reason)

FabOutput.write(directory, *, overwrite=False) creates directory, checks that no target file exists before writing anything (raising FileExistsError unless overwrite=True), skips status == "unavailable" entries, and returns the written tuple[Path, ...].

Layer Mapping (KiCad ↔ Canonical FabView Keys)

KiCadFabView.layer(key) accepts both canonical FabView layer keys and native KiCad layer names (for example, "F.Cu" and "TOP" return identical FabLayerItems):

KiCad LayerCanonical FabView KeyRoleDefault Gerber Ext
F.CuTOPconductor.GTL
In1.Cu .. InN.CuMID1 .. MIDNconductor.G1 .. .GN
B.CuBOTTOMconductor.GBL
F.Mask / B.MaskTOPSOLDER / BOTTOMSOLDERsolder_mask.GTS / .GBS
F.Paste / B.PasteTOPPASTE / BOTTOMPASTEpaste.GTP / .GBP
F.SilkS / B.SilkSTOPOVERLAY / BOTTOMOVERLAYsilkscreen.GTO / .GBO
Edge.Cuts (board + footprint graphics)PROFILEprofile.GM1 (remap e.g. "PROFILE": "GKO" if also plotting MECHANICAL1)
F.Fab / B.FabMECHANICAL1 / MECHANICAL2mechanical.GM1 / .GM2
F.CrtYd / B.CrtYdMECHANICAL3 / MECHANICAL4mechanical.GM3 / .GM4
User.Drawings (Dwgs.User) / User.Comments (Cmts.User)MECHANICAL5 / MECHANICAL6mechanical.GM5 / .GM6
User.Eco1 (Eco1.User) / User.Eco2 (Eco2.User)MECHANICAL7 / MECHANICAL8mechanical.GM7 / .GM8
F.Adhes / B.Adhes / MarginMECHANICAL9 / MECHANICAL10 / MECHANICAL11mechanical.GM9 / .GM10 / .GM11
User.1 .. User.9MECHANICAL12 .. MECHANICAL20mechanical.GM12 .. .GM20
Virtual layers (all 17 keys)CUTOUTS, PIN1_*, DIODES_*, CAPACITORS_*, INDUCTORS_*, RESISTORS_*, ASSEMBLY_OUTLINES_*, ASSEMBLY_DESIGNATORS_*, PAD_LABELS_*virtual.GCU, .GP1T/.GP1B, .GDT/.GDB, .GCT/.GCB, .GLT/.GLB, .GRT/.GRB, .GAT/.GAB, .GADT/.GADB, .GPLT/.GPLB

Output Guides

Gerber X2/X1 (to_gerbers)

Writes Ucamco Gerber Layer Format Specification 2026.05 files (X2 %TF/%TA attributes enabled by default, 6 decimal places of a millimetre = 1 nm grid, flashed copper pads, closed positive zone regions, and exact Edge.Cuts outline plus interior cutout strokes), along with any requested virtual fab layers.

Key options (GerberOptions from kicad_monkey.fab, contract struct FabGerberOptions in kicad_monkey.fab_view_contracts.generated, plus keyword-only virtual_options):

OptionTypeDefaultMeaning
x2_attributesboolTrueEmit Gerber X2 %TF/%TA attributes (False writes plain Gerber X1).
decimal_digitsint6Millimetre decimal places (0–9; 6 preserves exact whole-nanometre coordinates).
datum"user" | "absolute""user""user" shifts output relative to the board origin; "absolute" uses source coordinates.
offset_nmtuple[int, int](0, 0)Additional (x, y) output offset in nanometres.
stemstrboard stemFile name stem.
same_coordinatesstrauto UUIDShared .SameCoordinates GUID written into every file in the set.
creation_datestrnow (UTC)ISO 8601 timestamp with timezone for .CreationDate.
degenerate_strokes"draw" | "omit""draw"Policy for zero-length strokes supplied directly to the Gerber writer. KiCadFabView (and Rust FabViewData) automatically lowers sub-100 nm (<= 100 nm) KiCad dot segments/lines to filled disk areas (GeomDisk2D) so dot stubs flash cleanly with zero stroke_dot_not_stated warnings.
keepoutboolTrue (API) / False (fab.jsonc)Emit Keep-Out film when present in view.layers() (skipped cleanly when absent on KiCad boards).
profileboolTrueEmit the board profile film (.GM1, stroking outer outline and interior Edge.Cuts cutouts).
pad_mastersboolTrue (API) / False (fab.jsonc)Emit pad master films when present in view.layers() (Altium-origin; skipped cleanly on KiCad boards).
drill_guideboolTrue (API) / False (fab.jsonc)Emit drill guide films when present (Altium-origin; skipped cleanly when absent).
drill_drawingboolTrue (API) / False (fab.jsonc)Emit drill drawing films when present (Altium-origin; skipped cleanly when absent).
mechanical_layersSequence[str] | NoneNone (no mechanical films)None or [] writes no mechanical films; ["used"] writes every non-empty mechanical layer; explicit selectors match layer key or name (e.g. ["MECHANICAL1", "F.Fab"]). When plotting MECHANICAL1 alongside profile=True, override "PROFILE" or "MECHANICAL1" in extensions to avoid a .GM1 filename collision.
extensionsMapping[str, str]{}Dual-key custom extension overrides: keys accept canonical FabView keys ("TOP", "PROFILE", "CUTOUTS") or default extensions ("GTL", "GM1", "GCU"); leading . is stripped.
virtual_layersSequence[str]()Additional virtual layers lowered as monochrome positive Gerber films.
profile_cutoutsboolFalse (API) / True (fab.jsonc)Draw hatched "CUTOUT" callout labels directly on the .GM1 profile film.
virtual_optionsVirtualLayerOptions | NoneNoneShared virtual-layer options controlling fonts, visibility, cutouts, Pin 1, diodes, passives, assembly outlines, designators, and pad labels.
python
from kicad_monkey.fab import CutoutLayerOptions, VirtualLayerOptions

gerbers = fab.to_gerbers(
    x2_attributes=True,
    profile=True,
    mechanical_layers=["used"],
    extensions={
        "PROFILE": "GKO",       # canonical key override
        "GTO": "GTO_SILK",      # default-extension override
        "CUTOUTS": "GCU",       # virtual layer override
    },
    virtual_layers=("CUTOUTS", "PIN1_TOP", "DIODES_TOP", "ASSEMBLY_OUTLINES_TOP"),
    profile_cutouts=True,
    virtual_options=VirtualLayerOptions(
        cutouts=CutoutLayerOptions(hatch_pitch_mm=1.0, label="CUTOUT"),
    ),
)

Manufacturing Accuracy Highlights (KiCadFabView vs kicad-cli)

Excellon NC Drill (to_nc_drill)

Writes unambiguous metric Excellon NC Drill files (FMAT,2, METRIC, explicit decimal-point X{mm:.4f}Y{mm:.4f} coordinates) separated by plating (PTH vs. NPTH) and drill span, with native two-point G85 routed slots for oval and slotted KiCad pads plus optional board-edge rout toolpaths.

Key options (NcDrillOptions from kicad_monkey.fab):

OptionTypeDefaultMeaning
stemstrboard stemOutput file stem.
datum"user" | "absolute""user"Coordinate datum ("user" board origin or "absolute").
offset_nmtuple[int, int](0, 0)Additional (x, y) offset in nanometres.
decimal_digitsint4Millimetre decimal precision (0.0001 mm grid).
board_edge_routboolTrueEmit board-edge rout file when ROUT toolpaths exist.
board_edge_rout_toolint5_080_000Board-edge rout tool diameter in nanometres (5.08 mm default).

Each returned FabFile exposes file.role ("round", "slot", "board_edge_rout"), file.plated (True / False), and file.span.

IPC-2581 Rev B (to_ipc2581)

Writes a single schema-valid IPC-2581 Rev B XML document (<stem>.cvg) containing the board stackup, profile + cutouts, deduplicated padstacks, component packages, nets, BOM items, optional non-electrical document layers, and any requested virtual fab layers emitted as <Layer> + <LayerFeature> records outside <StackupGroup> so the physical stackup remains untouched.

Key options (Ipc2581Options from kicad_monkey.fab, plus keyword-only virtual_options):

OptionTypeDefaultMeaning
stemstrboard stemOutput stem (<stem>.cvg) and root <Step> name.
creation_datestrnow (UTC)ISO 8601 history timestamp with timezone.
degenerate_strokes"draw" | "omit""draw"Handling of zero-length strokes.
outline_arcs"exact" | "altium_chords""exact"Emit true circular arcs on outlines and slots ("altium_chords" tessellates arcs into chord polylines).
negative_standoffs"zero" | "as_saved""zero"Clamp negative component standoffs to 0 for strict schema validity.
document_layersSequence[str]all non-emptyNon-electrical DOCUMENT layers to include ([] omits all).
virtual_layersSequence[str]()Additional virtual layers emitted outside <StackupGroup> (CUTOUTS as DOCUMENT/ALL; sided layers as ASSEMBLY/TOP or BOTTOM).
virtual_optionsVirtualLayerOptions | NoneNoneShared virtual-layer options.

PCB SVG (to_svg, to_layer_svgs)

Draws either one composite board image (<stem>.svg) or one aligned SVG per requested layer (<stem>_<KEY>.svg) in millimetres. Both methods accept physical layers ("PROFILE", "TOP", "BOTTOM", "MID1", "TOPSOLDER", "TOPOVERLAY", "DRILLS") and any of the 17 virtual layers inside layers=(...), painted in either monochrome or shaded mode with contrast halos.

Key options (SvgOptions from kicad_monkey.fab, plus keyword-only virtual_options):

OptionTypeDefaultMeaning
layersSequence[str]all board layersOrdered layer keys (bottom-to-top paint order), including "PROFILE", "DRILLS", and any virtual layer key.
layer_coloursMapping[str, str]{}Override colours by layer key ("#rrggbb").
scalefloat1.0Display pixels per millimetre.
mirrorboolFalseMirror horizontally around frame centre (bottom-side view).
clip_to_outlineboolFalseClip rendered layers to the board profile minus cutouts.
clip_holesboolFalseKnock drill holes out of copper layers.
metadataboolFalseEmit data-kind, data-id, data-net, and data-source attributes on SVG elements.
annotationsSequence[Mapping[str, Any]]()Optional review overlays (e.g. origin_marker).
virtual_optionsVirtualLayerOptions | NoneNoneShared virtual-layer configuration.

Pick & Place (to_pnp) And BOM (to_bom)

Micro-STEP (to_micro_step)

fab.to_micro_step(output_path, options=None) (available in both pure Python and pure Rust kicad-monkey-fab) extrudes the board substrate, cutouts, copper pads, traces, vias, filled zones, drill rings/cuts, and optional virtual layers into a compact, geometry-instanced ISO 10303-21 AP242 / AP214 STEP file with zero OpenCASCADE or external geometry-kernel dependency.

Key options (FabMicroStepOptions from kicad_monkey.fab._fab_micro_step):

OptionTypeDefaultMeaning
layer_keystr"BOTTOM"Target copper layer extruded on the board face ("TOP", "BOTTOM", "MID1", etc.).
schema"ap242" | "ap214""ap242"STEP application protocol header.
origin_mode"board_origin" | "lower_left" | "absolute""board_origin"3D coordinate origin placement.
outline_mode"solid" | "frame" | "none""solid"Extrude board substrate as a solid slab, thin perimeter frame, or omit.
board_thickness_mmfloat | Noneboard stackup thicknessExplicit board thickness override in mm.
copper_thickness_mmfloat0.035Base copper extrusion height in mm (1 oz = 0.035 mm).
drill_mode"none" | "overlay" | "cut""overlay"Omit drills, draw drill collar overlays, or boolean-cut drill holes through the board/copper.
fuseboolFalse2D boolean-union touching copper shapes before extrusion.
highlight_test_pointsboolFalseTint test-point pads in highlight_color for mechanical alignment checks.
virtual_layerstuple[str, ...]()Optional virtual layers extruded above copper at virtual_layer_z_offset_mm.
enable_instancingboolTrueShare repeated pad/via solid definitions via STEP MAPPED_ITEM instances.

Baking Virtual Layers To Native KiCad User.* Layers (vdoc)

pcb.bake_virtual_layers(BakeVirtualLayersOptions(...)) (or bake_virtual_layers_to_pcb(pcb, view, options=None)) writes computed virtual layers back into native KiCad GrLine, GrArc, GrCircle, and GrPoly primitives on safe User.* layers (User.1..User.9, User.Eco1, User.Eco2), grouped under deterministic Virtual_<LAYER_KEY> KiCad groups with occupied-layer collision detection and idempotent clear_baked_virtual_layers(...). See Virtual Fab Layers — Baking to F.Fab / B.Fab / User.* and kcr vdoc.

Custom Lowerings With fab.view()

Request KiCadFabView directly whenever you are building a custom exporter, DFM/DRC checker, or viewer:

python
from kicad_monkey import KiCadPcb
from kicad_monkey.fab import JsonFabView, VirtualLayerOptions

pcb = KiCadPcb.from_file("board.kicad_pcb")
view = pcb.fab().view()

for row in view.layers():
    items = view.layer(row.key)
    lands = items.lands or ()
    strokes = items.strokes or ()
    areas = items.areas or ()
    print(f"{row.key:16s} ({row.role}): {len(lands)} lands, {len(strokes)} strokes, {len(areas)} areas")

# Query any virtual layer with explicit options
pin1 = view.virtual_layer("PIN1_TOP", VirtualLayerOptions())
print(f"PIN1_TOP items: {len(pin1.placed)}")

# Round-trip the entire view as validated kicad_monkey.fab_view.a0 JSON
raw_json = view.to_json()
reloaded = JsonFabView.from_json(raw_json)

Core Query Methods On FabView

QueryReturnsNotes
board()FabBoardBoard name, file identity, user origin (whole nm)
layers() / layer(key)tuple[FabLayer, ...] / FabLayerItemsStackup layer matrix and per-layer lands, strokes, areas, clears, texts, routs (accepts both canonical and KiCad layer names)
virtual_layer(key, options=None)VirtualLayerResultCompute any of the 17 virtual layers with explicit VirtualLayerOptions; call .to_fab_layer_items() for canonical FabLayerItems
holes() / drill_pairs()tuplesPlated & non-plated round holes and routed slots (rout=(start, end)), plus drill spans
profile()FabProfile | NoneClosed outer board outline ring and interior cutouts
components() / placements()tuplesFitted/DNP components, footprint properties (parameters), and pins
bodies() / models()tuplesComponent 3D STEP body poses and decoded model payloads
owners() / padstacks() / packages()tuplesOptional cross-CAD contract tables (inherited empty () on KiCadFabView)
nets()tuple[FabNet, ...]Board nets and net classes
stackup()FabStackupLayer dielectric/copper thickness stackup
bom()tuple[FabBomLine, ...]Grouped BOM lines
to_json()bytesValidated kicad_monkey.fab_view.a0 JSON snapshot

Practical Notes For Python Users

See Also

kicad-monkey v2026.11.30·Docs updated 2026.12.01 15:43 UTC (fd9b75b)