bambu-printer-mcp 1.1.93 → 1.1.95

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 (41) hide show
  1. package/README.md +6 -3
  2. package/dist/3mf_parser.js +3 -2
  3. package/dist/cad/contracts.d.ts +10 -0
  4. package/dist/cad/contracts.js +41 -1
  5. package/dist/cad-engine.d.ts +5 -0
  6. package/dist/cad-engine.js +74 -3
  7. package/dist/counterpart/diagnostics.d.ts +163 -0
  8. package/dist/counterpart/diagnostics.js +816 -0
  9. package/dist/counterpart/flight-tools.d.ts +2 -2
  10. package/dist/counterpart/info.js +1 -0
  11. package/dist/counterpart/make-3mf.d.ts +10 -0
  12. package/dist/counterpart/make-3mf.js +472 -65
  13. package/dist/counterpart/model-plates.d.ts +8 -1
  14. package/dist/counterpart/model-plates.js +9 -4
  15. package/dist/counterpart/plate-filaments.d.ts +19 -0
  16. package/dist/counterpart/plate-filaments.js +72 -10
  17. package/dist/counterpart/remote.js +1 -0
  18. package/dist/counterpart/schemas.d.ts +8 -2
  19. package/dist/counterpart/schemas.js +1 -0
  20. package/dist/index.js +100 -2
  21. package/dist/tool-annotations.js +1 -0
  22. package/package.json +2 -2
  23. package/src/3mf_parser.ts +3 -2
  24. package/src/cad/contracts.ts +46 -1
  25. package/src/cad/examples/desk_clamp_hook.py +32 -0
  26. package/src/cad/examples/desk_edge_cable_holder.py +24 -0
  27. package/src/cad/examples/phone_stand.py +26 -0
  28. package/src/cad/geometry.py +52 -2
  29. package/src/cad/project3mf.py +426 -0
  30. package/src/cad/purpose.py +492 -0
  31. package/src/cad/worker.py +17 -2
  32. package/src/cad-engine.ts +73 -3
  33. package/src/counterpart/diagnostics.ts +775 -0
  34. package/src/counterpart/info.ts +1 -0
  35. package/src/counterpart/make-3mf.ts +446 -61
  36. package/src/counterpart/model-plates.ts +17 -5
  37. package/src/counterpart/plate-filaments.ts +75 -7
  38. package/src/counterpart/remote.ts +1 -0
  39. package/src/counterpart/schemas.ts +3 -0
  40. package/src/index.ts +83 -2
  41. package/src/tool-annotations.ts +1 -0
