bambu-printer-mcp 1.1.59 → 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/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";
@@ -23,6 +23,8 @@ import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3M
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,6 +707,33 @@ 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
  }
@@ -2640,6 +2669,7 @@ class BambuPrinterMCPServer {
2640
2669
  plate_index: { type: "integer", minimum: 0, description: "Zero-based selected plate; defaults to 0. Raw G-code only supports 0." },
2641
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." },
2642
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." },
2643
2673
  },
2644
2674
  required: ["file_path", "bambu_model"],
2645
2675
  },
@@ -3081,9 +3111,11 @@ class BambuPrinterMCPServer {
3081
3111
  let result;
3082
3112
  switch (name) {
3083
3113
  case "inspect_print_file": {
3084
- 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"]);
3085
3115
  if (!args || Object.keys(args).some(key => !allowed.has(key)))
3086
- 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.");
3087
3119
  if (typeof args.file_path !== "string" || !args.file_path.trim() || args.file_path.includes("\0"))
3088
3120
  throw new Error("file_path must name a local prepared artifact.");
3089
3121
  if (typeof args.bambu_model !== "string" || !args.bambu_model.trim())
@@ -3105,6 +3137,8 @@ class BambuPrinterMCPServer {
3105
3137
  if (extra.signal.aborted)
3106
3138
  throw new Error("File inspection cancelled.");
3107
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;
3108
3142
  return {
3109
3143
  receipt_version: "1",
3110
3144
  evidence: "file-only",
@@ -3112,6 +3146,7 @@ class BambuPrinterMCPServer {
3112
3146
  artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
3113
3147
  selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
3114
3148
  inspection,
3149
+ ...(preview ? { preview } : {}),
3115
3150
  };
3116
3151
  });
3117
3152
  break;
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.59",
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/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,
@@ -53,6 +53,8 @@ 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,6 +918,25 @@ 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
  }
@@ -3175,6 +3196,7 @@ class BambuPrinterMCPServer {
3175
3196
  plate_index: { type: "integer", minimum: 0, description: "Zero-based selected plate; defaults to 0. Raw G-code only supports 0." },
3176
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." },
3177
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." },
3178
3200
  },
3179
3201
  required: ["file_path", "bambu_model"],
3180
3202
  },
@@ -3626,8 +3648,9 @@ class BambuPrinterMCPServer {
3626
3648
 
3627
3649
  switch (name) {
3628
3650
  case "inspect_print_file": {
3629
- const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type"]);
3630
- 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.");
3631
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.");
3632
3655
  if (typeof args.bambu_model !== "string" || !args.bambu_model.trim()) throw new Error("An explicit bambu_model is required for file inspection.");
3633
3656
  const model = validateBambuModel(args.bambu_model);
@@ -3642,6 +3665,8 @@ class BambuPrinterMCPServer {
3642
3665
  const inspection = await inspectPrintFile(snapshot, { model, nozzleDiameters: nozzles, plateIndex, bedType });
3643
3666
  if (extra.signal.aborted) throw new Error("File inspection cancelled.");
3644
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;
3645
3670
  return {
3646
3671
  receipt_version: "1",
3647
3672
  evidence: "file-only",
@@ -3649,6 +3674,7 @@ class BambuPrinterMCPServer {
3649
3674
  artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
3650
3675
  selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
3651
3676
  inspection,
3677
+ ...(preview ? { preview } : {}),
3652
3678
  };
3653
3679
  });
3654
3680
  break;
@@ -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
+ }