any2orca 0.7.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.
@@ -12,17 +12,20 @@ export function buildFilamentConfigs(slots, filamentShape, filamentKeyBlocklist)
12
12
  if (slots.length === 0) {
13
13
  return { files: {}, uniqueNames: null };
14
14
  }
15
- const uniqueNames = [];
15
+ // Each name's first slot, in one pass, in the order names first appear. Every slot is kept in the project; this
16
+ // only picks which one each embedded preset is written from. (Scanning the list for every slot was quadratic.)
17
+ // The settings came through JSON, so no name is NaN, the one value a Map compares differently from `===`.
18
+ const firstSlotByName = new Map();
16
19
  for (const slot of slots) {
17
20
  const name = slot.filament_settings_id ?? "Unnamed Filament";
18
- if (!uniqueNames.some((n) => n === name)) {
19
- uniqueNames.push(name);
20
- }
21
+ if (!firstSlotByName.has(name))
22
+ firstSlotByName.set(name, slot);
21
23
  }
24
+ const uniqueNames = [...firstSlotByName.keys()];
22
25
  const files = {};
23
26
  uniqueNames.forEach((name, i) => {
24
27
  const idx = i + 1;
25
- const rep = slots.find((s) => (s.filament_settings_id ?? "Unnamed Filament") === name);
28
+ const rep = firstSlotByName.get(name);
26
29
  const cfg = { ...filamentShape };
27
30
  for (const [key, val] of Object.entries(rep)) {
28
31
  if (filamentKeyBlocklist.has(key))
package/dist/inspect.d.ts CHANGED
@@ -44,6 +44,13 @@ export interface Inspection {
44
44
  slicerVersion: string | null;
45
45
  /** The source bed's printable_area, for drawing the source plate. */
46
46
  sourcePrintableArea: string[] | null;
47
+ /**
48
+ * Where each plate's bed sits in the source project, in mm from the first plate's, keyed by plate number: subtract it
49
+ * from an object's `bbox` to draw the object on its own plate. Present only when the source slicer doesn't lay its
50
+ * plates out on Bambu Studio's grid (columns = ceil(sqrt(plate count)), a pitch of 1.2 beds, later rows at negative Y):
51
+ * PrusaSlicer 2.9 places its beds in rings with a gap of at most 100 mm, later rows at positive Y. Absent: use that grid.
52
+ */
53
+ sourcePlateOrigins?: Record<number, [number, number]>;
47
54
  /** Non-fatal notes from reading the file. */
48
55
  warnings: string[];
49
56
  /**
@@ -54,4 +61,4 @@ export interface Inspection {
54
61
  }
55
62
  export declare function detectSourceVendor(printerModel: string | null, sourcePresetName?: string | null, printerNotes?: string | null, printerPresetName?: string | null): SourceVendor;
56
63
  /** Builds an {@link Inspection} from a parsed project's settings and objects. */
57
- export declare function inspectProject(projectSettings: Record<string, unknown>, objects: ConvertObject[], warnings: readonly string[], unpackedBytes: number): Inspection;
64
+ export declare function inspectProject(projectSettings: Record<string, unknown>, objects: ConvertObject[], warnings: readonly string[], unpackedBytes: number, sourcePlateOrigins?: Readonly<Record<number, readonly [number, number]>>): Inspection;
package/dist/inspect.js CHANGED
@@ -63,7 +63,7 @@ export function detectSourceVendor(printerModel, sourcePresetName = null, printe
63
63
  return "other";
64
64
  }
65
65
  /** Builds an {@link Inspection} from a parsed project's settings and objects. */
66
- export function inspectProject(projectSettings, objects, warnings, unpackedBytes) {
66
+ export function inspectProject(projectSettings, objects, warnings, unpackedBytes, sourcePlateOrigins) {
67
67
  const colors = toStringArray(projectSettings.filament_colour);
68
68
  const types = toStringArray(projectSettings.filament_type);
69
69
  const names = toStringArray(projectSettings.filament_settings_id);
@@ -105,5 +105,8 @@ export function inspectProject(projectSettings, objects, warnings, unpackedBytes
105
105
  : null,
106
106
  warnings: [...warnings],
107
107
  unpackedBytes,
108
+ ...(sourcePlateOrigins
109
+ ? { sourcePlateOrigins: Object.fromEntries(plates.filter((p) => Object.hasOwn(sourcePlateOrigins, p)).map((p) => [p, [sourcePlateOrigins[p][0], sourcePlateOrigins[p][1]]])) }
110
+ : {}),
108
111
  };
109
112
  }
package/dist/project.js CHANGED
@@ -191,7 +191,7 @@ export class Project {
191
191
  return structuredClone(this.request.projectSettings);
192
192
  }
193
193
  inspect() {
194
- return inspectProject(this.request.projectSettings, this.request.objects, this.parsed.warnings, this.parsed.unpackedBytes);
194
+ return inspectProject(this.request.projectSettings, this.request.objects, this.parsed.warnings, this.parsed.unpackedBytes, this.parsed.sourcePlateOrigins);
195
195
  }
196
196
  /** The profile auto-matching would pick for this file. */
197
197
  matchProfile(profiles) {
@@ -75,10 +75,10 @@ export function lookupPrintPresetName(bundle, recorded) {
75
75
  const candidates = [recorded];
76
76
  let inner = recorded;
77
77
  for (let i = 0; i < 8; i++) {
78
- const m = /^.+? \((.+)\)$/.exec(inner);
79
- if (!m)
78
+ const peeled = innerPresetName(inner);
79
+ if (peeled === null)
80
80
  break;
81
- inner = m[1];
81
+ inner = peeled;
82
82
  candidates.push(inner);
83
83
  }
84
84
  for (const candidate of candidates) {
@@ -90,3 +90,17 @@ export function lookupPrintPresetName(bundle, recorded) {
90
90
  }
91
91
  return null;
92
92
  }
93
+ /**
94
+ * The name inside one `<file>.3mf (<name>)` layer, or null when `name` isn't
95
+ * one: what `/^.+? \((.+)\)$/` captured, found without that pattern. The
96
+ * pattern rescanned the rest of the name for every " (" in it, and the
97
+ * settings file a name comes from may be 4 MB: 0.3 MB of " (" took 33 seconds.
98
+ */
99
+ function innerPresetName(name) {
100
+ // `.` in that pattern stopped at a line break, and `$` only matched at the very end.
101
+ if (!name.endsWith(")") || /[\n\r\u2028\u2029]/.test(name))
102
+ return null;
103
+ // `.+?` needs a character before the " (", and `.+` one between it and the final ")".
104
+ const at = name.indexOf(" (", 1);
105
+ return at !== -1 && at + 2 < name.length - 1 ? name.slice(at + 2, name.length - 1) : null;
106
+ }
@@ -52,6 +52,20 @@ const num = (v) => Number.parseFloat(v);
52
52
  function fmt(n) {
53
53
  return Number.isFinite(n) ? String(Number(n.toFixed(4))) : "0";
54
54
  }
55
+ /**
56
+ * Snapmaker Orca's brim type for PrusaSlicer's brim settings. PrusaSlicer's "Brim" checkbox is the brim width: it's
57
+ * checked when the width is above 0, and unchecking it sets the width to 0 (`FrequentlyChangedParameters.cpp`). It
58
+ * prints no brim when the width is 0 or the type is "no brim" (`Brim.cpp`), whatever the type says, so "outer only"
59
+ * with a width of 0 is no brim. Snapmaker Orca draws its brim by type alone, so that state becomes "no_brim"; anything
60
+ * else keeps PrusaSlicer's type, which Snapmaker Orca names the same.
61
+ */
62
+ function brimType(settings) {
63
+ const width = settings.get("brim_width");
64
+ const type = settings.get("brim_type");
65
+ if (width !== undefined && Number.isFinite(num(width)) && num(width) <= 0)
66
+ return "no_brim";
67
+ return type ?? null;
68
+ }
55
69
  /** The value as a list, split the way PrusaSlicer joined it for what the target keeps. */
56
70
  function entries(ini, key, target) {
57
71
  const raw = ini.raw.get(key);
@@ -236,6 +250,26 @@ export function convertObjectOverrides(ini, overrides) {
236
250
  break;
237
251
  }
238
252
  }
253
+ // An object that turns supports on itself gets the kind and the choices PrusaSlicer shows for it, which would
254
+ // otherwise come from the project's (Snapmaker's stock when the project has supports off).
255
+ if (overrides.get("support_material") === "1") {
256
+ const auto = merged.settings.get("support_material_auto");
257
+ if (auto !== undefined)
258
+ out.support_type ??= TRANSFORMS.supportType({ ini: merged, key: "support_material_auto", value: auto, warnings, dropped })[0];
259
+ const styleRule = PRUSA_KEY_MAP.support_material_style;
260
+ const style = merged.settings.get("support_material_style");
261
+ if (style !== undefined && styleRule?.kind === "choices" && styleRule.values[style] !== undefined)
262
+ out.support_style ??= styleRule.values[style];
263
+ const plateOnly = merged.settings.get("support_material_buildplate_only");
264
+ if (plateOnly !== undefined)
265
+ out.support_on_build_plate_only ??= plateOnly;
266
+ }
267
+ // An object's own brim width or type decides its brim on its own: off where the project's is on, or on where it's off.
268
+ if (overrides.has("brim_width") || overrides.has("brim_type")) {
269
+ const type = brimType(merged.settings);
270
+ if (type !== null)
271
+ out.brim_type = type;
272
+ }
239
273
  return out;
240
274
  }
241
275
  export function convertPrusaSettings(ini) {
@@ -302,6 +336,15 @@ export function convertPrusaSettings(ini) {
302
336
  break;
303
337
  }
304
338
  }
339
+ // The brim the project prints, from the width (PrusaSlicer's checkbox) as well as the type; also for a project from
340
+ // a PrusaSlicer old enough to have no brim type. Snapmaker Orca's pipeline always carries the source's brim type.
341
+ const brim = brimType(ini.settings);
342
+ if (brim !== null && settings.brim_type !== brim) {
343
+ settings.brim_type = brim;
344
+ const source = ini.settings.has("brim_type") ? "brim_type" : "brim_width";
345
+ if (!targets.get(source)?.includes("brim_type"))
346
+ targets.set(source, [...(targets.get(source) ?? []), "brim_type"]);
347
+ }
305
348
  if (ini.version)
306
349
  settings.version = ini.version;
307
350
  const filamentCount = Array.isArray(settings.filament_colour) ? settings.filament_colour.length : 1;
@@ -312,6 +355,18 @@ export function convertPrusaSettings(ini) {
312
355
  settings[key] = Array.from({ length: filamentCount }, () => value[0]);
313
356
  }
314
357
  }
358
+ // A support or wipe tower filament the project doesn't have (a preset for a five-tool printer on a one-filament
359
+ // project, say) would point Snapmaker Orca at a filament that isn't there, so the stock value stands.
360
+ for (const key of ["support_filament", "support_interface_filament", "wipe_tower_filament"]) {
361
+ const value = settings[key];
362
+ if (typeof value === "string" && Number.parseInt(value, 10) > filamentCount) {
363
+ delete settings[key];
364
+ for (const [source, written] of targets)
365
+ if (written.includes(key))
366
+ targets.set(source, written.filter((t) => t !== key));
367
+ dropped.push({ key, why: `filament ${value} isn't one of the project's ${filamentCount}` });
368
+ }
369
+ }
315
370
  // Snapmaker Orca sizes its purge structures by these two arrays and refuses a file whose matrix doesn't fit the
316
371
  // filament count. PrusaSlicer has the matrix (n x n) but no vector (2n); the pipeline sizes both from the source's,
317
372
  // so the vector is given here. The U1 purges by its own minimum, so only the sizes matter.
@@ -399,6 +399,8 @@ export const PRUSA_KEY_MAP = Object.freeze({
399
399
  min_layer_height: machine,
400
400
  duplicate_distance: machine,
401
401
  z_offset: machine,
402
+ // PrusaSlicer 2.9.7: scales only the filament statistics it shows and writes, never the extrusion; a printer setting.
403
+ used_filament_compensation: machine,
402
404
  nozzle_diameter: same,
403
405
  nozzle_high_flow: machine,
404
406
  extruder_offset: machine,
@@ -62,10 +62,11 @@ export function parsePrusaModelConfig(xml) {
62
62
  const id = /^\s*id="(\d{1,9})"/.exec(` ${attrs}`)?.[1] ?? /\bid="(\d{1,9})"/.exec(attrs)?.[1];
63
63
  if (!id)
64
64
  continue;
65
- // Object-level metadata sits outside the volumes; the volume blocks are cut out first so a volume's keys aren't read
66
- // as the object's.
65
+ // Object-level metadata sits outside the volumes; each volume's body is cut out, by its position, so a volume's keys
66
+ // aren't read as the object's. (Searching for each body's text instead rebuilt the object's text once per volume.)
67
67
  const volumes = [];
68
- let ownText = body;
68
+ const ownPieces = [];
69
+ let ownFrom = 0;
69
70
  for (const v of xmlBlocks(body, "volume")) {
70
71
  if (volumes.length >= MAX_VOLUMES)
71
72
  break;
@@ -73,7 +74,8 @@ export function parsePrusaModelConfig(xml) {
73
74
  const last = /\blastid="(\d{1,9})"/.exec(v.attrs)?.[1];
74
75
  if (first === undefined || last === undefined)
75
76
  continue;
76
- ownText = ownText.replace(v.body, "");
77
+ ownPieces.push(body.slice(ownFrom, v.bodyStart));
78
+ ownFrom = v.bodyEnd;
77
79
  const meta = metadata(v.body, "volume");
78
80
  volumes.push({
79
81
  firstTriangle: int(first, 0),
@@ -84,7 +86,8 @@ export function parsePrusaModelConfig(xml) {
84
86
  settings: new Map([...meta].filter(([k]) => !NOT_SETTINGS.has(k))),
85
87
  });
86
88
  }
87
- const own = metadata(ownText, "object");
89
+ ownPieces.push(body.slice(ownFrom));
90
+ const own = metadata(ownPieces.join(""), "object");
88
91
  objects.push({
89
92
  id: int(id, 0),
90
93
  name: own.get("name") ?? "",
@@ -18,6 +18,16 @@ export interface PolicyBResult {
18
18
  * @param printKeys the project keys that are print settings (the key map's print-group targets), to compare
19
19
  */
20
20
  export declare function changedPrintKeys(bundle: PrusaBundle, recordedPresetName: string, settings: ReadonlyMap<string, string>, printKeys: ReadonlySet<string>): PolicyBResult | null;
21
+ /**
22
+ * PrusaSlicer keys carried as the project has them, whatever its preset says (owner decision 2026-11-05): the Supports
23
+ * menu on PrusaSlicer's sidebar and the filaments supports print from. Left to the comparison, a project that turns
24
+ * supports on got Snapmaker's stock kind of support (tree) instead of the one PrusaSlicer showed (snug, say); an
25
+ * Input Shaper preset's default, "for support enforcers only", became Snapmaker's stock "off", leaving painted
26
+ * enforcers unused; and a soluble-support preset's support filament and zero contact distance became any filament with
27
+ * a gap. The menu's choices (everywhere, build plate only, enforcers only) and the kind of support count only when
28
+ * supports are on; the contact distances only with a support filament of its own.
29
+ */
30
+ export declare function statedPrintKeys(settings: ReadonlyMap<string, string>): string[];
21
31
  type BundleEntry = ReturnType<ProfileCatalog["prusaBundles"]>[number];
22
32
  /**
23
33
  * The bundles to try for a project, best first: per vendor, the newest whose
@@ -60,6 +60,24 @@ export function changedPrintKeys(bundle, recordedPresetName, settings, printKeys
60
60
  }
61
61
  return { presetName, changedKeys: changedKeys.sort(), compared };
62
62
  }
63
+ /**
64
+ * PrusaSlicer keys carried as the project has them, whatever its preset says (owner decision 2026-11-05): the Supports
65
+ * menu on PrusaSlicer's sidebar and the filaments supports print from. Left to the comparison, a project that turns
66
+ * supports on got Snapmaker's stock kind of support (tree) instead of the one PrusaSlicer showed (snug, say); an
67
+ * Input Shaper preset's default, "for support enforcers only", became Snapmaker's stock "off", leaving painted
68
+ * enforcers unused; and a soluble-support preset's support filament and zero contact distance became any filament with
69
+ * a gap. The menu's choices (everywhere, build plate only, enforcers only) and the kind of support count only when
70
+ * supports are on; the contact distances only with a support filament of its own.
71
+ */
72
+ export function statedPrintKeys(settings) {
73
+ const keys = ["support_material", "support_material_extruder", "support_material_interface_extruder"];
74
+ if (settings.get("support_material") === "1")
75
+ keys.push("support_material_auto", "support_material_buildplate_only", "support_material_style");
76
+ const ownFilament = ["support_material_extruder", "support_material_interface_extruder"].some((key) => Number.parseInt(settings.get(key) ?? "0", 10) > 0);
77
+ if (ownFilament)
78
+ keys.push("support_material_contact_distance", "support_material_bottom_contact_distance");
79
+ return keys.filter((key) => settings.has(key));
80
+ }
63
81
  const versionParts = (v) => v.split(".").map(Number);
64
82
  const compareVersions = (a, b) => {
65
83
  const [x, y] = [versionParts(a), versionParts(b)];
@@ -117,16 +135,17 @@ export async function applyPolicyB(prusa, catalog, projectSettings) {
117
135
  if (!result)
118
136
  continue;
119
137
  const changedTargets = new Set();
120
- for (const key of result.changedKeys)
138
+ for (const key of [...result.changedKeys, ...statedPrintKeys(prusa.settings)]) {
121
139
  for (const target of prusa.targets.get(key) ?? [])
122
140
  if (SETTINGS_CATALOG[target]?.group === "print")
123
141
  changedTargets.add(target);
142
+ }
124
143
  const list = projectSettings.different_settings_to_system;
125
144
  const rest = Array.isArray(list) ? list.slice(1) : [];
126
145
  return {
127
146
  projectSettings: { ...projectSettings, different_settings_to_system: [[...changedTargets].sort().join(";"), ...rest] },
128
147
  notes: [
129
- ` note: print settings compared with PrusaSlicer's "${result.presetName}" (${entry.name}'s presets of PrusaSlicer ${entry.slicerVersion}): ${result.changedKeys.length} of ${result.compared + result.changedKeys.length} differ from the preset, and only those are carried; Snapmaker's stock stands for the rest.`,
148
+ ` note: print settings compared with PrusaSlicer's "${result.presetName}" (${entry.name}'s presets of PrusaSlicer ${entry.slicerVersion}): ${result.changedKeys.length} of ${result.compared + result.changedKeys.length} differ from the preset, and only those are carried, with the Supports menu and the support filaments as the project has them; Snapmaker's stock stands for the rest.`,
130
149
  ],
131
150
  };
132
151
  }
@@ -23,7 +23,7 @@ import { MODEL_SETTINGS_PATH, PROJECT_SETTINGS_PATH, TOP_MODEL_PATH } from "../.
23
23
  import { xmlBlocks } from "../../archive/xmlBlocks.js";
24
24
  import { convertObjectOverrides, convertPrusaSettings } from "./convertSettings.js";
25
25
  import { parsePrusaIni, splitStringList } from "./ini.js";
26
- import { bedIndexOf, parseBedShape } from "./beds.js";
26
+ import { bedIndexOf, bedTranslation, MAX_BEDS, parseBedShape } from "./beds.js";
27
27
  import { parsePrusaModelConfig } from "./modelConfig.js";
28
28
  import { splitMultiPartObjects } from "./splitParts.js";
29
29
  const utf8Decoder = new TextDecoder("utf-8");
@@ -107,7 +107,14 @@ export function convertCustomGcodes(prusaXml) {
107
107
  let total = 0;
108
108
  // One pass over the blocks (xmlBlocks): a lazy pattern would rescan the file for every opener without a closer.
109
109
  for (const block of xmlBlocks(prusaXml, "custom_gcodes_per_print_z")) {
110
- const bedIndex = Number(/\bbed_idx="(\d{1,2})"/.exec(block.attrs)?.[1] ?? "0");
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))
114
+ continue;
115
+ const bedIndex = Number(bedAttr ?? "0");
116
+ if (bedIndex >= MAX_BEDS)
117
+ continue;
111
118
  const body = block.body;
112
119
  const layers = [];
113
120
  for (const m of body.matchAll(/<code\s+([^>]*?)\/>/g)) {
@@ -338,6 +345,8 @@ export const prusaReader = {
338
345
  return { id, ...(name ? { name } : {}), plate, ...(bbox ? { bbox } : { bbox: null, fallbackXy }) };
339
346
  });
340
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;
341
350
  if (plateCount > 1)
342
351
  warnings.push(` note: the project's ${plateCount} beds become ${plateCount} plates.`);
343
352
  // Objects the model file places, in its order; the per-object config may name objects that aren't placed.
@@ -391,6 +400,7 @@ export const prusaReader = {
391
400
  request: { projectSettings: converted.settings, objects },
392
401
  warnings,
393
402
  unpackedBytes,
403
+ ...(sourcePlateOrigins ? { sourcePlateOrigins } : {}),
394
404
  };
395
405
  },
396
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
  }
@@ -44,6 +44,11 @@ export interface ParsedProject {
44
44
  warnings: string[];
45
45
  /** The project's unpacked size, every entry together. */
46
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]>;
47
52
  }
48
53
  export interface ReadContext {
49
54
  /** The project's unpacked size, every entry together (already checked against the cap). */
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.7.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.7.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>;