1pub(crate) mod inflate;
87mod model;
88mod bambu_write;
89mod mesh_write;
90pub use mesh_write::write_3mf_meshes;
91mod write;
92mod xml;
93mod zip;
94
95pub use bambu_write::{write_3mf_bambu, ThreeMfBambuReport, BAMBU_MODEL_SETTINGS_PART};
96pub use write::{write_3mf, ThreeMfSolid, ThreeMfWriteReport};
97
98
99use serde::Serialize;
100
101pub const MATERIAL_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02";
103pub const BEAM_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02";
104pub const CORE_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02";
105const RELATIONSHIP_NAMESPACE: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
107const MODEL_RELATIONSHIP: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
109const RELATIONSHIP_PART: &str = "_rels/.rels";
111
112pub const MAX_PART_BYTES: usize = 256 * 1024 * 1024;
115pub const MAX_MESH_VERTICES: usize = 8_000_000;
117pub const MAX_MESH_TRIANGLES: usize = 16_000_000;
118pub const MAX_INSTANCES: usize = 65_536;
120pub const MAX_TOTAL_TRIANGLES: usize = 32_000_000;
122pub const MAX_COMPONENT_DEPTH: usize = 32;
126
127#[derive(Clone, Debug, PartialEq, Eq)]
130pub enum ThreeMfError {
131 Container(String),
133 Damaged { part: String, detail: String },
136 MissingPart { part: String, detail: String },
138 Unsupported { part: String, detail: String },
140 Bounds { part: String, detail: String },
142 Xml { part: String, detail: String },
144 Model { part: String, detail: String },
146}
147
148impl ThreeMfError {
149 pub fn part(&self) -> Option<&str> {
151 match self {
152 Self::Container(_) => None,
153 Self::Damaged { part, .. }
154 | Self::MissingPart { part, .. }
155 | Self::Unsupported { part, .. }
156 | Self::Bounds { part, .. }
157 | Self::Xml { part, .. }
158 | Self::Model { part, .. } => Some(part),
159 }
160 }
161}
162
163impl core::fmt::Display for ThreeMfError {
164 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
165 match self {
166 Self::Container(detail) => write!(f, "3MF package: {detail}"),
167 Self::Damaged { part, detail } => write!(f, "3MF '{part}' is damaged: {detail}"),
168 Self::MissingPart { part, detail } => write!(f, "3MF '{part}' is missing: {detail}"),
169 Self::Unsupported { part, detail } => write!(f, "3MF '{part}': {detail}"),
170 Self::Bounds { part, detail } => write!(f, "3MF '{part}' exceeds a bound: {detail}"),
171 Self::Xml { part, detail } => write!(f, "3MF '{part}' is not well-formed: {detail}"),
172 Self::Model { part, detail } => write!(f, "3MF '{part}': {detail}"),
173 }
174 }
175}
176
177impl std::error::Error for ThreeMfError {}
178
179#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
181pub enum ThreeMfUnit {
182 Micron,
183 Millimeter,
184 Centimeter,
185 Inch,
186 Foot,
187 Meter,
188}
189
190impl ThreeMfUnit {
191 pub fn millimetres(self) -> f64 {
193 match self {
194 Self::Micron => 0.001,
195 Self::Millimeter => 1.0,
196 Self::Centimeter => 10.0,
197 Self::Inch => 25.4,
198 Self::Foot => 304.8,
199 Self::Meter => 1000.0,
200 }
201 }
202
203 pub fn name(self) -> &'static str {
204 match self {
205 Self::Micron => "micron",
206 Self::Millimeter => "millimeter",
207 Self::Centimeter => "centimeter",
208 Self::Inch => "inch",
209 Self::Foot => "foot",
210 Self::Meter => "meter",
211 }
212 }
213
214 fn parse(text: &str) -> Option<Self> {
215 Some(match text {
216 "micron" => Self::Micron,
217 "millimeter" => Self::Millimeter,
218 "centimeter" => Self::Centimeter,
219 "inch" => Self::Inch,
220 "foot" => Self::Foot,
221 "meter" => Self::Meter,
222 _ => return None,
223 })
224 }
225}
226
227#[derive(Clone, Debug, PartialEq, Serialize)]
229pub enum ThreeMfAppearance {
230 Colors([[u8; 4]; 3]),
231 Texture { texture_id: u32, uv: [[f64; 2]; 3] },
232 Composite { colors: Vec<[u8; 3]>, weights: [Vec<f64>; 3] },
233}
234
235impl ThreeMfAppearance {
236 pub fn preview_rgb(&self) -> Option<[u8; 3]> {
238 let mut rgb = [0; 3];
239 match self {
240 Self::Colors(colors) => {
241 rgb.copy_from_slice(&colors[0][..3]);
243 }
244 Self::Composite { colors, weights } => {
245 let weights = &weights[0];
246 let sum: f64 = weights.iter().take(colors.len()).sum();
247 for i in 0..3 {
248 let mixed: f64 = colors.iter().enumerate().map(|(j, c)| {
249 let fraction = if sum > 0.0 { weights.get(j).copied().unwrap_or(0.0) / sum }
250 else { 1.0 / colors.len() as f64 };
251 c[i] as f64 * fraction
252 }).sum();
253 rgb[i] = mixed.round().clamp(0.0,255.0) as u8;
254 }
255 }
256 Self::Texture { .. } => return None,
257 }
258 Some(rgb)
259 }
260 fn reverse(&mut self) {
261 match self {
262 Self::Colors(c) => c.swap(1, 2),
263 Self::Texture { uv, .. } => uv.swap(1, 2),
264 Self::Composite { weights, .. } => weights.swap(1, 2),
265 }
266 }
267}
268
269#[derive(Clone, Debug, PartialEq, Serialize)]
273pub struct ThreeMfBeam {
274 pub vertices: [u32; 2],
275 pub radii: [f64; 2],
276 pub caps: [String; 2],
277}
278
279#[derive(Clone, Debug, PartialEq, Serialize)]
281pub struct ThreeMfBeamLattice {
282 pub min_length: f64,
283 pub beams: Vec<ThreeMfBeam>,
284}
285
286#[derive(Clone, Debug, PartialEq, Serialize)]
288pub struct ThreeMfTexture {
289 pub id: u32,
290 pub path: String,
291 pub png: Vec<u8>,
292 pub tile_u: String,
293 pub tile_v: String,
294 pub filter: String,
295}
296
297#[derive(Clone, Debug, Default, PartialEq, Serialize)]
301pub struct ThreeMfMesh {
302 pub object_id: u32,
304 pub beam_lattice: Option<ThreeMfBeamLattice>,
306 pub positions: Vec<f64>,
308 pub indices: Vec<u32>,
310 pub triangle_colors: Vec<Option<[u8; 3]>>,
314 pub triangle_appearance: Vec<Option<ThreeMfAppearance>>,
316}
317
318impl ThreeMfMesh {
319 pub fn vertex_count(&self) -> usize {
320 self.positions.len() / 3
321 }
322 pub fn triangle_count(&self) -> usize {
323 self.indices.len() / 3
324 }
325}
326
327#[derive(Clone, Debug, PartialEq, Serialize)]
330pub struct ThreeMfInstance {
331 pub object_id: u32,
334 pub mesh: usize,
336 pub transform: [f64; 12],
339 pub first_vertex: usize,
345 pub vertex_count: usize,
346 pub first_triangle: usize,
347 pub triangle_count: usize,
348 pub name: Option<String>,
352}
353
354impl ThreeMfInstance {
355 pub fn transform_point(&self, point: [f64; 3]) -> [f64; 3] {
357 transform_point(&self.transform, point)
358 }
359}
360
361#[derive(Clone, Debug, Serialize)]
363pub struct ThreeMfReadResult {
364 pub model_part: String,
366 pub unit: ThreeMfUnit,
368 pub textures: Vec<ThreeMfTexture>,
370 pub meshes: Vec<ThreeMfMesh>,
373 pub instances: Vec<ThreeMfInstance>,
376 pub positions: Vec<f64>,
379 pub indices: Vec<u32>,
382 pub triangle_colors: Vec<Option<[u8; 3]>>,
387 pub triangle_appearance: Vec<Option<ThreeMfAppearance>>,
389}
390
391impl ThreeMfReadResult {
392 pub fn vertex_count(&self) -> usize {
393 self.positions.len() / 3
394 }
395 pub fn triangle_count(&self) -> usize {
396 self.indices.len() / 3
397 }
398
399 pub fn instance_mesh(&self, instance: usize) -> Option<(Vec<f64>, Vec<u32>)> {
408 let instance = self.instances.get(instance)?;
409 let positions = self
410 .positions
411 .get(instance.first_vertex * 3..(instance.first_vertex + instance.vertex_count) * 3)?
412 .to_vec();
413 let base = instance.first_vertex as u32;
414 let indices = self
415 .indices
416 .get(
417 instance.first_triangle * 3
418 ..(instance.first_triangle + instance.triangle_count) * 3,
419 )?
420 .iter()
421 .map(|index| index - base)
422 .collect();
423 Some((positions, indices))
424 }
425}
426
427pub const IDENTITY: [f64; 12] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0];
429
430pub fn transform_point(transform: &[f64; 12], point: [f64; 3]) -> [f64; 3] {
432 let [x, y, z] = point;
433 [
434 x * transform[0] + y * transform[3] + z * transform[6] + transform[9],
435 x * transform[1] + y * transform[4] + z * transform[7] + transform[10],
436 x * transform[2] + y * transform[5] + z * transform[8] + transform[11],
437 ]
438}
439
440pub fn compose(inner: &[f64; 12], outer: &[f64; 12]) -> [f64; 12] {
443 let mut out = [0.0; 12];
444 for row in 0..4 {
445 for column in 0..3 {
446 let mut sum = if row == 3 { outer[9 + column] } else { 0.0 };
447 for k in 0..3 {
448 sum += inner[row * 3 + k] * outer[k * 3 + column];
449 }
450 out[row * 3 + column] = sum;
451 }
452 }
453 out
454}
455
456fn determinant(transform: &[f64; 12]) -> f64 {
459 let m = transform;
460 m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6])
461 + m[2] * (m[3] * m[7] - m[4] * m[6])
462}
463
464pub fn read_3mf(bytes: &[u8]) -> Result<ThreeMfReadResult, ThreeMfError> {
470 let archive = zip::ZipArchive::open(bytes).map_err(map_zip)?;
471 let relationships = archive.find(RELATIONSHIP_PART).ok_or_else(|| {
472 ThreeMfError::MissingPart {
473 part: RELATIONSHIP_PART.into(),
474 detail: "an OPC package must carry the package relationships part".into(),
475 }
476 })?;
477 let relationships_text = read_text(&archive, relationships, RELATIONSHIP_PART)?;
478 let model_part = start_part(&relationships_text)?;
479 let model_entry = archive.find(&model_part).ok_or_else(|| ThreeMfError::MissingPart {
480 part: model_part.clone(),
481 detail: format!("'{RELATIONSHIP_PART}' names it as the 3D model start part"),
482 })?;
483 let model_text = read_text(&archive, model_entry, &model_part)?;
484 let mut document = model::parse_model(&model_part, &model_text)?;
485 let mut texture_bytes = 0usize;
486 for texture in &mut document.textures {
487 let entry = archive.find(&texture.path).ok_or_else(|| ThreeMfError::MissingPart {
488 part: texture.path.clone(), detail: format!("texture2d {} references this PNG", texture.id),
489 })?;
490 texture.png = archive.read(entry, MAX_PART_BYTES.saturating_sub(texture_bytes)).map_err(map_zip)?;
491 texture_bytes += texture.png.len();
492 if !texture.png.starts_with(b"\x89PNG\r\n\x1a\n") {
493 return Err(ThreeMfError::Model { part: texture.path.clone(), detail: "texture2d is not a PNG".into() });
494 }
495 }
496 flatten(model_part, document)
497}
498
499fn map_zip(error: zip::ZipError) -> ThreeMfError {
501 let part = error.entry.clone().unwrap_or_else(|| "[package]".into());
502 match error.fault {
503 zip::ZipFault::Container => match &error.entry {
504 Some(entry) => ThreeMfError::Container(format!("{entry}: {}", error.message)),
505 None => ThreeMfError::Container(error.message),
506 },
507 zip::ZipFault::Damaged => ThreeMfError::Damaged { part, detail: error.message },
508 zip::ZipFault::Unsupported => ThreeMfError::Unsupported { part, detail: error.message },
509 zip::ZipFault::Bounds => ThreeMfError::Bounds { part, detail: error.message },
510 }
511}
512
513fn read_text(
514 archive: &zip::ZipArchive<'_>,
515 entry: &zip::ZipEntry,
516 part: &str,
517) -> Result<String, ThreeMfError> {
518 let bytes = archive.read(entry, MAX_PART_BYTES).map_err(map_zip)?;
519 String::from_utf8(bytes).map_err(|_| ThreeMfError::Xml {
520 part: part.to_owned(),
521 detail: "the part is not UTF-8 text".into(),
522 })
523}
524
525fn start_part(text: &str) -> Result<String, ThreeMfError> {
527 let mut reader = xml::XmlReader::new(text);
528 loop {
529 let event = reader.next().map_err(|error| ThreeMfError::Xml {
530 part: RELATIONSHIP_PART.into(),
531 detail: error.to_string(),
532 })?;
533 match event {
534 xml::Event::Start(tag) => {
535 if tag.namespace != RELATIONSHIP_NAMESPACE {
536 reader.skip_subtree(&tag).map_err(|error| ThreeMfError::Xml {
537 part: RELATIONSHIP_PART.into(),
538 detail: error.to_string(),
539 })?;
540 continue;
541 }
542 if tag.name != "Relationship" {
543 continue;
544 }
545 if tag.attribute("Type") != Some(MODEL_RELATIONSHIP) {
546 continue;
547 }
548 let target = tag.attribute("Target").ok_or_else(|| ThreeMfError::Model {
549 part: RELATIONSHIP_PART.into(),
550 detail: "the 3D model relationship has no Target".into(),
551 })?;
552 let target = target.trim_start_matches('/');
553 if target.is_empty() {
554 return Err(ThreeMfError::Model {
555 part: RELATIONSHIP_PART.into(),
556 detail: "the 3D model relationship has an empty Target".into(),
557 });
558 }
559 return Ok(target.to_owned());
560 }
561 xml::Event::End { .. } => {}
562 xml::Event::Eof => break,
563 }
564 }
565 Err(ThreeMfError::MissingPart {
566 part: RELATIONSHIP_PART.into(),
567 detail: format!("no relationship of type '{MODEL_RELATIONSHIP}' names a 3D model part"),
568 })
569}
570
571fn flatten(
573 model_part: String,
574 document: model::ModelDocument,
575) -> Result<ThreeMfReadResult, ThreeMfError> {
576 let scale = document.unit.millimetres();
577 let meshes = document
578 .meshes
579 .iter()
580 .map(|mesh| {
581 let mut triangle_appearance = mesh.properties.iter()
582 .map(|p| document.appearance(p.or(mesh.object_property), &model_part))
583 .collect::<Result<Vec<_>, _>>()?;
584 let mut triangle_colors: Vec<_> = triangle_appearance.iter()
585 .map(|a| a.as_ref().and_then(ThreeMfAppearance::preview_rgb)).collect();
586 if triangle_appearance.iter().all(Option::is_none) { triangle_appearance.clear(); }
587 if triangle_colors.iter().all(Option::is_none) {
588 triangle_colors.clear();
589 }
590 Ok(ThreeMfMesh {
591 object_id: mesh.object_id,
592 beam_lattice: mesh.beam_lattice.clone().map(|mut lattice| {
593 lattice.min_length *= scale;
594 for beam in &mut lattice.beams { for r in &mut beam.radii { *r *= scale; } }
595 lattice
596 }),
597 positions: mesh.positions.iter().map(|value| value * scale).collect(),
598 indices: mesh.indices.clone(),
599 triangle_colors,
600 triangle_appearance,
601 })
602 })
603 .collect::<Result<Vec<_>, ThreeMfError>>()?;
604 let mut instances = Vec::new();
605 for item in &document.items {
606 let mut transform = item.transform;
607 for value in &mut transform[9..12] {
608 *value *= scale;
609 }
610 place(&document, &model_part, item.object_id, transform, 0, None, &mut instances)?;
611 }
612 let mut positions = Vec::new();
613 let mut indices = Vec::new();
614 let mut triangle_colors: Vec<Option<[u8; 3]>> = Vec::new();
615 let colored = instances.iter().any(|instance| !meshes[instance.mesh].triangle_colors.is_empty());
616 let mut triangle_appearance = Vec::new();
617 let has_appearance = instances.iter().any(|i| !meshes[i.mesh].triangle_appearance.is_empty());
618 let mut triangles = 0usize;
619 for instance in &mut instances {
620 let mesh = &meshes[instance.mesh];
621 triangles += mesh.triangle_count();
622 if triangles > MAX_TOTAL_TRIANGLES {
623 return Err(ThreeMfError::Bounds {
624 part: model_part,
625 detail: format!(
626 "the build places more than {MAX_TOTAL_TRIANGLES} triangles in total"
627 ),
628 });
629 }
630 instance.first_vertex = positions.len() / 3;
631 instance.vertex_count = mesh.vertex_count();
632 instance.first_triangle = indices.len() / 3;
633 instance.triangle_count = mesh.triangle_count();
634 let base = instance.first_vertex as u32;
635 for point in mesh.positions.chunks_exact(3) {
636 let placed = instance.transform_point([point[0], point[1], point[2]]);
637 positions.extend(placed);
638 }
639 let mirrored = determinant(&instance.transform) < 0.0;
643 for triangle in mesh.indices.chunks_exact(3) {
644 if mirrored {
645 indices.extend([base + triangle[0], base + triangle[2], base + triangle[1]]);
646 } else {
647 indices.extend([base + triangle[0], base + triangle[1], base + triangle[2]]);
648 }
649 }
650 if has_appearance {
651 for i in 0..mesh.triangle_count() {
652 let mut appearance = mesh.triangle_appearance.get(i).cloned().flatten();
653 if mirrored { if let Some(a) = &mut appearance { a.reverse(); } }
654 triangle_appearance.push(appearance);
655 }
656 }
657 if colored {
659 if mesh.triangle_colors.is_empty() {
660 triangle_colors.extend(std::iter::repeat(None).take(mesh.triangle_count()));
661 } else {
662 triangle_colors.extend_from_slice(&mesh.triangle_colors);
663 }
664 }
665 }
666 Ok(ThreeMfReadResult {
667 model_part,
668 unit: document.unit,
669 textures: document.textures,
670 meshes,
671 instances,
672 positions,
673 indices,
674 triangle_colors,
675 triangle_appearance,
676 })
677}
678
679fn place(
681 document: &model::ModelDocument,
682 model_part: &str,
683 object_id: u32,
684 transform: [f64; 12],
685 depth: usize,
686 inherited_name: Option<&str>,
687 instances: &mut Vec<ThreeMfInstance>,
688) -> Result<(), ThreeMfError> {
689 if depth > MAX_COMPONENT_DEPTH {
690 return Err(ThreeMfError::Bounds {
691 part: model_part.to_owned(),
692 detail: format!("components nest deeper than {MAX_COMPONENT_DEPTH} levels"),
693 });
694 }
695 let object = document.object(object_id).ok_or_else(|| ThreeMfError::Model {
696 part: model_part.to_owned(),
697 detail: format!("object {object_id} is placed but never defined"),
698 })?;
699 let name = object.name.as_deref().or(inherited_name);
700 match &object.content {
701 model::ObjectContent::Mesh(mesh) => {
702 if object.model_type {
705 if instances.len() + 1 > MAX_INSTANCES {
706 return Err(ThreeMfError::Bounds {
707 part: model_part.to_owned(),
708 detail: format!("the build places more than {MAX_INSTANCES} instances"),
709 });
710 }
711 instances.push(ThreeMfInstance {
712 object_id: object.id,
713 mesh: *mesh,
714 transform,
715 first_vertex: 0,
717 vertex_count: 0,
718 first_triangle: 0,
719 triangle_count: 0,
720 name: name.map(str::to_owned),
721 });
722 }
723 Ok(())
724 }
725 model::ObjectContent::Components(components) => {
726 for component in components {
727 let mut inner = component.transform;
728 let scale = document.unit.millimetres();
732 for value in &mut inner[9..12] {
733 *value *= scale;
734 }
735 let composed = compose(&inner, &transform);
736 place(
737 document,
738 model_part,
739 component.object_id,
740 composed,
741 depth + 1,
742 name,
743 instances,
744 )?;
745 }
746 Ok(())
747 }
748 }
749}