Skip to main content

brep_kernel/io/three_mf/
mesh_write.rs

1//! Export imported mesh instances without reconstruction or appearance loss.
2use super::{ThreeMfAppearance, ThreeMfReadResult, CORE_NAMESPACE, MATERIAL_NAMESPACE, BEAM_NAMESPACE};
3use super::write::ZipWriter;
4use std::fmt::Write;
5
6fn escape(s: &str) -> String {
7    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
8}
9
10/// Write the mesh instances and appearance recovered by [`super::read_3mf`].
11/// Uses object-local meshes and placements; derived flattened buffers are not
12/// used. Unlike solid export, this preserves corner colours and packaged PNGs.
13pub fn write_3mf_meshes(model: &ThreeMfReadResult) -> Result<Vec<u8>, String> {
14    let mut resources = String::new();
15    let mut objects = String::new();
16    let mut build = String::new();
17    let mut id = 1u32;
18    let mut next = || -> Result<u32, String> {
19        let value = id;
20        id = id.checked_add(1).ok_or("3MF resource id overflow")?;
21        Ok(value)
22    };
23    let mut textures = std::collections::BTreeMap::new();
24    let mut zip = ZipWriter::new();
25    let mut paths = std::collections::BTreeSet::new();
26    let mut relationships = String::from("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">");
27    for texture in &model.textures {
28        if textures.contains_key(&texture.id) { return Err("duplicate texture id".into()); }
29        let resource = next()?;
30        textures.insert(texture.id, resource);
31        // Canonical package paths keep resources separate from model/control parts.
32        let path = format!("3D/Textures/texture-{resource}.png");
33        if !paths.insert(path.clone()) { return Err("duplicate texture path".into()); }
34        zip.add(&path, &texture.png)?;
35        write!(relationships, "<Relationship Id=\"tex{resource}\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture\" Target=\"/{path}\"/>").unwrap();
36        write!(resources, "<m:texture2d id=\"{resource}\" path=\"/{path}\" contenttype=\"image/png\" tilestyleu=\"{}\" tilestylev=\"{}\" filter=\"{}\"/>", escape(&texture.tile_u), escape(&texture.tile_v), escape(&texture.filter)).unwrap();
37    }
38    for instance in &model.instances {
39        let mesh = model.meshes.get(instance.mesh).ok_or("invalid instance mesh index")?;
40        if mesh.positions.len() % 3 != 0 || mesh.indices.len() % 3 != 0
41            || (!mesh.triangle_appearance.is_empty() && mesh.triangle_appearance.len() != mesh.triangle_count()) {
42            return Err("invalid mesh buffer lengths".into());
43        }
44        let object = next()?;
45        write!(objects, "<object id=\"{object}\" type=\"model\" name=\"{}\"><mesh><vertices>", escape(instance.name.as_deref().unwrap_or(""))).unwrap();
46        let object_attributes_end = objects.len() - "<mesh><vertices>".len() - 1;
47        let mut default_property = None;
48        for p in mesh.positions.chunks_exact(3) {
49            write!(objects, "<vertex x=\"{}\" y=\"{}\" z=\"{}\"/>",p[0],p[1],p[2]).unwrap();
50        }
51        objects.push_str("</vertices><triangles>");
52        for (index, t) in mesh.indices.chunks_exact(3).enumerate() {
53            write!(objects, "<triangle v1=\"{}\" v2=\"{}\" v3=\"{}\"",t[0],t[1],t[2]).unwrap();
54            if let Some(appearance) = mesh.triangle_appearance.get(index).and_then(Option::as_ref) {
55                let property = next()?;
56                default_property.get_or_insert(property);
57                match appearance {
58                    ThreeMfAppearance::Colors(colors) => {
59                        write!(resources, "<m:colorgroup id=\"{property}\">").unwrap();
60                        for c in colors { write!(resources, "<m:color color=\"#{:02X}{:02X}{:02X}{:02X}\"/>",c[0],c[1],c[2],c[3]).unwrap(); }
61                        resources.push_str("</m:colorgroup>");
62                        write!(objects, " pid=\"{property}\" p1=\"0\" p2=\"1\" p3=\"2\"").unwrap();
63                    }
64                    ThreeMfAppearance::Texture { texture_id, uv } => {
65                        let texid = textures.get(texture_id).ok_or("missing texture resource")?;
66                        write!(resources, "<m:texture2dgroup id=\"{property}\" texid=\"{texid}\">").unwrap();
67                        for p in uv { write!(resources, "<m:tex2coord u=\"{}\" v=\"{}\"/>",p[0],p[1]).unwrap(); }
68                        resources.push_str("</m:texture2dgroup>");
69                        write!(objects, " pid=\"{property}\" p1=\"0\" p2=\"1\" p3=\"2\"").unwrap();
70                    }
71                    ThreeMfAppearance::Composite { colors, weights } => {
72                        let base = next()?;
73                        write!(resources, "<basematerials id=\"{base}\">").unwrap();
74                        for (i,c) in colors.iter().enumerate() { write!(resources, "<base name=\"material-{i}\" displaycolor=\"#{:02X}{:02X}{:02X}\"/>",c[0],c[1],c[2]).unwrap(); }
75                        resources.push_str("</basematerials>");
76                        let indices = (0..colors.len()).map(|i| i.to_string()).collect::<Vec<_>>().join(" ");
77                        write!(resources, "<m:compositematerials id=\"{property}\" matid=\"{base}\" matindices=\"{indices}\">").unwrap();
78                        for corner in weights {
79                            let values = corner.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(" ");
80                            write!(resources, "<m:composite values=\"{values}\"/>").unwrap();
81                        }
82                        resources.push_str("</m:compositematerials>");
83                        write!(objects, " pid=\"{property}\" p1=\"0\" p2=\"1\" p3=\"2\"").unwrap();
84                    }
85                }
86            }
87            objects.push_str("/>");
88        }
89        objects.push_str("</triangles>");
90        if let Some(lattice) = &mesh.beam_lattice {
91            write!(objects, "<b:beamlattice radius=\"1\" minlength=\"{}\"><b:beams>", lattice.min_length).unwrap();
92            for beam in &lattice.beams {
93                write!(objects, "<b:beam v1=\"{}\" v2=\"{}\" r1=\"{}\" r2=\"{}\" cap1=\"{}\" cap2=\"{}\"/>", beam.vertices[0], beam.vertices[1], beam.radii[0], beam.radii[1], escape(&beam.caps[0]), escape(&beam.caps[1])).unwrap();
94            }
95            objects.push_str("</b:beams></b:beamlattice>");
96        }
97        objects.push_str("</mesh></object>");
98        if mesh.beam_lattice.is_none() && mesh.triangle_appearance.iter().all(Option::is_some) {
99            if let Some(property) = default_property {
100                objects.insert_str(object_attributes_end, &format!(" pid=\"{property}\" pindex=\"0\""));
101            }
102        }
103        let transform = instance.transform.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(" ");
104        write!(build, "<item objectid=\"{object}\" transform=\"{transform}\"/>").unwrap();
105    }
106    let has_beams = model.instances.iter().any(|i| model.meshes[i.mesh].beam_lattice.is_some());
107    let has_materials = !model.textures.is_empty() || model.instances.iter().any(|i| !model.meshes[i.mesh].triangle_appearance.is_empty());
108    let required = match (has_materials, has_beams) { (true, true) => "m b", (true, false) => "m", (false, true) => "b", _ => "" };
109    let xml = format!("<model unit=\"millimeter\" xmlns=\"{CORE_NAMESPACE}\" xmlns:m=\"{MATERIAL_NAMESPACE}\" xmlns:b=\"{BEAM_NAMESPACE}\" requiredextensions=\"{required}\"><resources>{resources}{objects}</resources><build>{build}</build></model>");
110    zip.add("3D/3dmodel.model", xml.as_bytes())?;
111    relationships.push_str("</Relationships>");
112    zip.add("3D/_rels/3dmodel.model.rels", relationships.as_bytes())?;
113    zip.add("_rels/.rels", b"<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"model\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\" Target=\"/3D/3dmodel.model\"/></Relationships>")?;
114    zip.add("[Content_Types].xml", b"<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/><Default Extension=\"png\" ContentType=\"image/png\"/></Types>")?;
115    let bytes = zip.finish()?;
116    super::read_3mf(&bytes).map_err(|e| e.to_string())?;
117    Ok(bytes)
118}