Skip to content

Commit

Permalink
Merge pull request #1739 from replicadse/main
Browse files Browse the repository at this point in the history
OBJ file format for export
  • Loading branch information
hannobraun authored Apr 3, 2023
2 parents e4ccc84 + 7bac970 commit 5605dd9
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/fj-export/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ fj-math.workspace = true
thiserror = "1.0.40"
threemf = "0.4.0"
stl = "0.2.1"
wavefront_rs = "2.0.0-alpha.1"
58 changes: 57 additions & 1 deletion crates/fj-export/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
#![warn(missing_docs)]

use std::{fs::File, path::Path};
use std::{fs::File, io::Write, path::Path};

use thiserror::Error;

Expand All @@ -35,6 +35,9 @@ pub fn export(mesh: &Mesh<Point<3>>, path: &Path) -> Result<(), Error> {
Some(extension) if extension.to_ascii_uppercase() == "STL" => {
export_stl(mesh, path)
}
Some(extension) if extension.to_ascii_uppercase() == "OBJ" => {
export_obj(mesh, path)
}
Some(extension) => Err(Error::InvalidExtension(
extension.to_string_lossy().into_owned(),
)),
Expand Down Expand Up @@ -119,6 +122,55 @@ fn export_stl(mesh: &Mesh<Point<3>>, path: &Path) -> Result<(), Error> {
Ok(())
}

fn export_obj(mesh: &Mesh<Point<3>>, path: &Path) -> Result<(), Error> {
let mut f = File::create(path)?;

for (cnt, t) in mesh.triangles().enumerate() {
// write each point of the triangle
for v in t.inner.points() {
wavefront_rs::obj::writer::Writer::write(
&mut f,
&wavefront_rs::obj::entity::Entity::Vertex {
x: v.x.into_f64(),
y: v.y.into_f64(),
z: v.z.into_f64(),
w: None,
},
)
.or(Err(Error::OBJ))?;
f.write_all(b"\n")?;
}

// write the triangle
wavefront_rs::obj::writer::Writer::write(
&mut f,
&wavefront_rs::obj::entity::Entity::Face {
vertices: vec![
wavefront_rs::obj::entity::FaceVertex {
vertex: (cnt * 3 + 1) as i64,
texture: None,
normal: None,
},
wavefront_rs::obj::entity::FaceVertex {
vertex: (cnt * 3 + 2) as i64,
texture: None,
normal: None,
},
wavefront_rs::obj::entity::FaceVertex {
vertex: (cnt * 3 + 3) as i64,
texture: None,
normal: None,
},
],
},
)
.or(Err(Error::OBJ))?;
f.write_all(b"\n")?;
}

Ok(())
}

/// An error that can occur while exporting
#[derive(Debug, Error)]
pub enum Error {
Expand All @@ -141,4 +193,8 @@ pub enum Error {
/// Threemf error whilst exporting to 3MF file
#[error("threemf error whilst exporting to 3MF file")]
ThreeMF(#[from] threemf::Error),

/// OBJ exporter error whilst exporting to OBJ file
#[error("obj error whilst exporting to OBJ file")]
OBJ,
}

0 comments on commit 5605dd9

Please sign in to comment.