bambu-printer-mcp 1.1.95 → 1.1.97

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 (51) hide show
  1. package/CONTRIBUTORS.md +1 -0
  2. package/README.md +13 -2
  3. package/dist/cad/contracts.js +7 -5
  4. package/dist/cad-engine.js +1 -0
  5. package/dist/counterpart/info.js +1 -0
  6. package/dist/counterpart/make-3mf.d.ts +1 -0
  7. package/dist/counterpart/make-3mf.js +37 -5
  8. package/dist/counterpart/model-plates.d.ts +2 -0
  9. package/dist/counterpart/model-plates.js +3 -0
  10. package/dist/counterpart/part-meshes.d.ts +114 -0
  11. package/dist/counterpart/part-meshes.js +323 -0
  12. package/dist/counterpart/plate-filaments.d.ts +3 -0
  13. package/dist/counterpart/plate-filaments.js +31 -10
  14. package/dist/counterpart/remote.js +1 -0
  15. package/dist/counterpart/schemas.d.ts +10 -0
  16. package/dist/counterpart/schemas.js +2 -0
  17. package/dist/design-app-setup.d.ts +9 -0
  18. package/dist/design-app-setup.js +5 -2
  19. package/dist/design-guidance.d.ts +3 -3
  20. package/dist/design-guidance.js +8 -4
  21. package/dist/fusion-mcp-bridge.d.ts +13 -0
  22. package/dist/fusion-mcp-bridge.js +35 -4
  23. package/dist/index.js +39 -8
  24. package/dist/refusal.d.ts +15 -1
  25. package/dist/refusal.js +19 -1
  26. package/dist/slicer/floating-regions.d.ts +54 -0
  27. package/dist/slicer/floating-regions.js +198 -0
  28. package/dist/slicer/profile-flatten.js +4 -0
  29. package/dist/tool-annotations.js +2 -0
  30. package/package.json +2 -2
  31. package/src/cad/contracts.ts +7 -5
  32. package/src/cad/project3mf.py +9 -4
  33. package/src/cad/scan_measure.py +207 -0
  34. package/src/cad/scan_touchup.py +4 -1
  35. package/src/cad/worker.py +2 -1
  36. package/src/cad-engine.ts +1 -0
  37. package/src/counterpart/info.ts +1 -0
  38. package/src/counterpart/make-3mf.ts +33 -7
  39. package/src/counterpart/model-plates.ts +4 -0
  40. package/src/counterpart/part-meshes.ts +304 -0
  41. package/src/counterpart/plate-filaments.ts +25 -9
  42. package/src/counterpart/remote.ts +1 -0
  43. package/src/counterpart/schemas.ts +4 -0
  44. package/src/design-app-setup.ts +7 -2
  45. package/src/design-guidance.ts +8 -4
  46. package/src/fusion-mcp-bridge.ts +34 -4
  47. package/src/index.ts +40 -8
  48. package/src/refusal.ts +19 -1
  49. package/src/slicer/floating-regions.ts +187 -0
  50. package/src/slicer/profile-flatten.ts +3 -0
  51. package/src/tool-annotations.ts +2 -0
