Metadata-Version: 2.5
Name: fdmguard
Version: 0.2.0
Summary: Function-first checks for 3D-printed parts: insertion-path sweep, thin necks, thin strips, hole fits, bed-contact stability, and an option trade-off table.
Project-URL: Homepage, https://github.com/SamKo88927/fdmguard
Project-URL: Documentation, https://github.com/SamKo88927/fdmguard/blob/main/docs/DESIGN.md
Project-URL: Issues, https://github.com/SamKo88927/fdmguard/issues
Project-URL: Changelog, https://github.com/SamKo88927/fdmguard/blob/main/CHANGELOG.md
Author: Sam Ko
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: 3d-printing,agents,assembly,claude-code,dfm,fdm,interference,manifold
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Manufacturing
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.10
Requires-Dist: manifold3d>=3.0
Requires-Dist: numpy>=1.24
Requires-Dist: pyyaml>=6.0
Requires-Dist: scipy>=1.10
Requires-Dist: shapely>=2.0
Requires-Dist: trimesh>=4.0
Description-Content-Type: text/markdown

# fdmguard

**A part that prints beautifully but cannot be assembled (or falls over mid-print) is a failed part. Function first, print quality second.**

Judge every print choice by **function first** (does it assemble, stay on the
bed while printing, move, hold, survive handling) and only then by **print quality** (supports, flat faces,
hole roundness). Every print choice (orientation, splitting into pieces,
adding joints) is a trade-off. Always include *"keep the original author's
geometry unchanged"* as an option, compare all options in one table, and let a
human decide.

