brepy 0.1.2__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.
brepy/__init__.py ADDED
File without changes
brepy/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from brepy.cli import main
4
+
5
+ sys.exit(main())
brepy/build.py ADDED
@@ -0,0 +1,149 @@
1
+ """Load a model script and turn its parts into the files they are written to."""
2
+
3
+ import importlib
4
+ import inspect
5
+ import sys
6
+ from collections.abc import Callable, Mapping, Sequence
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any, get_type_hints
10
+
11
+ from build123d import Compound, Shape
12
+
13
+ Shapes = Mapping[str, Shape[Any]]
14
+ Parts = Mapping[str, Shape[Any] | Shapes]
15
+ Files = dict[str, Shapes]
16
+ Builder = Callable[..., Parts]
17
+ PreviewSpec = Callable[[], dict[str, Any]]
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Model:
22
+ name: str
23
+ path: Path
24
+ build: Builder
25
+ preview_spec: PreviewSpec | None
26
+ separate_prints: bool
27
+
28
+
29
+ def module_name(path: Path, root: Path) -> str:
30
+ """The dotted name `path` imports as with `root` on sys.path."""
31
+ try:
32
+ relative = path.relative_to(root)
33
+ except ValueError:
34
+ raise SystemExit(f"brepy: {path} is not under the root {root}") from None
35
+ return ".".join(relative.with_suffix("").parts)
36
+
37
+
38
+ def model_from(path: Path, root: Path) -> Model:
39
+ module = importlib.import_module(module_name(path, root))
40
+ builder = getattr(module, "build", None)
41
+ if not callable(builder):
42
+ raise SystemExit(f"brepy: {path} defines no build()")
43
+ preview_spec = getattr(module, "preview_spec", None)
44
+ separate = bool(getattr(module, "SEPARATE_PRINTS", False))
45
+ return Model(
46
+ path.stem, path, builder, preview_spec if callable(preview_spec) else None, separate
47
+ )
48
+
49
+
50
+ def project_file(file: str | None, root: Path) -> bool:
51
+ """Whether `file` is the project's own source, not something installed under `root`."""
52
+ if not file:
53
+ return False
54
+ path = Path(file).resolve()
55
+ if not path.is_relative_to(root):
56
+ return False
57
+ parts = path.relative_to(root).parts
58
+ return not any(p.startswith(".") or p == "site-packages" for p in parts)
59
+
60
+
61
+ def load_model(path: Path, root: Path) -> Model:
62
+ """Import the script fresh, so a rebuild sees edits to it and to the modules it imports."""
63
+ if str(root) not in sys.path:
64
+ sys.path.insert(0, str(root))
65
+ for name, module in list(sys.modules.items()):
66
+ if name.partition(".")[0] != __package__ and project_file(
67
+ getattr(module, "__file__", None), root
68
+ ):
69
+ del sys.modules[name]
70
+ return model_from(path, root)
71
+
72
+
73
+ def parse_parameters(builder: Builder, assignments: Sequence[str]) -> dict[str, Any]:
74
+ """NAME=VALUE strings converted to the types build() annotates."""
75
+ hints = get_type_hints(builder)
76
+ parameters: dict[str, Any] = {}
77
+ for assignment in assignments:
78
+ name, separator, text = assignment.partition("=")
79
+ if not separator or name not in inspect.signature(builder).parameters:
80
+ raise SystemExit(f"brepy: --param {assignment!r} is not NAME=VALUE for build()")
81
+ kind = hints.get(name, str)
82
+ try:
83
+ parameters[name] = text.lower() in ("1", "true", "yes") if kind is bool else kind(text)
84
+ except ValueError as error:
85
+ raise SystemExit(f"brepy: --param {assignment!r}: {error}") from None
86
+ return parameters
87
+
88
+
89
+ def output_files(parts: Parts, stem: str, separate_prints: bool) -> Files:
90
+ """Each file to write, by stem: one per part and per colour shell, and one with
91
+ every part unless they print separately. A lone plain part is just <stem>."""
92
+ if len(parts) == 1:
93
+ ((name, part),) = parts.items()
94
+ if not isinstance(part, Mapping):
95
+ part.label = name
96
+ return {stem: {name: part}}
97
+ files: Files = {}
98
+ combined: dict[str, Shape[Any]] = {}
99
+ for name, part in parts.items():
100
+ if isinstance(part, Mapping):
101
+ shells = {f"{name}_{shell}": shape for shell, shape in part.items()}
102
+ files |= {f"{stem}_{label}": {label: shape} for label, shape in shells.items()}
103
+ else:
104
+ shells = {name: part}
105
+ for label, shape in shells.items():
106
+ shape.label = label
107
+ files[f"{stem}_{name}"] = shells
108
+ combined |= shells
109
+ if not separate_prints:
110
+ files[stem] = combined
111
+ return files
112
+
113
+
114
+ def build_files(model: Model, parameters: Sequence[str], part: str | None) -> Files:
115
+ """The files the model's parts go to, narrowed to `part`'s when it is given."""
116
+ parts = model.build(**parse_parameters(model.build, parameters))
117
+ files = output_files(parts, model.name, model.separate_prints)
118
+ if part is None:
119
+ return files
120
+ prefix = f"{model.name}_{part}"
121
+ chosen = {k: v for k, v in files.items() if k == prefix or k.startswith(f"{prefix}_")}
122
+ if not chosen:
123
+ raise SystemExit(f"brepy: no part {part!r}; parts are {', '.join(parts)}")
124
+ return chosen
125
+
126
+
127
+ def combine(shapes: Shapes, label: str) -> Shape[Any]:
128
+ """One shape holding every part as a distinct solid, each keeping its part name."""
129
+ if len(shapes) == 1:
130
+ return next(iter(shapes.values()))
131
+ return Compound(children=list(shapes.values()), label=label)
132
+
133
+
134
+ def seat_built(model: Model, files: Files, root: Path) -> Callable[[str], Shape[Any]]:
135
+ """An assembly's stem as a shape: one of these files, or ../<model>/<stem> from the
136
+ sibling script ../<model>/<model>.py, built once."""
137
+ siblings: dict[str, Files] = {}
138
+
139
+ def seat(stem: str) -> Shape[Any]:
140
+ if not stem.startswith("../"):
141
+ return combine(files[stem], stem)
142
+ name, _, sibling_stem = stem[3:].partition("/")
143
+ if name not in siblings:
144
+ path = (model.path.parent.parent / name / f"{name}.py").resolve()
145
+ sibling = model_from(path, root)
146
+ siblings[name] = output_files(sibling.build(), name, sibling.separate_prints)
147
+ return combine(siblings[name][sibling_stem], sibling_stem)
148
+
149
+ return seat
brepy/cli.py ADDED
@@ -0,0 +1,96 @@
1
+ """Build a build123d model script, then export it or preview it.
2
+
3
+ brepy [options] path/to/model.py
4
+
5
+ The script defines build(**parameters) returning {part name: shape}, where a
6
+ shape may instead be {shell name: shape}, the colour shells of one print. Each
7
+ part and shell gets a file, <name>_<part>[_<shell>], named after the script, and
8
+ the parts share one combined <name> file unless the script sets
9
+ SEPARATE_PRINTS = True. Output goes beside the script unless --out-dir says
10
+ otherwise; png writes preview sheets to its previews/ folder.
11
+
12
+ The script is imported by its path relative to --root, the current directory
13
+ by default, so it can import other modules under the root.
14
+
15
+ brepy -f step -f png models/bracket/bracket.py
16
+ brepy --watch models/bracket/bracket.py
17
+ """
18
+
19
+ import argparse
20
+ import sys
21
+ from collections.abc import Sequence
22
+ from pathlib import Path
23
+
24
+ from brepy.build import load_model
25
+ from brepy.export import FORMATS, export
26
+
27
+
28
+ def parser() -> argparse.ArgumentParser:
29
+ p = argparse.ArgumentParser(
30
+ prog="brepy",
31
+ description="Build a build123d model script, then export it or preview it.",
32
+ )
33
+ p.add_argument("model", type=Path, help="model script defining build()")
34
+ p.add_argument(
35
+ "-f",
36
+ "--format",
37
+ action="append",
38
+ choices=FORMATS,
39
+ dest="formats",
40
+ help="export format, repeatable (default: step, unless previewing)",
41
+ )
42
+ p.add_argument("-o", "--out-dir", type=Path, help="output folder (default: the script's)")
43
+ p.add_argument(
44
+ "--root",
45
+ type=Path,
46
+ default=Path.cwd(),
47
+ help="folder the script is imported from (default: the current directory)",
48
+ )
49
+ p.add_argument("--part", help="export only this part")
50
+ p.add_argument(
51
+ "-p",
52
+ "--param",
53
+ action="append",
54
+ default=[],
55
+ dest="parameters",
56
+ metavar="NAME=VALUE",
57
+ help="argument for build(), repeatable",
58
+ )
59
+ p.add_argument(
60
+ "--tolerance",
61
+ type=float,
62
+ default=0.01,
63
+ help="linear mesh tolerance in mm for stl and 3mf (default: 0.01)",
64
+ )
65
+ p.add_argument("--view", action="store_true", help="preview in a viewer window")
66
+ p.add_argument(
67
+ "--watch", action="store_true", help="preview, and rebuild whenever a source file changes"
68
+ )
69
+ p.add_argument("--port", type=int, default=3939, help="viewer port (default: 3939)")
70
+ return p
71
+
72
+
73
+ def main(argv: Sequence[str] | None = None) -> int:
74
+ args = parser().parse_args(argv)
75
+ path = args.model.resolve()
76
+ root = args.root.resolve()
77
+ previewing = args.view or args.watch
78
+ formats = args.formats or ([] if previewing else ["step"])
79
+ if formats:
80
+ out_dir = (args.out_dir or args.model.parent).resolve()
81
+ model = load_model(path, root)
82
+ export(model, root, formats, out_dir, args.parameters, args.part, args.tolerance)
83
+ if previewing:
84
+ try:
85
+ from brepy import viewer
86
+ except ImportError as error:
87
+ raise SystemExit(
88
+ f"brepy: previewing needs the viewer extra, brepy[viewer] ({error})"
89
+ ) from None
90
+ session = viewer.Session(path, root, args.parameters, args.part, args.port)
91
+ viewer.preview(session, args.watch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
brepy/export.py ADDED
@@ -0,0 +1,58 @@
1
+ """Write a model's files in the requested formats, and its preview sheets."""
2
+
3
+ import json
4
+ from collections.abc import Sequence
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from build123d import Mesher, export_brep, export_step, export_stl
9
+
10
+ from brepy import sheets
11
+ from brepy.build import Model, Shapes, build_files, combine, seat_built
12
+
13
+ FORMATS = ("step", "stl", "3mf", "brep", "png")
14
+
15
+
16
+ def write(shapes: Shapes, label: str, path: Path, tolerance: float) -> None:
17
+ match path.suffix:
18
+ case ".step":
19
+ export_step(combine(shapes, label), str(path))
20
+ case ".stl":
21
+ export_stl(combine(shapes, label), str(path), tolerance=tolerance)
22
+ case ".brep":
23
+ export_brep(combine(shapes, label), str(path))
24
+ case ".3mf":
25
+ mesher = Mesher()
26
+ for shape in shapes.values():
27
+ mesher.add_shape(shape, linear_deflection=tolerance)
28
+ mesher.write(str(path))
29
+ case _:
30
+ raise SystemExit(f"brepy: unknown output format {path.suffix}")
31
+ print(f"wrote {path} ({path.stat().st_size} bytes)")
32
+
33
+
34
+ def export(
35
+ model: Model,
36
+ root: Path,
37
+ formats: Sequence[str],
38
+ out_dir: Path,
39
+ parameters: Sequence[str] = (),
40
+ part: str | None = None,
41
+ tolerance: float = 0.01,
42
+ ) -> None:
43
+ files = build_files(model, parameters, part)
44
+ out_dir.mkdir(parents=True, exist_ok=True)
45
+ for fmt in formats:
46
+ if fmt != "png":
47
+ for stem, shapes in files.items():
48
+ write(shapes, stem, out_dir / f"{stem}.{fmt}", tolerance)
49
+ spec: dict[str, Any] = {}
50
+ if model.preview_spec is not None and {"png", "step"} & set(formats):
51
+ spec = model.preview_spec()
52
+ if "png" in formats:
53
+ shapes = {stem: combine(held, stem) for stem, held in files.items()}
54
+ sheets.draw_sheets(shapes, spec, seat_built(model, files, root), out_dir / "previews")
55
+ if spec and "step" in formats:
56
+ path = out_dir / "preview.json"
57
+ path.write_text(json.dumps(spec, indent=2) + "\n")
58
+ print(f"wrote {path}")
brepy/printability.py ADDED
@@ -0,0 +1,95 @@
1
+ """Printability measurements on a built solid, for a given build direction.
2
+
3
+ `build_up` points away from the plate. A face is unsupported where it points
4
+ down past 42 degrees from vertical and is not the layer on the plate, the rule
5
+ the preview sheets shade orange by.
6
+ """
7
+
8
+ from collections.abc import Sequence
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+ from build123d import Compound, Face, Pos, Sketch, Solid, Vector
14
+ from OCP.BRepClass3d import BRepClass3d_SolidClassifier
15
+ from OCP.gp import gp_Pnt
16
+ from OCP.TopAbs import TopAbs_State
17
+
18
+ from brepy import sheets
19
+
20
+ Body = Solid | Compound
21
+
22
+
23
+ def unsupported_triangles(
24
+ shape: Body, build_up: Sequence[float]
25
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
26
+ """Area and centroid of each unsupported triangle. The mesh finds candidates as the
27
+ sheets do; each is then judged by the surface's own normal at its centroid, so a
28
+ sliver facet along a boolean seam cannot read as an overhang."""
29
+ up = sheets.unit(build_up)
30
+ areas, centroids = [], []
31
+ for solid in shape.solids():
32
+ classifier = BRepClass3d_SolidClassifier(solid.wrapped)
33
+ meshes = []
34
+ for face in solid.faces():
35
+ if face.area > sheets.SLIVER_AREA:
36
+ vertices, triangles = face.tessellate(sheets.TESS_TOL)
37
+ meshes.append(
38
+ (
39
+ face,
40
+ np.array([tuple(v) for v in vertices]),
41
+ np.array(triangles, dtype=np.int64),
42
+ )
43
+ )
44
+ floor = min((v @ up).min() for _, v, t in meshes if len(t))
45
+ for face, vertices, triangles in meshes:
46
+ if not len(triangles):
47
+ continue
48
+ down = sheets.plate_ward(vertices, triangles, classifier, up)
49
+ down &= ~sheets.resting_on(vertices, triangles, up, floor)
50
+ for a, b, c in vertices[triangles[down]]:
51
+ centre = (a + b + c) / 3
52
+ if surface_points_down(face, centre, classifier, up):
53
+ areas.append(float(np.linalg.norm(np.cross(b - a, c - a))) / 2)
54
+ centroids.append(centre)
55
+ return np.array(areas), np.array(centroids).reshape(-1, 3)
56
+
57
+
58
+ def surface_points_down(
59
+ face: Face, point: npt.NDArray[np.float64], classifier: Any, up: npt.NDArray[np.float64]
60
+ ) -> bool:
61
+ """Whether the face's outward normal at `point` leans down past the overhang limit."""
62
+ normal = np.array(tuple(face.normal_at(Vector(*point))))
63
+ classifier.Perform(gp_Pnt(*(point + normal * sheets.PROBE_STEP)), 1e-6)
64
+ if classifier.State() == TopAbs_State.TopAbs_IN or classifier.IsOnAFace():
65
+ normal = -normal
66
+ return bool(normal @ up < -sheets.OVERHANG_COS)
67
+
68
+
69
+ def unsupported_area(shape: Body, build_up: Sequence[float]) -> float:
70
+ return float(unsupported_triangles(shape, build_up)[0].sum())
71
+
72
+
73
+ def section(shape: Body, z: float) -> Sketch:
74
+ """The plan section of `shape` at height z, dropped onto z=0."""
75
+ cut = shape & (Pos(0, 0, z) * Face.make_rect(1000, 1000))
76
+ return Pos(0, 0, -z) * Sketch(cut.faces()) if cut is not None else Sketch()
77
+
78
+
79
+ def island_area(shape: Body, layer_height: float, build_up: Sequence[float]) -> float:
80
+ """The largest area printed in some layer with nothing at all under it, walking the
81
+ layers in print order along Z."""
82
+ bounds = shape.bounding_box()
83
+ step = layer_height if build_up[2] > 0 else -layer_height
84
+ z = bounds.min.Z + layer_height / 2 if step > 0 else bounds.max.Z - layer_height / 2
85
+ worst, below = 0.0, None
86
+ while bounds.min.Z < z < bounds.max.Z:
87
+ layer = section(shape, z)
88
+ if below is not None and layer.faces():
89
+ for face in (layer - below).faces():
90
+ if face.distance_to(below) > 1e-6:
91
+ worst = max(worst, face.area)
92
+ if layer.faces():
93
+ below = layer
94
+ z += step
95
+ return worst
brepy/sheets.py ADDED
@@ -0,0 +1,631 @@
1
+ """Preview sheets: six dimensioned views of a part, drawn without a GPU or display.
2
+
3
+ Each solid is tessellated and projected orthographically, filled through a
4
+ z-buffer with flat shading, and overdrawn with its B-rep edges. brepy calls
5
+ draw_sheets() with the shapes it exports and the model's preview_spec():
6
+
7
+ {"parts": {"<stem>": {"build_up": [0, 0, 1],
8
+ "dimensions": [{"label": "pin hole dia", "view": "right",
9
+ "a": [x, y, z], "b": [x, y, z],
10
+ "detail": "<optional zoomed tile>"}]}},
11
+ "assemblies": {"<name>": {"seat": [{"stem": "<stem or ../<model>/<stem>>",
12
+ "at": [0, 0, 0], "build_up": [0, 0, 1]}],
13
+ "dimensions": [...]}}}
14
+
15
+ `build_up` points away from the build plate; faces that print unsupported are
16
+ drawn orange. A dimension draws the distance between its two points, and is
17
+ skipped in a view it is not parallel to.
18
+ """
19
+
20
+ import itertools
21
+ from collections.abc import Callable, Mapping, Sequence
22
+ from pathlib import Path
23
+ from typing import Any, Final
24
+
25
+ import numpy as np
26
+ import numpy.typing as npt
27
+ from build123d import Compound, Pos, Shape, Solid
28
+ from OCP.BRepAdaptor import BRepAdaptor_Curve
29
+ from OCP.BRepClass3d import BRepClass3d_SolidClassifier
30
+ from OCP.GCPnts import GCPnts_QuasiUniformDeflection
31
+ from OCP.gp import gp_Pnt
32
+ from OCP.TopAbs import TopAbs_State
33
+ from PIL import Image, ImageDraw, ImageFont
34
+
35
+ Array = npt.NDArray[np.float64]
36
+ Box2 = tuple[float, float, float, float]
37
+ Dimension = Mapping[str, Any]
38
+ Group = tuple[Array, npt.NDArray[np.int64], npt.NDArray[np.bool_]]
39
+ Projector = Callable[[Any], tuple[Array, Array, Array]]
40
+ Colour = tuple[int, int, int]
41
+ Font = ImageFont.FreeTypeFont | ImageFont.ImageFont
42
+
43
+ SS: Final = 2
44
+ TILE: Final = (960, 720)
45
+ COLS: Final = 2
46
+ MARGIN: Final = 0.06
47
+ TESS_TOL: Final = 0.05
48
+ SLIVER_AREA: Final = 1e-6
49
+
50
+ BG: Final[Colour] = (255, 255, 255)
51
+ INK: Final[Colour] = (40, 44, 48)
52
+ DIM: Final[Colour] = (46, 96, 158)
53
+ BODY: Final[Colour] = (176, 182, 189)
54
+ UNSUPPORTED: Final[Colour] = (214, 122, 92)
55
+
56
+ OVERHANG_COS: Final = float(np.cos(np.radians(42.0)))
57
+ PROBE_STEP: Final = 0.2
58
+
59
+ U: Final = SS * TILE[1] / 360.0
60
+ FONT_PX: Final = int(12 * U)
61
+ LW: Final = max(1, int(U))
62
+ GAP: Final = int(4 * U)
63
+ OVER: Final = int(5 * U)
64
+ OFF: Final = int(18 * U)
65
+ FEAT_OFF: Final = int(14 * U)
66
+ BAND: Final = int(68 * U)
67
+ ARROW_L: Final = int(8 * U)
68
+ ARROW_W: Final = int(3 * U)
69
+ DETAIL_PAD: Final = 3.0
70
+
71
+ VIEWS: Final = (
72
+ ("isometric", (-1.0, 1.0, -1.0), (0.0, 0.0, 1.0)),
73
+ ("underside", (-1.0, 1.0, 1.0), (0.0, 0.0, -1.0)),
74
+ ("front", (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
75
+ ("right", (-1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
76
+ ("top", (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)),
77
+ ("bottom", (0.0, 0.0, 1.0), (0.0, 1.0, 0.0)),
78
+ )
79
+
80
+
81
+ def unit(v: Any) -> Array:
82
+ a = np.asarray(v, dtype=float)
83
+ return a / np.linalg.norm(a)
84
+
85
+
86
+ def basis(direction: Sequence[float], up_hint: Sequence[float]) -> tuple[Array, Array, Array]:
87
+ """Orthonormal camera axes (right, up, forward)."""
88
+ fwd = unit(direction)
89
+ right = np.cross(fwd, unit(up_hint))
90
+ if np.linalg.norm(right) < 1e-9:
91
+ right = np.cross(fwd, (1.0, 0.0, 0.0))
92
+ right = unit(right)
93
+ return right, unit(np.cross(right, fwd)), fwd
94
+
95
+
96
+ def axis_of(vec: Array) -> int | None:
97
+ """The world axis a camera vector lies along, or None."""
98
+ a = np.abs(vec)
99
+ i = int(np.argmax(a))
100
+ return i if a[i] > 0.999 else None
101
+
102
+
103
+ def tessellate(shape: Shape[Any], build_up: Sequence[float] | None) -> tuple[list[Group], set[int]]:
104
+ """Per solid: vertices, triangles and which triangles print unsupported;
105
+ and the hashes of the edges bounding a face that carries any of those."""
106
+ up = unit(build_up) if build_up is not None else None
107
+ groups: list[Group] = []
108
+ flagged: set[int] = set()
109
+ for solid in shape.solids():
110
+ meshes = []
111
+ for face in solid.faces():
112
+ if face.area < SLIVER_AREA:
113
+ continue
114
+ vs, ts = face.tessellate(TESS_TOL)
115
+ if ts:
116
+ meshes.append(
117
+ (face, np.array([tuple(v) for v in vs]), np.array(ts, dtype=np.int64))
118
+ )
119
+ if not meshes:
120
+ continue
121
+ floor = min((v @ up).min() for _, v, _ in meshes) if up is not None else 0.0
122
+ classifier = BRepClass3d_SolidClassifier(solid.wrapped)
123
+ verts, tris, down, base = [], [], [], 0
124
+ for face, v, t in meshes:
125
+ d = plate_ward(v, t, classifier, up) & ~resting_on(v, t, up, floor)
126
+ if d.any():
127
+ flagged.update(hash(e) for e in face.edges())
128
+ verts.append(v)
129
+ tris.append(t + base)
130
+ down.append(d)
131
+ base += len(v)
132
+ groups.append((np.vstack(verts), np.vstack(tris), np.concatenate(down)))
133
+ return groups, flagged
134
+
135
+
136
+ def plate_ward(verts: Array, tris: Any, classifier: Any, up: Array | None) -> npt.NDArray[np.bool_]:
137
+ """The triangles of one face that lean toward the plate past the overhang limit.
138
+ Winding does not say which side is material, so the solid is probed once per face."""
139
+ none = np.zeros(len(tris), dtype=bool)
140
+ n = np.cross(verts[tris[:, 1]] - verts[tris[:, 0]], verts[tris[:, 2]] - verts[tris[:, 0]])
141
+ lengths = np.linalg.norm(n, axis=1)
142
+ ok = lengths > 1e-12
143
+ if up is None or not ok.any():
144
+ return none
145
+ n[ok] /= lengths[ok][:, None]
146
+ if (np.abs(n[ok] @ up) < OVERHANG_COS).all():
147
+ return none
148
+ k = int(np.argmax(lengths))
149
+ probe = verts[tris[k]].mean(axis=0) + n[k] * PROBE_STEP
150
+ classifier.Perform(gp_Pnt(*probe), 1e-6)
151
+ if classifier.State() == TopAbs_State.TopAbs_IN or classifier.IsOnAFace():
152
+ n = -n
153
+ return ok & ((n @ up) < -OVERHANG_COS)
154
+
155
+
156
+ def resting_on(verts: Array, tris: Any, up: Array | None, floor: float) -> npt.NDArray[np.bool_]:
157
+ """Triangles lying on the plate, the one downward surface that is supported."""
158
+ if up is None:
159
+ return np.zeros(len(tris), dtype=bool)
160
+ return ((verts @ up)[tris] - floor < TESS_TOL).all(axis=1)
161
+
162
+
163
+ def drawing_centre(size: tuple[int, int]) -> tuple[float, float]:
164
+ """Centre of the tile less the dimension band."""
165
+ return (size[0] - BAND) / 2.0, (size[1] - BAND) / 2.0
166
+
167
+
168
+ def projector(
169
+ right: Array, up: Array, fwd: Array, size: tuple[int, int], scale: float, centre: Array
170
+ ) -> Projector:
171
+ """World points (N, 3) -> pixel x, pixel y, depth."""
172
+ ox, oy = drawing_centre(size)
173
+
174
+ def to_px(points: Any) -> tuple[Array, Array, Array]:
175
+ p = np.asarray(points, dtype=float).reshape(-1, 3)
176
+ return (p @ right - centre[0]) * scale + ox, oy - (p @ up - centre[1]) * scale, p @ fwd
177
+
178
+ return to_px
179
+
180
+
181
+ def fit(lo: Array, hi: Array, size: tuple[int, int]) -> tuple[Array, float]:
182
+ """Centre and scale that fit the projected span lo..hi in the drawing area."""
183
+ extent = np.maximum(hi - lo, 1e-6)
184
+ ox, oy = drawing_centre(size)
185
+ scale = min(2 * ox * (1 - 2 * MARGIN) / extent[0], 2 * oy * (1 - 2 * MARGIN) / extent[1])
186
+ return (lo + hi) / 2.0, scale
187
+
188
+
189
+ def view_frame(
190
+ groups: list[Group], direction: Sequence[float], up_hint: Sequence[float], size: tuple[int, int]
191
+ ) -> tuple[Array, float]:
192
+ right, up, _ = basis(direction, up_hint)
193
+ xy = np.vstack([np.column_stack([v @ right, v @ up]) for v, _, _ in groups])
194
+ return fit(xy.min(axis=0), xy.max(axis=0), size)
195
+
196
+
197
+ def section(shape: Shape[Any], fwd: Array, depth: float) -> Shape[Any]:
198
+ """`shape` with everything nearer the camera than `depth` cut away."""
199
+ axis = axis_of(fwd)
200
+ if axis is None:
201
+ raise ValueError("a detail must look along an axis to section cleanly")
202
+ bb = shape.bounding_box()
203
+ lo = np.array(tuple(bb.min)) - 10.0
204
+ hi = np.array(tuple(bb.max)) + 10.0
205
+ if fwd[axis] > 0:
206
+ hi[axis] = depth * fwd[axis]
207
+ else:
208
+ lo[axis] = depth * fwd[axis]
209
+ return shape - Pos(*lo) * Solid.make_box(*(hi - lo))
210
+
211
+
212
+ def rasterise(img: Array, zbuf: Array, groups: list[Group], to_px: Projector, light: Array) -> None:
213
+ """Fill every triangle through the z-buffer, shaded on |n.L| so winding does not matter."""
214
+ h, w = zbuf.shape
215
+ for verts, tris, unsupported in groups:
216
+ px, py, depth = to_px(verts)
217
+ normals = np.cross(
218
+ verts[tris[:, 1]] - verts[tris[:, 0]], verts[tris[:, 2]] - verts[tris[:, 0]]
219
+ )
220
+ lengths = np.linalg.norm(normals, axis=1)
221
+ ok = lengths > 1e-12
222
+ normals[ok] /= lengths[ok][:, None]
223
+ shade = 0.35 + 0.65 * np.abs(normals @ light)
224
+ colour = np.where(unsupported[:, None], UNSUPPORTED, BODY)
225
+ for i in np.flatnonzero(ok):
226
+ x, y, z = px[tris[i]], py[tris[i]], depth[tris[i]]
227
+ x0, x1 = max(int(np.floor(x.min())), 0), min(int(np.ceil(x.max())) + 1, w)
228
+ y0, y1 = max(int(np.floor(y.min())), 0), min(int(np.ceil(y.max())) + 1, h)
229
+ area = (x[1] - x[0]) * (y[2] - y[0]) - (x[2] - x[0]) * (y[1] - y[0])
230
+ if x1 <= x0 or y1 <= y0 or abs(area) < 1e-12:
231
+ continue
232
+ gx, gy = np.arange(x0, x1) + 0.5, (np.arange(y0, y1) + 0.5)[:, None]
233
+ w0 = ((x[1] - x[0]) * (gy - y[0]) - (gx - x[0]) * (y[1] - y[0])) / area
234
+ w1 = ((gx - x[0]) * (y[2] - y[0]) - (x[2] - x[0]) * (gy - y[0])) / area
235
+ zi = z[0] + w1 * (z[1] - z[0]) + w0 * (z[2] - z[0])
236
+ window = zbuf[y0:y1, x0:x1]
237
+ hit = (w0 >= 0) & (w1 >= 0) & (w0 + w1 <= 1) & (zi < window)
238
+ window[hit] = zi[hit]
239
+ img[y0:y1, x0:x1][hit] = colour[i] * shade[i]
240
+
241
+
242
+ def edge_points(edge: Shape[Any]) -> Array:
243
+ """Points along an edge, no farther than TESS_TOL from it."""
244
+ sampler = GCPnts_QuasiUniformDeflection(BRepAdaptor_Curve(edge.wrapped), TESS_TOL)
245
+ if not sampler.IsDone():
246
+ return np.empty((0, 3))
247
+ points = (sampler.Value(i) for i in range(1, sampler.NbPoints() + 1))
248
+ return np.array([(p.X(), p.Y(), p.Z()) for p in points])
249
+
250
+
251
+ def draw_edges(
252
+ img: Array, zbuf: Array, shape: Shape[Any], to_px: Projector, flagged: set[int]
253
+ ) -> None:
254
+ """The B-rep edges, depth-tested; an overhanging face's edges are drawn wide and orange."""
255
+ h, w = zbuf.shape
256
+ finite = zbuf[np.isfinite(zbuf)]
257
+ bias = max(np.ptp(finite) if finite.size else 1.0, 1.0) * 1e-3
258
+ for edge in shape.edges():
259
+ overhang = hash(edge) in flagged
260
+ ex, ey, ez = to_px(edge_points(edge))
261
+ for k in range(len(ex) - 1):
262
+ n = int(max(abs(ex[k + 1] - ex[k]), abs(ey[k + 1] - ey[k]))) + 1
263
+ t = np.linspace(0.0, 1.0, n + 1)
264
+ sx = (ex[k] + t * (ex[k + 1] - ex[k])).astype(int)
265
+ sy = (ey[k] + t * (ey[k + 1] - ey[k])).astype(int)
266
+ sz = ez[k] + t * (ez[k + 1] - ez[k])
267
+ keep = (sx >= 0) & (sx < w) & (sy >= 0) & (sy < h)
268
+ sx, sy, sz = sx[keep], sy[keep], sz[keep]
269
+ seen = sz <= zbuf[sy, sx] + bias
270
+ vx, vy = sx[seen], sy[seen]
271
+ img[vy, vx] = UNSUPPORTED if overhang else INK
272
+ if overhang:
273
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
274
+ img[np.clip(vy + dy, 0, h - 1), np.clip(vx + dx, 0, w - 1)] = UNSUPPORTED
275
+
276
+
277
+ def arrow(draw: ImageDraw.ImageDraw, tip: Array, along: Array) -> None:
278
+ back = tip - along * ARROW_L
279
+ perp = np.array([-along[1], along[0]]) * ARROW_W
280
+ draw.polygon([tuple(tip), tuple(back + perp), tuple(back - perp)], fill=DIM)
281
+
282
+
283
+ def text_tile(text: str, font: Font, rotate: bool) -> Image.Image:
284
+ box = font.getbbox(text)
285
+ tile = Image.new("RGBA", (int(box[2] - box[0]) + 2, int(box[3] - box[1]) + 2), (0, 0, 0, 0))
286
+ ImageDraw.Draw(tile).text((1 - box[0], 1 - box[1]), text, font=font, fill=(*DIM, 255))
287
+ return tile.rotate(90, expand=True) if rotate else tile
288
+
289
+
290
+ def extent(tile: Image.Image, at: Array, out: Array) -> tuple[int, int, int, int]:
291
+ """Where `tile` lands centred on `at`, pushed clear along `out`."""
292
+ span = tile.height if abs(out[1]) > abs(out[0]) else tile.width
293
+ c = at + out * (span / 2.0 + GAP)
294
+ x, y = int(c[0] - tile.width / 2), int(c[1] - tile.height / 2)
295
+ return x, y, x + tile.width, y + tile.height
296
+
297
+
298
+ def overlaps(a: Box2, b: Box2) -> bool:
299
+ return not (a[2] <= b[0] or a[0] >= b[2] or a[3] <= b[1] or a[1] >= b[3])
300
+
301
+
302
+ def fits(box: Box2, size: tuple[int, int]) -> bool:
303
+ return box[0] >= GAP and box[1] >= GAP and box[2] <= size[0] - GAP and box[3] <= size[1] - GAP
304
+
305
+
306
+ def clear_of(box: Box2, blocker: Box2, out: Array) -> float:
307
+ """Extra push along `out` that moves `box` off `blocker`, or 0 if it is clear."""
308
+ if not overlaps(box, blocker):
309
+ return 0.0
310
+ i = 0 if abs(out[0]) > abs(out[1]) else 1
311
+ span = (blocker[i + 2] - box[i]) if out[i] > 0 else (box[i + 2] - blocker[i])
312
+ return span / max(abs(out[i]), 1e-6) + GAP
313
+
314
+
315
+ class Placement:
316
+ """A dimension line pushed out by `offset` from the points p0, p1, laid out before drawing."""
317
+
318
+ def __init__(
319
+ self,
320
+ size: tuple[int, int],
321
+ p0: Any,
322
+ p1: Any,
323
+ offset: Any,
324
+ text: str,
325
+ font: Font,
326
+ ) -> None:
327
+ self.p0, self.p1 = np.asarray(p0, dtype=float), np.asarray(p1, dtype=float)
328
+ offset = np.asarray(offset, dtype=float)
329
+ self.q0, self.q1 = self.p0 + offset, self.p1 + offset
330
+ self.out = offset / max(np.linalg.norm(offset), 1e-9)
331
+ span = np.linalg.norm(self.q1 - self.q0)
332
+ self.along = (self.q1 - self.q0) / max(span, 1e-9)
333
+ self.tile = text_tile(text, font, abs(self.along[1]) > abs(self.along[0]))
334
+ if span < 4 * ARROW_L:
335
+ at, push = self.q1 + self.along * ARROW_L, self.along
336
+ x0, y0, x1, y1 = extent(self.tile, at, push)
337
+ if x0 < 0 or y0 < 0 or x1 > size[0] or y1 > size[1]:
338
+ at, push = self.q0 - self.along * ARROW_L, -self.along
339
+ else:
340
+ at, push = (self.q0 + self.q1) / 2.0, self.out
341
+ box = extent(self.tile, at, push)
342
+ self.text_at = (box[0], box[1])
343
+ self.text_box: Box2 = box
344
+ self.box: Box2 = (
345
+ min(box[0], self.q0[0], self.q1[0]),
346
+ min(box[1], self.q0[1], self.q1[1]),
347
+ max(box[2], self.q0[0], self.q1[0]),
348
+ max(box[3], self.q0[1], self.q1[1]),
349
+ )
350
+
351
+ def draw(self, im: Image.Image, draw: ImageDraw.ImageDraw) -> None:
352
+ for p, q in ((self.p0, self.q0), (self.p1, self.q1)):
353
+ draw.line([tuple(p + self.out * GAP), tuple(q + self.out * OVER)], fill=DIM, width=LW)
354
+ draw.line([tuple(self.q0), tuple(self.q1)], fill=DIM, width=LW)
355
+ arrow(draw, self.q0, self.along)
356
+ arrow(draw, self.q1, -self.along)
357
+ im.paste(self.tile, self.text_at, self.tile)
358
+
359
+
360
+ def leader(
361
+ im: Image.Image,
362
+ draw: ImageDraw.ImageDraw,
363
+ p0: Array,
364
+ p1: Array,
365
+ centre: Array,
366
+ bounds: Box2,
367
+ text: str,
368
+ font: Font,
369
+ ) -> Box2:
370
+ """A dimension drawn on the feature, its text led out past `bounds`; returns the text box.
371
+ For a radial feature no perpendicular push reaches a margin without crossing the part."""
372
+ along = (p1 - p0) / max(np.linalg.norm(p1 - p0), 1e-9)
373
+ draw.line([tuple(p0), tuple(p1)], fill=DIM, width=LW)
374
+ arrow(draw, p0, along)
375
+ arrow(draw, p1, -along)
376
+ mid = (p0 + p1) / 2.0
377
+ out = mid - centre
378
+ n = np.linalg.norm(out)
379
+ out = along if n < 1.0 else out / n
380
+ x0, y0, x1, y1 = bounds
381
+ reach = min(
382
+ (((x1 if out[i] > 0 else x0) if i == 0 else (y1 if out[i] > 0 else y0)) - mid[i]) / out[i]
383
+ for i in (0, 1)
384
+ if abs(out[i]) > 1e-6
385
+ )
386
+ tip = mid + out * (max(reach, 0.0) + OFF)
387
+ tile = text_tile(text, font, abs(out[1]) > abs(out[0]))
388
+ box = extent(tile, tip, out)
389
+ shift = np.array(
390
+ [
391
+ max(0, OFF - box[0]) - max(0, box[2] - (im.width - OFF)),
392
+ max(0, OFF - box[1]) - max(0, box[3] - (im.height - OFF)),
393
+ ]
394
+ )
395
+ tip = tip + shift
396
+ x, y = int(box[0] + shift[0]), int(box[1] + shift[1])
397
+ draw.line([tuple(mid + out * GAP), tuple(tip)], fill=DIM, width=LW)
398
+ im.paste(tile, (x, y), tile)
399
+ return x, y, x + tile.width, y + tile.height
400
+
401
+
402
+ def annotate(
403
+ im: Image.Image,
404
+ name: str,
405
+ detail: str | None,
406
+ shape: Shape[Any],
407
+ dims: Sequence[Dimension],
408
+ right: Array,
409
+ up: Array,
410
+ fwd: Array,
411
+ to_px: Projector,
412
+ shaded: bool,
413
+ ) -> None:
414
+ """Name the view and dimension it: features first, then overall size, then leaders."""
415
+ draw = ImageDraw.Draw(im)
416
+ font = ImageFont.load_default(size=FONT_PX)
417
+ draw.text((GAP, GAP), f"detail: {name}" if detail else name, font=font, fill=DIM)
418
+ bb = shape.bounding_box()
419
+ lengths = (bb.size.X, bb.size.Y, bb.size.Z)
420
+ ra, ua = axis_of(right), axis_of(up)
421
+ if ra is None or ua is None:
422
+ draw.text(
423
+ (GAP, GAP + FONT_PX + GAP),
424
+ "{:.1f} x {:.1f} x {:.1f} mm".format(*lengths),
425
+ font=font,
426
+ fill=DIM,
427
+ )
428
+ if shaded:
429
+ note = "orange faces print unsupported (over 45 deg)"
430
+ draw.text((GAP, GAP + 2 * (FONT_PX + GAP)), note, font=font, fill=UNSUPPORTED)
431
+ return
432
+
433
+ mine = [
434
+ d
435
+ for d in dims
436
+ if (d.get("detail") == detail if detail else not d.get("detail") and d["view"] == name)
437
+ ]
438
+ corners = list(itertools.product(*zip(tuple(bb.min), tuple(bb.max), strict=True)))
439
+ if detail:
440
+ corners = [p for d in mine for p in (d["a"], d["b"])]
441
+ px, py, _ = to_px(corners)
442
+ x0, x1, y0, y1 = px.min(), px.max(), py.min(), py.max()
443
+ centre = np.array([(x0 + x1) / 2.0, (y0 + y1) / 2.0])
444
+ size = (im.width, im.height)
445
+
446
+ taken: list[Box2] = []
447
+ texts: list[Box2] = []
448
+ led: list[tuple[Array, Array, str]] = []
449
+ for dim in mine:
450
+ a, b = np.array(dim["a"], dtype=float), np.array(dim["b"], dtype=float)
451
+ length = float(np.linalg.norm(b - a))
452
+ if abs((b - a) @ fwd) > 1e-6 * max(length, 1.0):
453
+ print(f" skip '{dim['label']}': foreshortened in the {name} view")
454
+ continue
455
+ (ax, ay, _), (bx, by, _) = to_px([a]), to_px([b])
456
+ pa, pb = np.array([ax[0], ay[0]]), np.array([bx[0], by[0]])
457
+ v = pb - pa
458
+ n = float(np.linalg.norm(v))
459
+ if n < 1.0:
460
+ continue
461
+ out = np.array([-v[1], v[0]]) / n
462
+ mid = (pa + pb) / 2.0
463
+ side = out @ (mid - centre)
464
+ if side < -1.0 or (abs(side) <= 1.0 and out[0] + out[1] < 0):
465
+ out = -out
466
+ reach = abs(out[0]) * (x1 - mid[0] if out[0] > 0 else mid[0] - x0) + abs(out[1]) * (
467
+ y1 - mid[1] if out[1] > 0 else mid[1] - y0
468
+ )
469
+ label = f"{dim['label']} {length:.2f}" if detail else f"{dim['label']} {length:.1f}"
470
+ push = max(reach, 0.0) + FEAT_OFF
471
+ for _ in range(len(taken) + 1):
472
+ plan = Placement(size, pa, pb, out * push, label, font)
473
+ extra = max([clear_of(plan.box, t, out) for t in taken] + [0.0])
474
+ if extra <= 0.0:
475
+ break
476
+ push += extra
477
+ axis_aligned = min(abs(v[0]), abs(v[1])) / n < 0.035
478
+ blocked = any(clear_of(plan.box, t, out) > 0.0 for t in taken)
479
+ if not fits(plan.box, size) or (not axis_aligned and reach > n) or blocked:
480
+ led.append((pa, pb, label))
481
+ else:
482
+ plan.draw(im, draw)
483
+ taken.append(plan.box)
484
+ texts.append(plan.text_box)
485
+
486
+ edge: list[Box2] = []
487
+ if not detail:
488
+ below = max([t[3] for t in taken] + [y1]) + OFF
489
+ beside = max([t[2] for t in taken] + [x1]) + OFF
490
+ for p0, p1, offset, value in (
491
+ ((x0, y1), (x1, y1), (0, below - y1), lengths[ra]),
492
+ ((x1, y0), (x1, y1), (beside - x1, 0), lengths[ua]),
493
+ ):
494
+ plan = Placement(size, p0, p1, offset, f"{value:.1f}", font)
495
+ plan.draw(im, draw)
496
+ edge.append(plan.box)
497
+ texts.append(plan.text_box)
498
+ placed = taken + edge
499
+ clear = (
500
+ min([t[0] for t in placed] + [x0]),
501
+ min([t[1] for t in placed] + [y0]),
502
+ max([t[2] for t in placed] + [x1]),
503
+ max([t[3] for t in placed] + [y1]),
504
+ )
505
+ texts += [leader(im, draw, pa, pb, centre, clear, label, font) for pa, pb, label in led]
506
+ for one, other in itertools.combinations(texts, 2):
507
+ if overlaps(one, other):
508
+ raise ValueError(f"{name}: labels overlap, {one} and {other}")
509
+
510
+
511
+ def render_view(
512
+ shape: Shape[Any],
513
+ groups: list[Group],
514
+ flagged: set[int],
515
+ view: tuple[str, Any, Any, str | None],
516
+ size: tuple[int, int],
517
+ scale: float,
518
+ centre: Array,
519
+ dims: Sequence[Dimension],
520
+ ) -> Image.Image:
521
+ name, direction, up_hint, detail = view
522
+ w, h = size
523
+ right, up, fwd = basis(direction, up_hint)
524
+ to_px = projector(right, up, fwd, size, scale, centre)
525
+ img = np.empty((h, w, 3))
526
+ img[:] = BG
527
+ zbuf = np.full((h, w), np.inf)
528
+ rasterise(img, zbuf, groups, to_px, unit(-fwd + 0.45 * up + 0.35 * right))
529
+ draw_edges(img, zbuf, shape, to_px, flagged)
530
+ tile = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8))
531
+ shaded = any(u.any() for _, _, u in groups)
532
+ annotate(tile, name, detail, shape, dims, right, up, fwd, to_px, shaded)
533
+ return tile
534
+
535
+
536
+ def detail_frames(
537
+ shape: Shape[Any],
538
+ dims: Sequence[Dimension],
539
+ size: tuple[int, int],
540
+ build_up: Sequence[float] | None,
541
+ ) -> list[tuple[Any, ...]]:
542
+ """One zoomed, sectioned view per named detail, framed on what its dimensions span."""
543
+ frames = []
544
+ for name in sorted({d["detail"] for d in dims if d.get("detail")}):
545
+ group = [d for d in dims if d.get("detail") == name]
546
+ views = sorted({d["view"] for d in group})
547
+ if len(views) != 1:
548
+ raise ValueError(f"detail '{name}' spans views {views}")
549
+ direction, up_hint = next((d, u) for n, d, u in VIEWS if n == views[0])
550
+ right, up, fwd = basis(direction, up_hint)
551
+ pts = np.array([d[k] for d in group for k in ("a", "b")], dtype=float)
552
+ xy = np.column_stack([pts @ right, pts @ up])
553
+ lo, hi = xy.min(axis=0), xy.max(axis=0)
554
+ pad = (hi - lo) * (DETAIL_PAD - 1) / 2
555
+ centre, scale = fit(lo - pad, hi + pad, size)
556
+ cut = section(shape, fwd, float(np.mean(pts @ fwd)))
557
+ cut_groups, cut_flagged = tessellate(cut, build_up)
558
+ frames.append(
559
+ ((name, direction, up_hint, name), centre, scale, cut, cut_groups, cut_flagged)
560
+ )
561
+ return frames
562
+
563
+
564
+ def draw_sheet(
565
+ shape: Shape[Any],
566
+ groups: list[Group],
567
+ flagged: set[int],
568
+ dims: Sequence[Dimension],
569
+ build_up: Sequence[float] | None,
570
+ path: Path,
571
+ ) -> None:
572
+ """Six views at one shared scale, plus a tile per detail, to one PNG."""
573
+ size = (TILE[0] * SS, TILE[1] * SS)
574
+ frames = [view_frame(groups, d, u, size) for _, d, u in VIEWS]
575
+ scale = min(s for _, s in frames)
576
+ plan = [
577
+ ((n, d, u, None), c, scale, shape, groups, flagged)
578
+ for (n, d, u), (c, _) in zip(VIEWS, frames, strict=True)
579
+ ]
580
+ plan += detail_frames(shape, dims, size, build_up)
581
+ rows = -(-len(plan) // COLS)
582
+ sheet = Image.new("RGB", (size[0] * COLS, size[1] * rows), BG)
583
+ for i, (view, centre, s, seen, tris, flags) in enumerate(plan):
584
+ tile = render_view(seen, tris, flags, view, size, s, centre, dims)
585
+ sheet.paste(tile, ((i % COLS) * size[0], (i // COLS) * size[1]))
586
+ path.parent.mkdir(parents=True, exist_ok=True)
587
+ sheet.resize((size[0] * COLS // SS, size[1] * rows // SS), Image.Resampling.LANCZOS).save(path)
588
+ print(f"wrote {path}")
589
+
590
+
591
+ def draw_part(stem: str, shape: Shape[Any], spec: Mapping[str, Any], out_dir: Path) -> None:
592
+ build_up = spec.get("build_up")
593
+ if build_up is None:
594
+ print(f" {stem}: no build direction declared, overhangs not shaded")
595
+ groups, flagged = tessellate(shape, build_up)
596
+ draw_sheet(
597
+ shape, groups, flagged, spec.get("dimensions", []), build_up, out_dir / f"{stem}.png"
598
+ )
599
+
600
+
601
+ def draw_assembly(
602
+ name: str, spec: Mapping[str, Any], seat: Callable[[str], Shape[Any]], out_dir: Path
603
+ ) -> None:
604
+ """Every seated part in its assembled place, each with its own build direction."""
605
+ shapes: list[Shape[Any]] = []
606
+ groups: list[Group] = []
607
+ flagged: set[int] = set()
608
+ for part in spec["seat"]:
609
+ shape = Pos(*part.get("at", (0.0, 0.0, 0.0))) * seat(part["stem"])
610
+ g, f = tessellate(shape, part.get("build_up"))
611
+ shapes.append(shape)
612
+ groups += g
613
+ flagged |= f
614
+ draw_sheet(
615
+ Compound(shapes), groups, flagged, spec.get("dimensions", []), None, out_dir / f"{name}.png"
616
+ )
617
+
618
+
619
+ def draw_sheets(
620
+ shapes: Mapping[str, Shape[Any]],
621
+ spec: Mapping[str, Any],
622
+ seat: Callable[[str], Shape[Any]],
623
+ out_dir: Path,
624
+ ) -> None:
625
+ """A sheet per shape, keyed by file stem, and one per assembly in `spec`.
626
+ `seat` returns the shape for an assembly's stem, which may be ../<model>/<stem>."""
627
+ parts = spec.get("parts", {})
628
+ for stem, shape in shapes.items():
629
+ draw_part(stem, shape, parts.get(stem, {}), out_dir)
630
+ for name, assembly in sorted(spec.get("assemblies", {}).items()):
631
+ draw_assembly(name, assembly, seat, out_dir)
brepy/viewer.py ADDED
@@ -0,0 +1,121 @@
1
+ """Preview a model in an OCP viewer, rebuilding it when a source file changes."""
2
+
3
+ import os
4
+ import platform
5
+ import socket
6
+ import threading
7
+ import time
8
+ import traceback
9
+ import webbrowser
10
+ from collections.abc import Sequence
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import webview
16
+ from ocp_viewer import set_port, show
17
+ from ocp_viewer.server import create_server
18
+
19
+ from brepy.build import build_files, load_model
20
+
21
+ HOST = "127.0.0.1"
22
+ PORT = 3939
23
+ WATCH_INTERVAL_SECONDS = 0.5
24
+ WATCHED_SUFFIXES = (".py", ".json")
25
+
26
+
27
+ def port_in_use(port: int) -> bool:
28
+ try:
29
+ with socket.create_connection((HOST, port), timeout=0.5):
30
+ return True
31
+ except OSError:
32
+ return False
33
+
34
+
35
+ def start_server(port: int) -> tuple[Any, Any]:
36
+ """Serve the viewer from this process, so brepy can see when a page connects."""
37
+ if port_in_use(port):
38
+ raise SystemExit(f"brepy: port {port} is in use; pass another --port")
39
+ viewer, server = create_server({"host": HOST, "port": port})
40
+ threading.Thread(target=server.serve_forever, daemon=True).start()
41
+ return viewer, server
42
+
43
+
44
+ def watched_files(root: Path) -> dict[Path, float]:
45
+ """Modification times of the source files under `root`, skipping hidden folders."""
46
+ times: dict[Path, float] = {}
47
+ for folder, dirs, names in os.walk(root):
48
+ dirs[:] = [d for d in dirs if not d.startswith(".") and d != "__pycache__"]
49
+ for name in names:
50
+ if name.endswith(WATCHED_SUFFIXES):
51
+ path = Path(folder) / name
52
+ try:
53
+ times[path] = path.stat().st_mtime
54
+ except FileNotFoundError:
55
+ continue
56
+ return times
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Session:
61
+ """What to show and where: the model, its build arguments, and the viewer's port."""
62
+
63
+ path: Path
64
+ root: Path
65
+ parameters: Sequence[str]
66
+ part: str | None
67
+ port: int
68
+
69
+ def push(self) -> None:
70
+ model = load_model(self.path, self.root)
71
+ files = build_files(model, self.parameters, self.part)
72
+ shapes = {label: shape for held in files.values() for label, shape in held.items()}
73
+ set_port(self.port, HOST)
74
+ show(*shapes.values(), names=list(shapes))
75
+
76
+
77
+ def keep_current(viewer: Any, session: Session, watch: bool) -> None:
78
+ """Push the parts to each page that connects and, when watching, after each source
79
+ change. The viewer drops a model that arrives while no page is connected."""
80
+ shown_page: object = None
81
+ shown_files = watched_files(session.root)
82
+ while True:
83
+ time.sleep(WATCH_INTERVAL_SECONDS)
84
+ page = viewer.browser
85
+ files = watched_files(session.root) if watch else shown_files
86
+ if page is None or (page is shown_page and files == shown_files):
87
+ continue
88
+ shown_page, shown_files = page, files
89
+ try:
90
+ session.push()
91
+ print("brepy: sent the parts to the viewer", flush=True)
92
+ except Exception:
93
+ traceback.print_exc()
94
+
95
+
96
+ def open_window(url: str) -> None:
97
+ """A native window on macOS and Windows; the browser on Linux, where pywebview
98
+ needs Qt or GTK."""
99
+ if platform.system() != "Linux":
100
+ try:
101
+ webview.create_window("brepy", url)
102
+ webview.start()
103
+ return
104
+ except webview.errors.WebViewException as error:
105
+ print(f"brepy: no native window ({error})")
106
+ print(f"brepy: opening {url} in the browser", flush=True)
107
+ webbrowser.open(url)
108
+ threading.Event().wait()
109
+
110
+
111
+ def preview(session: Session, watch: bool) -> None:
112
+ viewer, server = start_server(session.port)
113
+ threading.Thread(target=keep_current, args=(viewer, session, watch), daemon=True).start()
114
+ try:
115
+ open_window(f"http://{HOST}:{session.port}/")
116
+ except KeyboardInterrupt:
117
+ pass
118
+ finally:
119
+ server.shutdown()
120
+ if viewer.browser is not None:
121
+ viewer.browser.close()
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.5
2
+ Name: brepy
3
+ Version: 0.1.2
4
+ Summary: Build, export and preview build123d model scripts
5
+ Author: Brandon Helwig
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: build123d>=0.13
10
+ Requires-Dist: numpy>=2
11
+ Requires-Dist: pillow>=11
12
+ Provides-Extra: viewer
13
+ Requires-Dist: ocp-viewer>=1.1; extra == 'viewer'
14
+ Requires-Dist: pywebview>=6; extra == 'viewer'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # brepy
18
+
19
+ Build, export and preview [build123d](https://build123d.readthedocs.io) model
20
+ scripts from the command line.
21
+
22
+ A model is a Python script with a `build()` function. `brepy` runs it, writes
23
+ the parts to STEP, STL, 3MF or BREP, draws dimensioned preview sheets without a
24
+ GPU or display, and can show the model in a live viewer that rebuilds on save.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ uv tool install "brepy[viewer]"
30
+ ```
31
+
32
+ The `viewer` extra adds `--view` and `--watch`. Leave it out on headless
33
+ machines. OCP needs the system library `libGL.so.1` (Debian: `libgl1`).
34
+ Releases are published to [PyPI](https://pypi.org/project/brepy/).
35
+
36
+ A container image with `brepy`, pytest, ruff and ty preinstalled is published
37
+ as `ghcr.io/brhelwig-dev/brepy:<version>` for each release, and as `:latest`,
38
+ rebuilt from `main` on every push and nightly:
39
+
40
+ ```sh
41
+ docker run --rm -v "$PWD:/work" -w /work ghcr.io/brhelwig-dev/brepy:0.1.2 \
42
+ brepy -f step models/bracket/bracket.py
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ```sh
48
+ brepy models/bracket/bracket.py # STEP beside the script
49
+ brepy -f stl -f 3mf -o out/ models/bracket/bracket.py
50
+ brepy -f png models/bracket/bracket.py # preview sheets
51
+ brepy --part lid models/box/box.py # one part
52
+ brepy -p width=30 models/bracket/bracket.py # a build() argument
53
+ brepy --watch models/bracket/bracket.py # live preview
54
+ ```
55
+
56
+ The script is imported by its path relative to `--root`, the current directory
57
+ by default. `models/bracket/bracket.py` imports as `models.bracket.bracket`, so
58
+ scripts can share code by importing each other or helper modules under the
59
+ root.
60
+
61
+ ## Model scripts
62
+
63
+ ```python
64
+ from build123d import Box, Cylinder, Pos
65
+
66
+ SEPARATE_PRINTS = False
67
+
68
+
69
+ def build(width: float = 40.0) -> dict:
70
+ base = Box(width, 20, 5)
71
+ pin = Pos(0, 0, 5) * Cylinder(3, 10)
72
+ return {"base": base, "pin": pin}
73
+
74
+
75
+ def preview_spec() -> dict:
76
+ return {"parts": {"bracket_base": {"build_up": [0, 0, 1]}}}
77
+ ```
78
+
79
+ `build()` returns parts by name. A part may itself be a mapping of shells,
80
+ `{"red": shape, "white": shape}`, for one print in several colours. Its
81
+ arguments can be set with `-p NAME=VALUE`, converted to the annotated type.
82
+
83
+ Output files are named after the script:
84
+
85
+ - one plain part: `<name>`
86
+ - several parts: `<name>_<part>` each, plus a combined `<name>` holding all of
87
+ them, unless the script sets `SEPARATE_PRINTS = True`
88
+ - shells: `<name>_<part>_<shell>` each, plus `<name>_<part>` holding the shells
89
+
90
+ ## Preview sheets
91
+
92
+ `-f png` writes one sheet per output file to `previews/`, with six orthographic
93
+ views (isometric, underside, front, right, top, bottom) at one shared scale.
94
+ `preview_spec()` adds to them:
95
+
96
+ ```python
97
+ {
98
+ "parts": {
99
+ "<stem>": {
100
+ "build_up": [0, 0, 1],
101
+ "dimensions": [
102
+ {"label": "pin dia", "view": "top", "a": [-3, 0, 15], "b": [3, 0, 15]},
103
+ {"label": "slot", "view": "front", "a": [...], "b": [...], "detail": "slot"},
104
+ ],
105
+ }
106
+ },
107
+ "assemblies": {
108
+ "<name>": {
109
+ "seat": [
110
+ {"stem": "<stem>", "at": [0, 0, 0], "build_up": [0, 0, 1]},
111
+ {"stem": "../<other model>/<stem>"},
112
+ ],
113
+ "dimensions": [],
114
+ }
115
+ },
116
+ }
117
+ ```
118
+
119
+ - `build_up` is the direction away from the build plate. With it, faces that
120
+ would print without support are shaded orange.
121
+ - A dimension is drawn in the view it names, between points `a` and `b`. One
122
+ with a `detail` name gets its own zoomed, sectioned tile.
123
+ - An assembly places output files, or files from a sibling script
124
+ (`../<other model>/<other model>.py`), on one sheet.
125
+
126
+ When the spec is present, `-f step` also writes it to `preview.json`.
127
+
128
+ ## Printability
129
+
130
+ `brepy.printability` measures a solid the same way the sheets shade it, for
131
+ use in a model's tests:
132
+
133
+ ```python
134
+ from brepy import printability
135
+
136
+ assert printability.unsupported_area(part, build_up=(0, 0, 1)) < 0.01
137
+ assert printability.island_area(part, layer_height=0.2, build_up=(0, 0, 1)) < 0.01
138
+ ```
139
+
140
+ A face is unsupported where it faces down more than 42 degrees from vertical
141
+ and does not rest on the plate. An island is an area printed in some layer with
142
+ nothing below it. `printability.section(part, z)` returns the plan section at
143
+ height `z`.
144
+
145
+ ## Development
146
+
147
+ ```sh
148
+ uv sync --extra viewer
149
+ uv run pytest
150
+ uv run ruff check && uv run ruff format --check
151
+ uv run ty check
152
+ ```
153
+
154
+ ## License
155
+
156
+ MIT
@@ -0,0 +1,13 @@
1
+ brepy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ brepy/__main__.py,sha256=EqSWT2YkC-ZOEOzyTuB-j2g9UMfIkST_mSOHqeRVIk8,57
3
+ brepy/build.py,sha256=ZUgcSWCsVSkH3rF577JAhvGKClLtIKHwyoUVjZw6pCc,5762
4
+ brepy/cli.py,sha256=UEWfGJUNse5jJtDdEVKzndINc_vSuoWDz9qg-UmuZlY,3345
5
+ brepy/export.py,sha256=6B1K_3R-gcaiGVUCbCJsCSFwXtCh3_X_7qpuYmHo-g4,2070
6
+ brepy/printability.py,sha256=dOw8GYs_j2F5EP9_Xfxp-Ka6twMQhmoHDoW4yS7ud_Y,3953
7
+ brepy/sheets.py,sha256=Hf1Ci3cvXev83hVIqSoIozk2EfKSjDN4f8LParMUOio,25216
8
+ brepy/viewer.py,sha256=G31vgM2sbFSU6bDBXfvmLY7-ddX88GWgkWVntlFX7nE,3980
9
+ brepy-0.1.2.dist-info/METADATA,sha256=zSSRF7S7wEDgSfbd8GJVC_7DJ_bmQdafmQSg3NZD6yw,4878
10
+ brepy-0.1.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
11
+ brepy-0.1.2.dist-info/entry_points.txt,sha256=MFVE7zpzFTDEAGu5PU4WiMRuHMp9m9BHdNbCFKdpy4I,41
12
+ brepy-0.1.2.dist-info/licenses/LICENSE,sha256=2KIIcv6DYaFuMX0NnOvLN7ZZYVJ0qS0PJClFPJPEJPw,1071
13
+ brepy-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ brepy = brepy.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brandon Helwig
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.