bambu-printer-mcp 1.1.71 → 1.1.73

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.
@@ -4,11 +4,13 @@
4
4
  * (M400 U1 on Bambu printers) before the chosen layer, so the printer pauses
5
5
  * by itself there and waits for Resume; no remote command is involved.
6
6
  *
7
- * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). It
8
- * does not apply the pauses a project 3MF already carries in
9
- * Metadata/custom_gcode_per_print_z.xml, so those are read here and passed the
10
- * same way. A pause's print_z must be the exact top of its layer: a height
11
- * between layers lands on the layer below.
7
+ * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). A
8
+ * project 3MF keeps its own pauses and colour changes in
9
+ * Metadata/custom_gcode_per_layer.xml (Bambu Studio 02.08.02.61 bbs_3mf.cpp:184,
10
+ * written at :8943-8990), which the CLI loads with the project. The JSON
11
+ * replaces that whole map (BambuStudio.cpp:4005-4008), so the plate's own
12
+ * entries are read here and merged in. A pause's print_z must be the exact top
13
+ * of its layer: a height between layers lands on the layer below.
12
14
  */
13
15
  /** CustomGCode::Type, in the order bbs_3mf.cpp writes it as an integer. */
14
16
  declare const CUSTOM_GCODE_TYPES: readonly ["ColorChange", "PausePrint", "ToolChange", "Template", "Custom", "Unknown"];
@@ -6,11 +6,13 @@ import JSZip from "jszip";
6
6
  * (M400 U1 on Bambu printers) before the chosen layer, so the printer pauses
7
7
  * by itself there and waits for Resume; no remote command is involved.
8
8
  *
9
- * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). It
10
- * does not apply the pauses a project 3MF already carries in
11
- * Metadata/custom_gcode_per_print_z.xml, so those are read here and passed the
12
- * same way. A pause's print_z must be the exact top of its layer: a height
13
- * between layers lands on the layer below.
9
+ * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). A
10
+ * project 3MF keeps its own pauses and colour changes in
11
+ * Metadata/custom_gcode_per_layer.xml (Bambu Studio 02.08.02.61 bbs_3mf.cpp:184,
12
+ * written at :8943-8990), which the CLI loads with the project. The JSON
13
+ * replaces that whole map (BambuStudio.cpp:4005-4008), so the plate's own
14
+ * entries are read here and merged in. A pause's print_z must be the exact top
15
+ * of its layer: a height between layers lands on the layer below.
14
16
  */
15
17
  /** CustomGCode::Type, in the order bbs_3mf.cpp writes it as an integer. */
16
18
  const CUSTOM_GCODE_TYPES = ["ColorChange", "PausePrint", "ToolChange", "Template", "Custom", "Unknown"];
