kicad monkey v2026.11.30
On This Page (7)

Examples Showcase / fab_virtual_layers

Analytic KiCadFabView & Virtual Fab Layers (34-Part Showcase)

Render copper, 7 hatched interior cutouts, 24 embedded 3D STEP HLR assembly outlines, fitted designators, Pin 1 & polarity markers, diodes/LEDs, passives, pad labels, Gerbers, IPC-2581B, and native vdoc baking on a real KiCad 10 board.

pcbfabvirtual-layersfabsvgvirtual-layersgerberipc-2581vdoc

Output Previews

virtual_cutouts_dark.svg
Open SVG
Analytic KiCadFabView & Virtual Fab Layers (34-Part Showcase)
virtual_diodes_dark.svg
Open SVG
Analytic KiCadFabView & Virtual Fab Layers (34-Part Showcase)
virtual_fab_layers_dark.svg
Open SVG
Analytic KiCadFabView & Virtual Fab Layers (34-Part Showcase)
virtual_pad_labels_dark.svg
Open SVG
Analytic KiCadFabView & Virtual Fab Layers (34-Part Showcase)
virtual_passives_dark.svg
Open SVG
Analytic KiCadFabView & Virtual Fab Layers (34-Part Showcase)
virtual_pin1_dark.svg
Open SVG
Analytic KiCadFabView & Virtual Fab Layers (34-Part Showcase)