@@ -0,0 +1,198 @@
1
+ import { promises as fs } from "node:fs";
2
+ /** About 500k binary triangles: the search runs between slicer calls, on the server's own thread. */
3
+ const MAX_BYTES = 25 * 1024 * 1024;
4
+ /** Triangles of a binary or ASCII STL, as a flat array of 9 numbers each. */
5
+ export function stlTriangles(bytes) {
6
+ const ascii = /^\s*solid\b/.test(bytes.subarray(0, 256).toString("latin1")) && bytes.includes("facet");
7
+ if (bytes.length >= 84) {
8
+ const n = bytes.readUInt32LE(80);
9
+ // Binary: exactly sized, or sized with trailing bytes some exporters add, unless it reads as ASCII.
10
+ if (84 + n * 50 === bytes.length || (84 + n * 50 < bytes.length && !ascii)) {
11
+ const out = new Float64Array(n * 9);
12
+ for (let i = 0; i < n; i++)
13
+ for (let k = 0; k < 9; k++)
14
+ out[i * 9 + k] = bytes.readFloatLE(84 + i * 50 + 12 + k * 4);
15
+ return out;
16
+ }
17
+ }
18
+ const text = bytes.toString("latin1");
19
+ if (!/^\s*solid/.test(text))
20
+ throw new Error("not an STL file");
21
+ const values = [];
22
+ for (const match of text.matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g))
23
+ values.push(Number(match[1]), Number(match[2]), Number(match[3]));
24
+ if (!values.length || values.length % 9 || values.some(v => !Number.isFinite(v)))
25
+ throw new Error("malformed ASCII STL");
26
+ return Float64Array.from(values);
27
+ }
28
+ /**
29
+ * The floating low points of a triangle mesh. A sweep from the bottom up joins vertices into connected pieces of the
30
+ * surface below each height; a piece that starts above `plate_mm` is a low point, and its depth is how far up it
31
+ * reaches before it joins a piece that started lower (or the whole of it, if it never does: a body in mid-air).
32
+ * Only low points whose surface faces down count (the floor of a bowl or of a closed void faces up), and only
33
+ * those deeper than `min_depth_mm` (about one layer: shallower bumps fall inside the layer that already has material).
34
+ */
35
+ export function floatingRegions(triangles, options = {}) {
36
+ const plate = options.plate_mm ?? 0.3, minDepth = options.min_depth_mm ?? 0.2, merge = options.merge_mm ?? 2, limit = options.limit ?? 12;
37
+ const nTri = Math.floor(triangles.length / 9);
38
+ // Weld the triangle soup by position.
39
+ const index = new Map();
40
+ const xyz = [];
41
+ const corner = new Int32Array(nTri * 3);
42
+ for (let i = 0; i < nTri * 3; i++) {
43
+ const x = triangles[i * 3], y = triangles[i * 3 + 1], z = triangles[i * 3 + 2];
44
+ const key = `${Math.round(x * 1e4)},${Math.round(y * 1e4)},${Math.round(z * 1e4)}`;
45
+ let v = index.get(key);
46
+ if (v === undefined) {
47
+ v = xyz.length / 3;
48
+ index.set(key, v);
49
+ xyz.push(x, y, z);
50
+ }
51
+ corner[i] = v;
52
+ }
53
+ const nV = xyz.length / 3;
54
+ if (!nV)
55
+ return { regions: [], count: 0, model_min_z: 0 };
56
+ let minZ = Infinity;
57
+ for (let v = 0; v < nV; v++)
58
+ minZ = Math.min(minZ, xyz[v * 3 + 2]);
59
+ // Neighbours, and each vertex's area-weighted normal z (downward-facing where negative).
60
+ const neighbours = Array.from({ length: nV }, () => []);
61
+ const normalZ = new Float64Array(nV);
62
+ for (let t = 0; t < nTri; t++) {
63
+ const a = corner[t * 3], b = corner[t * 3 + 1], c = corner[t * 3 + 2];
64
+ if (a === b || b === c || a === c)
65
+ continue;
66
+ const ux = xyz[b * 3] - xyz[a * 3], uy = xyz[b * 3 + 1] - xyz[a * 3 + 1];
67
+ const vx = xyz[c * 3] - xyz[a * 3], vy = xyz[c * 3 + 1] - xyz[a * 3 + 1];
68
+ const nz = ux * vy - uy * vx; // twice the area times the normal's z
69
+ for (const [p, q] of [[a, b], [b, c], [c, a]]) {
70
+ neighbours[p].push(q);
71
+ neighbours[q].push(p);
72
+ }
73
+ normalZ[a] += nz;
74
+ normalZ[b] += nz;
75
+ normalZ[c] += nz;
76
+ }
77
+ // Union-find over vertices in rising z; each piece remembers its lowest vertex.
78
+ const order = Array.from({ length: nV }, (_, i) => i).sort((p, q) => xyz[p * 3 + 2] - xyz[q * 3 + 2] || p - q);
79
+ const parent = new Int32Array(nV).fill(-1);
80
+ const lowest = new Int32Array(nV);
81
+ const find = (v) => { while (parent[v] !== v) {
82
+ parent[v] = parent[parent[v]];
83
+ v = parent[v];
84
+ } return v; };
85
+ const z = (v) => xyz[v * 3 + 2];
86
+ const found = [];
87
+ const consider = (root, depth) => {
88
+ const low = lowest[root];
89
+ if (z(low) - minZ > plate && depth >= minDepth && normalZ[low] < 0)
90
+ found.push({ v: low, depth });
91
+ };
92
+ for (const v of order) {
93
+ parent[v] = v;
94
+ lowest[v] = v;
95
+ for (const n of neighbours[v]) {
96
+ if (parent[n] < 0)
97
+ continue;
98
+ const a = find(v), b = find(n);
99
+ if (a === b)
100
+ continue;
101
+ // The piece that started higher ends here: it hung down by the height climbed to reach this join.
102
+ const [keep, end] = z(lowest[a]) <= z(lowest[b]) ? [a, b] : [b, a];
103
+ consider(end, z(v) - z(lowest[end]));
104
+ parent[end] = keep;
105
+ }
106
+ }
107
+ // Pieces that never joined a lower one: separate bodies; the one holding the lowest point sits on the plate.
108
+ const tops = new Map();
109
+ for (let v = 0; v < nV; v++) {
110
+ const r = find(v);
111
+ tops.set(r, Math.max(tops.get(r) ?? -Infinity, z(v)));
112
+ }
113
+ for (const [root, top] of tops)
114
+ consider(root, top - z(lowest[root]));
115
+ /**
116
+ * The box of what hangs: the surface walked from the low point through every vertex below the height where it joins
117
+ * the rest, with each edge that crosses that height cut there. The same for any facet order (Codex review, #169).
118
+ */
119
+ const hanging = (start, top) => {
120
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
121
+ const add = (p) => { for (let k = 0; k < 3; k++) {
122
+ lo[k] = Math.min(lo[k], p[k]);
123
+ hi[k] = Math.max(hi[k], p[k]);
124
+ } };
125
+ const seen = new Uint8Array(nV);
126
+ const stack = [start];
127
+ seen[start] = 1;
128
+ while (stack.length) {
129
+ const u = stack.pop();
130
+ const pu = [xyz[u * 3], xyz[u * 3 + 1], xyz[u * 3 + 2]];
131
+ add(pu);
132
+ for (const w of neighbours[u]) {
133
+ if (z(w) < top) {
134
+ if (!seen[w]) {
135
+ seen[w] = 1;
136
+ stack.push(w);
137
+ }
138
+ continue;
139
+ }
140
+ const f = (top - pu[2]) / (z(w) - pu[2] || 1);
141
+ add([pu[0] + (xyz[w * 3] - pu[0]) * f, pu[1] + (xyz[w * 3 + 1] - pu[1]) * f, top]);
142
+ }
143
+ }
144
+ return { lo, hi };
145
+ };
146
+ // Merge low points within merge_mm of a deeper one; deepest first.
147
+ found.sort((p, q) => q.depth - p.depth);
148
+ const kept = [];
149
+ for (const f of found) {
150
+ const near = kept.some(k => Math.hypot(xyz[k.v * 3] - xyz[f.v * 3], xyz[k.v * 3 + 1] - xyz[f.v * 3 + 1], z(k.v) - z(f.v)) <= merge);
151
+ if (!near)
152
+ kept.push(f);
153
+ }
154
+ const r2 = (n) => Math.round(n * 100) / 100;
155
+ return {
156
+ regions: kept.slice(0, limit).map(({ v, depth }) => ({ v, depth, ...hanging(v, z(v) + depth) })).map(({ v, depth, lo: l, hi: h }) => ({
157
+ z: r2(z(v) - minZ), depth_mm: r2(depth),
158
+ box_mm: { min: [r2(l[0]), r2(l[1]), r2(l[2] - minZ)], max: [r2(h[0]), r2(h[1]), r2(h[2] - minZ)] },
159
+ })),
160
+ count: kept.length,
161
+ model_min_z: r2(minZ),
162
+ };
163
+ }
164
+ /** The slicer said a model has floating regions or small islands: a cosmetic warning this rule bounds. */
165
+ export function isFloatingWarning(message) {
166
+ return !!message && /floating regions?|small islands?|isolated islands?/i.test(message);
167
+ }
168
+ export const SLICE_WARNING_RULE = "A cosmetic warning (floating regions, small islands) gets one targeted fix and one re-slice, then stops: if it remains, report it in the result or slice with supports on. Do not rebuild and re-slice to chase it. A region that is a separate body in mid-air, or on a feature that carries load or makes a fit, is not cosmetic: fix that one properly.";
169
+ /**
170
+ * What slice_stl adds to a slice that worked but warned about floating regions: the rule above, and where the
171
+ * regions are when the input is an STL the slicer did not turn (orient, rotate). Never throws: a location it
172
+ * cannot find is left out, with why.
173
+ */
174
+ export async function floatingWarningFacts(report, modelPath, turned) {
175
+ if (!report || report.failed || !isFloatingWarning(report.message))
176
+ return {};
177
+ const base = { next: SLICE_WARNING_RULE };
178
+ if (!/\.stl$/i.test(modelPath))
179
+ return { ...base, floating_regions_unlocated: "Only an STL input is located; this was a 3MF." };
180
+ if (turned)
181
+ return { ...base, floating_regions_unlocated: "The slicer turned or scaled the model (orient, rotate or scale), so the STL's own coordinates would mislead." };
182
+ try {
183
+ const stat = await fs.stat(modelPath);
184
+ if (stat.size > MAX_BYTES)
185
+ return { ...base, floating_regions_unlocated: "The STL is too large to search." };
186
+ const located = floatingRegions(stlTriangles(await fs.readFile(modelPath)));
187
+ return {
188
+ ...base,
189
+ floating_regions: {
190
+ ...located,
191
+ frame: "Each region starts at z and hangs depth_mm below where it joins the rest; box_mm bounds what hangs. x and y are the STL's own millimetres; z is millimetres above its lowest point, which the slicer puts on the plate.",
192
+ },
193
+ };
194
+ }
195
+ catch (error) {
196
+ return { ...base, floating_regions_unlocated: `Could not read the STL: ${error instanceof Error ? error.message : String(error)}` };
197
+ }
198
+ }
@@ -23,6 +23,7 @@
23
23
  * BBL only. Other vendors are out of scope and rejected explicitly so we
