microcad_export/stl/
writer.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! STL Export
5
6use microcad_core::*;
7
8/// Write into STL file
9pub struct StlWriter<'a> {
10    writer: &'a mut dyn std::io::Write,
11}
12
13impl<'a> StlWriter<'a> {
14    /// Create new STL writer
15    pub fn new(mut w: &'a mut dyn std::io::Write) -> std::io::Result<Self> {
16        writeln!(&mut w, "solid")?;
17
18        Ok(Self { writer: w })
19    }
20
21    /// Write triangle
22    pub fn write_triangle(&mut self, tri: &Triangle<&cgmath::Vector3<f32>>) -> std::io::Result<()> {
23        let n = tri.normal();
24        writeln!(&mut self.writer, "facet normal {} {} {}", n.x, n.y, n.z)?;
25        writeln!(&mut self.writer, "\touter loop")?;
26        writeln!(
27            &mut self.writer,
28            "\t\tvertex {} {} {}",
29            tri.0.x, tri.0.y, tri.0.z
30        )?;
31        writeln!(
32            &mut self.writer,
33            "\t\tvertex {} {} {}",
34            tri.1.x, tri.1.y, tri.1.z
35        )?;
36        writeln!(
37            &mut self.writer,
38            "\t\tvertex {} {} {}",
39            tri.2.x, tri.2.y, tri.2.z
40        )?;
41        writeln!(&mut self.writer, "\tendloop")?;
42        writeln!(&mut self.writer, "endfacet")?;
43        Ok(())
44    }
45}
46
47impl Drop for StlWriter<'_> {
48    fn drop(&mut self) {
49        writeln!(self.writer, "endsolid").expect("No error");
50    }
51}