any2orca 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -2
  3. package/dist/archive/lookupFilamentColorName.js +15 -4
  4. package/dist/archive/objectWorldBboxXY.js +80 -58
  5. package/dist/archive/parseObjectMetadata.js +33 -9
  6. package/dist/archive/recenterAssembleItems.js +9 -1
  7. package/dist/archive/recenterBuildItems.js +9 -1
  8. package/dist/archive/xmlBlocks.d.ts +52 -3
  9. package/dist/archive/xmlBlocks.js +106 -4
  10. package/dist/cli/config.js +32 -2
  11. package/dist/cli/watchState.js +22 -1
  12. package/dist/engine/buildFilamentConfigs.js +8 -5
  13. package/dist/errors.d.ts +1 -1
  14. package/dist/inspect.d.ts +8 -1
  15. package/dist/inspect.js +4 -1
  16. package/dist/node.js +7 -1
  17. package/dist/profiles.d.ts +39 -0
  18. package/dist/profiles.js +63 -0
  19. package/dist/project.js +10 -1
  20. package/dist/sources/prusa/beds.d.ts +33 -0
  21. package/dist/sources/prusa/beds.js +66 -0
  22. package/dist/sources/prusa/bundle.d.ts +53 -0
  23. package/dist/sources/prusa/bundle.js +106 -0
  24. package/dist/sources/prusa/convertSettings.d.ts +2 -0
  25. package/dist/sources/prusa/convertSettings.js +62 -2
  26. package/dist/sources/prusa/keyMap.js +5 -2
  27. package/dist/sources/prusa/modelConfig.d.ts +5 -1
  28. package/dist/sources/prusa/modelConfig.js +27 -10
  29. package/dist/sources/prusa/policyB.d.ts +56 -0
  30. package/dist/sources/prusa/policyB.js +161 -0
  31. package/dist/sources/prusa/prusa.d.ts +1 -1
  32. package/dist/sources/prusa/prusa.js +102 -36
  33. package/dist/sources/prusa/splitParts.d.ts +0 -13
  34. package/dist/sources/prusa/splitParts.js +107 -42
  35. package/dist/sources/reader.d.ts +26 -0
  36. package/dist/stamp.d.ts +1 -1
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/dist/worker-entry.js +4 -3
  40. package/dist/worker.d.ts +7 -2
  41. package/dist/worker.js +22 -8
  42. package/package.json +3 -3
@@ -22,7 +22,8 @@ import { parseItemPositions } from "../../archive/parseItemPositions.js";
22
22
  import { MODEL_SETTINGS_PATH, PROJECT_SETTINGS_PATH, TOP_MODEL_PATH } from "../../archive/paths.js";
23
23
  import { xmlBlocks } from "../../archive/xmlBlocks.js";
24
24
  import { convertObjectOverrides, convertPrusaSettings } from "./convertSettings.js";
25
- import { parsePrusaIni } from "./ini.js";
25
+ import { parsePrusaIni, splitStringList } from "./ini.js";
26
+ import { bedIndexOf, bedTranslation, MAX_BEDS, parseBedShape } from "./beds.js";
26
27
  import { parsePrusaModelConfig } from "./modelConfig.js";
27
28
  import { splitMultiPartObjects } from "./splitParts.js";
28
29
  const utf8Decoder = new TextDecoder("utf-8");