24
24
  * fail loud rather than producing dangerous gcode for hardware we don't own.
25
25
  */
26
+ import { FilamentSlotsError } from "../refusal.js";
26
27
  import fs from "node:fs/promises";
27
28
  import { existsSync, realpathSync } from "node:fs";
28
29
  import path from "node:path";
@@ -586,6 +587,9 @@ export async function flattenForCli(opts) {
586
587
  normalizeForCli(processFlat, "process", opts.processLeaf);
587
588
  filamentFlats.forEach((f, i) => normalizeForCli(f, "filament", opts.filamentLeaves[i]));
588
589
  if (opts.filamentColours && opts.filamentColours.length !== filamentFlats.length) {
590
+ // More colours than slots is a design the loaded filaments can't print in its colours: said plainly (#858).
591
+ if (opts.filamentColours.length > filamentFlats.length)
592
+ throw new FilamentSlotsError(opts.filamentColours.length, filamentFlats.length);
589
593
  throw new Error(`${opts.filamentColours.length} filament colours were supplied for ${filamentFlats.length} filament slots.`);
590
594
  }
591
595
  filamentFlats.forEach((f, i) => ensureFilamentColour(f, opts.filamentColours?.[i]));
@@ -59,6 +59,8 @@ export const TOOL_ANNOTATIONS = {
59
59
  slice_with_template: hints(false, true, false, true),
60
60
  // New 3MF at a caller-chosen path; never overwrites, so a repeat fails and changes nothing.
61
61
  counterpart_make_3mf: hints(false, false, true, false),
62
+ // A new folder of STLs each call, inside a caller-chosen folder; never overwrites.
63
+ counterpart_part_meshes: hints(false, false, false, false),
62
64
  // Copies into the template registry, replacing a template of the same name.
63
65
  save_template: hints(false, true, true, false),
64
66
  // Replaces BAMBU_DEFAULT_CONNECTION_MODE/TYPE in .env and in this process.
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.95",
3
+ "version": "1.1.97",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "counterpart": {
6
6
  "contract": "counterpart/1",
7
- "notes": "Checks what a design is for on the design as used, and returns this server’s own redacted diagnostics for bug reports.",
7
+ "notes": "Builds designs early and measures a scan once, gives each part of any 3MF as its own mesh in its colour, and says plainly when a two-colour print needs an AMS.",
8
8
  "autoUpdate": true
9
9
  },
10
10
  "main": "dist/index.js",
@@ -417,21 +417,23 @@ export const CAD_DESIGN_PROMPT = {
417
417
  description:
418
418
  "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
419
419
  text: `Use code-CAD for dimensioned functional designs and parameter edits. Build in millimetres with build123d 0.13.0; the MCP owns the Python environment, execution, export, validation and rendering. Check cad_status and use cad_setup with install: true when needed. No Blender, Fusion, network or printer access is available to your script.
420
- A new design starts from the product, in this order. First, name two or three products a person would buy for this request (search when you are not sure what is sold) and say which one the design follows. Second, choose from the cookbook by purpose: the list below says what each example is for (cad_examples with no name returns it with each one's pattern and product). Read the example whose use is nearest the request, with cad_examples and its name, before deciding anything else, and adapt its form and pattern, never its sizes. Third, and only then, choose the mechanism (a clamp, screw, spring, hinge or snap) and read a second example for it if you need one. A mechanism chosen before the product gives a bracket with the mechanism bolted on.
421
- Then state the purpose as data, before any geometry: a literal PURPOSE = {...} beside P (cad_run reads it from the source; parameters cannot change it). "for": what it is for in the person's words (who uses it, where, doing what); "modelled_on": the bought product; "holds": [{"body": name, "mass_g": grams}] for what it carries; "mounts": [{"body": name, "by": "tape", "rests", "screw", "clamp", "hook" or "other"}] for each surface that takes the load; "user": [x, y, z], the eye of the person who uses it, in mm in the use() frame, when it shows them something; optional "jolt_g", "press_n", "reach_mm", "material" and "faces": {"body": name, "within_deg": 25}. Its words add requirements whatever you list: a holder, hook, stand, dock, mount, rack, bracket, cradle or organizer must name what it holds and what it mounts to; anything in a vehicle takes jolts of at least 1.5 g in every direction; a phone, tablet or screen it holds must face the user's eye within 25 degrees. Then define use() beside build(): return Compound(children=[...]) of the part as it is used, Z up and gravity along -Z, with each held object at its real size and pose labelled "held:<body>" and each surface it meets as a solid slab where it really is (a dash face at its real angle, a desk's underside, a wall) labelled "world:<body>", all touching the part where they really touch. cad_run computes the loads at each mount from that geometry (gravity on the part and what it holds, the jolts, a hand pressing the held object), checks tape against 3M VHB's published stresses and that a resting part neither tips, lifts nor slides, checks that a held screen faces the user, draws renders.use (from the user's eye when given) and reports it all in purpose. final: true is recorded only when ready is true; until then the result lists final_refused. A run that is not the design itself (a part exported only for cad_check_fit, a reference, a diagnostic) is a check: pass role: "check" to every cad_run that is not the design itself, so it is never mistaken for the model (it is never final and evaluates no PURPOSE). Every valid run that is not final carries draft_reasons, saying why. When a requirement fails, change the design the way the bought products solve it (a joint that aims it, a broader pad, a wider or heavier base), never the purpose.
420
+ Build early, in pieces. The first cad_run is a rough but complete model within your first few turns: each main body at about its size and place, in simple shapes. Then add one body, mechanism or detail per run, read what the run returns, and go on. Never write a whole multi-part script in your head, and never plan the full design in one long thought before the first run: build, look, then add. A wrong first guess costs one quick run; a long plan that was never built costs many minutes and is still unchecked. Every check below still applies; each runs as soon as the geometry it checks exists, not before the first build. Call cad_run once at a time: the engine runs one call at a time, so parallel calls only queue.
421
+ A new design starts from the product, and each step before the first run is a sentence, not a study. First, name two or three products a person would buy for this request (search only when you are not sure what is sold) and say which one the design follows. Second, choose from the cookbook by purpose: the list below says what each example is for (cad_examples with no name returns it with each one's pattern and product). Read the one example whose use is nearest the request, with cad_examples and its name, and adapt its form and pattern, never its sizes. Third, and only then, choose the mechanism (a clamp, screw, spring, hinge or snap) and read a second example for it if you need one. A mechanism chosen before the product gives a bracket with the mechanism bolted on.
422
+ State the purpose as data in the first build, as a short first version, and complete it as the design grows: a literal PURPOSE = {...} beside P (cad_run reads it from the source; parameters cannot change it). "for": what it is for in the person's words (who uses it, where, doing what); "modelled_on": the bought product; "holds": [{"body": name, "mass_g": grams}] for what it carries; "mounts": [{"body": name, "by": "tape", "rests", "screw", "clamp", "hook" or "other"}] for each surface that takes the load; "user": [x, y, z], the eye of the person who uses it, in mm in the use() frame, when it shows them something; optional "jolt_g", "press_n", "reach_mm", "material" and "faces": {"body": name, "within_deg": 25}. Its words add requirements whatever you list: a holder, hook, stand, dock, mount, rack, bracket, cradle or organizer must name what it holds and what it mounts to; anything in a vehicle takes jolts of at least 1.5 g in every direction; a phone, tablet or screen it holds must face the user's eye within 25 degrees. Add use() beside build() once the main bodies exist, by the second or third run: return Compound(children=[...]) of the part as it is used, Z up and gravity along -Z, with each held object at its real size and pose labelled "held:<body>" and each surface it meets as a solid slab where it really is (a dash face at its real angle, a desk's underside, a wall) labelled "world:<body>", all touching the part where they really touch. cad_run computes the loads at each mount from that geometry (gravity on the part and what it holds, the jolts, a hand pressing the held object), checks tape against 3M VHB's published stresses and that a resting part neither tips, lifts nor slides, checks that a held screen faces the user, draws renders.use (from the user's eye when given) and reports it all in purpose. final: true is recorded only when ready is true; until then the result lists final_refused. A run that is not the design itself (a part exported only for cad_check_fit, a reference, a diagnostic) is a check: pass role: "check" to every cad_run that is not the design itself, so it is never mistaken for the model (it is never final and evaluates no PURPOSE). Every valid run that is not final carries draft_reasons, saying why. When a requirement fails, change the design the way the bought products solve it (a joint that aims it, a broader pad, a wider or heavier base), never the purpose.
422
423
  The cookbook, by what each example is for:
423
424
  ${cadExampleLines()}
424
- Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept as the script's opening docstring, the way every cookbook example does: what it is, then "Modelled on:" the bought product you named, its mechanism, the load path, the print orientation and why. A script whose header names no product was designed from the mechanism. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
425
+ Form first: build the product's shape, not a profile pushed up. Write the concept in a few lines as the first build's opening docstring, the way every cookbook example does: what it is, then "Modelled on:" the bought product you named, its mechanism, the load path, the print orientation and why; correct it as the design firms up. A script whose header names no product was designed from the mechanism. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
425
426
  What the cookbook taught about this engine: return several bodies as Compound([a, b]); bodies that touch or overlap come back invalid, so leave a real gap (0.2 mm or more) or union them, and check that solid_count equals the bodies you intend (for a print-in-place mechanism that count is the first evidence nothing fused). fillet() often fails on the edges of an outline unioned from many curves, where chamfer() usually succeeds: fillet or chamfer simple bodies before the booleans that complicate them, and when a chamfer fails too, apply it to the plain body and union the details on afterwards. Do not round a sketch by growing and shrinking it with offset(): the solid looks right and its STEP comes back with no solids (the step_solids check fails). A whole Sphere() exports open at its poles: trim them (Sphere(r) & Box(2 * r, 2 * r, 2 * r - 0.1)). One fillet of the same radius over every edge of a box can export open: fillet in two passes with different radii. A model with moving parts takes a pose parameter: the assembled pose to judge it, the print plate to make it.
426
427
  Declare exactly one top-level P = {...} dictionary of JSON-compatible literal named parameters. Put every functional dimension in P; derive geometry from P. Define build() to return a build123d Shape or Compound of disjoint solid parts. When a design has separate bodies (print-in-place parts, a captive wheel, links of a fabric), return Compound(children=[...]) with a label on each body: cad_run then checks that each labelled body is exactly one solid, so a piece cut off one body cannot hide behind two bodies fused into one. Near pairs of solids are screened and, where the screen cannot clear them, measured exactly against P["print_in_place_clearance_mm"] when you declare it, else 0.3 mm. If the bodies are shown assembled rather than printed in place (a shaft in its hole at a fit clearance), set P["print_in_place"] = False: only touching or overlap is then a problem. Export in print orientation with the plate at Z = 0: a solid below it, or above it with nothing under it that reaches it, is a problem. Do not put construction or exports in a __main__ block: cad_run calls build() and exports the result. Imports, functions and derived P entries are fine. Parameters are applied to the literal defaults before derived expressions execute. For solid designs without inputs, the script and parameters file alone reconstruct it. For input-dependent designs, declare inputs as an array of {name, path} files: cad_run snapshots only those allowed files, exposes INPUTS[alias] to your script, and saves an inputs manifest. Retain the snapshots too for recovery; subsequent script_path edits reuse them unless inputs is explicitly supplied. No other personal files are readable. For a mesh-only experiment use mode: "mesh" and return a trimesh.Trimesh from build(); it exports and checks STL plus the same renders, with step: null and an explicit reason. It does not manufacture a fake parametric STEP or promise scan-cleanup capability.
427
428
  Call cad_run with script, output_dir and a plain name. It saves <name>.py and <name>.parameters.json before running, then exports <name>.stl and <name>.step in a fresh subfolder. For an edit, one cad_run with script_path pointing to the earlier .py, parameters containing just the changed dimension, output_dir and name regenerates it without resending the script. Existing parameter values are retained; unknown names and type changes are refused. A killed run can be retried from its checkpoint in a new workspace; mutations are never replayed automatically.
428
429
  Captured mesh preparation: load_scan(name, source_units="m" or "mm", up_axis="x"|"-x"|"y"|"-y"|"z"|"-z", ground=True) is provided to build(). Name must be a declared input. Declare source units and the object's usage-up axis explicitly: the helper converts metres to millimetres, applies a rigid up-axis rotation and translates the lowest Z to zero; it never guesses scale or fits to calipers. Geometry/texture references must be declared inputs too; snapshots preserve distinct original filenames. Exports must be millimetres, Z up, in the orientation the object is used.
430
+ Measure a scan once, before designing from it: one check run (role: "check", mode: "mesh") whose build() is r = measure_scan(load_scan("scan", source_units="m", up_axis="y")); return r["mesh"]. It keeps the scan's main piece, removes the turntable or support it stands on (fitted even when tilted) and any floating pieces, and prints scan_measure: size_mm in the object's own frame (long side on x, across on y, height on z), profile (its length and depth at ten heights), what it removed, and scan-measure.png in the run folder (silhouettes seen from -y, +x and above, ticks every 10 mm); the returned mesh is the object alone in the scan's x and y, standing at z = 0. Read both and design from those numbers instead of writing measuring scripts of your own. When support_removed is set, check it against the photos: if the cut piece is the object's own base rather than a turntable, design from its uncut_size_mm. They carry the scan's accuracy: calipers or published sizes win where they exist.
429
431
  Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y") from build() in mode: "mesh" to export an unchanged, prepared reference STL for cad_check_fit. Declare every linked OBJ/MTL/texture asset. If you crop, simplify, fill, or otherwise alter this reference, report exactly what you excluded/changed and that the fit check proves only that reduced reference in the stated pose. A fit check against a scan is information; it must never resize or override an interface specified by measured dimensions. Keep those measured interfaces and report the discrepancy.
430
432
  Result selection and edits: set final: true only on the result you select. cad-result.json in each immediate run folder is protected from script writes and retains final, completed_at, lineage_id (source hash), full checks and artifact paths; clients can discover the latest completed final record after restart without rebuilding. Final is a selection marker, not a replacement for valid/checks. Queued calls may expire with cad-queue-timeout before dispatch; do not automatically replay. Unchanged declared files reuse a read-only content-addressed bundle under output_dir/.cad-inputs, preserving filenames and restricting reads to that bundle. Keep this shared cache with the saved runs.
431
433
  Mesh cleanup workflow: return a trimesh.Trimesh in mode: "mesh". Load the prepared mesh, fit needed geometry with NumPy/SciPy, rebuild regular sections/features with build123d or manifold3d CrossSection/extrusion/revolve, and combine meshes with manifold3d booleans. scikit-image supplies marching cubes for voxel/SDF work; Shapely supplies planar operations; Pillow supplies image/texture reads. Keep numeric choices in P and regenerate from declared inputs. Validate closure, winding, manifold status, dimensions and all six views using cad_run. What to regularise, infer, preserve or label comes from the caller's cleanup rules, not this engine prompt.
432
- Multi-colour 3MF projects: build() may return project_3mf() instead of a shape. A new project: p = project_3mf(); p.add_part(shape, name="Lid", filament=2, object="Box", plate=1) for each part (parts that share object= are one object, printed as one piece; plates from 1), in solid mode with build123d shapes (the checks fuse each object's parts) or mode: "mesh" with trimesh parts. Editing a designer's 3MF: declare it as an input and p = project_3mf("kit") in mode: "mesh"; p.objects lists its objects (name, id, plate; p.object(id or unique name)) and their parts (name, id, filament, painted, mesh: a trimesh in the object's frame); p.add_part(shape, name=..., filament=..., object="Body") adds a part in that object's frame, p.replace_part(part, mesh) swaps a part's mesh (its painting goes with the old mesh) and p.set_part(part, name=..., filament=...) renames or recolours one; everything else in the file (print settings, painting, plates, other parts) is kept. cad_run writes <name>.3mf beside the STL and returns three_mf and three_mf_project (each plate's parts and filaments, read back from the file); slice it with slice_stl, never by rebuilding it from the STL.
434
+ Multi-colour 3MF projects: build() may return project_3mf() instead of a shape. A new project: p = project_3mf(); p.add_part(shape, name="Lid", filament=2, color="#1A1A1A", object="Box", plate=1) for each part (parts that share object= are one object, printed as one piece; plates from 1; color, given for every part or none, declares each filament's colour in the 3MF), in solid mode with build123d shapes (the checks fuse each object's parts) or mode: "mesh" with trimesh parts. Editing a designer's 3MF: declare it as an input and p = project_3mf("kit") in mode: "mesh"; p.objects lists its objects (name, id, plate; p.object(id or unique name)) and their parts (name, id, filament, painted, mesh: a trimesh in the object's frame); p.add_part(shape, name=..., filament=..., object="Body") adds a part in that object's frame, p.replace_part(part, mesh) swaps a part's mesh (its painting goes with the old mesh) and p.set_part(part, name=..., filament=...) renames or recolours one; everything else in the file (print settings, painting, plates, other parts) is kept. cad_run writes <name>.3mf beside the STL and returns three_mf and three_mf_project (each plate's parts and filaments, read back from the file); slice it with slice_stl, never by rebuilding it from the STL. A design in several colours gets them from the same run as the model: build() returns project_3mf() with one add_part per colour body, so one cad_run builds the shape once and writes the STL and the 3MF together. Never re-run the whole script once per colour to export each colour's STL: that repeats the full build for every colour.
433
435
  Captured scan touch-up: t = scan_touchup(load_scan("scan", source_units="m", up_axis="y", ground=False), colour="colour", normal="normal", edge_mm=0.4) takes a textured capture (declare its OBJ, MTL and colour and normal map PNGs as inputs; pass the map aliases). It removes loose pieces and spikes, closes holes and refines to edge_mm without shrinking the body. t.regions() prints the colour regions (id, colour, area, size, flatness; 0 is the body) to build.log and saves regions.png in the run folder: read both, then name regions by id in the same scan and edge_mm. t.flatten(ids, shape="plane" or "curved"), t.bead(id, diameter_mm, proud_mm), t.cord(id, diameter_mm, proud_mm) (a cord follows its region's own curve) and t.seat(height_mm) record steps; return t.mesh(relief_gain=1.0), which adds the normal map's measured relief, applies the steps with manifold3d and prints its changes. Keep relief_gain at 1: a larger gain amplifies the map's noise, not stitches. When the caller's rules call for a textile's relief the scan missed (fabric, knit, crochet the photos show raised), t.texture_relief(height_mm, regions=None) raises its stitch pattern from the colour texture on the textile only (never flattened, beaded or corded regions); about 0.6 to 1.0 mm peak to peak prints visibly. It is off unless called: never for hard objects, printed graphics or labels.
434
436
  The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. After every cad_run, Read its perspective view (renders.perspective, as the result's next says) before the next cad_run or any other change: a run you have not looked at tells you nothing about the form. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. Before the final run, list what the views show is wrong against the bought product you named (for a scan, the object in its photos), and fix each one or report it. To get a number out of a design (a spring force, a strain, a clearance you derived), print() it in the script: the result returns it as printed, with no need to make a run fail. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
435
437
  Fit, flexure and thread parameters: put each interface's nominal size, its source (measured, published, or assumed), the print correction, and the design fit in P as separate named values, so a fit report revises one number without resending the script. Model every dimension you claim: a parameter the geometry never uses (a wallet or case width that no cut or wall reads) is a defect; use it or remove it. Shape flexures so their bending lies in the layer plane of the exported print orientation, with the stroke, preload, and hard-stop gap as P values; build the stopped pose as well as the rest pose when checking. Model printed threads as explicit coarse geometry with the same pitch on both sides and clearance as a radial P offset; never scale a screw to clear its hole.
436
- Check insertion and articulated poses with cad_check_fit against each object state that matters (the bare product, the product in its case, and the case with its attachment as its own reference envelope), including the widest section on the way in. Report interference and minimum gap per state. In your summary, attach each "fits", "holds", and "prints without supports" claim to the check or slice number that shows it; a valid flag alone shows none of them. Apply fdm_design and fdm_slicing too. When a part meets a real object apply fdm_fit, and when it flexes, grips, snaps or springs apply fdm_flexures: if they were not attached, read them with the design_guidance tool before choosing that fit or spring. Never invoke a printer as part of constructing CAD.`,
438
+ Once the bodies it involves exist, check insertion and articulated poses with cad_check_fit against each object state that matters (the bare product, the product in its case, and the case with its attachment as its own reference envelope), including the widest section on the way in. Report interference and minimum gap per state. In your summary, attach each "fits", "holds", and "prints without supports" claim to the check or slice number that shows it; a valid flag alone shows none of them. Apply fdm_design and fdm_slicing too. When a part meets a real object apply fdm_fit, and when it flexes, grips, snaps or springs apply fdm_flexures: if they were not attached, read them with the design_guidance tool before choosing that fit or spring. Never invoke a printer as part of constructing CAD.`,
437
439
  };
@@ -243,9 +243,10 @@ class Project3mf:
243
243
  if len(self._new) + sum(1 for e in self._edits if 'geometry' in e) >= MAX_PARTS:
244
244
  raise ValueError(f'A project takes at most {MAX_PARTS} new or replaced parts.')
245
245
 
246
- def add_part(self, geometry, *, name, filament=None, object=None, plate=1):
246
+ def add_part(self, geometry, *, name, filament=None, object=None, plate=1, color=None):
247
247
  """Add a part. Editing a 3MF: into the base object `object` (name or id), in that object's frame.
248
- A new project: into the object named `object` (default: one object per part's name) on `plate`."""
248
+ A new project: into the object named `object` (default: one object per part's name) on `plate`, with an
249
+ optional color '#RRGGBB' (give every part one, or none): the 3MF then declares each filament's colour."""
249
250
  self._count()
250
251
  name = _name(name, 'name')
251
252
  geometry = _geometry(geometry, f'Part {name!r}')
@@ -257,15 +258,19 @@ class Project3mf:
257
258
  raise ValueError(f'Object {target.name!r} is one mesh without parts (a plain 3MF): only a Bambu Studio or OrcaSlicer project\'s objects take new parts.')
258
259
  if plate != 1:
259
260
  raise ValueError('Editing a 3MF, a new part sits on its object\'s plate; plate cannot be set.')
261
+ if color is not None:
262
+ raise ValueError('Editing a 3MF, its filaments keep their own colours; color applies to a new project.')
260
263
  self._edits.append({'op': 'add_part', 'object_id': target.id, 'name': name,
261
264
  'filament': self._declared(filament if filament is not None else (target.parts[0].filament if target.parts else 1), 'filament'),
262
265
  'geometry': geometry})
263
266
  else:
264
267
  if isinstance(plate, bool) or not isinstance(plate, int) or not 1 <= plate <= MAX_PLATES:
265
268
  raise ValueError(f'plate must be an integer from 1 to {MAX_PLATES}.')
269
+ if color is not None and not (isinstance(color, str) and re.fullmatch(r'#[0-9A-Fa-f]{6}', color)):
270
+ raise ValueError('color must be a colour as #RRGGBB.')
266
271
  self._new.append({'object': _name(object, 'object') if object is not None else name, 'plate': plate, 'name': name,
267
272
  'filament': _filament(filament if filament is not None else len(self._new) + 1, 'filament'),
268
- 'geometry': geometry})
273
+ 'geometry': geometry, **({'color': color.upper()} if color else {})})
269
274
  return self
270
275
 
271
276
  def _base_part(self, part):
@@ -404,7 +409,7 @@ def export(project, out, mode):
404
409
  raise ValueError(f'Object {key!r} has parts on two plates; one object sits on one plate.')
405
410
  index, mesh = stl(part['geometry'])
406
411
  objects.setdefault(key, {'name': key, 'plate': part['plate'], 'parts': []})['parts'].append(
407
- {'stl': index, 'name': part['name'], 'filament': part['filament']})
412
+ {'stl': index, 'name': part['name'], 'filament': part['filament'], **({'color': part['color']} if 'color' in part else {})})
408
413
  meshes.setdefault(key, []).append(mesh)
409
414
  for key in objects:
410
415
  combined += _fused(meshes[key])
@@ -0,0 +1,207 @@
1
+ """measure_scan(scan): a captured object measured once, before any design (scan-to-make #859).
2
+
3
+ A design pass measured the DAD sign's scan by hand twice, writing a script each time to drop the turntable and the
4
+ floating chunk under it. This does that in one call: it keeps the scan's main piece, cuts away a turntable or support
5
+ it stands on, and returns the object's size in its own frame (its long side along x), its width and depth at ten
6
+ heights, and front, side and top silhouettes with a millimetre scale, saved as one picture in the run folder.
7
+ """
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+
14
+ def _components(V, F):
15
+ from scipy.sparse import coo_matrix
16
+ from scipy.sparse.csgraph import connected_components
17
+ e = np.concatenate([F[:, [0, 1]], F[:, [1, 2]], F[:, [2, 0]]])
18
+ A = coo_matrix((np.ones(len(e)), (e[:, 0], e[:, 1])), shape=(len(V), len(V)))
19
+ return connected_components(A, directed=False)[1]
20
+
21
+
22
+ def _support_plane(V, F, n, area, body):
23
+ """The top of a turntable or support plate the object stands on, as a plane (point, unit normal), or None: the
24
+ largest face-up plane in the lower part of the piece, reaching wider than what stands on it. Fitted, not assumed
25
+ level: a turntable is often a degree or two off."""
26
+ sel = body[F[:, 0]]
27
+ up = sel & (n[:, 2] > 0.9)
28
+ if not up.any():
29
+ return None
30
+ centres = V[F].mean(1)
31
+ lo, hi = V[body][:, 2].min(), V[body][:, 2].max()
32
+ weight, edges = np.histogram(centres[up, 2], bins=np.arange(lo, hi + 4.0, 4.0), weights=area[up])
33
+ k = int(np.argmax(weight))
34
+ near = up & (centres[:, 2] > edges[k] - 6) & (centres[:, 2] < edges[k + 1] + 6)
35
+ for _ in range(3):
36
+ normal = (n[near] * area[near, None]).sum(0)
37
+ normal /= np.linalg.norm(normal)
38
+ point = (centres[near] * area[near, None]).sum(0) / area[near].sum()
39
+ near = sel & (n @ normal > np.cos(np.radians(5))) & (np.abs((centres - point) @ normal) < 2.0)
40
+ plate_area = float(area[near].sum())
41
+ height = (V - point) @ normal
42
+ above = body & (height > 1.0)
43
+ below = body & ~above
44
+ footprint = np.ptp(V[body][:, 0]) * np.ptp(V[body][:, 1])
45
+ if not above.any() or point[2] > lo + 0.6 * (hi - lo) or plate_area < 0.15 * footprint:
46
+ return None
47
+ # A turntable is round and reaches well past what stands on it. A product's own base (a lamp's square foot, a
48
+ # plinth) usually isn't both; one that is still gets cut, and the result says so (uncut_size_mm, note).
49
+ below_area, roundness = _hull_shape(V[below][:, :2])
50
+ above_area, _ = _hull_shape(V[above][:, :2])
51
+ if roundness < 0.8 or below_area < 2.5 * above_area:
52
+ return None
53
+ return point, normal
54
+
55
+
56
+ def _hull_shape(xy):
57
+ """A footprint's convex-hull area and how round it is: the area over the circle through its farthest point (a
58
+ disc is about 1, a square 0.64). (0, 0) when the footprint is a point or a line."""
59
+ from scipy.spatial import ConvexHull, QhullError
60
+ try:
61
+ hull = ConvexHull(xy)
62
+ except (QhullError, ValueError):
63
+ return 0.0, 0.0
64
+ ring = xy[hull.vertices]
65
+ radius = np.linalg.norm(ring - ring.mean(0), axis=1).max()
66
+ return float(hull.volume), float(hull.volume / (np.pi * radius ** 2)) if radius > 0 else 0.0
67
+
68
+
69
+ def _rect_yaw(xy):
70
+ """The yaw (radians) that turns the footprint's smallest bounding rectangle square to x and y, its long side on x."""
71
+ from scipy.spatial import ConvexHull, QhullError
72
+ try:
73
+ hull = xy[ConvexHull(xy).vertices]
74
+ except (QhullError, ValueError):
75
+ return 0.0 # a point or a line: measured in the scan's own x and y
76
+ best = None
77
+ for i in range(len(hull)):
78
+ d = hull[(i + 1) % len(hull)] - hull[i]
79
+ a = -np.arctan2(d[1], d[0])
80
+ c, s = np.cos(a), np.sin(a)
81
+ r = hull @ np.array([[c, s], [-s, c]])
82
+ size = np.ptp(r, axis=0)
83
+ if best is None or size[0] * size[1] < best[0]:
84
+ best = (size[0] * size[1], a if size[0] >= size[1] else a + np.pi / 2)
85
+ return best[1]
86
+
87
+
88
+ def _silhouettes(P, F, path, size):
89
+ from PIL import Image, ImageDraw
90
+ lo, hi = P.min(0), P.max(0)
91
+ views = (("seen from -y (x, z)", 0, 2), ("seen from +x (y, z)", 1, 2), ("seen from above (x, y)", 0, 1))
92
+ span = max(np.ptp(P[:, 0]), np.ptp(P[:, 1]), np.ptp(P[:, 2]))
93
+ px, pad = 600, 40
94
+ scale = (px - 2 * pad) / span
95
+ sheet = Image.new("RGB", (px * 3, px), (255, 255, 255))
96
+ for i, (name, a, b) in enumerate(views):
97
+ im = Image.new("RGB", (px, px), (255, 255, 255))
98
+ d = ImageDraw.Draw(im)
99
+ T = P[F]
100
+ for tri in T:
101
+ d.polygon([(pad + (v[a] - lo[a]) * scale, px - pad - (v[b] - lo[b]) * scale) for v in tri], fill=(40, 40, 40))
102
+ # a 10 mm grid and the extents written on it
103
+ for g in np.arange(0, span + 10, 10):
104
+ d.line([(pad + g * scale, px - pad + 6), (pad + g * scale, px - pad + 12)], fill=(200, 0, 0))
105
+ d.text((8, 8), f"{name}: {np.ptp(P[:, a]):.1f} x {np.ptp(P[:, b]):.1f} mm; ticks every 10 mm", fill=(0, 0, 0))
106
+ sheet.paste(im, (i * px, 0))
107
+ sheet.save(path)
108
+
109
+
110
+ def measure_scan(scan, picture="scan-measure.png", support=True, levels=10):
111
+ """The object in a captured scan, measured once. scan: load_scan's trimesh (mm, Z up). Prints one JSON line,
112
+ {"scan_measure": {...}}, saves the silhouettes as `picture` in the run folder, and returns the same dict with
113
+ "mesh": the object alone (a trimesh) in the scan's own x and y, standing at z = 0; when a support is removed it is
114
+ levelled on the support's plane about the plane's own point and cut 0.5 mm above it."""
115
+ import trimesh
116
+ V = np.asarray(scan.vertices, dtype=np.float64)
117
+ F = np.asarray(scan.faces, dtype=np.int64)
118
+ scan_size = np.ptp(V, axis=0)
119
+ tri = V[F]
120
+ cross = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])
121
+ area = np.linalg.norm(cross, axis=1) / 2
122
+ n = cross / np.maximum(np.linalg.norm(cross, axis=1), 1e-20)[:, None]
123
+ label = _components(V, F)
124
+ piece_area = np.bincount(label[F[:, 0]], area, label.max() + 1)
125
+ main = int(np.argmax(piece_area))
126
+ body = label == main
127
+ # The ten largest removed pieces only: a noisy scan's thousands of specks are counted, not each measured.
128
+ others = [int(k) for k in np.argsort(-piece_area) if k != main and piece_area[k] > 0]
129
+ removed = [{"size_mm": [round(float(v), 1) for v in np.ptp(V[label == k], axis=0)], "area_mm2": round(float(piece_area[k]), 1)}
130
+ for k in others[:10]]
131
+ plane = _support_plane(V, F, n, area, body) if support else None
132
+ if plane is not None:
133
+ # Stand the object on the support's plane, then keep what is above it.
134
+ point, normal = plane
135
+ axis = np.cross(normal, [0, 0, 1])
136
+ angle = float(np.arccos(np.clip(normal[2], -1, 1)))
137
+ V = V - point
138
+ if np.linalg.norm(axis) > 1e-9:
139
+ V = V @ trimesh.transformations.rotation_matrix(angle, axis / np.linalg.norm(axis))[:3, :3].T
140
+ # Levelled about the support's own point, which keeps its x and y: the scan's x and y stay where they were.
141
+ V = V + [point[0], point[1], 0.0]
142
+ body_faces = body[F].all(1)
143
+ obj = trimesh.Trimesh(V, F[body_faces], process=False)
144
+ # process=False keeps every vertex: the removed pieces' would otherwise still count in the floor, size and profile.
145
+ obj.remove_unreferenced_vertices()
146
+ if plane is not None:
147
+ # What stands on the support: cut 0.5 mm above its plane, then the largest connected piece above the cut.
148
+ try:
149
+ # Capped, so the object alone is closed again where it stood and its volume can be measured.
150
+ obj = obj.slice_plane([0, 0, 0.5], [0, 0, 1], cap=True)
151
+ except Exception: # noqa: BLE001 (no triangulation engine for the cap: the open cut still measures)
152
+ obj = obj.slice_plane([0, 0, 0.5], [0, 0, 1])
153
+ obj.remove_unreferenced_vertices()
154
+ label2 = _components(np.asarray(obj.vertices), np.asarray(obj.faces))
155
+ pick = label2[obj.faces[:, 0]] == int(np.argmax(np.bincount(label2[obj.faces[:, 0]], obj.area_faces)))
156
+ obj = trimesh.Trimesh(obj.vertices, obj.faces[pick], process=False)
157
+ obj.remove_unreferenced_vertices()
158
+ floor = 0.0 if plane is not None else float(obj.vertices[:, 2].min())
159
+ obj.apply_translation([0, 0, -floor])
160
+ used_V = np.asarray(obj.vertices)
161
+ Fk = np.asarray(obj.faces)
162
+ yaw = _rect_yaw(used_V[:, :2])
163
+ c, s = np.cos(yaw), np.sin(yaw)
164
+ R = np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
165
+ P = used_V @ R.T
166
+ centre = (P.min(0) + P.max(0)) / 2
167
+ P = P - [centre[0], centre[1], 0]
168
+ size = np.ptp(P, axis=0)
169
+ size[2] = P[:, 2].max()
170
+ # The whole main piece in the same frame, support included: the size if the cut piece was the object's own base.
171
+ whole = (V[body] - [0, 0, floor]) @ R.T
172
+ uncut = np.ptp(whole, axis=0)
173
+ # The surface's own cross-section at each height, not the vertices near it: a mesh of large triangles has none there.
174
+ profile = []
175
+ framed = trimesh.Trimesh(P, Fk, process=False)
176
+ for h in np.linspace(0, size[2], levels + 2)[1:-1]:
177
+ section = framed.section(plane_origin=[0, 0, h], plane_normal=[0, 0, 1])
178
+ if section is not None and len(section.vertices) > 1:
179
+ xy = np.asarray(section.vertices)[:, :2]
180
+ profile.append({"z_mm": round(float(h), 1), "length_mm": round(float(np.ptp(xy[:, 0])), 1),
181
+ "depth_mm": round(float(np.ptp(xy[:, 1])), 1)})
182
+ report = {
183
+ "size_mm": [round(float(v), 1) for v in size],
184
+ "frame": "Object frame: x along its long side, y across, z up from where it stands; centred on x and y.",
185
+ "yaw_deg": round(float(np.degrees(yaw)) % 180, 1),
186
+ "scan_size_mm": [round(float(v), 1) for v in scan_size],
187
+ "support_removed": None if plane is None else {
188
+ "top_z_mm": round(float(plane[0][2]), 1), "tilt_deg": round(float(np.degrees(np.arccos(np.clip(plane[1][2], -1, 1)))), 1),
189
+ "size_mm": [round(float(v), 1) for v in np.ptp(V[body & (V[:, 2] <= 0.5)], axis=0)],
190
+ "uncut_size_mm": [round(float(v), 1) for v in uncut],
191
+ "note": "A round plate wider than what stands on it was cut away as a turntable. If the photos show it is "
192
+ "the object's own base, design from uncut_size_mm instead."},
193
+ "cut_mm": 0.5 if plane is not None else None,
194
+ "pieces_removed": removed,
195
+ "pieces_removed_count": len(others),
196
+ "profile": profile,
197
+ "volume_mm3": None,
198
+ "picture": str(picture) if picture else None,
199
+ }
200
+ if obj.is_watertight:
201
+ report["volume_mm3"] = round(float(abs(obj.volume)), 1)
202
+ # The object as returned stands at z = 0, its cut face on the plate.
203
+ obj.apply_translation([0, 0, -float(obj.vertices[:, 2].min())])
204
+ if picture:
205
+ _silhouettes(P, Fk, Path(picture), size)
206
+ print(json.dumps({"scan_measure": report}))
207
+ return {**report, "mesh": obj}
@@ -335,7 +335,10 @@ def _regions(V, F, colours, clusters, min_area, max_regions=40):
335
335
  normal = (vn[sel] * w[:, None]).sum(0)
336
336
  normal /= np.linalg.norm(normal) + 1e-20
337
337
  rel = V[sel] - centre
338
- span = rel @ np.linalg.svd(rel * np.sqrt(w)[:, None], full_matrices=False)[2].T
338
+ # The weighted covariance's axes, longest first: always three, so a region of one or two vertices (a coarse
339
+ # scan's big vertex areas pass min_area) measures as a point or a line, not an IndexError (scan-to-make #858).
340
+ axes = np.linalg.eigh((rel * w[:, None]).T @ rel)[1][:, ::-1]
341
+ span = rel @ axes
339
342
  around = np.unique(pairs[pairs[:, 0] == rid][:, 1])
340
343
  out.append({"id": rid, "colour": "#%02x%02x%02x" % tuple(int(round(v * 255)) for v in colours[sel].mean(0)),
341
344
  "area_mm2": round(float(w.sum()), 1), "centre_mm": [round(float(v), 2) for v in centre],
package/src/cad/worker.py CHANGED
@@ -104,9 +104,10 @@ 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
+ from scan_measure import measure_scan
107
108
  from project3mf import Project3mf, export as export_project, project_factory
108
109
  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', {})),
109
- 'scan_touchup': scan_touchup_factory(request.get('inputs', {}))}
110
+ 'scan_touchup': scan_touchup_factory(request.get('inputs', {})), 'measure_scan': measure_scan}
110
111
  exec(compile(tree, request['script'], 'exec'), namespace)
111
112
  shape = namespace['build']()
112
113
  out = Path(request['output']) / request['name']
package/src/cad-engine.ts CHANGED
@@ -492,6 +492,7 @@ export class CadEngine {
492
492
  "worker.py",
493
493
  "geometry.py",
494
494
  "scan_touchup.py",
495
+ "scan_measure.py",
495
496
  "project3mf.py",
496
497
  "purpose.py",
497
498
  "process.ts",
@@ -47,6 +47,7 @@ export function bambuPrinterInfo(options: { server: { name: string; version: str
47
47
  camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
48
48
  cameraStream: !!model && (TCP_CAMERA_MODELS.has(model) || RTSP_CAMERA_MODELS.has(model)),
49
49
  diagnostics: true,
50
+ partMeshes: true,
50
51
  filaments: "ams",
51
52
  pause: true,
52
53
  resume: true,