@@ -44,7 +46,7 @@ export async function readProjectCustomGcodes(threeMfPath, plate = 1) {
44
46
  catch {
45
47
  return undefined;
46
48
  }
47
- const file = zip.file(/^Metadata\/custom_gcode_per_print_z\.xml$/i)[0];
49
+ const file = zip.file(/^Metadata\/custom_gcode_per_layer\.xml$/i)[0];
48
50
  if (!file)
49
51
  return undefined;
50
52
  const xml = await file.async("string");
@@ -11,8 +11,10 @@ import { EventEmitter } from 'events';
11
11
  import * as crypto from 'crypto';
12
12
  import { execFile } from 'child_process';
13
13
  import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
14
+ import { listModelPlates } from '../counterpart/model-plates.js';
14
15
  import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
15
16
  import { plainSlicerError, UNKNOWN_SLICER_ERROR } from '../slicer/slicer-messages.js';
17
+ import { bambuCliExitCode } from '../slicer/cli-exit-codes.js';
16
18
  import { applyProcessOverrides } from '../slicer/process-overrides.js';
17
19
  import { profileJsonFiles } from '../slicer/profile-files.js';
18
20
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
@@ -25,11 +27,13 @@ const BAMBU_PROFILE_ROOTS = [
25
27
  '/Applications/BambuStudio.app/Contents/Resources/profiles/BBL',
26
28
  '/Applications/OrcaSlicer.app/Contents/Resources/profiles/BBL',
27
29
  ];
30
+ // curr_bed_type's enum keys (Bambu Studio 02.08.02.61 libslic3r/PrintConfig.cpp:437-445).
28
31
  const BAMBU_CLI_BED_TYPES = {
29
32
  textured_plate: 'Textured PEI Plate',
30
33
  cool_plate: 'Cool Plate',
31
34
  engineering_plate: 'Engineering Plate',
32
35
  hot_plate: 'High Temp Plate',
36
+ supertack_plate: 'Supertack Plate',
33
37
  };
34
38
  export const SLICER_TYPES = [
35
39
  'bambustudio',
@@ -171,29 +175,6 @@ function describeSlicerFailure(error, stdout, stderr, cli) {
171
175
  const output = stderr.trim() ? "" : stdout.trim().split("\n").slice(-20).join("\n");
172
176
  return `Slicer failed: the slicer ${status}${reason ? ` (${reason})` : ""}. ${error.message.trim()}${output ? `\nSlicer output: ${output}` : ""}`;
173
177
  }
174
- // Bambu Studio and OrcaSlicer CLI errors (libslic3r/Utils.hpp). The process
175
- // exits with the low byte of the code; result.json names the error.
176
- const BAMBU_CLI_ERRORS = {
177
- [-2]: "invalid parameters to the slicer",
178
- [-3]: "input files not found",
179
- [-5]: "preset file cannot be parsed",
180
- [-6]: "model file cannot be parsed",
181
- [-9]: "copying objects failed",
182
- [-17]: "printer is not compatible with the process preset",
183
- [-21]: "auto-arranging objects failed",
184
- [-22]: "auto-orienting objects failed",
185
- [-50]: "a plate is empty or has no object fully inside it; arrange the model or place it on the plate",
186
- [-51]: "incorrect slicing parameters",
187
- [-52]: "objects extend over the bed boundary",
188
- [-60]: "no printable objects remain after skipping",
189
- [-61]: "filaments are not compatible with the plate type",
190
- [-62]: "the filaments' temperatures differ too much",
191
- [-63]: "objects collide in print-by-object mode",
192
- [-64]: "objects collide",
193
- [-100]: "slicing the model failed",
194
- [-101]: "G-code conflicts after slicing",
195
- [-102]: "G-code in an unprintable area",
196
- };
197
178
  function bambuCliFailureReason(exitCode, cli) {
198
179
  const result = readCliResult(cli);
199
180
  if (typeof result?.error_string === "string" && result.error_string.trim()) {
@@ -201,8 +182,8 @@ function bambuCliFailureReason(exitCode, cli) {
201
182
  }
202
183
  if (typeof exitCode !== "number")
203
184
  return undefined;
204
- const code = Object.keys(BAMBU_CLI_ERRORS).map(Number).find(value => (value & 0xff) === exitCode);
205
- return code === undefined ? undefined : `${BAMBU_CLI_ERRORS[code]} [${code}]`;
185
+ const known = bambuCliExitCode(exitCode);
186
+ return known ? `${known.sentence} [${known.code}]` : undefined;
206
187
  }
207
188
  export class STLManipulator extends EventEmitter {
208
189
  constructor(tempDir = path.join(process.cwd(), 'temp')) {
@@ -623,9 +604,6 @@ export class STLManipulator extends EventEmitter {
623
604
  if (!bedType)
624
605
  return undefined;
625
606
  const normalized = bedType.trim().toLowerCase();
626
- if (normalized === 'supertack_plate') {
627
- throw new Error('BambuStudio CLI SuperTack bed type is not verified; use a pre-sliced 3MF or choose textured_plate, cool_plate, engineering_plate, or hot_plate.');
628
- }
629
607
  return BAMBU_CLI_BED_TYPES[normalized] || bedType;
630
608
  }
631
609
  /**
@@ -1381,37 +1359,41 @@ export class STLManipulator extends EventEmitter {
1381
1359
  const once = (options) => this.sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, options);
1382
1360
  const layers = bambuOptions?.pauseAtLayers?.length ? bambuOptions.pauseAtLayers : undefined;
1383
1361
  const cli = slicerType === 'bambustudio' || slicerType === 'orcaslicer' || slicerType === 'orcaslicer-bambulab';
1384
- const plate = bambuOptions?.slicePlate && bambuOptions.slicePlate > 0 ? bambuOptions.slicePlate : 1;
1385
- // The CLI drops a project's own pauses and colour changes; carry them over.
1386
- const project = cli && /\.3mf$/i.test(stlFilePath) ? await readProjectCustomGcodes(stlFilePath, plate) : undefined;
1387
- if (!layers && !project?.gcodes.length)
1362
+ // Without new pauses the CLI keeps the project's own pauses and colour changes itself: it loads a
1363
+ // Bambu 3MF's Metadata/custom_gcode_per_layer.xml with the project (Bambu Studio 02.08.02.61
1364
+ // BambuStudio.cpp:1882, bbs_3mf.cpp:2051), so nothing is passed.
1365
+ if (!layers)
1388
1366
  return once(bambuOptions);
1389
- if (layers && !cli) {
1367
+ if (!cli) {
1390
1368
  throw new Error(`Pausing at a layer needs the Bambu Studio or OrcaSlicer CLI, not ${slicerType}.`);
1391
1369
  }
1370
+ const chosenPlate = bambuOptions?.slicePlate && bambuOptions.slicePlate > 0 ? bambuOptions.slicePlate : undefined;
1371
+ const plate = chosenPlate ?? 1;
1372
+ const threeMf = /\.3mf$/i.test(stlFilePath);
1373
+ // --load-custom-gcodes replaces the whole per-plate map and holds one plate (--slice N, or plate 1 for
1374
+ // --slice 0: BambuStudio.cpp:2224-2233, 4005-4008), so slicing every plate would drop plates 2..n's own.
1375
+ if (threeMf && chosenPlate === undefined && (await listModelPlates(stlFilePath)).plate_count > 1) {
1376
+ throw new Error('Pausing at a layer works on one plate at a time. Choose the plate with slice_plate.');
1377
+ }
1378
+ // The map replaces the project's own entries for this plate, so they are merged in.
1379
+ const project = threeMf ? await readProjectCustomGcodes(stlFilePath, plate) : undefined;
1392
1380
  const customGcodesFile = path.join(this.tempDir, `custom-gcodes-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
1393
1381
  try {
1394
- let tops = [];
1395
- if (layers) {
1396
- // A pause sits at its layer's exact top Z; learn the tops from a slice without pauses.
1397
- if (progressCallback)
1398
- progressCallback(10, `Finding layer heights for the pause before layer ${layers.join(", ")}`);
1399
- const plain = await once({ ...bambuOptions, pauseAtLayers: undefined, customGcodesFile: undefined });
1400
- const gcode = await readPlateGcode(plain.path, plate);
1401
- if (!gcode)
1402
- throw new Error('The slicer wrote no plate G-code, so the pause layers cannot be placed.');
1403
- tops = layerTops(gcode);
1404
- }
1405
- const info = layers ? customGcodesWithPauses(tops, layers, project) : project;
1406
- await fs.promises.writeFile(customGcodesFile, JSON.stringify(info));
1382
+ // A pause sits at its layer's exact top Z; learn the tops from a slice without pauses.
1383
+ if (progressCallback)
1384
+ progressCallback(10, `Finding layer heights for the pause before layer ${layers.join(", ")}`);
1385
+ const plain = await once({ ...bambuOptions, pauseAtLayers: undefined, customGcodesFile: undefined });
1386
+ const plainGcode = await readPlateGcode(plain.path, plate);
1387
+ if (!plainGcode)
1388
+ throw new Error('The slicer wrote no plate G-code, so the pause layers cannot be placed.');
1389
+ const tops = layerTops(plainGcode);
1390
+ await fs.promises.writeFile(customGcodesFile, JSON.stringify(customGcodesWithPauses(tops, layers, project)));
1407
1391
  const result = await once({ ...bambuOptions, customGcodesFile });
1408
- if (layers) {
1409
- const gcode = await readPlateGcode(result.path, plate);
1410
- const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
1411
- const missing = layers.filter(layer => !placed.includes(layer));
1412
- if (!gcode || missing.length || layerTops(gcode).length !== tops.length) {
1413
- throw new Error(`The slicer did not place the pause before layer ${(missing.length ? missing : layers).join(", ")}. Nothing was sent to the printer.`);
1414
- }
1392
+ const gcode = await readPlateGcode(result.path, plate);
1393
+ const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
1394
+ const missing = layers.filter(layer => !placed.includes(layer));
1395
+ if (!gcode || missing.length || layerTops(gcode).length !== tops.length) {
1396
+ throw new Error(`The slicer did not place the pause before layer ${(missing.length ? missing : layers).join(", ")}. Nothing was sent to the printer.`);
1415
1397
  }
1416
1398
  return result;
1417
1399
  }
package/dist/types.d.ts CHANGED
@@ -81,12 +81,18 @@ export interface ThreeMFAmsRequirements {
81
81
  filaments: ThreeMFFilamentRequirement[];
82
82
  }
83
83
  export interface ThreeMFPlateObject {
84
+ /** The instance's identify_id: the id the printer's skip_objects command takes. */
84
85
  id: number;
85
86
  name: string;
87
+ /** Already skipped in this file (slice_info's skipped="true"). */
88
+ skipped: boolean;
89
+ /** First-layer area and box from plate_N.json, only when the name is unique on the plate. */
86
90
  area: number | null;
87
91
  bbox: unknown;
88
92
  }
89
93
  export interface ThreeMFPlateObjects {
90
94
  plateIndex: number;
95
+ /** The plate was sliced with object labels, which the printer needs to skip objects. */
96
+ labelObjectEnabled: boolean;
91
97
  objects: ThreeMFPlateObject[];
92
98
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.71",
3
+ "version": "1.1.73",
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
@@ -499,73 +499,67 @@ export async function analyze3MFAmsRequirements(
499
499
  };
500
500
  }
501
501
 
502
+ /**
503
+ * The objects of one sliced plate that the printer can skip, as Bambu Studio lists them in its skip dialog
504
+ * (02.08.02.61 slic3r/GUI/PartSkipDialog.cpp:734-741, SkipPartCanvas.cpp:690-730): one entry per instance
505
+ * from Metadata/slice_info.config's plate whose `index` matches (written per instance at bbs_3mf.cpp:8718-8750),
506
+ * with its identify_id. plate_N.json's bbox_objects are not paired by position: their `id` is an internal
507
+ * object id the printer doesn't know (BambuStudio.cpp:7374-7382), and copies share a name. The wipe tower
508
+ * is never a slice_info object.
509
+ */
502
510
  export async function analyze3MFPlateObjects(
503
511
  filePath: string,
504
512
  plateIndex: number = 0
505
513
  ): Promise<ThreeMFPlateObjects> {
506
514
  const data = await fs.readFile(filePath);
507
515
  const zip = await JSZip.loadAsync(data);
508
- const plateName = `Metadata/plate_${plateIndex + 1}.json`;
509
- const plateFile = zip.file(plateName);
510
-
511
- if (!plateFile) {
512
- throw new Error(`3MF is missing ${plateName}; cannot list plate objects.`);
513
- }
514
-
515
- const plateJson = JSON.parse(await plateFile.async('string'));
516
- const bboxObjects = Array.isArray(plateJson?.bbox_objects) ? plateJson.bbox_objects : [];
517
- const sliceInfoObjects: Array<{ id: number; name: string | null }> = [];
516
+ const plateNumber = plateIndex + 1;
518
517
  const sliceInfo = zip.file('Metadata/slice_info.config');
518
+ if (!sliceInfo) {
519
+ throw new Error('This 3MF has no Metadata/slice_info.config, so it was not sliced by Bambu Studio or OrcaSlicer and has no skip-object ids. Slice it first.');
520
+ }
521
+ const parsed = await parseStringPromise(await sliceInfo.async('string'), { explicitArray: true });
522
+ const plates: any[] = parsed?.config?.plate ?? [];
523
+ const selected = plates.find(plate => (plate?.metadata ?? [])
524
+ .some((item: any) => item?.$?.key === 'index' && Number(item?.$?.value) === plateNumber));
525
+ if (!selected) {
526
+ throw new Error(`Plate ${plateNumber} was not sliced in this 3MF, so it has no skip-object ids.`);
527
+ }
528
+ const labelObjectEnabled = (selected.metadata ?? [])
529
+ .some((item: any) => item?.$?.key === 'label_object_enabled' && item?.$?.value === 'true');
530
+ const instances = (selected.object ?? []).flatMap((object: any) => {
531
+ const id = Number(object?.$?.identify_id);
532
+ if (!Number.isSafeInteger(id) || id <= 0) return [];
533
+ return [{ id, name: typeof object.$.name === 'string' ? object.$.name : `object_${id}`, skipped: object.$.skipped === 'true' }];
534
+ });
519
535
 
520
- if (sliceInfo) {
536
+ // First-layer area and box, attached by name only where one instance and one box carry it.
537
+ const boxes = new Map<string, any[]>();
538
+ const plateFile = zip.file(`Metadata/plate_${plateNumber}.json`);
539
+ if (plateFile) {
521
540
  try {
522
- const parsed = await parseStringPromise(await sliceInfo.async('string'), {
523
- explicitArray: false,
524
- mergeAttrs: true,
525
- });
526
- const plateNodes = parsed?.config?.plate
527
- ? Array.isArray(parsed.config.plate) ? parsed.config.plate : [parsed.config.plate]
528
- : [];
529
- const plateNumber = plateIndex + 1;
530
- const selectedPlate =
531
- plateNodes.find((plate: any) => {
532
- const metadata = Array.isArray(plate?.metadata)
533
- ? plate.metadata
534
- : plate?.metadata
535
- ? [plate.metadata]
536
- : [];
537
- return metadata.some((item: any) => item?.key === 'index' && Number(item?.value) === plateNumber);
538
- }) || plateNodes[plateIndex] || plateNodes[0];
539
- const objectNodes = selectedPlate?.object
540
- ? Array.isArray(selectedPlate.object) ? selectedPlate.object : [selectedPlate.object]
541
- : [];
542
- for (const object of objectNodes) {
543
- const id = Number.parseInt(String(object?.identify_id ?? ''), 10);
544
- if (!Number.isInteger(id)) continue;
545
- sliceInfoObjects.push({
546
- id,
547
- name: typeof object?.name === 'string' ? object.name : null,
548
- });
541
+ const plateJson = JSON.parse(await plateFile.async('string'));
542
+ for (const box of Array.isArray(plateJson?.bbox_objects) ? plateJson.bbox_objects : []) {
543
+ if (typeof box?.name !== 'string' || box.name === 'wipe_tower') continue;
544
+ boxes.set(box.name, [...(boxes.get(box.name) ?? []), box]);
549
545
  }
550
546
  } catch {
551
- // Fall back to bbox IDs for older or malformed 3MFs.
547
+ // The ids above still stand without the boxes.
552
548
  }
553
549
  }
550
+ const nameCount = new Map<string, number>();
551
+ for (const instance of instances) nameCount.set(instance.name, (nameCount.get(instance.name) ?? 0) + 1);
554
552
 
555
553
  return {
556
554
  plateIndex,
557
- objects: bboxObjects
558
- .map((object: any, index: number) => {
559
- const sliceObject = sliceInfoObjects[index];
560
- const id = sliceObject?.id ?? Number(object?.id);
561
- if (!Number.isInteger(id)) return null;
562
- return {
563
- id,
564
- name: sliceObject?.name || (typeof object?.name === 'string' ? object.name : `object_${id}`),
565
- area: Number.isFinite(Number(object?.area)) ? Number(object.area) : null,
566
- bbox: object?.bbox ?? null,
567
- };
568
- })
569
- .filter((object: unknown): object is NonNullable<typeof object> => object !== null),
555
+ labelObjectEnabled,
556
+ objects: instances.map((instance: { id: number; name: string; skipped: boolean }) => {
557
+ const box = nameCount.get(instance.name) === 1 && boxes.get(instance.name)?.length === 1 ? boxes.get(instance.name)![0] : undefined;
558
+ return {
559
+ ...instance,
560
+ area: box && Number.isFinite(Number(box.area)) ? Number(box.area) : null,
561
+ bbox: box?.bbox ?? null,
562
+ };
563
+ }),
570
564
  };
571
565
  }
@@ -75,7 +75,9 @@ export function bridgeAmsMapping2Entry(value: number, dualNozzle = false): { ams
75
75
  if (value < 0) return { ams_id: 255, slot_id: 255 };
76
76
  if (value === 255) return dualNozzle ? { ams_id: 255, slot_id: 0 } : { ams_id: 255, slot_id: 255 };
77
77
  if (value === 254) return { ams_id: 254, slot_id: dualNozzle ? 0 : 254 };
78
- if (value >= 128) return { ams_id: 128, slot_id: value - 128 };
78
+ // An AMS-HT has one slot; its absolute tray index is its own unit id (Bambu Studio 02.08.02.61
79
+ // DevFilaSystem.cpp:367-368), sent as that unit's ams_id with slot 0 (SelectMachine.cpp:1489-1497).
80
+ if (value >= 128) return { ams_id: value, slot_id: 0 };
79
81
  return { ams_id: Math.floor(value / 4), slot_id: value % 4 };
80
82
  }
81
83
 
@@ -130,3 +132,13 @@ export function studioAmsMappingInfo(filaments: ProjectFilament[], mapping: numb
130
132
  };
131
133
  });
132
134
  }
135
+
136
+ /**
137
+ * A project-level ams_mapping as Bambu Studio sends it: the caller's tray for each filament the selected plate prints,
138
+ * -1 for every project filament it doesn't (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500,
139
+ * maps only the plate's own filaments). A tray for an unused filament is never sent to the printer.
140
+ */
141
+ export function studioAmsMapping(mapping: number[], usedPositions: number[]): number[] {
142
+ const used = new Set(usedPositions);
143
+ return mapping.map((tray, position) => used.has(position) ? tray : -1);
144
+ }
@@ -8,14 +8,27 @@
8
8
  * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
9
  */
10
10
  import { readSafe3mfArchive } from "../safety/archive.js";
11
+ import { plateFilaments, type PlateFilament, type PlateLayout } from "./plate-filaments.js";
11
12
 
12
13
  export interface ModelPlate {
13
14
  /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
14
15
  index: number;
15
16
  name: string;
16
17
  objects: string[];
18
+ /**
19
+ * Each object copy on the plate with its identify_id, from model_settings.config's <model_instance> entries
20
+ * (Bambu Studio 02.08.02.61 bbs_3mf.cpp:8448-8482). These are the ids slice_stl's skip_objects takes: the
21
+ * CLI matches them against each instance's loaded id (BambuStudio.cpp:1785-1789, 6530-6545).
22
+ */
23
+ instances: { identify_id: number; name: string }[];
17
24
  /** The file already holds this plate's G-code. */
18
25
  sliced: boolean;
26
+ /**
27
+ * The project filaments this plate prints with, and only those (counterpart/1): what a client asks the person to
28
+ * choose spools for. From the slice when the file holds one (plate_N.json filament_ids), otherwise worked out as
29
+ * Bambu Studio does for the objects on this plate (see plate-filaments.ts). Filaments of other plates never appear.
30
+ */
31
+ filaments: PlateFilament[];
19
32
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
20
33
  thumbnail_png_base64?: string;
21
34
  }
@@ -25,12 +38,18 @@ export interface ModelPlates {
25
38
  title?: string;
26
39
  designer?: string;
27
40
  licence?: string;
41
+ /**
42
+ * Every filament the project declares (project_settings.config), used on a plate or not, from 1: slice_stl takes one
43
+ * load_filaments profile per declared filament. Empty for a 3MF that declares none.
44
+ */
45
+ project_filaments: PlateFilament[];
28
46
  }
29
47
 
30
48
  /** For the settings and plate files; the model file can be large and is only scanned. */
31
49
  const MAX_METADATA_BYTES = 8 * 1024 * 1024;
32
50
  const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
33
51
  const MAX_PLATES = 1000;
52
+ const MAX_INSTANCES_PER_PLATE = 1000;
34
53
 
35
54
  const words = (value: string) => value
36
55
  .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]!))