@@ -100,43 +101,62 @@ export function adaptPrusaModel(text) {
100
101
  export function convertCustomGcodes(prusaXml) {
101
102
  if (!/<custom_gcodes_per_print_z[\s>]/.test(prusaXml))
102
103
  return null;
103
- const layers = [];
104
+ // PrusaSlicer 2.9 writes one block per bed, side by side, each with its bed_idx; older files have one block.
105
+ const plates = [];
104
106
  let colorChanges = 0;
105
- for (const m of prusaXml.matchAll(/<code\s+([^>]*?)\/>/g)) {
106
- if (layers.length >= MAX_CUSTOM_GCODES)
107
- break;
108
- const attrs = m[1];
109
- const attr = (name) => {
110
- const found = new RegExp(`\\b${name}="([^"]*)"`).exec(attrs);
111
- return found ? decodeXml(found[1]) : null;
112
- };
113
- const printZ = attr("print_z");
114
- if (printZ === null || !/^\d+(\.\d+)?$/.test(printZ))
115
- continue;
116
- const sourceType = attr("type") ?? "";
117
- if (!/^[0-4]$/.test(sourceType))
107
+ let total = 0;
108
+ // One pass over the blocks (xmlBlocks): a lazy pattern would rescan the file for every opener without a closer.
109
+ for (const block of xmlBlocks(prusaXml, "custom_gcodes_per_print_z")) {
110
+ // A project without bed_idx has one bed. A bed number outside PrusaSlicer's beds (a negative one, as a crafted
111
+ // file has it) is skipped, as PrusaSlicer 2.9.7 skips it, never moved onto another plate.
112
+ const bedAttr = /\bbed_idx="([^"]*)"/.exec(block.attrs)?.[1];
113
+ if (bedAttr !== undefined && !/^\d{1,2}$/.test(bedAttr))
118
114
  continue;
119
- const extruder = attr("extruder") ?? "1";
120
- if (!/^\d{1,3}$/.test(extruder))
115
+ const bedIndex = Number(bedAttr ?? "0");
116
+ if (bedIndex >= MAX_BEDS)
121
117
  continue;
122
- const color = (attr("color") ?? "").slice(0, 32);
123
- let extra = (attr("extra") ?? "").slice(0, 4000);
124
- // 0 is a color change: a pause (1) in Snapmaker Orca, where the U1 pauses with M600 for the swap.
125
- let type = sourceType;
126
- if (sourceType === "0") {
127
- type = "1";
128
- extra = color ? `Color change to ${color}` : "Color change";
129
- colorChanges++;
118
+ const body = block.body;
119
+ const layers = [];
120
+ for (const m of body.matchAll(/<code\s+([^>]*?)\/>/g)) {
121
+ if (total >= MAX_CUSTOM_GCODES)
122
+ break;
123
+ total++;
124
+ const attrs = m[1];
125
+ const attr = (name) => {
126
+ const found = new RegExp(`\\b${name}="([^"]*)"`).exec(attrs);
127
+ return found ? decodeXml(found[1]) : null;
128
+ };
129
+ const printZ = attr("print_z");
130
+ if (printZ === null || !/^\d+(\.\d+)?$/.test(printZ))
131
+ continue;
132
+ const sourceType = attr("type") ?? "";
133
+ if (!/^[0-4]$/.test(sourceType))
134
+ continue;
135
+ const extruder = attr("extruder") ?? "1";
136
+ if (!/^\d{1,3}$/.test(extruder))
137
+ continue;
138
+ const color = (attr("color") ?? "").slice(0, 32);
139
+ let extra = (attr("extra") ?? "").slice(0, 4000);
140
+ // 0 is a color change: a pause (1) in Snapmaker Orca, where the U1 pauses with M600 for the swap.
141
+ let type = sourceType;
142
+ if (sourceType === "0") {
143
+ type = "1";
144
+ extra = color ? `Color change to ${color}` : "Color change";
145
+ colorChanges++;
146
+ }
147
+ // 4 is custom G-code, the only kind whose text is the creator's own.
148
+ const gcode = type === "4" ? (attr("gcode") ?? extra).slice(0, 4000) : type === "2" ? "tool_change" : "";
149
+ layers.push(`<layer top_z="${printZ}" type="${type}" extruder="${extruder}" color="${xmlAttr(color)}" extra="${xmlAttr(extra)}" gcode="${xmlAttr(gcode)}"/>`);
130
150
  }
131
- // 4 is custom G-code, the only kind whose text is the creator's own.
132
- const gcode = type === "4" ? (attr("gcode") ?? extra).slice(0, 4000) : type === "2" ? "tool_change" : "";
133
- layers.push(`<layer top_z="${printZ}" type="${type}" extruder="${extruder}" color="${xmlAttr(color)}" extra="${xmlAttr(extra)}" gcode="${xmlAttr(gcode)}"/>`);
151
+ if (layers.length === 0)
152
+ continue;
153
+ const mode = /<mode\s+value="(SingleExtruder|MultiAsSingle|MultiExtruder)"/.exec(body)?.[1] ?? "SingleExtruder";
154
+ plates.push(["<plate>", `<plate_info id="${bedIndex + 1}"/>`, ...layers, `<mode value="${mode}"/>`, "</plate>"].join("\n"));
134
155
  }
135
- if (layers.length === 0)
156
+ if (plates.length === 0)
136
157
  return null;
137
- const mode = /<mode\s+value="(SingleExtruder|MultiAsSingle|MultiExtruder)"/.exec(prusaXml)?.[1] ?? "SingleExtruder";
138
158
  return {
139
- xml: ['<?xml version="1.0" encoding="utf-8"?>', "<custom_gcodes_per_layer>", "<plate>", '<plate_info id="1"/>', ...layers, `<mode value="${mode}"/>`, "</plate>", "</custom_gcodes_per_layer>", ""].join("\n"),
159
+ xml: ['<?xml version="1.0" encoding="utf-8"?>', "<custom_gcodes_per_layer>", ...plates, "</custom_gcodes_per_layer>", ""].join("\n"),
140
160
  colorChanges,
141
161
  };
142
162
  }
@@ -174,6 +194,10 @@ export function componentIds(topModelText) {
174
194
  }
175
195
  return out;
176
196
  }
197
+ const compareVersions = (a, b) => {
198
+ const [x, y] = [a.split(".").map(Number), b.split(".").map(Number)];
199
+ return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
200
+ };
177
201
  /** The filament an object prints with: its own, else its only part's; 0 is the default (filament 1). */