Exercise KiCadFabView and the complete virtual fabrication layer suite on virtual_fab_layers.kicad_pcb — a real 92.71 × 56.39 mm KiCad 10 board with 34 footprints, 24 embedded 3D STEP models (kicad-embed://), and 7 interior board cutouts (rectangular, composite/circular, and intersecting slots).

The showcase projects all 24 embedded STEP models via Geometer HLR onto ASSEMBLY_OUTLINES_TOP, fits designators inside each outline, renders Paper and Dark composite and focused virtual-layer SVGs, lowers Gerber X2 / Excellon NC Drill / IPC-2581B from the same view, and verifies idempotent native KiCad User.* baking (vdoc).

What It Shows

  1. Real 3D STEP HLR Assembly Outlines & Fitted Designators: Projects all 24 embedded kicad-embed:// STEP models via AssemblyOutlineLayerOptions and AssemblyDesignatorLayerOptions (cached in-memory with AssemblyHlrCache).
  2. Composite & Focused SVG Rendering (Fab.to_svg): Combines physical copper, drills, board profile, 7 hatched interior cutouts, 3D HLR assembly outlines, and shaded virtual layers (CUTOUTS, PIN1_TOP, DIODES_TOP, CAPACITORS_TOP, INDUCTORS_TOP, RESISTORS_TOP, ASSEMBLY_OUTLINES_TOP, ASSEMBLY_DESIGNATORS_TOP, and PAD_LABELS_TOP) in Paper and Dark themes.
  3. Per-Component Overrides (DiodeOverride, InductorOverride): Configures anode/cathode pads on 3-pin SOT-23 D7, Schottky bar styling on D10, and winding-start dot polarity on L2 without modifying the source .kicad_pcb.
  4. Unified Gerber X2, Excellon NC Drill, and IPC-2581B Lowering: Calls Fab.to_gerbers(), Fab.to_nc_drill(), and Fab.to_ipc2581() from the exact same KiCadFabView.
  5. Idempotent Native KiCad Baking (KiCadPcb.bake_virtual_layers): Writes native KiCad primitives grouped under Virtual_<LAYER_KEY> using BakeVirtualLayersOptions.

Board Inventory

Input

text
examples/fab_virtual_layers/virtual_fab_layers.kicad_pcb

Run

From the repository root:

sh
uv run python examples/fab_virtual_layers/fab_virtual_layers.py

To regenerate the full set of documentation guide SVGs under assets/images/virtual_layers/:

sh
uv run python examples/fab_virtual_layers/render_showcase_svgs.py

Output

text
examples/fab_virtual_layers/output/virtual_fab_layers.svg
examples/fab_virtual_layers/output/virtual_fab_layers_dark.svg
examples/fab_virtual_layers/output/virtual_cutouts.svg
examples/fab_virtual_layers/output/virtual_cutouts_dark.svg
examples/fab_virtual_layers/output/virtual_pin1.svg
examples/fab_virtual_layers/output/virtual_pin1_dark.svg
examples/fab_virtual_layers/output/virtual_diodes.svg
examples/fab_virtual_layers/output/virtual_diodes_dark.svg
examples/fab_virtual_layers/output/virtual_passives.svg
examples/fab_virtual_layers/output/virtual_passives_dark.svg
examples/fab_virtual_layers/output/virtual_pad_labels.svg
examples/fab_virtual_layers/output/virtual_pad_labels_dark.svg

See the full Virtual Fab Layers Guide and Fab & KiCadFabView Guide for every option dataclass and field.

Source Code

examples/fab_virtual_layers/fab_virtual_layers.py
"""Runnable example: KiCadFabView, virtual fab layers, Gerber/Drill/IPC-2581,
and native KiCad User.* layer baking (vdoc) on the 34-component
``virtual_fab_layers.kicad_pcb`` KiCad 10 board (24 embedded 3D STEP models).
"""

from __future__ import annotations

import re
from pathlib import Path

from kicad_monkey import KiCadPcb
from kicad_monkey.fab import (
    AssemblyDesignatorLayerOptions,
    AssemblyOutlineLayerOptions,
    BakeVirtualLayersOptions,
    CapacitorLayerOptions,
    CutoutLayerOptions,
    DiodeLayerOptions,
    DiodeOverride,
    InductorLayerOptions,
    InductorOverride,
    PadLabelLayerOptions,
    Pin1LayerOptions,
    ResistorLayerOptions,
    VirtualLayerOptions,
)


class _MemoryHlrCache:
    """In-memory AssemblyHlrCache so each embedded 3D STEP model is projected once."""

    def __init__(self) -> None:
        self._store: dict[tuple[str, str, tuple[float, ...]], object] = {}

    def load(self, model_hash: str, side: str, pose_signature: tuple[float, ...]) -> object | None:
        return self._store.get((model_hash, side, pose_signature))

    def store(self, model_hash: str, side: str, pose_signature: tuple[float, ...], geometry: object) -> None:
        self._store[(model_hash, side, pose_signature)] = geometry


def _add_canvas_bg(svg_text: str, color: str) -> str:
    match = re.search(r'viewBox="([^"]+)"', svg_text)
    if not match:
        return svg_text
    x, y, w, h = match.group(1).split()
    bg = f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}"/>'
    return svg_text.replace(">\n", f">\n{bg}\n", 1)


def _render_pair(fab, layers: tuple[str, ...], opts: VirtualLayerOptions, out_dir: Path, stem: str) -> None:
    paper = next(
        iter(
            fab.to_svg(
                layers=layers,
                virtual_options=opts,
                layer_colours={"TOP": "#E2E8F0", "PROFILE": "#334155", "DRILLS": "#CBD5E1"},
            ).values()
        )
    ).text
    (out_dir / f"{stem}.svg").write_text(_add_canvas_bg(paper, "#FFFFFF"), encoding="utf-8")

    dark = next(
        iter(
            fab.to_svg(
                layers=layers,
                virtual_options=opts,
                layer_colours={"TOP": "#283546", "PROFILE": "#94A3B8", "DRILLS": "#11161D"},
            ).values()
        )
    ).text
    (out_dir / f"{stem}_dark.svg").write_text(_add_canvas_bg(dark, "#11161D"), encoding="utf-8")


