bambu-printer-mcp 1.1.50 → 1.1.51

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.
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import os from "node:os";
9
9
  import path from "path";
10
10
  import { createServer as createHttpServer } from "node:http";
11
11
  import { randomUUID } from "node:crypto";
12
- import { STLManipulator, SLICER_TYPES, normalizeSlicerType, } from "./stl/stl-manipulator.js";
12
+ import { STLManipulator, SLICER_TYPES, normalizeSlicerType, SlicerRunError, } from "./stl/stl-manipulator.js";
13
13
  import { BambuNetworkBridge, describeBambuNetworkPrintError } from "./bambu-network-bridge.js";
14
14
  import { assertBambuNativeAvailable, bambuNativeControlsAvailable, bambuNativeUnavailableReason, interruptNativeOperations, validateBambuNativeMetadata, buildBambuNativeFanCommand, buildBambuNativeTemperatureCommand, printWithBambuNative, sendCommandWithBambuNative, uploadWithBambuNative, } from "./bambu-native.js";
15
15
  import { importFileViaBambuConnect } from "./bambu-connect.js";
@@ -2011,7 +2011,7 @@ class BambuPrinterMCPServer {
2011
2011
  },
2012
2012
  {
2013
2013
  name: "slice_stl",
2014
- description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer.",
2014
+ description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. A failed slice's text starts with those words.",
2015
2015
  inputSchema: {
2016
2016
  type: "object",
2017
2017
  properties: {
@@ -2686,7 +2686,7 @@ class BambuPrinterMCPServer {
2686
2686
  },
2687
2687
  {
2688
2688
  name: "lay_flat",
2689
- description: "Rotate the model so its largest flat face lies on the XY plane (Z=0)",
2689
+ description: "Rotate the model so a face rests on the bed (Z=0), choosing the orientation with the least part and support volume per mm² of bed contact. A face counts only if nothing hangs below it. Returns the new STL path; structuredContent.laid_flat is false, with the input path, when no orientation qualifies.",
2690
2690
  inputSchema: {
2691
2691
  type: "object",
2692
2692
  properties: {
@@ -3611,9 +3611,11 @@ class BambuPrinterMCPServer {
3611
3611
  console.warn("Could not resolve live printer filaments for slicing:", filamentError);
3612
3612
  }
3613
3613
  }
3614
- result = await this.stlManipulator.sliceSTL(String(args.stl_path), slicerType, slicerPath, activeSlicerProfile, undefined, // progressCallback
3614
+ const sliced = await this.stlManipulator.sliceSTLWithResult(String(args.stl_path), slicerType, slicerPath, activeSlicerProfile, undefined, // progressCallback
3615
3615
  printerPreset, sliceBambuOptions);
3616
- break;
3616
+ await progressNotifications;
3617
+ // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim.
3618
+ return { content: [{ type: "text", text: sliced.path }], structuredContent: sliced };
3617
3619
  }
3618
3620
  case "print_3mf": {
3619
3621
  if (!args?.three_mf_path) {
@@ -3853,11 +3855,14 @@ class BambuPrinterMCPServer {
3853
3855
  throw new Error("Missing required parameter: stl_path");
3854
3856
  result = await this.stlManipulator.centerModel(String(args.stl_path));
3855
3857
  break;
3856
- case "lay_flat":
3858
+ case "lay_flat": {
3857
3859
  if (!args?.stl_path)
3858
3860
  throw new Error("Missing required parameter: stl_path");
3859
- result = await this.stlManipulator.layFlat(String(args.stl_path));
3860
- break;
3861
+ const layFlatResult = await this.stlManipulator.layFlatWithResult(String(args.stl_path));
3862
+ await progressNotifications;
3863
+ // The text stays the STL path clients read; structuredContent says whether it was laid flat.
3864
+ return { content: [{ type: "text", text: layFlatResult.path }], structuredContent: layFlatResult };
3865
+ }
3861
3866
  case "blender_mcp_status":
3862
3867
  result = await this.blender.status(args ?? {}, extra.signal);
3863
3868
  break;
@@ -3919,11 +3924,14 @@ class BambuPrinterMCPServer {
3919
3924
  : `Check parameters and try again. Error: ${message}`,
3920
3925
  message,
3921
3926
  tool: name,
3927
+ // The slicer's own result.json; the message starts with its error_string and warnings.
3928
+ ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult } : {}),
3922
3929
  };
3923
3930
  // MCP clients validate structuredContent against a declared outputSchema even on
3924
3931
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
3925
3932
  return {
3926
- content: [{ type: "text", text: `Error: ${message}` }],
3933
+ // A slicer failure leads with the slicer's own words.
3934
+ content: [{ type: "text", text: error instanceof SlicerRunError && error.slicerText ? message : `Error: ${message}` }],
3927
3935
  ...(OUTPUT_SCHEMA_TOOLS.has(name) ? {} : { structuredContent: structured }),
3928
3936
  isError: true,
3929
3937
  };
@@ -52,6 +52,22 @@ export interface BambuSliceOptions {
52
52
  slicePlate?: number;
53
53
  processOverrides?: ProcessOverrides;
54
54
  }
55
+ /** Bambu Studio's or OrcaSlicer's own result.json, parsed verbatim. */
56
+ export type SlicerResult = Record<string, unknown>;
57
+ /** A sliced file, with the slicer's own result.json when it wrote one. */
58
+ export type SliceOutput = {
59
+ path: string;
60
+ slicer_result?: SlicerResult;
61
+ };
62
+ /**
63
+ * A slicer failure that keeps the slicer's own result.json. The message starts
64
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
65
+ */
66
+ export declare class SlicerRunError extends Error {
67
+ readonly slicerResult?: SlicerResult | undefined;
68
+ readonly slicerText: string;
69
+ constructor(detail: string, slicerResult?: SlicerResult | undefined);
70
+ }
55
71
  export declare class STLManipulator extends EventEmitter {
56
72
  private tempDir;
57
73
  private activeOperations;
@@ -172,6 +188,12 @@ export declare class STLManipulator extends EventEmitter {
172
188
  * @returns Path to the generated G-code or sliced 3MF file
173
189
  */
174
190
  sliceSTL(stlFilePath: string, slicerType: SlicerType, slicerPath: string, slicerProfile?: string, progressCallback?: ProgressCallback, printerPreset?: string, bambuOptions?: BambuSliceOptions): Promise<string>;
191
+ /**
192
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
193
+ * A failure throws SlicerRunError, whose message starts with the slicer's
194
+ * error_string and plate warnings.
195
+ */
196
+ sliceSTLWithResult(stlFilePath: string, slicerType: SlicerType, slicerPath: string, slicerProfile?: string, progressCallback?: ProgressCallback, printerPreset?: string, bambuOptions?: BambuSliceOptions): Promise<SliceOutput>;
175
197
  /**
176
198
  * Enhanced version of confirmTemperatures with better error handling
177
199
  * @param gcodePath Path to the G-code file
@@ -207,7 +229,21 @@ export declare class STLManipulator extends EventEmitter {
207
229
  */
208
230
  centerModel(stlFilePath: string, progressCallback?: ProgressCallback): Promise<string>;
209
231
  /**
210
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
232
+ * Rotate the model so a face rests on the bed, in the pose with the least
233
+ * part and support material per mm² of bed contact, then move it down to
234
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
211
235
  */
212
236
  layFlat(stlFilePath: string, progressCallback?: ProgressCallback): Promise<string>;
237
+ /**
238
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
239
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
240
+ * and the model is unchanged when none does.
241
+ */
242
+ layFlatWithResult(stlFilePath: string, progressCallback?: ProgressCallback): Promise<LayFlatResult>;
213
243
  }
244
+ export type LayFlatResult = {
245
+ /** The laid-flat STL, or the unchanged input when `laid_flat` is false. */
246
+ path: string;
247
+ laid_flat: boolean;
248
+ message: string;
249
+ };
@@ -113,6 +113,45 @@ const PROFILE_METADATA_KEYS = new Set([
113
113
  'name', 'type', 'from', 'inherits', 'instantiation', 'setting_id', 'version', 'is_custom_defined',
114
114
  'compatible_printers', 'compatible_printers_condition', 'compatible_prints', 'compatible_prints_condition',
115
115
  ]);
116
+ /**
117
+ * A slicer failure that keeps the slicer's own result.json. The message starts
118
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
119
+ */
120
+ export class SlicerRunError extends Error {
121
+ constructor(detail, slicerResult) {
122
+ const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
123
+ super(slicerText ? `${slicerText}\n${detail}` : detail);
124
+ this.slicerResult = slicerResult;
125
+ this.name = "SlicerRunError";
126
+ this.slicerText = slicerText;
127
+ }
128
+ }
129
+ /**
130
+ * The result.json this run wrote. Bambu Studio 02.08.02.61 writes it on macOS
131
+ * for successes and failures alike; an older file must not describe this run.
132
+ */
133
+ function readCliResult(cli) {
134
+ try {
135
+ if (fs.statSync(cli.resultPath).mtimeMs < cli.startedAt)
136
+ return undefined;
137
+ const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
138
+ return result && typeof result === "object" && !Array.isArray(result) ? result : undefined;
139
+ }
140
+ catch {
141
+ return undefined;
142
+ }
143
+ }
144
+ /**
145
+ * The slicer's own words: its error_string when it reports a failing
146
+ * return_code (not "Success."), then each plate's warning_message.
147
+ */
148
+ function slicerResultText(result) {
149
+ const plates = Array.isArray(result.sliced_plates) ? result.sliced_plates : [];
150
+ return [
151
+ result.return_code === 0 ? undefined : result.error_string,
152
+ ...plates.map(plate => plate && typeof plate === "object" ? plate.warning_message : undefined),
153
+ ].filter((text) => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
154
+ }
116
155
  function describeSlicerFailure(error, stdout, stderr, cli) {
117
156
  const status = typeof error.signal === "string" && error.signal
118
157
  ? `crashed with ${error.signal}`
@@ -122,7 +161,7 @@ function describeSlicerFailure(error, stdout, stderr, cli) {
122
161
  return `Slicer failed: the slicer ${status}${reason ? ` (${reason})` : ""}. ${error.message.trim()}${output ? `\nSlicer output: ${output}` : ""}`;
123
162
  }
124
163
  // Bambu Studio and OrcaSlicer CLI errors (libslic3r/Utils.hpp). The process
125
- // exits with the low byte of the code; on Linux result.json names the error.
164
+ // exits with the low byte of the code; result.json names the error.
126
165
  const BAMBU_CLI_ERRORS = {
127
166
  [-2]: "invalid parameters to the slicer",
128
167
  [-3]: "input files not found",
@@ -145,16 +184,9 @@ const BAMBU_CLI_ERRORS = {
145
184
  [-102]: "G-code in an unprintable area",
146
185
  };
147
186
  function bambuCliFailureReason(exitCode, cli) {
148
- try {
149
- if (fs.statSync(cli.resultPath).mtimeMs >= cli.startedAt) {
150
- const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
151
- if (typeof result.error_string === "string" && result.error_string.trim()) {
152
- return `${result.error_string.trim()} [${result.return_code}]`;
153
- }
154
- }
155
- }
156
- catch {
157
- // result.json is written only on Linux and only for handled errors.
187
+ const result = readCliResult(cli);
188
+ if (typeof result?.error_string === "string" && result.error_string.trim()) {
189
+ return `${result.error_string.trim()} [${result.return_code}]`;
158
190
  }
159
191
  if (typeof exitCode !== "number")
160
192
  return undefined;
@@ -1305,6 +1337,14 @@ export class STLManipulator extends EventEmitter {
1305
1337
  * @returns Path to the generated G-code or sliced 3MF file
1306
1338
  */
1307
1339
  async sliceSTL(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1340
+ return (await this.sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions)).path;
1341
+ }
1342
+ /**
1343
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
1344
+ * A failure throws SlicerRunError, whose message starts with the slicer's
1345
+ * error_string and plate warnings.
1346
+ */
1347
+ async sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1308
1348
  const operationId = this.generateOperationId();
1309
1349
  this.activeOperations.set(operationId, true);
1310
1350
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
@@ -1538,7 +1578,8 @@ export class STLManipulator extends EventEmitter {
1538
1578
  if (error) {
1539
1579
  console.error(`Slicer Error: ${error.message}`);
1540
1580
  console.error(`Slicer Stderr: ${stderr}`);
1541
- reject(new Error(describeSlicerFailure(error, stdout, stderr, cliResult)));
1581
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1582
+ reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
1542
1583
  }
1543
1584
  else {
1544
1585
  console.error(`Slicer Stdout: ${stdout}`);
@@ -1573,8 +1614,16 @@ export class STLManipulator extends EventEmitter {
1573
1614
  // This check might be redundant if the promise rejected on kill, but good safety
1574
1615
  throw new Error("Slicing operation cancelled after process finished");
1575
1616
  }
1617
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1618
+ if (cliResult && !slicerResult) {
1619
+ // Older or Linux CLIs may write result.json only for handled errors.
1620
+ console.error(`${slicerType} wrote no result.json for this slice, so its own checks are not available.`);
1621
+ }
1622
+ if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
1623
+ throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
1624
+ }
1576
1625
  if (!fs.existsSync(outputFilePath)) {
1577
- throw new Error(`Slicer finished but output file not found: ${outputFilePath}`);
1626
+ throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1578
1627
  }
1579
1628
  if (progressCallback)
1580
1629
  progressCallback(100, "Slicing completed successfully");
@@ -1584,7 +1633,7 @@ export class STLManipulator extends EventEmitter {
1584
1633
  success: true,
1585
1634
  output: outputFilePath
1586
1635
  });
1587
- return outputFilePath;
1636
+ return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
1588
1637
  }
1589
1638
  catch (error) {
1590
1639
  console.error(`Slicing failed for ${stlFilePath}:`, error);
@@ -1774,9 +1823,19 @@ export class STLManipulator extends EventEmitter {
1774
1823
  }
1775
1824
  }
1776
1825
  /**
1777
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
1826
+ * Rotate the model so a face rests on the bed, in the pose with the least
1827
+ * part and support material per mm² of bed contact, then move it down to
1828
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
1778
1829
  */
1779
1830
  async layFlat(stlFilePath, progressCallback) {
1831
+ return (await this.layFlatWithResult(stlFilePath, progressCallback)).path;
1832
+ }
1833
+ /**
1834
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
1835
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
1836
+ * and the model is unchanged when none does.
1837
+ */
1838
+ async layFlatWithResult(stlFilePath, progressCallback) {
1780
1839
  const operationId = this.generateOperationId();
1781
1840
  this.activeOperations.set(operationId, true);
1782
1841
  try {
@@ -1790,91 +1849,96 @@ export class STLManipulator extends EventEmitter {
1790
1849
  const positionAttribute = geometry.getAttribute('position');
1791
1850
  if (!positionAttribute)
1792
1851
  throw new Error("Geometry has no position attribute.");
1793
- const faces = [];
1852
+ const faceCount = Math.floor(positionAttribute.count / 3);
1853
+ if (faceCount === 0)
1854
+ throw new Error("No faces found in geometry.");
1855
+ const mesh = {
1856
+ positions: new Float64Array(faceCount * 9),
1857
+ normals: new Float64Array(faceCount * 3),
1858
+ areas: new Float64Array(faceCount),
1859
+ volume: 0,
1860
+ };
1861
+ const center = new THREE.Vector3();
1862
+ boundingBox.getCenter(center);
1794
1863
  const vA = new THREE.Vector3();
1795
1864
  const vB = new THREE.Vector3();
1796
1865
  const vC = new THREE.Vector3();
1797
- const faceNormal = new THREE.Vector3();
1798
1866
  const cb = new THREE.Vector3(), ab = new THREE.Vector3();
1799
- // Iterate through faces (triangles)
1800
- for (let i = 0; i < positionAttribute.count; i += 3) {
1801
- vA.fromBufferAttribute(positionAttribute, i);
1802
- vB.fromBufferAttribute(positionAttribute, i + 1);
1803
- vC.fromBufferAttribute(positionAttribute, i + 2);
1804
- // Calculate face normal
1867
+ const fromA = new THREE.Vector3(), fromB = new THREE.Vector3(), fromC = new THREE.Vector3();
1868
+ for (let face = 0; face < faceCount; face++) {
1869
+ vA.fromBufferAttribute(positionAttribute, face * 3);
1870
+ vB.fromBufferAttribute(positionAttribute, face * 3 + 1);
1871
+ vC.fromBufferAttribute(positionAttribute, face * 3 + 2);
1872
+ vA.toArray(mesh.positions, face * 9);
1873
+ vB.toArray(mesh.positions, face * 9 + 3);
1874
+ vC.toArray(mesh.positions, face * 9 + 6);
1875
+ // Signed tetrahedron volumes about the center sum to the enclosed volume.
1876
+ fromA.subVectors(vA, center);
1877
+ fromB.subVectors(vB, center);
1878
+ fromC.subVectors(vC, center);
1879
+ mesh.volume += fromA.dot(fromB.cross(fromC)) / 6;
1880
+ // The cross product's direction is the outward normal; half its length is the area.
1805
1881
  cb.subVectors(vC, vB);
1806
1882
  ab.subVectors(vA, vB);
1807
1883
  cb.cross(ab);
1808
- faceNormal.copy(cb).normalize();
1809
- // Calculate face area (using cross product magnitude / 2)
1810
- const area = cb.length() / 2;
1811
- faces.push({
1812
- normal: faceNormal.clone(),
1813
- area: area,
1814
- vertices: [vA.clone(), vB.clone(), vC.clone()] // Store vertices if needed for center calculation
1815
- });
1884
+ mesh.areas[face] = cb.length() / 2;
1885
+ cb.normalize().toArray(mesh.normals, face * 3);
1816
1886
  }
1817
- if (faces.length === 0)
1818
- throw new Error("No faces found in geometry.");
1887
+ mesh.volume = Math.abs(mesh.volume);
1819
1888
  if (!this.activeOperations.get(operationId))
1820
1889
  throw new Error("Operation cancelled");
1821
1890
  if (progressCallback)
1822
1891
  progressCallback(65, "Grouping faces by normal...");
1823
1892
  // Group faces by similar normal vectors (tolerance for floating point errors)
1824
- const normalGroups = new Map();
1893
+ const normalGroups = [];
1825
1894
  const tolerance = 1e-5;
1826
- for (const face of faces) {
1827
- let foundGroup = false;
1828
- for (const [key, group] of normalGroups.entries()) {
1829
- if (face.normal.distanceToSquared(group.representativeNormal) < tolerance) {
1830
- group.totalArea += face.area;
1831
- // Optional: Average the normal? For now, just use the first one.
1832
- foundGroup = true;
1833
- break;
1834
- }
1835
- }
1836
- if (!foundGroup) {
1837
- const key = `${face.normal.x.toFixed(5)},${face.normal.y.toFixed(5)},${face.normal.z.toFixed(5)}`;
1838
- if (!normalGroups.has(key)) { // Ensure unique key even if floats slightly differ after toFixed
1839
- normalGroups.set(key, { totalArea: face.area, representativeNormal: face.normal });
1840
- }
1841
- }
1895
+ const faceNormal = new THREE.Vector3();
1896
+ for (let face = 0; face < faceCount; face++) {
1897
+ if (!(mesh.areas[face] > 0))
1898
+ continue;
1899
+ faceNormal.fromArray(mesh.normals, face * 3);
1900
+ const group = normalGroups.find(candidate => faceNormal.distanceToSquared(candidate.representativeNormal) < tolerance);
1901
+ if (group)
1902
+ group.totalArea += mesh.areas[face];
1903
+ else
1904
+ normalGroups.push({ totalArea: mesh.areas[face], representativeNormal: faceNormal.clone() });
1842
1905
  }
1843
- if (normalGroups.size === 0)
1844
- throw new Error("Could not group faces by normal.");
1845
1906
  if (!this.activeOperations.get(operationId))
1846
1907
  throw new Error("Operation cancelled");
1847
1908
  if (progressCallback)
1848
- progressCallback(75, "Finding largest flat surface...");
1849
- // Include already-horizontal faces: excluding Z-aligned normals can
1850
- // stand a flat model on its edge, including on a repeated layFlat call.
1851
- let largestArea = 0;
1852
- let targetNormal = null;
1853
- const downVector = new THREE.Vector3(0, 0, -1); // Target normal (pointing down)
1854
- // Faces are grouped by direction, so a part whose flat faces are all
1855
- // horizontal has equal up- and down-facing areas. On a tie, keep the
1856
- // face that already points down so a seated part is not flipped.
1857
- for (const group of normalGroups.values()) {
1858
- const tied = targetNormal !== null && Math.abs(group.totalArea - largestArea) <= largestArea * 1e-6;
1859
- if (tied ? group.representativeNormal.z < targetNormal.z : group.totalArea > largestArea) {
1860
- largestArea = group.totalArea;
1861
- targetNormal = group.representativeNormal;
1862
- }
1909
+ progressCallback(75, "Finding the pose that rests on the bed...");
1910
+ // Candidate directions to turn down: the largest face groups, plus the
1911
+ // model's own axes so a part with a domed side can be flipped exactly.
1912
+ const candidates = normalGroups
1913
+ .sort((a, b) => b.totalArea - a.totalArea)
1914
+ .slice(0, LAY_FLAT_MAX_GROUP_CANDIDATES)
1915
+ .map(group => group.representativeNormal);
1916
+ for (const axis of [[0, 0, -1], [0, 0, 1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]]) {
1917
+ const normal = new THREE.Vector3(axis[0], axis[1], axis[2]);
1918
+ if (!candidates.some(candidate => candidate.distanceToSquared(normal) < tolerance))
1919
+ candidates.push(normal);
1863
1920
  }
1864
- if (!targetNormal) {
1865
- // Only a mesh without any face area reaches this.
1866
- console.warn("Could not find a suitable large flat face to lay down. No changes made.");
1867
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message: "No suitable flat face found." });
1868
- return stlFilePath;
1921
+ let best = null;
1922
+ for (const normal of candidates) {
1923
+ const pose = evaluateLayFlatPose(mesh, normal);
1924
+ if (pose && (!best || isBetterLayFlatPose(pose, best)))
1925
+ best = pose;
1926
+ }
1927
+ if (!best) {
1928
+ const message = "No face lies on the model's lowest plane in any candidate orientation, so the model is unchanged.";
1929
+ console.error(`lay_flat: ${message}`);
1930
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message });
1931
+ return { path: stlFilePath, laid_flat: false, message };
1869
1932
  }
1870
1933
  if (progressCallback)
1871
1934
  progressCallback(80, "Calculating rotation...");
1872
- // Calculate the rotation needed to align targetNormal with downVector
1873
- const quaternion = new THREE.Quaternion().setFromUnitVectors(targetNormal, downVector);
1874
- const rotationMatrix = new THREE.Matrix4().makeRotationFromQuaternion(quaternion);
1935
+ // Turn the chosen normal to face straight down. Turning +Z down rotates
1936
+ // half a turn about X, which keeps the model's X layout.
1937
+ const downVector = new THREE.Vector3(0, 0, -1);
1938
+ const rotationMatrix = best.normal.dot(downVector) < -1 + 1e-9
1939
+ ? new THREE.Matrix4().makeRotationX(Math.PI)
1940
+ : new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(best.normal, downVector));
1875
1941
  // Rotate around the model's center
1876
- const center = new THREE.Vector3();
1877
- boundingBox.getCenter(center);
1878
1942
  const toOriginMatrix = new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z);
1879
1943
  const fromOriginMatrix = new THREE.Matrix4().makeTranslation(center.x, center.y, center.z);
1880
1944
  // Apply rotation
@@ -1892,8 +1956,9 @@ export class STLManipulator extends EventEmitter {
1892
1956
  const outputFileName = path.basename(stlFilePath, '.stl') + '_flat.stl';
1893
1957
  const outputFilePath = path.join(this.tempDir, outputFileName);
1894
1958
  await this.saveSTL(geometry, outputFilePath, progressCallback); // 90-100% progress
1895
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath });
1896
- return outputFilePath;
1959
+ const message = `Rests on ${best.contactArea.toFixed(1)} mm² of bed contact; overhangs more than 45° from vertical need about ${best.supportVolume.toFixed(0)} mm³ of support.`;
1960
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath, message });
1961
+ return { path: outputFilePath, laid_flat: true, message };
1897
1962
  }
1898
1963
  catch (error) {
1899
1964
  this.emit('operationError', { operationId, type: 'layFlat', error: error instanceof Error ? error.message : String(error) });
@@ -1904,3 +1969,62 @@ export class STLManipulator extends EventEmitter {
1904
1969
  }
1905
1970
  }
1906
1971
  }
1972
+ const LAY_FLAT_MAX_GROUP_CANDIDATES = 64;
1973
+ /** Faces tilted more than 45° from vertical overhang and need support. */
1974
+ const LAY_FLAT_OVERHANG_COS = Math.SQRT1_2 + 1e-6;
1975
+ /**
1976
+ * Score turning `normal` to face the bed. The bed is the mesh's lowest plane in
1977
+ * that pose, its support plane. Faces lying on it, within 0.5% of the model's
1978
+ * height there (at most 0.2 mm), are bed contact. Overhanging faces above it
1979
+ * need support up from the bed: their projected area times their height.
1980
+ * Returns null when no face lies on the bed: turning that normal down would
1981
+ * rest the model on an edge or a point, not a face.
1982
+ */
1983
+ function evaluateLayFlatPose(mesh, normal) {
1984
+ const { positions, normals, areas } = mesh;
1985
+ const nx = normal.x, ny = normal.y, nz = normal.z;
1986
+ // Distance along the normal grows toward the bed: the bed is at its maximum.
1987
+ let bed = -Infinity, top = Infinity;
1988
+ for (let index = 0; index < positions.length; index += 3) {
1989
+ const along = positions[index] * nx + positions[index + 1] * ny + positions[index + 2] * nz;
1990
+ if (along > bed)
1991
+ bed = along;
1992
+ if (along < top)
1993
+ top = along;
1994
+ }
1995
+ const tolerance = Math.min(0.2, Math.max(0.005 * (bed - top), 1e-4));
1996
+ let contactArea = 0;
1997
+ let supportVolume = 0;
1998
+ for (let face = 0; face < areas.length; face++) {
1999
+ const facing = normals[face * 3] * nx + normals[face * 3 + 1] * ny + normals[face * 3 + 2] * nz;
2000
+ if (!(facing > 0))
2001
+ continue;
2002
+ const base = face * 9;
2003
+ let heightSum = 0, heightMax = 0;
2004
+ for (let corner = base; corner < base + 9; corner += 3) {
2005
+ const height = bed - (positions[corner] * nx + positions[corner + 1] * ny + positions[corner + 2] * nz);
2006
+ heightSum += height;
2007
+ if (height > heightMax)
2008
+ heightMax = height;
2009
+ }
2010
+ if (heightMax <= tolerance)
2011
+ contactArea += areas[face];
2012
+ else if (facing > LAY_FLAT_OVERHANG_COS)
2013
+ supportVolume += areas[face] * facing * (heightSum / 3);
2014
+ }
2015
+ if (!(contactArea > 0))
2016
+ return null;
2017
+ return { normal, contactArea, supportVolume, stackHeight: (mesh.volume + supportVolume) / contactArea };
2018
+ }
2019
+ /**
2020
+ * Prefer the pose with the lowest stack height, then the larger contact. On a
2021
+ * tie, keep the face that already points down so a seated part is not flipped.
2022
+ */
2023
+ function isBetterLayFlatPose(pose, best) {
2024
+ const same = (a, b) => Math.abs(a - b) <= 1e-9 + 1e-6 * Math.max(Math.abs(a), Math.abs(b));
2025
+ if (!same(pose.stackHeight, best.stackHeight))
2026
+ return pose.stackHeight < best.stackHeight;
2027
+ if (!same(pose.contactArea, best.contactArea))
2028
+ return pose.contactArea > best.contactArea;
2029
+ return pose.normal.z < best.normal.z;
2030
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.50",
3
+ "version": "1.1.51",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
package/src/index.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  STLManipulator,
22
22
  SLICER_TYPES,
23
23
  normalizeSlicerType,
24
+ SlicerRunError,
24
25
  type BambuSliceOptions,
25
26
  type SlicerType,
26
27
  } from "./stl/stl-manipulator.js";
@@ -933,6 +934,7 @@ type StructuredToolError = {
933
934
  suggestion: string;
934
935
  message: string;
935
936
  tool: string;
937
+ slicer_result?: Record<string, unknown>;
936
938
  };
937
939
 
938
940
  type UploadGcodeSource = {
@@ -2540,7 +2542,7 @@ class BambuPrinterMCPServer {
2540
2542
  },
2541
2543
  {
2542
2544
  name: "slice_stl",
2543
- description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer.",
2545
+ description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. A failed slice's text starts with those words.",
2544
2546
  inputSchema: {
2545
2547
  type: "object",
2546
2548
  properties: {
@@ -3215,7 +3217,7 @@ class BambuPrinterMCPServer {
3215
3217
  },
3216
3218
  {
3217
3219
  name: "lay_flat",
3218
- description: "Rotate the model so its largest flat face lies on the XY plane (Z=0)",
3220
+ description: "Rotate the model so a face rests on the bed (Z=0), choosing the orientation with the least part and support volume per mm² of bed contact. A face counts only if nothing hangs below it. Returns the new STL path; structuredContent.laid_flat is false, with the input path, when no orientation qualifies.",
3219
3221
  inputSchema: {
3220
3222
  type: "object",
3221
3223
  properties: {
@@ -4269,14 +4271,16 @@ class BambuPrinterMCPServer {
4269
4271
  }
4270
4272
  }
4271
4273
 
4272
- result = await this.stlManipulator.sliceSTL(
4274
+ const sliced = await this.stlManipulator.sliceSTLWithResult(
4273
4275
  String(args.stl_path), slicerType, slicerPath,
4274
4276
  activeSlicerProfile,
4275
4277
  undefined, // progressCallback
4276
4278
  printerPreset,
4277
4279
  sliceBambuOptions
4278
4280
  );
4279
- break;
4281
+ await progressNotifications;
4282
+ // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim.
4283
+ return { content: [{ type: "text", text: sliced.path }], structuredContent: sliced };
4280
4284
  }
4281
4285
 
4282
4286
  case "print_3mf": {
@@ -4598,10 +4602,13 @@ class BambuPrinterMCPServer {
4598
4602
  result = await this.stlManipulator.centerModel(String(args.stl_path));
4599
4603
  break;
4600
4604
 
4601
- case "lay_flat":
4605
+ case "lay_flat": {
4602
4606
  if (!args?.stl_path) throw new Error("Missing required parameter: stl_path");
4603
- result = await this.stlManipulator.layFlat(String(args.stl_path));
4604
- break;
4607
+ const layFlatResult = await this.stlManipulator.layFlatWithResult(String(args.stl_path));
4608
+ await progressNotifications;
4609
+ // The text stays the STL path clients read; structuredContent says whether it was laid flat.
4610
+ return { content: [{ type: "text", text: layFlatResult.path }], structuredContent: layFlatResult };
4611
+ }
4605
4612
 
4606
4613
  case "blender_mcp_status":
4607
4614
  result = await this.blender.status(args ?? {}, extra.signal);
@@ -4686,12 +4693,15 @@ class BambuPrinterMCPServer {
4686
4693
  : `Check parameters and try again. Error: ${message}`,
4687
4694
  message,
4688
4695
  tool: name,
4696
+ // The slicer's own result.json; the message starts with its error_string and warnings.
4697
+ ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult } : {}),
4689
4698
  };
4690
4699
 
4691
4700
  // MCP clients validate structuredContent against a declared outputSchema even on
4692
4701
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
4693
4702
  return {
4694
- content: [{ type: "text", text: `Error: ${message}` }],
4703
+ // A slicer failure leads with the slicer's own words.
4704
+ content: [{ type: "text", text: error instanceof SlicerRunError && error.slicerText ? message : `Error: ${message}` }],
4695
4705
  ...(OUTPUT_SCHEMA_TOOLS.has(name) ? {} : { structuredContent: structured }),
4696
4706
  isError: true,
4697
4707
  };
@@ -209,9 +209,55 @@ const PROFILE_METADATA_KEYS = new Set([
209
209
  * segfaults with no output), so name the signal or exit code and add the end
210
210
  * of stdout instead.
211
211
  */
212
- /** Where a Bambu-style CLI records its error on Linux, and when this run started. */
212
+ /** Where a Bambu-style CLI writes result.json, and when this run started. */
213
213
  type CliResultSource = { resultPath: string; startedAt: number };
214
214
 
215
+ /** Bambu Studio's or OrcaSlicer's own result.json, parsed verbatim. */
216
+ export type SlicerResult = Record<string, unknown>;
217
+
218
+ /** A sliced file, with the slicer's own result.json when it wrote one. */
219
+ export type SliceOutput = { path: string; slicer_result?: SlicerResult };
220
+
221
+ /**
222
+ * A slicer failure that keeps the slicer's own result.json. The message starts
223
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
224
+ */
225
+ export class SlicerRunError extends Error {
226
+ readonly slicerText: string;
227
+ constructor(detail: string, readonly slicerResult?: SlicerResult) {
228
+ const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
229
+ super(slicerText ? `${slicerText}\n${detail}` : detail);
230
+ this.name = "SlicerRunError";
231
+ this.slicerText = slicerText;
232
+ }
233
+ }
234
+
235
+ /**
236
+ * The result.json this run wrote. Bambu Studio 02.08.02.61 writes it on macOS
237
+ * for successes and failures alike; an older file must not describe this run.
238
+ */
239
+ function readCliResult(cli: CliResultSource): SlicerResult | undefined {
240
+ try {
241
+ if (fs.statSync(cli.resultPath).mtimeMs < cli.startedAt) return undefined;
242
+ const result: unknown = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
243
+ return result && typeof result === "object" && !Array.isArray(result) ? result as SlicerResult : undefined;
244
+ } catch {
245
+ return undefined;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * The slicer's own words: its error_string when it reports a failing
251
+ * return_code (not "Success."), then each plate's warning_message.
252
+ */
253
+ function slicerResultText(result: SlicerResult): string {
254
+ const plates = Array.isArray(result.sliced_plates) ? result.sliced_plates : [];
255
+ return [
256
+ result.return_code === 0 ? undefined : result.error_string,
257
+ ...plates.map(plate => plate && typeof plate === "object" ? (plate as Record<string, unknown>).warning_message : undefined),
258
+ ].filter((text): text is string => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
259
+ }
260
+
215
261
  function describeSlicerFailure(
216
262
  error: { message: string; code?: unknown; signal?: unknown },
217
263
  stdout: string,
@@ -227,7 +273,7 @@ function describeSlicerFailure(
227
273
  }
228
274
 
229
275
  // Bambu Studio and OrcaSlicer CLI errors (libslic3r/Utils.hpp). The process
230
- // exits with the low byte of the code; on Linux result.json names the error.
276
+ // exits with the low byte of the code; result.json names the error.
231
277
  const BAMBU_CLI_ERRORS: Record<number, string> = {
232
278
  [-2]: "invalid parameters to the slicer",
233
279
  [-3]: "input files not found",
@@ -251,15 +297,9 @@ const BAMBU_CLI_ERRORS: Record<number, string> = {
251
297
  };
252
298
 
253
299
  function bambuCliFailureReason(exitCode: unknown, cli: CliResultSource): string | undefined {
254
- try {
255
- if (fs.statSync(cli.resultPath).mtimeMs >= cli.startedAt) {
256
- const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
257
- if (typeof result.error_string === "string" && result.error_string.trim()) {
258
- return `${result.error_string.trim()} [${result.return_code}]`;
259
- }
260
- }
261
- } catch {
262
- // result.json is written only on Linux and only for handled errors.
300
+ const result = readCliResult(cli);
301
+ if (typeof result?.error_string === "string" && result.error_string.trim()) {
302
+ return `${result.error_string.trim()} [${result.return_code}]`;
263
303
  }
264
304
  if (typeof exitCode !== "number") return undefined;
265
305
  const code = Object.keys(BAMBU_CLI_ERRORS).map(Number).find(value => (value & 0xff) === exitCode);
@@ -1684,6 +1724,23 @@ export class STLManipulator extends EventEmitter {
1684
1724
  printerPreset?: string,
1685
1725
  bambuOptions?: BambuSliceOptions
1686
1726
  ): Promise<string> {
1727
+ return (await this.sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions)).path;
1728
+ }
1729
+
1730
+ /**
1731
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
1732
+ * A failure throws SlicerRunError, whose message starts with the slicer's
1733
+ * error_string and plate warnings.
1734
+ */
1735
+ async sliceSTLWithResult(
1736
+ stlFilePath: string,
1737
+ slicerType: SlicerType,
1738
+ slicerPath: string,
1739
+ slicerProfile?: string,
1740
+ progressCallback?: ProgressCallback,
1741
+ printerPreset?: string,
1742
+ bambuOptions?: BambuSliceOptions
1743
+ ): Promise<SliceOutput> {
1687
1744
  const operationId = this.generateOperationId();
1688
1745
  this.activeOperations.set(operationId, true);
1689
1746
 
@@ -1920,7 +1977,8 @@ export class STLManipulator extends EventEmitter {
1920
1977
  if (error) {
1921
1978
  console.error(`Slicer Error: ${error.message}`);
1922
1979
  console.error(`Slicer Stderr: ${stderr}`);
1923
- reject(new Error(describeSlicerFailure(error, stdout, stderr, cliResult)));
1980
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1981
+ reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
1924
1982
  } else {
1925
1983
  console.error(`Slicer Stdout: ${stdout}`);
1926
1984
  if (stderr) {
@@ -1959,8 +2017,17 @@ export class STLManipulator extends EventEmitter {
1959
2017
  throw new Error("Slicing operation cancelled after process finished");
1960
2018
  }
1961
2019
 
2020
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
2021
+ if (cliResult && !slicerResult) {
2022
+ // Older or Linux CLIs may write result.json only for handled errors.
2023
+ console.error(`${slicerType} wrote no result.json for this slice, so its own checks are not available.`);
2024
+ }
2025
+ if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
2026
+ throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
2027
+ }
2028
+
1962
2029
  if (!fs.existsSync(outputFilePath)) {
1963
- throw new Error(`Slicer finished but output file not found: ${outputFilePath}`);
2030
+ throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1964
2031
  }
1965
2032
 
1966
2033
  if (progressCallback) progressCallback(100, "Slicing completed successfully");
@@ -1972,7 +2039,7 @@ export class STLManipulator extends EventEmitter {
1972
2039
  output: outputFilePath
1973
2040
  });
1974
2041
 
1975
- return outputFilePath;
2042
+ return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
1976
2043
  } catch (error) {
1977
2044
  console.error(`Slicing failed for ${stlFilePath}:`, error);
1978
2045
  this.emit('operationError', {
@@ -2200,12 +2267,26 @@ export class STLManipulator extends EventEmitter {
2200
2267
  }
2201
2268
 
2202
2269
  /**
2203
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
2270
+ * Rotate the model so a face rests on the bed, in the pose with the least
2271
+ * part and support material per mm² of bed contact, then move it down to
2272
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
2204
2273
  */
2205
2274
  async layFlat(
2206
2275
  stlFilePath: string,
2207
2276
  progressCallback?: ProgressCallback
2208
2277
  ): Promise<string> {
2278
+ return (await this.layFlatWithResult(stlFilePath, progressCallback)).path;
2279
+ }
2280
+
2281
+ /**
2282
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
2283
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
2284
+ * and the model is unchanged when none does.
2285
+ */
2286
+ async layFlatWithResult(
2287
+ stlFilePath: string,
2288
+ progressCallback?: ProgressCallback
2289
+ ): Promise<LayFlatResult> {
2209
2290
  const operationId = this.generateOperationId();
2210
2291
  this.activeOperations.set(operationId, true);
2211
2292
 
@@ -2220,100 +2301,98 @@ export class STLManipulator extends EventEmitter {
2220
2301
  const positionAttribute = geometry.getAttribute('position');
2221
2302
  if (!positionAttribute) throw new Error("Geometry has no position attribute.");
2222
2303
 
2223
- const faces: { normal: THREE.Vector3; area: number; vertices: THREE.Vector3[] }[] = [];
2304
+ const faceCount = Math.floor(positionAttribute.count / 3);
2305
+ if (faceCount === 0) throw new Error("No faces found in geometry.");
2306
+ const mesh: LayFlatMesh = {
2307
+ positions: new Float64Array(faceCount * 9),
2308
+ normals: new Float64Array(faceCount * 3),
2309
+ areas: new Float64Array(faceCount),
2310
+ volume: 0,
2311
+ };
2312
+ const center = new THREE.Vector3();
2313
+ boundingBox.getCenter(center);
2224
2314
  const vA = new THREE.Vector3();
2225
2315
  const vB = new THREE.Vector3();
2226
2316
  const vC = new THREE.Vector3();
2227
- const faceNormal = new THREE.Vector3();
2228
2317
  const cb = new THREE.Vector3(), ab = new THREE.Vector3();
2229
-
2230
- // Iterate through faces (triangles)
2231
- for (let i = 0; i < positionAttribute.count; i += 3) {
2232
- vA.fromBufferAttribute(positionAttribute, i);
2233
- vB.fromBufferAttribute(positionAttribute, i + 1);
2234
- vC.fromBufferAttribute(positionAttribute, i + 2);
2235
-
2236
- // Calculate face normal
2318
+ const fromA = new THREE.Vector3(), fromB = new THREE.Vector3(), fromC = new THREE.Vector3();
2319
+
2320
+ for (let face = 0; face < faceCount; face++) {
2321
+ vA.fromBufferAttribute(positionAttribute, face * 3);
2322
+ vB.fromBufferAttribute(positionAttribute, face * 3 + 1);
2323
+ vC.fromBufferAttribute(positionAttribute, face * 3 + 2);
2324
+ vA.toArray(mesh.positions, face * 9);
2325
+ vB.toArray(mesh.positions, face * 9 + 3);
2326
+ vC.toArray(mesh.positions, face * 9 + 6);
2327
+ // Signed tetrahedron volumes about the center sum to the enclosed volume.
2328
+ fromA.subVectors(vA, center);
2329
+ fromB.subVectors(vB, center);
2330
+ fromC.subVectors(vC, center);
2331
+ mesh.volume += fromA.dot(fromB.cross(fromC)) / 6;
2332
+
2333
+ // The cross product's direction is the outward normal; half its length is the area.
2237
2334
  cb.subVectors(vC, vB);
2238
2335
  ab.subVectors(vA, vB);
2239
2336
  cb.cross(ab);
2240
- faceNormal.copy(cb).normalize();
2241
-
2242
- // Calculate face area (using cross product magnitude / 2)
2243
- const area = cb.length() / 2;
2244
-
2245
- faces.push({
2246
- normal: faceNormal.clone(),
2247
- area: area,
2248
- vertices: [vA.clone(), vB.clone(), vC.clone()] // Store vertices if needed for center calculation
2249
- });
2337
+ mesh.areas[face] = cb.length() / 2;
2338
+ cb.normalize().toArray(mesh.normals, face * 3);
2250
2339
  }
2251
2340
 
2252
- if (faces.length === 0) throw new Error("No faces found in geometry.");
2341
+ mesh.volume = Math.abs(mesh.volume);
2253
2342
 
2254
2343
  if (!this.activeOperations.get(operationId)) throw new Error("Operation cancelled");
2255
2344
  if (progressCallback) progressCallback(65, "Grouping faces by normal...");
2256
2345
 
2257
2346
  // Group faces by similar normal vectors (tolerance for floating point errors)
2258
- const normalGroups: Map<string, { totalArea: number; representativeNormal: THREE.Vector3 }> = new Map();
2259
- const tolerance = 1e-5;
2260
-
2261
- for (const face of faces) {
2262
- let foundGroup = false;
2263
- for (const [key, group] of normalGroups.entries()) {
2264
- if (face.normal.distanceToSquared(group.representativeNormal) < tolerance) {
2265
- group.totalArea += face.area;
2266
- // Optional: Average the normal? For now, just use the first one.
2267
- foundGroup = true;
2268
- break;
2269
- }
2270
- }
2271
- if (!foundGroup) {
2272
- const key = `${face.normal.x.toFixed(5)},${face.normal.y.toFixed(5)},${face.normal.z.toFixed(5)}`;
2273
- if (!normalGroups.has(key)) { // Ensure unique key even if floats slightly differ after toFixed
2274
- normalGroups.set(key, { totalArea: face.area, representativeNormal: face.normal });
2275
- }
2276
- }
2347
+ const normalGroups: { totalArea: number; representativeNormal: THREE.Vector3 }[] = [];
2348
+ const tolerance = 1e-5;
2349
+ const faceNormal = new THREE.Vector3();
2350
+
2351
+ for (let face = 0; face < faceCount; face++) {
2352
+ if (!(mesh.areas[face] > 0)) continue;
2353
+ faceNormal.fromArray(mesh.normals, face * 3);
2354
+ const group = normalGroups.find(candidate => faceNormal.distanceToSquared(candidate.representativeNormal) < tolerance);
2355
+ if (group) group.totalArea += mesh.areas[face];
2356
+ else normalGroups.push({ totalArea: mesh.areas[face], representativeNormal: faceNormal.clone() });
2277
2357
  }
2278
-
2279
- if (normalGroups.size === 0) throw new Error("Could not group faces by normal.");
2280
2358
 
2281
2359
  if (!this.activeOperations.get(operationId)) throw new Error("Operation cancelled");
2282
- if (progressCallback) progressCallback(75, "Finding largest flat surface...");
2283
-
2284
- // Include already-horizontal faces: excluding Z-aligned normals can
2285
- // stand a flat model on its edge, including on a repeated layFlat call.
2286
- let largestArea = 0;
2287
- let targetNormal: THREE.Vector3 | null = null;
2288
- const downVector = new THREE.Vector3(0, 0, -1); // Target normal (pointing down)
2289
-
2290
- // Faces are grouped by direction, so a part whose flat faces are all
2291
- // horizontal has equal up- and down-facing areas. On a tie, keep the
2292
- // face that already points down so a seated part is not flipped.
2293
- for (const group of normalGroups.values()) {
2294
- const tied = targetNormal !== null && Math.abs(group.totalArea - largestArea) <= largestArea * 1e-6;
2295
- if (tied ? group.representativeNormal.z < targetNormal!.z : group.totalArea > largestArea) {
2296
- largestArea = group.totalArea;
2297
- targetNormal = group.representativeNormal;
2298
- }
2360
+ if (progressCallback) progressCallback(75, "Finding the pose that rests on the bed...");
2361
+
2362
+ // Candidate directions to turn down: the largest face groups, plus the
2363
+ // model's own axes so a part with a domed side can be flipped exactly.
2364
+ const candidates = normalGroups
2365
+ .sort((a, b) => b.totalArea - a.totalArea)
2366
+ .slice(0, LAY_FLAT_MAX_GROUP_CANDIDATES)
2367
+ .map(group => group.representativeNormal);
2368
+ for (const axis of [[0, 0, -1], [0, 0, 1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]]) {
2369
+ const normal = new THREE.Vector3(axis[0], axis[1], axis[2]);
2370
+ if (!candidates.some(candidate => candidate.distanceToSquared(normal) < tolerance)) candidates.push(normal);
2299
2371
  }
2300
2372
 
2301
- if (!targetNormal) {
2302
- // Only a mesh without any face area reaches this.
2303
- console.warn("Could not find a suitable large flat face to lay down. No changes made.");
2304
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message: "No suitable flat face found." });
2305
- return stlFilePath;
2373
+ let best: LayFlatPose | null = null;
2374
+ for (const normal of candidates) {
2375
+ const pose = evaluateLayFlatPose(mesh, normal);
2376
+ if (pose && (!best || isBetterLayFlatPose(pose, best))) best = pose;
2306
2377
  }
2307
-
2378
+
2379
+ if (!best) {
2380
+ const message = "No face lies on the model's lowest plane in any candidate orientation, so the model is unchanged.";
2381
+ console.error(`lay_flat: ${message}`);
2382
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message });
2383
+ return { path: stlFilePath, laid_flat: false, message };
2384
+ }
2385
+
2308
2386
  if (progressCallback) progressCallback(80, "Calculating rotation...");
2309
-
2310
- // Calculate the rotation needed to align targetNormal with downVector
2311
- const quaternion = new THREE.Quaternion().setFromUnitVectors(targetNormal, downVector);
2312
- const rotationMatrix = new THREE.Matrix4().makeRotationFromQuaternion(quaternion);
2387
+
2388
+ // Turn the chosen normal to face straight down. Turning +Z down rotates
2389
+ // half a turn about X, which keeps the model's X layout.
2390
+ const downVector = new THREE.Vector3(0, 0, -1);
2391
+ const rotationMatrix = best.normal.dot(downVector) < -1 + 1e-9
2392
+ ? new THREE.Matrix4().makeRotationX(Math.PI)
2393
+ : new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(best.normal, downVector));
2313
2394
 
2314
2395
  // Rotate around the model's center
2315
- const center = new THREE.Vector3();
2316
- boundingBox.getCenter(center);
2317
2396
  const toOriginMatrix = new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z);
2318
2397
  const fromOriginMatrix = new THREE.Matrix4().makeTranslation(center.x, center.y, center.z);
2319
2398
 
@@ -2336,8 +2415,9 @@ export class STLManipulator extends EventEmitter {
2336
2415
 
2337
2416
  await this.saveSTL(geometry, outputFilePath, progressCallback); // 90-100% progress
2338
2417
 
2339
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath });
2340
- return outputFilePath;
2418
+ const message = `Rests on ${best.contactArea.toFixed(1)} mm² of bed contact; overhangs more than 45° from vertical need about ${best.supportVolume.toFixed(0)} mm³ of support.`;
2419
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath, message });
2420
+ return { path: outputFilePath, laid_flat: true, message };
2341
2421
 
2342
2422
  } catch (error) {
2343
2423
  this.emit('operationError', { operationId, type: 'layFlat', error: error instanceof Error ? error.message : String(error) });
@@ -2347,3 +2427,75 @@ export class STLManipulator extends EventEmitter {
2347
2427
  }
2348
2428
  }
2349
2429
  }
2430
+
2431
+ export type LayFlatResult = {
2432
+ /** The laid-flat STL, or the unchanged input when `laid_flat` is false. */
2433
+ path: string;
2434
+ laid_flat: boolean;
2435
+ message: string;
2436
+ };
2437
+
2438
+ /** Face corners (9 per face), outward unit normals (3 per face), areas, and the enclosed volume. */
2439
+ type LayFlatMesh = { positions: Float64Array; normals: Float64Array; areas: Float64Array; volume: number };
2440
+
2441
+ /**
2442
+ * A direction to turn down, with the bed contact and support it gives.
2443
+ * `stackHeight` is the part and support volume over the contact area: the mean
2444
+ * height of material standing on each mm² of bed. Standing a long part on its
2445
+ * end, or resting a part on a fin under a wide cap, makes it tall.
2446
+ */
2447
+ type LayFlatPose = { normal: THREE.Vector3; contactArea: number; supportVolume: number; stackHeight: number };
2448
+
2449
+ const LAY_FLAT_MAX_GROUP_CANDIDATES = 64;
2450
+ /** Faces tilted more than 45° from vertical overhang and need support. */
2451
+ const LAY_FLAT_OVERHANG_COS = Math.SQRT1_2 + 1e-6;
2452
+
2453
+ /**
2454
+ * Score turning `normal` to face the bed. The bed is the mesh's lowest plane in
2455
+ * that pose, its support plane. Faces lying on it, within 0.5% of the model's
2456
+ * height there (at most 0.2 mm), are bed contact. Overhanging faces above it
2457
+ * need support up from the bed: their projected area times their height.
2458
+ * Returns null when no face lies on the bed: turning that normal down would
2459
+ * rest the model on an edge or a point, not a face.
2460
+ */
2461
+ function evaluateLayFlatPose(mesh: LayFlatMesh, normal: THREE.Vector3): LayFlatPose | null {
2462
+ const { positions, normals, areas } = mesh;
2463
+ const nx = normal.x, ny = normal.y, nz = normal.z;
2464
+ // Distance along the normal grows toward the bed: the bed is at its maximum.
2465
+ let bed = -Infinity, top = Infinity;
2466
+ for (let index = 0; index < positions.length; index += 3) {
2467
+ const along = positions[index] * nx + positions[index + 1] * ny + positions[index + 2] * nz;
2468
+ if (along > bed) bed = along;
2469
+ if (along < top) top = along;
2470
+ }
2471
+ const tolerance = Math.min(0.2, Math.max(0.005 * (bed - top), 1e-4));
2472
+
2473
+ let contactArea = 0;
2474
+ let supportVolume = 0;
2475
+ for (let face = 0; face < areas.length; face++) {
2476
+ const facing = normals[face * 3] * nx + normals[face * 3 + 1] * ny + normals[face * 3 + 2] * nz;
2477
+ if (!(facing > 0)) continue;
2478
+ const base = face * 9;
2479
+ let heightSum = 0, heightMax = 0;
2480
+ for (let corner = base; corner < base + 9; corner += 3) {
2481
+ const height = bed - (positions[corner] * nx + positions[corner + 1] * ny + positions[corner + 2] * nz);
2482
+ heightSum += height;
2483
+ if (height > heightMax) heightMax = height;
2484
+ }
2485
+ if (heightMax <= tolerance) contactArea += areas[face];
2486
+ else if (facing > LAY_FLAT_OVERHANG_COS) supportVolume += areas[face] * facing * (heightSum / 3);
2487
+ }
2488
+ if (!(contactArea > 0)) return null;
2489
+ return { normal, contactArea, supportVolume, stackHeight: (mesh.volume + supportVolume) / contactArea };
2490
+ }
2491
+
2492
+ /**
2493
+ * Prefer the pose with the lowest stack height, then the larger contact. On a
2494
+ * tie, keep the face that already points down so a seated part is not flipped.
2495
+ */
2496
+ function isBetterLayFlatPose(pose: LayFlatPose, best: LayFlatPose): boolean {
2497
+ const same = (a: number, b: number) => Math.abs(a - b) <= 1e-9 + 1e-6 * Math.max(Math.abs(a), Math.abs(b));
2498
+ if (!same(pose.stackHeight, best.stackHeight)) return pose.stackHeight < best.stackHeight;
2499
+ if (!same(pose.contactArea, best.contactArea)) return pose.contactArea > best.contactArea;
2500
+ return pose.normal.z < best.normal.z;
2501
+ }