Skip to main content

brep_kernel/io/three_mf/
bambu_write.rs

1//! 3MF export shaped for Bambu Studio (and the slicers that share its
2//! project reader): the variant of [`super::write_3mf`] a user picks when the
3//! file is going to that slicer. The standard export stays as it is. This
4//! writer welds and colours the same way and differs in how parts are grouped
5//! and how filaments are assigned.
6//!
7//! # Why a second shape
8//!
9//! Bambu Studio ignores Core base materials. When the standard export puts one
10//! top-level `<build>` item per body, the slicer builds one object per body:
11//! a coin and the inlays set into it become three objects, which it can
12//! arrange apart. The only filament information then is the per-triangle
13//! painting, and painting is not an assignment the user can edit from the
14//! part list. (The case that showed it: a cream coin with two charcoal
15//! inlays.)
16//!
17//! # The package
18//!
19//! Everything [`super::write_3mf`] writes, with these changes:
20//!
21//! * TOUCHING solids form ONE multipart object. Two solids are touching
22//!   when their bounding boxes overlap or meet, within a tolerance scaled to
23//!   the scene. Each group is an `<object>` holding `<components>`, one
24//!   `<component>` per member mesh object, at the identity, since the meshes
25//!   are already in world coordinates. Each group gets one `<build>` `<item>`;
26//!   the member meshes have no build item of their own. Groups and members
27//!   keep scene order, and a group is named after its first member. The
28//!   bounding-box test can merge two solids that come near each other
29//!   without touching. That costs nothing: they still print where they are,
30//!   now as parts of one object. Solids that do touch are never split apart.
31//! * `Metadata/model_settings.config`, the per-object configuration Bambu
32//!   Studio reads, has one `<object id>` per group (the group's object id)
33//!   and one `<part id>` per member (the member's mesh object id, which is how
34//!   the reader pairs a part with its component). Each part carries its
35//!   `name`, an identity `matrix`, and an `extruder` (the filament number
36//!   shown and edited in the part list). The object's own `extruder` is its
37//!   first part's.
38//! * A part's filament is the colour of most of its triangles (on a tie, the
39//!   first one seen). Colours become filament numbers in first-seen order, by
40//!   the slot rule painting already uses: from 1, or from 2 when anything in
41//!   the file is uncoloured, which then prints with filament 1. Painting is
42//!   written only on triangles whose filament DIFFERS from their part's, such
43//!   as a face the document coloured. A part in one colour is therefore an
44//!   assignment, not paint, and changing its filament in the slicer recolours
45//!   all of it.
46//!
47//! # What it does not write
48//!
49//! No `Metadata/project_settings.config`. That file is the only place the
50//! slicer takes filament RGB from, but the slicer loads it as a whole
51//! project: it lays the file over its factory defaults and selects the
52//! printer, process and filament presets the file names. A file holding
53//! only the filament colours would replace the user's printer and process
54//! settings with defaults. So the RGB values stay in the base materials
55//! (named `color_rrggbb`) for readers that use them, and the filament
56//! numbers here say which parts share a filament. The colour of each
57//! filament is chosen in the slicer, once.
58//!
59//! The slicer shows a part's own filament only while it has at least that
60//! many filaments loaded. Past that, the part list shows the object's
61//! filament instead.
62//!
63//! The `Application` metadata stays `next.BREP.io`. The reader treats a file
64//! from another application as "geometry plus model settings": it builds the
65//! objects and parts and applies their `extruder`s.
66
67use std::collections::BTreeMap;
68
69use super::write::{
70    display_color, paint_slot, painting_code, weld, xml_escape, Palette, WeldedObject, ZipWriter, BASE_MATERIALS_ID,
71    FIRST_OBJECT_ID, MAX_PAINT_SLOTS, MODEL_PART, RELATIONSHIPS_PART, RELATIONSHIPS_XML, SLIC3RPE_NAMESPACE,
72    CONTENT_TYPES_PART,
73};
74use super::write::{ThreeMfSolid, ThreeMfWriteReport};
75use super::CORE_NAMESPACE;
76
77/// The part Bambu Studio reads per-object and per-part settings from.
78pub const BAMBU_MODEL_SETTINGS_PART: &str = "Metadata/model_settings.config";
79
80/// The content types, with `.config` declared so every part of the package
81/// has one, as OPC asks.
82const CONTENT_TYPES_XML: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
83<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\n  \
84<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\n  \
85<Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\n  \
86<Default Extension=\"config\" ContentType=\"text/xml\"/>\n\
87</Types>\n";
88
89/// A 4 x 4 identity, as the part `matrix` metadata spells it (row major).
90const IDENTITY_MATRIX: &str = "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1";
91
92/// What one Bambu-shaped package contains.
93#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
94pub struct ThreeMfBambuReport {
95    /// Multipart objects: groups of touching solids, one `<build>` item each.
96    pub objects: usize,
97    /// Parts: solids that kept at least one triangle.
98    pub parts: usize,
99    /// Triangles written, across every part.
100    pub triangles: usize,
101    /// Vertices written after welding, across every part.
102    pub vertices: usize,
103    /// Triangles dropped because welding collapsed two of their corners.
104    pub degenerate_triangles: usize,
105    /// Distinct colours, as `<base>` entries.
106    pub materials: usize,
107    /// The filament number the first colour takes: 1 when every triangle is
108    /// coloured, else 2, with filament 1 kept for the uncoloured triangles.
109    pub first_filament: usize,
110    /// Distinct filament numbers used, by parts or by painting.
111    pub filaments: usize,
112    /// Triangles painted because their filament differs from their part's.
113    pub painted_triangles: usize,
114    /// Distinct colours past the filament limit, written as base materials
115    /// only. A part in one of them prints with filament 1.
116    pub unassigned_colors: usize,
117    /// Total package length in bytes.
118    pub bytes: usize,
119}
120
121/// An axis-aligned box over a solid's positions.
122#[derive(Clone, Copy)]
123struct Bounds {
124    low: [f64; 3],
125    high: [f64; 3],
126}
127
128impl Bounds {
129    fn of(positions: &[f64]) -> Self {
130        let mut low = [f64::INFINITY; 3];
131        let mut high = [f64::NEG_INFINITY; 3];
132        for point in positions.chunks_exact(3) {
133            for axis in 0..3 {
134                low[axis] = low[axis].min(point[axis]);
135                high[axis] = high[axis].max(point[axis]);
136            }
137        }
138        Self { low, high }
139    }
140
141    fn largest_extent(&self) -> f64 {
142        (0..3).map(|axis| self.high[axis] - self.low[axis]).fold(0.0, f64::max)
143    }
144
145    /// Overlapping or meeting, within `tolerance`, on every axis.
146    fn touches(&self, other: &Self, tolerance: f64) -> bool {
147        (0..3).all(|axis| self.low[axis] <= other.high[axis] + tolerance && other.low[axis] <= self.high[axis] + tolerance)
148    }
149}
150
151/// Group indices into `bounds` by box contact (union-find), each group in
152/// index order and the groups ordered by their first member.
153fn touching_groups(bounds: &[Bounds]) -> Vec<Vec<usize>> {
154    let scale = bounds.iter().map(Bounds::largest_extent).fold(0.0, f64::max);
155    // Touching bodies of one tessellated model share coordinates almost
156    // exactly. This only absorbs f32 printing noise.
157    let tolerance = (scale * 1e-6).max(1e-9);
158    let mut parent: Vec<usize> = (0..bounds.len()).collect();
159    fn root(parent: &mut [usize], mut at: usize) -> usize {
160        while parent[at] != at {
161            parent[at] = parent[parent[at]];
162            at = parent[at];
163        }
164        at
165    }
166    for a in 0..bounds.len() {
167        for b in a + 1..bounds.len() {
168            if bounds[a].touches(&bounds[b], tolerance) {
169                let (ra, rb) = (root(&mut parent, a), root(&mut parent, b));
170                if ra != rb {
171                    // The lower index is the root, so the group's first
172                    // member is its root.
173                    parent[ra.max(rb)] = ra.min(rb);
174                }
175            }
176        }
177    }
178    let mut groups: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
179    for index in 0..bounds.len() {
180        let group = root(&mut parent, index);
181        groups.entry(group).or_default().push(index);
182    }
183    groups.into_values().collect()
184}
185
186/// The palette index most of `object`'s triangles carry (`None` for
187/// uncoloured), the first seen on a tie.
188fn majority_color(object: &WeldedObject) -> Option<u32> {
189    let mut order: Vec<Option<u32>> = Vec::new();
190    let mut counts: BTreeMap<Option<u32>, usize> = BTreeMap::new();
191    for (_, color) in &object.triangles {
192        let count = counts.entry(*color).or_insert(0);
193        if *count == 0 {
194            order.push(*color);
195        }
196        *count += 1;
197    }
198    let mut best = order[0];
199    for color in order {
200        if counts[&color] > counts[&best] {
201            best = color;
202        }
203    }
204    best
205}
206
207/// The filament a triangle or part of palette index `color` prints with.
208/// Uncoloured is filament 1, and so is a colour past the limit.
209fn filament_of(color: Option<u32>, first_slot: usize) -> usize {
210    color.and_then(|color| paint_slot(color, first_slot)).unwrap_or(1)
211}
212
213/// One part as written: its mesh object and its filament.
214struct Part {
215    object: WeldedObject,
216    filament: usize,
217}
218
219/// The model part's XML: the meshes, then one components object per group.
220fn model_xml(parts: &[Part], groups: &[(u32, Vec<usize>)], palette: &Palette, document_name: &str, first_slot: usize) -> String {
221    let mut xml = String::new();
222    xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
223    xml.push_str(&format!(
224        "<model unit=\"millimeter\" xml:lang=\"en-US\" xmlns=\"{CORE_NAMESPACE}\" \
225         xmlns:slic3rpe=\"{SLIC3RPE_NAMESPACE}\">\n"
226    ));
227    xml.push_str(&format!("  <metadata name=\"Title\">{}</metadata>\n", xml_escape(document_name)));
228    xml.push_str("  <metadata name=\"Application\">next.BREP.io</metadata>\n");
229    xml.push_str("  <resources>\n");
230    if !palette.colors.is_empty() {
231        xml.push_str(&format!("    <basematerials id=\"{BASE_MATERIALS_ID}\">\n"));
232        for rgb in &palette.colors {
233            xml.push_str(&format!(
234                "      <base name=\"color_{:02x}{:02x}{:02x}\" displaycolor=\"{}\"/>\n",
235                rgb[0],
236                rgb[1],
237                rgb[2],
238                display_color(*rgb)
239            ));
240        }
241        xml.push_str("    </basematerials>\n");
242    }
243    for part in parts {
244        let object = &part.object;
245        xml.push_str(&format!("    <object id=\"{}\" name=\"{}\" type=\"model\"", object.id, xml_escape(&object.name)));
246        if let Some(body) = object.body {
247            xml.push_str(&format!(" pid=\"{BASE_MATERIALS_ID}\" pindex=\"{body}\""));
248        }
249        xml.push_str(">\n      <mesh>\n        <vertices>\n");
250        for [x, y, z] in &object.vertices {
251            xml.push_str(&format!("          <vertex x=\"{x}\" y=\"{y}\" z=\"{z}\"/>\n"));
252        }
253        xml.push_str("        </vertices>\n        <triangles>\n");
254        for ([a, b, c], color) in &object.triangles {
255            xml.push_str(&format!("          <triangle v1=\"{a}\" v2=\"{b}\" v3=\"{c}\""));
256            if let Some(code) = triangle_paint(*color, part.filament, first_slot) {
257                xml.push_str(&format!(" slic3rpe:mmu_segmentation=\"{code}\" paint_color=\"{code}\""));
258            }
259            if let Some(color) = color {
260                if Some(*color) != object.body {
261                    xml.push_str(&format!(" pid=\"{BASE_MATERIALS_ID}\" p1=\"{color}\""));
262                }
263            }
264            xml.push_str("/>\n");
265        }
266        xml.push_str("        </triangles>\n      </mesh>\n    </object>\n");
267    }
268    for (id, members) in groups {
269        let name = &parts[members[0]].object.name;
270        xml.push_str(&format!("    <object id=\"{id}\" name=\"{}\" type=\"model\">\n      <components>\n", xml_escape(name)));
271        for member in members {
272            xml.push_str(&format!("        <component objectid=\"{}\"/>\n", parts[*member].object.id));
273        }
274        xml.push_str("      </components>\n    </object>\n");
275    }
276    xml.push_str("  </resources>\n  <build>\n");
277    for (id, _) in groups {
278        xml.push_str(&format!("    <item objectid=\"{id}\"/>\n"));
279    }
280    xml.push_str("  </build>\n</model>\n");
281    xml
282}
283
284/// The painting a triangle of palette index `color` needs inside a part on
285/// filament `part_filament`: none when it prints with the part's filament
286/// anyway, or when its colour got no filament number.
287fn triangle_paint(color: Option<u32>, part_filament: usize, first_slot: usize) -> Option<String> {
288    let filament = match color {
289        Some(color) => paint_slot(color, first_slot)?,
290        // An uncoloured triangle prints with filament 1, which `first_slot`
291        // keeps free for it.
292        None => 1,
293    };
294    (filament != part_filament).then(|| painting_code(filament))
295}
296
297/// `Metadata/model_settings.config`.
298fn model_settings_xml(parts: &[Part], groups: &[(u32, Vec<usize>)]) -> String {
299    let mut xml = String::new();
300    xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<config>\n");
301    for (id, members) in groups {
302        let first = &parts[members[0]];
303        xml.push_str(&format!("  <object id=\"{id}\">\n"));
304        xml.push_str(&format!("    <metadata key=\"name\" value=\"{}\"/>\n", xml_escape(&first.object.name)));
305        xml.push_str(&format!("    <metadata key=\"extruder\" value=\"{}\"/>\n", first.filament));
306        for member in members {
307            let part = &parts[*member];
308            xml.push_str(&format!("    <part id=\"{}\" subtype=\"normal_part\">\n", part.object.id));
309            xml.push_str(&format!("      <metadata key=\"name\" value=\"{}\"/>\n", xml_escape(&part.object.name)));
310            xml.push_str(&format!("      <metadata key=\"matrix\" value=\"{IDENTITY_MATRIX}\"/>\n"));
311            xml.push_str(&format!("      <metadata key=\"extruder\" value=\"{}\"/>\n", part.filament));
312            xml.push_str("    </part>\n");
313        }
314        xml.push_str("  </object>\n");
315    }
316    xml.push_str("</config>\n");
317    xml
318}
319
320/// Write `solids` as one 3MF package shaped for Bambu Studio. See the
321/// module documentation for what differs from [`super::write_3mf`].
322///
323/// Solids with no triangles are skipped, and a set in which nothing has a
324/// triangle is refused, as [`super::write_3mf`] does.
325pub fn write_3mf_bambu(solids: &[ThreeMfSolid], document_name: &str) -> Result<(Vec<u8>, ThreeMfBambuReport), String> {
326    // `weld` reports into the standard report; only its degenerate count is read.
327    let mut weld_report = ThreeMfWriteReport::default();
328    let mut palette = Palette::default();
329    let mut objects = Vec::new();
330    let mut bounds = Vec::new();
331    for solid in solids {
332        let id = FIRST_OBJECT_ID + objects.len() as u32;
333        if let Some(object) = weld(solid, id, &mut palette, &mut weld_report)? {
334            objects.push(object);
335            bounds.push(Bounds::of(&solid.mesh.positions));
336        }
337    }
338    if objects.is_empty() {
339        return Err("write_3mf_bambu: nothing to export, no solid has a triangle".into());
340    }
341    let any_uncolored = objects.iter().any(|o| o.triangles.iter().any(|(_, c)| c.is_none()));
342    let first_slot = if any_uncolored { 2 } else { 1 };
343    let parts: Vec<Part> = objects
344        .into_iter()
345        .map(|object| {
346            let filament = filament_of(majority_color(&object), first_slot);
347            Part { object, filament }
348        })
349        .collect();
350    let mut next_id = FIRST_OBJECT_ID + parts.len() as u32;
351    let groups: Vec<(u32, Vec<usize>)> = touching_groups(&bounds)
352        .into_iter()
353        .map(|members| {
354            let id = next_id;
355            next_id += 1;
356            (id, members)
357        })
358        .collect();
359
360    let mut report = ThreeMfBambuReport {
361        objects: groups.len(),
362        parts: parts.len(),
363        degenerate_triangles: weld_report.degenerate_triangles,
364        materials: palette.colors.len(),
365        first_filament: first_slot,
366        unassigned_colors: palette.colors.len().saturating_sub(MAX_PAINT_SLOTS + 1 - first_slot),
367        ..Default::default()
368    };
369    let mut filaments = std::collections::BTreeSet::new();
370    for part in &parts {
371        report.vertices += part.object.vertices.len();
372        report.triangles += part.object.triangles.len();
373        filaments.insert(part.filament);
374        for (_, color) in &part.object.triangles {
375            if triangle_paint(*color, part.filament, first_slot).is_some() {
376                report.painted_triangles += 1;
377                filaments.insert(filament_of(*color, first_slot));
378            }
379        }
380    }
381    report.filaments = filaments.len();
382
383    let model = model_xml(&parts, &groups, &palette, document_name, first_slot);
384    let settings = model_settings_xml(&parts, &groups);
385    let mut zip = ZipWriter::new();
386    zip.add(CONTENT_TYPES_PART, CONTENT_TYPES_XML.as_bytes())?;
387    zip.add(RELATIONSHIPS_PART, RELATIONSHIPS_XML.as_bytes())?;
388    zip.add(MODEL_PART, model.as_bytes())?;
389    zip.add(BAMBU_MODEL_SETTINGS_PART, settings.as_bytes())?;
390    let bytes = zip.finish()?;
391    report.bytes = bytes.len();
392    Ok((bytes, report))
393}
394