Skip to main content

rscad_openscad/
import.rs

1use crate::*;
2use std::path::{Path, PathBuf};
3
4#[derive(Debug, Clone)]
5pub struct ImportedObject {
6    pub path: PathBuf,
7    pub convexity: Option<f64>,
8}
9
10impl rscad_core::Object for ImportedObject {}
11
12pub fn import(path: impl AsRef<Path>) -> Result<ImportedObject> {
13    ImportedObject::new(path)
14}
15
16impl ImportedObject {
17    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
18        Ok(Self {
19            path: dunce::canonicalize(path).change_context(Error)?,
20            convexity: None,
21        })
22    }
23    pub fn with_convexity<T: Number>(mut self, convexity: impl Into<Option<T>>) -> Self {
24        self.convexity = convexity.into().map(|c| c.to_f64());
25        self
26    }
27}
28
29impl OpenscadCodegen for ImportedObject {
30    fn render_fmt(&self, writer: &mut dyn core::fmt::Write) -> Result<()> {
31        write!(writer, "import(\"{}\"", self.path.display())
32            .change_context(Error)
33            .attach("Failed to render imported object")?;
34        if let Some(convexity) = self.convexity {
35            write!(writer, ", convexity = {}", convexity)
36                .change_context(Error)
37                .attach("Failed to render imported object")?;
38        }
39        write!(writer, ");")
40            .change_context(Error)
41            .attach("Failed to render imported object")?;
42        Ok(())
43    }
44}