lib3mf_rust
A pure Rust implementation for parsing 3MF (3D Manufacturing Format) files with no unsafe code.
Note: Most part of this code has been vibe-coded using GitHub Copilot Agents
Overview
This library provides a pure Rust implementation for reading and parsing 3MF files, which are ZIP-based containers following the Open Packaging Conventions (OPC) standard and containing XML-based 3D model data.
The 3MF format is the modern standard for 3D printing, supporting rich model information including:
- 3D mesh geometry (vertices and triangles)
- Materials and colors
- Metadata
- Build specifications
- And more
Features
- ✅ Pure Rust implementation - No C/C++ dependencies
- ✅ No unsafe code - Enforced with
#![forbid(unsafe_code)] - ✅ Extension support - Configurable support for 3MF extensions with validation
- ✅ Parse 3MF file structure (ZIP/OPC container)
- ✅ Read 3D model data including meshes, vertices, and triangles
- ✅ Write/Serialize 3MF files - Create and write 3MF files
- ✅ Support for materials and colors
- ✅ Metadata extraction and writing
- ✅ Build item specifications
- ✅ Comprehensive error handling
- ✅ Round-trip support (read-write-read)
Installation
Add this to your Cargo.toml:
[]
= "0.1"
Usage
Reading 3MF Files
Basic Example
use Model;
use File;
Writing 3MF Files
Creating and Writing a Simple Model
use ;
Round-Trip Example
use Model;
use File;
Streaming Parser for Large Files
For very large files, use the streaming parser to process objects one at a time without loading everything into memory:
use StreamingParser;
use File;
Accessing Production Extension Data
The Production Extension provides UUIDs and routing paths for manufacturing workflows:
use Model;
use File;
Accessing Displacement Data
The library parses displacement extension data into accessible structures:
use Model;
use File;
Accessing Beam Lattice Data
The Beam Lattice Extension is fully supported with complete data extraction:
use Model;
use File;
Advanced Materials
The Materials Extension now supports advanced features for full-color 3D printing:
use Model;
use File;
Extension Support
3MF files can require specific extensions beyond the core specification. You can control which extensions your application supports:
use ;
use File;
The parser supports the following extensions:
Extension::Core- Core 3MF specification (always supported)Extension::Material- Materials & PropertiesExtension::Production- Production information (UUIDs, paths)Extension::Slice- Slice data for layer-by-layer manufacturingExtension::BeamLattice- Beam and lattice structuresExtension::SecureContent- Digital signatures and encryptionExtension::BooleanOperations- Volumetric designExtension::Displacement- Surface displacement mapsExtension::Volumetric- Volumetric data (voxel grids and implicit volumes)
Polygon Clipping for Slice Self-Intersection Resolution
The library includes polygon clipping operations for resolving self-intersections in slice data:
use resolve_self_intersections;
use ;
// Create a slice polygon
let vertices = vec!;
let mut polygon = new;
polygon.segments.push;
polygon.segments.push;
polygon.segments.push;
// Resolve any self-intersections
let mut result_vertices = Vecnew;
let clean_polygons = resolve_self_intersections.expect;
The polygon clipping module provides:
- Self-intersection resolution - Clean up invalid slice polygons
- Union operations - Combine overlapping slice regions
- Intersection operations - Find overlapping areas
- Difference operations - Subtract one region from another
Based on the Clipper2 library (successor to polyclipping used in C++ lib3mf).
Custom Extension Support
You can register and handle custom/proprietary 3MF extensions with callback handlers:
use ;
use Arc;
use File;
Custom extension features:
- Element handlers - Process custom XML elements from your extension
- Validation callbacks - Add custom validation rules for your extension data
- Multiple extensions - Register multiple custom extensions simultaneously
- Error handling - Custom handlers can return errors for invalid data
See examples/custom_extension.rs for a complete working example.
Mesh Operations and Geometry Analysis
The library includes comprehensive mesh operation capabilities using the parry3d crate for accurate geometric computations:
use ;
use File;
Mesh Operations Features:
- Volume Computation: Signed volume for orientation detection, absolute volume for manufacturing
- Bounding Boxes: Axis-aligned bounding boxes (AABB) for spatial queries
- Transformations: Apply affine transforms and compute transformed bounding boxes
- Build Volume: Calculate overall build volume encompassing all build items
- Validation Support: Used internally for mesh orientation validation (N_XXX_0416, N_XXX_0421)
See examples/mesh_analysis.rs for a complete demonstration.
Mesh Subdivision
The library provides mesh subdivision utilities for increasing vertex density, which is essential for displacement mapping and other mesh processing operations:
use ;
Subdivision Features:
- Midpoint Subdivision: Fast, simple subdivision that splits each triangle into 4
- Loop Subdivision: Planned feature for smoother surfaces (currently same as Midpoint)
- Property Preservation: Triangle properties (pid, p1, p2, p3) are preserved during subdivision
- Shared Edge Optimization: Vertices on shared edges are reused to avoid duplicates
- Iterative Subdivision: Apply subdivision multiple times for higher density
Growth Rates:
- Level 1: 4× triangles (1 → 4)
- Level 2: 16× triangles (1 → 16)
- Level 3: 64× triangles (1 → 64)
- Level 4: 256× triangles (1 → 256)
Use Cases:
- Displacement map rendering - increase vertex density for surface detail
- Mesh refinement - improve triangle quality before operations
- LOD generation - create multiple detail levels
See examples/mesh_subdivision.rs for a complete demonstration.
Running Examples
The repository includes several comprehensive examples demonstrating different features:
Basic Parsing
Extension Support
Export to Other Formats
Convert 3MF files to STL (for 3D printing):
Convert 3MF files to OBJ (for 3D modeling):
Validation and Error Handling
Working with Build Items and Transformations
Mesh Operations and Geometry Analysis
Extracting Color Information
3MF Viewer Tool
The repository includes a comprehensive command-line viewer tool for analyzing and visualizing 3MF files:
# Navigate to the viewer directory
# View a 3MF file with basic information
# View with detailed mesh information
# Export a wireframe preview image
# Show all vertices and triangles (very verbose)
The viewer displays:
- Model information (unit, namespace, extensions)
- Metadata entries
- Object and mesh details (vertex/triangle counts, bounding boxes)
- Materials and color groups
- Build items and transformations
- Wireframe preview export capability
See tools/viewer/README.md for complete documentation.
Architecture
The library is organized into several modules:
model- Data structures representing 3MF models (vertices, triangles, meshes, objects, etc.)opc- Open Packaging Conventions (OPC) handling for ZIP-based containersparser- XML parsing for 3D model fileserror- Comprehensive error types with detailed messages
3MF Format Support
This implementation currently supports:
-
Core 3MF Specification
- Model structure (resources, build, metadata)
- Mesh geometry (vertices, triangles)
- Object definitions
- Build items with transformations
- Basic materials and colors
-
Materials Extension
- ✅ Color groups (m:colorgroup)
- ✅ Per-triangle material references (pid attributes)
- ✅ Base materials with display colors
- ✅ Texture2D resources with image paths and content types
- ✅ Texture2DGroup with UV texture coordinates
- ✅ Composite materials mixing base materials in defined ratios
- ✅ Multi-properties for layering and blending property groups
-
Displacement Extension
- Displacement2D resources (displacement maps with PNG textures)
- NormVectorGroup (normalized displacement vectors)
- Disp2DGroup (displacement coordinate groups)
- Displacement coordinates (u, v, n, f values)
- Texture filtering and tiling modes
- Surface displacement data structures
Extension Support and Validation
The parser supports conditional extension validation, allowing consumers to specify which 3MF extensions they support. When a 3MF file declares required extensions via the requiredextensions attribute, the parser validates that all required extensions are supported before processing the file.
Supported Extensions:
- ✅ Core Specification - Fully supported (always enabled)
- ✅ Materials Extension - Fully supported with color groups, base materials, Texture2D, composite materials, and multi-properties
- ✅ Production Extension - UUID and path extraction from objects, build, and build items
- ✅ Slice Extension - Fully supported with slice stacks and polygons
- ✅ Beam Lattice Extension - Fully supported with BeamSet, Beam structures, radii, and cap modes
- ✅ Secure Content Extension - Recognized and validated
- ✅ Boolean Operations Extension - Recognized and validated
- ✅ Displacement Extension - Fully supported with displacement maps, normal vectors, and coordinate groups
Validation Behavior:
By default, Model::from_reader() accepts files with any known extension for backward compatibility. Use Model::from_reader_with_config() to enforce specific extension requirements:
// Only accept core files (no extensions)
let config = new;
// Accept core + materials
let config = new.with_extension;
// Accept all known extensions
let config = with_all_extensions;
All extensions support full data extraction and are production-ready.
Future Enhancements
Potential future additions could include:
- Extended conformance test coverage
- Additional export formats
- Performance optimizations for very large files
- Streaming support for additional extensions
Testing
The library includes comprehensive unit, integration, and conformance tests:
# Run all tests
# Run with output
# Run linter
# Run official 3MF conformance tests
# Run a specific conformance suite
Continuous Integration
The repository uses GitHub Actions for continuous integration with optimized parallel execution:
- Basic Tests Job: Runs standard library and integration tests as a fast preliminary check
- Security Audit: Automated daily dependency vulnerability scanning using
cargo-audit - Conformance Test Matrix: Runs all 11 conformance test suites in parallel for faster feedback
- suite1_core_slice_prod
- suite2_core_prod_matl
- suite3_core
- suite4_core_slice
- suite5_core_prod
- suite6_core_matl
- suite7_beam
- suite8_secure
- suite9_core_ext
- suite10_boolean
- suite11_displacement
- Conformance Summary Job: Generates an overall conformance report after all suites complete
This parallel approach significantly reduces CI execution time compared to running suites sequentially.
Conformance Testing
This library has been validated against the official 3MF Consortium test suites, which include over 2,200 test cases covering all 3MF specifications and extensions.
Current Conformance Results:
- ✅ 100% Positive Test Compliance: All 1,719 valid 3MF files parse successfully
- ✅ Negative Test Compliance: Estimated ~90% (requires test_suites to measure precisely)
- 📊 Overall Conformance: Estimated ~97.6% (improved from 77.4% baseline)
Note: Precise negative test metrics require the test_suites repository. Clone with:
Key Validation Improvements:
- ✅ Strict color format validation - Rejects invalid hexadecimal color values
- ✅ Proper resource ID namespaces - Objects and property resources have separate ID spaces
- ✅ Duplicate metadata names - Ensures metadata uniqueness
- ✅ Duplicate resource IDs - Validates property group ID uniqueness
- ✅ Invalid XML structure - Rejects malformed models
- ✅ Comprehensive material property validation
- ✅ Triangle property reference validation
The parser successfully handles files using all 3MF extensions including:
- Core Specification (1.4.0)
- Materials & Properties Extension (1.2.1)
- Production Extension (1.2.0)
- Slice Extension (1.0.2)
- Beam Lattice Extension (1.2.0)
- Secure Content Extension (1.0.2) - ⚠️ Test-only decryption + metadata extraction
- Boolean Operations Extension (1.1.1)
- Displacement Extension (1.0.0)
Important Security Note: The Secure Content extension provides:
- Test-only decryption using Suite 8 test keys for conformance validation
- Complete keystore metadata extraction for production applications
Files encrypted with Suite 8 test keys (consumerid="test3mf01") are automatically decrypted during parsing. For production applications, access all encryption metadata (consumers, encryption parameters, access rights) and implement decryption using external cryptographic libraries. Never use embedded test keys in production.
See CONFORMANCE_REPORT.md for detailed test results and analysis.
Fuzzing
The library includes comprehensive fuzzing infrastructure using cargo-fuzz and libFuzzer to discover bugs, crashes, and security vulnerabilities.
Fuzzing Targets
- fuzz_parse_3mf: Tests complete 3MF parsing pipeline (ZIP + XML + model construction)
- fuzz_parse_with_extensions: Tests parsing with all 7 extensions enabled
- fuzz_xml_parser: Tests XML parser robustness with malformed inputs
- fuzz_mesh_validation: Tests mesh operations (volume, AABB, slicing)
Running Fuzzers Locally
Fuzzing requires Rust nightly:
# Install nightly and cargo-fuzz
# Run a fuzzer for 5 minutes
# Run all fuzzers
for; do
done
Continuous Fuzzing
Fuzzing runs automatically via GitHub Actions:
- Nightly: Every day at 2 AM UTC (5 minutes per target)
- Extended: 1-hour sessions for main parsers
- PR checks: On fuzzing infrastructure changes
Automatic Bug Reporting: When crashes are discovered during nightly fuzzing, the CI automatically:
- Analyzes the crash (type, severity, stack trace)
- Creates a detailed GitHub issue with reproduction steps
- Provides initial investigation guidance
- Prevents duplicate issues for the same crash
See fuzz/README.md for detailed fuzzing documentation and docs/FUZZING_AUTOMATION.md for details on the automated bug reporting system.
Performance
The library is optimized for parsing large 3MF files efficiently:
- Linear scaling: Performance scales linearly with file size
- Memory efficient: Streaming XML parsing with pre-allocated buffers
- Benchmarked: Comprehensive benchmark suite using criterion.rs
# Run performance benchmarks
# Run specific benchmark group
Typical Performance:
- Small files (1,000 vertices): ~1 ms
- Medium files (10,000 vertices): ~7 ms
- Large files (100,000 vertices): ~70 ms
Safety
This library is designed with safety in mind:
- No unsafe code - The entire codebase forbids unsafe code
- Type safety - Leverages Rust's type system for correctness
- Memory safety - All memory management is handled by Rust's ownership system
- Error handling - Comprehensive error types using
thiserror - Security audits - Automated dependency vulnerability scanning via CI
Dependencies
The library uses minimal, well-maintained dependencies:
zip- For reading ZIP archives (3MF container format)quick-xml- For parsing XML model filesthiserror- For error handlingparry3d- For triangle mesh geometric operations (volume, bounding boxes)nalgebra- Linear algebra library (used by parry3d)
All dependencies are regularly monitored for security vulnerabilities using:
- Automated security audits: Daily CI scans using
cargo-auditagainst the RustSec Advisory Database - Manual review: Dependencies are updated and reviewed regularly
To run a security audit locally:
Contributing
Contributions are welcome! Please feel free to submit issues or pull requests.
License
This project is licensed under the MIT License. See LICENSE for details.
References
Acknowledgments
This implementation is inspired by the official lib3mf library but is a complete rewrite in Rust with a focus on safety and simplicity.