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.
Files changed (118) hide show
  1. replicator/__init__.py +6 -0
  2. replicator/app.py +204 -0
  3. replicator/config.py +48 -0
  4. replicator/core/__init__.py +0 -0
  5. replicator/core/assembly.py +117 -0
  6. replicator/core/blender_link.py +161 -0
  7. replicator/core/critique.py +594 -0
  8. replicator/core/drawing.py +389 -0
  9. replicator/core/dxf.py +120 -0
  10. replicator/core/evaluate.py +439 -0
  11. replicator/core/explain.py +139 -0
  12. replicator/core/export.py +96 -0
  13. replicator/core/fit.py +170 -0
  14. replicator/core/importers.py +185 -0
  15. replicator/core/materials.py +104 -0
  16. replicator/core/ops_advanced.py +496 -0
  17. replicator/core/ops_engineering.py +223 -0
  18. replicator/core/physics.py +147 -0
  19. replicator/core/printers.py +100 -0
  20. replicator/core/program.py +298 -0
  21. replicator/core/render.py +145 -0
  22. replicator/core/reverse.py +350 -0
  23. replicator/core/robot.py +153 -0
  24. replicator/core/step.py +245 -0
  25. replicator/fixtures/gaming_pc_liquid.json +2259 -0
  26. replicator/fixtures/gas_generator_rocket.json +876 -0
  27. replicator/fixtures/gas_generator_rocket_aero.json +861 -0
  28. replicator/fixtures/house_two_bed.json +979 -0
  29. replicator/fixtures/quadcopter_drone.json +687 -0
  30. replicator/fixtures/raspberry_pi_5.json +884 -0
  31. replicator/fixtures/rocket_engine.json +652 -0
  32. replicator/fixtures/turbofan.json +931 -0
  33. replicator/fixtures/vector_engine.json +314 -0
  34. replicator/gpu.py +81 -0
  35. replicator/image3d/__init__.py +0 -0
  36. replicator/image3d/comfy.py +181 -0
  37. replicator/image3d/pipeline.py +208 -0
  38. replicator/image3d/sheet.py +154 -0
  39. replicator/knowledge/__init__.py +61 -0
  40. replicator/knowledge/car_wheel_corner.md +21 -0
  41. replicator/knowledge/desk_lamp.md +21 -0
  42. replicator/knowledge/desktop_pc.md +20 -0
  43. replicator/knowledge/electronics_board.md +21 -0
  44. replicator/knowledge/exoskeleton.md +21 -0
  45. replicator/knowledge/house.md +22 -0
  46. replicator/knowledge/light_aircraft.md +22 -0
  47. replicator/knowledge/multirotor_drone.md +25 -0
  48. replicator/knowledge/print_replica.md +13 -0
  49. replicator/knowledge/rocket_engine.md +27 -0
  50. replicator/knowledge/turbofan.md +23 -0
  51. replicator/llm/__init__.py +0 -0
  52. replicator/llm/client.py +424 -0
  53. replicator/llm/prompts/blueprint.md +28 -0
  54. replicator/llm/prompts/edit.md +15 -0
  55. replicator/llm/prompts/explain.md +37 -0
  56. replicator/llm/prompts/name_parts.md +13 -0
  57. replicator/llm/prompts/program.md +72 -0
  58. replicator/llm/prompts/research_queries.md +8 -0
  59. replicator/mcp_server.py +307 -0
  60. replicator/qml/Main.qml +874 -0
  61. replicator/qml/Replicator/UI/Chip.qml +17 -0
  62. replicator/qml/Replicator/UI/DockHeader.qml +27 -0
  63. replicator/qml/Replicator/UI/Icon.qml +118 -0
  64. replicator/qml/Replicator/UI/IconButton.qml +31 -0
  65. replicator/qml/Replicator/UI/Kbd.qml +18 -0
  66. replicator/qml/Replicator/UI/NumField.qml +69 -0
  67. replicator/qml/Replicator/UI/Pill.qml +28 -0
  68. replicator/qml/Replicator/UI/RCombo.qml +51 -0
  69. replicator/qml/Replicator/UI/RMenu.qml +42 -0
  70. replicator/qml/Replicator/UI/RSlider.qml +23 -0
  71. replicator/qml/Replicator/UI/Segmented.qml +63 -0
  72. replicator/qml/Replicator/UI/Swatch.qml +47 -0
  73. replicator/qml/Replicator/UI/Theme.qml +149 -0
  74. replicator/qml/Replicator/UI/qmldir +14 -0
  75. replicator/qml/panels/AgentPrompt.qml +53 -0
  76. replicator/qml/panels/AttributeManager.qml +171 -0
  77. replicator/qml/panels/Commander.qml +136 -0
  78. replicator/qml/panels/HolodeckPanel.qml +117 -0
  79. replicator/qml/panels/IssuesCard.qml +78 -0
  80. replicator/qml/panels/LedgerPanel.qml +110 -0
  81. replicator/qml/panels/MaterialShelf.qml +97 -0
  82. replicator/qml/panels/ObjectManager.qml +107 -0
  83. replicator/qml/panels/Preferences.qml +211 -0
  84. replicator/qml/panels/Presenter.qml +316 -0
  85. replicator/qml/panels/StatusBar.qml +77 -0
  86. replicator/qml/panels/Timeline.qml +149 -0
  87. replicator/qml/panels/Welcome.qml +126 -0
  88. replicator/qml/viewport/Callouts.qml +87 -0
  89. replicator/qml/viewport/EdgeMaterial.qml +16 -0
  90. replicator/qml/viewport/GridMaterial.qml +16 -0
  91. replicator/qml/viewport/HoloMaterial.qml +23 -0
  92. replicator/qml/viewport/NavGizmo.qml +72 -0
  93. replicator/qml/viewport/ReferenceMaterial.qml +17 -0
  94. replicator/qml/viewport/Viewport.qml +583 -0
  95. replicator/qt/__init__.py +0 -0
  96. replicator/qt/bridge.py +1427 -0
  97. replicator/qt/drawing_sheet.py +33 -0
  98. replicator/qt/envmap.py +40 -0
  99. replicator/qt/library.py +68 -0
  100. replicator/qt/mesh_geometry.py +167 -0
  101. replicator/qt/svg.py +41 -0
  102. replicator/research/__init__.py +0 -0
  103. replicator/research/lane.py +281 -0
  104. replicator/shaders/edge.frag +9 -0
  105. replicator/shaders/edge.vert +7 -0
  106. replicator/shaders/grid.frag +52 -0
  107. replicator/shaders/grid.vert +6 -0
  108. replicator/shaders/holo.frag +41 -0
  109. replicator/shaders/reference.frag +15 -0
  110. replicator/shaders/reference.vert +6 -0
  111. replicator/voice.py +120 -0
  112. replicator_workshop-0.1.0.dist-info/METADATA +410 -0
  113. replicator_workshop-0.1.0.dist-info/RECORD +118 -0
  114. replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
  115. replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
  116. replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
  117. replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
  118. replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,594 @@
