egraphics_io/
export.rs

1use crate::error::Error;
2use crate::export_impl::write_gltf_file;
3use egraphics_core::TriangleMesh;
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8/// `EgraphicsExporter` exports to glTF 2.0 and derives to additional formats.
9///
10/// * `path` - Path to file with gltf extension.
11/// * `derive_obj_file` - If true, also derive an obj file (dependency [assimp](https://github.com/assimp/assimp)).
12#[derive(Debug, Clone)]
13pub struct EgraphicsExporter {
14    path: PathBuf,
15    derive_obj_file: bool,
16    create_parent_directories: bool,
17}
18
19impl EgraphicsExporter {
20    pub fn new(path: impl AsRef<Path>) -> Self {
21        Self {
22            path: path.as_ref().to_owned(),
23            derive_obj_file: false,
24            create_parent_directories: false,
25        }
26    }
27
28    pub fn with_derive_obj_file(mut self, derive_obj_file: bool) -> Self {
29        self.derive_obj_file = derive_obj_file;
30        self
31    }
32
33    pub fn with_create_parent_directories(mut self, create_parent_directories: bool) -> Self {
34        self.create_parent_directories = create_parent_directories;
35        self
36    }
37
38    pub fn get_obj_file_path(&self) -> PathBuf {
39        self.path.clone().with_extension("obj")
40    }
41
42    pub fn finish(&self, triangle_mesh: TriangleMesh) -> Result<(), Error> {
43        if self.create_parent_directories {
44            fs::create_dir_all(self.path.parent().unwrap())?;
45        }
46
47        write_gltf_file(triangle_mesh, &self.path);
48
49        if self.derive_obj_file {
50            let mut child = Command::new("assimp")
51                .arg("export")
52                .arg(&self.path)
53                .arg(self.get_obj_file_path())
54                .spawn()
55                .expect("assimp command failed to start");
56
57            let _result = child.wait().unwrap();
58        }
59
60        Ok(())
61    }
62}