178
202
  function objectFilament(object) {
179
203
  if (object.extruder > 0)
@@ -210,9 +234,10 @@ export function partsOf(object, components, split, depth = 0) {
210
234
  * Bambu's `model_settings.config`: each object with its name, filament and settings, its parts, and one plate holding
211
235
  * every instance.
212
236
  */
213
- export function buildModelSettings(ini, objects, instanceCounts, parts) {
237
+ export function buildModelSettings(ini, objects, instanceCounts, parts, plateOf = () => 1) {
214
238
  const lines = ['<?xml version="1.0" encoding="UTF-8"?>', "<config>"];
215
- const instances = [];
239
+ /** Each plate's `<model_instance>` blocks, by plate number. */
240
+ const plates = new Map();
216
241
  for (const object of objects) {
217
242
  const filament = objectFilament(object);
218
243
  const name = object.name || `Object ${object.id}`;
@@ -233,11 +258,18 @@ export function buildModelSettings(ini, objects, instanceCounts, parts) {
233
258
  }
234
259
  lines.push(" </object>");
235
260
  const count = instanceCounts.get(object.id) ?? 1;
261
+ const instances = plates.get(plateOf(object.id)) ?? [];
236
262
  for (let i = 0; i < count; i++) {
237
263
  instances.push(" <model_instance>", ` <metadata key="object_id" value="${object.id}"/>`, ` <metadata key="instance_id" value="${i}"/>`, ` <metadata key="identify_id" value="${object.id * 100 + i}"/>`, " </model_instance>");
238
264
  }
265
+ plates.set(plateOf(object.id), instances);
239
266
  }
240
- lines.push(" <plate>", ' <metadata key="plater_id" value="1"/>', ' <metadata key="plater_name" value=""/>', ' <metadata key="locked" value="false"/>', ...instances, " </plate>", "</config>", "");
267
+ // Plates in order, every number up to the highest used, so a plate's number is its position (as the Bambu family's are).
268
+ const highest = Math.max(1, ...plates.keys());
269
+ for (let plate = 1; plate <= highest; plate++) {
270
+ lines.push(" <plate>", ` <metadata key="plater_id" value="${plate}"/>`, ' <metadata key="plater_name" value=""/>', ' <metadata key="locked" value="false"/>', ...(plates.get(plate) ?? []), " </plate>");
271
+ }
272
+ lines.push("</config>", "");
241
273
  return lines.join("\n");
242
274
  }
243
275
  export const prusaReader = {
@@ -291,11 +323,32 @@ export const prusaReader = {
291
323
  // A wrapper object (an older PrusaSlicer's extra instance) has no config entry of its own: the mesh object's serves.
292
324
  const configFor = (id) => byId.get(id) ?? components.get(id)?.map((c) => byId.get(c)).find((o) => o !== undefined);
293
325
  const partFileCache = new Map();
326
+ // PrusaSlicer 2.9 can place objects on several beds, virtual copies of the printer's bed on a grid; each becomes a
327
+ // plate. An older project has one bed. An object on no bed (off every one) stays on plate 1, with a warning.
328
+ const version = ini.version ? (/^\d+\.\d+\.\d+/.exec(ini.version)?.[0] ?? null) : null;
329
+ const severalBeds = version !== null && compareVersions(version, "2.9.0") >= 0;
330
+ const bed = severalBeds ? parseBedShape(ini.settings.get("bed_shape")) : null;
331
+ const plateOf = new Map();
294
332
  const objects = Object.entries(itemPositions).map(([id, fallbackXy]) => {
295
333
  const bbox = objectWorldBboxXY(id, modelText, partFileCache, zipEntries);
296
334
  const name = configFor(Number(id))?.name;
297
- return { id, ...(name ? { name } : {}), plate: 1, ...(bbox ? { bbox } : { bbox: null, fallbackXy }) };
335
+ let plate = 1;
336
+ if (bed) {
337
+ const box = bbox ?? [fallbackXy[0], fallbackXy[0], fallbackXy[1], fallbackXy[1]];
338
+ const index = bedIndexOf(box, bed);
339
+ if (index === null)
340
+ warnings.push(` WARN: "${name ?? id}" sits on none of PrusaSlicer's beds (off every bed); it's put on plate 1.`);
341
+ else
342
+ plate = index + 1;
343
+ }
344
+ plateOf.set(Number(id), plate);
345
+ return { id, ...(name ? { name } : {}), plate, ...(bbox ? { bbox } : { bbox: null, fallbackXy }) };
298
346
  });
347
+ const plateCount = new Set(plateOf.values()).size;
348
+ // Where each plate's bed sits in the project, for drawing an object on its own plate: PrusaSlicer's grid, not Bambu Studio's.
349
+ const sourcePlateOrigins = bed ? Object.fromEntries([...new Set(plateOf.values())].map((plate) => [plate, bedTranslation(plate - 1, bed)])) : undefined;
350
+ if (plateCount > 1)
351
+ warnings.push(` note: the project's ${plateCount} beds become ${plateCount} plates.`);
299
352
  // Objects the model file places, in its order; the per-object config may name objects that aren't placed.
300
353
  const placed = objects.map((o) => {
301
354
  const config = configFor(Number(o.id));
@@ -309,7 +362,7 @@ export const prusaReader = {
309
362
  }
310
363
  const model = adaptPrusaModel(modelText);
311
364
  entries[TOP_MODEL_PATH] = model.text === topModelText ? topModelBytes : utf8Encoder.encode(model.text);
312
- entries[MODEL_SETTINGS_PATH] = utf8Encoder.encode(buildModelSettings(ini, placed, instanceCounts, (object) => partsOf(object, components, split.parts)));
365
+ entries[MODEL_SETTINGS_PATH] = utf8Encoder.encode(buildModelSettings(ini, placed, instanceCounts, (object) => partsOf(object, components, split.parts), (id) => plateOf.get(id) ?? 1));
313
366
  const customGcodeBytes = zipEntries[PRUSA_CUSTOM_GCODE_PATH];
314
367
  if (customGcodeBytes && customGcodeBytes.length <= MAX_AUX_BYTES) {
315
368
  const orca = convertCustomGcodes(utf8Decoder.decode(customGcodeBytes));
@@ -329,12 +382,25 @@ export const prusaReader = {
329
382
  if (zipEntries[PRUSA_LAYER_RANGES_PATH]) {
330
383
  warnings.push(" WARN: this project's layer-range settings (settings for a range of heights of an object) aren't carried yet.");
331
384
  }
385
+ const printerNotes = ini.settings.get("printer_notes") ?? "";
332
386
  return {
333
387
  source: "prusaslicer",
388
+ prusa: {
389
+ version,
390
+ settings: ini.settings,
391
+ targets: converted.targets,
392
+ presets: {
393
+ print: ini.settings.get("print_settings_id") ?? "",
394
+ printer: ini.settings.get("printer_settings_id") ?? "",
395
+ filaments: splitStringList(ini.raw.get("filament_settings_id") ?? ""),
396
+ },
397
+ vendorKeyword: /\bPRINTER_VENDOR_([A-Z0-9]{1,20})\b/.exec(printerNotes)?.[1] ?? null,
398
+ },
334
399
  zipEntries: entries,
335
400
  request: { projectSettings: converted.settings, objects },
336
401
  warnings,
337
402
  unpackedBytes,
403
+ ...(sourcePlateOrigins ? { sourcePlateOrigins } : {}),
338
404
  };
339
405
  },
340
406
  };
@@ -1,16 +1,3 @@
1
- /**
2
- * PrusaSlicer keeps an object's parts and modifiers as triangle ranges of one
3
- * mesh; the Bambu Studio family keeps each part as a mesh object of its own,
4
- * referenced by the object's components. A PrusaSlicer object with several
5
- * parts (the usual way a multi-color model is built there: one part per
6
- * filament) is split here into that layout, so each part keeps its filament,
7
- * its settings and its painting.
8
- *
9
- * Text in, text out: the vertex and triangle tags are copied as written
10
- * (painting attributes included), only the vertex indices are renumbered, and
11
- * each part gets the vertices it uses. PrusaSlicer writes the vertices already
12
- * in the object's coordinates, so every component sits at identity.
13
- */
14
1
  import type { PrusaObject, PrusaVolume } from "./modelConfig.js";
15
2
  export interface SplitPart {
16
3
  /** The new mesh object's id. */
@@ -1,77 +1,142 @@
1
- /** Past this, the split is skipped and the object kept as one part: the tag arrays would be the memory problem. */
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * PrusaSlicer keeps an object's parts and modifiers as triangle ranges of one
4
+ * mesh; the Bambu Studio family keeps each part as a mesh object of its own,
5
+ * referenced by the object's components. A PrusaSlicer object with several
6
+ * parts (the usual way a multi-color model is built there: one part per
7
+ * filament) is split here into that layout, so each part keeps its filament,
8
+ * its settings and its painting.
9
+ *
10
+ * Text in, text out: the vertex and triangle tags are copied as written
11
+ * (painting attributes included), only the vertex indices are renumbered, and
12
+ * each part gets the vertices it uses. PrusaSlicer writes the vertices already
13
+ * in the object's coordinates, so every component sits at identity.
14
+ *
15
+ * Every step is linear in the model's size: the objects are found in one scan,
16
+ * each is replaced in place, and the text is joined once at the end, so a
17
+ * model with many multi-part objects doesn't make a slower machine wait.
18
+ */
19
+ import { isSelfClosingTag, xmlTags } from "../../archive/xmlBlocks.js";
20
+ /** Past this, the split is skipped and the object kept as one part. */
2
21
  const MAX_TRIANGLES = 4_000_000;
3
22
  const IDENTITY = "1 0 0 0 1 0 0 0 1 0 0 0";
4
- /** The `<object id="N" ...>...</object>` block's bounds in `text`, or null. */
5
- function objectBounds(text, id) {
6
- let from = 0;
7
- for (;;) {
8
- const start = text.indexOf(`<object id="${id}"`, from);
9
- if (start === -1)
23
+ const CLOSE = "</object>";
24
+ /** An object's opening tag: its id, and the character after it (the tag must go on with a space, a tab, a newline or `>`). */
25
+ const OPENER = /<object id="(\d{1,9})"([ >\t\n]?)/g;
26
+ /** A triangle's three vertex indices. Not global, so each `exec` starts from the beginning of the tag. */
27
+ const CORNERS = [/\bv1="(\d+)"/, /\bv2="(\d+)"/, /\bv3="(\d+)"/];
28
+ /**
29
+ * The mesh of an object's block, or null when it can't be split: a triangle
30
+ * without three vertex indices, an index past the last vertex, or more
31
+ * triangles than {@link MAX_TRIANGLES} (stops reading there, so a huge mesh
32
+ * isn't held twice).
33
+ */
34
+ function readMesh(block) {
35
+ const vertices = [];
36
+ for (const { attrs, start, end } of xmlTags(block, "vertex")) {
37
+ if (isSelfClosingTag(attrs))
38
+ vertices.push(block.slice(start, end));
39
+ }
40
+ const triangles = [];
41
+ const corners = [];
42
+ for (const { attrs, start, end } of xmlTags(block, "triangle")) {
43
+ if (!isSelfClosingTag(attrs))
44
+ continue;
45
+ if (triangles.length === MAX_TRIANGLES)
10
46
  return null;
11
- const next = text[start + `<object id="${id}"`.length];
12
- if (next === " " || next === ">" || next === "\t" || next === "\n") {
13
- const end = text.indexOf("</object>", start);
14
- return end === -1 ? null : [start, end + "</object>".length];
47
+ for (const pattern of CORNERS) {
48
+ const index = pattern.exec(attrs)?.[1];
49
+ const n = index === undefined ? -1 : Number(index);
50
+ if (n < 0 || n >= vertices.length)
51
+ return null;
52
+ corners.push(n);
15
53
  }
16
- from = start + 1;
54
+ triangles.push(block.slice(start, end));
17
55
  }
56
+ return { vertices, triangles, corners };
18
57
  }
19
- function renumber(tag, map) {
20
- return tag.replace(/\b(v[123])="(\d+)"/g, (_, name, index) => `${name}="${map[Number(index)]}"`);
58
+ /** Whether the volumes' triangle ranges cover the mesh in order, each starting where the last one ended. */
59
+ function rangesCoverMesh(volumes, triangleCount) {
60
+ return (volumes.every((v, i) => v.firstTriangle <= v.lastTriangle && (i === 0 ? v.firstTriangle === 0 : v.firstTriangle === volumes[i - 1].lastTriangle + 1)) &&
61
+ volumes[volumes.length - 1].lastTriangle === triangleCount - 1);
21
62
  }
22
63
  export function splitMultiPartObjects(text, objects, warnings) {
23
64
  const parts = new Map();
65
+ // One scan: the highest object id (new ids follow it) and where each object starts.
24
66
  let nextId = 0;
25
- for (const m of text.matchAll(/<object id="(\d{1,9})"/g))
67
+ const startOf = new Map();
68
+ for (const m of text.matchAll(OPENER)) {
26
69
  nextId = Math.max(nextId, Number(m[1]));
70
+ if (m[2] !== "" && !startOf.has(m[1]))
71
+ startOf.set(m[1], m.index);
72
+ }
27
73
  nextId++;
74
+ // An object that starts after the last closing tag has none, so no block: known without scanning to the end for it.
75
+ const lastClose = text.lastIndexOf(CLOSE);
76
+ /** Each split object's replacement, by the position of the closing tag that ends its block. */
77
+ const edits = new Map();
28
78
  for (const object of objects) {
29
79
  if (object.volumes.length < 2)
30
80
  continue;
31
- const bounds = objectBounds(text, object.id);
32
- if (!bounds)
81
+ const start = startOf.get(String(object.id));
82
+ if (start === undefined || start > lastClose)
33
83
  continue;
34
- const block = text.slice(bounds[0], bounds[1]);
84
+ const close = text.indexOf(CLOSE, start);
85
+ // Two blocks that end at the same closing tag overlap (an object that never closed before the next one began),
86
+ // and an object listed twice ends where it did the first time: the first one split keeps that stretch of text.
87
+ if (edits.has(close))
88
+ continue;
89
+ const end = close + CLOSE.length;
90
+ const block = text.slice(start, end);
35
91
  if (block.includes("<component"))
36
92
  continue;
37
- const vertices = [...block.matchAll(/<vertex\b[^>]*\/>/g)].map((m) => m[0]);
38
- const triangles = [...block.matchAll(/<triangle\b[^>]*\/>/g)].map((m) => m[0]);
39
- const corners = triangles.map((tag) => {
40
- const v1 = /\bv1="(\d+)"/.exec(tag);
41
- const v2 = /\bv2="(\d+)"/.exec(tag);
42
- const v3 = /\bv3="(\d+)"/.exec(tag);
43
- return v1 && v2 && v3 ? [Number(v1[1]), Number(v2[1]), Number(v3[1])] : null;
44
- });
45
- const ranges = object.volumes.map((v) => [v.firstTriangle, v.lastTriangle]);
46
- const contiguous = ranges.every(([a, b], i) => a <= b && (i === 0 ? a === 0 : a === ranges[i - 1][1] + 1)) && ranges[ranges.length - 1][1] === triangles.length - 1;
47
- const wellFormed = corners.every((c) => c !== null && c.every((i) => i < vertices.length));
48
- if (!contiguous || !wellFormed || triangles.length > MAX_TRIANGLES) {
93
+ const mesh = readMesh(block);
94
+ if (!mesh || !rangesCoverMesh(object.volumes, mesh.triangles.length)) {
49
95
  warnings.push(` WARN: "${object.name || `Object ${object.id}`}" has ${object.volumes.length} parts whose mesh couldn't be split, so it's converted as one part on its own filament.`);
50
96
  continue;
51
97
  }
52
- const map = new Int32Array(vertices.length).fill(-1);
98
+ // A vertex's index in the part being written is valid while `partOf` holds that part's number, so the map
99
+ // never needs clearing between parts.
100
+ const partOf = new Int32Array(mesh.vertices.length);
101
+ const newIndex = new Int32Array(mesh.vertices.length);
102
+ const renumber = (tag, part) => tag.replace(/\b(v[123])="(\d+)"/g, (_, name, index) => {
103
+ const i = Number(index);
104
+ return `${name}="${partOf[i] === part ? newIndex[i] : -1}"`;
105
+ });
53
106
  const pieces = [];
54
107
  const split = [];
55
- for (const volume of object.volumes) {
108
+ object.volumes.forEach((volume, v) => {
109
+ const part = v + 1;
56
110
  const id = nextId++;
57
- map.fill(-1);
58
111
  const ownVertices = [];
59
112
  const ownTriangles = [];
60
113
  for (let t = volume.firstTriangle; t <= volume.lastTriangle; t++) {
61
- for (const index of corners[t]) {
62
- if (map[index] === -1) {
63
- map[index] = ownVertices.length;
64
- ownVertices.push(vertices[index]);
114
+ for (let c = 3 * t; c < 3 * t + 3; c++) {
115
+ const index = mesh.corners[c];
116
+ if (partOf[index] !== part) {
117
+ partOf[index] = part;
118
+ newIndex[index] = ownVertices.length;
119
+ ownVertices.push(mesh.vertices[index]);
65
120
  }
66
121
  }
67
- ownTriangles.push(renumber(triangles[t], map));
122
+ ownTriangles.push(renumber(mesh.triangles[t], part));
68
123
  }
69
- pieces.push([` <object id="${id}" type="model">`, " <mesh>", " <vertices>", ...ownVertices.map((v) => ` ${v}`), " </vertices>", " <triangles>", ...ownTriangles.map((t) => ` ${t}`), " </triangles>", " </mesh>", " </object>"].join("\n"));
124
+ pieces.push([` <object id="${id}" type="model">`, " <mesh>", " <vertices>", ...ownVertices.map((s) => ` ${s}`), " </vertices>", " <triangles>", ...ownTriangles.map((s) => ` ${s}`), " </triangles>", " </mesh>", " </object>"].join("\n"));
70
125
  split.push({ id, volume });
71
- }
126
+ });
72
127
  pieces.push([` <object id="${object.id}" type="model">`, " <components>", ...split.map((p) => ` <component objectid="${p.id}" transform="${IDENTITY}"/>`), " </components>", " </object>"].join("\n"));
73
- text = `${text.slice(0, bounds[0])}${pieces.join("\n").trimStart()}${text.slice(bounds[1])}`;
128
+ edits.set(close, { start, end, text: pieces.join("\n").trimStart() });
74
129
  parts.set(object.id, split);
75
130
  }
76
- return { text, parts };
131
+ if (edits.size === 0)
132
+ return { text, parts };
133
+ // Blocks that don't share a closing tag never overlap, so the replacements apply in order of position, in one join.
134
+ const out = [];
135
+ let at = 0;
136
+ for (const edit of [...edits.values()].sort((a, b) => a.start - b.start)) {
137
+ out.push(text.slice(at, edit.start), edit.text);
138
+ at = edit.end;
139
+ }
140
+ out.push(text.slice(at));
141
+ return { text: out.join(""), parts };
77
142
  }
@@ -12,9 +12,30 @@
12
12
  import type { ConvertRequest } from "../schema.js";
13
13
  /** The slicer family a project came from. */
14
14
  export type SourceFormat = "bambu-family" | "prusaslicer";
15
+ /**
16
+ * What a PrusaSlicer project keeps for the step that needs profile data
17
+ * (`convert()`, once the catalog is loaded): the project's settings in
18
+ * PrusaSlicer's own keys and value forms, which Snapmaker Orca keys each
19
+ * wrote, and the preset names it recorded.
20
+ */
21
+ export interface PrusaProjectInfo {
22
+ /** The PrusaSlicer version that saved the project ("2.9.6"), from the settings file's first line; null when unreadable. */
23
+ version: string | null;
24
+ settings: ReadonlyMap<string, string>;
25
+ targets: ReadonlyMap<string, readonly string[]>;
26
+ presets: {
27
+ print: string;
28
+ printer: string;
29
+ filaments: readonly string[];
30
+ };
31
+ /** The vendor keyword from `printer_notes` ("PRUSA3D"), when the printer profile names one. */
32
+ vendorKeyword: string | null;
33
+ }
15
34
  export interface ParsedProject {
16
35
  /** Which reader read the file. */
17
36
  source: SourceFormat;
37
+ /** Present for a PrusaSlicer project. */
38
+ prusa?: PrusaProjectInfo;
18
39
  /** The full decompressed source zip, kept for applyConvertResponse's final reassembly. */
19
40
  zipEntries: Record<string, Uint8Array>;
20
41
  /** The conversion request payload. */
@@ -23,6 +44,11 @@ export interface ParsedProject {
23
44
  warnings: string[];
24
45
  /** The project's unpacked size, every entry together. */
25
46
  unpackedBytes: number;
47
+ /**
48
+ * Where each plate's bed sits in the source project, in mm from the first plate's, when the source doesn't lay its
49
+ * plates out on Bambu Studio's grid (PrusaSlicer 2.9's beds). Absent for the Bambu Studio family.
50
+ */
51
+ sourcePlateOrigins?: Record<number, [number, number]>;
26
52
  }
27
53
  export interface ReadContext {
28
54
  /** The project's unpacked size, every entry together (already checked against the cap). */
package/dist/stamp.d.ts CHANGED
@@ -24,8 +24,8 @@ export declare const OutputStampSchema: z.ZodObject<{
24
24
  profileId: z.ZodString;
25
25
  source: z.ZodOptional<z.ZodObject<{
26
26
  format: z.ZodEnum<{
27
- "bambu-family": "bambu-family";
28
27
  prusaslicer: "prusaslicer";
28
+ "bambu-family": "bambu-family";
29
29
  }>;
30
30
  slicerVersion: z.ZodOptional<z.ZodString>;
31
31
  }, z.core.$strict>>;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.6.0";
1
+ export declare const VERSION = "0.7.1";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Written by scripts/sync-version.mjs from package.json; a test checks they match.
3
- export const VERSION = "0.6.0";
3
+ export const VERSION = "0.7.1";
@@ -133,9 +133,10 @@ async function handle(request) {
133
133
  const entries = unwrapBundle(toBytes(request.bytes));
134
134
  if (!entries)
135
135
  return { result: null, transfer: [] };
136
- // Copy each entry into its own buffer so it can be transferred alone.
137
- const copies = entries.map((e) => ({ name: e.name, bytes: e.bytes.slice() }));
138
- return { result: copies, transfer: copies.map((c) => c.bytes.buffer) };
136
+ // The unzip gives each entry a buffer of its own, so each is handed over as it is; one that shares its buffer
137
+ // with something else (a reader of another kind, say) is copied first, so the transfer takes only its bytes.
138
+ const owned = entries.map((e) => ({ name: e.name, bytes: e.bytes.byteOffset === 0 && e.bytes.byteLength === e.bytes.buffer.byteLength ? e.bytes : e.bytes.slice() }));
139
+ return { result: owned, transfer: owned.map((c) => c.bytes.buffer) };
139
140
  }
140
141
  default:
141
142
  throw new Any2orcaError("invalid_file", "Unknown worker request.");
package/dist/worker.d.ts CHANGED
@@ -82,8 +82,13 @@ export interface ConverterWorker {
82
82
  * stock marked, for a badge) and notes on anything it would leave out.
83
83
  */
84
84
  resolvePreset(preset: Preset, options?: WorkerReleaseOption): Promise<ResolvedPreset>;
85
- /** Each .3mf inside a bundle zip, or null for a plain .3mf. */
86
- unwrapBundle(bytes: Uint8Array): Promise<Array<{
85
+ /**
86
+ * Each .3mf inside a bundle zip, or null for a plain .3mf. Pass `transfer: true`
87
+ * to move the bytes instead of copying them, as for `open`.
88
+ */
89
+ unwrapBundle(bytes: Uint8Array, options?: {
90
+ transfer?: boolean;
91
+ }): Promise<Array<{
87
92
  name: string;
88
93
  bytes: Uint8Array;
89
94
  }> | null>;
package/dist/worker.js CHANGED
@@ -45,12 +45,16 @@ export function createConverterWorker(worker, options) {
45
45
  return;
46
46
  }
47
47
  pending.delete(message.id);
48
- if (message.ok)
48
+ if (message.ok === true) {
49
49
  entry.resolve(message.result);
50
- else {
51
- const slicer = message.error.slicer;
52
- entry.reject(new Any2orcaError(message.error.code, message.error.message, typeof slicer === "string" ? { slicer } : undefined));
50
+ return;
53
51
  }
52
+ // Read defensively: a reply without a usable error would otherwise throw here, after the entry is gone, and the
53
+ // call would never settle.
54
+ const error = message.error;
55
+ const code = typeof error?.code === "string" ? error.code : "invalid_file";
56
+ const text = typeof error?.message === "string" ? error.message : "The converter's worker sent a reply it couldn't read.";
57
+ entry.reject(new Any2orcaError(code, text, typeof error?.slicer === "string" ? { slicer: error.slicer } : undefined));
54
58
  });
55
59
  function call(body, transfer = [], onProgress) {
56
60
  if (terminated)
@@ -95,9 +99,7 @@ export function createConverterWorker(worker, options) {
95
99
  }
96
100
  return {
97
101
  async open(bytes, openOptions = {}) {
98
- // Either way only one buffer crosses: the caller's own (transfer) or a fresh copy.
99
- const ownsWholeBuffer = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength;
100
- const payload = openOptions.transfer && ownsWholeBuffer ? bytes : bytes.slice();
102
+ const payload = outgoing(bytes, openOptions.transfer);
101
103
  const { handle, inspection } = await call({ op: "open", bytes: payload }, [payload.buffer]);
102
104
  return { project: project(handle, inspection), inspection };
103
105
  },
@@ -107,7 +109,10 @@ export function createConverterWorker(worker, options) {
107
109
  },
108
110
  resolvePreset: (preset, release) => call({ op: "resolvePreset", preset, ...releaseField(release) }),
109
111
  listProfiles: (filter) => call({ op: "listProfiles", ...(filter ? { filter } : {}) }),
110
- unwrapBundle: (bytes) => call({ op: "unwrapBundle", bytes }),
112
+ unwrapBundle(bytes, bundleOptions = {}) {
113
+ const payload = outgoing(bytes, bundleOptions.transfer);
114
+ return call({ op: "unwrapBundle", bytes: payload }, [payload.buffer]);
115
+ },
111
116
  terminate() {
112
117
  terminated = true;
113
118
  worker.terminate();
@@ -117,6 +122,15 @@ export function createConverterWorker(worker, options) {
117
122
  },
118
123
  };
119
124
  }
125
+ /**
126
+ * The bytes to post: the caller's own buffer when it may be moved and the
127
+ * view covers all of it, otherwise a fresh copy. Either way only one buffer
128
+ * crosses to the worker.
129
+ */
130
+ function outgoing(bytes, transfer) {
131
+ const ownsWholeBuffer = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength;
132
+ return transfer && ownsWholeBuffer ? bytes : bytes.slice();
133
+ }
120
134
  /** The release field for a request, left out when no release is named. */
121
135
  function releaseField(release) {
122
136
  return release?.snapmakerOrcaVersion === undefined ? {} : { release: { snapmakerOrcaVersion: release.snapmakerOrcaVersion } };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "any2orca",
3
- "version": "0.6.0",
4
- "outputAffecting": "six more PrusaSlicer settings are carried; converted PrusaSlicer files change, Bambu-family files don't",
3
+ "version": "0.7.1",
4
+ "outputAffecting": "PrusaSlicer files: an unchecked Brim box is no brim and supports convert as PrusaSlicer shows them; a placement that isn't a number is kept as written. Bambu-family files are otherwise unchanged",
5
5
  "description": "Convert Bambu Studio, Creality Print, Anycubic Slicer Next, ElegooSlicer and Flash Studio 3MF projects for the Snapmaker U1 (Snapmaker Orca), entirely on your own machine. Library, CLI and Web Worker in one package.",
6
6
  "keywords": [
7
7
  "3mf",
@@ -65,7 +65,7 @@
65
65
  "docs": "typedoc"
66
66
  },
67
67
  "dependencies": {
68
- "any2orca-profiles": "0.2.0",
68
+ "any2orca-profiles": "0.3.1",
69
69
  "fflate": "0.8.3",
70
70
  "zod": "4.6.7"
71
71
  },