fdmguard is a small Python CLI/library plus a [Claude Code skill](https://github.com/SamKo88927/fdmguard/blob/main/skills/fdmguard/SKILL.md).
It stops an AI agent (or a person) from "optimising a 3D-printed part for
printability" in ways that break the assembly.

> Status: alpha. All examples and figures use **synthetic geometry generated in
> code**. The tolerances are **starting points** for FDM PLA, not measurements of
> your printer. Nothing here simulates printing.

## Where this comes from

These four failures happened while adapting an open-source hobby robot for FDM
PLA printing. Each one passed the checks that were being used at the time.

| # | What went wrong | What catches it | Fix |
|---|---|---|---|
| 1 | Filament-pin holes drawn at 1.85-1.9 mm for 1.75 mm filament. FDM holes print 0.1-0.3 mm small; the pins did not go in. | `holes` | draw slip-fit pin holes at 2.1 mm; at least 0.4 mm diametral clearance for printed peg-in-hole |
| 2 | A horizontal split left two regions joined only by a flat strip about 0.5 mm thick and 0.9 mm wide. It snapped in handling. | `necks` (0.7 mm erosion splits it into 2 chunks) | keep every joining section at least about 1.6 mm |
| 3 | A flat 1.76 mm plate: 51% of its area was 1.6-1.8 mm wide strips, 13% narrower than 1.6 mm, plus a free 12 mm arm. A thickness/erosion check missed it. | `strips` (per-layer 2D opening) | widen strips; report the marginal band too |
| 4 | **The main one.** To print a one-piece part flat with no supports, it was split in two halves joined by an added keel with screws. The mating pocket was carved only around the **seated** pose (+0.3 mm). The seated pose had zero overlap, every check passed, and the halves printed clean. But moving the part into the pocket along its insertion path hit a 20-24 mm long, 0.4-0.7 mm undercut rim. It could not be assembled, and forcing it breaks PLA. The original one-piece design dropped in cleanly except for two small intentional snap tabs. | `insertion` | sweep the moving part along its path (grown about 0.1 mm for FDM, 0.25 mm steps). Every step must show zero overlap except named, small snap regions. Cut pockets with the swept volume. |

Also from failure 4: the original design had zero clearance on two seat faces.
Seated pockets need about +0.2-0.25 mm per side for FDM.

A fifth failure came later: a 54 mm tall one-piece part was oriented
"diagonally" because that orientation had the least support (2.8%). Its
first-layer bed contact was only 0.5 mm², so it would likely topple or detach.
The same part standing on a face had 127 mm² of contact, a rounder bearing bore
(axis vertical) and 21.5% support, and that was the right choice. `stability`
catches this.

![Overlap vs insertion step](https://raw.githubusercontent.com/SamKo88927/fdmguard/main/docs/insertion_sweep.png)

*Synthetic block-into-pocket pair. The seated-only pocket has 0 mm³ overlap at
the seated pose, so a seated check passes, but the 22 mm rim interferes over
13 mm of travel. The pocket cut by the swept volume has 0 overlap at every
step. The 8 mm snap tab overlaps only inside its declared allowed region.*

## Install

[![PyPI](https://img.shields.io/pypi/v/fdmguard)](https://pypi.org/project/fdmguard/) [![CI](https://github.com/SamKo88927/fdmguard/actions/workflows/ci.yml/badge.svg)](https://github.com/SamKo88927/fdmguard/actions/workflows/ci.yml)

```sh
pip install fdmguard        # or: uv tool install fdmguard
fdmguard --help
uvx fdmguard --help         # run without installing
```

From a checkout (development): `uv sync`, then `uv run fdmguard --help`.

Python >= 3.10. Dependencies: manifold3d, trimesh, numpy, shapely, scipy, pyyaml.

## Checks

Exit codes for every command: `0` PASS, `1` FAIL, `2` bad input (missing file,
open or empty mesh). A bad input is never reported as a pass. Every command
also accepts `--json`: one JSON document per call, with the same decision as
the exit code (format: [docs/JSON.md](https://github.com/SamKo88927/fdmguard/blob/main/docs/JSON.md)).

### `insertion`: sweep the real assembly path

```sh
fdmguard insertion moving_seated.stl fixed.stl [more_fixed.stl ...] \
    --direction=-z --travel 20 --step 0.25 --grow 0.1 \
    [--allow tab:x0,y0,z0,x1,y1,z1] [--max-snap-length 12] [--full] [--json]
```

- The moving mesh is in its **seated** pose. `--direction` is the motion
  direction during assembly (`x|-x|y|-y|z|-z` or `dx,dy,dz`; write `--direction=-z`
  so the minus sign is not read as an option). The part starts at
  `seated - direction * travel` and moves to seated in `--step` steps; the exact
  seated pose is always the last step.
- `--grow` models FDM over-size. Default mode `inplane` is the union of the part
  translated by `grow` in 8 directions perpendicular to travel, so the seat stop
  face is not grown. `--grow-mode full` is a true Minkowski sum with a small
  octahedron (experimental: it also grows the stop face, so a seated part
  resting on a floor will report contact).
- Overlap volume is computed per fixed part with exact mesh booleans
  (manifold3d) and split into *outside* and *inside* allowed snap regions.
- **PASS** needs: (a) the start pose outside every fixed part's bounding box,
  (b) zero overlap outside allowed regions at every step (1e-3 mm³ noise floor),
  and (c) the overlap inside each allowed region no longer than
  `--max-snap-length` (12 mm) in the plane perpendicular to travel. Length is
  measured per connected piece of overlap, so a long rigid rim still fails
  inside one big "allowed" box or several small tiled boxes. There is no depth
  limit; a warning is printed when the overlap is deeper than
  `--warn-snap-depth` (1.0 mm).
- The seated-pose-only result is printed next to the path result.

Real output on the synthetic pair (bad pocket, then the swept-cut fix; the
first table is shortened by the tool itself, `--full` prints every step):

```text
$ fdmguard insertion examples/out/insert_rim.stl examples/out/socket_seated_only.stl --direction=-z --travel 20
| step | to go (mm) | socket_seated_only overlap | socket_seated_only outside allowed | socket_seated_only in allowed | ok |
|---|---|---|---|---|---|
| 0 | 20.00 | 0.000 | 0.000 | 0.000 | yes |
| 29 | 12.75 | 4.160 | 4.160 | 0.000 | NO |
| 30 | 12.50 | 8.320 | 8.320 | 0.000 | NO |
...
| 78 | 0.50 | 3.328 | 3.328 | 0.000 | NO |
| 80 | 0.00 | 0.000 | 0.000 | 0.000 | yes |

seated-pose-only check : PASS  (outside overlap 0.000 mm^3)
insertion-path sweep   : FAIL  (worst step 52 at 7.00 mm to go, outside overlap 49.920 mm^3; 81 steps of 0.25 mm, grow 0.1 mm)
NOTE: seated pose is clear but the part cannot travel there. Seated-only clearance is not enough.

$ fdmguard insertion examples/out/insert_rim.stl examples/out/socket_swept.stl --direction=-z --travel 20
| step | to go (mm) | socket_swept overlap | socket_swept outside allowed | socket_swept in allowed | ok |
|---|---|---|---|---|---|
| 0 | 20.00 | 0.000 | 0.000 | 0.000 | yes |
| 80 | 0.00 | 0.000 | 0.000 | 0.000 | yes |

seated-pose-only check : PASS  (outside overlap 0.000 mm^3)
insertion-path sweep   : PASS  (no overlap outside allowed regions at any step; 81 steps of 0.25 mm, grow 0.1 mm)
```

Library helper: `fdmguard.insertion.swept_volume(moving, direction, travel)`
returns the union of the moving part over the path. Subtract it (grown a
little) from the fixed part to cut a pocket that admits the real motion.

### `necks`: thin joins left by splitting

```sh
fdmguard necks part.stl [--radius 0.7] [--pitch 0.05]
```

Erodes each body of the solid by `r` on a voxel grid and counts chunks above
0.5 mm³. A body that falls apart into several chunks is joined only by a
section thinner than about `2r` (status `NECK`). A body that vanishes
completely is reported as `THIN`, not as a pass. Parts with more than one body are noted. Accuracy is
about half the voxel pitch (0.025 mm by default).

### `strips`: narrow strips on each printed layer

```sh
fdmguard strips part.stl [--width 1.6] [--layer 0.2] [--up z] [--band 0.2]
```

For each mid-layer section P, computes the opening `(P shrunk by w/2) grown by w/2`
with mitre joins (so square corners are not reported as thin). Material outside
the opening is narrower than `w`. Also reports the marginal band `w .. w+band`,
because a plate can pass at 1.6 mm and still be mostly 1.6-1.8 mm strips.
`--up` sets the build direction in the mesh's axes; results depend on it.

### `holes`: printed hole size for pins and screws

```sh
fdmguard holes --pin 1.75                        # table of recommended sizes
fdmguard holes --pin 1.75 --fit slip part.stl    # also check round holes in a mesh
```

| fit | added to nominal (diametral) | example |
|---|---|---|
| press | +0.10 | |
| slip | +0.35 | 1.75 mm filament pin -> 2.10 mm |
| peg (printed in printed) | +0.40 | |
| screw-clearance | +0.60 | M3 -> 3.6 mm |
| screw-tap (pilot) | -0.20 | M3 -> 2.8 mm |

Mesh checking finds circular holes whose axis is along `--up` from layer
sections (circularity >= 0.9) and flags holes smaller than the recommendation.
If no round hole is found, the result is "nothing checked" (exit 1), not a pass.
Calibrate these values with a test print on your own printer.

### `stability`: printable without toppling

```sh
fdmguard stability part_in_print_orientation.stl [--up z] [--min-contact 20] [--max-slenderness 10]
```

The mesh must be in print orientation. The part is dropped to z = 0, then the
tool reports first-layer bed contact (sections at z = 0.1 / 0.3 / 0.5 mm),
height, contact width (short side of the minimum rotated rectangle around the
first-layer contact), height / contact width, and whether the centre of mass
(uniform density) is over the contact footprint, with a tip angle.

Defaults (conservative, configurable): FAIL if contact < 20 mm², if height /
contact width > 10, or if the centre of mass is not over the footprint. WARN
above height / contact width 5 (add a brim). This is a geometric screen. It does
not model adhesion, nozzle forces, brims, or supports that touch the bed.

Real output on the synthetic 54 mm post with an 8 mm bore:

```text
$ fdmguard stability examples/out/post_on_edge.stl
stability: post_on_edge.stl: up axis z
  height                 : 48.1 mm
  bed contact z=0.1/0.3/0.5 : 3.2 / 9.6 / 16.0 mm^2  (min 20)
  contact width          : 0.20 mm
  height / contact width : 240.4  (warn > 5, fail > 10)
  centre of mass         : z 24.0 mm, over base: NO, tip angle -30.3 deg
  -> FAIL
  FAIL: first-layer contact 3.2 mm^2 < 20 mm^2
  FAIL: height / contact width = 240.4 > 10
  FAIL: centre of mass is not over the contact footprint: the part leans out of its base

$ fdmguard stability examples/out/post_face_down.stl
stability: post_face_down.stl: up axis z
  height                 : 54.0 mm
  bed contact z=0.1/0.3/0.5 : 173.8 / 173.8 / 173.8 mm^2  (min 20)
  contact width          : 14.00 mm
  height / contact width : 3.9  (warn > 5, fail > 10)
  centre of mass         : z 27.0 mm, over base: yes, tip angle 14.5 deg
  -> PASS
```

### `tradeoff`: function gates first, then print metrics

```sh
fdmguard tradeoff options.yaml
```

See [examples/tradeoff_block.yaml](https://github.com/SamKo88927/fdmguard/blob/main/examples/tradeoff_block.yaml). Each option
lists `insertion`, `necks`, `strips`, `stability` (printable without toppling)
as `pass`, `fail`, `unknown`, or a check
spec that fdmguard runs on meshes. It also lists `extra_hardware`,
`geometry_change` (`none|minor|major`) and print metrics (lower is better).

Rules:
1. A gate that is missing or `unknown` is **UNVERIFIED**, never a pass.
2. Only options that pass every gate are ranked on print metrics.
3. The suggestion defaults to the **least-change** passing option. Another
   option replaces it only if it is no worse on function cost (geometry change,
   extra hardware) and at least as good on every print metric and strictly
   better on one.
4. The file must contain an option with `original: true`. If the original
   fails a gate, the output says so.
5. The table is always printed. A human decides.

Real output (the insertion and stability gates marked as checks were run on
meshes; the print metrics in the file are illustrative numbers, not slicer
output). The minimum-support diagonal option is gated out by stability:

```text
| option | insertion | necks | strips | stability | extra hardware | geometry change | function gates | support_pct | hole_error_mm | print_time_min | print rank | suggested |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| original | PASS | PASS | PASS | PASS | 0 | none | PASS | 18 | 0.15 | 95 | 2 | yes |
| reorient (same geometry) | PASS | PASS | PASS | PASS | 0 | none | PASS | 9 | 0.25 | 100 | 1 |  |
| diagonal, min support | PASS | PASS | PASS | FAIL | 0 | none | FAIL | 3 | 0.3 | 105 | - (gated out) |  |
| split + keel, seated-only pocket | FAIL | PASS | PASS | PASS | 2 | major | FAIL | 0 | 0.1 | 80 | - (gated out) |  |
| split + keel, swept pocket | PASS | PASS | UNVERIFIED | PASS | 2 | major | UNVERIFIED | 0 | 0.1 | 82 | - (gated out) |  |

Checks run:
- original: insertion: seated-only PASS, path PASS
- original: stability: PASS (bed contact 344.2 mm^2, height 24.0 mm, height/width 1.8)
- diagonal, min support: stability: FAIL (bed contact 5.1 mm^2, height 26.5 mm, height/width 132.6)
- split + keel, seated-only pocket: insertion: seated-only PASS, path FAIL
- split + keel, swept pocket: insertion: seated-only PASS, path PASS

Recommendation: original
'original' is the least-change option that passes every function gate. Also passing: reorient (same geometry). They change more or are not better on every print metric. This is a suggestion. Show this table to a human and let them decide.
```

## Examples and tests

```sh
sh examples/run_examples.sh      # writes examples/out/*.stl, runs every check, asserts exit codes
uv run python examples/make_figures.py
uv run pytest -q
```

The synthetic cases (`src/fdmguard/synthetic.py`) reproduce each failure and a
fix: pin holes 1.9 vs 2.1 mm; a split part with a 0.5 x 0.9 mm neck vs a
1.6 x 2.0 mm neck; a plate with 1.7 / 1.2 mm strips vs 2.4 mm strips; and the
block-into-pocket pair (seated-only pocket, swept pocket, small snap tab with
and without an allowed region, a long rim inside an "allowed" box, and zero
seat clearance); and a 54 mm post balanced on an edge vs standing on a face.

## Agent skill

The skill ships inside the package:

```sh
fdmguard skill --install ~/.claude/skills     # or your project's .claude/skills
fdmguard skill                                # print SKILL.md
```

It is also in the repository at [skills/fdmguard/SKILL.md](https://github.com/SamKo88927/fdmguard/blob/main/skills/fdmguard/SKILL.md). The skill tells the agent when to run the checks, in which
order, the tolerance defaults, the anti-patterns, and to show the trade-off
table instead of deciding silently.

## Limits

- Straight-line insertion only. Rotations or multi-leg paths need several runs.
- FDM over-size is modelled as a fixed grow. It is not a print or warp simulation.
- Snap regions are axis-aligned boxes in the fixed parts' frame. The tool
  judges a snap by overlap length only; it does not compute stress or flex.
- Strips and holes use horizontal layer sections in the chosen up axis.
- Meshes must be closed manifold solids.

See [docs/DESIGN.md](https://github.com/SamKo88927/fdmguard/blob/main/docs/DESIGN.md) for goals, non-goals, key decisions and the roadmap, and
[docs/PRIOR_ART.md](https://github.com/SamKo88927/fdmguard/blob/main/docs/PRIOR_ART.md) for related tools. The pieces are
known techniques; this project is a small, focused combination of them.

## 繁體中文摘要

**印得漂亮但裝不起來、或印到一半倒掉，就是失敗的零件。先顧能用，再顧印得好。** 先看功能（裝得進去、印的時候不會倒、能動、
夾得住、拿起來不會斷），再看列印品質（支撐、平面、孔圓度）。拆件、換方向、
加接頭都是取捨。比較時一定要包含「維持原作者幾何不變」這個選項，把所有
選項放在同一張表，讓人來決定。

- `insertion`：沿著實際組裝路徑掃描（零件外擴 0.1 mm、每步 0.25 mm），
  只看最終位置的檢查會漏掉路徑上的倒扣。
- `necks`：內縮 0.7 mm 後如果裂成多塊，代表有細頸。
- `strips`：逐層 2D 開運算，找出窄於 1.6 mm 的細條，並回報 1.6–1.8 mm 的邊緣比例。
- `holes`：1.75 mm 線材銷孔畫 2.1 mm；列印件對列印件至少 0.4 mm 直徑間隙。
- `stability`：列印方向的貼床面積與高寬比；只看支撐 % 選「斜放」常常會倒。
- `tradeoff`：功能關卡先過，才比列印指標；預設推薦改動最少的選項。

所有範例都是程式產生的合成幾何，公差只是起始值，請用自己的印表機校正。

## License

Apache-2.0. See [LICENSE](https://github.com/SamKo88927/fdmguard/blob/main/LICENSE).
