any2orca 0.4.1 → 0.6.0

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.
@@ -0,0 +1,59 @@
1
+ import type { SourceReader } from "../reader.js";
2
+ import { type PrusaIni } from "./ini.js";
3
+ import { type PrusaObject } from "./modelConfig.js";
4
+ import { type SplitPart } from "./splitParts.js";
5
+ export declare const PRUSA_SETTINGS_PATH = "Metadata/Slic3r_PE.config";
6
+ /**
7
+ * The model file as Bambu's reader expects it: its version entry (without one, the reader treats the file as another
8
+ * vendor's: instances split into objects, a lone object renamed after the file, transforms baked into the mesh), and
9
+ * the paint attributes under the names it decodes. Everything else, the mesh included, stays as written.
10
+ */
11
+ export declare function adaptPrusaModel(text: string): {
12
+ text: string;
13
+ painted: boolean;
14
+ };
15
+ /**
16
+ * Snapmaker Orca's `custom_gcode_per_layer.xml` from PrusaSlicer's `custom_gcode_per_print_z.xml`: the same entries
17
+ * (a pause, a tool change, custom G-code, each at a height) under Orca's names, on plate 1, and PrusaSlicer's color
18
+ * changes as pauses. Snapmaker Orca, like Bambu Studio, writes no G-code for a "color change" entry (its generator
19
+ * has that path removed); what it writes at a pause is the printer's pause G-code, which on the U1 is `M600`, the
20
+ * filament swap PrusaSlicer's color change means. The color the creator chose stays on the entry and in the pause's
21
+ * note. The G-code text itself isn't carried for either: Snapmaker Orca emits the U1's own, as it does for a Bambu
22
+ * project.
23
+ */
24
+ export declare function convertCustomGcodes(prusaXml: string): {
25
+ xml: string;
26
+ colorChanges: number;
27
+ } | null;
28
+ /**
29
+ * Snapmaker Orca's `layer_heights_profile.txt` from PrusaSlicer's: the same `object_id=N|z;h;z;h...` lines, with N
30
+ * turned from PrusaSlicer's 1-based object index into the object's 3MF id, which the format's version 2 header says.
31
+ */
32
+ export declare function convertLayerHeights(prusaText: string, objectIds: readonly number[]): string | null;
33
+ /**
34
+ * For each object that is built from components (PrusaSlicer 2.2 and 2.3 wrote an object's extra instances that way,
35
+ * each a wrapper around the mesh object), the ids of the objects it references. Bambu's reader takes those as the
36
+ * object's parts.
37
+ */
38
+ export declare function componentIds(topModelText: string): Map<number, number[]>;
39
+ /** One `<part>` of an object in `model_settings.config`. */
40
+ export interface ModelPart {
41
+ id: number;
42
+ name: string;
43
+ subtype: string;
44
+ /** 0 for the object's own filament. */
45
+ extruder: number;
46
+ settings: ReadonlyMap<string, string>;
47
+ }
48
+ /**
49
+ * The parts of each object: the mesh objects it was split into (each with its volume's name, kind, filament and
50
+ * settings), the mesh objects an older PrusaSlicer's instance wrapper references (resolved through the split), or,
51
+ * with the mesh inline, the object itself.
52
+ */
53
+ export declare function partsOf(object: PrusaObject, components: ReadonlyMap<number, readonly number[]>, split: ReadonlyMap<number, readonly SplitPart[]>, depth?: number): ModelPart[];
54
+ /**
55
+ * Bambu's `model_settings.config`: each object with its name, filament and settings, its parts, and one plate holding
56
+ * every instance.
57
+ */
58
+ export declare function buildModelSettings(ini: PrusaIni, objects: readonly PrusaObject[], instanceCounts: ReadonlyMap<number, number>, parts: (object: PrusaObject) => ModelPart[]): string;
59
+ export declare const prusaReader: SourceReader;
@@ -0,0 +1,340 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * The reader for PrusaSlicer projects. PrusaSlicer keeps a project's settings
4
+ * as an INI in `Metadata/Slic3r_PE.config`, the per-object settings in
5
+ * `Metadata/Slic3r_PE_model.config`, color changes and variable layer heights
6
+ * in files of its own, and painting as triangle attributes under its own
7
+ * names. The reader turns all of that into what the Bambu Studio family's
8
+ * layout carries, so the pipeline and the writer see a project like any
9
+ * other: settings in Snapmaker Orca's keys (the key map), a synthesized
10
+ * `model_settings.config` with every object on plate 1, Snapmaker Orca's own
11
+ * files for color changes and layer heights, and the model file with the
12
+ * paint attributes renamed and the version entry Bambu's reader looks for.
13
+ *
14
+ * Snapmaker Orca opens a file whose `Application` names PrusaSlicer with its
15
+ * geometry-only reader; every converted file names Snapmaker Orca there, so
16
+ * it takes Bambu's reader, the one that reads `project_settings.config`.
17
+ */
18
+ import { Any2orcaError } from "../../errors.js";
19
+ import { MAX_OBJECTS } from "../../schema.js";
20
+ import { objectWorldBboxXY } from "../../archive/objectWorldBboxXY.js";
21
+ import { parseItemPositions } from "../../archive/parseItemPositions.js";
22
+ import { MODEL_SETTINGS_PATH, PROJECT_SETTINGS_PATH, TOP_MODEL_PATH } from "../../archive/paths.js";
23
+ import { xmlBlocks } from "../../archive/xmlBlocks.js";
24
+ import { convertObjectOverrides, convertPrusaSettings } from "./convertSettings.js";
25
+ import { parsePrusaIni } from "./ini.js";
26
+ import { parsePrusaModelConfig } from "./modelConfig.js";
27
+ import { splitMultiPartObjects } from "./splitParts.js";
28
+ const utf8Decoder = new TextDecoder("utf-8");
29
+ const utf8Encoder = new TextEncoder();
30
+ export const PRUSA_SETTINGS_PATH = "Metadata/Slic3r_PE.config";
31
+ const PRUSA_MODEL_CONFIG_PATH = "Metadata/Slic3r_PE_model.config";
32
+ const PRUSA_CUSTOM_GCODE_PATH = "Metadata/Prusa_Slicer_custom_gcode_per_print_z.xml";
33
+ const PRUSA_LAYER_HEIGHTS_PATH = "Metadata/Slic3r_PE_layer_heights_profile.txt";
34
+ const PRUSA_LAYER_RANGES_PATH = "Metadata/Prusa_Slicer_layer_config_ranges.xml";
35
+ /** Snapmaker Orca's files for the same things. */
36
+ const ORCA_CUSTOM_GCODE_PATH = "Metadata/custom_gcode_per_layer.xml";
37
+ const ORCA_LAYER_HEIGHTS_PATH = "Metadata/layer_heights_profile.txt";
38
+ /** PrusaSlicer's own metadata files: replaced by Snapmaker Orca's, never copied (two sets of settings would confuse it). */
39
+ const PRUSA_METADATA = /^Metadata\/(?:Slic3r_PE|Prusa_Slicer_)/;
40
+ /** As in the Bambu family reader: the engine's longest string, and UTF-8 never takes fewer bytes than characters. */
41
+ const MAX_TOP_MODEL_BYTES = 500 * 1024 * 1024;
42
+ /** A real settings file is 15 to 60 KB; the INI reader also caps the lines. */
43
+ const MAX_SETTINGS_BYTES = 4 * 1024 * 1024;
44
+ const MAX_AUX_BYTES = 16 * 1024 * 1024;
45
+ const MAX_CUSTOM_GCODES = 10_000;
46
+ /** Paint attributes: PrusaSlicer's names to the ones Bambu's reader decodes (the same encoding on both sides). */
47
+ const PAINT_ATTRIBUTES = [
48
+ ['slic3rpe:mmu_segmentation="', 'paint_color="'],
49
+ ['slic3rpe:custom_seam="', 'paint_seam="'],
50
+ ['slic3rpe:custom_supports="', 'paint_supports="'],
51
+ ['slic3rpe:fuzzy_skin="', 'paint_fuzzy_skin="'],
52
+ ];
53
+ /** The slicer a settings file names on its first line, from its first bytes only. */
54
+ function generatedBy(settings) {
55
+ const firstLine = utf8Decoder.decode(settings.subarray(0, 200)).split(/\r?\n/, 1)[0] ?? "";
56
+ return /^; generated by ([A-Za-z][A-Za-z0-9]{1,30}) /.exec(firstLine)?.[1] ?? null;
57
+ }
58
+ function xmlAttr(value) {
59
+ return value.replace(/[&<>"\r\n]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "\r": "&#13;", "\n": "&#10;" })[c] ?? c);
60
+ }
61
+ function decodeXml(s) {
62
+ return s.replace(/&(amp|lt|gt|quot|apos|#(\d{1,7}));/g, (_, name, code) => {
63
+ if (code)
64
+ return String.fromCodePoint(Math.min(Number(code), 0x10ffff));
65
+ return { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }[name] ?? "";
66
+ });
67
+ }
68
+ /**
69
+ * The model file as Bambu's reader expects it: its version entry (without one, the reader treats the file as another
70
+ * vendor's: instances split into objects, a lone object renamed after the file, transforms baked into the mesh), and
71
+ * the paint attributes under the names it decodes. Everything else, the mesh included, stays as written.
72
+ */
73
+ export function adaptPrusaModel(text) {
74
+ let out = text;
75
+ let painted = false;
76
+ for (const [from, to] of PAINT_ATTRIBUTES) {
77
+ if (!out.includes(from))
78
+ continue;
79
+ painted = true;
80
+ out = out.split(from).join(to);
81
+ }
82
+ if (!out.includes('<metadata name="BambuStudio:3mfVersion">')) {
83
+ const version = '<metadata name="BambuStudio:3mfVersion">1</metadata>';
84
+ const application = /([ \t]*)(<metadata name="Application">[^<]*<\/metadata>)/.exec(out);
85
+ out = application
86
+ ? out.replace(application[0], `${application[1]}${application[2]}\n${application[1]}${version}`)
87
+ : out.replace(/(<model\b[^>]*>)/, `$1\n ${version}`);
88
+ }
89
+ return { text: out, painted };
90
+ }
91
+ /**
92
+ * Snapmaker Orca's `custom_gcode_per_layer.xml` from PrusaSlicer's `custom_gcode_per_print_z.xml`: the same entries
93
+ * (a pause, a tool change, custom G-code, each at a height) under Orca's names, on plate 1, and PrusaSlicer's color
94
+ * changes as pauses. Snapmaker Orca, like Bambu Studio, writes no G-code for a "color change" entry (its generator
95
+ * has that path removed); what it writes at a pause is the printer's pause G-code, which on the U1 is `M600`, the
96
+ * filament swap PrusaSlicer's color change means. The color the creator chose stays on the entry and in the pause's
97
+ * note. The G-code text itself isn't carried for either: Snapmaker Orca emits the U1's own, as it does for a Bambu
98
+ * project.
99
+ */
100
+ export function convertCustomGcodes(prusaXml) {
101
+ if (!/<custom_gcodes_per_print_z[\s>]/.test(prusaXml))
102
+ return null;
103
+ const layers = [];
104
+ 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))
118
+ continue;
119
+ const extruder = attr("extruder") ?? "1";
120
+ if (!/^\d{1,3}$/.test(extruder))
121
+ 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++;
130
+ }
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)}"/>`);
134
+ }
135
+ if (layers.length === 0)
136
+ return null;
137
+ const mode = /<mode\s+value="(SingleExtruder|MultiAsSingle|MultiExtruder)"/.exec(prusaXml)?.[1] ?? "SingleExtruder";
138
+ 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"),
140
+ colorChanges,
141
+ };
142
+ }
143
+ /**
144
+ * Snapmaker Orca's `layer_heights_profile.txt` from PrusaSlicer's: the same `object_id=N|z;h;z;h...` lines, with N
145
+ * turned from PrusaSlicer's 1-based object index into the object's 3MF id, which the format's version 2 header says.
146
+ */
147
+ export function convertLayerHeights(prusaText, objectIds) {
148
+ const lines = [];
149
+ for (const line of prusaText.split(/\r?\n/)) {
150
+ const m = /^object_id=(\d{1,6})\|([\d.;]+)$/.exec(line.trim());
151
+ if (!m)
152
+ continue;
153
+ const id = objectIds[Number(m[1]) - 1];
154
+ if (id === undefined)
155
+ continue;
156
+ lines.push(`object_id=${id}|${m[2]}`);
157
+ }
158
+ return lines.length === 0 ? null : ["layer_heights_profile_format_version=2", ...lines, ""].join("\n");
159
+ }
160
+ /**
161
+ * For each object that is built from components (PrusaSlicer 2.2 and 2.3 wrote an object's extra instances that way,
162
+ * each a wrapper around the mesh object), the ids of the objects it references. Bambu's reader takes those as the
163
+ * object's parts.
164
+ */
165
+ export function componentIds(topModelText) {
166
+ const out = new Map();
167
+ for (const { attrs, body } of xmlBlocks(topModelText, "object")) {
168
+ const id = /\bid="(\d{1,9})"/.exec(attrs)?.[1];
169
+ if (!id || !body.includes("<component"))
170
+ continue;
171
+ const ids = [...body.matchAll(/<component\b[^>]*\bobjectid="(\d{1,9})"/g)].map((m) => Number(m[1]));
172
+ if (ids.length > 0)
173
+ out.set(Number(id), ids);
174
+ }
175
+ return out;
176
+ }
177
+ /** The filament an object prints with: its own, else its only part's; 0 is the default (filament 1). */
178
+ function objectFilament(object) {
179
+ if (object.extruder > 0)
180
+ return object.extruder;
181
+ const parts = object.volumes.filter((v) => v.volumeType === "ModelPart");
182
+ return parts.length === 1 ? parts[0].extruder : 0;
183
+ }
184
+ /** Bambu's part kinds, from PrusaSlicer's volume types. */
185
+ const PART_SUBTYPES = {
186
+ ModelPart: "normal_part",
187
+ NegativeVolume: "negative_part",
188
+ ParameterModifier: "modifier_part",
189
+ SupportEnforcer: "support_enforcer",
190
+ SupportBlocker: "support_blocker",
191
+ };
192
+ /**
193
+ * The parts of each object: the mesh objects it was split into (each with its volume's name, kind, filament and
194
+ * settings), the mesh objects an older PrusaSlicer's instance wrapper references (resolved through the split), or,
195
+ * with the mesh inline, the object itself.
196
+ */
197
+ export function partsOf(object, components, split, depth = 0) {
198
+ const own = split.get(object.id);
199
+ const name = object.name || `Object ${object.id}`;
200
+ if (own) {
201
+ return own.map(({ id, volume }) => ({ id, name: volume.name || name, subtype: PART_SUBTYPES[volume.volumeType] ?? "normal_part", extruder: volume.extruder, settings: volume.settings }));
202
+ }
203
+ const referenced = components.get(object.id);
204
+ if (referenced && depth < 4) {
205
+ return referenced.flatMap((id) => (split.has(id) ? partsOf({ ...object, id }, components, split, depth + 1) : [{ id, name, subtype: "normal_part", extruder: 0, settings: new Map() }]));
206
+ }
207
+ return [{ id: object.id, name, subtype: "normal_part", extruder: 0, settings: new Map() }];
208
+ }
209
+ /**
210
+ * Bambu's `model_settings.config`: each object with its name, filament and settings, its parts, and one plate holding
211
+ * every instance.
212
+ */
213
+ export function buildModelSettings(ini, objects, instanceCounts, parts) {
214
+ const lines = ['<?xml version="1.0" encoding="UTF-8"?>', "<config>"];
215
+ const instances = [];
216
+ for (const object of objects) {
217
+ const filament = objectFilament(object);
218
+ const name = object.name || `Object ${object.id}`;
219
+ lines.push(` <object id="${object.id}">`, ` <metadata key="name" value="${xmlAttr(name)}"/>`);
220
+ if (filament > 0)
221
+ lines.push(` <metadata key="extruder" value="${filament}"/>`);
222
+ for (const [key, value] of Object.entries(convertObjectOverrides(ini, object.settings)).sort()) {
223
+ lines.push(` <metadata key="${key}" value="${xmlAttr(value)}"/>`);
224
+ }
225
+ for (const part of parts(object)) {
226
+ lines.push(` <part id="${part.id}" subtype="${part.subtype}">`, ` <metadata key="name" value="${xmlAttr(part.name)}"/>`, ' <metadata key="matrix" value="1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1"/>');
227
+ if (part.extruder > 0)
228
+ lines.push(` <metadata key="extruder" value="${part.extruder}"/>`);
229
+ for (const [key, value] of Object.entries(convertObjectOverrides(ini, part.settings)).sort()) {
230
+ lines.push(` <metadata key="${key}" value="${xmlAttr(value)}"/>`);
231
+ }
232
+ lines.push(" </part>");
233
+ }
234
+ lines.push(" </object>");
235
+ const count = instanceCounts.get(object.id) ?? 1;
236
+ for (let i = 0; i < count; i++) {
237
+ 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
+ }
239
+ }
240
+ lines.push(" <plate>", ' <metadata key="plater_id" value="1"/>', ' <metadata key="plater_name" value=""/>', ' <metadata key="locked" value="false"/>', ...instances, " </plate>", "</config>", "");
241
+ return lines.join("\n");
242
+ }
243
+ export const prusaReader = {
244
+ format: "prusaslicer",
245
+ detect(entries) {
246
+ const settings = entries[PRUSA_SETTINGS_PATH];
247
+ return settings !== undefined && entries[PROJECT_SETTINGS_PATH] === undefined && generatedBy(settings) === "PrusaSlicer";
248
+ },
249
+ read(zipEntries, { unpackedBytes, warnings }) {
250
+ const settingsBytes = zipEntries[PRUSA_SETTINGS_PATH];
251
+ if (!settingsBytes || settingsBytes.length > MAX_SETTINGS_BYTES) {
252
+ throw new Any2orcaError("invalid_file", "This project's print settings are damaged, so it can't be converted. Re-saving the project in PrusaSlicer usually fixes this.");
253
+ }
254
+ const ini = parsePrusaIni(utf8Decoder.decode(settingsBytes));
255
+ if (ini.settings.size === 0) {
256
+ throw new Any2orcaError("invalid_file", "This project's print settings are empty, so there's nothing to convert. Re-saving the project in PrusaSlicer usually fixes this.");
257
+ }
258
+ const topModelBytes = zipEntries[TOP_MODEL_PATH];
259
+ if (!topModelBytes)
260
+ throw new Any2orcaError("invalid_file", "This 3MF has no model in it, so there's nothing to convert.");
261
+ if (topModelBytes.length > MAX_TOP_MODEL_BYTES) {
262
+ throw new Any2orcaError("invalid_project", `This project's main model file is ${Math.round(topModelBytes.length / 1024 / 1024)} MB, more than the ${MAX_TOP_MODEL_BYTES / 1024 / 1024} MB that can be read in one piece.`);
263
+ }
264
+ const topModelText = utf8Decoder.decode(topModelBytes);
265
+ const converted = convertPrusaSettings(ini);
266
+ warnings.push(...converted.warnings);
267
+ if (converted.dropped.length > 0) {
268
+ const keys = converted.dropped.map((d) => d.key);
269
+ warnings.push(` note: ${keys.length} PrusaSlicer settings have no Snapmaker Orca counterpart and weren't carried: ${keys.slice(0, 12).join(", ")}${keys.length > 12 ? ` and ${keys.length - 12} more` : ""}.`);
270
+ }
271
+ if (converted.unknown.length > 0) {
272
+ warnings.push(` note: ${converted.unknown.length} settings this PrusaSlicer version writes aren't known here and weren't carried: ${converted.unknown.slice(0, 12).join(", ")}${converted.unknown.length > 12 ? ` and ${converted.unknown.length - 12} more` : ""}.`);
273
+ }
274
+ const modelConfigBytes = zipEntries[PRUSA_MODEL_CONFIG_PATH];
275
+ const prusaObjects = modelConfigBytes && modelConfigBytes.length <= MAX_AUX_BYTES ? parsePrusaModelConfig(utf8Decoder.decode(modelConfigBytes)) : [];
276
+ const byId = new Map(prusaObjects.map((o) => [o.id, o]));
277
+ const itemPositions = parseItemPositions(topModelText);
278
+ const itemCount = Object.keys(itemPositions).length;
279
+ if (itemCount > MAX_OBJECTS) {
280
+ throw new Any2orcaError("invalid_project", `This project has ${itemCount} objects, more than the ${MAX_OBJECTS} a conversion supports.`);
281
+ }
282
+ const instanceCounts = new Map();
283
+ for (const m of topModelText.matchAll(/<item objectid="(\d{1,9})"/g)) {
284
+ const id = Number(m[1]);
285
+ instanceCounts.set(id, (instanceCounts.get(id) ?? 0) + 1);
286
+ }
287
+ // A multi-part object becomes one mesh object per part, as the Bambu family keeps them (decision 6 of the design).
288
+ const split = splitMultiPartObjects(topModelText, prusaObjects, warnings);
289
+ const modelText = split.text;
290
+ const components = componentIds(modelText);
291
+ // A wrapper object (an older PrusaSlicer's extra instance) has no config entry of its own: the mesh object's serves.
292
+ const configFor = (id) => byId.get(id) ?? components.get(id)?.map((c) => byId.get(c)).find((o) => o !== undefined);
293
+ const partFileCache = new Map();
294
+ const objects = Object.entries(itemPositions).map(([id, fallbackXy]) => {
295
+ const bbox = objectWorldBboxXY(id, modelText, partFileCache, zipEntries);
296
+ const name = configFor(Number(id))?.name;
297
+ return { id, ...(name ? { name } : {}), plate: 1, ...(bbox ? { bbox } : { bbox: null, fallbackXy }) };
298
+ });
299
+ // Objects the model file places, in its order; the per-object config may name objects that aren't placed.
300
+ const placed = objects.map((o) => {
301
+ const config = configFor(Number(o.id));
302
+ return config ? { ...config, id: Number(o.id) } : { id: Number(o.id), name: "", extruder: 0, volumes: [], settings: new Map() };
303
+ });
304
+ const entries = {};
305
+ for (const [name, bytes] of Object.entries(zipEntries)) {
306
+ if (PRUSA_METADATA.test(name) || name === TOP_MODEL_PATH || name === MODEL_SETTINGS_PATH)
307
+ continue;
308
+ entries[name] = bytes;
309
+ }
310
+ const model = adaptPrusaModel(modelText);
311
+ 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)));
313
+ const customGcodeBytes = zipEntries[PRUSA_CUSTOM_GCODE_PATH];
314
+ if (customGcodeBytes && customGcodeBytes.length <= MAX_AUX_BYTES) {
315
+ const orca = convertCustomGcodes(utf8Decoder.decode(customGcodeBytes));
316
+ if (orca) {
317
+ entries[ORCA_CUSTOM_GCODE_PATH] = utf8Encoder.encode(orca.xml);
318
+ if (orca.colorChanges > 0) {
319
+ warnings.push(` note: ${orca.colorChanges} color change(s) at set heights become pauses at the same heights: the U1 pauses there (M600) for the filament swap, as PrusaSlicer's color change means. The new colors aren't shown in the preview.`);
320
+ }
321
+ }
322
+ }
323
+ const layerHeightsBytes = zipEntries[PRUSA_LAYER_HEIGHTS_PATH];
324
+ if (layerHeightsBytes && layerHeightsBytes.length <= MAX_AUX_BYTES) {
325
+ const orca = convertLayerHeights(utf8Decoder.decode(layerHeightsBytes), prusaObjects.map((o) => o.id));
326
+ if (orca)
327
+ entries[ORCA_LAYER_HEIGHTS_PATH] = utf8Encoder.encode(orca);
328
+ }
329
+ if (zipEntries[PRUSA_LAYER_RANGES_PATH]) {
330
+ warnings.push(" WARN: this project's layer-range settings (settings for a range of heights of an object) aren't carried yet.");
331
+ }
332
+ return {
333
+ source: "prusaslicer",
334
+ zipEntries: entries,
335
+ request: { projectSettings: converted.settings, objects },
336
+ warnings,
337
+ unpackedBytes,
338
+ };
339
+ },
340
+ };
@@ -0,0 +1,25 @@
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
+ import type { PrusaObject, PrusaVolume } from "./modelConfig.js";
15
+ export interface SplitPart {
16
+ /** The new mesh object's id. */
17
+ id: number;
18
+ volume: PrusaVolume;
19
+ }
20
+ export interface SplitResult {
21
+ text: string;
22
+ /** For each object that was split, its parts in volume order. */
23
+ parts: Map<number, SplitPart[]>;
24
+ }
25
+ export declare function splitMultiPartObjects(text: string, objects: readonly PrusaObject[], warnings: string[]): SplitResult;
@@ -0,0 +1,77 @@
1
+ /** Past this, the split is skipped and the object kept as one part: the tag arrays would be the memory problem. */
2
+ const MAX_TRIANGLES = 4_000_000;
3
+ 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)
10
+ 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];
15
+ }
16
+ from = start + 1;
17
+ }
18
+ }
19
+ function renumber(tag, map) {
20
+ return tag.replace(/\b(v[123])="(\d+)"/g, (_, name, index) => `${name}="${map[Number(index)]}"`);
21
+ }
22
+ export function splitMultiPartObjects(text, objects, warnings) {
23
+ const parts = new Map();
24
+ let nextId = 0;
25
+ for (const m of text.matchAll(/<object id="(\d{1,9})"/g))
26
+ nextId = Math.max(nextId, Number(m[1]));
27
+ nextId++;
28
+ for (const object of objects) {
29
+ if (object.volumes.length < 2)
30
+ continue;
31
+ const bounds = objectBounds(text, object.id);
32
+ if (!bounds)
33
+ continue;
34
+ const block = text.slice(bounds[0], bounds[1]);
35
+ if (block.includes("<component"))
36
+ 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) {
49
+ 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
+ continue;
51
+ }
52
+ const map = new Int32Array(vertices.length).fill(-1);
53
+ const pieces = [];
54
+ const split = [];
55
+ for (const volume of object.volumes) {
56
+ const id = nextId++;
57
+ map.fill(-1);
58
+ const ownVertices = [];
59
+ const ownTriangles = [];
60
+ 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]);
65
+ }
66
+ }
67
+ ownTriangles.push(renumber(triangles[t], map));
68
+ }
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"));
70
+ split.push({ id, volume });
71
+ }
72
+ 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])}`;
74
+ parts.set(object.id, split);
75
+ }
76
+ return { text, parts };
77
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A source reader turns one slicer family's project files into the one shape
3
+ * the rest of the converter works on: the conversion request (the project's
4
+ * settings in Snapmaker Orca's keys, plus every top-level object's bounding
5
+ * box, plate and name) and the zip entries laid out the way the writer expects
6
+ * (the Bambu Studio family's layout: `Metadata/project_settings.config`,
7
+ * `Metadata/model_settings.config`, `3D/3dmodel.model`). Everything after a
8
+ * reader, the pipeline and the writer, is the same for every source.
9
+ *
10
+ * Readers are tried in order; the first whose `detect` says yes reads the file.
11
+ */
12
+ import type { ConvertRequest } from "../schema.js";
13
+ /** The slicer family a project came from. */
14
+ export type SourceFormat = "bambu-family" | "prusaslicer";
15
+ export interface ParsedProject {
16
+ /** Which reader read the file. */
17
+ source: SourceFormat;
18
+ /** The full decompressed source zip, kept for applyConvertResponse's final reassembly. */
19
+ zipEntries: Record<string, Uint8Array>;
20
+ /** The conversion request payload. */
21
+ request: ConvertRequest;
22
+ /** Non-fatal notes collected while parsing (e.g. tolerantJsonParse's trailing-content note), for surfacing in the UI. */
23
+ warnings: string[];
24
+ /** The project's unpacked size, every entry together. */
25
+ unpackedBytes: number;
26
+ }
27
+ export interface ReadContext {
28
+ /** The project's unpacked size, every entry together (already checked against the cap). */
29
+ unpackedBytes: number;
30
+ /** Where the reader appends its non-fatal notes; may already hold the size warning. */
31
+ warnings: string[];
32
+ }
33
+ export interface SourceReader {
34
+ readonly format: SourceFormat;
35
+ /** Whether these zip entries are this reader's format. Cheap: a look at which files exist. */
36
+ detect(entries: Record<string, Uint8Array>): boolean;
37
+ /**
38
+ * Reads the project. Throws an `Any2orcaError` (`invalid_file`, `invalid_project`) for a file of this format
39
+ * that can't be read; never for a file of another format, which `detect` has already said no to.
40
+ */
41
+ read(entries: Record<string, Uint8Array>, context: ReadContext): ParsedProject;
42
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/stamp.d.ts CHANGED
@@ -22,6 +22,13 @@ export declare const OutputStampSchema: z.ZodObject<{
22
22
  tracks: z.ZodString;
23
23
  }, z.core.$strict>;
24
24
  profileId: z.ZodString;
25
+ source: z.ZodOptional<z.ZodObject<{
26
+ format: z.ZodEnum<{
27
+ "bambu-family": "bambu-family";
28
+ prusaslicer: "prusaslicer";
29
+ }>;
30
+ slicerVersion: z.ZodOptional<z.ZodString>;
31
+ }, z.core.$strict>>;
25
32
  options: z.ZodObject<{
26
33
  highFlowHotends: z.ZodUnion<readonly [z.ZodBoolean, z.ZodArray<z.ZodBoolean>]>;
27
34
  hardenedNozzles: z.ZodBoolean;
package/dist/stamp.js CHANGED
@@ -43,6 +43,14 @@ export const OutputStampSchema = z
43
43
  })
44
44
  .strict(),
45
45
  profileId: z.string(),
46
+ /** The source project's format and the slicer version that saved it. Absent in files written before this field: the Bambu Studio family. */
47
+ source: z
48
+ .object({
49
+ format: z.enum(["bambu-family", "prusaslicer"]),
50
+ slicerVersion: z.string().max(64).optional(),
51
+ })
52
+ .strict()
53
+ .optional(),
46
54
  options: z
47
55
  .object({
48
56
  highFlowHotends: HighFlowHotendsSchema,
@@ -69,6 +77,8 @@ const StampReadSchema = z.object({
69
77
  version: noteText(64),
70
78
  profiles: z.object({ version: noteText(64), tracks: noteText(200) }),
71
79
  profileId: noteText(64),
80
+ // Added with the PrusaSlicer reader; absent means the Bambu Studio family.
81
+ source: z.object({ format: z.enum(["bambu-family", "prusaslicer"]), slicerVersion: noteText(64).optional() }).optional(),
72
82
  options: z.object({
73
83
  highFlowHotends: HighFlowHotendsSchema,
74
84
  // Added after the first stamps were written; absent means the stock stainless nozzles.
@@ -90,11 +100,12 @@ export function decodeStamp(bytes) {
90
100
  const parsed = StampReadSchema.safeParse(JSON.parse(new TextDecoder().decode(bytes)));
91
101
  if (!parsed.success)
92
102
  return null;
93
- const { stamp, generator, version, profiles, profileId, options } = parsed.data;
103
+ const { stamp, generator, version, profiles, profileId, source, options } = parsed.data;
94
104
  return {
95
105
  stamp,
96
106
  generator,
97
107
  version,
108
+ ...(source ? { source: { format: source.format, ...(source.slicerVersion !== undefined ? { slicerVersion: source.slicerVersion } : {}) } } : {}),
98
109
  profiles: { version: profiles.version, tracks: profiles.tracks },
99
110
  profileId,
100
111
  options: {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.4.1";
1
+ export declare const VERSION = "0.6.0";
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.4.1";
3
+ export const VERSION = "0.6.0";
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "any2orca",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
+ "outputAffecting": "six more PrusaSlicer settings are carried; converted PrusaSlicer files change, Bambu-family files don't",
4
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.",
5
6
  "keywords": [
6
7
  "3mf",