Skip to main content

04_boolean/
04_boolean.rs

1//! Boolean operations: union, subtract, and intersect between a box and a cylinder.
2
3use cadrum::{Compound, DVec3, Solid};
4
5fn main() -> Result<(), cadrum::Error> {
6    let example_name = std::path::Path::new(file!()).file_stem().unwrap().to_str().unwrap();
7
8    let make_box = Solid::cube(20.0, 20.0, 20.0)
9        .color("#4a90d9");
10    let make_cyl = Solid::cylinder(8.0, DVec3::Z, 30.0)
11        .translate(DVec3::new(10.0, 10.0, -5.0))
12        .color("#e67e22");
13
14    // union: merge both shapes into one — offset X=0
15    let union = make_box
16        .union(&[make_cyl.clone()])?;
17
18    // subtract: box minus cylinder — offset X=40
19    let subtract = make_box
20        .subtract(&[make_cyl.clone()])?
21        .translate(DVec3::X * 40.0);
22
23    // intersect: only the overlapping volume — offset X=80
24    let intersect = make_box
25        .intersect(&[make_cyl])?
26        .translate(DVec3::X * 80.0);
27
28    let shapes: Vec<Solid> = [union, subtract, intersect].concat();
29
30    let mut f = std::fs::File::create(format!("{example_name}.step")).expect("failed to create file");
31    cadrum::write_step(&shapes, &mut f).expect("failed to write STEP");
32
33    let mut svg = std::fs::File::create(format!("{example_name}.svg")).expect("failed to create SVG file");
34    cadrum::mesh(&shapes, 0.5).and_then(|m| m.write_svg(DVec3::new(1.0, 1.0, 2.0), DVec3::Z, true, false, &mut svg)).expect("failed to write SVG");
35
36    Ok(())
37}