bambu-printer-mcp 1.1.58 → 1.1.60

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/README.md CHANGED
@@ -1198,7 +1198,7 @@ When `slicer_type` is `bambustudio` (the default), these additional parameters a
1198
1198
  | `skip_modified_gcodes` | boolean | Ignore stale custom gcodes in the 3MF |
1199
1199
  | `slice_plate` | number | Which plate to slice (0 = all plates, default: 0) |
1200
1200
  | `quality` | string | `draft`, `standard` or `fine`: the server picks the layer height for the nozzle in use (0.28 and 0.12 mm on 0.4 mm; standard keeps the preset) |
1201
- | `strength` | string | `standard`, `strong` or `max`: the server picks walls and infill (4 walls at 25%, 6 at 40%; standard keeps the preset) |
1201
+ | `strength` | string | `standard`, `strong` or `max`: the server picks walls and infill (at least 4 walls and 25%, or 6 and 40%; a process that already has more keeps it; standard keeps the process as it is) |
1202
1202
  | `layer_height` | number | Layer height in mm, such as 0.28, 0.2 or 0.12; at most the nozzle diameter |
1203
1203
  | `wall_loops` | integer | Number of walls, 0 to 1000 |
1204
1204
  | `sparse_infill_density` | string | Sparse infill density, such as `"15%"` |
@@ -1,6 +1,8 @@
1
1
  import { ThreeMFData, CollarCharmAnalysis, ThreeMFAmsRequirements, ThreeMFPlateObjects } from './types.js';
2
2
  export { ThreeMFData };
3
3
  export declare function parse3MF(filePath: string): Promise<ThreeMFData>;
4
+ /** Whether a 3MF carries its own Bambu Studio/Orca process (a designer's project, not a bare mesh archive). */
5
+ export declare function hasBambuProjectSettings(filePath: string): Promise<boolean>;
4
6
  export declare function extractBambuTemplateSettings(filePath: string, outputDir: string): Promise<string>;
5
7
  export declare function analyzeCollarCharm3MF(filePath: string, plateIndex?: number): Promise<CollarCharmAnalysis>;
6
8
  export declare function getCollarCharmRolePolicy(): {
@@ -1,6 +1,7 @@
1
1
  import JSZip from 'jszip';
2
2
  import { parseStringPromise } from 'xml2js';
3
3
  import * as fs from 'fs/promises';
4
+ import { createHash } from 'crypto';
4
5
  // Parses Bambu Studio's JSON config data
5
6
  function parseBambuJSONConfig(jsonData) {
6
7
  const config = {};
@@ -219,6 +220,20 @@ export async function parse3MF(filePath) {
219
220
  throw new Error(`Failed to parse 3MF file: ${error.message}`);
220
221
  }
221
222
  }
223
+ /** Whether a 3MF carries its own Bambu Studio/Orca process (a designer's project, not a bare mesh archive). */
224
+ export async function hasBambuProjectSettings(filePath) {
225
+ try {
226
+ const zip = await JSZip.loadAsync(await fs.readFile(filePath));
227
+ const settings = zip.file('Metadata/project_settings.config');
228
+ if (!settings)
229
+ return false;
230
+ const parsed = JSON.parse(await settings.async('string'));
231
+ return !!parsed && typeof parsed === 'object' && !Array.isArray(parsed) && parsed.layer_height !== undefined;
232
+ }
233
+ catch {
234
+ return false;
235
+ }
236
+ }
222
237
  export async function extractBambuTemplateSettings(filePath, outputDir) {
223
238
  const data = await fs.readFile(filePath);
224
239
  const zip = await JSZip.loadAsync(data);
@@ -233,7 +248,9 @@ export async function extractBambuTemplateSettings(filePath, outputDir) {
233
248
  if (!file)
234
249
  continue;
235
250
  const content = await file.async('string');
236
- const outputPath = `${outputDir}/${name.replace(/\//g, '_')}`;
251
+ // Named by content, so two projects sliced at once never share (or overwrite) one settings file.
252
+ const digest = createHash('sha256').update(content).digest('hex').slice(0, 16);
253
+ const outputPath = `${outputDir}/${digest}_${name.replace(/\//g, '_')}`;
237
254
  await fs.writeFile(outputPath, content, 'utf8');
238
255
  return outputPath;
239
256
  }
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import fs from "fs";
11
11
  import os from "node:os";
12
12
  import path from "path";
13
13
  import { createServer as createHttpServer } from "node:http";
14
- import { randomUUID } from "node:crypto";
14
+ import { createHash, randomUUID } from "node:crypto";
15
15
  import { STLManipulator, SLICER_TYPES, normalizeSlicerType, SlicerRunError, } from "./stl/stl-manipulator.js";
16
16
  import { BambuNetworkBridge, describeBambuNetworkPrintError } from "./bambu-network-bridge.js";
17
17
  import { assertBambuNativeAvailable, bambuNativeControlsAvailable, bambuNativeUnavailableReason, interruptNativeOperations, validateBambuNativeMetadata, buildBambuNativeFanCommand, buildBambuNativeTemperatureCommand, printWithBambuNative, sendCommandWithBambuNative, uploadWithBambuNative, } from "./bambu-native.js";
@@ -19,10 +19,12 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
19
19
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
20
20
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge } from "./fusion-mcp-bridge.js";
21
21
  import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
22
- import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, parse3MF } from './3mf_parser.js';
22
+ import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, parse3MF } from './3mf_parser.js';
23
23
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
24
24
  import { resolveStudioPrintOptions, usedNozzleCount } from "./studio-print-options.js";
25
25
  import { inspectPrintFile } from "./safety/print-file.js";
26
+ import { previewPrintFile } from "./safety/print-preview.js";
27
+ import { loadSafe3mfArchive } from "./safety/archive.js";
26
28
  import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
27
29
  import { isDualNozzleModel } from "./safety/limits.js";
28
30
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
@@ -705,9 +707,50 @@ async function resolveTemplateSlicerProfilePath(templatePath, tempDir) {
705
707
  }
706
708
  throw new Error(`Template profile must be a .3mf, .json, or .config file: ${templatePath}`);
707
709
  }
710
+ /** inspect_print_file's preview: drawn from the snapshot's own bytes, refused if they aren't the inspected ones. */
711
+ async function previewOfSnapshot(snapshot, plateIndex, sha256) {
712
+ const bytes = await fs.promises.readFile(snapshot);
713
+ if (createHash("sha256").update(bytes).digest("hex") !== sha256)
714
+ throw new Error("The file changed while it was being inspected; nothing was previewed.");
715
+ let gcode, projectColours;
716
+ if (snapshot.toLowerCase().endsWith(".3mf")) {
717
+ const zip = await loadSafe3mfArchive(bytes);
718
+ const entry = zip.file(`Metadata/plate_${plateIndex + 1}.gcode`);
719
+ if (!entry)
720
+ return undefined;
721
+ gcode = await entry.async("string");
722
+ const settings = zip.file("Metadata/project_settings.config");
723
+ if (settings) {
724
+ try {
725
+ const parsed = JSON.parse(await settings.async("string"));
726
+ if (Array.isArray(parsed?.filament_colour))
727
+ projectColours = parsed.filament_colour;
728
+ }
729
+ catch { /* colours fall back to the G-code header */ }
730
+ }
731
+ }
732
+ else
733
+ gcode = bytes.toString("utf8");
734
+ const preview = await previewPrintFile({ gcode, ...(projectColours ? { projectColours } : {}) });
735
+ return preview ? { ...preview, artifact_sha256: sha256, plate_index: plateIndex } : undefined;
736
+ }
708
737
  function hasExplicitSlicerProfile(args) {
709
738
  return typeof args?.slicer_profile === "string" && args.slicer_profile.trim().length > 0;
710
739
  }