@@ -0,0 +1,492 @@
1
+ """What a design is for, compiled into requirements the engine evaluates on the design as it is used (scan-to-make #608).
2
+
3
+ The council of 2026-11-11 found that the engine verified only what the designer wrote down: nothing could say "faces
4
+ the driver" or "the mount carries the phone's moment", so a phone holder square to the cabin on a 30 mm strip passed.
5
+ Here the script states its purpose as a literal PURPOSE = {...} (read from the source, never run, never overridden by
6
+ parameters); a small product-class table adds the requirements its words imply; and use() returns the part as it is
7
+ used, with what it holds (held:<name>) and what it meets (world:<name>). The forces and moments at each mount are
8
+ computed from that geometry, never supplied. cad_run records final only when every requirement passes.
9
+ """
10
+ import ast
11
+ import math
12
+ import re
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ KINDS = ('tape', 'rests', 'screw', 'clamp', 'hook', 'other')
18
+ G = 9.81
19
+ DENSITY = {'pla': 1.24, 'petg': 1.27, 'abs': 1.04, 'asa': 1.07, 'tpu': 1.21, 'pc': 1.20, 'pa': 1.14, 'nylon': 1.14}
20
+ # The product classes a purpose's words put it in, and what each class requires whatever the designer lists.
21
+ HOLDER = re.compile(r'\b(holders?|hooks?|hangers?|stands?|docks?|mounts?|racks?|shel(f|ves)|brackets?|cradles?|caddy|caddies|organi[sz]ers?|holsters?)\b', re.I)
22
+ VEHICLE = re.compile(r'\b(cars?|trucks?|vans?|dash|dashboard|vents?|windshield|windscreen|vehicles?|bikes?|bicycles?|handlebars?|scooters?|motorcycles?|strollers?|boats?)\b', re.I)
23
+ SCREEN = re.compile(r'\b(phones?|iphones?|smartphones?|tablets?|ipads?|screens?|displays?|monitors?|kindles?|e-?readers?)\b', re.I)
24
+ # 3M VHB static shear holds 1000 g on 0.5 in^2 for 10,000 min at 22 C and 500 g at 93 C (about 30 and 15 kPa); 3M
25
+ # publishes no sustained tension rating, so the same figure bounds sustained tension. 3M's VHB structural glazing
26
+ # guide designs short-term loads (wind) to 85 kPa (12 psi). Check: a 50 mm disc under a 230 g phone 60 mm out reads
27
+ # about 11 kPa sustained, and a 5 N press over its ball almost nothing, as the bought mounts that work would.
28
+ TAPE_SUSTAINED_KPA = {'vehicle': 15.0, 'indoor': 30.0}
29
+ TAPE_SHORT_KPA = 85.0
30
+ FRICTION = 0.4 # printed plastic, or its pads, resting on wood, laminate or painted metal
31
+ TOUCH_MM = 0.5 # a held object within this of the part sits on it
32
+ PATCH_MM = 0.2 # part surface within this of a world body is in contact with it
33
+ SPLIT_MM = 1.0 # a face straddling a world body's edge is split to pieces this long, and the pieces on the body count
34
+ SPLIT_PIECES = 200_000 # at most this many pieces over the body at once, so a huge contact stays bounded (the rest is left out)
35
+ INSIDE_MM = TOUCH_MM # a held body may sink this far into the part (its volume inside over half its surface there) and still sit on it
36
+ INSIDE_MM3 = 1.0 # and an overlap below this is a boolean sliver where faces meet, not a body inside the part
37
+ INSIDE_SHARE = 0.5 # more than this share of a held body inside the part is buried, however thin (a 0.3 mm photo in a slab)
38
+ SAME_SHAPE = 0.02 # use()'s part matches build()'s within this fraction: volume, surface area and each principal moment
39
+ HELD_DENSITY = (0.03, 8.0) # g/cm^3: a paper-towel roll is about 0.09, expanded foam 0.02 to 0.03, steel tools under 8; outside it the held body is not the object
40
+ FLAT = 0.9 # a patch whose mean normal is shorter than this is not one plane
41
+ WORLD_AREA = 3.0 # a tape or rest surface reaches this many times the contact's area in its plane
42
+ WORLD_DEPTH_MM = 3.0 # and at least this far behind it
43
+
44
+
45
+ def read(script):
46
+ """PURPOSE from the script's source: (dict, None), (None, None) when absent, (None, error) when malformed."""
47
+ try:
48
+ tree = ast.parse(Path(script).read_text())
49
+ except (OSError, SyntaxError, ValueError) as e:
50
+ return None, f'the script could not be read ({type(e).__name__})'
51
+ found = [n for n in tree.body if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'PURPOSE' for t in n.targets)]
52
+ if not found:
53
+ return None, None
54
+ if len(found) > 1:
55
+ return None, 'declare exactly one top-level PURPOSE'
56
+ try:
57
+ value = ast.literal_eval(found[0].value)
58
+ except ValueError:
59
+ return None, 'PURPOSE must be a literal dictionary (no names or calls)'
60
+ return (value, None) if isinstance(value, dict) else (None, 'PURPOSE must be a dictionary')
61
+
62
+
63
+ def compile_purpose(p):
64
+ """The requirements a purpose implies: [(name, problem or None)] plus the load settings to evaluate."""
65
+ text = str(p.get('for') or '')
66
+ bodies = [e.get('body') for key in ('holds', 'mounts') for e in (p.get(key) if isinstance(p.get(key), list) else [p.get(key)]) if isinstance(e, dict) and isinstance(e.get('body'), str)]
67
+ words = ' '.join([text, str(p.get('modelled_on') or '')] + bodies).replace('_', ' ') # what it is, read from everything that names it
68
+ classes = [c for c, rx in (('holder', HOLDER), ('vehicle', VEHICLE), ('screen', SCREEN)) if rx.search(words)]
69
+ out, req = {'classes': classes}, []
70
+ req.append(('for', None if text.strip() else 'PURPOSE["for"] is missing: say who uses it, where, doing what, in the person\'s words'))
71
+ req.append(('modelled_on', None if str(p.get('modelled_on') or '').strip() else 'PURPOSE["modelled_on"] is missing: name the bought product the design follows'))
72
+ holds = p.get('holds') or []
73
+ mounts = p.get('mounts') or []
74
+ holds = holds if isinstance(holds, list) else [holds]
75
+ mounts = mounts if isinstance(mounts, list) else [mounts]
76
+ good_hold = lambda h: isinstance(h, dict) and isinstance(h.get('body'), str) and isinstance(h.get('mass_g'), (int, float)) and not isinstance(h.get('mass_g'), bool) and h['mass_g'] > 0
77
+ bad = [h for h in holds if not good_hold(h)]
78
+ for h in bad:
79
+ named = isinstance(h, dict) and isinstance(h.get('body'), str)
80
+ req.append(('holds', f'The {h["body"]} in PURPOSE["holds"] needs its real mass: give "mass_g" in grams, more than 0' if named
81
+ else 'Write each PURPOSE["holds"] entry as {"body": name, "mass_g": grams}'))
82
+ good_mount = lambda m: isinstance(m, dict) and isinstance(m.get('body'), str) and m.get('by') in KINDS
83
+ bad = [m for m in mounts if not good_mount(m)]
84
+ if bad:
85
+ req.append(('mounts', 'each PURPOSE["mounts"] entry is {"body": name, "by": one of ' + ', '.join(KINDS) + '}'))
86
+ if holds and any(good_mount(m) and m['by'] == 'other' for m in mounts):
87
+ req.append(('mounts', 'A mount that carries a held body must say how it holds: in PURPOSE["mounts"] pick the nearest real kind: tape, rests, screw, clamp or hook (not "other")'))
88
+ if 'holder' in classes and not holds:
89
+ req.append(('holds', f'"{text[:60]}" holds something: list it in PURPOSE["holds"] with its mass and model it in use() as held:<name>'))
90
+ if (holds or 'holder' in classes) and not mounts:
91
+ req.append(('mounts', 'what carries the load into the world is not named: list PURPOSE["mounts"] (the surface and how: ' + ', '.join(KINDS) + ') and model it in use() as world:<name>'))
92
+ user = p.get('user')
93
+ good_point = isinstance(user, (list, tuple)) and len(user) == 3 and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in user)
94
+ faces = p.get('faces')
95
+ if 'screen' in classes and holds and faces is None:
96
+ named = [h.get('body') for h in holds if isinstance(h, dict) and isinstance(h.get('body'), str)]
97
+ faces = {'body': next((n for n in named if SCREEN.search(n.replace('_', ' '))), named[0] if named else None)}
98
+ if faces is not None or p.get('reach_mm') is not None:
99
+ if not good_point:
100
+ req.append(('user', 'a screen held for a person must face them: give PURPOSE["user"], their eye point [x, y, z] mm in the use() frame'))
101
+ jolt = p.get('jolt_g', 0)
102
+ jolt = float(jolt) if isinstance(jolt, (int, float)) and not isinstance(jolt, bool) and jolt >= 0 else 0.0
103
+ if 'vehicle' in classes:
104
+ jolt = max(jolt, 1.5)
105
+ press = p.get('press_n', 1.5 if holds else 0.0) # a finger on a screen or on what it holds
106
+ press = float(press) if isinstance(press, (int, float)) and not isinstance(press, bool) and press >= 0 else 1.5
107
+ if holds:
108
+ press = max(press, 1.5) # floors, like the jolt's: the designer may raise them, never lower
109
+ material = str(p.get('material') or 'PLA').lower()
110
+ within = (faces or {}).get('within_deg', 25) if isinstance(faces, dict) else 25
111
+ within = float(within) if isinstance(within, (int, float)) and not isinstance(within, bool) and 0 < within <= 90 else 25.0
112
+ if 'screen' in classes:
113
+ within = min(within, 25.0)
114
+ out.update(requirements=req, holds=[h for h in holds if good_hold(h)], mounts=[m for m in mounts if good_mount(m)],
115
+ user=list(map(float, user)) if good_point else None, faces=faces if isinstance(faces, dict) else None,
116
+ within_deg=within,
117
+ reach_mm=p.get('reach_mm'), jolt_g=jolt, press_n=press,
118
+ density=DENSITY.get(material, DENSITY['pla']), material=material,
119
+ environment='vehicle' if 'vehicle' in classes else 'indoor')
120
+ return out
121
+
122
+
123
+ def _mesh(shape, tol=0.05):
124
+ import trimesh
125
+ v, f = shape.tessellate(tol, 0.2)
126
+ m = trimesh.Trimesh(np.array([[q.X, q.Y, q.Z] for q in v], float), np.array(f, np.int64), process=True)
127
+ m.merge_vertices()
128
+ return m
129
+
130
+
131
+ def _patch(part, world):
132
+ """Part triangles lying on a world body: area, centroid, outward normal (part into world) and plane moments."""
133
+ import trimesh
134
+ tri = part.triangles
135
+ lo, hi = world.bounds[0] - PATCH_MM - 1e-6, world.bounds[1] + PATCH_MM + 1e-6
136
+ near = np.flatnonzero(((part.vertices >= lo) & (part.vertices <= hi)).all(axis=1)) # only vertices by the surface
137
+ d = np.full(len(part.vertices), np.inf)
138
+ if len(near):
139
+ d[near] = trimesh.proximity.closest_point(world, part.vertices[near])[1]
140
+ within = d[part.faces] <= PATCH_MM
141
+ on = within.all(axis=1)
142
+ t, n, a = [tri[on]], [part.face_normals[on]], [part.area_faces[on]]
143
+ # A face partly on the world body (a base over a desk's edge, or across a shelf with no corner on it) is found by
144
+ # where it is, not by its corners: every other triangle whose box meets the body's box (grown by PATCH_MM) is
145
+ # split, and its pieces keep splitting while they still meet that box, down to SPLIT_MM. A piece wholly within
146
+ # PATCH_MM of the body and facing it counts; the rest are dropped. Only pieces over the body are ever split.
147
+ meets = lambda p: ((p.min(axis=1) <= hi) & (p.max(axis=1) >= lo)).all(axis=1)
148
+ cand = np.flatnonzero(~on & meets(tri))
149
+ pieces, normals = tri[cand], part.face_normals[cand]
150
+ while len(pieces) and len(pieces) <= SPLIT_PIECES:
151
+ pts = pieces.reshape(-1, 3)
152
+ dist, facing = np.full(len(pts), np.inf), np.zeros((len(pts), 3))
153
+ inbox = ((pts >= lo) & (pts <= hi)).all(axis=1)
154
+ if inbox.any():
155
+ _, dist[inbox], hit = trimesh.proximity.closest_point(world, pts[inbox])
156
+ facing[inbox] = world.face_normals[hit]
157
+ close = (dist <= PATCH_MM).reshape(-1, 3).all(axis=1)
158
+ # A piece counts only where it faces the body (a base on a desk, not the thin strip of a side wall beside it).
159
+ whole = close & (np.einsum('ij,ij->i', normals, facing.reshape(-1, 3, 3)[:, 0]) < -0.5)
160
+ t.append(pieces[whole]); n.append(normals[whole])
161
+ a.append(np.linalg.norm(np.cross(pieces[whole, 1] - pieces[whole, 0], pieces[whole, 2] - pieces[whole, 0]), axis=1) / 2)
162
+ edges = np.linalg.norm(pieces - np.roll(pieces, 1, axis=1), axis=2).max(axis=1)
163
+ split = ~close & (edges > SPLIT_MM) # pieces already small judged their corners
164
+ pieces, normals = pieces[split], normals[split]
165
+ if not len(pieces):
166
+ break
167
+ m = (pieces + np.roll(pieces, -1, axis=1)) / 2 # midpoints of edges 01, 12, 20
168
+ pieces = np.concatenate([np.stack([pieces[:, 0], m[:, 0], m[:, 2]], 1), np.stack([m[:, 0], pieces[:, 1], m[:, 1]], 1),
169
+ np.stack([m[:, 2], m[:, 1], pieces[:, 2]], 1), np.stack([m[:, 0], m[:, 1], m[:, 2]], 1)])
170
+ normals = np.concatenate([normals] * 4)
171
+ keep = meets(pieces)
172
+ pieces, normals = pieces[keep], normals[keep]
173
+ t, n, a = np.concatenate(t), np.concatenate(n), np.concatenate(a)
174
+ if not len(t) or a.sum() <= 0:
175
+ return None
176
+ area = float(a.sum())
177
+ c = (t.mean(axis=1) * a[:, None]).sum(axis=0) / area
178
+ mean = (n * a[:, None]).sum(axis=0) / area
179
+ return {'tri': t, 'area': area, 'centroid': c, 'normal': mean, 'flat': float(np.linalg.norm(mean))}
180
+
181
+
182
+ def _plane(patch):
183
+ n = patch['normal'] / np.linalg.norm(patch['normal'])
184
+ e1 = np.cross(n, [0, 0, 1.0]) if abs(n[2]) < 0.9 else np.cross(n, [1.0, 0, 0])
185
+ e1 /= np.linalg.norm(e1)
186
+ e2 = np.cross(n, e1) # e1 x e2 = n
187
+ q = patch['tri'] - patch['centroid']
188
+ x, y = q @ e1, q @ e2 # (T, 3) each
189
+ x0, x1, x2, y0, y1, y2 = x[:, 0], x[:, 1], x[:, 2], y[:, 0], y[:, 1], y[:, 2]
190
+ A = np.abs((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)) / 2
191
+ ixx = float((A / 6 * (x0 * x0 + x1 * x1 + x2 * x2 + x0 * x1 + x1 * x2 + x2 * x0)).sum())
192
+ iyy = float((A / 6 * (y0 * y0 + y1 * y1 + y2 * y2 + y0 * y1 + y1 * y2 + y2 * y0)).sum())
193
+ ixy = float((A / 12 * (2 * x0 * y0 + 2 * x1 * y1 + 2 * x2 * y2 + x0 * y1 + x1 * y0 + x0 * y2 + x2 * y0 + x1 * y2 + x2 * y1)).sum())
194
+ return n, e1, e2, x.ravel(), y.ravel(), ixx, iyy, ixy
195
+
196
+
197
+ def _surface(world, patch):
198
+ """How far a world body reaches in the plane of a contact (convex hull area) and how far behind it (depth)."""
199
+ from shapely.geometry import MultiPoint
200
+ n = patch['normal'] / np.linalg.norm(patch['normal'])
201
+ e1 = np.cross(n, [0, 0, 1.0]) if abs(n[2]) < 0.9 else np.cross(n, [1.0, 0, 0])
202
+ e1 /= np.linalg.norm(e1)
203
+ e2 = np.cross(n, e1)
204
+ q = np.asarray(world.vertices, float) - patch['centroid']
205
+ return {'area': float(MultiPoint(list(zip((q @ e1).tolist(), (q @ e2).tolist()))).convex_hull.area), 'depth': float((q @ n).max())}
206
+
207
+
208
+ def _held_face(held, part_com):
209
+ """The held object's exposed face: the normal of its broad face that points away from the part, and its centre."""
210
+ m = _mesh(held, 0.2)
211
+ vals, vecs = m.principal_inertia_components, m.principal_inertia_vectors
212
+ n = np.asarray(vecs[int(np.argmax(vals))], float) # a plate's largest moment is about its normal
213
+ com = np.asarray(m.center_mass, float)
214
+ if n @ (com - part_com) < 0:
215
+ n = -n
216
+ half = float(np.max((m.vertices - com) @ n))
217
+ return n, com + n * half, com
218
+
219
+
220
+ def signature(shape):
221
+ """What a rigid move keeps: volume, surface area and the principal moments of inertia about the centre of mass."""
222
+ moments = sorted(float(v) for v in np.linalg.eigvalsh(np.array(shape.matrix_of_inertia, float)))
223
+ return {'volume': float(shape.volume), 'area': float(shape.area), 'moments': moments}
224
+
225
+
226
+ def _overlap(a, b):
227
+ """The volume two solids share and the surface area of what they share (0, 0 where they only touch)."""
228
+ common = a.intersect(b)
229
+ pieces = [] if common is None else list(common) if isinstance(common, (list, tuple)) or hasattr(common, 'sort_by') else [common]
230
+ return sum(float(p.volume) for p in pieces), sum(float(p.area) for p in pieces)
231
+
232
+
233
+ def evaluate(use_step, compiled, built=None):
234
+ """Each requirement's status on the use() assembly, the computed loads at the mounts, and what blocks ready."""
235
+ from build123d import Compound, import_step, CenterOf
236
+ results, loads, notes = [], [], []
237
+ for name, problem in compiled['requirements']:
238
+ results.append({'requirement': name, 'status': 'fail' if problem else 'pass', 'says': problem or 'stated', **({'fix': problem} if problem else {})})
239
+ needs = compiled['holds'] or compiled['mounts'] or compiled['user'] is not None
240
+ failed = Path(str(use_step)[:-len('.use.step')] + '.use.error')
241
+ if failed.exists():
242
+ results.append({'requirement': 'use', 'status': 'not_modelled', 'says': 'use() failed: ' + failed.read_text()[:300],
243
+ 'fix': 'Fix use() (it raised ' + failed.read_text()[:200] + '); it must return a Compound of the part with labelled held:<name> and world:<name> solids'})
244
+ return results, loads, notes
245
+ if not use_step.exists():
246
+ if needs:
247
+ results.append({'requirement': 'use', 'status': 'not_modelled', 'says': 'no use(): the loads cannot be computed',
248
+ 'fix': 'Define use() beside build(): return Compound(children=[...]) of the part as it is used (Z up, gravity -Z) with each held object as held:<name> and each surface it meets as world:<name>, touching where they really touch, so the loads can be computed'})
249
+ return results, loads, notes
250
+ shape = import_step(str(use_step))
251
+ kids = list(shape.children) if isinstance(shape, Compound) else []
252
+ role = lambda c: (c.label or '').split(':', 1)
253
+ held = {role(c)[1]: c for c in kids if role(c)[0] == 'held' and len(role(c)) == 2}
254
+ world = {role(c)[1]: c for c in kids if role(c)[0] == 'world' and len(role(c)) == 2}
255
+ part = [s for c in kids if role(c)[0] not in ('held', 'world') for s in c.solids()] or ([] if kids else list(shape.solids()))
256
+ if not part:
257
+ results.append({'requirement': 'use', 'status': 'not_modelled', 'says': 'use() returned no part bodies besides held: and world: ones',
258
+ 'fix': 'Return the part itself in use() too, beside its held: and world: bodies (label it anything else)'})
259
+ return results, loads, notes
260
+ part_shape = Compound(children=part) if len(part) > 1 else part[0]
261
+ part_mesh = _mesh(part_shape)
262
+ vol = sum(s.volume for s in part)
263
+ part_mass = vol * compiled['density'] / 1000.0 # g
264
+ build_volume = built['volume'] if built else None
265
+ if build_volume and abs(vol - build_volume) > SAME_SHAPE * build_volume + 1.0:
266
+ results.append({'requirement': 'use is the built part', 'status': 'fail', 'says': f'the part in use() is {vol:.0f} mm^3, the part build() exports {build_volume:.0f} mm^3',
267
+ 'fix': f'Build the part in use() from build() (the same bodies, moved into the pose it is used in): its {vol:.0f} mm^3 is not the {build_volume:.0f} mm^3 build() exports, so nothing checked in use() is the part that prints'})
268
+ elif build_volume:
269
+ # The same volume is not the same part (a 100 x 100 x 0.36 mm pad and a 30 x 30 x 4 mm strip are both 3600 mm^3):
270
+ # a rigid move keeps the surface area and the principal moments too.
271
+ mine = signature(part_shape)
272
+ off = lambda a, b: abs(a - b) > SAME_SHAPE * abs(b) + 1e-6 * max(built['moments'][-1], 1.0)
273
+ if abs(mine['area'] - built['area']) > SAME_SHAPE * built['area'] + 1.0 or any(off(a, b) for a, b in zip(mine['moments'], built['moments'])):
274
+ results.append({'requirement': 'use is the built part', 'status': 'fail',
275
+ 'says': f'the part in use() has {vol:.0f} mm^3 like the part build() exports, but {mine["area"]:.0f} mm^2 of surface against {built["area"]:.0f} mm^2 and other moments of inertia',
276
+ 'fix': f'Build the part in use() from build() (the same bodies, moved into the pose it is used in): its shape is not the shape build() exports ({mine["area"]:.0f} mm^2 of surface, not {built["area"]:.0f} mm^2, though both are {vol:.0f} mm^3), so nothing checked in use() is the part that prints'})
277
+ part_com = np.array(list(part_shape.center(CenterOf.MASS)), float) if vol > 0 else part_mesh.center_mass
278
+ masses = [('the part', part_mass, part_com)]
279
+ held_faces = []
280
+ for h in compiled['holds']:
281
+ body = held.get(h['body'])
282
+ if body is None:
283
+ results.append({'requirement': f'holds {h["body"]}', 'status': 'not_modelled', 'says': f'use() has no held:{h["body"]} body',
284
+ 'fix': f'Model the {h["body"]} at its real size where it sits on the part, as held:{h["body"]} in use(), so its weight is carried through the part'})
285
+ continue
286
+ gap = float(body.distance_to(part_shape))
287
+ ok = gap <= TOUCH_MM
288
+ results.append({'requirement': f'holds {h["body"]}', 'status': 'pass' if ok else 'fail',
289
+ 'says': f'held:{h["body"]} sits on the part ({gap:.2f} mm)' if ok else f'held:{h["body"]} is {gap:.1f} mm from the part: nothing carries it',
290
+ **({} if ok else {'fix': f'Put held:{h["body"]} where it really rests on the part in use() (it is {gap:.1f} mm away), or make the part reach it'})})
291
+ if ok:
292
+ # distance_to() is 0 for a body inside the part too: a phone sunk into its cradle's back touches nothing it rests on.
293
+ try:
294
+ inside, skin = _overlap(body, part_shape)
295
+ except Exception as e: # a measurement that failed proves nothing: it blocks ready
296
+ results.append({'requirement': f'held {h["body"]} is outside the part', 'status': 'not_modelled', 'says': f'the overlap of held:{h["body"]} and the part could not be measured ({type(e).__name__})',
297
+ 'fix': f'Model held:{h["body"]} as one closed solid resting on the part in use(); the engine could not measure whether it is inside the part'})
298
+ else:
299
+ depth = 2 * inside / skin if skin > 0 else 0.0 # a thin overlap of area A and depth t has volume A*t and surface about 2A
300
+ # The depth is the overlap's average thickness: for a thin body buried whole it is only the body's own
301
+ # thickness, so a large share of the body inside the part fails too. No real resting contact comes near half.
302
+ buried = inside > INSIDE_SHARE * float(body.volume)
303
+ if inside > INSIDE_MM3 and (depth > INSIDE_MM or buried):
304
+ results.append({'requirement': f'held {h["body"]} is outside the part', 'status': 'fail',
305
+ 'says': f'{inside:.0f} mm^3 of held:{h["body"]} is inside the part ({"most of it" if buried else f"about {depth:.1f} mm deep"})',
306
+ 'fix': f'Move held:{h["body"]} out of the part in use() so it rests on the part\'s surface: {inside:.0f} mm^3 of it is inside the part ({"most of it" if buried else f"about {depth:.1f} mm deep"}), and a part cannot carry what it overlaps'})
307
+ cm3 = float(body.volume) / 1000.0
308
+ density = float(h['mass_g']) / cm3 if cm3 > 0 else float('inf')
309
+ if not HELD_DENSITY[0] <= density <= HELD_DENSITY[1]:
310
+ results.append({'requirement': f'held {h["body"]} size and mass', 'status': 'fail', 'says': f'{h["mass_g"]:g} g in {cm3:.1f} cm^3 of held:{h["body"]} is {density:.2f} g/cm^3',
311
+ 'fix': f'Model the {h["body"]} at its real size and mass: {h["mass_g"]:g} g in the {cm3:.1f} cm^3 held:{h["body"]} is {density:.2f} g/cm^3, outside {HELD_DENSITY[0]} to {HELD_DENSITY[1]:g} g/cm^3 for real objects'})
312
+ n, face, com = _held_face(body, part_com)
313
+ masses.append((h['body'], float(h['mass_g']), com))
314
+ held_faces.append((h['body'], n, face))
315
+ patches = []
316
+ for mnt in compiled['mounts']:
317
+ body = world.get(mnt['body'])
318
+ if body is None:
319
+ results.append({'requirement': f'mounts {mnt["body"]}', 'status': 'not_modelled', 'says': f'use() has no world:{mnt["body"]} body',
320
+ 'fix': f'Model the {mnt["body"]} as world:{mnt["body"]} in use(): a solid slab where it really is, touching the part where it {"is taped" if mnt["by"] == "tape" else "rests" if mnt["by"] == "rests" else "meets it"}, so the {mnt["by"]} mount can be checked'})
321
+ continue
322
+ p = _patch(part_mesh, _mesh(body, 0.1))
323
+ if p is None:
324
+ results.append({'requirement': f'mounts {mnt["body"]}', 'status': 'not_modelled', 'says': f'the part does not touch world:{mnt["body"]} in use(): no contact, so no load path',
325
+ 'fix': f'Move the part or world:{mnt["body"]} in use() so they touch where the part is {"taped" if mnt["by"] == "tape" else "held"} to it (within {PATCH_MM} mm)'})
326
+ continue
327
+ results.append({'requirement': f'mounts {mnt["body"]}', 'status': 'pass', 'says': f'{p["area"]:.0f} mm^2 of the part touches world:{mnt["body"]} ({mnt["by"]})'})
328
+ if mnt['by'] in ('tape', 'rests'):
329
+ if p['flat'] < FLAT:
330
+ if mnt['by'] == 'tape': # tape fails closed: a curved or folded contact has no stress the engine can compute
331
+ results.append({'requirement': f'tape on {mnt["body"]}', 'status': 'not_modelled', 'says': f'the taped contact on world:{mnt["body"]} is not one flat patch',
332
+ 'fix': f'Model the taped contact as one flat patch per mount, on a flat world body: the part meets world:{mnt["body"]} on surfaces that are not one plane, so the tape cannot be checked'})
333
+ continue
334
+ else:
335
+ q = _surface(_mesh(body, 0.1), p)
336
+ if q['area'] < WORLD_AREA * p['area'] or q['depth'] < WORLD_DEPTH_MM:
337
+ results.append({'requirement': f'world {mnt["body"]} is a surface', 'status': 'fail',
338
+ 'says': f'world:{mnt["body"]} spans {q["area"]:.0f} mm^2 in the contact plane and {q["depth"]:.1f} mm behind it, for a {p["area"]:.0f} mm^2 contact',
339
+ 'fix': f'Model the {mnt["body"]} as one slab where it really is, not a block shaped to the part: it spans {q["area"]:.0f} mm^2 in the contact\'s plane (needs at least {WORLD_AREA:g} times the {p["area"]:.0f} mm^2 contact) and {q["depth"]:.1f} mm behind it (needs {WORLD_DEPTH_MM:g})'})
340
+ patches.append((mnt, p))
341
+ # The faces requirement: the held object's exposed face turned toward the person's eye.
342
+ if compiled['user'] is not None:
343
+ eye = np.array(compiled['user'], float)
344
+ want = (compiled['faces'] or {}).get('body')
345
+ if compiled['faces'] is not None and want is not None and want not in [h['body'] for h in compiled['holds']]:
346
+ results.append({'requirement': f'faces user ({want})', 'status': 'not_modelled', 'says': f'faces names {want}, which is not in PURPOSE["holds"]',
347
+ 'fix': f'Name in PURPOSE["faces"] the held body that must face the user ({", ".join(h["body"] for h in compiled["holds"]) or "none is listed"}), or list {want} in PURPOSE["holds"] and model it as held:{want}'})
348
+ for name, n, face in held_faces:
349
+ if compiled['faces'] is not None and want not in (None, name):
350
+ continue
351
+ to = eye - face
352
+ dist = float(np.linalg.norm(to))
353
+ if compiled['faces'] is not None:
354
+ ang = math.degrees(math.acos(max(-1.0, min(1.0, float(n @ to) / max(dist, 1e-9)))))
355
+ ok = ang <= compiled['within_deg']
356
+ results.append({'requirement': f'faces user ({name})', 'status': 'pass' if ok else 'fail', 'angle_deg': round(ang, 1),
357
+ 'says': f'{name}\'s exposed face is {ang:.0f} deg off the line to the user\'s eye (allowed {compiled["within_deg"]:.0f})',
358
+ **({} if ok else {'fix': f'Turn the {name} toward the user: its face is {ang:.0f} deg off the line to their eye (allowed {compiled["within_deg"]:.0f}). Aim it the way the bought products do, with a joint or an angled base, and show it aimed in use()'})})
359
+ if isinstance(compiled['reach_mm'], (int, float)):
360
+ ok = dist <= compiled['reach_mm']
361
+ results.append({'requirement': f'reach ({name})', 'status': 'pass' if ok else 'fail', 'distance_mm': round(dist),
362
+ 'says': f'{name} is {dist:.0f} mm from the user (allowed {compiled["reach_mm"]})',
363
+ **({} if ok else {'fix': f'Bring the {name} within reach: it is {dist:.0f} mm from the user (allowed {compiled["reach_mm"]})'})})
364
+ if not patches or not compiled['mounts']:
365
+ return results, loads, notes
366
+ # Loads: gravity on everything, jolts along each axis, and a hand pressing each held object's exposed face.
367
+ cases = [('gravity', np.array([0, 0, -G]), None)]
368
+ j = compiled['jolt_g']
369
+ if j > 0:
370
+ for k, axis in enumerate('XYZ'):
371
+ for s in (1, -1):
372
+ d = np.zeros(3); d[k] = s * j * G
373
+ cases.append((f'gravity + {j:g} g along {"+" if s > 0 else "-"}{axis}', np.array([0, 0, -G]) + d, None))
374
+ if compiled['press_n'] > 0:
375
+ for name, n, face in held_faces:
376
+ cases.append((f'gravity + {compiled["press_n"]:g} N pressing {name}', np.array([0, 0, -G]), (face, -n * compiled['press_n'])))
377
+
378
+ def group(items):
379
+ area = sum(p['area'] for _, p in items)
380
+ return {'tri': np.concatenate([p['tri'] for _, p in items]), 'area': area,
381
+ 'centroid': sum(p['centroid'] * p['area'] for _, p in items) / area,
382
+ 'normal': sum(p['normal'] * p['area'] for _, p in items) / area}
383
+
384
+ def rows(g, kind):
385
+ """The reaction at one group of contacts for every case, carried by that group alone."""
386
+ c, area = g['centroid'], g['area']
387
+ plane = _plane(g) if float(np.linalg.norm(g['normal'])) >= FLAT else None
388
+ out = []
389
+ for label, gv, press in cases:
390
+ F, M = np.zeros(3), np.zeros(3)
391
+ for _, mass, com in masses:
392
+ f = gv * mass / 1000.0 # N
393
+ F += f; M += np.cross(com - c, f) / 1000.0 # N m
394
+ if press is not None:
395
+ F += press[1]; M += np.cross(press[0] - c, press[1]) / 1000.0
396
+ R, MR = -F, -M * 1000.0 # the mount's reaction on the part (N, N mm)
397
+ row = {'case': label, 'force_n': round(float(np.linalg.norm(F)), 2), 'moment_nm': round(float(np.linalg.norm(M)), 3)}
398
+ if plane is not None:
399
+ n, e1, e2, x, y, ixx, iyy, ixy = plane
400
+ N = float(R @ n) # + pulls the part onto the surface: the tape in tension
401
+ shear = float(np.linalg.norm(R - N * n))
402
+ if kind == 'tape':
403
+ det = ixy * ixy - iyy * ixx
404
+ a, b = ((np.linalg.solve([[ixy, iyy], [ixx, ixy]], [MR @ e1, -(MR @ e2)])) if abs(det) > 1e-9 else (0.0, 0.0))
405
+ peak = (N / area + a * x + b * y).max() * 1000.0 # kPa
406
+ twist = abs(float(MR @ n)) * float(np.sqrt(x * x + y * y).max()) / max(ixx + iyy, 1e-9) * 1000.0
407
+ row.update(peak_tension_kpa=round(float(max(peak, 0.0)), 1), shear_kpa=round(shear / area * 1000.0 + twist, 1))
408
+ elif kind == 'rests':
409
+ press_in = -N # the surface pushes back: positive when resting
410
+ if press_in <= 1e-9:
411
+ row.update(lifts=True)
412
+ else:
413
+ from shapely.geometry import MultiPoint, Point
414
+ xc, yc = -float(MR @ e2) / N, float(MR @ e1) / N
415
+ hull = MultiPoint(list(zip(x.tolist(), y.tolist()))).convex_hull
416
+ inside = hull.buffer(1e-6).contains(Point(xc, yc))
417
+ margin = hull.exterior.distance(Point(xc, yc)) if hasattr(hull, 'exterior') else 0.0
418
+ row.update(tips=not inside, tip_margin_mm=round(float(margin if inside else -margin), 1),
419
+ slides=bool(shear > FRICTION * press_in + 1e-9))
420
+ out.append(row)
421
+ return out, plane is not None
422
+
423
+ by = {}
424
+ for m, p in patches:
425
+ by.setdefault(m['by'], []).append((m, p))
426
+ alone = len(by) > 1 # other kinds share the load in reality; each kind checked here carries all of it
427
+ tape = by.get('tape', [])
428
+ if tape:
429
+ g = group(tape)
430
+ sets = [tape] if float(np.linalg.norm(g['normal'])) >= FLAT else [[t] for t in tape] # mounts in different planes: each alone
431
+ for items in sets:
432
+ names = ', '.join(m['body'] for m, _ in items)
433
+ got, _ = rows(group(items), 'tape')
434
+ loads.extend(got if len(sets) == 1 else [dict(r, mount=names) for r in got])
435
+ area = sum(p['area'] for _, p in items)
436
+ stress = lambda r: max(r['peak_tension_kpa'], r['shear_kpa'])
437
+ sustained, short = got[0], max(got[1:], key=stress, default=None)
438
+ whole = ' (the whole load on the tape: the other mounts are not counted)' if alone or len(sets) > 1 else ''
439
+ for row, limit, word in ((sustained, TAPE_SUSTAINED_KPA[compiled['environment']], 'sustained'), (short, TAPE_SHORT_KPA, 'short-term')):
440
+ if row is None:
441
+ continue
442
+ ok = stress(row) <= limit
443
+ results.append({'requirement': f'tape on {names}, {word}', 'status': 'pass' if ok else 'fail',
444
+ 'says': f'{row["case"]}: peak tension {row["peak_tension_kpa"]} kPa, shear {row["shear_kpa"]} kPa over {area:.0f} mm^2 (allowed {limit:g} kPa {word}; 3M VHB){whole}',
445
+ **({} if ok else {'fix': f'Spread the tape or bring the load closer to it: {row["case"]} puts {stress(row)} kPa on the tape (allowed {limit:g} kPa {word}). A broader or taller pad, a shorter stand-off or a lighter part lowers it'})})
446
+ if 'rests' in by and not alone:
447
+ names = ', '.join(m['body'] for m, _ in by['rests'])
448
+ got, flat = rows(group(by['rests']), 'rests')
449
+ loads.extend(got)
450
+ if flat:
451
+ bad = [f'{row["case"]}: ' + ' and '.join(w for w, flag in (('lifts off', row.get('lifts')), ('tips over', row.get('tips')), ('slides', row.get('slides'))) if flag)
452
+ for row in got if row.get('lifts') or row.get('tips') or row.get('slides')]
453
+ least = min((row.get('tip_margin_mm', 0) for row in got), default=0)
454
+ results.append({'requirement': f'rests on {names}', 'status': 'fail' if bad else 'pass',
455
+ 'says': '; '.join(bad) if bad else f'stays put in every case, the load at least {least} mm inside its footprint',
456
+ **({'fix': 'Widen or lengthen the base under the load, move the load over it, or add weight: ' + '; '.join(bad)} if bad else {})})
457
+ else:
458
+ notes.append(f'whether the part tips on {names}: it rests on surfaces that are not one plane')
459
+ elif 'rests' in by:
460
+ notes.append('whether the part tips or slides where it rests: it also has other kinds of mount, which share the load')
461
+ for kind in [k for k in by if k not in ('tape', 'rests')]:
462
+ names = ', '.join(m['body'] for m, _ in by[kind])
463
+ if not loads:
464
+ loads.extend(rows(group(by[kind]), kind)[0])
465
+ notes.append(f'the strength of the {kind} interface on {names}: its loads are computed (purpose.loads), its capacity is not')
466
+ return results, loads, notes
467
+
468
+
469
+ def inspect_purpose(request, built=None):
470
+ """The purpose block of a solid result, or None for mesh mode and 3MF projects (their paths are unchanged)."""
471
+ base = Path(request['output']) / request['name']
472
+ if request.get('mode', 'solid') != 'solid' or Path(str(base) + '.project.json').exists() or request.get('role') == 'check':
473
+ return None # a check part or reference export is not the design: nothing to hold it to
474
+ p, error = read(request['script'])
475
+ if p is None:
476
+ why = (f'Fix PURPOSE: {error}' if error else 'Add PURPOSE = {"for": ..., "modelled_on": ...} beside P: what the part is for in the person\'s words and the bought product it follows (plus holds, mounts and use() when it carries something), so its use can be checked')
477
+ return {'declared': False, 'requirements': [{'requirement': 'purpose', 'status': 'not_modelled', 'says': error or 'no PURPOSE', 'fix': why}],
478
+ 'loads': [], 'not_checked': [], 'blocked': [why + '.'], 'ready': False}
479
+ compiled = compile_purpose(p)
480
+ try:
481
+ results, loads, notes = evaluate(Path(str(base) + '.use.step'), compiled, signature(built) if built is not None else None)
482
+ except Exception as e: # a measurement that failed proves nothing: reported, and it blocks ready
483
+ loads, notes = [], []
484
+ results = [{'requirement': n, 'status': 'fail' if pr else 'pass', 'says': pr or 'stated'} for n, pr in compiled['requirements']]
485
+ results.append({'requirement': 'use', 'status': 'not_modelled', 'says': f'the use() assembly could not be measured ({type(e).__name__}: {e})'[:300],
486
+ 'fix': 'Return use() as a Compound of closed solids labelled with the part, held:<name> and world:<name>; the engine could not measure it as returned'})
487
+ # Each entry is an instruction the designer can act on, as a sentence: cad_run's next quotes the first ones.
488
+ blocked = [(lambda t: t if t.endswith('.') else t + '.')(r.get('fix') or f'{r["requirement"]}: {r["says"]}') for r in results if r['status'] != 'pass']
489
+ return {'declared': True, 'for': str(p.get('for') or ''), 'modelled_on': str(p.get('modelled_on') or ''),
490
+ 'classes': compiled['classes'], 'user': compiled['user'], 'material': compiled['material'], 'jolt_g': compiled['jolt_g'], 'press_n': compiled['press_n'],
491
+ 'within_deg': compiled['within_deg'],
492
+ 'requirements': results, 'loads': loads, 'not_checked': notes, 'blocked': blocked, 'ready': not blocked}
package/src/cad/worker.py CHANGED
@@ -104,12 +104,16 @@ def main():
104
104
  declaration.value = ast.Name(id='__cad_parameters__', ctx=ast.Load())
