replicator-workshop 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.
- replicator/__init__.py +6 -0
- replicator/app.py +204 -0
- replicator/config.py +48 -0
- replicator/core/__init__.py +0 -0
- replicator/core/assembly.py +117 -0
- replicator/core/blender_link.py +161 -0
- replicator/core/critique.py +594 -0
- replicator/core/drawing.py +389 -0
- replicator/core/dxf.py +120 -0
- replicator/core/evaluate.py +439 -0
- replicator/core/explain.py +139 -0
- replicator/core/export.py +96 -0
- replicator/core/fit.py +170 -0
- replicator/core/importers.py +185 -0
- replicator/core/materials.py +104 -0
- replicator/core/ops_advanced.py +496 -0
- replicator/core/ops_engineering.py +223 -0
- replicator/core/physics.py +147 -0
- replicator/core/printers.py +100 -0
- replicator/core/program.py +298 -0
- replicator/core/render.py +145 -0
- replicator/core/reverse.py +350 -0
- replicator/core/robot.py +153 -0
- replicator/core/step.py +245 -0
- replicator/fixtures/gaming_pc_liquid.json +2259 -0
- replicator/fixtures/gas_generator_rocket.json +876 -0
- replicator/fixtures/gas_generator_rocket_aero.json +861 -0
- replicator/fixtures/house_two_bed.json +979 -0
- replicator/fixtures/quadcopter_drone.json +687 -0
- replicator/fixtures/raspberry_pi_5.json +884 -0
- replicator/fixtures/rocket_engine.json +652 -0
- replicator/fixtures/turbofan.json +931 -0
- replicator/fixtures/vector_engine.json +314 -0
- replicator/gpu.py +81 -0
- replicator/image3d/__init__.py +0 -0
- replicator/image3d/comfy.py +181 -0
- replicator/image3d/pipeline.py +208 -0
- replicator/image3d/sheet.py +154 -0
- replicator/knowledge/__init__.py +61 -0
- replicator/knowledge/car_wheel_corner.md +21 -0
- replicator/knowledge/desk_lamp.md +21 -0
- replicator/knowledge/desktop_pc.md +20 -0
- replicator/knowledge/electronics_board.md +21 -0
- replicator/knowledge/exoskeleton.md +21 -0
- replicator/knowledge/house.md +22 -0
- replicator/knowledge/light_aircraft.md +22 -0
- replicator/knowledge/multirotor_drone.md +25 -0
- replicator/knowledge/print_replica.md +13 -0
- replicator/knowledge/rocket_engine.md +27 -0
- replicator/knowledge/turbofan.md +23 -0
- replicator/llm/__init__.py +0 -0
- replicator/llm/client.py +424 -0
- replicator/llm/prompts/blueprint.md +28 -0
- replicator/llm/prompts/edit.md +15 -0
- replicator/llm/prompts/explain.md +37 -0
- replicator/llm/prompts/name_parts.md +13 -0
- replicator/llm/prompts/program.md +72 -0
- replicator/llm/prompts/research_queries.md +8 -0
- replicator/mcp_server.py +307 -0
- replicator/qml/Main.qml +874 -0
- replicator/qml/Replicator/UI/Chip.qml +17 -0
- replicator/qml/Replicator/UI/DockHeader.qml +27 -0
- replicator/qml/Replicator/UI/Icon.qml +118 -0
- replicator/qml/Replicator/UI/IconButton.qml +31 -0
- replicator/qml/Replicator/UI/Kbd.qml +18 -0
- replicator/qml/Replicator/UI/NumField.qml +69 -0
- replicator/qml/Replicator/UI/Pill.qml +28 -0
- replicator/qml/Replicator/UI/RCombo.qml +51 -0
- replicator/qml/Replicator/UI/RMenu.qml +42 -0
- replicator/qml/Replicator/UI/RSlider.qml +23 -0
- replicator/qml/Replicator/UI/Segmented.qml +63 -0
- replicator/qml/Replicator/UI/Swatch.qml +47 -0
- replicator/qml/Replicator/UI/Theme.qml +149 -0
- replicator/qml/Replicator/UI/qmldir +14 -0
- replicator/qml/panels/AgentPrompt.qml +53 -0
- replicator/qml/panels/AttributeManager.qml +171 -0
- replicator/qml/panels/Commander.qml +136 -0
- replicator/qml/panels/HolodeckPanel.qml +117 -0
- replicator/qml/panels/IssuesCard.qml +78 -0
- replicator/qml/panels/LedgerPanel.qml +110 -0
- replicator/qml/panels/MaterialShelf.qml +97 -0
- replicator/qml/panels/ObjectManager.qml +107 -0
- replicator/qml/panels/Preferences.qml +211 -0
- replicator/qml/panels/Presenter.qml +316 -0
- replicator/qml/panels/StatusBar.qml +77 -0
- replicator/qml/panels/Timeline.qml +149 -0
- replicator/qml/panels/Welcome.qml +126 -0
- replicator/qml/viewport/Callouts.qml +87 -0
- replicator/qml/viewport/EdgeMaterial.qml +16 -0
- replicator/qml/viewport/GridMaterial.qml +16 -0
- replicator/qml/viewport/HoloMaterial.qml +23 -0
- replicator/qml/viewport/NavGizmo.qml +72 -0
- replicator/qml/viewport/ReferenceMaterial.qml +17 -0
- replicator/qml/viewport/Viewport.qml +583 -0
- replicator/qt/__init__.py +0 -0
- replicator/qt/bridge.py +1427 -0
- replicator/qt/drawing_sheet.py +33 -0
- replicator/qt/envmap.py +40 -0
- replicator/qt/library.py +68 -0
- replicator/qt/mesh_geometry.py +167 -0
- replicator/qt/svg.py +41 -0
- replicator/research/__init__.py +0 -0
- replicator/research/lane.py +281 -0
- replicator/shaders/edge.frag +9 -0
- replicator/shaders/edge.vert +7 -0
- replicator/shaders/grid.frag +52 -0
- replicator/shaders/grid.vert +6 -0
- replicator/shaders/holo.frag +41 -0
- replicator/shaders/reference.frag +15 -0
- replicator/shaders/reference.vert +6 -0
- replicator/voice.py +120 -0
- replicator_workshop-0.1.0.dist-info/METADATA +410 -0
- replicator_workshop-0.1.0.dist-info/RECORD +118 -0
- replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
- replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
- replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Evaluate a BuildProgram into meshes with manifold3d. Pure CPU, no GPU anywhere.
|
|
2
|
+
|
|
3
|
+
Internal geometry is Y-up. manifold3d builds cylinders and extrusions along +Z, so those get turned to +Y here.
|
|
4
|
+
Results are cached by op hash, so an edit recomputes only that op and what depends on it.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from manifold3d import CrossSection, Manifold, Mesh, OpType
|
|
15
|
+
|
|
16
|
+
from .program import COMBINERS, check, component_map, op_hash, op_inputs
|
|
17
|
+
|
|
18
|
+
Z_TO_Y = (-90.0, 0.0, 0.0) # rotate +Z onto +Y
|
|
19
|
+
AXIS_ROT = {"y": Z_TO_Y, "z": (0.0, 0.0, 0.0), "x": (0.0, 90.0, 0.0)}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class EvalError(ValueError):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _Status:
|
|
27
|
+
name = "NotManifold"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _RawMeshData:
|
|
31
|
+
def __init__(self, vp, tri):
|
|
32
|
+
self.vert_properties = vp
|
|
33
|
+
self.tri_verts = tri
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class RawMesh:
|
|
37
|
+
"""Imported geometry that is not a closed manifold (most downloaded GLBs). It can be shown, moved, exploded and
|
|
38
|
+
exported to GLB, but not used in booleans, hulls or STL. Implements the subset of Manifold the app uses."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, V: np.ndarray, F: np.ndarray, N: np.ndarray | None = None):
|
|
41
|
+
self.V = np.asarray(V, np.float64)
|
|
42
|
+
self.F = np.asarray(F, np.uint32)
|
|
43
|
+
self.N = N
|
|
44
|
+
|
|
45
|
+
def _new(self, V):
|
|
46
|
+
return RawMesh(V, self.F)
|
|
47
|
+
|
|
48
|
+
def is_empty(self):
|
|
49
|
+
return len(self.F) == 0
|
|
50
|
+
|
|
51
|
+
def bounding_box(self):
|
|
52
|
+
lo, hi = self.V.min(0), self.V.max(0)
|
|
53
|
+
return (*lo.tolist(), *hi.tolist())
|
|
54
|
+
|
|
55
|
+
def volume(self):
|
|
56
|
+
a, b, c = (self.V[self.F[:, i]] for i in range(3))
|
|
57
|
+
return float(abs(np.einsum("ij,ij->i", a, np.cross(b, c)).sum()) / 6.0)
|
|
58
|
+
|
|
59
|
+
def status(self):
|
|
60
|
+
return _Status()
|
|
61
|
+
|
|
62
|
+
def genus(self):
|
|
63
|
+
return -1
|
|
64
|
+
|
|
65
|
+
def num_tri(self):
|
|
66
|
+
return len(self.F)
|
|
67
|
+
|
|
68
|
+
def translate(self, t):
|
|
69
|
+
return self._new(self.V + np.asarray(t, np.float64))
|
|
70
|
+
|
|
71
|
+
def scale(self, s):
|
|
72
|
+
return self._new(self.V * np.asarray(s, np.float64))
|
|
73
|
+
|
|
74
|
+
def mirror(self, n):
|
|
75
|
+
n = np.asarray(n, np.float64)
|
|
76
|
+
n = n / (np.linalg.norm(n) or 1)
|
|
77
|
+
V = self.V - 2 * np.outer(self.V @ n, n)
|
|
78
|
+
return RawMesh(V, self.F[:, ::-1].copy())
|
|
79
|
+
|
|
80
|
+
def rotate(self, r):
|
|
81
|
+
rx, ry, rz = np.radians(np.asarray(r, np.float64))
|
|
82
|
+
cx, sx, cy, sy, cz, sz = np.cos(rx), np.sin(rx), np.cos(ry), np.sin(ry), np.cos(rz), np.sin(rz)
|
|
83
|
+
Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]])
|
|
84
|
+
Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]])
|
|
85
|
+
Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]])
|
|
86
|
+
return self._new(self.V @ (Rz @ Ry @ Rx).T) # X, then Y, then Z (manifold's order)
|
|
87
|
+
|
|
88
|
+
def calculate_normals(self, _idx=0, _angle=0.0):
|
|
89
|
+
a, b, c = (self.V[self.F[:, i]] for i in range(3))
|
|
90
|
+
fn = np.cross(b - a, c - a)
|
|
91
|
+
vn = np.stack([sum(np.bincount(self.F[:, i], fn[:, k], len(self.V)) for i in range(3))
|
|
92
|
+
for k in range(3)], axis=1)
|
|
93
|
+
vn /= np.linalg.norm(vn, axis=1, keepdims=True) + 1e-12
|
|
94
|
+
return RawMesh(self.V, self.F, vn)
|
|
95
|
+
|
|
96
|
+
def to_mesh(self):
|
|
97
|
+
vp = self.V if self.N is None else np.hstack([self.V, self.N])
|
|
98
|
+
return _RawMeshData(vp.astype(np.float32), self.F)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def load_asset(base: Path | None, rel: str):
|
|
102
|
+
if base is None:
|
|
103
|
+
raise EvalError("mesh assets need a project folder (open the program from disk)")
|
|
104
|
+
path = (base / rel).resolve()
|
|
105
|
+
if base.resolve() not in path.parents:
|
|
106
|
+
raise EvalError("mesh asset must live inside the project folder")
|
|
107
|
+
if not path.exists():
|
|
108
|
+
raise EvalError(f"mesh asset {rel} not found")
|
|
109
|
+
d = np.load(path)
|
|
110
|
+
V, F = np.asarray(d["V"], np.float32), np.asarray(d["F"], np.uint32)
|
|
111
|
+
try:
|
|
112
|
+
m = Manifold(Mesh(vert_properties=np.ascontiguousarray(V), tri_verts=np.ascontiguousarray(F)))
|
|
113
|
+
if not m.is_empty() and m.status().name == "NoError":
|
|
114
|
+
return m
|
|
115
|
+
except Exception: # noqa: BLE001 - any failure means "not a manifold": fall back to the raw mesh
|
|
116
|
+
pass
|
|
117
|
+
return RawMesh(V, F)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _segs(p: dict, default: int = 64) -> int:
|
|
121
|
+
n = int(p.get("segments", default))
|
|
122
|
+
if not 3 <= n <= 512:
|
|
123
|
+
raise EvalError("segments must be 3..512") # millions of segments hang or crash the kernel
|
|
124
|
+
return n
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _vec3(v, name: str, positive: bool = False) -> list[float]:
|
|
128
|
+
if isinstance(v, (int, float)):
|
|
129
|
+
v = [v] * 3
|
|
130
|
+
if not (isinstance(v, (list, tuple)) and len(v) == 3):
|
|
131
|
+
raise EvalError(f"{name} must be a number or [x, y, z]")
|
|
132
|
+
out = [float(x) for x in v]
|
|
133
|
+
if not all(math.isfinite(x) for x in out):
|
|
134
|
+
raise EvalError(f"{name} must be finite numbers, got {v}")
|
|
135
|
+
if positive and min(out) <= 0:
|
|
136
|
+
raise EvalError(f"{name} must be greater than 0 on every axis, got {v}")
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _pos(p: dict, key: str, default: float | None = None) -> float:
|
|
141
|
+
v = float(p[key] if key in p else default)
|
|
142
|
+
if not math.isfinite(v) or v <= 0:
|
|
143
|
+
raise EvalError(f"{key} must be a positive finite number, got {p.get(key, default)}")
|
|
144
|
+
return v
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _poly(points, name: str) -> list[list[float]]:
|
|
148
|
+
if not isinstance(points, list) or len(points) < 3:
|
|
149
|
+
raise EvalError(f"{name} needs at least 3 [x, y] points")
|
|
150
|
+
out = []
|
|
151
|
+
for pt in points:
|
|
152
|
+
if not (isinstance(pt, (list, tuple)) and len(pt) == 2):
|
|
153
|
+
raise EvalError(f"{name}: every point is [x, y]")
|
|
154
|
+
out.append([float(pt[0]), float(pt[1])])
|
|
155
|
+
if not np.isfinite(out).all():
|
|
156
|
+
raise EvalError(f"{name} must hold finite numbers")
|
|
157
|
+
return out
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _axis_index(axis) -> int:
|
|
161
|
+
"""'x'/'y'/'z' or an axis-aligned vector like [0, 0, 1] (models write both)."""
|
|
162
|
+
if isinstance(axis, str) and axis.lower().lstrip("+-") in ("x", "y", "z"):
|
|
163
|
+
return "xyz".index(axis.lower().lstrip("+-"))
|
|
164
|
+
if isinstance(axis, (list, tuple)) and len(axis) == 3:
|
|
165
|
+
a = [abs(float(v)) for v in axis]
|
|
166
|
+
if sorted(a)[:2] == [0.0, 0.0] and max(a) > 0:
|
|
167
|
+
return a.index(max(a))
|
|
168
|
+
raise EvalError("axis must be x, y, z or an axis-aligned vector like [0, 1, 0]")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _place(m: Manifold, p: dict) -> Manifold:
|
|
172
|
+
if "scale" in p:
|
|
173
|
+
m = m.scale(_vec3(p["scale"], "scale"))
|
|
174
|
+
if "rotate" in p:
|
|
175
|
+
m = m.rotate(_vec3(p["rotate"], "rotate"))
|
|
176
|
+
if "translate" in p:
|
|
177
|
+
m = m.translate(_vec3(p["translate"], "translate"))
|
|
178
|
+
return m
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
EXT_PRIMITIVES: dict = {}
|
|
182
|
+
EXT_MODIFIERS: dict = {}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# "center": false puts the base on the origin instead of the middle (OpenSCAD's convention, which models know)
|
|
186
|
+
BASE_LIFT = {"cylinder": lambda p: float(p["height"]) / 2, "tube": lambda p: float(p["height"]) / 2,
|
|
187
|
+
"capsule": lambda p: float(p["height"]) / 2 + float(p["radius"])}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def build_primitive(kind: str, p: dict, base: Path | None = None) -> Manifold:
|
|
191
|
+
m = _build_primitive(kind, p, base)
|
|
192
|
+
if kind in BASE_LIFT and p.get("center", True) is False:
|
|
193
|
+
m = m.translate((0.0, BASE_LIFT[kind](p), 0.0))
|
|
194
|
+
return m
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _build_primitive(kind: str, p: dict, base: Path | None = None) -> Manifold:
|
|
198
|
+
if kind in EXT_PRIMITIVES:
|
|
199
|
+
return EXT_PRIMITIVES[kind][2](p)
|
|
200
|
+
if kind == "mesh":
|
|
201
|
+
return load_asset(base, str(p["asset"]))
|
|
202
|
+
if kind == "box":
|
|
203
|
+
return Manifold.cube(_vec3(p["size"], "size", positive=True), center=bool(p.get("center", True)))
|
|
204
|
+
if kind == "cylinder":
|
|
205
|
+
r0 = _pos(p, "radius")
|
|
206
|
+
r1 = float(p.get("radius_top", r0))
|
|
207
|
+
if not math.isfinite(r1) or r1 < 0 or r0 == r1 == 0:
|
|
208
|
+
raise EvalError("cylinder radius_top must be >= 0 (0 makes a cone)")
|
|
209
|
+
return Manifold.cylinder(_pos(p, "height"), r0, r1, _segs(p), center=True).rotate(Z_TO_Y)
|
|
210
|
+
if kind == "sphere":
|
|
211
|
+
return Manifold.sphere(_pos(p, "radius"), _segs(p))
|
|
212
|
+
if kind == "torus":
|
|
213
|
+
R, r = _pos(p, "major_radius"), _pos(p, "minor_radius")
|
|
214
|
+
if r >= R:
|
|
215
|
+
raise EvalError("torus minor_radius must be smaller than major_radius")
|
|
216
|
+
circle = CrossSection.circle(r, _segs(p, 32)).translate((R, 0.0))
|
|
217
|
+
return Manifold.revolve(circle, _segs(p)).rotate(Z_TO_Y)
|
|
218
|
+
if kind == "capsule":
|
|
219
|
+
h, r = _pos(p, "height"), _pos(p, "radius")
|
|
220
|
+
a = Manifold.sphere(r, _segs(p)).translate((0, -h / 2, 0))
|
|
221
|
+
b = Manifold.sphere(r, _segs(p)).translate((0, h / 2, 0))
|
|
222
|
+
return Manifold.batch_hull([a, b])
|
|
223
|
+
if kind == "extrude":
|
|
224
|
+
polys = [_poly(p["points"], "points")] + [_poly(h, "holes") for h in p.get("holes", [])]
|
|
225
|
+
cs = CrossSection(polys)
|
|
226
|
+
st = p.get("scale_top", [1.0, 1.0])
|
|
227
|
+
st = [float(st)] * 2 if isinstance(st, (int, float)) else [float(st[0]), float(st[1])]
|
|
228
|
+
h = _pos(p, "height")
|
|
229
|
+
if not abs(float(p.get("twist", 0))) <= 3600:
|
|
230
|
+
raise EvalError("extrude twist must be within +-3600 degrees")
|
|
231
|
+
m = Manifold.extrude(cs, h, n_divisions=int(abs(float(p.get("twist", 0))) // 10),
|
|
232
|
+
twist_degrees=float(p.get("twist", 0.0)), scale_top=st)
|
|
233
|
+
m = m.translate((0, 0, -h / 2))
|
|
234
|
+
axis = p.get("axis", "y")
|
|
235
|
+
if axis not in AXIS_ROT:
|
|
236
|
+
raise EvalError("extrude axis must be x, y or z")
|
|
237
|
+
return m.rotate(AXIS_ROT[axis])
|
|
238
|
+
if kind == "revolve":
|
|
239
|
+
# points are [radius, height] pairs, a lathe profile around the Y axis
|
|
240
|
+
pts = _poly(p["points"], "points")
|
|
241
|
+
if any(x < 0 for x, _ in pts):
|
|
242
|
+
raise EvalError("revolve points are [radius, height]; radius must be >= 0")
|
|
243
|
+
if max(x for x, _ in pts) <= 0:
|
|
244
|
+
raise EvalError("revolve profile lies on the axis; give some points a radius > 0 (points are "
|
|
245
|
+
"[radius, height] pairs)")
|
|
246
|
+
deg = float(p.get("degrees", 360.0))
|
|
247
|
+
if not 0 < deg <= 360:
|
|
248
|
+
raise EvalError("revolve degrees must be in (0, 360]")
|
|
249
|
+
return Manifold.revolve(CrossSection([pts]), _segs(p), deg).rotate(Z_TO_Y)
|
|
250
|
+
raise EvalError(f"unknown primitive {kind}")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def build_modifier(kind: str, p: dict, m: Manifold) -> Manifold:
|
|
254
|
+
if kind in EXT_MODIFIERS:
|
|
255
|
+
_need_manifold(m, kind)
|
|
256
|
+
return EXT_MODIFIERS[kind][2](p, m)
|
|
257
|
+
if kind == "transform":
|
|
258
|
+
return m
|
|
259
|
+
if kind != "array":
|
|
260
|
+
_need_manifold(m, kind)
|
|
261
|
+
elif isinstance(m, RawMesh):
|
|
262
|
+
raise EvalError("array needs a closed solid; this imported mesh is not watertight")
|
|
263
|
+
if kind == "array":
|
|
264
|
+
mode, n = p["mode"], int(p["count"])
|
|
265
|
+
if n < 1 or n > 256:
|
|
266
|
+
raise EvalError("array count must be 1..256")
|
|
267
|
+
if mode == "linear":
|
|
268
|
+
off = _vec3(p.get("offset", [10, 0, 0]), "offset")
|
|
269
|
+
parts = [m.translate([off[0] * i, off[1] * i, off[2] * i]) for i in range(n)]
|
|
270
|
+
elif mode == "radial":
|
|
271
|
+
ang = float(p.get("angle", 360.0))
|
|
272
|
+
step = ang / n if ang >= 360 else ang / max(n - 1, 1)
|
|
273
|
+
idx = _axis_index(p.get("axis", "y"))
|
|
274
|
+
parts = []
|
|
275
|
+
for i in range(n):
|
|
276
|
+
r = [0.0, 0.0, 0.0]
|
|
277
|
+
r[idx] = step * i
|
|
278
|
+
parts.append(m.rotate(r))
|
|
279
|
+
else: # mirror: the original plus its reflection
|
|
280
|
+
normal = _vec3(p.get("plane", [1, 0, 0]), "plane")
|
|
281
|
+
parts = [m, m.mirror(normal)]
|
|
282
|
+
return Manifold.batch_boolean(parts, OpType.Add)
|
|
283
|
+
if kind == "smooth":
|
|
284
|
+
levels = int(p.get("levels", 2))
|
|
285
|
+
if levels < 1 or levels > 4:
|
|
286
|
+
raise EvalError("smooth levels must be 1..4")
|
|
287
|
+
return m.smooth_out(float(p.get("sharp_angle", 60.0))).refine(2 ** levels)
|
|
288
|
+
if kind in ("round", "shell"):
|
|
289
|
+
return _offset_modifier(kind, p, m)
|
|
290
|
+
raise EvalError(f"unknown modifier {kind}")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _erode(m: Manifold, r: float, segments: int) -> Manifold:
|
|
294
|
+
"""m pulled in by r on every side: the complement inside a padded box, grown by r, and taken back out."""
|
|
295
|
+
lo, hi = np.array(m.bounding_box()[:3]), np.array(m.bounding_box()[3:])
|
|
296
|
+
box = Manifold.cube((hi - lo + 6 * r).tolist()).translate((lo - 3 * r).tolist())
|
|
297
|
+
return box - (box - m).minkowski_sum(Manifold.sphere(r, segments))
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _offset_modifier(kind: str, p: dict, m: Manifold) -> Manifold:
|
|
301
|
+
"""round: erode then grow back (a morphological opening), so convex edges are rounded by `radius` and the part
|
|
302
|
+
keeps its size; anything thinner than 2 x radius disappears. shell: m minus its own inward offset, an even wall
|
|
303
|
+
whatever the shape."""
|
|
304
|
+
key = "radius" if kind == "round" else "thickness"
|
|
305
|
+
r = float(p[key])
|
|
306
|
+
if not math.isfinite(r) or r <= 0:
|
|
307
|
+
raise EvalError(f"{kind} {key} must be a positive number")
|
|
308
|
+
size = np.array(m.bounding_box()[3:]) - np.array(m.bounding_box()[:3])
|
|
309
|
+
if r * 2 >= size.min():
|
|
310
|
+
raise EvalError(f"{kind} {key} {r:g} must be under half the smallest size ({size.min() / 2:g})")
|
|
311
|
+
eroded = _erode(m, r, _segs(p, 12))
|
|
312
|
+
if eroded.is_empty():
|
|
313
|
+
raise EvalError(f"{kind} {key} {r:g} is too large for this shape: it has parts thinner than {2 * r:g}")
|
|
314
|
+
if kind == "shell":
|
|
315
|
+
return m - eroded
|
|
316
|
+
return eroded.minkowski_sum(Manifold.sphere(r, _segs(p, 12)))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _need_manifold(m, what: str):
|
|
320
|
+
if isinstance(m, RawMesh):
|
|
321
|
+
raise EvalError(f"{what} needs a closed solid; this imported mesh is not watertight (show, move and explode "
|
|
322
|
+
"work, CSG does not)")
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def build_combiner(kind: str, p: dict, ms: list[Manifold]) -> Manifold:
|
|
326
|
+
for m in ms:
|
|
327
|
+
_need_manifold(m, kind)
|
|
328
|
+
if kind == "boolean":
|
|
329
|
+
op = {"union": OpType.Add, "difference": OpType.Subtract, "intersection": OpType.Intersect}[p["mode"]]
|
|
330
|
+
return Manifold.batch_boolean(ms, op)
|
|
331
|
+
if kind == "hull":
|
|
332
|
+
return Manifold.batch_hull(ms)
|
|
333
|
+
if kind == "group":
|
|
334
|
+
return Manifold.compose(ms)
|
|
335
|
+
raise EvalError(f"unknown combiner {kind}")
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
@dataclass
|
|
339
|
+
class Shape:
|
|
340
|
+
id: str
|
|
341
|
+
label: str
|
|
342
|
+
part: str
|
|
343
|
+
material: str | None
|
|
344
|
+
manifold: Manifold
|
|
345
|
+
hash: str = ""
|
|
346
|
+
component: str = ""
|
|
347
|
+
|
|
348
|
+
def arrays(self) -> tuple[np.ndarray, np.ndarray]:
|
|
349
|
+
"""(positions float32 [n,3], indices uint32 [m,3]) for the viewport and exporters."""
|
|
350
|
+
mesh = self.manifold.to_mesh()
|
|
351
|
+
return np.asarray(mesh.vert_properties[:, :3], np.float32), np.asarray(mesh.tri_verts, np.uint32)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class Evaluator:
|
|
355
|
+
def __init__(self, base: Path | None = None):
|
|
356
|
+
self.base = base
|
|
357
|
+
self._cache: dict[str, Manifold] = {}
|
|
358
|
+
self.last_hits = 0
|
|
359
|
+
self.last_misses = 0
|
|
360
|
+
|
|
361
|
+
def run(self, program: dict) -> tuple[dict[str, Manifold], dict[str, str]]:
|
|
362
|
+
check(program)
|
|
363
|
+
out: dict[str, Manifold] = {}
|
|
364
|
+
hashes: dict[str, str] = {}
|
|
365
|
+
self.last_hits = self.last_misses = 0
|
|
366
|
+
for op in program["ops"]:
|
|
367
|
+
ins = op_inputs(op)
|
|
368
|
+
h = op_hash(op, [hashes[i] for i in ins])
|
|
369
|
+
hashes[op["id"]] = h
|
|
370
|
+
if h in self._cache:
|
|
371
|
+
out[op["id"]] = self._cache[h]
|
|
372
|
+
self.last_hits += 1
|
|
373
|
+
continue
|
|
374
|
+
self.last_misses += 1
|
|
375
|
+
kind, p = op["op"], op.get("params", {})
|
|
376
|
+
try:
|
|
377
|
+
if not ins:
|
|
378
|
+
m = build_primitive(kind, p, self.base)
|
|
379
|
+
elif kind in COMBINERS:
|
|
380
|
+
m = build_combiner(kind, p, [out[i] for i in ins])
|
|
381
|
+
else:
|
|
382
|
+
m = build_modifier(kind, p, out[ins[0]])
|
|
383
|
+
m = _place(m, p)
|
|
384
|
+
except EvalError as e:
|
|
385
|
+
raise EvalError(f"op {op['id']} ({kind}): {e}") from None
|
|
386
|
+
except (KeyError, TypeError, ValueError) as e:
|
|
387
|
+
raise EvalError(f"op {op['id']} ({kind}): bad params ({e})") from None
|
|
388
|
+
if m.is_empty():
|
|
389
|
+
raise EvalError(f"op {op['id']} ({kind}): result is empty (a difference removed everything, "
|
|
390
|
+
"or the shapes do not overlap)")
|
|
391
|
+
self._cache[h] = m
|
|
392
|
+
out[op["id"]] = m
|
|
393
|
+
return out, hashes
|
|
394
|
+
|
|
395
|
+
def trim(self, limit: int) -> None:
|
|
396
|
+
"""Bound the cache: drop the oldest results beyond `limit` (dicts keep insertion order)."""
|
|
397
|
+
extra = len(self._cache) - limit
|
|
398
|
+
if extra > 0:
|
|
399
|
+
for h in list(self._cache)[:extra]:
|
|
400
|
+
del self._cache[h]
|
|
401
|
+
|
|
402
|
+
def step(self, program: dict, k: int | None = None) -> list[Shape]:
|
|
403
|
+
"""The visible shapes after step k (0-based, inclusive). None = the finished build."""
|
|
404
|
+
ops = program["ops"]
|
|
405
|
+
k = len(ops) - 1 if k is None else max(0, min(k, len(ops) - 1))
|
|
406
|
+
sub = dict(program, ops=ops[: k + 1])
|
|
407
|
+
built, hashes = self.run(sub)
|
|
408
|
+
consumed = {i for op in sub["ops"] for i in op_inputs(op)}
|
|
409
|
+
# a leaf inherits material from its first input chain when it has none of its own
|
|
410
|
+
mat_of: dict[str, str | None] = {}
|
|
411
|
+
comp = component_map(sub)
|
|
412
|
+
for op in sub["ops"]:
|
|
413
|
+
ins = op_inputs(op)
|
|
414
|
+
mat_of[op["id"]] = op.get("material") or (mat_of.get(ins[0]) if ins else None)
|
|
415
|
+
return [Shape(op["id"], op.get("label", op["id"]), op.get("part", op["id"]), mat_of[op["id"]],
|
|
416
|
+
built[op["id"]], hashes[op["id"]], comp[op["id"]])
|
|
417
|
+
for op in sub["ops"] if op["id"] not in consumed]
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def bounds(shapes: list[Shape]) -> tuple[list[float], list[float]]:
|
|
421
|
+
lo = [math.inf] * 3
|
|
422
|
+
hi = [-math.inf] * 3
|
|
423
|
+
for s in shapes:
|
|
424
|
+
b = s.manifold.bounding_box()
|
|
425
|
+
lo = [min(lo[i], b[i]) for i in range(3)]
|
|
426
|
+
hi = [max(hi[i], b[i + 3]) for i in range(3)]
|
|
427
|
+
return lo, hi
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _register_extensions() -> None:
|
|
431
|
+
from . import ops_advanced, ops_engineering
|
|
432
|
+
from .program import register
|
|
433
|
+
prims = {**ops_advanced.PRIMITIVES, **ops_engineering.PRIMITIVES}
|
|
434
|
+
register(prims, ops_advanced.MODIFIERS)
|
|
435
|
+
EXT_PRIMITIVES.update(prims)
|
|
436
|
+
EXT_MODIFIERS.update(ops_advanced.MODIFIERS)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
_register_extensions()
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Explain: how the object on the floor works, as a short presentation where every sentence shows where it came from.
|
|
2
|
+
|
|
3
|
+
A sentence is one of three kinds, and the kind is checked here, not taken on the model's word:
|
|
4
|
+
|
|
5
|
+
cited a real-world fact. It names a source from the research lane, and it must share real vocabulary with the
|
|
6
|
+
excerpt it cites; a citation to a source that does not say it is thrown out.
|
|
7
|
+
measured a number from the geometry (sizes, counts). Every number in it must be one Replicator measured.
|
|
8
|
+
concept the model's reasoning about what a fictional design would do. Allowed only when the object is a concept,
|
|
9
|
+
and the presentation then opens with a notice saying so.
|
|
10
|
+
|
|
11
|
+
For a real object, a sentence that fails its check is dropped. For a concept it is kept but shown as concept, so a
|
|
12
|
+
fictional jet cannon still gets a full walkthrough without anything invented being passed off as a cited fact.
|
|
13
|
+
What this guarantees: no sentence is shown as cited without a matching source excerpt. What it cannot guarantee:
|
|
14
|
+
that the source itself is right, or that a paraphrase kept every nuance. The sources are listed for that reason.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
import time
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from ..research.lane import stems
|
|
24
|
+
|
|
25
|
+
MIN_SHARED = 3 # stems a cited sentence must share with its excerpt(s)
|
|
26
|
+
MIN_SHARE = 0.34 # ...or this fraction of its own vocabulary
|
|
27
|
+
WPM = 165 # reading speed used to time a chapter when no voice plays
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def rest_pose(shapes) -> str:
|
|
31
|
+
"""'flush' when the object has a real footprint to stand on, 'levitate' when it would only touch the floor
|
|
32
|
+
along a line or a point (a pod, an engine, a ball): those are shown floating, as a product display would."""
|
|
33
|
+
try:
|
|
34
|
+
V = np.vstack([s.arrays()[0] for s in shapes])
|
|
35
|
+
except (ValueError, AttributeError):
|
|
36
|
+
return "flush"
|
|
37
|
+
if len(V) < 8:
|
|
38
|
+
return "flush"
|
|
39
|
+
lo, hi = V.min(0), V.max(0)
|
|
40
|
+
h = max(hi[1] - lo[1], 1e-6)
|
|
41
|
+
foot = V[V[:, 1] <= lo[1] + 0.02 * h]
|
|
42
|
+
area = max((hi[0] - lo[0]) * (hi[2] - lo[2]), 1e-9)
|
|
43
|
+
if len(foot) < 3:
|
|
44
|
+
return "levitate"
|
|
45
|
+
f = (np.ptp(foot[:, 0]) * np.ptp(foot[:, 2])) / area
|
|
46
|
+
return "flush" if f >= 0.22 else "levitate"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def component_facts(comps, dims: list[float], units: str = "mm") -> list[dict]:
|
|
50
|
+
facts = [{"id": "", "what": "whole object", "size": [round(d, 1) for d in dims], "units": units,
|
|
51
|
+
"components": len(comps)}]
|
|
52
|
+
for c in comps:
|
|
53
|
+
facts.append({"id": c.id, "label": c.label, "role": c.role, "pieces": len(c.shapes),
|
|
54
|
+
"size": (c.hi - c.lo).round(1).tolist(), "center": c.center.round(1).tolist()})
|
|
55
|
+
return facts
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def at_a_glance(subject: str, comps, dims: list[float], units: str = "mm") -> dict:
|
|
59
|
+
"""The one chapter written by code: it only repeats measurements, so it is always right."""
|
|
60
|
+
size = " by ".join(f"{d:,.0f}" for d in dims)
|
|
61
|
+
biggest = max(comps, key=lambda c: float(np.prod(c.hi - c.lo)), default=None)
|
|
62
|
+
s = [{"kind": "measured", "text": f"{subject} measures {size} {units}.", "cite": []},
|
|
63
|
+
{"kind": "measured", "text": f"It is made of {len(comps)} component" + ("s." if len(comps) != 1 else "."),
|
|
64
|
+
"cite": []}]
|
|
65
|
+
if biggest is not None and len(comps) > 1:
|
|
66
|
+
s.append({"kind": "measured", "text": f"The largest is the {biggest.label}.", "cite": []})
|
|
67
|
+
return {"title": "At a glance", "component": "", "sentences": s}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _numbers(text: str) -> list[float]:
|
|
71
|
+
return [float(x.replace(",", "")) for x in re.findall(r"(?<![\w.])\d[\d,]*\.?\d*", text)]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def verify(raw: dict, sources: list[dict], facts: list[dict], force_concept: bool = False) -> dict:
|
|
75
|
+
"""Keep only what can be backed. Returns {concept, concept_note, chapters, dropped, relabelled}."""
|
|
76
|
+
concept = bool(raw.get("concept")) or force_concept
|
|
77
|
+
by_n = {s["n"]: stems(" ".join(s["excerpts"]) + " " + s["title"]) for s in sources}
|
|
78
|
+
known = set()
|
|
79
|
+
for f in facts:
|
|
80
|
+
for v in f.values():
|
|
81
|
+
for x in (v if isinstance(v, list) else [v]):
|
|
82
|
+
if isinstance(x, (int, float)) and not isinstance(x, bool):
|
|
83
|
+
known |= {round(float(x)), round(float(x), 1)}
|
|
84
|
+
ids = {f["id"] for f in facts}
|
|
85
|
+
dropped = relabelled = 0
|
|
86
|
+
chapters = []
|
|
87
|
+
for ch in raw.get("chapters", [])[:8]:
|
|
88
|
+
if not isinstance(ch, dict):
|
|
89
|
+
continue
|
|
90
|
+
out = []
|
|
91
|
+
for s in (ch.get("sentences") or [])[:5]:
|
|
92
|
+
if not isinstance(s, dict) or not str(s.get("text", "")).strip():
|
|
93
|
+
continue
|
|
94
|
+
text = re.sub(r"\s*\[\d+(?:,\s*\d+)*\]", "", str(s["text"]).strip())[:320]
|
|
95
|
+
kind = s.get("kind")
|
|
96
|
+
cites = [int(c) for c in (s.get("cite") or []) if isinstance(c, (int, float)) and int(c) in by_n]
|
|
97
|
+
ok = False
|
|
98
|
+
if kind == "cited" and cites:
|
|
99
|
+
mine = stems(text)
|
|
100
|
+
shared = len(mine & set().union(*(by_n[c] for c in cites)))
|
|
101
|
+
ok = shared >= MIN_SHARED or (mine and shared / len(mine) >= MIN_SHARE)
|
|
102
|
+
elif kind == "measured":
|
|
103
|
+
nums = _numbers(text)
|
|
104
|
+
ok = bool(nums) and all(round(x) in known or round(x, 1) in known for x in nums)
|
|
105
|
+
cites = []
|
|
106
|
+
elif kind == "concept":
|
|
107
|
+
ok, cites = concept, []
|
|
108
|
+
if not ok and concept and kind != "concept":
|
|
109
|
+
kind, cites, ok = "concept", [], True # kept, but shown as the design's intent
|
|
110
|
+
relabelled += 1
|
|
111
|
+
if ok:
|
|
112
|
+
out.append({"kind": kind, "text": text, "cite": cites})
|
|
113
|
+
else:
|
|
114
|
+
dropped += 1
|
|
115
|
+
if out:
|
|
116
|
+
comp = ch.get("component") or ""
|
|
117
|
+
chapters.append({"title": str(ch.get("title", "")).strip()[:60] or "Part",
|
|
118
|
+
"component": comp if comp in ids else "", "sentences": out})
|
|
119
|
+
return {"concept": concept, "concept_note": str(raw.get("concept_note", "")).strip()[:240],
|
|
120
|
+
"chapters": chapters, "dropped": dropped, "relabelled": relabelled}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def finish(subject: str, checked: dict, glance: dict, sources: list[dict], rest: str, engine: str) -> dict:
|
|
124
|
+
"""The explanation document saved beside the program and played by Present."""
|
|
125
|
+
chapters = [glance] + checked["chapters"]
|
|
126
|
+
used = {c for ch in chapters for s in ch["sentences"] for c in s["cite"]}
|
|
127
|
+
for ch in chapters:
|
|
128
|
+
text = " ".join(s["text"] for s in ch["sentences"])
|
|
129
|
+
ch["text"] = text
|
|
130
|
+
ch["seconds"] = round(max(4.0, len(text.split()) / WPM * 60 + 1.5), 1)
|
|
131
|
+
counts = {k: sum(1 for ch in chapters for s in ch["sentences"] if s["kind"] == k)
|
|
132
|
+
for k in ("cited", "measured", "concept")}
|
|
133
|
+
note = checked["concept_note"] or "This is a concept: a designed object, not a real product."
|
|
134
|
+
return {"subject": subject, "concept": checked["concept"],
|
|
135
|
+
"notice": ("Concept. " + note + " Real-world principles are cited; everything about this design itself "
|
|
136
|
+
"is the model's reasoning about what it would do.") if checked["concept"] else "",
|
|
137
|
+
"rest": rest, "chapters": chapters, "sources": [s for s in sources if s["n"] in used],
|
|
138
|
+
"sources_read": len(sources), "counts": counts, "dropped": checked["dropped"],
|
|
139
|
+
"relabelled": checked["relabelled"], "engine": engine, "made": time.strftime("%Y-%m-%d %H:%M")}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Export a build to GLB, OBJ, STL, 3MF (trimesh) or STEP (faceted B-rep, core/step.py). STL and 3MF are for printers: they refuse anything that is not
|
|
2
|
+
watertight (prints must not fail) and are written Z-up, the printer convention, so importing them back is lossless. With a printer given, print formats
|
|
3
|
+
are also refused when the build overflows its bed (core/fit.py), naming the overflow per axis; it is never clipped."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import trimesh
|
|
9
|
+
|
|
10
|
+
from . import fit
|
|
11
|
+
from .evaluate import Shape
|
|
12
|
+
from .printers import Printer
|
|
13
|
+
|
|
14
|
+
PRINT_FORMATS = ("stl", "3mf")
|
|
15
|
+
CAD_FORMATS = ("step", "stp")
|
|
16
|
+
FORMATS = ("glb", "gltf", "obj", *PRINT_FORMATS, *CAD_FORMATS)
|
|
17
|
+
Y_TO_Z_UP = trimesh.transformations.rotation_matrix(1.5707963267948966, [1, 0, 0])
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _material(spec: dict | None, name: str) -> trimesh.visual.material.PBRMaterial:
|
|
21
|
+
spec = spec or {}
|
|
22
|
+
c = list(spec.get("base_color", [0.7, 0.7, 0.72]))
|
|
23
|
+
a = min(max(float(spec.get("opacity", 1.0)), 0.0), 1.0) # glass and clear panels: glTF alpha blend
|
|
24
|
+
return trimesh.visual.material.PBRMaterial(
|
|
25
|
+
name=name, baseColorFactor=[*c[:3], a], metallicFactor=float(spec.get("metalness", 0.0)),
|
|
26
|
+
roughnessFactor=float(spec.get("roughness", 0.5)), alphaMode="BLEND" if a < 1.0 else None)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def to_scene(shapes: list[Shape], materials: dict) -> trimesh.Scene:
|
|
30
|
+
scene = trimesh.Scene()
|
|
31
|
+
made: dict[str, trimesh.visual.material.PBRMaterial] = {}
|
|
32
|
+
for s in shapes:
|
|
33
|
+
v, f = s.arrays()
|
|
34
|
+
mesh = trimesh.Trimesh(v, f, process=False)
|
|
35
|
+
name = s.material or "default"
|
|
36
|
+
if name not in made:
|
|
37
|
+
made[name] = _material(materials.get(s.material), name)
|
|
38
|
+
mesh.visual = trimesh.visual.TextureVisuals(material=made[name])
|
|
39
|
+
scene.add_geometry(mesh, node_name=s.id, geom_name=s.part)
|
|
40
|
+
return scene
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _printable(shapes: list[Shape], fmt: str) -> None:
|
|
44
|
+
bad = [s.id for s in shapes if s.manifold.status().name != "NoError"]
|
|
45
|
+
if bad:
|
|
46
|
+
raise ValueError(f"{fmt.upper()} needs closed solids; these parts are open surfaces or broken: {bad}. "
|
|
47
|
+
"Imported surfaces are shown and moved but cannot be printed; export GLB instead")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _gate_bed(shapes: list[Shape], units: str, printer: Printer) -> None:
|
|
51
|
+
"""Refuse a build that overflows the printer's bed, naming every axis and how much, and the replica
|
|
52
|
+
scale that would fit it. The as-built factor, because the file stands as built and cannot be rotated."""
|
|
53
|
+
r = fit.check(shapes, units, printer)
|
|
54
|
+
if r.fits:
|
|
55
|
+
return
|
|
56
|
+
over = ", ".join(f"{ax} by {v:.1f} mm" for ax, v in zip(fit.AXES, r.overflow) if v > 0)
|
|
57
|
+
s = fit.scale_to_fit(shapes, units, printer, allow_rotate=False).scale
|
|
58
|
+
raise ValueError(f"{printer.name} ({printer.id}): the build is {r.size[0]:.1f} x {r.size[1]:.1f} x "
|
|
59
|
+
f"{r.size[2]:.1f} mm but only {r.usable[0]:.1f} x {r.usable[1]:.1f} x {r.usable[2]:.1f} mm "
|
|
60
|
+
f"is usable; it overflows {over}. A {s:.3f}x replica would fit")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _print_file(shapes: list[Shape], materials: dict, fmt: str, path: Path) -> None:
|
|
64
|
+
_printable(shapes, fmt)
|
|
65
|
+
scene = to_scene(shapes, materials)
|
|
66
|
+
scene.apply_transform(Y_TO_Z_UP)
|
|
67
|
+
if fmt == "3mf": # one object per part, named, so a slicer can colour and arrange them
|
|
68
|
+
scene.export(path)
|
|
69
|
+
return
|
|
70
|
+
merged = scene.to_geometry()
|
|
71
|
+
if not merged.is_watertight:
|
|
72
|
+
raise ValueError("parts touch along an edge or face so the combined mesh is not watertight; "
|
|
73
|
+
"union them with a boolean, or separate them")
|
|
74
|
+
merged.export(path)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def export(shapes: list[Shape], materials: dict, path: str | Path, name: str = "", units: str = "mm",
|
|
78
|
+
printer: Printer | None = None) -> Path:
|
|
79
|
+
path = Path(path)
|
|
80
|
+
fmt = path.suffix.lower().lstrip(".")
|
|
81
|
+
if fmt not in FORMATS:
|
|
82
|
+
raise ValueError(f"unsupported format {fmt or path.name}; use one of {', '.join(FORMATS)}")
|
|
83
|
+
if not shapes:
|
|
84
|
+
raise ValueError("nothing to export: the build has no visible parts")
|
|
85
|
+
if fmt in CAD_FORMATS:
|
|
86
|
+
from . import step
|
|
87
|
+
step.write(shapes, path, name=name or path.stem, units=units)
|
|
88
|
+
elif fmt in PRINT_FORMATS:
|
|
89
|
+
if printer is not None:
|
|
90
|
+
_gate_bed(shapes, units, printer)
|
|
91
|
+
_print_file(shapes, materials, fmt, path)
|
|
92
|
+
elif fmt == "obj":
|
|
93
|
+
to_scene(shapes, materials).export(path, mtl_name=f"{path.stem}.mtl")
|
|
94
|
+
else:
|
|
95
|
+
to_scene(shapes, materials).export(path)
|
|
96
|
+
return path
|