def main() -> None:
    here = Path(__file__).resolve().parent
    pcb = KiCadPcb.from_file(here / "virtual_fab_layers.kicad_pcb")
    fab = pcb.fab()

    opts = VirtualLayerOptions(
        font_mode="stroke",
        stroke_font="sans_serif",
        dnp_mode="crossout",
        hlr_cache=_MemoryHlrCache(),
        cutouts=CutoutLayerOptions(scope="interior", hatch=True, hatch_pitch_mm=1.0),
        pin1=Pin1LayerOptions(style="dot", knockout=False),
        diodes=DiodeLayerOptions(
            color_mode="shaded",
            overrides={
                "D7": DiodeOverride(anode_pad="1", cathode_pad="3", diode_type="normal"),
                "D10": DiodeOverride(diode_type="schottky"),
            },
        ),
        capacitors=CapacitorLayerOptions(visibility_mode="all", color_mode="shaded"),
        inductors=InductorLayerOptions(
            visibility_mode="all",
            color_mode="shaded",
            overrides={"L2": InductorOverride(polarized=True, polarity_pad="1")},
        ),
        resistors=ResistorLayerOptions(style="zigzag", color_mode="shaded"),
        assembly_outlines=AssemblyOutlineLayerOptions(detail="simple"),
        assembly_designators=AssemblyDesignatorLayerOptions(),
        pad_labels=PadLabelLayerOptions(orientation="pad", knockout=False),
    )

    out_dir = here / "output"
    out_dir.mkdir(parents=True, exist_ok=True)

    # 1. Render Paper + Dark SVG pairs (composite + focused virtual layer views)
    views: tuple[tuple[str, tuple[str, ...]], ...] = (
        (
            "virtual_fab_layers",
            (
                "PROFILE",
                "CUTOUTS",
                "TOP",
                "DRILLS",
                "ASSEMBLY_OUTLINES_TOP",
                "ASSEMBLY_DESIGNATORS_TOP",
                "PIN1_TOP",
                "DIODES_TOP",
                "CAPACITORS_TOP",
                "INDUCTORS_TOP",
                "RESISTORS_TOP",
            ),
        ),
        ("virtual_cutouts", ("PROFILE", "CUTOUTS", "DRILLS")),
        ("virtual_pin1", ("PROFILE", "TOP", "DRILLS", "ASSEMBLY_OUTLINES_TOP", "PIN1_TOP")),
        ("virtual_diodes", ("PROFILE", "TOP", "DRILLS", "ASSEMBLY_OUTLINES_TOP", "DIODES_TOP")),
        (
            "virtual_passives",
            ("PROFILE", "TOP", "DRILLS", "ASSEMBLY_OUTLINES_TOP", "CAPACITORS_TOP", "INDUCTORS_TOP", "RESISTORS_TOP"),
        ),
        ("virtual_pad_labels", ("PROFILE", "TOP", "DRILLS", "ASSEMBLY_OUTLINES_TOP", "PAD_LABELS_TOP")),
    )
    for stem, layer_tuple in views:
        _render_pair(fab, layer_tuple, opts, out_dir, stem)

    # 2. Gerber X2 + Excellon NC Drill + IPC-2581B in memory
    gerbers = fab.to_gerbers(
        virtual_layers=("CUTOUTS", "PIN1_TOP", "DIODES_TOP", "ASSEMBLY_OUTLINES_TOP"),
        profile_cutouts=True,
        virtual_options=opts,
    )
    drills = fab.to_nc_drill()
    ipc = fab.to_ipc2581(virtual_layers=("CUTOUTS", "PIN1_TOP"), virtual_options=opts)
    print(f"Gerbers: {len(gerbers)} files | Drills: {len(drills)} files | IPC-2581: {len(ipc)} file")

    # 3. Bake virtual layers onto native KiCad User.* layers (idempotent Virtual_* groups)
    report = pcb.bake_virtual_layers(
        BakeVirtualLayersOptions(
            layers=("CUTOUTS", "PIN1_TOP", "DIODES_TOP", "ASSEMBLY_OUTLINES_TOP"),
            virtual_options=opts,
        )
    )
    print(f"Baked {sum(r.items_written for r in report.layers)} native KiCad primitives")


if __name__ == "__main__":
    main()
kicad-monkey v2026.11.30·Docs updated 2026.12.01 15:43 UTC (fd9b75b)