@@ -51,7 +70,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
51
70
  if (!/<(?:\w+:)?model\b/.test(head)) throw new Error("That file is not a 3MF model.");
52
71
  // An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
53
72
  const has = (tag: string) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
54
- const result: ModelPlates = { plate_count: 0, plates: [] };
73
+ const result: ModelPlates = { plate_count: 0, plates: [], project_filaments: [] };
55
74
  const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
56
75
  if (metadata.get("Title")) result.title = metadata.get("Title");
57
76
  if (metadata.get("Designer")) result.designer = metadata.get("Designer");
@@ -63,6 +82,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
63
82
  return [match[1], words(name?.[1] ?? "")];
64
83
  }));
65
84
  const plates = new Map<number, ModelPlate>();
85
+ const layouts = new Map<number, PlateLayout>();
66
86
  // A plate number out of range is skipped, as a slicer would not show it.
67
87
  const valid = (number: number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
68
88
  for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
@@ -71,7 +91,19 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
71
91
  const number = Number(id[1]);
72
92
  if (!valid(number)) continue;
73
93
  const name = /<metadata\s+key="plater_name"\s+value="([^"]*)"/.exec(match[1]);
74
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false,
94
+ const instances = [...match[1].matchAll(/<model_instance>([\s\S]*?)<\/model_instance>/g)].flatMap(instance => {
95
+ const object = /<metadata\s+key="object_id"\s+value="(\d+)"/.exec(instance[1])?.[1];
96
+ const identify = Number(/<metadata\s+key="identify_id"\s+value="(\d+)"/.exec(instance[1])?.[1]);
97
+ return object !== undefined && Number.isSafeInteger(identify) && identify > 0
98
+ ? [{ identify_id: identify, name: objects.get(object) ?? "" }] : [];
99
+ }).slice(0, MAX_INSTANCES_PER_PLATE);
100
+ layouts.set(number, { number, objectIds: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].map(item => item[1]),
101
+ instances: [...match[1].matchAll(/<model_instance>([\s\S]*?)<\/model_instance>/g)].flatMap(instance => {
102
+ const objectId = /<metadata\s+key="object_id"\s+value="(\d+)"/.exec(instance[1])?.[1];
103
+ const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
104
+ return objectId ? [{ objectId, instanceId }] : [];
105
+ }) });
106
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [],
75
107
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
76
108
  }
