any2orca 0.13.0 → 0.14.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,312 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * A problem report someone can copy into a bug report: what was converted, with what, for what, and what came of
4
+ * it, as plain text. Nothing is sent anywhere; the function only builds the text.
5
+ *
6
+ * It holds nothing that identifies the file or its owner: no file name, no object or plate names, no paths, no
7
+ * error message or stack. What a file can carry in a name or a value never goes in as it is:
8
+ *
9
+ * - Preset names (filaments, the process preset) are short, plain, and cut at a "(...3mf)" suffix, which is where
10
+ * Bambu Studio puts the project file's name on an edited preset; a name that still holds a file name is left out.
11
+ * - A note's text is included only when it matches one of the wordings in {@link PLAIN_NOTES}, whose variable parts
12
+ * are numbers, plate, object and filament numbers, Snapmaker Orca's own setting names and this conversion's
13
+ * preset names. Any other note is listed by its topic alone. A wording changed in a later release stops matching
14
+ * and falls back to its topic: the safe side.
15
+ */
16
+ import { SETTINGS_CATALOG } from "./diff/settingsCatalog.js";
17
+ import { Any2orcaError } from "./errors.js";
18
+ import { plainText } from "./plainText.js";
19
+ import { VERSION } from "./version.js";
20
+ const MAX_NAME = 80;
21
+ /** A preset name as the report may show it, or null when it can't be shown. */
22
+ function presetName(name) {
23
+ if (typeof name !== "string")
24
+ return null;
25
+ // Bambu Studio names an edited preset after the project file: "Bambu PLA Basic @BBL X1C(my-model.3mf)".
26
+ const cut = plainText(name).replace(/\s*\([^()]*\.3mf\)\s*$/i, "").trim().slice(0, MAX_NAME);
27
+ if (cut === "" || /\.(3mf|stl|step|stp|obj|zip|gcode)\b/i.test(cut) || /[\\/]/.test(cut.replace(/ \/ /g, " ")))
28
+ return null;
29
+ return cut;
30
+ }
31
+ /** A short plain value the file gives about itself (a version, a printer model): letters, digits and a little punctuation only. */
32
+ function plainFact(value, max = 60) {
33
+ if (typeof value !== "string")
34
+ return null;
35
+ const text = plainText(value).trim().slice(0, max);
36
+ return /^[A-Za-z0-9][A-Za-z0-9 .+_()-]*$/.test(text) && !/\.(3mf|stl|step|stp|obj|zip|gcode)\b/i.test(text) ? text : null;
37
+ }
38
+ /** A material as written, when it reads like one ("PLA", "PETG-CF", "PA6-GF"); otherwise "other". */
39
+ function material(type) {
40
+ return /^[A-Za-z0-9][A-Za-z0-9+ -]{0,15}$/.test(type) ? type : "other";
41
+ }
42
+ // --- Notes whose text can't quote the file ------------------------------------------------------------------------
43
+ const N = String.raw `\d+(?:\.\d+)?`;
44
+ const PRESET = String.raw `\u0001\d+\u0002`;
45
+ const PIECES = {
46
+ n: N,
47
+ list: String.raw `\d+(?:, \d+)*(?: and \d+)?`,
48
+ key: String.raw `[a-z][a-z0-9_]{1,80}`,
49
+ keys: String.raw `[a-z][a-z0-9_]{1,80}(?:, [a-z][a-z0-9_]{1,80})*(?: and \d+ more)?`,
50
+ preset: PRESET,
51
+ presets: String.raw `${PRESET}(?:, ${PRESET})*`,
52
+ version: String.raw `\d+(?:\.\d+){1,3}`,
53
+ sizes: String.raw `${N}(?:, ${N})*(?: and ${N})? mm`,
54
+ onsizes: String.raw `filament \d+ on ${N} mm(?:, filament \d+ on ${N} mm)*`,
55
+ size: String.raw `\d+(?:\.\d+)? [MG]B`,
56
+ unit: String.raw `mm/s²?|mm³/s|mm`,
57
+ // A filament preset's changed settings, as filamentNotes words them: a setting it names, and two numbers with its unit.
58
+ changes: (() => {
59
+ const item = String.raw `(?:nozzle temperature|first-layer nozzle temperature|flow ratio|max volumetric speed|pressure advance|retraction length|bed temperature \((?:smooth|textured) PEI\)|max fan speed) -?[\d.]{1,12}(?: °C| mm³/s| mm|%)? → -?[\d.]{1,12}(?: °C| mm³/s| mm|%)?`;
60
+ return String.raw `(?:${item}(?:, ${item})*(?: and ${item})?(?:, and \d+ other settings?)?|\d+ other settings?)`;
61
+ })(),
62
+ };
63
+ /**
64
+ * The wordings whose text goes into a report, as the notes read (a capital at the start, a period at the end).
65
+ * `{n}` is a number, `{list}` numbers ("1, 2 and 3"), `{key}` and `{keys}` Snapmaker Orca setting names (checked
66
+ * against its settings), `{preset}` one of this conversion's own preset names, `{a|b}` one of the words given.
67
+ */
68
+ export const PLAIN_NOTES = [
69
+ // Which filaments each plate uses.
70
+ "Plate {n} needs {n} filaments at the same height (it uses {filament|filaments} {list}), and the U1 prints with {n} at a time, so it can't print as it is. In Snapmaker Orca, move some of its objects to another plate or use fewer filaments on it.",
71
+ "Plate {n} uses {n} filaments ({filament|filaments} {list}), no more than {n} at the same height. The U1 prints with {n} at a time, so this plate needs filament changes at pauses, which you set up in Snapmaker Orca.",
72
+ "Plate {n} uses {filament|filaments} {list}.",
73
+ "Check {plate|plates} {list} before printing. Snapmaker Orca {version} can skip {filament|filaments} {list} on some layers when {filament|filaments} {list} {is|are} on the same plate, and it gives no warning. Look through the sliced preview for missing color. To avoid the problem, print {the two|each pair} on separate plates, or give {filament|filaments} {list} {a number|numbers} from 1 to {n} in Snapmaker Orca.",
74
+ // Plates and placement.
75
+ "Plate {n} has no objects in the project; it stays empty, so the other plates keep their numbers.",
76
+ "Plate {n}'s spacing was clamped to {n}x (ideally {n}x) to keep every object on the bed, so objects on this plate may be closer together than the Snapmaker U1's clearance radius calls for. Review spacing on this plate manually before printing.",
77
+ "Plate {n}'s objects were pulled together to fit the target bed, and object {n} and object {n} are touching or overlapping as a result (tolerance {n}mm). Review spacing on this plate before printing.",
78
+ "Plate {n}'s objects were pulled together to fit the target bed, and object {n} and object {n} are only {n}mm apart as a result (tolerance {n}mm). Review spacing on this plate before printing.",
79
+ "Plate {n}'s combined footprint ({n} x {n} mm) is larger than the usable printable area ({n} x {n} mm, keeping a {n}mm margin from the {n} x {n} mm bed's edge) by {n}mm in {X|Y} -- some objects will be positioned outside the printable area even when centered. Split this plate or rearrange/scale down the objects before converting.",
80
+ "Plate {n}'s combined footprint ({n} x {n} mm) is larger than the usable printable area ({n} x {n} mm, keeping a {n}mm margin from the {n} x {n} mm bed's edge) by {n}mm in X and by {n}mm in Y -- some objects will be positioned outside the printable area even when centered. Split this plate or rearrange/scale down the objects before converting.",
81
+ "The project's {n} beds become {n} plates.",
82
+ // The nozzle size and the profile.
83
+ "The creator's project is set up for a {n} mm nozzle; converted for your {n} mm nozzles (choose {n} mm if your U1 has them).",
84
+ "The creator's project uses {sizes} nozzles; Snapmaker Orca allows one size for all four toolheads, so the whole file is for {n} mm.",
85
+ "The creator's project uses {sizes} nozzles; converted for your {n} mm nozzles, since Snapmaker Orca allows one size for all four toolheads.",
86
+ "The creator's project uses {sizes} nozzles ({onsizes}); converted for your {n} mm nozzles, since Snapmaker Orca allows one size for all four toolheads.",
87
+ "The source file doesn't give a usable nozzle size; converted for your {n} mm nozzles.",
88
+ "The source file doesn't give a usable nozzle size, so the default profile is used.",
89
+ "The source file is set up for a {n} mm nozzle, which has no U1 profile; the {n} mm profile is used.",
90
+ "The U1 has no {n} mm profile for this nozzle size, so your file's {n} mm layer height was kept, on the closest profile ({n} mm).",
91
+ "Your file's {n} mm layer height is outside what the U1 supports for this nozzle size, so it was set to {n} mm, on the closest profile ({n} mm).",
92
+ "High-flow hotends were requested, but Snapmaker has no high-flow option for this nozzle size (only 0.4 mm), so the project is set up for standard hotends.",
93
+ "This profile has no separate high-flow speeds in Snapmaker's presets, so it uses its normal speeds; the selected toolheads are still set to the Liber High Flow Hotend.",
94
+ // Settings.
95
+ "No changed print settings were marked in this file. If the printer profile was switched in the slicer without re-applying the settings afterward, they may not have carried over.",
96
+ "Filament max volumetric speed lowered to at most {n} mm³/s, Snapmaker's value for its fastest U1 filament. Raise it in Snapmaker Orca if your filament can melt faster.",
97
+ "Filament max volumetric speed lowered to at most {n} mm³/s ({n} mm³/s on a high-flow toolhead), Snapmaker's value for its fastest U1 filament. Raise it in Snapmaker Orca if your filament can melt faster.",
98
+ "{key} lowered to {n} {unit}, the U1's machine limit.",
99
+ "{key} has {n} values for {n} filaments in the source file, so Snapmaker's stock value is used for it.",
100
+ "{n} filament settings have {n} values for {n} filaments in the source file, so Snapmaker's stock values are used for them: {keys}.",
101
+ "{key} has {n} values for {n} filaments in the source file; the first {n} are used.",
102
+ "{n} filament settings have {n} values for {n} filaments in the source file; the first {n} of each are used: {keys}.",
103
+ "The source file has no filament_colour list, so its filament settings aren't carried over.",
104
+ // Reading the file.
105
+ "This is a large project ({size} unpacked). Converting it takes a minute or two and a few GB of memory; close other apps or tabs if your computer has little memory.",
106
+ "{n} filament color(s) taken from the printer's extruder colors, which are what PrusaSlicer shows for this project.",
107
+ "{n} 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.",
108
+ "This project's layer-range settings (settings for a range of heights of an object) aren't carried yet.",
109
+ // Filament presets.
110
+ "{Filament|Filaments} {list} {uses|use} {preset}'s own settings, which match the creator's.",
111
+ "{Filament|Filaments} {list} {uses|use} {preset}'s own settings instead of the creator's: {changes}.",
112
+ "{Filament|Filaments} {list} {was|were} tuned for a {n} mm nozzle on the creator's printer; converted {for your|with the U1's} {n} mm {nozzles|profile}, {it takes|they take} the U1's calibration for {its material|their materials} from {presets} (flow, max volumetric speed, pressure advance, retraction, cooling) and {keeps|keep} the creator's temperatures and other filament facts. The colors are unchanged, so a preset of your own can be chosen in Snapmaker Orca.",
113
+ ];
114
+ function escapeRegExp(text) {
115
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
116
+ }
117
+ /** A wording as a pattern that matches the whole note. */
118
+ function wordingPattern(wording) {
119
+ let source = "";
120
+ let at = 0;
121
+ for (const m of wording.matchAll(/\{([^{}]*)\}/g)) {
122
+ source += escapeRegExp(wording.slice(at, m.index));
123
+ const inner = m[1];
124
+ source += Object.hasOwn(PIECES, inner) ? `(?:${PIECES[inner]})` : `(?:${inner.split("|").map(escapeRegExp).join("|")})`;
125
+ at = m.index + m[0].length;
126
+ }
127
+ return new RegExp(`^${source}${escapeRegExp(wording.slice(at))}$`);
128
+ }
129
+ const PLAIN_PATTERNS = PLAIN_NOTES.map(wordingPattern);
130
+ /** Setting-like words in a note (they have an underscore) must be Snapmaker Orca's own: a file can name a setting anything. */
131
+ function onlyKnownSettings(text) {
132
+ return (text.match(/\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b/g) ?? []).every((word) => Object.hasOwn(SETTINGS_CATALOG, word) || word === "filament_colour");
133
+ }
134
+ /**
135
+ * A note's text as the report may show it, or null when it could quote the file. `presets` are this conversion's
136
+ * preset names as the file has them; in the text each is replaced by its form for the report.
137
+ */
138
+ function plainNoteText(note, presets) {
139
+ // The conversion's own preset names become markers, longest first, so a name inside a longer one doesn't split it.
140
+ const names = [...new Set(presets.filter((name) => name.length >= 3))].sort((a, b) => b.length - a.length);
141
+ let marked = note.text;
142
+ if (/[\u0001\u0002]/.test(marked))
143
+ return null;
144
+ names.forEach((name, i) => {
145
+ marked = marked.split(name).join(`\u0001${i}\u0002`);
146
+ });
147
+ if (!PLAIN_PATTERNS.some((pattern) => pattern.test(marked)) || !onlyKnownSettings(marked))
148
+ return null;
149
+ let shown = true;
150
+ const text = marked.replace(/\u0001(\d+)\u0002/g, (_, i) => {
151
+ const name = presetName(names[Number(i)]);
152
+ if (name === null)
153
+ shown = false;
154
+ return name ?? "";
155
+ });
156
+ return shown ? text : null;
157
+ }
158
+ // --- Where it ran ---------------------------------------------------------------------------------------------------
159
+ const SYSTEMS = [
160
+ [/Windows/i, "Windows"],
161
+ [/Android/i, "Android"],
162
+ [/iPhone|iPad|iPod/i, "iOS"],
163
+ [/Mac OS X|Macintosh|macOS/i, "macOS"],
164
+ [/CrOS/i, "ChromeOS"],
165
+ [/Linux/i, "Linux"],
166
+ ];
167
+ const BROWSERS = [
168
+ [/\bEdg(?:e|A|iOS)?\/(\d{1,4})/, "Edge"],
169
+ [/\bOPR\/(\d{1,4})/, "Opera"],
170
+ [/\bFirefox\/(\d{1,4})/, "Firefox"],
171
+ [/\bChrome\/(\d{1,4})/, "Chrome"],
172
+ [/\bVersion\/(\d{1,4})[\d.]* (?:Mobile\/\S+ )?Safari\//, "Safari"],
173
+ ];
174
+ /**
175
+ * A browser and system from a user agent string: the browser's name and major version, and the system's name.
176
+ * Nothing else of the string is kept; one that names no browser this knows gives "a browser".
177
+ */
178
+ export function describeUserAgent(userAgent) {
179
+ const ua = String(userAgent).slice(0, 1000);
180
+ const system = SYSTEMS.find(([pattern]) => pattern.test(ua))?.[1];
181
+ for (const [pattern, name] of BROWSERS) {
182
+ const version = pattern.exec(ua)?.[1];
183
+ if (version)
184
+ return `${name} ${version}${system ? ` on ${system}` : ""}`;
185
+ }
186
+ return `a browser${system ? ` on ${system}` : ""}`;
187
+ }
188
+ const NODE_SYSTEMS = { darwin: "macOS", win32: "Windows", linux: "Linux" };
189
+ /**
190
+ * Where this code is running, in a few words: "Node 22.12.0 on macOS (arm64)" or "Chrome 131 on Windows". Reads only
191
+ * the runtime's own version and system name; makes no request.
192
+ */
193
+ export function describeEnvironment() {
194
+ const node = globalThis.process;
195
+ if (node?.versions?.node) {
196
+ const system = NODE_SYSTEMS[node.platform ?? ""] ?? plainFact(node.platform, 20) ?? "an unknown system";
197
+ const arch = plainFact(node.arch, 20);
198
+ return `Node ${plainFact(node.versions.node, 20) ?? "?"} on ${system}${arch ? ` (${arch})` : ""}`;
199
+ }
200
+ const userAgent = globalThis.navigator?.userAgent;
201
+ return typeof userAgent === "string" ? describeUserAgent(userAgent) : "an unknown runtime";
202
+ }
203
+ // --- The report -----------------------------------------------------------------------------------------------------
204
+ /** "1, 2 and 3". */
205
+ const list = (items) => (items.length <= 1 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`);
206
+ function optionsLine(options) {
207
+ const highFlow = options.highFlowHotends;
208
+ const toolheads = Array.isArray(highFlow) ? highFlow.flatMap((on, i) => (on === true ? [i + 1] : [])).slice(0, 16) : [];
209
+ const keys = (names) => (names ?? []).filter((k) => typeof k === "string" && Object.hasOwn(SETTINGS_CATALOG, k)).slice(0, 40);
210
+ const keep = keys(options.aboveStock?.keep);
211
+ const stock = keys(options.aboveStock?.stock);
212
+ return [
213
+ `nozzle ${options.nozzle !== undefined && /^(\d{1,2}(\.\d{1,3})?|match)$/.test(options.nozzle) ? options.nozzle : "default"}`,
214
+ `Snapmaker Orca ${options.snapmakerOrcaVersion !== undefined && /^\d+(\.\d+){1,3}$/.test(options.snapmakerOrcaVersion) ? options.snapmakerOrcaVersion : "newest"}`,
215
+ `profile ${options.profileId !== undefined && /^[a-z0-9][a-z0-9.-]{0,80}$/.test(options.profileId) ? `${options.profileId} (chosen)` : "matched"}`,
216
+ `filament names ${options.filamentComplianceMode === "generic" || options.filamentComplianceMode === "snapmaker" ? options.filamentComplianceMode : "original"}`,
217
+ `high flow ${highFlow === true ? "all toolheads" : toolheads.length > 0 ? `toolheads ${list(toolheads)}` : "none"}`,
218
+ `hardened nozzles ${options.hardenedNozzles === true ? "yes" : "no"}`,
219
+ `version note ${options.stamp === false ? "off" : "on"}`,
220
+ `own preset ${options.preset === true ? "yes" : "no"}`,
221
+ ...(keep.length > 0 ? [`kept above stock: ${keep.join(", ")}`] : []),
222
+ ...(stock.length > 0 ? [`set to stock: ${stock.join(", ")}`] : []),
223
+ ].join("; ");
224
+ }
225
+ /** What went wrong, without the message: an Any2orcaError's code, or an unexpected error's kind. */
226
+ function errorFact(error) {
227
+ if (error instanceof Any2orcaError || (typeof error === "object" && error !== null && error.name === "Any2orcaError")) {
228
+ const code = error.code;
229
+ return typeof code === "string" && /^[a-z][a-z0-9_]{0,40}$/.test(code) ? code : "unknown code";
230
+ }
231
+ const name = typeof error === "object" && error !== null ? error.name : undefined;
232
+ return `unexpected (${typeof name === "string" && /^[A-Za-z][A-Za-z0-9]{0,40}$/.test(name) ? name : "not an Error"})`;
233
+ }
234
+ /**
235
+ * The problem report as text, one fact per line, ready to copy. Give it what you have: the inspection when the
236
+ * file opened, the report when the conversion finished, the error when it didn't. See the module comment for what
237
+ * never goes in.
238
+ */
239
+ export function problemReport(input) {
240
+ const { inspection, report, catalog } = input;
241
+ const lines = ["any2orca problem report", "(Text only. It holds no file name, object names or paths.)", ""];
242
+ const add = (label, value) => {
243
+ if (value)
244
+ lines.push(`${label}: ${value}`);
245
+ };
246
+ add("any2orca", VERSION);
247
+ const tracks = catalog ? `${catalog.index.slicer.name} ${catalog.index.slicer.version}` : report?.stamp?.profiles.tracks;
248
+ const dataVersion = catalog?.index.dataVersion ?? report?.stamp?.profiles.version;
249
+ add("Profile data", dataVersion ? `${plainFact(dataVersion, 20) ?? "?"}${tracks ? `, for ${plainFact(tracks, 40) ?? "?"}` : ""}` : null);
250
+ add("App", input.app !== undefined ? (plainFact(input.app, 80) ?? "(not shown: not plain text)") : null);
251
+ add("Ran on", plainText(input.environment ?? describeEnvironment()).slice(0, 80));
252
+ if (inspection) {
253
+ const stampFormat = report?.stamp?.source?.format;
254
+ add("Source", [
255
+ stampFormat ? `${plainFact(stampFormat, 30) ?? "?"} project` : null,
256
+ inspection.slicerVersion ? `slicer version ${plainFact(inspection.slicerVersion, 30) ?? "(not shown)"}` : null,
257
+ inspection.printerModel ? `printer ${presetName(inspection.printerModel) ?? "(not shown)"} (${plainFact(inspection.sourceVendor, 20) ?? "other"})` : `printer maker ${plainFact(inspection.sourceVendor, 20) ?? "other"}`,
258
+ inspection.sourcePresetName ? `process preset ${presetName(inspection.sourcePresetName) ?? "(not shown)"}` : null,
259
+ ]
260
+ .filter(Boolean)
261
+ .join("; "));
262
+ const plateCount = inspection.plateCount ?? inspection.plates.length;
263
+ const sizes = inspection.nozzleDiameters ?? [];
264
+ add("Project", [
265
+ `${plateCount} plate${plateCount === 1 ? "" : "s"}${inspection.plates.length < plateCount ? ` (${inspection.plates.length} with objects)` : ""}`,
266
+ `${inspection.objects.length} object${inspection.objects.length === 1 ? "" : "s"}`,
267
+ `${inspection.filaments.length} filament${inspection.filaments.length === 1 ? "" : "s"}`,
268
+ `${inspection.unpackedBytes >= 1024 ** 2 ? `${(inspection.unpackedBytes / 1024 ** 2).toFixed(1)} MB` : `${Math.max(1, Math.round(inspection.unpackedBytes / 1024))} KB`} unpacked`,
269
+ sizes.length > 0 ? `nozzle ${sizes.map((s) => plainFact(s, 8) ?? "?").join(", ")} mm` : null,
270
+ inspection.layerHeight !== null ? `layer height ${inspection.layerHeight} mm` : null,
271
+ ]
272
+ .filter(Boolean)
273
+ .join("; "));
274
+ for (const filament of inspection.filaments.slice(0, 64)) {
275
+ const output = report?.filaments?.find((f) => f.slot === filament.slot)?.outputName;
276
+ const source = presetName(filament.presetName) ?? (filament.presetName ? "(name not shown)" : "(no preset name)");
277
+ const renamed = output !== undefined && output !== filament.presetName ? ` -> ${presetName(output) ?? "(name not shown)"}` : "";
278
+ lines.push(`Filament ${filament.slot}: ${material(filament.type)}, ${/^#[0-9A-Fa-f]{3,8}$/.test(filament.color) ? filament.color : "(color not shown)"}, ${source}${renamed}`);
279
+ }
280
+ if (inspection.filaments.length > 64)
281
+ lines.push(`(and ${inspection.filaments.length - 64} more filaments)`);
282
+ for (const plate of (report?.plateFilaments ?? inspection.plateFilaments ?? []).filter((p) => p.filaments.length > 0).slice(0, 100)) {
283
+ const objects = inspection.objects.filter((o) => (o.plate ?? 1) === plate.plate).length;
284
+ const uses = plate.filaments.map((f) => `${f.slot} (${f.uses.filter((u) => /^[a-z-]{1,20}$/.test(u)).join(", ")})`).join(", ");
285
+ lines.push(`Plate ${plate.plate}: ${objects} object${objects === 1 ? "" : "s"}; filaments ${uses}; most at the same height ${plate.mostAtOnce}`);
286
+ }
287
+ }
288
+ if (input.options)
289
+ add("Options", optionsLine(input.options));
290
+ // A report built by hand (a test's stand-in) may hold only some of its fields.
291
+ if (report?.profile) {
292
+ const match = report.profileMatch ? `matched, ${plainFact(report.profileMatch.matchSource, 30) ?? "?"}` : report.preset ? "from the preset" : "chosen";
293
+ add("Result", `converted with ${plainFact(report.profile.id, 80) ?? "?"} (${match}), for ${plainFact(report.nozzle?.size, 8) ?? "?"} mm nozzles${report.retiredProfile ? "; the profile asked for is retired" : ""}`);
294
+ add("What changed", (report.whatChanged?.groups ?? []).map((g) => `${plainFact(String(g.reason), 20) ?? "?"} ${g.items.length}`).join(", "));
295
+ }
296
+ else if (input.error !== undefined) {
297
+ add("Result", `error ${errorFact(input.error)}${input.stage !== undefined ? ` at ${plainFact(input.stage, 30) ?? "an unnamed step"}` : ""}`);
298
+ }
299
+ const notes = report?.notes ?? [];
300
+ if (notes.length > 0) {
301
+ const presets = [...(inspection?.filaments.map((f) => f.presetName) ?? []), ...(report?.filaments?.map((f) => f.outputName) ?? []), ...(report?.filamentPresets?.map((p) => p.preset) ?? [])];
302
+ lines.push(`Notes: ${notes.length}`);
303
+ for (const note of notes.slice(0, 200)) {
304
+ const topic = /^[a-z][a-z-]{0,30}$/.test(note.topic) ? note.topic : "other";
305
+ lines.push(` [${topic}] ${plainNoteText(note, presets) ?? "(text not included: it can quote a name or value from the file)"}`);
306
+ }
307
+ }
308
+ else if (report) {
309
+ lines.push("Notes: none");
310
+ }
311
+ return lines.join("\n");
312
+ }
@@ -73,6 +73,7 @@ export declare const ProfileIndexSchema: z.ZodObject<{
73
73
  name: z.ZodString;
74
74
  version: z.ZodString;
75
75
  application: z.ZodString;
76
+ sharedLayerFilamentLimit: z.ZodOptional<z.ZodNumber>;
76
77
  }, z.core.$strip>;
