fdmguard 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fdmguard/__init__.py +6 -0
- fdmguard/__main__.py +5 -0
- fdmguard/cli.py +286 -0
- fdmguard/geometry.py +137 -0
- fdmguard/holes.py +102 -0
- fdmguard/insertion.py +380 -0
- fdmguard/necks.py +108 -0
- fdmguard/stability.py +147 -0
- fdmguard/strips.py +135 -0
- fdmguard/synthetic.py +175 -0
- fdmguard/tradeoff.py +250 -0
- fdmguard-0.1.0.dist-info/METADATA +339 -0
- fdmguard-0.1.0.dist-info/RECORD +16 -0
- fdmguard-0.1.0.dist-info/WHEEL +4 -0
- fdmguard-0.1.0.dist-info/entry_points.txt +2 -0
- fdmguard-0.1.0.dist-info/licenses/LICENSE +202 -0
fdmguard/__init__.py
ADDED
fdmguard/__main__.py
ADDED
fdmguard/cli.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Command line: ``fdmguard <check> ...`` or ``python -m fdmguard <check> ...``.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 = PASS, 1 = FAIL (or nothing passes), 2 = bad input.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
|
|
15
|
+
EXIT_PASS, EXIT_FAIL, EXIT_USAGE = 0, 1, 2
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _plain(o):
|
|
19
|
+
"""json.dumps default: numpy scalars and arrays to plain Python values."""
|
|
20
|
+
if hasattr(o, "tolist"):
|
|
21
|
+
return o.tolist()
|
|
22
|
+
if hasattr(o, "item"):
|
|
23
|
+
return o.item()
|
|
24
|
+
return str(o)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _vec(text: str) -> list[float]:
|
|
28
|
+
named = {"x": [1, 0, 0], "-x": [-1, 0, 0], "y": [0, 1, 0], "-y": [0, -1, 0], "z": [0, 0, 1], "-z": [0, 0, -1]}
|
|
29
|
+
t = text.strip().lower()
|
|
30
|
+
if t in named:
|
|
31
|
+
return [float(v) for v in named[t]]
|
|
32
|
+
vals = [float(v) for v in t.split(",")]
|
|
33
|
+
if len(vals) != 3:
|
|
34
|
+
raise argparse.ArgumentTypeError("direction is x|-x|y|-y|z|-z or 'dx,dy,dz'")
|
|
35
|
+
return vals
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def cmd_insertion(a) -> int:
|
|
39
|
+
from .geometry import load_mesh
|
|
40
|
+
from .insertion import Box, check_insertion, format_table, to_dict
|
|
41
|
+
|
|
42
|
+
moving = load_mesh(a.moving)
|
|
43
|
+
fixed = {Path(p).stem: load_mesh(p) for p in a.fixed}
|
|
44
|
+
allowed = [Box.parse(b) for b in a.allow]
|
|
45
|
+
r = check_insertion(
|
|
46
|
+
moving,
|
|
47
|
+
fixed,
|
|
48
|
+
a.direction,
|
|
49
|
+
a.travel,
|
|
50
|
+
a.step,
|
|
51
|
+
a.grow,
|
|
52
|
+
allowed,
|
|
53
|
+
a.grow_mode,
|
|
54
|
+
a.max_snap_length,
|
|
55
|
+
not a.no_start_check,
|
|
56
|
+
)
|
|
57
|
+
if a.json:
|
|
58
|
+
print(json.dumps(to_dict(r), indent=2))
|
|
59
|
+
else:
|
|
60
|
+
print(f"insertion: {Path(a.moving).name} -> {', '.join(Path(p).name for p in a.fixed)}")
|
|
61
|
+
print(format_table(r, full=a.full))
|
|
62
|
+
return EXIT_PASS if r.passed else EXIT_FAIL
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def cmd_necks(a) -> int:
|
|
66
|
+
from .geometry import load_mesh
|
|
67
|
+
from .necks import check_necks, format_result
|
|
68
|
+
|
|
69
|
+
worst = EXIT_PASS
|
|
70
|
+
for p in a.meshes:
|
|
71
|
+
r = check_necks(load_mesh(p), a.radius, a.pitch, a.min_chunk)
|
|
72
|
+
if a.json:
|
|
73
|
+
print(json.dumps({"mesh": Path(p).name, "status": r.status, **vars(r)}, indent=2, default=str))
|
|
74
|
+
else:
|
|
75
|
+
print(format_result(r, Path(p).name))
|
|
76
|
+
if not r.passed:
|
|
77
|
+
worst = EXIT_FAIL
|
|
78
|
+
return worst
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def cmd_strips(a) -> int:
|
|
82
|
+
from .geometry import load_mesh
|
|
83
|
+
from .strips import check_strips, format_result
|
|
84
|
+
|
|
85
|
+
worst = EXIT_PASS
|
|
86
|
+
for p in a.meshes:
|
|
87
|
+
r = check_strips(load_mesh(p), a.width, a.layer, a.up, a.band, a.min_region)
|
|
88
|
+
if a.json:
|
|
89
|
+
d = {
|
|
90
|
+
"mesh": Path(p).name,
|
|
91
|
+
"pass": r.passed,
|
|
92
|
+
"thin_fraction": r.thin_fraction,
|
|
93
|
+
"marginal_fraction": r.marginal_fraction,
|
|
94
|
+
"worst": [vars(w) for w in r.worst],
|
|
95
|
+
}
|
|
96
|
+
print(json.dumps(d, indent=2))
|
|
97
|
+
else:
|
|
98
|
+
print(format_result(r, Path(p).name))
|
|
99
|
+
if not r.passed:
|
|
100
|
+
worst = EXIT_FAIL
|
|
101
|
+
return worst
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def cmd_holes(a) -> int:
|
|
105
|
+
from .holes import check_holes, format_holes, recommend, recommend_table
|
|
106
|
+
|
|
107
|
+
if not a.meshes:
|
|
108
|
+
if a.json:
|
|
109
|
+
fits = [a.fit] if a.fit else ["press", "slip", "peg", "screw-clearance", "screw-tap"]
|
|
110
|
+
print(json.dumps({"pin": a.pin, "recommended": {f: round(recommend(a.pin, f), 3) for f in fits}}, indent=2))
|
|
111
|
+
return EXIT_PASS
|
|
112
|
+
print(recommend_table(a.pin))
|
|
113
|
+
if a.fit:
|
|
114
|
+
print(f"\n{a.fit}: draw the hole at {recommend(a.pin, a.fit):.2f} mm")
|
|
115
|
+
return EXIT_PASS
|
|
116
|
+
from .geometry import load_mesh
|
|
117
|
+
|
|
118
|
+
fit = a.fit or "slip"
|
|
119
|
+
worst = EXIT_PASS
|
|
120
|
+
for p in a.meshes:
|
|
121
|
+
need, holes = check_holes(load_mesh(p), a.pin, fit, a.up, a.layer)
|
|
122
|
+
status = "NOTHING_CHECKED" if not holes else ("FAIL" if any(not h.ok for h in holes) else "PASS")
|
|
123
|
+
if a.json:
|
|
124
|
+
d = {
|
|
125
|
+
"mesh": Path(p).name,
|
|
126
|
+
"status": status,
|
|
127
|
+
"pass": status == "PASS",
|
|
128
|
+
"fit": fit,
|
|
129
|
+
"pin": a.pin,
|
|
130
|
+
"need_diameter": need,
|
|
131
|
+
"holes": [vars(h) for h in holes],
|
|
132
|
+
}
|
|
133
|
+
print(json.dumps(d, indent=2, default=_plain))
|
|
134
|
+
else:
|
|
135
|
+
print(format_holes(need, holes, a.pin, fit, Path(p).name))
|
|
136
|
+
if status == "NOTHING_CHECKED":
|
|
137
|
+
print("NOTHING CHECKED: no round holes found along --up. Check --up; this is not a pass.")
|
|
138
|
+
if status != "PASS":
|
|
139
|
+
worst = EXIT_FAIL
|
|
140
|
+
return worst
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cmd_stability(a) -> int:
|
|
144
|
+
from .geometry import load_mesh
|
|
145
|
+
from .stability import check_stability, format_result
|
|
146
|
+
|
|
147
|
+
worst = EXIT_PASS
|
|
148
|
+
for p in a.meshes:
|
|
149
|
+
r = check_stability(load_mesh(p), a.up, a.min_contact, a.max_slenderness, a.warn_slenderness)
|
|
150
|
+
if a.json:
|
|
151
|
+
d = {"mesh": Path(p).name, "pass": r.passed, **vars(r), "first_layer_contact": r.first_layer}
|
|
152
|
+
d["contact"] = {f"{z:g}": v for z, v in r.contact.items()}
|
|
153
|
+
print(json.dumps(d, indent=2, default=_plain))
|
|
154
|
+
else:
|
|
155
|
+
print(format_result(r, Path(p).name))
|
|
156
|
+
if not r.passed:
|
|
157
|
+
worst = EXIT_FAIL
|
|
158
|
+
return worst
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def cmd_tradeoff(a) -> int:
|
|
162
|
+
from .tradeoff import decide, load_options
|
|
163
|
+
|
|
164
|
+
opts, limits, metrics = load_options(a.options)
|
|
165
|
+
d = decide(opts, limits, metrics)
|
|
166
|
+
if a.json:
|
|
167
|
+
out = {
|
|
168
|
+
"pass": d.recommended is not None,
|
|
169
|
+
"recommended": d.recommended.name if d.recommended else None,
|
|
170
|
+
"reason": d.reason,
|
|
171
|
+
"passing": [o.name for o in d.passing],
|
|
172
|
+
"options": [
|
|
173
|
+
{
|
|
174
|
+
"name": o.name,
|
|
175
|
+
"original": o.original,
|
|
176
|
+
"geometry_change": o.geometry_change,
|
|
177
|
+
"extra_hardware": o.extra_hardware,
|
|
178
|
+
"function_gates": o.gate_status(limits),
|
|
179
|
+
"gates": o.gates,
|
|
180
|
+
"metrics": o.metrics,
|
|
181
|
+
"notes": o.gate_notes,
|
|
182
|
+
}
|
|
183
|
+
for o in opts
|
|
184
|
+
],
|
|
185
|
+
"table": d.table,
|
|
186
|
+
}
|
|
187
|
+
print(json.dumps(out, indent=2, default=_plain))
|
|
188
|
+
return EXIT_PASS if d.recommended else EXIT_FAIL
|
|
189
|
+
print(d.table)
|
|
190
|
+
print()
|
|
191
|
+
print("Recommendation: " + (d.recommended.name if d.recommended else "none"))
|
|
192
|
+
print(d.reason)
|
|
193
|
+
return EXIT_PASS if d.recommended else EXIT_FAIL
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
197
|
+
p = argparse.ArgumentParser(
|
|
198
|
+
prog="fdmguard",
|
|
199
|
+
description="Function-first checks for 3D-printed parts. A part that prints well but cannot be assembled has failed.",
|
|
200
|
+
)
|
|
201
|
+
p.add_argument("--version", action="version", version=f"fdmguard {__version__}")
|
|
202
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
203
|
+
|
|
204
|
+
s = sub.add_parser("insertion", help="sweep a moving part along its insertion path into fixed part(s)")
|
|
205
|
+
s.add_argument("moving", help="moving part mesh, in its SEATED pose")
|
|
206
|
+
s.add_argument("fixed", nargs="+", help="fixed part mesh(es)")
|
|
207
|
+
s.add_argument(
|
|
208
|
+
"--direction", "-d", type=_vec, default=[0.0, 0.0, -1.0], help="insertion motion direction (default -z)"
|
|
209
|
+
)
|
|
210
|
+
s.add_argument("--travel", "-t", type=float, default=20.0, help="path length in mm before seated (default 20)")
|
|
211
|
+
s.add_argument("--step", type=float, default=0.25, help="step in mm (default 0.25)")
|
|
212
|
+
s.add_argument("--grow", type=float, default=0.1, help="FDM over-size of the moving part in mm (default 0.1)")
|
|
213
|
+
s.add_argument("--grow-mode", choices=["inplane", "full"], default="inplane")
|
|
214
|
+
s.add_argument(
|
|
215
|
+
"--allow",
|
|
216
|
+
action="append",
|
|
217
|
+
default=[],
|
|
218
|
+
metavar="NAME:X0,Y0,Z0,X1,Y1,Z1",
|
|
219
|
+
help="allowed snap region box (repeatable)",
|
|
220
|
+
)
|
|
221
|
+
s.add_argument("--max-snap-length", type=float, default=12.0, help="longest overlap allowed in a snap region (mm)")
|
|
222
|
+
s.add_argument("--warn-snap-depth", type=float, default=1.0, help="warn when a snap overlap is deeper (mm)")
|
|
223
|
+
s.add_argument(
|
|
224
|
+
"--no-start-check", action="store_true", help="allow a start pose inside a fixed part's bounding box (warns)"
|
|
225
|
+
)
|
|
226
|
+
s.add_argument("--full", action="store_true", help="print every step")
|
|
227
|
+
s.add_argument("--json", action="store_true")
|
|
228
|
+
s.set_defaults(func=cmd_insertion)
|
|
229
|
+
|
|
230
|
+
s = sub.add_parser("necks", help="erosion test for thin necks between regions")
|
|
231
|
+
s.add_argument("meshes", nargs="+")
|
|
232
|
+
s.add_argument("--radius", "-r", type=float, default=0.7, help="erosion radius in mm (default 0.7)")
|
|
233
|
+
s.add_argument("--pitch", type=float, default=0.05, help="voxel size in mm (default 0.05)")
|
|
234
|
+
s.add_argument("--min-chunk", type=float, default=0.5, help="ignore chunks below this volume in mm^3")
|
|
235
|
+
s.add_argument("--json", action="store_true")
|
|
236
|
+
s.set_defaults(func=cmd_necks)
|
|
237
|
+
|
|
238
|
+
s = sub.add_parser("strips", help="per-layer opening test for strips narrower than a width")
|
|
239
|
+
s.add_argument("meshes", nargs="+")
|
|
240
|
+
s.add_argument("--width", "-w", type=float, default=1.6, help="minimum strip width in mm (default 1.6)")
|
|
241
|
+
s.add_argument("--layer", type=float, default=0.2, help="layer height in mm (default 0.2)")
|
|
242
|
+
s.add_argument("--up", default="z", help="build direction axis in the mesh: x, y, z, -x, -y, -z (default z)")
|
|
243
|
+
s.add_argument("--band", type=float, default=0.2, help="marginal band above the width (default 0.2)")
|
|
244
|
+
s.add_argument("--min-region", type=float, default=0.5, help="ignore thin regions below this area in mm^2")
|
|
245
|
+
s.add_argument("--json", action="store_true")
|
|
246
|
+
s.set_defaults(func=cmd_strips)
|
|
247
|
+
|
|
248
|
+
s = sub.add_parser("holes", help="recommend printed hole size; optionally check holes in meshes")
|
|
249
|
+
s.add_argument("meshes", nargs="*")
|
|
250
|
+
s.add_argument("--pin", type=float, required=True, help="nominal pin or screw diameter in mm")
|
|
251
|
+
s.add_argument("--fit", choices=["press", "slip", "peg", "screw-clearance", "screw-tap"])
|
|
252
|
+
s.add_argument("--up", default="z", help="hole axis / build direction (default z)")
|
|
253
|
+
s.add_argument("--layer", type=float, default=0.2)
|
|
254
|
+
s.add_argument("--json", action="store_true")
|
|
255
|
+
s.set_defaults(func=cmd_holes)
|
|
256
|
+
|
|
257
|
+
s = sub.add_parser("stability", help="bed contact and toppling screen for a mesh in print orientation")
|
|
258
|
+
s.add_argument("meshes", nargs="+", help="mesh(es) in PRINT orientation")
|
|
259
|
+
s.add_argument("--up", default="z", help="build direction axis in the mesh (default z)")
|
|
260
|
+
s.add_argument("--min-contact", type=float, default=20.0, help="minimum first-layer contact in mm^2 (default 20)")
|
|
261
|
+
s.add_argument("--max-slenderness", type=float, default=10.0, help="fail above height / contact width (default 10)")
|
|
262
|
+
s.add_argument("--warn-slenderness", type=float, default=5.0, help="warn above height / contact width (default 5)")
|
|
263
|
+
s.add_argument("--json", action="store_true")
|
|
264
|
+
s.set_defaults(func=cmd_stability)
|
|
265
|
+
|
|
266
|
+
s = sub.add_parser("tradeoff", help="compare print options: function gates first, then print metrics")
|
|
267
|
+
s.add_argument("options", help="YAML or JSON options file")
|
|
268
|
+
s.add_argument("--json", action="store_true")
|
|
269
|
+
s.set_defaults(func=cmd_tradeoff)
|
|
270
|
+
return p
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def main(argv: list[str] | None = None) -> int:
|
|
274
|
+
from .geometry import MeshError
|
|
275
|
+
from .tradeoff import TradeoffError
|
|
276
|
+
|
|
277
|
+
args = build_parser().parse_args(argv)
|
|
278
|
+
try:
|
|
279
|
+
return args.func(args)
|
|
280
|
+
except (MeshError, TradeoffError, ValueError, FileNotFoundError, KeyError) as e:
|
|
281
|
+
print(f"fdmguard: error: {e}", file=sys.stderr)
|
|
282
|
+
return EXIT_USAGE
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
if __name__ == "__main__":
|
|
286
|
+
sys.exit(main())
|
fdmguard/geometry.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Mesh loading, Manifold conversion and layer sections.
|
|
2
|
+
|
|
3
|
+
All lengths are millimetres. All volumes are mm^3.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from functools import reduce
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import manifold3d as m3d
|
|
12
|
+
import numpy as np
|
|
13
|
+
import shapely
|
|
14
|
+
from shapely.geometry import MultiPolygon, Polygon
|
|
15
|
+
from shapely.geometry.base import BaseGeometry
|
|
16
|
+
|
|
17
|
+
AXES = {"x": 0, "y": 1, "z": 2}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MeshError(ValueError):
|
|
21
|
+
"""Raised when a mesh cannot be used as a closed solid."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def to_manifold(vertices: np.ndarray, faces: np.ndarray, name: str = "mesh") -> m3d.Manifold:
|
|
25
|
+
"""Convert vertex/face arrays to a Manifold and refuse anything that is not a valid solid.
|
|
26
|
+
|
|
27
|
+
A failed conversion gives an empty Manifold. Every intersection with an empty
|
|
28
|
+
Manifold is zero, so a check would silently PASS. That is why this raises.
|
|
29
|
+
"""
|
|
30
|
+
mesh = m3d.Mesh(
|
|
31
|
+
vert_properties=np.ascontiguousarray(vertices, dtype=np.float32),
|
|
32
|
+
tri_verts=np.ascontiguousarray(faces, dtype=np.uint32),
|
|
33
|
+
)
|
|
34
|
+
solid = m3d.Manifold(mesh)
|
|
35
|
+
check_solid(solid, name)
|
|
36
|
+
return solid
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def check_solid(solid: m3d.Manifold, name: str = "mesh") -> None:
|
|
40
|
+
if solid.status() != m3d.Error.NoError:
|
|
41
|
+
raise MeshError(f"{name}: not a closed manifold solid ({solid.status()})")
|
|
42
|
+
if solid.is_empty() or solid.volume() <= 0:
|
|
43
|
+
raise MeshError(f"{name}: empty or zero-volume solid")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def load_mesh(path: str | Path) -> m3d.Manifold:
|
|
47
|
+
"""Load STL/OBJ/PLY/3MF (anything trimesh reads) as a Manifold."""
|
|
48
|
+
import trimesh
|
|
49
|
+
|
|
50
|
+
path = Path(path)
|
|
51
|
+
if not path.exists():
|
|
52
|
+
raise MeshError(f"{path}: file not found")
|
|
53
|
+
loaded = trimesh.load(path, force="mesh", process=True)
|
|
54
|
+
if not isinstance(loaded, trimesh.Trimesh) or len(loaded.faces) == 0:
|
|
55
|
+
raise MeshError(f"{path.name}: no triangles found")
|
|
56
|
+
loaded.merge_vertices()
|
|
57
|
+
return to_manifold(np.asarray(loaded.vertices), np.asarray(loaded.faces), path.name)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def save_mesh(solid: m3d.Manifold, path: str | Path) -> None:
|
|
61
|
+
import trimesh
|
|
62
|
+
|
|
63
|
+
mesh = solid.to_mesh()
|
|
64
|
+
tm = trimesh.Trimesh(vertices=np.asarray(mesh.vert_properties)[:, :3], faces=np.asarray(mesh.tri_verts))
|
|
65
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
tm.export(path)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def up_axis_transform(solid: m3d.Manifold, up: str) -> m3d.Manifold:
|
|
70
|
+
"""Rotate so that the given axis ('x', 'y', 'z', optionally '-x' etc.) becomes +Z (build direction)."""
|
|
71
|
+
up = up.lower().strip()
|
|
72
|
+
sign = -1.0 if up.startswith("-") else 1.0
|
|
73
|
+
axis = up.lstrip("+-")
|
|
74
|
+
if axis not in AXES:
|
|
75
|
+
raise ValueError(f"up axis must be x, y or z (got {up!r})")
|
|
76
|
+
if axis == "z":
|
|
77
|
+
return solid if sign > 0 else solid.rotate([180.0, 0.0, 0.0])
|
|
78
|
+
if axis == "x":
|
|
79
|
+
return solid.rotate([0.0, -90.0 * sign, 0.0])
|
|
80
|
+
return solid.rotate([90.0 * sign, 0.0, 0.0])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def section(solid: m3d.Manifold, z: float) -> BaseGeometry:
|
|
84
|
+
"""Horizontal cross-section at height z as a shapely (Multi)Polygon.
|
|
85
|
+
|
|
86
|
+
Rings are combined even-odd, which is correct for the non-overlapping
|
|
87
|
+
contours of a valid solid (islands inside holes included).
|
|
88
|
+
"""
|
|
89
|
+
rings = solid.slice(float(z)).to_polygons()
|
|
90
|
+
polys = [Polygon(np.asarray(r)) for r in rings if len(r) >= 3]
|
|
91
|
+
polys = [p if p.is_valid else p.buffer(0) for p in polys]
|
|
92
|
+
if not polys:
|
|
93
|
+
return Polygon()
|
|
94
|
+
return reduce(lambda a, b: a.symmetric_difference(b), polys)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def layer_heights(solid: m3d.Manifold, layer: float) -> np.ndarray:
|
|
98
|
+
"""Mid-layer z values from the bottom of the part, like a slicer."""
|
|
99
|
+
bb = solid.bounding_box()
|
|
100
|
+
zmin, zmax = bb[2], bb[5]
|
|
101
|
+
n = max(1, int(np.floor((zmax - zmin) / layer + 1e-9)))
|
|
102
|
+
return zmin + layer * (np.arange(n) + 0.5)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def polygons_of(geom: BaseGeometry) -> list[Polygon]:
|
|
106
|
+
if geom.is_empty:
|
|
107
|
+
return []
|
|
108
|
+
if isinstance(geom, Polygon):
|
|
109
|
+
return [geom]
|
|
110
|
+
if isinstance(geom, MultiPolygon):
|
|
111
|
+
return list(geom.geoms)
|
|
112
|
+
return [g for g in getattr(geom, "geoms", []) if isinstance(g, Polygon) and not g.is_empty]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def voxelize(solid: m3d.Manifold, pitch: float) -> tuple[np.ndarray, np.ndarray]:
|
|
116
|
+
"""Occupancy grid from layer sections sampled at voxel centres.
|
|
117
|
+
|
|
118
|
+
Returns (grid[z, y, x] bool, origin xyz of voxel (0,0,0) centre). One empty
|
|
119
|
+
voxel border is kept on every side so erosion sees the outside.
|
|
120
|
+
"""
|
|
121
|
+
bb = np.asarray(solid.bounding_box(), dtype=float)
|
|
122
|
+
lo, hi = bb[:3] - pitch, bb[3:] + pitch
|
|
123
|
+
xs = np.arange(lo[0] + pitch / 2, hi[0], pitch)
|
|
124
|
+
ys = np.arange(lo[1] + pitch / 2, hi[1], pitch)
|
|
125
|
+
zs = np.arange(lo[2] + pitch / 2, hi[2], pitch)
|
|
126
|
+
gx, gy = np.meshgrid(xs, ys)
|
|
127
|
+
grid = np.zeros((len(zs), len(ys), len(xs)), dtype=bool)
|
|
128
|
+
for k, z in enumerate(zs):
|
|
129
|
+
sec = section(solid, z)
|
|
130
|
+
if sec.is_empty:
|
|
131
|
+
continue
|
|
132
|
+
grid[k] = shapely.contains_xy(sec, gx, gy)
|
|
133
|
+
return grid, np.array([xs[0], ys[0], zs[0]])
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def manifold_components(solid: m3d.Manifold, min_volume: float = 0.0) -> list[m3d.Manifold]:
|
|
137
|
+
return [p for p in solid.decompose() if p.volume() > min_volume]
|
fdmguard/holes.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Printed hole sizes for pins and screws.
|
|
2
|
+
|
|
3
|
+
FDM holes usually print 0.1-0.3 mm smaller than drawn (vertical holes; the
|
|
4
|
+
exact value depends on printer, material, slicer and hole compensation). The
|
|
5
|
+
table below gives STARTING POINTS for the diameter to draw in CAD. Calibrate
|
|
6
|
+
with your own printer before trusting them for a batch.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
import manifold3d as m3d
|
|
14
|
+
import numpy as np
|
|
15
|
+
from shapely.geometry import Polygon
|
|
16
|
+
|
|
17
|
+
from .geometry import check_solid, layer_heights, polygons_of, section, up_axis_transform
|
|
18
|
+
|
|
19
|
+
# fit type -> (diametral allowance added to the nominal diameter in mm, description)
|
|
20
|
+
FITS: dict[str, tuple[float, str]] = {
|
|
21
|
+
"press": (0.10, "light press: a pin pressed into a printed hole"),
|
|
22
|
+
"slip": (0.35, "slip fit: a metal or filament pin slides in by hand (1.75 mm filament -> 2.10 mm)"),
|
|
23
|
+
"peg": (0.40, "printed peg in printed hole: at least 0.4 mm diametral clearance"),
|
|
24
|
+
"screw-clearance": (0.60, "screw passes freely (M3 -> 3.6 mm)"),
|
|
25
|
+
"screw-tap": (-0.20, "screw cuts its own thread in the plastic (M3 -> 2.8 mm pilot)"),
|
|
26
|
+
}
|
|
27
|
+
TOL = 0.03 # mm; polygonal holes measure slightly under their nominal diameter
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def recommend(nominal: float, fit: str) -> float:
|
|
31
|
+
if fit not in FITS:
|
|
32
|
+
raise ValueError(f"fit must be one of {', '.join(FITS)}")
|
|
33
|
+
return round(nominal + FITS[fit][0], 2)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def recommend_table(nominal: float) -> str:
|
|
37
|
+
lines = [f"| fit | draw hole at (mm) for nominal {nominal:g} mm | meaning |", "|---|---|---|"]
|
|
38
|
+
for fit, (_, desc) in FITS.items():
|
|
39
|
+
lines.append(f"| {fit} | {recommend(nominal, fit):.2f} | {desc} |")
|
|
40
|
+
return "\n".join(lines)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Hole:
|
|
45
|
+
cx: float
|
|
46
|
+
cy: float
|
|
47
|
+
diameter: float # smallest area-equivalent diameter seen over the hole's layers
|
|
48
|
+
z0: float
|
|
49
|
+
z1: float
|
|
50
|
+
ok: bool | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def find_holes(solid: m3d.Manifold, up: str = "z", layer: float = 0.2, circularity: float = 0.9) -> list[Hole]:
|
|
54
|
+
"""Circular holes whose axis is along the up axis, found from layer sections."""
|
|
55
|
+
check_solid(solid)
|
|
56
|
+
part = up_axis_transform(solid, up)
|
|
57
|
+
holes: dict[tuple[int, int], Hole] = {}
|
|
58
|
+
for z in layer_heights(part, layer):
|
|
59
|
+
for poly in polygons_of(section(part, z)):
|
|
60
|
+
for ring in poly.interiors:
|
|
61
|
+
p = Polygon(ring)
|
|
62
|
+
if p.length == 0:
|
|
63
|
+
continue
|
|
64
|
+
circ = 4 * np.pi * p.area / p.length**2
|
|
65
|
+
if circ < circularity:
|
|
66
|
+
continue
|
|
67
|
+
d = 2 * np.sqrt(p.area / np.pi)
|
|
68
|
+
c = p.centroid
|
|
69
|
+
key = (round(c.x * 10), round(c.y * 10))
|
|
70
|
+
h = holes.get(key)
|
|
71
|
+
if h is None:
|
|
72
|
+
holes[key] = Hole(c.x, c.y, d, float(z), float(z))
|
|
73
|
+
else:
|
|
74
|
+
h.diameter = min(h.diameter, d)
|
|
75
|
+
h.z1 = float(z)
|
|
76
|
+
return sorted(holes.values(), key=lambda h: (h.cx, h.cy))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_holes(
|
|
80
|
+
solid: m3d.Manifold, pin: float, fit: str, up: str = "z", layer: float = 0.2
|
|
81
|
+
) -> tuple[float, list[Hole]]:
|
|
82
|
+
need = recommend(pin, fit)
|
|
83
|
+
holes = find_holes(solid, up, layer)
|
|
84
|
+
for h in holes:
|
|
85
|
+
h.ok = h.diameter >= need - TOL
|
|
86
|
+
return need, holes
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def format_holes(need: float, holes: list[Hole], pin: float, fit: str, name: str = "part") -> str:
|
|
90
|
+
lines = [
|
|
91
|
+
f"holes: {name}: pin {pin:g} mm, fit '{fit}' -> draw holes at >= {need:.2f} mm",
|
|
92
|
+
"| hole | centre x,y | measured d (mm) | clearance (mm) | z range | ok |",
|
|
93
|
+
"|---|---|---|---|---|---|",
|
|
94
|
+
]
|
|
95
|
+
for i, h in enumerate(holes):
|
|
96
|
+
lines.append(
|
|
97
|
+
f"| {i} | {h.cx + 0.0:.2f},{h.cy + 0.0:.2f} | {h.diameter:.3f} | {h.diameter - pin:+.3f} | "
|
|
98
|
+
f"{h.z0:.1f}..{h.z1:.1f} | {'yes' if h.ok else 'NO'} |"
|
|
99
|
+
)
|
|
100
|
+
if not holes:
|
|
101
|
+
lines.append("(no circular holes along the up axis)")
|
|
102
|
+
return "\n".join(lines)
|