77
109
  for (const name of Object.keys(zip.files)) {
@@ -79,11 +111,15 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
79
111
  if (!match) continue;
80
112
  const number = Number(match[1]);
81
113
  if (!valid(number)) continue;
82
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], sliced: false };
114
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [] };
115
+ const layout = layouts.get(number) ?? { number, objectIds: [] };
116
+ layouts.set(number, layout);
83
117
  if (match[2] === "gcode") plate.sliced = true;
84
118
  else {
85
119
  try {
86
- const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[] };
120
+ const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[]; filament_ids?: unknown };
121
+ // Studio's record of the filaments this plate's slice uses (0-based project positions).
122
+ if (Array.isArray(value.filament_ids)) layout.slicedFilamentIds = value.filament_ids.filter((id): id is number => Number.isInteger(id) && id >= 0 && id < 64);
87
123
  if (Array.isArray(value.bbox_objects)) plate.objects = value.bbox_objects
88
124
  .flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
89
125
  } catch { /* the plate keeps the objects model_settings lists */ }
@@ -92,13 +128,25 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
92
128
  }
93
129
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
94
130
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
95
- if (!result.plates.length) result.plates.push({ index: 0, name: "Plate 1", objects: [], sliced: false });
131
+ if (!result.plates.length) {
132
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [] });
133
+ // Without plates every object is on the one plate.
134
+ layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
135
+ }
96
136
  const geometry = has("item") && (has("mesh") || has("component"));
97
137
  if (!geometry) {
98
138
  // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
99
139
  result.plates = result.plates.filter(plate => plate.sliced);
100
140
  if (!result.plates.length) throw new Error("This 3MF has previews and settings but no model or printable plate.");
101
141
  }
142
+ // A slice's G-code without its plate_N.json gives no filament list: the derivation stands.
143
+ // A model file too large to read whole: its resources come first and its build items last (a plain 3MF).
144
+ const modelText = !modelBytes ? "" : modelBytes.length <= 64 * 1024 * 1024 ? modelBytes.toString("utf8")
145
+ : `${head}${modelBytes.subarray(-1024 * 1024).toString("utf8")}`;
146
+ const filaments = await plateFilaments(zip, settings, modelText,
147
+ result.plates.map(plate => layouts.get(plate.index + 1) ?? { number: plate.index + 1, objectIds: [] }));
148
+ for (const plate of result.plates) plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
149
+ result.project_filaments = filaments.project;
102
150
  if (options.thumbnails) for (const plate of result.plates) {
103
151
  const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
104
152
  if (!file) continue;