77
78
  source: z.ZodOptional<z.ZodObject<{
78
79
  repository: z.ZodString;
@@ -195,6 +196,8 @@ export interface ProfileIndex {
195
196
  name: string;
196
197
  version: string;
197
198
  application: string;
199
+ /** The release can leave a filament numbered above this out of some layers when the filament that many numbers below it prints on the same plate; see `ProfileCatalog.sharedLayerFilamentLimit`. Absent when it has no such limit. */
200
+ sharedLayerFilamentLimit?: number;
198
201
  };
199
202
  /** Where the profiles come from: the target slicer's repository and the release tag and commit they were generated at. */
200
203
  source?: {
@@ -311,6 +314,15 @@ export declare class ProfileCatalog {
311
314
  * release that allows mixed sizes says so in its catalog entry, which is where per-toolhead sizes would start.
312
315
  */
313
316
  get mixedNozzleSizes(): boolean;
317
+ /**
318
+ * The highest filament number this catalog's Snapmaker Orca release prints in every layer whatever else is on
319
+ * the plate, or null when the release has no such limit. Snapmaker Orca 2.4.0 and 2.4.1 can leave filament 17
320
+ * and up out of some layers, with no message, when the filament 16 numbers below it prints on the same plate
321
+ * (the key its tool order cache uses, read from each release's own source code when its profile data is
322
+ * generated), so for them this is 16; a release whose source no longer has that key gives null. `convert()`
323
+ * notes a plate that uses a filament above the limit together with the filament that many numbers below it.
324
+ */
325
+ get sharedLayerFilamentLimit(): number | null;
314
326
  list(filter?: {
315
327
  nozzleDiameter?: string;
316
328
  }): ProfileSummary[];
package/dist/profiles.js CHANGED
@@ -78,7 +78,13 @@ export const ProfileIndexSchema = z.object({
78
78
  schema: z.literal(1),
79
79
  dataVersion: VERSION,
80
80
  slicer: z
81
- .object({ name: NAME, version: VERSION, application: z.string().regex(APPLICATION_VALUE) })
81
+ .object({
82
+ name: NAME,
83
+ version: VERSION,
84
+ application: z.string().regex(APPLICATION_VALUE),
85
+ /** See {@link ProfileCatalog.sharedLayerFilamentLimit}. Absent when the release has no such limit. */
86
+ sharedLayerFilamentLimit: z.number().int().min(1).max(1024).optional(),
87
+ })
82
88
  // The Application value names the pinned release, so it can't disagree with it.
83
89
  .refine((s) => s.application.endsWith(`-${s.version}`), "slicer.application must end with the slicer version"),
84
90
  /** Where the profiles come from: the target slicer's repository and the release tag and commit they were generated at. */
@@ -258,6 +264,17 @@ export class ProfileCatalog {
258
264
  get mixedNozzleSizes() {
259
265
  return this.index.releases?.find((r) => r.path === ".")?.mixedNozzleSizes === true;
260
266
  }
267
+ /**
268
+ * The highest filament number this catalog's Snapmaker Orca release prints in every layer whatever else is on
269
+ * the plate, or null when the release has no such limit. Snapmaker Orca 2.4.0 and 2.4.1 can leave filament 17
270
+ * and up out of some layers, with no message, when the filament 16 numbers below it prints on the same plate
271
+ * (the key its tool order cache uses, read from each release's own source code when its profile data is
272
+ * generated), so for them this is 16; a release whose source no longer has that key gives null. `convert()`
273
+ * notes a plate that uses a filament above the limit together with the filament that many numbers below it.
274
+ */
275
+ get sharedLayerFilamentLimit() {
276
+ return this.index.slicer.sharedLayerFilamentLimit ?? null;
277
+ }
261
278
  list(filter = {}) {
262
279
  const { nozzleDiameter } = filter;
263
280
  return this.summaries.filter((s) => nozzleDiameter === undefined || s.nozzleDiameter === nozzleDiameter).map((s) => ({ ...s }));
package/dist/project.d.ts CHANGED
@@ -4,6 +4,7 @@ import { type WhatChanged } from "./explain/whatChanged.js";
4
4
  import { cleanWarnings, type ConvertNote } from "./explain/notes.js";
5
5
  export { cleanWarnings };
6
6
  import { type Inspection } from "./inspect.js";
7
+ import { type PlateFilaments } from "./archive/plateFilaments.js";
7
8
  import { ProfileCatalog, type ProfileSource, type ProfileSummary, type RetiredProfile } from "./profiles.js";
8
9
  import { type ProfileMatch, type Shifts } from "./schema.js";
9
10
  import { type AboveStockChoice } from "./engine/aboveStock.js";
@@ -156,6 +157,13 @@ export interface ConvertReport {
156
157
  plateOrigins?: Record<number, [number, number]>;
157
158
  /** The plates in the converted file, empty ones included. */
158
159
  plates: number;
160
+ /**
161
+ * The filaments each plate of the converted file uses, one entry per plate in order, empty plates included: what
162
+ * to load for it, and whether it needs more at the same height than the U1 has toolheads (`mostAtOnce`; `notes`
163
+ * says so in words). As `inspection.plateFilaments`, read by the converted project's settings. Always set by
164
+ * `convert()`; optional so code that builds a report itself (a test's mock) needn't.
165
+ */
166
+ plateFilaments?: PlateFilaments[];
159
167
  objects: number;
160
168
  filamentSlots: number;
161
169
  /**
@@ -226,12 +234,19 @@ export declare function matchProfile(projectSettings: Record<string, unknown>, p
226
234
  export declare class Project {
227
235
  private readonly parsed;
228
236
  private readonly request;
237
+ private partPaint?;
238
+ private sourcePlateFilaments?;
229
239
  private constructor();
230
240
  /** Reads a .3mf. Throws {@link Any2orcaError} (`invalid_file`, `too_large` or `invalid_project`) if it can't be used. */
231
241
  static open(bytes: Uint8Array, options?: OpenOptions): Project;
232
242
  /** The project's own settings (Metadata/project_settings.config), as a copy: for a settings diff. */
233
243
  settings(): Record<string, unknown>;
234
244
  inspect(): Inspection;
245
+ /**
246
+ * The filaments each plate uses, read by `projectSettings`: the source's for what the creator's file says, a
247
+ * converted project's for what the U1 prints. The meshes' paint is scanned once, on first use.
248
+ */
249
+ private plateFilaments;
235
250
  /** The profile auto-matching would pick for this file, for the user's nozzle size (`options.nozzle`, default 0.4). */
236
251
  matchProfile(profiles: ProfileSource | ProfileCatalog, options?: {
237
252
  nozzle?: NozzleChoice;
package/dist/project.js CHANGED
@@ -22,6 +22,8 @@ import { cleanWarnings, noteFrom, sortNotes } from "./explain/notes.js";
22
22
  export { cleanWarnings };
23
23
  import { filamentPresetNotes } from "./explain/filamentNotes.js";
24
24
  import { inspectProject } from "./inspect.js";
25
+ import { filamentCountOf, readPartPaint, readPlateFilaments } from "./archive/plateFilaments.js";
26
+ import { plateFilamentNotes, sharedLayerFilamentNote } from "./explain/plateNotes.js";
25
27
  import { catalogEngine, loadCatalog, ProfileCatalog } from "./profiles.js";
26
28
  import { ConvertRequestSchema, ConvertResponseSchema, HighFlowHotendsSchema, } from "./schema.js";
27
29
  import { resolveAboveStockChoice } from "./engine/aboveStock.js";
@@ -174,6 +176,8 @@ function describeIssues(issues) {
174
176
  export class Project {
175
177
  parsed;
176
178
  request;
179
+ partPaint;
180
+ sourcePlateFilaments;
177
181
  constructor(parsed, request) {
178
182
  this.parsed = parsed;
179
183
  this.request = request;
@@ -206,7 +210,23 @@ export class Project {
206
210
  return structuredClone(this.request.projectSettings);
207
211
  }
208
212
  inspect() {
209
- return inspectProject(this.request.projectSettings, this.request.objects, this.parsed.warnings, this.parsed.unpackedBytes, this.parsed.sourcePlateOrigins, this.request.plateCount);
213
+ this.sourcePlateFilaments ??= this.plateFilaments(this.request.projectSettings);
214
+ return inspectProject(this.request.projectSettings, this.request.objects, this.parsed.warnings, this.parsed.unpackedBytes, this.parsed.sourcePlateOrigins, this.request.plateCount, this.sourcePlateFilaments);
215
+ }
216
+ /**
217
+ * The filaments each plate uses, read by `projectSettings`: the source's for what the creator's file says, a
218
+ * converted project's for what the U1 prints. The meshes' paint is scanned once, on first use.
219
+ */
220
+ plateFilaments(projectSettings) {
221
+ this.partPaint ??= readPartPaint(this.parsed.zipEntries, this.request.objects, this.parsed.partPlacements, filamentCountOf(this.request.projectSettings));
222
+ return readPlateFilaments({
223
+ zipEntries: this.parsed.zipEntries,
224
+ projectSettings,
225
+ objects: this.request.objects,
226
+ partPlacements: this.parsed.partPlacements,
227
+ plateCount: Math.max(1, this.request.plateCount ?? 0),
228
+ paint: this.partPaint,
229
+ });
210
230
  }
211
231
  /** The profile auto-matching would pick for this file, for the user's nozzle size (`options.nozzle`, default 0.4). */
212
232
  matchProfile(profiles, options = {}) {
@@ -352,6 +372,15 @@ export class Project {
352
372
  const presetTopic = (slot) => (diameterSlots.has(slot) ? "filament-diameter" : nozzleSlots.has(slot) ? "nozzle" : "filament-presets");
353
373
  const presetNotes = filamentPresetNotes(response, presetTopic).map((n) => ({ topic: n.slots.length > 0 ? presetTopic(n.slots[0]) : "filament-presets", ...(n.slots.length > 0 ? { slots: n.slots } : {}), text: n.text }));
354
374
  const from = (topic, lines) => lines.flatMap((line) => noteFrom(topic, line) ?? []);
375
+ // Which filaments each plate uses, read by the converted project's settings: what the U1 prints. The printer's
376
+ // nozzle list has one entry per toolhead.
377
+ const plateFilaments = this.plateFilaments(response.projectSettings);
378
+ const nozzles = response.projectSettings.nozzle_diameter;
379
+ const toolheads = Array.isArray(nozzles) && nozzles.length > 0 ? nozzles.length : 4;
380
+ // First the release's own limit, where a plate runs into it: a filament can go missing from the print with no message.
381
+ const sharedLayerNote = sharedLayerFilamentNote(plateFilaments, catalog.sharedLayerFilamentLimit, `${catalog.index.slicer.name} ${catalog.index.slicer.version}`);
382
+ const plateNotes = [...(sharedLayerNote ? [sharedLayerNote] : []), ...plateFilamentNotes(plateFilaments, filamentCountOf(this.request.projectSettings), toolheads)];
383
+ const plateFilamentWarnings = plateNotes.filter((n) => n.warning).map((n) => ` WARN: ${n.text}`);
355
384
  const plateWarnings = new Set(pipeline.plateWarnings);
356
385
  const notes = sortNotes([
357
386
  ...routeNotes,
@@ -359,6 +388,9 @@ export class Project {
359
388
  ...presetNotes,
360
389
  ...from("source", this.parsed.warnings),
361
390
  ...from("settings", (pipeline.response.warnings ?? []).filter((w) => !plateWarnings.has(w))),
391
+ // What a plate's filaments mean for printing it is something to act on, so it has its own topic near the top;
392
+ // the plain lines of what each plate uses stay with the plates.
393
+ ...plateNotes.flatMap((n) => noteFrom(n.warning ? "plate-filaments" : "plates", n.text, n.slots) ?? []),
362
394
  ...from("plates", [...pipeline.plateWarnings, ...applyWarnings.filter((w) => w.includes("WARN"))]),
363
395
  ]);
364
396
  const inspection = this.inspect();
@@ -379,15 +411,17 @@ export class Project {
379
411
  profileNotes,
380
412
  ...(retiredProfile ? { retiredProfile } : {}),
381
413
  // A filament set to a U1 preset because of its diameter comes first: the user has to load other filament.
382
- warnings: cleanWarnings([...pipeline.leadWarnings, ...this.parsed.warnings, ...(response.warnings ?? []), ...applyWarnings.filter((w) => w.includes("WARN"))]),
414
+ // Then what a plate's filaments mean for printing it, ahead of the notes about settings.
415
+ warnings: cleanWarnings([...pipeline.leadWarnings, ...plateFilamentWarnings, ...this.parsed.warnings, ...(response.warnings ?? []), ...applyWarnings.filter((w) => w.includes("WARN"))]),
383
416
  notes,
384
- log: [...this.parsed.warnings, ...routeWarnings, ...pipeline.warnings, ...applyWarnings].map((w) => w.trim()).filter(Boolean),
417
+ log: [...this.parsed.warnings, ...routeWarnings, ...pipeline.warnings, ...plateFilamentWarnings, ...applyWarnings].map((w) => w.trim()).filter(Boolean),
385
418
  ...(response.filamentComplianceFallback ? { filamentComplianceFallback: response.filamentComplianceFallback } : {}),
386
419
  ...(response.filamentComplianceUnchanged ? { filamentComplianceUnchanged: response.filamentComplianceUnchanged } : {}),
387
420
  ...(response.filamentPresets ? { filamentPresets: response.filamentPresets } : {}),
388
421
  shifts: response.shifts,
389
422
  ...(response.plateOrigins ? { plateOrigins: Object.fromEntries(Object.entries(response.plateOrigins).map(([plate, origin]) => [Number(plate), origin])) } : {}),
390
423
  plates: Math.max(1, this.request.plateCount ?? 0, ...inspection.plates),
424
+ plateFilaments,
391
425
  objects: inspection.objects.length,
392
426
  filamentSlots: inspection.filaments.length,
393
427
  filaments,
@@ -59,8 +59,12 @@ export const bambuFamilyReader = {
59
59
  const plateCount = modelSettingsText ? Math.min(countPlates(modelSettingsText), MAX_OBJECTS) : 0;
60
60
  const objectMetadata = parseObjectMetadata(topModelText, modelSettingsText);
61
61
  const partFileCache = new Map();
62
+ const partPlacements = new Map();
62
63
  const objects = Object.entries(itemPositions).map(([id, fallbackXy]) => {
63
- const bbox = objectWorldBboxXY(id, topModelText, partFileCache, zipEntries);
64
+ const parts = [];
65
+ const bbox = objectWorldBboxXY(id, topModelText, partFileCache, zipEntries, parts);
66
+ if (parts.length > 0)
67
+ partPlacements.set(id, parts);
64
68
  const plate = plateAssignments[id];
65
69
  const meta = objectMetadata[id];
66
70
  return {
@@ -78,6 +82,7 @@ export const bambuFamilyReader = {
78
82
  request: { projectSettings: projectSettings, objects, ...(plateCount > 0 ? { plateCount } : {}) },
79
83
  warnings,
80
84
  unpackedBytes,
85
+ partPlacements,
81
86
  };
82
87
  },
83
88
  };
@@ -323,6 +323,7 @@ export const prusaReader = {
323
323
  // A wrapper object (an older PrusaSlicer's extra instance) has no config entry of its own: the mesh object's serves.
324
324
  const configFor = (id) => byId.get(id) ?? components.get(id)?.map((c) => byId.get(c)).find((o) => o !== undefined);
325
325
  const partFileCache = new Map();
326
+ const partPlacements = new Map();
326
327
  // PrusaSlicer 2.9 can place objects on several beds, virtual copies of the printer's bed on a grid; each becomes a
327
328
  // plate. An older project has one bed. An object on no bed (off every one) stays on plate 1, with a warning.
328
329
  const version = ini.version ? (/^\d+\.\d+\.\d+/.exec(ini.version)?.[0] ?? null) : null;
@@ -330,7 +331,10 @@ export const prusaReader = {
330
331
  const bed = severalBeds ? parseBedShape(ini.settings.get("bed_shape")) : null;
331
332
  const plateOf = new Map();
332
333
  const objects = Object.entries(itemPositions).map(([id, fallbackXy]) => {
333
- const bbox = objectWorldBboxXY(id, modelText, partFileCache, zipEntries);
334
+ const parts = [];
335
+ const bbox = objectWorldBboxXY(id, modelText, partFileCache, zipEntries, parts);
336
+ if (parts.length > 0)
337
+ partPlacements.set(id, parts);
334
338
  const name = configFor(Number(id))?.name;
335
339
  let plate = 1;
336
340
  if (bed) {
@@ -403,6 +407,7 @@ export const prusaReader = {
403
407
  warnings,
404
408
  unpackedBytes,
405
409
  ...(sourcePlateOrigins ? { sourcePlateOrigins } : {}),
410
+ partPlacements,
406
411
  };
407
412
  },
408
413
  };
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * Readers are tried in order; the first whose `detect` says yes reads the file.
11
11
  */
12
+ import type { PartPlacement } from "../archive/objectWorldBboxXY.js";
12
13
  import type { ConvertRequest } from "../schema.js";
13
14
  /** The file formats any2orca reads: Bambu Studio's and the slicers built on it, and PrusaSlicer's. */
14
15
  export declare const SOURCE_FORMATS: readonly ["bambu-family", "prusaslicer"];
@@ -52,6 +53,11 @@ export interface ParsedProject {
52
53
  * plates out on Bambu Studio's grid (PrusaSlicer 2.9's beds). Absent for the Bambu Studio family.
53
54
  */
54
55
  sourcePlateOrigins?: Record<number, [number, number]>;
56
+ /**
57
+ * Each object's parts as the model places them, by object id, from the pass that measured the objects: what the
58
+ * per-plate filament reading takes each part's mesh, transform and height from.
59
+ */
60
+ partPlacements?: Map<string, PartPlacement[]>;
55
61
  }
56
62
  export interface ReadContext {
57
63
  /** The project's unpacked size, every entry together (already checked against the cap). */
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Written by scripts/sync-version.mjs from package.json; a test checks they match.
3
3
  // Typed as string, so a release doesn't change the public API's shape.
4
- export const VERSION = "0.13.0";
4
+ export const VERSION = "0.14.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "any2orca",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Convert Bambu Studio, Creality Print, Anycubic Slicer Next, ElegooSlicer, Flash Studio, QIDI Studio and PrusaSlicer 3MF projects for the Snapmaker U1 (Snapmaker Orca), entirely on your own machine. Library, CLI and Web Worker in one package.",
5
5
  "keywords": [
6
6
  "3mf",
@@ -66,7 +66,7 @@
66
66
  "api": "node scripts/api-report.mjs"
67
67
  },
68
68
  "dependencies": {
69
- "any2orca-profiles": "0.4.0",
69
+ "any2orca-profiles": "0.5.0",
70
70
  "fflate": "0.8.3",
71
71
  "zod": "4.6.7"
72
72
  },