1
+ """Accuracy critic: measured checks that catch the ways a local model gets an assembly wrong.
2
+
3
+ A program can be valid and still be a bad build: a ring spun around the wrong axis, a part floating in the air, a
4
+ pump buried inside the casing where nobody can see it. Every check here measures the built geometry, so an issue is
5
+ an observation, not an opinion. `fix` issues go back to the model on a critique round; `warn` issues are shown.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import asdict, dataclass
11
+
12
+ import numpy as np
13
+
14
+ from .assembly import Component
15
+ from .evaluate import Evaluator, RawMesh, Shape, _axis_index
16
+ from .program import op_inputs
17
+ from .physics import properties
18
+ from .. import knowledge
19
+
20
+ AXISYM = {"cylinder", "tube", "torus", "revolve", "nozzle", "rotor", "capsule", "gear", "helix"}
21
+ CLIP_SHARE = 0.25 # overlap, as a share of the smaller part, that reads as parts passing through each other
22
+ BURIED_SHARE = 0.95
23
+ SIZE_WARN = 0.15 # built size off the blueprint by more than this on any axis: shown
24
+ SIZE_FIX = 0.40 # by more than this: goes back to the model (the lamp that came out twice its planned size)
25
+ STOP = {"the", "and", "with", "for", "assembly", "set", "main", "unit", "part", "parts", "system", "section"}
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Issue:
30
+ kind: str
31
+ severity: str # "fix" | "warn"
32
+ subject: str # component id, or "" for the whole object
33
+ message: str
34
+
35
+ def as_dict(self) -> dict:
36
+ return asdict(self)
37
+
38
+
39
+ @dataclass
40
+ class Build:
41
+ program: dict
42
+ shapes: list[Shape]
43
+ comps: list[Component]
44
+
45
+ @property
46
+ def size(self) -> np.ndarray:
47
+ lo = np.min([c.lo for c in self.comps], axis=0)
48
+ hi = np.max([c.hi for c in self.comps], axis=0)
49
+ return hi - lo
50
+
51
+ def label(self, cid: str) -> str:
52
+ return next((c.label for c in self.comps if c.id == cid), cid)
53
+
54
+
55
+ def _solid(s: Shape) -> bool:
56
+ return not isinstance(s.manifold, RawMesh)
57
+
58
+
59
+ def _box(s: Shape) -> tuple[np.ndarray, np.ndarray]:
60
+ b = s.manifold.bounding_box()
61
+ return np.array(b[:3]), np.array(b[3:])
62
+
63
+
64
+ def _gap(alo, ahi, blo, bhi) -> float:
65
+ return float(np.linalg.norm(np.maximum(0.0, np.maximum(alo - bhi, blo - ahi))))
66
+
67
+
68
+ def _boxes(shapes: list[Shape]) -> tuple[np.ndarray, np.ndarray]:
69
+ bb = np.array([s.manifold.bounding_box() for s in shapes], dtype=np.float64).reshape(-1, 6)
70
+ return bb[:, :3], bb[:, 3:]
71
+
72
+
73
+ def floating(b: Build) -> list[Issue]:
74
+ if len(b.comps) < 2:
75
+ return []
76
+ tol = 0.01 * float(np.linalg.norm(b.size))
77
+ lo, hi = np.array([c.lo for c in b.comps]), np.array([c.hi for c in b.comps])
78
+ d = np.maximum(0.0, np.maximum(lo[:, None, :] - hi[None, :, :], lo[None, :, :] - hi[:, None, :]))
79
+ gap = np.linalg.norm(d, axis=2)
80
+ np.fill_diagonal(gap, np.inf)
81
+ out = []
82
+ for i, c in enumerate(b.comps):
83
+ j = int(np.argmin(gap[i]))
84
+ if gap[i, j] > tol:
85
+ out.append(Issue("floating", "fix", c.id, f"{c.label} floats free: it touches no other part "
86
+ f"(nearest is {b.comps[j].label}, {gap[i, j]:.0f} {b.program.get('units', 'mm')} away). "
87
+ "Move it until it is attached."))
88
+ return out
89
+
90
+
91
+ def _grown(s: Shape, tol: float) -> Shape:
92
+ lo, hi = _box(s)
93
+ c, size = (lo + hi) / 2, np.maximum(hi - lo, 1e-9)
94
+ return Shape(s.id, s.label, s.part, s.material, s.manifold.translate((-c).tolist()).scale(((size + 2 * tol) / size).tolist()).translate(c.tolist()), s.hash, s.component)
95
+
96
+
97
+ def cavity_floating(b: Build) -> list[Issue]:
98
+ """A part whose bounding box sits inside another part's box passes the box test even when it hangs loose in a
99
+ hollow body; grow it by the contact tolerance and test the real solids."""
100
+ if len(b.comps) < 2:
101
+ return []
102
+ tol = 0.01 * float(np.linalg.norm(b.size))
103
+ by_comp: dict[str, list[Shape]] = {}
104
+ for s in b.shapes:
105
+ if _solid(s):
106
+ by_comp.setdefault(s.component, []).append(s)
107
+ lo, hi = np.array([c.lo for c in b.comps]), np.array([c.hi for c in b.comps])
108
+ inside = np.all(lo[:, None, :] >= lo[None, :, :] - tol, axis=2) & np.all(hi[:, None, :] <= hi[None, :, :] + tol, axis=2)
109
+ np.fill_diagonal(inside, False)
110
+ out = []
111
+ for i, c in enumerate(b.comps):
112
+ mine = by_comp.get(c.id)
113
+ if not mine or not inside[i].any():
114
+ continue
115
+ host = b.comps[int(np.argmax(inside[i]))]
116
+ grown = [_grown(s, tol) for s in mine]
117
+ others = [(_box(t), t) for o in b.comps if o is not c for t in by_comp.get(o.id, [])]
118
+ touches = any(_gap(*_box(g), *tb) == 0.0 and (g.manifold ^ t.manifold).volume() > 0
119
+ for g in grown for tb, t in others)
120
+ if not touches:
121
+ out.append(Issue("floating", "fix", c.id, f"{c.label} hangs loose inside {host.label}: it touches "
122
+ "nothing, so it would fall to the bottom of the cavity. Attach it with a bracket or "
123
+ "move it against a wall."))
124
+ return out
125
+
126
+
127
+ def _pairs(b: Build):
128
+ solids = [s for s in b.shapes if _solid(s)]
129
+ if len(solids) < 2:
130
+ return
131
+ lo, hi = _boxes(solids)
132
+ vol = np.array([s.manifold.volume() for s in solids])
133
+ comp = np.array([s.component for s in solids])
134
+ for i in range(len(solids) - 1):
135
+ j = np.arange(i + 1, len(solids))
136
+ inter = np.minimum(hi[i], hi[j]) - np.maximum(lo[i], lo[j])
137
+ touch = np.all(inter >= 0.0, axis=1) & (comp[j] != comp[i])
138
+ cap = np.prod(np.maximum(inter, 0.0), axis=1)
139
+ keep = touch & (cap >= CLIP_SHARE * np.minimum(vol[i], vol[j]))
140
+ for k in j[keep]:
141
+ yield solids[i], solids[k]
142
+
143
+
144
+ PLUGS = {"pipe", "capsule"}
145
+ PLUG_WORDS = re.compile(r"\b(duct|line|pipe|hose|shaft|strut|rod|pin|bolt|inlet|outlet|axle|spindle|tube)s?\b", re.I)
146
+ SLENDER = 4.0
147
+
148
+
149
+ def _plugs_in(b_ops: dict, small: Shape, big: Shape) -> bool:
150
+ """Pipes, shafts and struts are meant to run into the part they connect: that overlap is contact, not clipping."""
151
+ if b_ops.get(small.id, {}).get("op") in PLUGS or b_ops.get(big.id, {}).get("op") in PLUGS:
152
+ return True
153
+ if PLUG_WORDS.search(small.label) or PLUG_WORDS.search(big.label):
154
+ return True
155
+ lo, hi = _box(small)
156
+ d = np.sort(hi - lo)
157
+ return bool(d[2] >= SLENDER * max(d[1], 1e-9))
158
+
159
+
160
+ def overlaps(b: Build) -> list[Issue]:
161
+ out, buried = [], set()
162
+ ops = {o["id"]: o for o in b.program["ops"]}
163
+ for s, t in _pairs(b):
164
+ shared = (s.manifold ^ t.manifold).volume()
165
+ if shared <= 0:
166
+ continue
167
+ small, big = (s, t) if s.manifold.volume() <= t.manifold.volume() else (t, s)
168
+ share = shared / max(small.manifold.volume(), 1e-9)
169
+ if share >= BURIED_SHARE and small.component not in buried:
170
+ buried.add(small.component)
171
+ out.append(Issue("buried", "fix", small.component, f"{small.label} is buried inside {big.label} "
172
+ f"({share:.0%} of it is inside solid material) and can never be seen. Hollow "
173
+ f"{big.label} or move the part out."))
174
+ elif CLIP_SHARE <= share < BURIED_SHARE and not _plugs_in(ops, small, big):
175
+ out.append(Issue("clipping", "warn", small.component, f"{small.label} passes through {big.label} "
176
+ f"({share:.0%} of it overlaps)."))
177
+ return out
178
+
179
+
180
+ COPY_OVERLAP = 0.15
181
+ THIN_WALL = 0.001
182
+
183
+
184
+ def _closure(ops: dict, oid: str) -> list[dict]:
185
+ seen: list[str] = []
186
+
187
+ def walk(i: str):
188
+ for j in op_inputs(ops[i]):
189
+ walk(j)
190
+ if i not in seen:
191
+ seen.append(i)
192
+ walk(oid)
193
+ return [ops[i] for i in seen]
194
+
195
+
196
+ def array_copies(b: Build) -> list[Issue]:
197
+ """The copies of an array should sit apart; copies that interpenetrate fuse into one lump (a radial array whose
198
+ source is on the axis stacks every copy in the same place)."""
199
+ ops = {o["id"]: o for o in b.program["ops"]}
200
+ out = []
201
+ for s in b.shapes:
202
+ op = ops.get(s.id, {})
203
+ p = op.get("params", {})
204
+ if op.get("op") != "array" or not _solid(s) or "scale" in p or len(op_inputs(op)) != 1:
205
+ continue
206
+ n = 2 if p.get("mode") == "mirror" else int(p.get("count", 1))
207
+ if n < 2:
208
+ continue
209
+ try:
210
+ src = Evaluator().step({**{k: b.program[k] for k in ("units", "materials") if k in b.program},
211
+ "version": 1, "ops": _closure(ops, op_inputs(op)[0])})
212
+ except Exception: # noqa: BLE001 - a broken source is reported by the build, not here
213
+ continue
214
+ if not src or not _solid(src[-1]):
215
+ continue
216
+ lost = 1.0 - s.manifold.volume() / (n * src[-1].manifold.volume())
217
+ if lost > COPY_OVERLAP:
218
+ out.append(Issue("array_overlap", "fix", s.component, f"The {n} copies in {s.label} overlap each other "
219
+ f"({lost:.0%} of their volume is shared). Increase the offset or angle, or move the "
220
+ "source off the pivot."))
221
+ return out
222
+
223
+
224
+ def thin_wall(b: Build) -> list[Issue]:
225
+ """A hollow body whose wall is a sliver next to its size will not render, print or survive a load."""
226
+ out = []
227
+ for o in b.program["ops"]:
228
+ p = o.get("params", {})
229
+ if o.get("op") != "tube" or not isinstance(p.get("wall"), (int, float)):
230
+ continue
231
+ reach = max(float(p.get("radius", 0)), float(p.get("radius_top", 0)), float(p.get("height", 0)) / 2)
232
+ if reach > 0 and p["wall"] < THIN_WALL * reach:
233
+ out.append(Issue("thin_wall", "warn", next((s.component for s in b.shapes if s.id == o["id"]), ""),
234
+ f"{o.get('label', o['id'])} has a {p['wall']:g} {b.program.get('units', 'mm')} wall on a "
235
+ f"body {reach:.0f} across: a sliver. Make the wall at least {THIN_WALL * reach:.1f}."))
236
+ return out
237
+
238
+
239
+ def _rot_matrix(op: dict) -> np.ndarray:
240
+ rot = op.get("params", {}).get("rotate", [0, 0, 0])
241
+ if isinstance(rot, (int, float)):
242
+ rot = [rot] * 3
243
+ rx, ry, rz = np.radians(rot)
244
+ cx, sx, cy, sy, cz, sz = np.cos(rx), np.sin(rx), np.cos(ry), np.sin(ry), np.cos(rz), np.sin(rz)
245
+ Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]])
246
+ Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]])
247
+ Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]])
248
+ return Rz @ Ry @ Rx
249
+
250
+
251
+ def _axis(op: dict) -> np.ndarray:
252
+ return _rot_matrix(op) @ np.array([0.0, 1.0, 0.0])
253
+
254
+
255
+ def off_axis(b: Build) -> list[Issue]:
256
+ """A ring, casing or rotor that sits on the body's centre line must spin around the same axis as the body."""
257
+ ops = {o["id"]: o for o in b.program["ops"]}
258
+ sym = [s for s in b.shapes if ops.get(s.id, {}).get("op") in AXISYM and _solid(s)]
259
+ if len(sym) < 2:
260
+ return []
261
+ body = max(sym, key=lambda s: s.manifold.volume())
262
+ axis = _axis(ops[body.id])
263
+ lo, hi = _box(body)
264
+ centre, reach = (lo + hi) / 2, 0.5 * float(np.max(hi - lo))
265
+ out = []
266
+ for s in sym:
267
+ if s is body:
268
+ continue
269
+ slo, shi = _box(s)
270
+ d = (slo + shi) / 2 - centre
271
+ off_line = float(np.linalg.norm(d - np.dot(d, axis) * axis))
272
+ a = _axis(ops[s.id])
273
+ if off_line < 0.1 * reach and abs(float(np.dot(a, axis))) < 0.94:
274
+ name = "XYZ"[int(np.argmax(np.abs(axis)))]
275
+ out.append(Issue("off_axis", "fix", s.component, f"{s.label} sits on the centre line of {body.label} but "
276
+ f"spins around a different axis; {body.label} runs along {name}. Rotate it to match."))
277
+ return out
278
+
279
+
280
+ def array_axis(b: Build) -> list[Issue]:
281
+ """A full-circle radial array is a ring: it must spin about the axis of the body it wraps, and about that
282
+ body's centre line. A ring spun about a sideways axis scatters its copies off the body (the turbofan whose
283
+ blades turned around world Y while the engine ran along Z)."""
284
+ ops = {o["id"]: o for o in b.program["ops"]}
285
+ out = []
286
+ for o in b.program["ops"]:
287
+ p = o.get("params", {})
288
+ if o.get("op") != "array" or p.get("mode") != "radial" or float(p.get("angle", 360.0)) < 360:
289
+ continue
290
+ ins = op_inputs(o)
291
+ if len(ins) != 1:
292
+ continue
293
+ top = {k: b.program[k] for k in ("units", "materials") if k in b.program}
294
+ try:
295
+ src = Evaluator().step({**top, "version": 1, "ops": _closure(ops, ins[0])})
296
+ except Exception: # noqa: BLE001 - a broken source is reported by the build, not here
297
+ continue
298
+ if not src or not _solid(src[-1]):
299
+ continue
300
+ bb = np.array(src[-1].manifold.bounding_box())
301
+ centre = (bb[:3] + bb[3:]) / 2
302
+ bodies = []
303
+ for s in b.shapes:
304
+ if s.id == o["id"] or not _solid(s) or ops.get(s.id, {}).get("op") not in AXISYM:
305
+ continue
306
+ lo, hi = _box(s)
307
+ m = 0.05 * float(np.max(np.maximum(hi - lo, 1e-9)))
308
+ if np.all(centre >= lo - m) and np.all(centre <= hi + m):
309
+ bodies.append(s)
310
+ if not bodies:
311
+ continue
312
+ body = max(bodies, key=lambda s: s.manifold.volume())
313
+ axis = _axis(ops[body.id])
314
+ unit = np.zeros(3)
315
+ unit[_axis_index(p.get("axis", "y"))] = 1.0
316
+ spin = _rot_matrix(o) @ unit
317
+ if abs(float(np.dot(spin, axis))) < 0.94:
318
+ label, subject = o.get("label") or o["id"], o.get("component") or o.get("part") or o["id"]
319
+ out.append(Issue("off_axis", "fix", subject, f"{label} spins around "
320
+ f"{'XYZ'[int(np.argmax(np.abs(spin)))]} but {body.label} runs along "
321
+ f"{'XYZ'[int(np.argmax(np.abs(axis)))]}; array it about "
322
+ f"{'XYZ'[int(np.argmax(np.abs(axis)))]} and move the array onto the body's centre line."))
323
+ continue
324
+ if "translate" not in p:
325
+ continue # no placement: the ring spins about the world axis, already tested
326
+ blo, bhi = _box(body)
327
+ centre_b, reach = (blo + bhi) / 2, 0.5 * float(np.max(bhi - blo))
328
+ d = np.asarray(p["translate"], dtype=float) - centre_b
329
+ off = float(np.linalg.norm(d - np.dot(d, axis) * axis))
330
+ if off > 0.1 * reach:
331
+ label, subject = o.get("label") or o["id"], o.get("component") or o.get("part") or o["id"]
332
+ out.append(Issue("off_axis", "fix", subject,
333
+ f"{label} spins around a line {off:.0f} {b.program.get('units', 'mm')} off "
334
+ f"{body.label}'s centre line. Move the array's pivot onto the body's centre line."))
335
+ return out
336
+
337
+
338
+ ALIGNED = re.compile(r"\b(?:along|aligned with|parallel to|parallel with)\s+(?:the\s+|each\s+)?")
339
+
340
+
341
+ def _name_tokens(s: str) -> list[str]:
342
+ return [w for w in re.sub(r"[^a-z]+", " ", s.lower()).split() if len(w) > 1 and not w.isdigit()]
343
+
344
+
345
+ def _principal(s: Shape) -> tuple[np.ndarray, float] | None:
346
+ """The shape's principal direction (first SVD vector of its centred vertices) and its elevation in degrees.
347
+ None when the shape is stocky (elongation under 2), for which no direction is meaningful."""
348
+ pts = np.asarray(s.arrays()[0], dtype=np.float64)
349
+ if len(pts) < 3:
350
+ return None
351
+ c = pts - pts.mean(0)
352
+ _, sv, vt = np.linalg.svd(c, full_matrices=False)
353
+ if sv[1] <= 0 or sv[0] / sv[1] < 2.0:
354
+ return None
355
+ d = vt[0]
356
+ return d, float(np.degrees(np.arcsin(min(1.0, abs(float(d[1]))))))
357
+
358
+
359
+ def alignment(b: Build) -> list[Issue]:
360
+ """Parts the plan says run along another part (a spring along its arm) must actually point the same way."""
361
+ parts = [p for p in (b.program.get("blueprint") or {}).get("parts") or []
362
+ if isinstance(p, dict) and str(p.get("name", ""))]
363
+ names: dict[tuple[str, ...], str] = {}
364
+ for p in parts:
365
+ toks = _name_tokens(str(p["name"]))
366
+ if toks and tuple(toks) not in names:
367
+ names[tuple(toks)] = str(p["name"])
368
+ out = []
369
+ seen = set()
370
+ for p in parts:
371
+ subject = str(p["name"])
372
+ text = " ".join(str(p.get(k) or "") for k in ("role", "position")).lower()
373
+ for m in ALIGNED.finditer(text):
374
+ words = _name_tokens(text[m.end():])
375
+ target = None
376
+ for n in range(min(4, len(words)), 0, -1):
377
+ target = names.get(tuple(words[:n]))
378
+ if target:
379
+ break
380
+ if not target or target == subject or (subject, target) in seen:
381
+ continue
382
+ seen.add((subject, target))
383
+ sub = [s for s in b.shapes if _solid(s) and s.part == subject]
384
+ tgt = [s for s in b.shapes if _solid(s) and s.part == target]
385
+ su = next((d for d in (_principal(s) for s in sub) if d), None)
386
+ tu = next((d for d in (_principal(s) for s in tgt) if d), None)
387
+ if not su or not tu:
388
+ continue
389
+ off = float(np.degrees(np.arccos(min(1.0, abs(float(np.dot(su[0], tu[0])))))))
390
+ if off > 20:
391
+ s_label = next((s.label for s in sub if s.label), subject)
392
+ t_label = next((s.label for s in tgt if s.label), target)
393
+ out.append(Issue("alignment", "fix", next((s.component for s in sub if s.component), ""),
394
+ f"{s_label} should run along {t_label} (the plan says so) "
395
+ f"but sits {off:.0f} degrees off it."))
396
+ return out
397
+
398
+
399
+ _HEAD_NOUN_DROP = {"left", "right", "front", "rear", "upper", "lower", "inner", "outer", "a", "b", "source"}
400
+
401
+
402
+ def _head_noun(label: str) -> str:
403
+ words = [w for w in ("".join(ch for ch in t.lower() if ch.isalpha()) for t in label.split()) if w]
404
+ for w in reversed(words):
405
+ if w not in _HEAD_NOUN_DROP:
406
+ return w
407
+ return ""
408
+
409
+
410
+ def card_rules(b: Build) -> list[Issue]:
411
+ """Knowledge cards state how a kind of object is really proportioned (a balanced lamp's arm rises steeply);
412
+ every built shape named for one of the card's parts must sit inside the card's stated range."""
413
+ bp = b.program.get("blueprint") or {}
414
+ text = " ".join(str(bp.get(k) or "") for k in ("title", "summary")) + " " + str(b.program.get("name") or "")
415
+ out = []
416
+ for card in knowledge.pick(text):
417
+ for rise in card.rises:
418
+ for s in b.shapes:
419
+ if not _solid(s) or _head_noun(s.label) != rise.word:
420
+ continue
421
+ r = _principal(s)
422
+ if r is None:
423
+ continue
424
+ elev = r[1]
425
+ if not rise.lo <= elev <= rise.hi:
426
+ out.append(Issue("proportion", "fix", s.component,
427
+ f"{s.label} rises {elev:.0f} degrees; a {card.title.lower()}'s {rise.word} "
428
+ f"rises {rise.lo:.0f} to {rise.hi:.0f} degrees (knowledge card). "
429
+ + ("Tilt it up." if elev < rise.lo else "Tilt it down.")))
430
+ return out
431
+
432
+
433
+ def size(b: Build) -> list[Issue]:
434
+ want = (b.program.get("blueprint") or {}).get("dimensions")
435
+ if not (isinstance(want, list) and len(want) == 3 and all(isinstance(v, (int, float)) and v > 0 for v in want)):
436
+ return []
437
+ got = b.size
438
+ share = [abs(got[i] - want[i]) / want[i] for i in range(3)]
439
+ off = [i for i in range(3) if share[i] > SIZE_WARN]
440
+ if not off:
441
+ return []
442
+ fmt = lambda v: " x ".join(f"{x:.0f}" for x in v) # noqa: E731
443
+ worst = max(share)
444
+ axes = ", ".join(f"{'XYZ'[i]} {'+' if got[i] > want[i] else '-'}{share[i]:.0%}" for i in off)
445
+ return [Issue("size", "fix" if worst > SIZE_FIX else "warn", "",
446
+ f"Built {fmt(got)} but the blueprint plans {fmt(want)} ({axes}). Scale the parts that "
447
+ "overshoot, or correct the plan if the build is right.")]
448
+
449
+
450
+ ROOF_WORDS = ("roof",)
451
+ PITCHED = re.compile(r"\b(gable|gabled|pitched|hip|hipped|ridge|saltbox|a-frame|mansard)\b")
452
+ BUTTERFLY = re.compile(r"\b(butterfly|v-shaped|inverted)\b")
453
+ ANGLE = re.compile(r"(\d{1,2}(?:\.\d+)?)\s*(?:°|deg\b|degrees?\b)")
454
+
455
+
456
+ def _named(s: Shape, words: tuple[str, ...]) -> bool:
457
+ text = f"{s.id} {s.label} {s.part} {s.component}".lower()
458
+ return any(w in text for w in words)
459
+
460
+
461
+ def _union(shapes: list[Shape]):
462
+ out = shapes[0].manifold
463
+ for s in shapes[1:]:
464
+ out = out + s.manifold
465
+ return out
466
+
467
+
468
+ def roof(b: Build) -> list[Issue]:
469
+ """For a building: does the roof cover the walls, sit on them, and have the shape and pitch the plan asks for?
470
+ Heights come from slicing the roof with thin vertical slabs at the middle and near both ends of each side."""
471
+ from .drawing import is_building
472
+ solid = [s for s in b.shapes if _solid(s)]
473
+ roofs = [s for s in solid if _named(s, ROOF_WORDS)]
474
+ if not roofs:
475
+ return []
476
+ lo, hi = _boxes(solid)
477
+ if not is_building(lo.min(0), hi.max(0), b.program.get("units", "mm")):
478
+ return []
479
+ walls = [s for s in solid if _named(s, ("wall",)) and s not in roofs] or [s for s in solid if s not in roofs]
480
+ wlo, whi = _boxes(walls)
481
+ wlo, whi = wlo.min(0), whi.max(0)
482
+ top = float(whi[1])
483
+ shell = _union(roofs)
484
+ rlo, rhi = _boxes(roofs)
485
+ span_lo, span_hi = np.minimum(rlo.min(0), wlo) - 1.0, np.maximum(rhi.max(0), whi) + 1.0
486
+ from manifold3d import Manifold
487
+
488
+ def heights(axis: int, at: float) -> tuple[float, float] | None:
489
+ """(lowest, highest) roof y on a vertical slab across the building at `axis` = `at`, or None if bare. The slab
490
+ stays inside the walls on the other side, so eaves hanging past the walls do not count as dipping."""
491
+ inset = (whi - wlo) * 0.03
492
+ lo_, hi_ = np.maximum(span_lo, wlo + inset), np.minimum(span_hi, whi - inset)
493
+ lo_[1], hi_[1] = span_lo[1], span_hi[1]
494
+ size, centre = hi_ - lo_, (hi_ + lo_) / 2
495
+ size[axis] = max((whi[axis] - wlo[axis]) * 0.01, 1e-3)
496
+ centre[axis] = at
497
+ bb = (shell ^ Manifold.cube(size.tolist(), True).translate(centre.tolist())).bounding_box()
498
+ return None if not np.all(np.isfinite(bb)) or bb[4] < bb[1] else (float(bb[1]), float(bb[4]))
499
+
500
+ roof_text = " ".join(f"{s.label} {s.part}" for s in roofs)
501
+ bp = b.program.get("blueprint") or {}
502
+ for part in bp.get("parts") or []:
503
+ if isinstance(part, dict) and "roof" in str(part.get("name", "")).lower():
504
+ roof_text += f" {part.get('name', '')} {part.get('role', '')} {part.get('shape', '')}"
505
+ intent = (roof_text + " " + str(bp.get("summary", ""))).lower()
506
+ wants_pitch = bool(PITCHED.search(intent)) and not BUTTERFLY.search(intent)
507
+ out: list[Issue] = []
508
+ label = roofs[0].label or "The roof"
509
+ profile, lows = {}, []
510
+ for axis in (0, 2):
511
+ w = float(whi[axis] - wlo[axis])
512
+ mid = float((whi[axis] + wlo[axis]) / 2)
513
+ samples = {"middle": mid, "one end": float(wlo[axis]) + 0.06 * w, "the other end": float(whi[axis]) - 0.06 * w}
514
+ h = {k: heights(axis, v) for k, v in samples.items()}
515
+ bare = [k for k, v in h.items() if v is None]
516
+ if bare:
517
+ out.append(Issue("roof", "fix", roofs[0].component, f"{label} leaves the walls uncovered along "
518
+ f"{'XYZ'[axis]} ({', '.join(bare)}): the roof spans {rlo.min(0)[axis]:.0f} to "
519
+ f"{rhi.max(0)[axis]:.0f} but the walls run {wlo[axis]:.0f} to {whi[axis]:.0f}."))
520
+ continue
521
+ lows.append(min(v[0] for v in h.values()))
522
+ profile[axis] = (h["middle"][1], max(h["one end"][1], h["the other end"][1]),
523
+ min(h["one end"][1], h["the other end"][1]), 0.44 * w)
524
+ if out or len(profile) < 2:
525
+ return out
526
+ rises = {a: (mid - edge_hi) / run for a, (mid, edge_hi, _, run) in profile.items()}
527
+ valleys = {a: (edge_lo - mid) / run for a, (mid, _, edge_lo, run) in profile.items()}
528
+ ridge = max(rises, key=rises.get)
529
+ if wants_pitch and any(v > 0.05 for v in valleys.values()):
530
+ a = max(valleys, key=valleys.get)
531
+ return [Issue("roof", "fix", roofs[0].component, f"{label} is low in the middle and high at the eaves along "
532
+ f"{'XYZ'[a]} (a V), but the plan asks for a pitched roof: each slope must rise toward the "
533
+ "ridge, so flip the panel's tilt.")]
534
+ low = min(lows)
535
+ if low < top - 0.08 * (top - float(wlo[1])): # after the shape test: "a V, flip it" says more than "too low"
536
+ return [Issue("roof", "fix", roofs[0].component, f"{label} dips to {low:.0f}, below the wall tops at "
537
+ f"{top:.0f}: it cuts down into the rooms.")]
538
+ if wants_pitch and rises[ridge] < 0.05:
539
+ return [Issue("roof", "fix", roofs[0].component, f"{label} is flat, but the plan asks for a pitched roof.")]
540
+ stated = ANGLE.search(intent)
541
+ if wants_pitch and stated:
542
+ pitch = float(np.degrees(np.arctan(rises[ridge])))
543
+ if abs(pitch - float(stated.group(1))) > 10:
544
+ out.append(Issue("roof", "warn", roofs[0].component, f"{label} pitches at about {pitch:.0f} degrees "
545
+ f"across {'XYZ'[ridge]}; the plan says {stated.group(1)}."))
546
+ return out
547
+
548
+
549
+ def _words(s: str) -> list[str]:
550
+ out = []
551
+ for w in re.findall(r"[a-z]+", s.lower()):
552
+ if len(w) >= 3 and w not in STOP:
553
+ out.append((w[:-1] if len(w) > 3 and w.endswith("s") and not w.endswith("ss") else w)[:6])
554
+ return out
555
+
556
+
557
+ def missing(b: Build) -> list[Issue]:
558
+ """A listed part counts as built when its head noun, or at least half of its words, appears in a part name."""
559
+ parts = (b.program.get("blueprint") or {}).get("parts") or []
560
+ have = set(_words(" ".join([c.label for c in b.comps] + [o.get("label", "") for o in b.program["ops"]])))
561
+ out = []
562
+ for p in parts:
563
+ name = str(p.get("name", "")) if isinstance(p, dict) else ""
564
+ words = _words(name)
565
+ if not words:
566
+ continue
567
+ hit = [w in have for w in words]
568
+ if not (hit[-1] and sum(hit) * 2 >= len(words)):
569
+ out.append(Issue("missing", "warn", "", f"The blueprint lists {name}, but no part is named for it."))
570
+ return out
571
+
572
+
573
+ def stability(b: Build) -> list[Issue]:
574
+ m = properties(b.program, [s for s in b.shapes if _solid(s)])
575
+ if m.stands is False:
576
+ return [Issue("tips", "fix", "", f"It would tip over: the centre of gravity ({m.kg:.1f} kg at "
577
+ f"x {m.cg[0]:.0f}, z {m.cg[2]:.0f}) lies outside the footprint on the floor. Widen the base, "
578
+ "move mass over it, or add a stand.")]
579
+ return []
580
+
581
+
582
+ CHECKS = (floating, cavity_floating, overlaps, array_copies, thin_wall, off_axis, array_axis, alignment,
583
+ card_rules, size, missing, stability, roof)
584
+
585
+
586
+ def critique(program: dict, shapes: list[Shape], comps: list[Component]) -> list[Issue]:
587
+ if not shapes or not comps:
588
+ return []
589
+ b = Build(program, shapes, comps)
590
+ return [i for check in CHECKS for i in check(b)]
591
+
592
+
593
+ def blocking(issues: list[Issue]) -> list[Issue]:
594
+ return [i for i in issues if i.severity == "fix"]