Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fj::Instance #2217

Merged
merged 10 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions crates/fj-core/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::{layers::Layers, validate::ValidationConfig};
/// An instance of the Fornjot core
///
/// This is the main entry point to `fj-core`'s API.
#[derive(Default)]
pub struct Instance {
/// The layers of data that make up the state of a core instance
pub layers: Layers,
Expand All @@ -15,8 +16,7 @@ pub struct Instance {
impl Instance {
/// Construct an instance of `Instance`
pub fn new() -> Self {
let layers = Layers::new();
Self { layers }
Self::default()
}

/// Construct an instance of `Instance`, using the provided configuration
Expand All @@ -25,9 +25,3 @@ impl Instance {
Self { layers }
}
}

impl Default for Instance {
fn default() -> Self {
Self::new()
}
}
6 changes: 3 additions & 3 deletions crates/fj/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use fj_math::Scalar;
/// interface for viewing and exporting models, and is used for Fornjot's
/// example models and the testing infrastructure they are part of.
///
/// You might not want to use this struct directly. [`handle_model`] Provides a
/// more high-level and convenient interface.
/// You might not want to use this struct directly. [`Instance::process_model`]
/// provides a more high-level and convenient interface.
///
/// [`handle_model`]: crate::handle_model()
/// [`Instance::process_model`]: crate::Instance::process_model
#[derive(clap::Parser)]
pub struct Args {
/// Export model to this path
Expand Down
133 changes: 0 additions & 133 deletions crates/fj/src/handle_model.rs

This file was deleted.

154 changes: 154 additions & 0 deletions crates/fj/src/instance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
use std::{error::Error as _, fmt};

use fj_core::{
algorithms::{
approx::{InvalidTolerance, Tolerance},
bounding_volume::BoundingVolume,
triangulate::Triangulate,
},
validate::{ValidationConfig, ValidationErrors},
};
use fj_interop::Model;
use fj_math::{Aabb, Point, Scalar};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

use crate::Args;

/// An instance of Fornjot
///
/// This is the main entry point into the Fornjot API
#[derive(Default)]
pub struct Instance {
/// The instance of the Fornjot core
pub core: fj_core::Instance,
}

impl Instance {
/// Construct an instance of `Instance`
pub fn new() -> Self {
Self::default()
}

/// Construct an instance of `Instance`, using the provided configuration
pub fn with_validation_config(config: ValidationConfig) -> Self {
let core = fj_core::Instance::with_validation_config(config);
Self { core }
}

/// Export or display a model, according to CLI arguments
///
/// This function is intended to be called by applications that define a
/// model and want to provide a standardized CLI interface for dealing with
/// that model.
///
/// This function is used by Fornjot's own testing infrastructure, but is
/// useful beyond that, when using Fornjot directly to define a model.
pub fn process_model<M>(&mut self, model: &M) -> Result
where
for<'r> (&'r M, Tolerance): Triangulate,
M: BoundingVolume<3>,
{
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer())
.with(tracing_subscriber::EnvFilter::from_default_env())
.init();

let args = Args::parse();

if !args.ignore_validation {
self.core.layers.validation.take_errors()?;
}

let aabb = model.aabb().unwrap_or(Aabb {
min: Point::origin(),
max: Point::origin(),
});

let tolerance = match args.tolerance {
None => {
// Compute a reasonable default for the tolerance value. To do
// this, we just look at the smallest non-zero extent of the
// bounding box and divide that by some value.

let mut min_extent = Scalar::MAX;
for extent in aabb.size().components {
if extent > Scalar::ZERO && extent < min_extent {
min_extent = extent;
}
}

let tolerance = min_extent / Scalar::from_f64(1000.);
Tolerance::from_scalar(tolerance)?
}
Some(user_defined_tolerance) => user_defined_tolerance,
};

let mesh = (model, tolerance).triangulate();

if let Some(path) = args.export {
crate::export::export(&mesh, &path)?;
return Ok(());
}

let model = Model { mesh, aabb };

crate::window::display(model, false)?;

Ok(())
}
}

/// Return value of [`Instance::process_model`]
pub type Result = std::result::Result<(), Error>;

/// Error returned by [`Instance::process_model`]
#[derive(thiserror::Error)]
pub enum Error {
/// Failed to set up logger
#[error("Failed to set up logger")]
Tracing(#[from] tracing::subscriber::SetGlobalDefaultError),

/// Error displaying model
#[error("Error displaying model")]
Display(#[from] crate::window::Error),

/// Error exporting model
#[error("Error exporting model")]
Export(#[from] crate::export::Error),

/// Invalid tolerance
#[error(transparent)]
Tolerance(#[from] InvalidTolerance),

/// Unhandled validation errors
#[error(transparent)]
Validation(#[from] ValidationErrors),
}

impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// When returning an error from Rust's `main` function, the runtime uses
// the error's `Debug` implementation to display it, not the `Display`
// one. This is unfortunate, and forces us to override `Debug` here.

// We should be able to replace this with `Report`, once it is stable:
// https://doc.rust-lang.org/std/error/struct.Report.html

write!(f, "{self}")?;

let mut source = self.source();

if source.is_some() {
write!(f, "\n\nCaused by:")?;
}

let mut i = 0;
while let Some(s) = source {
write!(f, "\n {i}: {s}")?;
source = s.source();
i += 1;
}

Ok(())
}
}
4 changes: 2 additions & 2 deletions crates/fj/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
//! [Fornjot]: https://www.fornjot.app/

mod args;
mod handle_model;
mod instance;

pub use self::{
args::Args,
handle_model::{handle_model, Error, Result},
instance::{Error, Instance, Result},
};

pub use fj_core as core;
Expand Down
8 changes: 3 additions & 5 deletions models/all/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use fj::handle_model;

fn main() -> fj::Result {
let mut core = fj::core::Instance::new();
let model = all::model(&mut core);
handle_model(&model, core)?;
let mut fj = fj::Instance::new();
let model = all::model(&mut fj.core);
fj.process_model(&model)?;
Ok(())
}
8 changes: 3 additions & 5 deletions models/color/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use fj::handle_model;

fn main() -> fj::Result {
let mut core = fj::core::Instance::new();
let model = color::model(&mut core);
handle_model(&model, core)?;
let mut fj = fj::Instance::new();
let model = color::model(&mut fj.core);
fj.process_model(&model)?;
Ok(())
}
8 changes: 3 additions & 5 deletions models/cuboid/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use fj::handle_model;

fn main() -> fj::Result {
let mut core = fj::core::Instance::new();
let model = cuboid::model([3., 2., 1.], &mut core);
handle_model(&model, core)?;
let mut fj = fj::Instance::new();
let model = cuboid::model([3., 2., 1.], &mut fj.core);
fj.process_model(&model)?;
Ok(())
}
8 changes: 3 additions & 5 deletions models/holes/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use fj::handle_model;

fn main() -> fj::Result {
let mut core = fj::core::Instance::new();
let model = holes::model(0.25, &mut core);
handle_model(&model, core)?;
let mut fj = fj::Instance::new();
let model = holes::model(0.25, &mut fj.core);
fj.process_model(&model)?;
Ok(())
}
Loading