Skip to main content

02_write_read/
02_write_read.rs

1//! Read and write: chain STEP, BRep text, and BRep binary round-trips with progressive rotation.
2
3use cadrum::{Compound, DVec3, Solid};
4use std::f64::consts::FRAC_PI_8;
5
6fn main() -> Result<(), cadrum::Error> {
7    let example_name = std::path::Path::new(file!()).file_stem().unwrap().to_str().unwrap();
8    let step_path = format!("{example_name}.step");
9    let text_path = format!("{example_name}_text.brep");
10    let brep_path = format!("{example_name}.brep");
11
12    // 0. Original: read colored_box.step
13    let manifest_dir = env!("CARGO_MANIFEST_DIR");
14    let original = cadrum::read_step(
15        &mut std::fs::File::open(format!("{manifest_dir}/steps/colored_box.step")).expect("open file"),
16    )?;
17
18    // 1. STEP round-trip: rotate 30° → write → read
19    let a_written = original.clone().rotate_x(FRAC_PI_8);
20    cadrum::write_step(&a_written, &mut std::fs::File::create(&step_path).expect("create file"))?;
21    let a = cadrum::read_step(&mut std::fs::File::open(&step_path).expect("open file"))?;
22
23    // 2. BRep text round-trip: rotate another 30° → write → read
24    let b_written = a.clone().rotate_x(FRAC_PI_8);
25    cadrum::write_brep_text(&b_written, &mut std::fs::File::create(&text_path).expect("create file"))?;
26    let b = cadrum::read_brep_text(&mut std::fs::File::open(&text_path).expect("open file"))?;
27
28    // 3. BRep binary round-trip: rotate another 30° → write → read
29    let c_written = b.clone().rotate_x(FRAC_PI_8);
30    cadrum::write_brep_binary(&c_written, &mut std::fs::File::create(&brep_path).expect("create file"))?;
31    let c = cadrum::read_brep_binary(&mut std::fs::File::open(&brep_path).expect("open file"))?;
32
33    // 4. Arrange side by side and export SVG + STL
34    let [min, max] = original[0].bounding_box();
35    let spacing = (max - min).length() * 1.5;
36    let all: Vec<Solid> = [original, a, b, c].into_iter()
37        .enumerate()
38        .flat_map(|(i, solids)| solids.translate(DVec3::X * spacing * i as f64))
39        .collect();
40
41    let mut svg = std::fs::File::create(format!("{example_name}.svg")).expect("create file");
42    cadrum::mesh(&all, 0.5).and_then(|m| m.write_svg(DVec3::new(1.0, 1.0, 2.0), DVec3::Z, true, false, &mut svg))?;
43
44    let mut stl = std::fs::File::create(format!("{example_name}.stl")).expect("create file");
45    cadrum::mesh(&all, 0.1).and_then(|m| m.write_stl(&mut stl))?;
46
47    // 5. Print summary
48    let stl_path = format!("{example_name}.stl");
49    for (label, path) in [("STEP", &step_path), ("BRep text", &text_path), ("BRep binary", &brep_path), ("STL", &stl_path)] {
50        let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
51        println!("{label:12} {path:30} {size:>8} bytes");
52    }
53
54    Ok(())
55}