740
+ /**
741
+ * A 3MF that carries its own process (a designer's project) as its slicing template, when the call names
742
+ * no profile or template of its own. A configured default profile or template must not replace the
743
+ * designer's layer height, walls and infill; the machine still comes from the chosen printer preset.
744
+ */
745
+ /** The template this call names: template_name (resolved by the caller) or template_3mf_path. */
746
+ function namedTemplatePath(args, fromName) {
747
+ return fromName || (typeof args?.template_3mf_path === "string" && args.template_3mf_path.trim() ? String(args.template_3mf_path) : undefined);
748
+ }
749
+ async function ownProcessTemplate(args, modelPath, requestedTemplatePath) {
750
+ if (hasExplicitSlicerProfile(args) || requestedTemplatePath || !modelPath.toLowerCase().endsWith(".3mf"))
751
+ return undefined;
752
+ return await hasBambuProjectSettings(modelPath) ? modelPath : undefined;
753
+ }
711
754
  async function resolveTemplateFirstSlicerProfilePath(args, configuredProfile, template3mfPath, tempDir) {
712
755
  if (hasExplicitSlicerProfile(args)) {
713
756
  return configuredProfile || undefined;
@@ -1167,7 +1210,9 @@ class BambuPrinterMCPServer {
1167
1210
  nozzleType: resolveNozzleType(args?.nozzle_type),
1168
1211
  nozzleVolumeType: resolveNozzleVolumeType(args?.nozzle_volume_type),
1169
1212
  };
1170
- threeMFPath = await this.stlManipulator.sliceSTL(threeMFPath, slicerType, slicerPath, slicerProfile || undefined, undefined, printPreset, autoSliceOptions);
1213
+ // A designer's project slices with its own process here too, as slice_stl and the LAN route do.
1214
+ const ownProcess = await ownProcessTemplate(args, threeMFPath, namedTemplatePath(args, typeof args?.template_name === "string" && args.template_name.trim() ? String(args.template_name) : undefined));
1215
+ threeMFPath = await this.stlManipulator.sliceSTL(threeMFPath, slicerType, slicerPath, ownProcess ? await resolveTemplateSlicerProfilePath(ownProcess, TEMP_DIR) : slicerProfile || undefined, undefined, printPreset, autoSliceOptions);
1171
1216
  console.error("Auto-sliced to: " + threeMFPath);
1172
1217
  return { threeMFPath, autoSliced: true };
1173
1218
  }
@@ -2079,7 +2124,7 @@ class BambuPrinterMCPServer {
2079
2124
  },
2080
2125
  {
2081
2126
  name: "slice_stl",
2082
- 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.",
2127
+ 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. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2083
2128
  inputSchema: {
2084
2129
  type: "object",
2085
2130
  properties: {
@@ -2624,6 +2669,7 @@ class BambuPrinterMCPServer {
2624
2669
  plate_index: { type: "integer", minimum: 0, description: "Zero-based selected plate; defaults to 0. Raw G-code only supports 0." },
2625
2670
  nozzle_diameters: { type: "array", minItems: 1, maxItems: 2, items: { type: "number", enum: [0.2, 0.4, 0.6, 0.8] }, description: "Optional requested nozzle diameters to compare with file declarations; this does not observe installed hardware." },
2626
2671
  bed_type: { type: "string", enum: [...VALID_BED_TYPES], description: "Optional declared bed type to compare with file metadata." },
2672
+ include_preview: { type: "boolean", description: "Also return preview: PNG pictures drawn from this exact file's G-code (every extruding line in its filament's colour; the top as it sits on the bed, and the bed side turned over), with the artifact's sha256. Large (tens of KB of base64); for apps that show the person what will print, not for agents." },
2627
2673
  },
2628
2674
  required: ["file_path", "bambu_model"],
2629
2675
  },
@@ -3065,9 +3111,11 @@ class BambuPrinterMCPServer {
3065
3111
  let result;
3066
3112
  switch (name) {
3067
3113
  case "inspect_print_file": {
3068
- const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type"]);
3114
+ const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type", "include_preview"]);
3069
3115
  if (!args || Object.keys(args).some(key => !allowed.has(key)))
3070
- throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed arguments.");
3116
+ throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed/preview arguments.");
3117
+ if (args.include_preview !== undefined && typeof args.include_preview !== "boolean")
3118
+ throw new Error("include_preview must be true or false.");
3071
3119
  if (typeof args.file_path !== "string" || !args.file_path.trim() || args.file_path.includes("\0"))
3072
3120
  throw new Error("file_path must name a local prepared artifact.");
3073
3121
  if (typeof args.bambu_model !== "string" || !args.bambu_model.trim())
@@ -3089,6 +3137,8 @@ class BambuPrinterMCPServer {
3089
3137
  if (extra.signal.aborted)
3090
3138
  throw new Error("File inspection cancelled.");
3091
3139
  const byteLength = (await fs.promises.stat(snapshot)).size;
3140
+ // The picture is drawn from these same snapshot bytes, so it is of exactly the file inspected.
3141
+ const preview = args.include_preview === true ? await previewOfSnapshot(snapshot, plateIndex, inspection.sha256) : undefined;
3092
3142
  return {
3093
3143
  receipt_version: "1",
3094
3144
  evidence: "file-only",
@@ -3096,6 +3146,7 @@ class BambuPrinterMCPServer {
3096
3146
  artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
3097
3147
  selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
3098
3148
  inspection,
3149
+ ...(preview ? { preview } : {}),
3099
3150
  };
3100
3151
  });
3101
3152
  break;
@@ -3667,8 +3718,12 @@ class BambuPrinterMCPServer {
3667
3718
  }
3668
3719
  const sliceModel = await this.resolveBambuModel(args?.bambu_model);
3669
3720
  const nozzleDiam = String(args?.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER);
3670
- const activeSlicerProfile = await resolveSlicerProfilePath(slicerProfile || undefined, resolveTemplatePathFromName(["json", "config", "3mf"]) || explicitTemplatePath || undefined, TEMP_DIR);
3671
3721
  const explicitSlicerProfile = hasExplicitSlicerProfile(args);
3722
+ const requestedTemplatePath = namedTemplatePath(args, resolveTemplatePathFromName(["json", "config", "3mf"]));
3723
+ const ownProcess3mf = await ownProcessTemplate(args, String(args.stl_path), requestedTemplatePath);
3724
+ const activeSlicerProfile = ownProcess3mf
3725
+ ? await resolveSlicerProfilePath(undefined, ownProcess3mf, TEMP_DIR)
3726
+ : await resolveSlicerProfilePath(slicerProfile || undefined, requestedTemplatePath || explicitTemplatePath || undefined, TEMP_DIR);
3672
3727
  // Resolve printer preset for BambuStudio slicer
3673
3728
  const printerPreset = BAMBU_MODEL_PRESETS[sliceModel]?.(nozzleDiam);
3674
3729
  const sliceBambuOptions = {};
@@ -3791,7 +3846,11 @@ class BambuPrinterMCPServer {
3791
3846
  const printBedType = resolveBedType(args?.bed_type);
3792
3847
  const printNozzles = requestedPrintNozzles(args);
3793
3848
  const printNozzle = String(printNozzles?.[0] ?? DEFAULT_NOZZLE_DIAMETER);
3794
- const activeSlicerProfile = await resolveTemplateFirstSlicerProfilePath(args, slicerProfile || undefined, resolveTemplatePathFromName(["json", "config", "3mf"]) || explicitTemplatePath || undefined, TEMP_DIR);
3849
+ const requestedPrintTemplate = namedTemplatePath(args, resolveTemplatePathFromName(["json", "config", "3mf"]));
3850
+ const ownPrintProcess = await ownProcessTemplate(args, String(args.three_mf_path), requestedPrintTemplate);
3851
+ const activeSlicerProfile = ownPrintProcess
3852
+ ? await resolveTemplateSlicerProfilePath(ownPrintProcess, TEMP_DIR)
3853
+ : await resolveTemplateFirstSlicerProfilePath(args, slicerProfile || undefined, requestedPrintTemplate || explicitTemplatePath || undefined, TEMP_DIR);
3795
3854
  const explicitSlicerProfile = hasExplicitSlicerProfile(args);
3796
3855
  const printPreset = BAMBU_MODEL_PRESETS[printModel]?.(printNozzle);
3797
3856
  const plateIndex = args?.plate_index !== undefined ? Number(args.plate_index) : 0;
@@ -0,0 +1,41 @@
1
+ export interface PreviewView {
2
+ name: "top" | "bed_side";
3
+ label: string;
4
+ png_base64: string;
5
+ width: number;
6
+ height: number;
7
+ }
8
+ export interface PrintPreview {
9
+ views: PreviewView[];
10
+ /** Millimetres per pixel in both views. */
11
+ mm_per_pixel: number;
12
+ /** The drawn area on the bed, in millimetres: [minX, minY, maxX, maxY]. */
13
+ extent_mm: [number, number, number, number];
14
+ layers: number;
15
+ /** Filament slots (0-based, as the G-code's T numbers) that extrude on this plate. */
16
+ filaments_used: number[];
17
+ }
18
+ /** RGB pixels (row-major) as a PNG. */
19
+ export declare function encodePng(width: number, height: number, rgb: Uint8Array): Buffer;
20
+ interface Segment {
21
+ x0: number;
22
+ y0: number;
23
+ x1: number;
24
+ y1: number;
25
+ z: number;
26
+ tool: number;
27
+ width: number;
28
+ }
29
+ /** Extruding moves of one plate's G-code, start-up purge and filament-change flushing excluded. */
30
+ export declare function extrusionSegments(gcode: string): {
31
+ segments: Segment[];
32
+ layers: number;
33
+ };
34
+ /** The top and bed-side pictures of one plate's G-code. `colours` are the project's filament colours by slot. */
35
+ export declare function renderPrintPreview(gcode: string, colours?: unknown[]): PrintPreview | undefined;
36
+ /** The preview of one plate of a sliced .3mf or a .gcode file, or undefined when it has no extruding moves. */
37
+ export declare function previewPrintFile(source: {
38
+ gcode: string;
39
+ projectColours?: unknown[];
40
+ }): Promise<PrintPreview | undefined>;
41
+ export {};
@@ -0,0 +1,307 @@
1
+ /**
2
+ * A picture of what the printer will lay down, drawn from the exact sliced G-code (never from a
3
+ * thumbnail: Bambu Studio's CLI copies a project's old plate PNGs into the sliced file unchanged).
4
+ * Every extruding move on the selected plate is drawn in its filament's colour, except the slicer's
5
+ * start-up purge and prime lines (feature "Custom") and Bambu's filament-change flushing (between
6
+ * M620 and M621). Features are read from Bambu Studio/Orca "; FEATURE:" and PrusaSlicer/Cura ";TYPE:"
7
+ * comments; G-code with neither is drawn whole. Two views: the top as it sits on the bed, and
8
+ * the bed side as you see it after turning the part over toward you (top to bottom), so text on
9
+ * that face reads as it will.
10
+ * Deterministic: the same bytes always give the same pictures.
11
+ */
12
+ import { deflateSync } from "zlib";
13
+ const BACKGROUND = [245, 245, 247];
14
+ const MAX_PIXELS = 1400;
15
+ function parseColour(value) {
16
+ const match = typeof value === "string" ? /^#?([0-9a-f]{6})/i.exec(value.trim()) : null;
17
+ if (!match)
18
+ return undefined;
19
+ const n = parseInt(match[1], 16);
20
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
21
+ }
22
+ const crcTable = (() => {
23
+ const table = new Uint32Array(256);
24
+ for (let n = 0; n < 256; n++) {
25
+ let c = n;
26
+ for (let k = 0; k < 8; k++)
27
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
28
+ table[n] = c >>> 0;
29
+ }
30
+ return table;
31
+ })();
32
+ function crc32(bytes) {
33
+ let c = 0xffffffff;
34
+ for (const b of bytes)
35
+ c = crcTable[(c ^ b) & 255] ^ (c >>> 8);
36
+ return (c ^ 0xffffffff) >>> 0;
37
+ }
38
+ function chunk(type, data) {
39
+ const length = Buffer.alloc(4);
40
+ length.writeUInt32BE(data.length);
41
+ const body = Buffer.concat([Buffer.from(type, "ascii"), Buffer.from(data)]);
42
+ const crc = Buffer.alloc(4);
43
+ crc.writeUInt32BE(crc32(body));
44
+ return Buffer.concat([length, body, crc]);
45
+ }
46
+ /** RGB pixels (row-major) as a PNG. */
47
+ export function encodePng(width, height, rgb) {
48
+ const raw = Buffer.alloc((width * 3 + 1) * height);
49
+ for (let y = 0; y < height; y++) {
50
+ raw[y * (width * 3 + 1)] = 0;
51
+ Buffer.from(rgb.buffer, rgb.byteOffset + y * width * 3, width * 3).copy(raw, y * (width * 3 + 1) + 1);
52
+ }
53
+ const header = Buffer.alloc(13);
54
+ header.writeUInt32BE(width, 0);
55
+ header.writeUInt32BE(height, 4);
56
+ header[8] = 8;
57
+ header[9] = 2;
58
+ header[10] = 0;
59
+ header[11] = 0;
60
+ header[12] = 0;
61
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", new Uint8Array())]);
62
+ }
63
+ /** Extruding moves of one plate's G-code, start-up purge and filament-change flushing excluded. */
64
+ export function extrusionSegments(gcode) {
65
+ const marked = [], unmarked = [];
66
+ let x = 0, y = 0, z = 0, e = 0, absoluteXY = true, relativeE = false, tool = 0, feature = "", layers = 0, width = 0.42;
67
+ let sawFeature = false, changingFilament = false;
68
+ const lines = gcode.split(/\r\n|\n|\r/);
69
+ for (const raw of lines) {
70
+ const comment = raw.indexOf(";");
71
+ if (comment >= 0) {
72
+ const note = raw.slice(comment + 1).trim();
73
+ const featureMatch = /^(?:FEATURE|TYPE)\s*:\s*(.*)$/i.exec(note);
74
+ if (featureMatch) {
75
+ feature = featureMatch[1].trim().toLowerCase();
76
+ sawFeature = true;
77
+ }
78
+ else if (/^(CHANGE_LAYER|LAYER_CHANGE)$/i.test(note))
79
+ layers++;
80
+ else {
81
+ const w = /^(?:LINE_WIDTH|WIDTH)\s*:\s*([\d.]+)/i.exec(note);
82
+ if (w && Number(w[1]) > 0 && Number(w[1]) < 5)
83
+ width = Number(w[1]);
84
+ }
85
+ }
86
+ // The syntax file inspection accepts (print-file.ts): optional line number and checksum, a command word that
87
+ // may be zero-padded (G01) or touch its first parameter (G1X20), and parameters with or without spaces or a + sign.
88
+ const line = (comment >= 0 ? raw.slice(0, comment) : raw).trim().toUpperCase().replace(/^N\d+\s*/, "").replace(/\*\d+\s*$/, "");
89
+ if (!line)
90
+ continue;
91
+ const command = /^([GMT])(\d+(?:\.\d+)?)/.exec(line);
92
+ if (!command)
93
+ continue;
94
+ const word = command[1] + String(Number(command[2].split(".")[0])) + (command[2].includes(".") ? "." + command[2].split(".")[1] : "");
95
+ const words = parameterWords(line.slice(command[0].length));
96
+ if (command[1] === "T") {
97
+ const t = Number(command[2]);
98
+ if (Number.isInteger(t) && t < 255)
99
+ tool = t;
100
+ continue;
101
+ }
102
+ // Bambu's AMS filament change (cut, retract, flush into the chute) runs from M620 to M621: not the part.
103
+ if (word === "M620") {
104
+ changingFilament = true;
105
+ continue;
106
+ }
107
+ if (word === "M621") {
108
+ changingFilament = false;
109
+ continue;
110
+ }
111
+ if (word === "G90") {
112
+ absoluteXY = true;
113
+ continue;
114
+ }
115
+ if (word === "G91") {
116
+ absoluteXY = false;
117
+ continue;
118
+ }
119
+ if (word === "M82") {
120
+ relativeE = false;
121
+ continue;
122
+ }
123
+ if (word === "M83") {
124
+ relativeE = true;
125
+ continue;
126
+ }
127
+ if (word === "G92") {
128
+ const reset = words.get("E");
129
+ if (reset !== undefined)
130
+ e = reset;
131
+ continue;
132
+ }
133
+ if (word !== "G0" && word !== "G1" && word !== "G2" && word !== "G3")
134
+ continue;
135
+ const value = (axis) => words.get(axis);
136
+ const nx = value("X"), ny = value("Y"), nz = value("Z"), ne = value("E");
137
+ const tx = nx === undefined ? x : absoluteXY ? nx : x + nx;
138
+ const ty = ny === undefined ? y : absoluteXY ? ny : y + ny;
139
+ if (nz !== undefined)
140
+ z = absoluteXY ? nz : z + nz;
141
+ let extruding = false;
142
+ if (ne !== undefined) {
143
+ const delta = relativeE ? ne : ne - e;
144
+ e = relativeE ? e + ne : ne;
145
+ extruding = delta > 0 && word !== "G0";
146
+ }
147
+ const arc = word === "G2" || word === "G3";
148
+ const centre = arc ? arcCentre(x, y, tx, ty, word === "G2", value("I"), value("J"), value("R")) : undefined;
149
+ const segments = feature ? marked : unmarked;
150
+ if (extruding && !changingFilament && feature !== "custom" && (tx !== x || ty !== y || centre)) {
151
+ if (centre) {
152
+ // Arc about its centre, swept clockwise (G2) or counter-clockwise (G3); the same end point is a full circle.
153
+ const [cx, cy] = centre;
154
+ const r = Math.hypot(x - cx, y - cy);
155
+ let a0 = Math.atan2(y - cy, x - cx), a1 = Math.atan2(ty - cy, tx - cx);
156
+ if (word === "G2") {
157
+ while (a1 >= a0)
158
+ a1 -= 2 * Math.PI;
159
+ }
160
+ else {
161
+ while (a1 <= a0)
162
+ a1 += 2 * Math.PI;
163
+ }
164
+ const steps = Math.max(2, Math.ceil(Math.abs(a1 - a0) * r / 0.2));
165
+ let px = x, py = y;
166
+ for (let i = 1; i <= steps; i++) {
167
+ const a = a0 + (a1 - a0) * i / steps;
168
+ const qx = i === steps ? tx : cx + r * Math.cos(a), qy = i === steps ? ty : cy + r * Math.sin(a);
169
+ segments.push({ x0: px, y0: py, x1: qx, y1: qy, z, tool, width });
170
+ px = qx;
171
+ py = qy;
172
+ }
173
+ }
174
+ else
175
+ segments.push({ x0: x, y0: y, x1: tx, y1: ty, z, tool, width });
176
+ }
177
+ x = tx;
178
+ y = ty;
179
+ }
180
+ // G-code that names no features at all is drawn whole rather than not at all.
181
+ return { segments: sawFeature ? marked : unmarked, layers };
182
+ }
183
+ /** A command's parameters, as file inspection reads them: letter then number, spaces and a + sign optional. */
184
+ function parameterWords(text) {
185
+ const words = new Map();
186
+ let rest = text.trim();
187
+ while (rest) {
188
+ const token = /^([A-Z])\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+))?/.exec(rest);
189
+ if (!token)
190
+ break;
191
+ if (token[2] !== undefined && !words.has(token[1]))
192
+ words.set(token[1], Number(token[2]));
193
+ rest = rest.slice(token[0].length).trimStart();
194
+ }
195
+ return words;
196
+ }
197
+ /** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
198
+ function arcCentre(x, y, tx, ty, clockwise, i, j, r) {
199
+ if (i !== undefined || j !== undefined)
200
+ return [x + (i ?? 0), y + (j ?? 0)];
201
+ if (r === undefined || r === 0 || (tx === x && ty === y))
202
+ return undefined;
203
+ const dx = tx - x, dy = ty - y, chord = Math.hypot(dx, dy);
204
+ if (chord > 2 * Math.abs(r) + 1e-9)
205
+ return undefined;
206
+ const h = Math.sqrt(Math.max(0, r * r - (chord / 2) ** 2));
207
+ const mx = (x + tx) / 2, my = (y + ty) / 2;
208
+ // Which side of the chord the centre lies on: clockwise short arcs keep it to the right of the travel.
209
+ const side = (clockwise ? -1 : 1) * (r > 0 ? 1 : -1);
210
+ return [mx - side * h * dy / chord, my + side * h * dx / chord];
211
+ }
212
+ /** The top and bed-side pictures of one plate's G-code. `colours` are the project's filament colours by slot. */
213
+ export function renderPrintPreview(gcode, colours = []) {
214
+ const { segments, layers } = extrusionSegments(gcode);
215
+ if (!segments.length)
216
+ return undefined;
217
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity, minZ = Infinity, maxZ = -Infinity;
218
+ for (const s of segments) {
219
+ minX = Math.min(minX, s.x0, s.x1);
220
+ maxX = Math.max(maxX, s.x0, s.x1);
221
+ minY = Math.min(minY, s.y0, s.y1);
222
+ maxY = Math.max(maxY, s.y0, s.y1);
223
+ minZ = Math.min(minZ, s.z);
224
+ maxZ = Math.max(maxZ, s.z);
225
+ }
226
+ const margin = 2;
227
+ minX -= margin;
228
+ minY -= margin;
229
+ maxX += margin;
230
+ maxY += margin;
231
+ const span = Math.max(maxX - minX, maxY - minY);
232
+ // Fine enough for 0.3 mm ruler ticks (at least 4 px/mm) whenever the plate's drawn area allows.
233
+ const ppm = Math.min(8, Math.max(1, MAX_PIXELS / span));
234
+ const width = Math.max(1, Math.ceil((maxX - minX) * ppm)), height = Math.max(1, Math.ceil((maxY - minY) * ppm));
235
+ const palette = (tool) => parseColour(colours[tool]) ?? [40, 40, 40];
236
+ const used = new Set();
237
+ const draw = (top) => {
238
+ const depth = new Float64Array(width * height).fill(top ? -Infinity : Infinity);
239
+ const toolAt = new Int16Array(width * height).fill(-1);
240
+ for (const s of segments) {
241
+ used.add(s.tool);
242
+ const ax = (s.x0 - minX) * ppm, ay = (maxY - s.y0) * ppm, bx = (s.x1 - minX) * ppm, by = (maxY - s.y1) * ppm;
243
+ // Each line at its extrusion width, so a surface's lines meet as they do on the part.
244
+ const radius = Math.max(0.5, s.width * ppm / 2), r2 = radius * radius, reach = Math.ceil(radius);
245
+ const steps = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / Math.max(0.5, radius / 2)));
246
+ for (let i = 0; i <= steps; i++) {
247
+ const cx = ax + (bx - ax) * i / steps, cy = ay + (by - ay) * i / steps;
248
+ for (let dy = -reach; dy <= reach; dy++)
249
+ for (let dx = -reach; dx <= reach; dx++) {
250
+ if (dx * dx + dy * dy > r2)
251
+ continue;
252
+ const px = Math.floor(cx + dx), py = Math.floor(cy + dy);
253
+ if (px < 0 || py < 0 || px >= width || py >= height)
254
+ continue;
255
+ const k = py * width + px;
256
+ if (top ? s.z >= depth[k] : s.z <= depth[k]) {
257
+ depth[k] = s.z;
258
+ toolAt[k] = s.tool;
259
+ }
260
+ }
261
+ }
262
+ }
263
+ const rgb = new Uint8Array(width * height * 3);
264
+ const zRange = Math.max(1e-6, maxZ - minZ);
265
+ for (let py = 0; py < height; py++)
266
+ for (let px = 0; px < width; px++) {
267
+ // The bed side is the part turned over top to bottom, so its text reads as it will on the part.
268
+ const sy = top ? py : height - 1 - py;
269
+ const k = sy * width + px, o = (py * width + px) * 3, t = toolAt[k];
270
+ if (t < 0) {
271
+ rgb[o] = BACKGROUND[0];
272
+ rgb[o + 1] = BACKGROUND[1];
273
+ rgb[o + 2] = BACKGROUND[2];
274
+ continue;
275
+ }
276
+ const [r, g, b] = palette(t);
277
+ // Height shading, toward white so it shows on dark filament too: on the top view the highest
278
+ // lines (raised tabs, top surfaces) are lightest; on the bed side the face on the bed is.
279
+ const h = (depth[k] - minZ) / zRange, lift = 0.4 * (top ? h : 1 - h);
280
+ rgb[o] = Math.round(r + (255 - r) * lift);
281
+ rgb[o + 1] = Math.round(g + (255 - g) * lift);
282
+ rgb[o + 2] = Math.round(b + (255 - b) * lift);
283
+ }
284
+ return encodePng(width, height, rgb).toString("base64");
285
+ };
286
+ const top = draw(true), bed = draw(false);
287
+ return {
288
+ views: [
289
+ { name: "top", label: "Top, as it sits on the bed", png_base64: top, width, height },
290
+ { name: "bed_side", label: "Bed side, turned over toward you", png_base64: bed, width, height },
291
+ ],
292
+ mm_per_pixel: Math.round(1e6 / ppm) / 1e6,
293
+ extent_mm: [minX, minY, maxX, maxY].map(v => Math.round(v * 100) / 100),
294
+ layers,
295
+ filaments_used: [...used].sort((a, b) => a - b),
296
+ };
297
+ }
298
+ /** The preview of one plate of a sliced .3mf or a .gcode file, or undefined when it has no extruding moves. */
299
+ export async function previewPrintFile(source) {
300
+ let colours = source.projectColours;
301
+ if (!colours?.length) {
302
+ // A bare .gcode file carries its colours in its header: "; filament_colour = #000000;#FFFFFF".
303
+ const header = /^\s*;\s*filament_colou?r\s*[=:]\s*(.+)$/im.exec(source.gcode);
304
+ colours = header ? header[1].split(/[;,]/).map(v => v.trim()) : [];
305
+ }
306
+ return renderPrintPreview(source.gcode, colours);
307
+ }
@@ -2,8 +2,10 @@
2
2
  * slice_stl's `quality` and `strength` (PRD §8.4): a client's print-sheet choice, mapped here to the
3
3
  * slicer's own numbers so no client carries layer heights, wall counts or infill. Draft and Fine set
4
4
  * the layer height for the nozzle in use (0.28 and 0.12 mm on a 0.4 mm nozzle, scaled with it); Strong
5
- * and Max set walls and infill. Standard sends nothing: the resolved preset decides. An explicit
6
- * layer_height, wall_loops or sparse_infill_density in the same call wins over these.
5
+ * and Max raise walls and infill to at least their values: a process that already has more (a
6
+ * designer's 3MF at 100% infill) keeps it, so a stronger choice never prints weaker. Standard sends
7
+ * nothing: the resolved process decides. An explicit layer_height, wall_loops or
8
+ * sparse_infill_density in the same call wins over these and is written as given.
7
9
  */
8
10
  export declare const PRINT_QUALITIES: readonly ["draft", "standard", "fine"];
9
11
  export declare const PRINT_STRENGTHS: readonly ["standard", "strong", "max"];
@@ -21,6 +23,6 @@ export declare const PRINT_QUALITY_PROPERTIES: {
21
23
  readonly strength: {
22
24
  readonly type: "string";
23
25
  readonly enum: readonly ["standard", "strong", "max"];
24
- readonly description: "Part strength: standard (the preset's walls and infill), strong or max (more walls and denser infill). The server picks the values; explicit wall_loops or sparse_infill_density win.";
26
+ readonly description: "Part strength: standard (the process's own walls and infill), strong or max (at least more walls and denser infill; a process that already has more keeps it). The server picks the values; explicit wall_loops or sparse_infill_density win.";
25
27
  };
26
28
  };
@@ -2,8 +2,10 @@
2
2
  * slice_stl's `quality` and `strength` (PRD §8.4): a client's print-sheet choice, mapped here to the
3
3
  * slicer's own numbers so no client carries layer heights, wall counts or infill. Draft and Fine set
4
4
  * the layer height for the nozzle in use (0.28 and 0.12 mm on a 0.4 mm nozzle, scaled with it); Strong
5
- * and Max set walls and infill. Standard sends nothing: the resolved preset decides. An explicit
6
- * layer_height, wall_loops or sparse_infill_density in the same call wins over these.
5
+ * and Max raise walls and infill to at least their values: a process that already has more (a
6
+ * designer's 3MF at 100% infill) keeps it, so a stronger choice never prints weaker. Standard sends
7
+ * nothing: the resolved process decides. An explicit layer_height, wall_loops or
8
+ * sparse_infill_density in the same call wins over these and is written as given.
7
9
  */
8
10
  export const PRINT_QUALITIES = ["draft", "standard", "fine"];
9
11
  export const PRINT_STRENGTHS = ["standard", "strong", "max"];
@@ -34,9 +36,9 @@ export function withPrintQuality(args, nozzleDiameter) {
34
36
  const walls = STRENGTH[strength];
35
37
  if (walls) {
36
38
  if (out.wall_loops === undefined)
37
- out.wall_loops = walls.wall_loops;
39
+ out.wall_loops_floor = walls.wall_loops;
38
40
  if (out.sparse_infill_density === undefined)
39
- out.sparse_infill_density = walls.sparse_infill_density;
41
+ out.sparse_infill_density_floor = walls.sparse_infill_density;
40
42
  }
41
43
  return out;
42
44
  }
@@ -48,6 +50,6 @@ export const PRINT_QUALITY_PROPERTIES = {
48
50
  },
49
51
  strength: {
50
52
  type: "string", enum: [...PRINT_STRENGTHS],
51
- description: "Part strength: standard (the preset's walls and infill), strong or max (more walls and denser infill). The server picks the values; explicit wall_loops or sparse_infill_density win.",
53
+ description: "Part strength: standard (the process's own walls and infill), strong or max (at least more walls and denser infill; a process that already has more keeps it). The server picks the values; explicit wall_loops or sparse_infill_density win.",
52
54
  },
53
55
  };
@@ -5,7 +5,9 @@
5
5
  * "15%"), so the machine preset and every other process value stay as resolved.
6
6
  */
7
7
  export declare const PROCESS_OVERRIDE_KEYS: readonly ["layer_height", "wall_loops", "sparse_infill_density", "enable_support", "support_type", "support_threshold_angle"];
8
- export type ProcessOverrides = Partial<Record<(typeof PROCESS_OVERRIDE_KEYS)[number], string>>;
8
+ /** Minimums from a strength choice: the resolved process keeps its own value when it is already higher. */
9
+ export declare const PROCESS_FLOOR_KEYS: readonly ["wall_loops_floor", "sparse_infill_density_floor"];
10
+ export type ProcessOverrides = Partial<Record<(typeof PROCESS_OVERRIDE_KEYS)[number] | (typeof PROCESS_FLOOR_KEYS)[number], string>>;
9
11
  /** Bambu Studio's and OrcaSlicer's support_type values. */
10
12
  export declare const SUPPORT_TYPES: readonly ["normal(auto)", "tree(auto)", "normal(manual)", "tree(manual)"];
11
13
  /** Validate the tool arguments; undefined when none are given. */
@@ -5,6 +5,8 @@
5
5
  * "15%"), so the machine preset and every other process value stay as resolved.
6
6
  */
7
7
  export const PROCESS_OVERRIDE_KEYS = ["layer_height", "wall_loops", "sparse_infill_density", "enable_support", "support_type", "support_threshold_angle"];
8
+ /** Minimums from a strength choice: the resolved process keeps its own value when it is already higher. */
9
+ export const PROCESS_FLOOR_KEYS = ["wall_loops_floor", "sparse_infill_density_floor"];
8
10
  /** Bambu Studio's and OrcaSlicer's support_type values. */
9
11
  export const SUPPORT_TYPES = ["normal(auto)", "tree(auto)", "normal(manual)", "tree(manual)"];
10
12
  /** Validate the tool arguments; undefined when none are given. */
@@ -33,6 +35,11 @@ export function parseProcessOverrides(args, nozzleDiameter) {
33
35
  throw new Error('sparse_infill_density must be a percentage from 0% to 100%, such as "15%".');
34
36
  overrides.sparse_infill_density = `${Number(match[1])}%`;
35
37
  }
38
+ // Written by withPrintQuality for strong/max, never by a caller.
39
+ if (typeof args?.wall_loops_floor === "number")
40
+ overrides.wall_loops_floor = String(args.wall_loops_floor);
41
+ if (typeof args?.sparse_infill_density_floor === "string")
42
+ overrides.sparse_infill_density_floor = args.sparse_infill_density_floor;
36
43
  const enableSupport = args?.enable_support;
37
44
  if (enableSupport !== undefined) {
38
45
  if (typeof enableSupport !== "boolean")
@@ -58,5 +65,15 @@ export function parseProcessOverrides(args, nozzleDiameter) {
58
65
  }
59
66
  /** The process profile with the overrides written over its values. */
60
67
  export function applyProcessOverrides(profile, overrides) {
61
- return { ...profile, ...overrides };
68
+ const { wall_loops_floor: wallFloor, sparse_infill_density_floor: densityFloor, ...exact } = overrides;
69
+ const out = { ...profile };
70
+ const number = (value) => {
71
+ const parsed = Number.parseFloat(String(Array.isArray(value) ? value[0] : value ?? ""));
72
+ return Number.isFinite(parsed) ? parsed : undefined;
73
+ };
74
+ if (wallFloor !== undefined && (number(out.wall_loops) ?? -1) < Number(wallFloor))
75
+ out.wall_loops = wallFloor;
76
+ if (densityFloor !== undefined && (number(out.sparse_infill_density) ?? -1) < Number.parseFloat(densityFloor))
77
+ out.sparse_infill_density = densityFloor;
78
+ return { ...out, ...exact };
62
79
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.58",
3
+ "version": "1.1.60",
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/3mf_parser.ts CHANGED
@@ -2,6 +2,7 @@ import JSZip from 'jszip';
2
2
  import { parseStringPromise } from 'xml2js';
3
3
  import { ThreeMFData, BambuSlicerConfig, ThreeMFMetadata, ThreeMFObject, ThreeMFBuildItem, AMSFilamentMapping, CollarCharmAnalysis, CollarCharmRole, ThreeMFAmsRequirements, ThreeMFPlateObjects } from './types.js';
4
4
  import * as fs from 'fs/promises';
5
+ import { createHash } from 'crypto';
5
6
 
6
7
  // Parses Bambu Studio's JSON config data
7
8
  function parseBambuJSONConfig(jsonData: any): Partial<BambuSlicerConfig> {
@@ -227,6 +228,19 @@ export async function parse3MF(filePath: string): Promise<ThreeMFData> {
227
228
  }
228
229
  }
229
230
 
231
+ /** Whether a 3MF carries its own Bambu Studio/Orca process (a designer's project, not a bare mesh archive). */
232
+ export async function hasBambuProjectSettings(filePath: string): Promise<boolean> {
233
+ try {
234
+ const zip = await JSZip.loadAsync(await fs.readFile(filePath));
235
+ const settings = zip.file('Metadata/project_settings.config');
236
+ if (!settings) return false;
237
+ const parsed = JSON.parse(await settings.async('string'));
238
+ return !!parsed && typeof parsed === 'object' && !Array.isArray(parsed) && parsed.layer_height !== undefined;
239
+ } catch {
240
+ return false;
241
+ }
242
+ }
243
+
230
244
  export async function extractBambuTemplateSettings(
231
245
  filePath: string,
232
246
  outputDir: string
@@ -245,7 +259,9 @@ export async function extractBambuTemplateSettings(
245
259
  if (!file) continue;
246
260
 
247
261
  const content = await file.async('string');
248
- const outputPath = `${outputDir}/${name.replace(/\//g, '_')}`;
262
+ // Named by content, so two projects sliced at once never share (or overwrite) one settings file.
263
+ const digest = createHash('sha256').update(content).digest('hex').slice(0, 16);
264
+ const outputPath = `${outputDir}/${digest}_${name.replace(/\//g, '_')}`;
249
265
  await fs.writeFile(outputPath, content, 'utf8');
250
266
  return outputPath;
251
267
  }
package/src/index.ts CHANGED
@@ -21,7 +21,7 @@ import fs from "fs";
21
21
  import os from "node:os";
22
22
  import path from "path";
23
23
  import { createServer as createHttpServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from "node:http";
24
- import { randomUUID } from "node:crypto";
24
+ import { createHash, randomUUID } from "node:crypto";
25
25
  import {
26
26
  STLManipulator,
27
27
  SLICER_TYPES,
@@ -48,11 +48,13 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
48
48
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
49
49
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge } from "./fusion-mcp-bridge.js";
50
50
  import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
51
- import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, parse3MF } from './3mf_parser.js';
51
+ import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, parse3MF } from './3mf_parser.js';
52
52
  import type { ThreeMFAmsRequirements } from "./types.js";
53
53
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
54
54
  import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "./studio-print-options.js";
55
55
  import { inspectPrintFile } from "./safety/print-file.js";
56
+ import { previewPrintFile } from "./safety/print-preview.js";
57
+ import { loadSafe3mfArchive } from "./safety/archive.js";
56
58
  import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
57
59
  import { isDualNozzleModel } from "./safety/limits.js";
58
60
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
@@ -916,10 +918,44 @@ async function resolveTemplateSlicerProfilePath(
916
918
  throw new Error(`Template profile must be a .3mf, .json, or .config file: ${templatePath}`);
917
919
  }
918
920
 
921
+ /** inspect_print_file's preview: drawn from the snapshot's own bytes, refused if they aren't the inspected ones. */
922
+ async function previewOfSnapshot(snapshot: string, plateIndex: number, sha256: string) {
923
+ const bytes = await fs.promises.readFile(snapshot);
924
+ if (createHash("sha256").update(bytes).digest("hex") !== sha256) throw new Error("The file changed while it was being inspected; nothing was previewed.");
925
+ let gcode: string, projectColours: unknown[] | undefined;
926
+ if (snapshot.toLowerCase().endsWith(".3mf")) {
927
+ const zip = await loadSafe3mfArchive(bytes);
928
+ const entry = zip.file(`Metadata/plate_${plateIndex + 1}.gcode`);
929
+ if (!entry) return undefined;
930
+ gcode = await entry.async("string");
931
+ const settings = zip.file("Metadata/project_settings.config");
932
+ if (settings) {
933
+ try { const parsed = JSON.parse(await settings.async("string")); if (Array.isArray(parsed?.filament_colour)) projectColours = parsed.filament_colour; } catch { /* colours fall back to the G-code header */ }
934
+ }
935
+ } else gcode = bytes.toString("utf8");
936
+ const preview = await previewPrintFile({ gcode, ...(projectColours ? { projectColours } : {}) });
937
+ return preview ? { ...preview, artifact_sha256: sha256, plate_index: plateIndex } : undefined;
938
+ }
939
+
919
940
  function hasExplicitSlicerProfile(args: any): boolean {
920
941
  return typeof args?.slicer_profile === "string" && args.slicer_profile.trim().length > 0;
921
942
  }
922
943
 
944
+ /**
945
+ * A 3MF that carries its own process (a designer's project) as its slicing template, when the call names
946
+ * no profile or template of its own. A configured default profile or template must not replace the
947
+ * designer's layer height, walls and infill; the machine still comes from the chosen printer preset.
948
+ */
949
+ /** The template this call names: template_name (resolved by the caller) or template_3mf_path. */
950
+ function namedTemplatePath(args: any, fromName: string | undefined): string | undefined {
951
+ return fromName || (typeof args?.template_3mf_path === "string" && args.template_3mf_path.trim() ? String(args.template_3mf_path) : undefined);
952
+ }
953
+
954
+ async function ownProcessTemplate(args: any, modelPath: string, requestedTemplatePath: string | undefined): Promise<string | undefined> {
955
+ if (hasExplicitSlicerProfile(args) || requestedTemplatePath || !modelPath.toLowerCase().endsWith(".3mf")) return undefined;
956
+ return await hasBambuProjectSettings(modelPath) ? modelPath : undefined;
957
+ }
958
+
923
959
  async function resolveTemplateFirstSlicerProfilePath(
924
960
  args: any,
925
961
  configuredProfile: string | undefined,
@@ -1525,8 +1561,10 @@ class BambuPrinterMCPServer {
1525
1561
  nozzleType: resolveNozzleType(args?.nozzle_type),
1526
1562
  nozzleVolumeType: resolveNozzleVolumeType(args?.nozzle_volume_type),
1527
1563
  };
1564
+ // A designer's project slices with its own process here too, as slice_stl and the LAN route do.
1565
+ const ownProcess = await ownProcessTemplate(args, threeMFPath, namedTemplatePath(args, typeof args?.template_name === "string" && args.template_name.trim() ? String(args.template_name) : undefined));
1528
1566
  threeMFPath = await this.stlManipulator.sliceSTL(
1529
- threeMFPath, slicerType, slicerPath, slicerProfile || undefined,
1567
+ threeMFPath, slicerType, slicerPath, ownProcess ? await resolveTemplateSlicerProfilePath(ownProcess, TEMP_DIR) : slicerProfile || undefined,
1530
1568
  undefined,
1531
1569
  printPreset,
1532
1570
  autoSliceOptions
@@ -2613,7 +2651,7 @@ class BambuPrinterMCPServer {
2613
2651
  },
2614
2652
  {
2615
2653
  name: "slice_stl",
2616
- 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.",
2654
+ 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. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2617
2655
  inputSchema: {
2618
2656
  type: "object",
2619
2657
  properties: {
@@ -3158,6 +3196,7 @@ class BambuPrinterMCPServer {
3158
3196
  plate_index: { type: "integer", minimum: 0, description: "Zero-based selected plate; defaults to 0. Raw G-code only supports 0." },
3159
3197
  nozzle_diameters: { type: "array", minItems: 1, maxItems: 2, items: { type: "number", enum: [0.2, 0.4, 0.6, 0.8] }, description: "Optional requested nozzle diameters to compare with file declarations; this does not observe installed hardware." },
3160
3198
  bed_type: { type: "string", enum: [...VALID_BED_TYPES], description: "Optional declared bed type to compare with file metadata." },
3199
+ include_preview: { type: "boolean", description: "Also return preview: PNG pictures drawn from this exact file's G-code (every extruding line in its filament's colour; the top as it sits on the bed, and the bed side turned over), with the artifact's sha256. Large (tens of KB of base64); for apps that show the person what will print, not for agents." },
3161
3200
  },
3162
3201
  required: ["file_path", "bambu_model"],
3163
3202
  },
@@ -3609,8 +3648,9 @@ class BambuPrinterMCPServer {
3609
3648
 
3610
3649
  switch (name) {
3611
3650
  case "inspect_print_file": {
3612
- const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type"]);
3613
- if (!args || Object.keys(args).some(key => !allowed.has(key))) throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed arguments.");
3651
+ const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type", "include_preview"]);
3652
+ if (!args || Object.keys(args).some(key => !allowed.has(key))) throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed/preview arguments.");
3653
+ if (args.include_preview !== undefined && typeof args.include_preview !== "boolean") throw new Error("include_preview must be true or false.");
3614
3654
  if (typeof args.file_path !== "string" || !args.file_path.trim() || args.file_path.includes("\0")) throw new Error("file_path must name a local prepared artifact.");
3615
3655
  if (typeof args.bambu_model !== "string" || !args.bambu_model.trim()) throw new Error("An explicit bambu_model is required for file inspection.");
3616
3656
  const model = validateBambuModel(args.bambu_model);
@@ -3625,6 +3665,8 @@ class BambuPrinterMCPServer {
3625
3665
  const inspection = await inspectPrintFile(snapshot, { model, nozzleDiameters: nozzles, plateIndex, bedType });
3626
3666
  if (extra.signal.aborted) throw new Error("File inspection cancelled.");
3627
3667
  const byteLength = (await fs.promises.stat(snapshot)).size;
3668
+ // The picture is drawn from these same snapshot bytes, so it is of exactly the file inspected.
3669
+ const preview = args.include_preview === true ? await previewOfSnapshot(snapshot, plateIndex, inspection.sha256) : undefined;
3628
3670
  return {
3629
3671
  receipt_version: "1",
3630
3672
  evidence: "file-only",
@@ -3632,6 +3674,7 @@ class BambuPrinterMCPServer {
3632
3674
  artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
3633
3675
  selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
3634
3676
  inspection,
3677
+ ...(preview ? { preview } : {}),
3635
3678
  };
3636
3679
  });
3637
3680
  break;
@@ -4325,12 +4368,16 @@ class BambuPrinterMCPServer {
4325
4368
  }
4326
4369
  const sliceModel = await this.resolveBambuModel(args?.bambu_model as string | undefined);
4327
4370
  const nozzleDiam = String(args?.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER);
4328
- const activeSlicerProfile = await resolveSlicerProfilePath(
4329
- slicerProfile || undefined,
4330
- resolveTemplatePathFromName(["json", "config", "3mf"]) || explicitTemplatePath || undefined,
4331
- TEMP_DIR
4332
- );
4333
4371
  const explicitSlicerProfile = hasExplicitSlicerProfile(args);
4372
+ const requestedTemplatePath = namedTemplatePath(args, resolveTemplatePathFromName(["json", "config", "3mf"]));
4373
+ const ownProcess3mf = await ownProcessTemplate(args, String(args.stl_path), requestedTemplatePath);
4374
+ const activeSlicerProfile = ownProcess3mf
4375
+ ? await resolveSlicerProfilePath(undefined, ownProcess3mf, TEMP_DIR)
4376
+ : await resolveSlicerProfilePath(
4377
+ slicerProfile || undefined,
4378
+ requestedTemplatePath || explicitTemplatePath || undefined,
4379
+ TEMP_DIR
4380
+ );
4334
4381
  // Resolve printer preset for BambuStudio slicer
4335
4382
  const printerPreset = BAMBU_MODEL_PRESETS[sliceModel]?.(nozzleDiam);
4336
4383
 
@@ -4454,12 +4501,16 @@ class BambuPrinterMCPServer {
4454
4501
  const printBedType = resolveBedType(args?.bed_type as string | undefined);
4455
4502
  const printNozzles = requestedPrintNozzles(args as Record<string, any>);
4456
4503
  const printNozzle = String(printNozzles?.[0] ?? DEFAULT_NOZZLE_DIAMETER);
4457
- const activeSlicerProfile = await resolveTemplateFirstSlicerProfilePath(
4458
- args,
4459
- slicerProfile || undefined,
4460
- resolveTemplatePathFromName(["json", "config", "3mf"]) || explicitTemplatePath || undefined,
4461
- TEMP_DIR
4462
- );
4504
+ const requestedPrintTemplate = namedTemplatePath(args, resolveTemplatePathFromName(["json", "config", "3mf"]));
4505
+ const ownPrintProcess = await ownProcessTemplate(args, String(args.three_mf_path), requestedPrintTemplate);
4506
+ const activeSlicerProfile = ownPrintProcess
4507
+ ? await resolveTemplateSlicerProfilePath(ownPrintProcess, TEMP_DIR)
4508
+ : await resolveTemplateFirstSlicerProfilePath(
4509
+ args,
4510
+ slicerProfile || undefined,
4511
+ requestedPrintTemplate || explicitTemplatePath || undefined,
4512
+ TEMP_DIR
4513
+ );
4463
4514
  const explicitSlicerProfile = hasExplicitSlicerProfile(args);
4464
4515
  const printPreset = BAMBU_MODEL_PRESETS[printModel]?.(printNozzle);
4465
4516
  const plateIndex = args?.plate_index !== undefined ? Number(args.plate_index) : 0;
@@ -0,0 +1,244 @@
1
+ /**
2
+ * A picture of what the printer will lay down, drawn from the exact sliced G-code (never from a
3
+ * thumbnail: Bambu Studio's CLI copies a project's old plate PNGs into the sliced file unchanged).
4
+ * Every extruding move on the selected plate is drawn in its filament's colour, except the slicer's
5
+ * start-up purge and prime lines (feature "Custom") and Bambu's filament-change flushing (between
6
+ * M620 and M621). Features are read from Bambu Studio/Orca "; FEATURE:" and PrusaSlicer/Cura ";TYPE:"
7
+ * comments; G-code with neither is drawn whole. Two views: the top as it sits on the bed, and
8
+ * the bed side as you see it after turning the part over toward you (top to bottom), so text on
9
+ * that face reads as it will.
10
+ * Deterministic: the same bytes always give the same pictures.
11
+ */
12
+ import { deflateSync } from "zlib";
13
+
14
+ export interface PreviewView { name: "top" | "bed_side"; label: string; png_base64: string; width: number; height: number }
15
+ export interface PrintPreview {
16
+ views: PreviewView[];
17
+ /** Millimetres per pixel in both views. */
18
+ mm_per_pixel: number;
19
+ /** The drawn area on the bed, in millimetres: [minX, minY, maxX, maxY]. */
20
+ extent_mm: [number, number, number, number];
21
+ layers: number;
22
+ /** Filament slots (0-based, as the G-code's T numbers) that extrude on this plate. */
23
+ filaments_used: number[];
24
+ }
25
+
26
+ const BACKGROUND = [245, 245, 247];
27
+ const MAX_PIXELS = 1400;
28
+
29
+ function parseColour(value: unknown): [number, number, number] | undefined {
30
+ const match = typeof value === "string" ? /^#?([0-9a-f]{6})/i.exec(value.trim()) : null;
31
+ if (!match) return undefined;
32
+ const n = parseInt(match[1], 16);
33
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
34
+ }
35
+
36
+ const crcTable = (() => {
37
+ const table = new Uint32Array(256);
38
+ for (let n = 0; n < 256; n++) {
39
+ let c = n;
40
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
41
+ table[n] = c >>> 0;
42
+ }
43
+ return table;
44
+ })();
45
+ function crc32(bytes: Uint8Array): number {
46
+ let c = 0xffffffff;
47
+ for (const b of bytes) c = crcTable[(c ^ b) & 255] ^ (c >>> 8);
48
+ return (c ^ 0xffffffff) >>> 0;
49
+ }
50
+ function chunk(type: string, data: Uint8Array): Buffer {
51
+ const length = Buffer.alloc(4); length.writeUInt32BE(data.length);
52
+ const body = Buffer.concat([Buffer.from(type, "ascii"), Buffer.from(data)]);
53
+ const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(body));
54
+ return Buffer.concat([length, body, crc]);
55
+ }
56
+ /** RGB pixels (row-major) as a PNG. */
57
+ export function encodePng(width: number, height: number, rgb: Uint8Array): Buffer {
58
+ const raw = Buffer.alloc((width * 3 + 1) * height);
59
+ for (let y = 0; y < height; y++) {
60
+ raw[y * (width * 3 + 1)] = 0;
61
+ Buffer.from(rgb.buffer, rgb.byteOffset + y * width * 3, width * 3).copy(raw, y * (width * 3 + 1) + 1);
62
+ }
63
+ const header = Buffer.alloc(13);
64
+ header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4);
65
+ header[8] = 8; header[9] = 2; header[10] = 0; header[11] = 0; header[12] = 0;
66
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", new Uint8Array())]);
67
+ }
68
+
69
+ interface Segment { x0: number; y0: number; x1: number; y1: number; z: number; tool: number; width: number }
70
+
71
+ /** Extruding moves of one plate's G-code, start-up purge and filament-change flushing excluded. */
72
+ export function extrusionSegments(gcode: string): { segments: Segment[]; layers: number } {
73
+ const marked: Segment[] = [], unmarked: Segment[] = [];
74
+ let x = 0, y = 0, z = 0, e = 0, absoluteXY = true, relativeE = false, tool = 0, feature = "", layers = 0, width = 0.42;
75
+ let sawFeature = false, changingFilament = false;
76
+ const lines = gcode.split(/\r\n|\n|\r/);
77
+ for (const raw of lines) {
78
+ const comment = raw.indexOf(";");
79
+ if (comment >= 0) {
80
+ const note = raw.slice(comment + 1).trim();
81
+ const featureMatch = /^(?:FEATURE|TYPE)\s*:\s*(.*)$/i.exec(note);
82
+ if (featureMatch) { feature = featureMatch[1].trim().toLowerCase(); sawFeature = true; }
83
+ else if (/^(CHANGE_LAYER|LAYER_CHANGE)$/i.test(note)) layers++;
84
+ else { const w = /^(?:LINE_WIDTH|WIDTH)\s*:\s*([\d.]+)/i.exec(note); if (w && Number(w[1]) > 0 && Number(w[1]) < 5) width = Number(w[1]); }
85
+ }
86
+ // The syntax file inspection accepts (print-file.ts): optional line number and checksum, a command word that
87
+ // may be zero-padded (G01) or touch its first parameter (G1X20), and parameters with or without spaces or a + sign.
88
+ const line = (comment >= 0 ? raw.slice(0, comment) : raw).trim().toUpperCase().replace(/^N\d+\s*/, "").replace(/\*\d+\s*$/, "");
89
+ if (!line) continue;
90
+ const command = /^([GMT])(\d+(?:\.\d+)?)/.exec(line);
91
+ if (!command) continue;
92
+ const word = command[1] + String(Number(command[2].split(".")[0])) + (command[2].includes(".") ? "." + command[2].split(".")[1] : "");
93
+ const words = parameterWords(line.slice(command[0].length));
94
+ if (command[1] === "T") { const t = Number(command[2]); if (Number.isInteger(t) && t < 255) tool = t; continue; }
95
+ // Bambu's AMS filament change (cut, retract, flush into the chute) runs from M620 to M621: not the part.
96
+ if (word === "M620") { changingFilament = true; continue; }
97
+ if (word === "M621") { changingFilament = false; continue; }
98
+ if (word === "G90") { absoluteXY = true; continue; }
99
+ if (word === "G91") { absoluteXY = false; continue; }
100
+ if (word === "M82") { relativeE = false; continue; }
101
+ if (word === "M83") { relativeE = true; continue; }
102
+ if (word === "G92") { const reset = words.get("E"); if (reset !== undefined) e = reset; continue; }
103
+ if (word !== "G0" && word !== "G1" && word !== "G2" && word !== "G3") continue;
104
+ const value = (axis: string) => words.get(axis);
105
+ const nx = value("X"), ny = value("Y"), nz = value("Z"), ne = value("E");
106
+ const tx = nx === undefined ? x : absoluteXY ? nx : x + nx;
107
+ const ty = ny === undefined ? y : absoluteXY ? ny : y + ny;
108
+ if (nz !== undefined) z = absoluteXY ? nz : z + nz;
109
+ let extruding = false;
110
+ if (ne !== undefined) {
111
+ const delta = relativeE ? ne : ne - e;
112
+ e = relativeE ? e + ne : ne;
113
+ extruding = delta > 0 && word !== "G0";
114
+ }
115
+ const arc = word === "G2" || word === "G3";
116
+ const centre = arc ? arcCentre(x, y, tx, ty, word === "G2", value("I"), value("J"), value("R")) : undefined;
117
+ const segments = feature ? marked : unmarked;
118
+ if (extruding && !changingFilament && feature !== "custom" && (tx !== x || ty !== y || centre)) {
119
+ if (centre) {
120
+ // Arc about its centre, swept clockwise (G2) or counter-clockwise (G3); the same end point is a full circle.
121
+ const [cx, cy] = centre;
122
+ const r = Math.hypot(x - cx, y - cy);
123
+ let a0 = Math.atan2(y - cy, x - cx), a1 = Math.atan2(ty - cy, tx - cx);
124
+ if (word === "G2") { while (a1 >= a0) a1 -= 2 * Math.PI; } else { while (a1 <= a0) a1 += 2 * Math.PI; }
125
+ const steps = Math.max(2, Math.ceil(Math.abs(a1 - a0) * r / 0.2));
126
+ let px = x, py = y;
127
+ for (let i = 1; i <= steps; i++) {
128
+ const a = a0 + (a1 - a0) * i / steps;
129
+ const qx = i === steps ? tx : cx + r * Math.cos(a), qy = i === steps ? ty : cy + r * Math.sin(a);
130
+ segments.push({ x0: px, y0: py, x1: qx, y1: qy, z, tool, width });
131
+ px = qx; py = qy;
132
+ }
133
+ } else segments.push({ x0: x, y0: y, x1: tx, y1: ty, z, tool, width });
134
+ }
135
+ x = tx; y = ty;
136
+ }
137
+ // G-code that names no features at all is drawn whole rather than not at all.
138
+ return { segments: sawFeature ? marked : unmarked, layers };
139
+ }
140
+
141
+ /** A command's parameters, as file inspection reads them: letter then number, spaces and a + sign optional. */
142
+ function parameterWords(text: string): Map<string, number> {
143
+ const words = new Map<string, number>();
144
+ let rest = text.trim();
145
+ while (rest) {
146
+ const token = /^([A-Z])\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+))?/.exec(rest);
147
+ if (!token) break;
148
+ if (token[2] !== undefined && !words.has(token[1])) words.set(token[1], Number(token[2]));
149
+ rest = rest.slice(token[0].length).trimStart();
150
+ }
151
+ return words;
152
+ }
153
+
154
+ /** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
155
+ function arcCentre(x: number, y: number, tx: number, ty: number, clockwise: boolean, i?: number, j?: number, r?: number): [number, number] | undefined {
156
+ if (i !== undefined || j !== undefined) return [x + (i ?? 0), y + (j ?? 0)];
157
+ if (r === undefined || r === 0 || (tx === x && ty === y)) return undefined;
158
+ const dx = tx - x, dy = ty - y, chord = Math.hypot(dx, dy);
159
+ if (chord > 2 * Math.abs(r) + 1e-9) return undefined;
160
+ const h = Math.sqrt(Math.max(0, r * r - (chord / 2) ** 2));
161
+ const mx = (x + tx) / 2, my = (y + ty) / 2;
162
+ // Which side of the chord the centre lies on: clockwise short arcs keep it to the right of the travel.
163
+ const side = (clockwise ? -1 : 1) * (r > 0 ? 1 : -1);
164
+ return [mx - side * h * dy / chord, my + side * h * dx / chord];
165
+ }
166
+
167
+ /** The top and bed-side pictures of one plate's G-code. `colours` are the project's filament colours by slot. */
168
+ export function renderPrintPreview(gcode: string, colours: unknown[] = []): PrintPreview | undefined {
169
+ const { segments, layers } = extrusionSegments(gcode);
170
+ if (!segments.length) return undefined;
171
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity, minZ = Infinity, maxZ = -Infinity;
172
+ for (const s of segments) {
173
+ minX = Math.min(minX, s.x0, s.x1); maxX = Math.max(maxX, s.x0, s.x1);
174
+ minY = Math.min(minY, s.y0, s.y1); maxY = Math.max(maxY, s.y0, s.y1);
175
+ minZ = Math.min(minZ, s.z); maxZ = Math.max(maxZ, s.z);
176
+ }
177
+ const margin = 2;
178
+ minX -= margin; minY -= margin; maxX += margin; maxY += margin;
179
+ const span = Math.max(maxX - minX, maxY - minY);
180
+ // Fine enough for 0.3 mm ruler ticks (at least 4 px/mm) whenever the plate's drawn area allows.
181
+ const ppm = Math.min(8, Math.max(1, MAX_PIXELS / span));
182
+ const width = Math.max(1, Math.ceil((maxX - minX) * ppm)), height = Math.max(1, Math.ceil((maxY - minY) * ppm));
183
+ const palette = (tool: number) => parseColour(colours[tool]) ?? [40, 40, 40];
184
+ const used = new Set<number>();
185
+ const draw = (top: boolean) => {
186
+ const depth = new Float64Array(width * height).fill(top ? -Infinity : Infinity);
187
+ const toolAt = new Int16Array(width * height).fill(-1);
188
+ for (const s of segments) {
189
+ used.add(s.tool);
190
+ const ax = (s.x0 - minX) * ppm, ay = (maxY - s.y0) * ppm, bx = (s.x1 - minX) * ppm, by = (maxY - s.y1) * ppm;
191
+ // Each line at its extrusion width, so a surface's lines meet as they do on the part.
192
+ const radius = Math.max(0.5, s.width * ppm / 2), r2 = radius * radius, reach = Math.ceil(radius);
193
+ const steps = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / Math.max(0.5, radius / 2)));
194
+ for (let i = 0; i <= steps; i++) {
195
+ const cx = ax + (bx - ax) * i / steps, cy = ay + (by - ay) * i / steps;
196
+ for (let dy = -reach; dy <= reach; dy++) for (let dx = -reach; dx <= reach; dx++) {
197
+ if (dx * dx + dy * dy > r2) continue;
198
+ const px = Math.floor(cx + dx), py = Math.floor(cy + dy);
199
+ if (px < 0 || py < 0 || px >= width || py >= height) continue;
200
+ const k = py * width + px;
201
+ if (top ? s.z >= depth[k] : s.z <= depth[k]) { depth[k] = s.z; toolAt[k] = s.tool; }
202
+ }
203
+ }
204
+ }
205
+ const rgb = new Uint8Array(width * height * 3);
206
+ const zRange = Math.max(1e-6, maxZ - minZ);
207
+ for (let py = 0; py < height; py++) for (let px = 0; px < width; px++) {
208
+ // The bed side is the part turned over top to bottom, so its text reads as it will on the part.
209
+ const sy = top ? py : height - 1 - py;
210
+ const k = sy * width + px, o = (py * width + px) * 3, t = toolAt[k];
211
+ if (t < 0) { rgb[o] = BACKGROUND[0]; rgb[o + 1] = BACKGROUND[1]; rgb[o + 2] = BACKGROUND[2]; continue; }
212
+ const [r, g, b] = palette(t);
213
+ // Height shading, toward white so it shows on dark filament too: on the top view the highest
214
+ // lines (raised tabs, top surfaces) are lightest; on the bed side the face on the bed is.
215
+ const h = (depth[k] - minZ) / zRange, lift = 0.4 * (top ? h : 1 - h);
216
+ rgb[o] = Math.round(r + (255 - r) * lift);
217
+ rgb[o + 1] = Math.round(g + (255 - g) * lift);
218
+ rgb[o + 2] = Math.round(b + (255 - b) * lift);
219
+ }
220
+ return encodePng(width, height, rgb).toString("base64");
221
+ };
222
+ const top = draw(true), bed = draw(false);
223
+ return {
224
+ views: [
225
+ { name: "top", label: "Top, as it sits on the bed", png_base64: top, width, height },
226
+ { name: "bed_side", label: "Bed side, turned over toward you", png_base64: bed, width, height },
227
+ ],
228
+ mm_per_pixel: Math.round(1e6 / ppm) / 1e6,
229
+ extent_mm: [minX, minY, maxX, maxY].map(v => Math.round(v * 100) / 100) as [number, number, number, number],
230
+ layers,
231
+ filaments_used: [...used].sort((a, b) => a - b),
232
+ };
233
+ }
234
+
235
+ /** The preview of one plate of a sliced .3mf or a .gcode file, or undefined when it has no extruding moves. */
236
+ export async function previewPrintFile(source: { gcode: string; projectColours?: unknown[] }): Promise<PrintPreview | undefined> {
237
+ let colours = source.projectColours;
238
+ if (!colours?.length) {
239
+ // A bare .gcode file carries its colours in its header: "; filament_colour = #000000;#FFFFFF".
240
+ const header = /^\s*;\s*filament_colou?r\s*[=:]\s*(.+)$/im.exec(source.gcode);
241
+ colours = header ? header[1].split(/[;,]/).map(v => v.trim()) : [];
242
+ }
243
+ return renderPrintPreview(source.gcode, colours);
244
+ }
@@ -2,8 +2,10 @@
2
2
  * slice_stl's `quality` and `strength` (PRD §8.4): a client's print-sheet choice, mapped here to the
3
3
  * slicer's own numbers so no client carries layer heights, wall counts or infill. Draft and Fine set
4
4
  * the layer height for the nozzle in use (0.28 and 0.12 mm on a 0.4 mm nozzle, scaled with it); Strong
5
- * and Max set walls and infill. Standard sends nothing: the resolved preset decides. An explicit
6
- * layer_height, wall_loops or sparse_infill_density in the same call wins over these.
5
+ * and Max raise walls and infill to at least their values: a process that already has more (a
6
+ * designer's 3MF at 100% infill) keeps it, so a stronger choice never prints weaker. Standard sends
7
+ * nothing: the resolved process decides. An explicit layer_height, wall_loops or
8
+ * sparse_infill_density in the same call wins over these and is written as given.
7
9
  */
8
10
  export const PRINT_QUALITIES = ["draft", "standard", "fine"] as const;
9
11
  export const PRINT_STRENGTHS = ["standard", "strong", "max"] as const;
@@ -36,8 +38,8 @@ export function withPrintQuality(args: Record<string, unknown>, nozzleDiameter?:
36
38
  if (layer !== undefined && out.layer_height === undefined) out.layer_height = Math.round(layer * scale * 100) / 100;
37
39
  const walls = STRENGTH[strength as PrintStrength];
38
40
  if (walls) {
39
- if (out.wall_loops === undefined) out.wall_loops = walls.wall_loops;
40
- if (out.sparse_infill_density === undefined) out.sparse_infill_density = walls.sparse_infill_density;
41
+ if (out.wall_loops === undefined) out.wall_loops_floor = walls.wall_loops;
42
+ if (out.sparse_infill_density === undefined) out.sparse_infill_density_floor = walls.sparse_infill_density;
41
43
  }
42
44
  return out;
43
45
  }
@@ -50,6 +52,6 @@ export const PRINT_QUALITY_PROPERTIES = {
50
52
  },
51
53
  strength: {
52
54
  type: "string", enum: [...PRINT_STRENGTHS],
53
- description: "Part strength: standard (the preset's walls and infill), strong or max (more walls and denser infill). The server picks the values; explicit wall_loops or sparse_infill_density win.",
55
+ description: "Part strength: standard (the process's own walls and infill), strong or max (at least more walls and denser infill; a process that already has more keeps it). The server picks the values; explicit wall_loops or sparse_infill_density win.",
54
56
  },
55
57
  } as const;
@@ -6,7 +6,10 @@
6
6
  */
7
7
  export const PROCESS_OVERRIDE_KEYS = ["layer_height", "wall_loops", "sparse_infill_density", "enable_support", "support_type", "support_threshold_angle"] as const;
8
8
 
9
- export type ProcessOverrides = Partial<Record<(typeof PROCESS_OVERRIDE_KEYS)[number], string>>;
9
+ /** Minimums from a strength choice: the resolved process keeps its own value when it is already higher. */
10
+ export const PROCESS_FLOOR_KEYS = ["wall_loops_floor", "sparse_infill_density_floor"] as const;
11
+
12
+ export type ProcessOverrides = Partial<Record<(typeof PROCESS_OVERRIDE_KEYS)[number] | (typeof PROCESS_FLOOR_KEYS)[number], string>>;
10
13
 
11
14
  /** Bambu Studio's and OrcaSlicer's support_type values. */
12
15
  export const SUPPORT_TYPES = ["normal(auto)", "tree(auto)", "normal(manual)", "tree(manual)"] as const;
@@ -36,6 +39,9 @@ export function parseProcessOverrides(args: Record<string, unknown> | undefined,
36
39
  if (!match || Number(match[1]) > 100) throw new Error('sparse_infill_density must be a percentage from 0% to 100%, such as "15%".');
37
40
  overrides.sparse_infill_density = `${Number(match[1])}%`;
38
41
  }
42
+ // Written by withPrintQuality for strong/max, never by a caller.
43
+ if (typeof args?.wall_loops_floor === "number") overrides.wall_loops_floor = String(args.wall_loops_floor);
44
+ if (typeof args?.sparse_infill_density_floor === "string") overrides.sparse_infill_density_floor = args.sparse_infill_density_floor;
39
45
  const enableSupport = args?.enable_support;
40
46
  if (enableSupport !== undefined) {
41
47
  if (typeof enableSupport !== "boolean") throw new Error("enable_support must be true or false.");
@@ -61,5 +67,13 @@ export function parseProcessOverrides(args: Record<string, unknown> | undefined,
61
67
 
62
68
  /** The process profile with the overrides written over its values. */
63
69
  export function applyProcessOverrides(profile: Record<string, unknown>, overrides: ProcessOverrides): Record<string, unknown> {
64
- return { ...profile, ...overrides };
70
+ const { wall_loops_floor: wallFloor, sparse_infill_density_floor: densityFloor, ...exact } = overrides;
71
+ const out: Record<string, unknown> = { ...profile };
72
+ const number = (value: unknown) => {
73
+ const parsed = Number.parseFloat(String(Array.isArray(value) ? value[0] : value ?? ""));
74
+ return Number.isFinite(parsed) ? parsed : undefined;
75
+ };
76
+ if (wallFloor !== undefined && (number(out.wall_loops) ?? -1) < Number(wallFloor)) out.wall_loops = wallFloor;
77
+ if (densityFloor !== undefined && (number(out.sparse_infill_density) ?? -1) < Number.parseFloat(densityFloor)) out.sparse_infill_density = densityFloor;
78
+ return { ...out, ...exact };
65
79
  }