105
105
  ast.fix_missing_locations(tree)
106
106
  from scan_touchup import scan_touchup_factory
107
- namespace = {'__name__': 'cad_design', '__file__': request['script'], '__cad_parameters__': merged, 'INPUTS': request.get('inputs', {}), 'load_scan': scan_loader(request.get('inputs', {})),
107
+ from project3mf import Project3mf, export as export_project, project_factory
108
+ namespace = {'project_3mf': project_factory(request.get('inputs', {})), '__name__': 'cad_design', '__file__': request['script'], '__cad_parameters__': merged, 'INPUTS': request.get('inputs', {}), 'load_scan': scan_loader(request.get('inputs', {})),
108
109
  'scan_touchup': scan_touchup_factory(request.get('inputs', {}))}
109
110
  exec(compile(tree, request['script'], 'exec'), namespace)
110
111
  shape = namespace['build']()
111
112
  out = Path(request['output']) / request['name']
112
- if request.get('mode', 'solid') == 'mesh':
113
+ if isinstance(shape, Project3mf):
114
+ # A 3MF project: parts and a manifest for the MCP to write the 3MF from, plus the usual combined exports.
115
+ export_project(shape, out, request.get('mode', 'solid'))
116
+ elif request.get('mode', 'solid') == 'mesh':
113
117
  import trimesh
114
118
  if not isinstance(shape, trimesh.Trimesh):
115
119
  raise ValueError('Mesh-mode build() must return a trimesh.Trimesh.')
@@ -119,6 +123,17 @@ def main():
119
123
  raise ValueError('build() must return a valid build123d Shape containing solids.')
120
124
  cad.export_stl(shape, str(out) + '.stl', tolerance=0.01, angular_tolerance=0.1)
121
125
  cad.export_step(shape, str(out) + '.step')
126
+ # The design as it is used: the part with what it holds (held:<name>) and what it meets (world:<name>),
127
+ # Z up. Exported for the inspection process, which computes its loads; the script never reports them.
128
+ # A use() that fails costs the run its readiness, never the export build() already made.
129
+ if callable(namespace.get('use')):
130
+ try:
131
+ used = namespace['use']()
132
+ if not isinstance(used, cad.Shape) or not used.solids():
133
+ raise ValueError('use() must return a build123d Shape: a Compound of the part with labelled held:<name> and world:<name> solids.')
134
+ cad.export_step(used, str(out) + '.use.step')
135
+ except Exception as e:
136
+ Path(str(out) + '.use.error').write_text(f'{type(e).__name__}: {e}'[:300])
122
137
  elif mode == 'inspect':
123
138
  from geometry import inspect
124
139
  print(json.dumps(inspect(request), allow_nan=False))