filamentPresets.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // Tiered filament-preset list, shared by every picker that has to offer "all
  2. // the filaments this install knows about".
  3. //
  4. // Lookup order is fixed across the app: local imported > Orca Cloud > Bambu
  5. // Cloud > hardcoded built-in table. It mirrors ConfigureAmsSlotModal's picker
  6. // and SliceModal's tier groups, so a filament the user sees in one place is
  7. // named and ranked the same way in the others.
  8. //
  9. // The built-in table is the floor, not an equal source: it is a static list
  10. // compiled into the backend, so it is the only tier that can never be empty
  11. // and the only one that works with no cloud account and nothing imported.
  12. import type { BuiltinFilament, LocalPreset, OrcaProfileMeta, SlicerSetting } from '../api/client';
  13. import { parsePresetName, toFilamentId } from '../components/spool-form/utils';
  14. export type FilamentPresetSource = 'local' | 'orca_cloud' | 'cloud' | 'builtin';
  15. export interface FilamentPresetOption {
  16. /** Opaque, source-prefixed handle: ``local_12`` / ``orca_<uuid>`` / a Bambu
  17. * cloud setting_id / ``builtin_GFA00``. Prefixes match the convention
  18. * ConfigureAmsSlotModal already uses so the two can share resolvers. */
  19. id: string;
  20. name: string;
  21. source: FilamentPresetSource;
  22. /** The Bambu filament id this preset resolves to, when it is derivable
  23. * without a network round trip. Empty for Bambu Cloud *user* presets, whose
  24. * real filament_id only exists in the cloud detail — see
  25. * resolveFilamentId. */
  26. filamentId: string;
  27. /** Material as the preset itself declares it, used to derive a generic
  28. * filament id for tiers that carry no Bambu id of their own. */
  29. filamentType: string;
  30. }
  31. export interface FilamentPresetSources {
  32. localPresets?: LocalPreset[];
  33. orcaProfiles?: OrcaProfileMeta[];
  34. cloudSettings?: SlicerSetting[];
  35. builtinFilaments?: BuiltinFilament[];
  36. }
  37. /** Generic Bambu filament ids by material. Local and Orca Cloud presets carry
  38. * no Bambu filament id, but the printer's calibration table is indexed by
  39. * one, so the closest generic is what a calibration for such a preset has to
  40. * be filed under. Same table and same fallback chain as the AMS slot
  41. * configure flow — the two must agree or a profile created here won't match
  42. * the slot configured there. */
  43. const GENERIC_FILAMENT_IDS: Record<string, string> = {
  44. 'PLA': 'GFL99', 'PLA-CF': 'GFL98', 'PLA SILK': 'GFL96', 'PLA HIGH SPEED': 'GFL95',
  45. 'PETG': 'GFG99', 'PETG HF': 'GFG96', 'PETG-CF': 'GFG98', 'PCTG': 'GFG97',
  46. 'ABS': 'GFB99', 'ASA': 'GFB98',
  47. 'PC': 'GFC99',
  48. 'PA': 'GFN99', 'PA-CF': 'GFN98', 'NYLON': 'GFN99',
  49. 'TPU': 'GFU99',
  50. 'PVA': 'GFS99', 'HIPS': 'GFS98',
  51. 'PE': 'GFP99', 'PP': 'GFP97',
  52. };
  53. /** Resolve a material string to a generic Bambu filament id, trying the exact
  54. * spelling before progressively stripping the suffixes slicer presets add
  55. * ("-CF", "+", " HF"). Returns '' when nothing matches, which callers must
  56. * treat as "not calibratable" rather than substituting a default — filing a
  57. * calibration under the wrong material is worse than refusing. */
  58. export function genericFilamentIdForMaterial(material: string | null | undefined): string {
  59. const m = (material || '').toUpperCase().trim();
  60. if (!m) return '';
  61. return GENERIC_FILAMENT_IDS[m]
  62. || GENERIC_FILAMENT_IDS[m.replace(/[-\s]?CF$/, '')]
  63. || GENERIC_FILAMENT_IDS[m.replace(/\+$/, '')]
  64. || GENERIC_FILAMENT_IDS[m.split(/[-\s]/)[0]]
  65. || '';
  66. }
  67. /** Strip the printer/nozzle suffix and the "# " custom-preset marker a preset
  68. * name may carry, e.g. "Elegoo PLA+ @BBL X1C 0.4 nozzle" → "Elegoo PLA+". */
  69. export function presetDisplayName(name: string): string {
  70. const withoutSuffix = name.replace(/@.+$/, '').trim();
  71. return withoutSuffix.startsWith('# ') ? withoutSuffix.slice(2).trim() : withoutSuffix;
  72. }
  73. const SOURCE_ORDER: Record<FilamentPresetSource, number> = {
  74. local: 0,
  75. orca_cloud: 1,
  76. cloud: 2,
  77. builtin: 3,
  78. };
  79. /**
  80. * Merge every filament source into one ranked list.
  81. *
  82. * Deduplication is deliberately asymmetric, because "the same name in two
  83. * tiers" means different things depending on which tiers:
  84. *
  85. * - *Within* a tier, by resolved filament id or display name. This is what
  86. * collapses the per-printer-model copies a cloud account carries —
  87. * "Bambu PLA Basic @BBL X1C", "@BBL P1S", "@BBL A1" are one name once the
  88. * suffix is stripped — and repeated imports of one filament for several
  89. * printers.
  90. *
  91. * - *Across* tiers, by id only. Two entries carrying the same id really are
  92. * one record reached by two routes; two entries merely sharing a name are
  93. * not. Imported presets and an Orca Cloud library overlap heavily by name
  94. * (they are usually the same profiles, synced), and suppressing one for the
  95. * other empties a tier the user curated on purpose. The heading says where
  96. * each came from, which is the point of having tiers at all.
  97. *
  98. * - *Into the built-in tier*, by name as well as by id. That tier is a static
  99. * table of the same Bambu catalogue every other source also ships, so
  100. * without a name check it echoes back everything above it. It exists to
  101. * guarantee the list is never empty, not to be a fourth copy.
  102. */
  103. export function buildFilamentPresetOptions(sources: FilamentPresetSources): FilamentPresetOption[] {
  104. const { localPresets, orcaProfiles, cloudSettings, builtinFilaments } = sources;
  105. const options: FilamentPresetOption[] = [];
  106. const nameKey = (name: string) => name.trim().toLowerCase();
  107. // Ids seen anywhere: a cloud setting_id, an Orca profile id, a resolved
  108. // filament id. Shared across tiers — an id collision is true identity.
  109. const claimedIds = new Set<string>();
  110. // Names seen, scoped to one tier, so two tiers can each list "Elegoo PLA+".
  111. const namesInTier = new Set<string>();
  112. // Every name any real source offered, consulted only by the built-in tier.
  113. const namesOffered = new Set<string>();
  114. const take = (source: FilamentPresetSource, name: string, ...ids: (string | undefined)[]): boolean => {
  115. const usableIds = ids.filter((k): k is string => !!k);
  116. if (usableIds.some(k => claimedIds.has(k))) return false;
  117. const scoped = `${source}|${nameKey(name)}`;
  118. if (namesInTier.has(scoped)) return false;
  119. usableIds.forEach(k => claimedIds.add(k));
  120. namesInTier.add(scoped);
  121. namesOffered.add(nameKey(name));
  122. return true;
  123. };
  124. // 1. Local imported presets. filament_id lives in the preset's setting JSON,
  125. // which the list endpoint doesn't return, so the generic material id is what
  126. // we can offer without a per-preset detail fetch.
  127. for (const lp of localPresets ?? []) {
  128. const name = presetDisplayName(lp.name);
  129. const material = lp.filament_type || parsePresetName(name).material;
  130. // No id is claimed here: the generic id an import maps to is shared by
  131. // every filament of that material, so claiming it would let the first
  132. // imported PLA swallow every other PLA in the list.
  133. if (!take('local', name)) continue;
  134. options.push({
  135. id: `local_${lp.id}`,
  136. name,
  137. source: 'local',
  138. filamentId: genericFilamentIdForMaterial(material),
  139. filamentType: material || '',
  140. });
  141. }
  142. // 2. Orca Cloud. setting_ids are UUIDs a Bambu printer can't resolve, so
  143. // these also fall back to the generic id for their material.
  144. for (const op of orcaProfiles ?? []) {
  145. const name = presetDisplayName(op.name);
  146. const material = parsePresetName(name).material;
  147. // Same reasoning as the local tier for the generic id. The Orca profile id
  148. // is claimed, so a Bambu Cloud row carrying that same id is recognised as
  149. // the same record — a shared *name* is not, since an Orca library and an
  150. // imported bundle are usually the same profiles reached two ways and both
  151. // are worth showing under their own heading.
  152. if (!take('orca_cloud', name, op.setting_id)) continue;
  153. options.push({
  154. id: `orca_${op.setting_id}`,
  155. name,
  156. source: 'orca_cloud',
  157. filamentId: genericFilamentIdForMaterial(material),
  158. filamentType: material,
  159. });
  160. }
  161. // 3. Bambu Cloud. Official presets (GFS…) carry their filament id in the
  162. // setting_id itself; user presets (PFUS… / PFCN…) do not, and toFilamentId
  163. // would hand back the raw cloud id, which the printer rejects. Leave those
  164. // empty here and let resolveFilamentId fetch the detail on selection.
  165. for (const cp of cloudSettings ?? []) {
  166. const name = presetDisplayName(cp.name);
  167. // Cloud setting_ids carry a variant suffix ("GFSA00_01"); claim the bare
  168. // filament id as well, or the built-in tier won't recognise the filament
  169. // as covered and will list it again under its own heading.
  170. const filamentId = cp.setting_id.startsWith('GFS') ? toFilamentId(cp.setting_id) : '';
  171. if (!take('cloud', name, cp.setting_id, filamentId || undefined)) continue;
  172. options.push({
  173. id: cp.setting_id,
  174. name,
  175. source: 'cloud',
  176. filamentId,
  177. filamentType: parsePresetName(name).material,
  178. });
  179. }
  180. // 4. Hardcoded fallback. Always present, so the picker is never empty even
  181. // with no cloud account and nothing imported — but only for filaments none
  182. // of the tiers above already offered.
  183. for (const bf of builtinFilaments ?? []) {
  184. // Cloud setting_ids insert an "S" after "GF" ("GFA00" → "GFSA00"); check
  185. // both spellings so a filament a cloud tier already offered isn't listed
  186. // a second time under a slightly different id.
  187. const asSettingId = bf.filament_id.startsWith('GF') ? `GFS${bf.filament_id.slice(2)}` : bf.filament_id;
  188. // Unlike the tiers above, a name match is enough to skip: this table is a
  189. // static copy of the same catalogue, not a library of its own.
  190. if (namesOffered.has(nameKey(bf.name))) continue;
  191. if (!take('builtin', bf.name, bf.filament_id, asSettingId)) continue;
  192. options.push({
  193. id: `builtin_${bf.filament_id}`,
  194. name: bf.name,
  195. source: 'builtin',
  196. filamentId: bf.filament_id,
  197. filamentType: parsePresetName(bf.name).material,
  198. });
  199. }
  200. return options.sort((a, b) => {
  201. if (a.source !== b.source) return SOURCE_ORDER[a.source] - SOURCE_ORDER[b.source];
  202. return a.name.localeCompare(b.name);
  203. });
  204. }
  205. /**
  206. * The Bambu filament id to file a calibration under for a chosen preset.
  207. *
  208. * Everything except a Bambu Cloud *user* preset is already resolved by
  209. * buildFilamentPresetOptions; those need the cloud detail, because the
  210. * PFUS/PFCN setting_id is not a filament id and the printer's calibration
  211. * table is indexed by filament id. ``fetchDetail`` is injected so the pure
  212. * cases stay testable without a network stub.
  213. */
  214. export async function resolveFilamentId(
  215. option: FilamentPresetOption,
  216. fetchDetail?: (settingId: string) => Promise<{ filament_id?: string | null }>,
  217. ): Promise<string> {
  218. if (option.filamentId) return option.filamentId;
  219. if (option.source !== 'cloud' || !fetchDetail) return '';
  220. try {
  221. const detail = await fetchDetail(option.id);
  222. // Never fall back to the preset's base_id: that collapses a custom preset
  223. // onto the generic it inherits from, and the printer then resolves the
  224. // calibration to "Generic …" instead of the user's filament (#1053).
  225. return detail.filament_id || '';
  226. } catch {
  227. return '';
  228. }
  229. }