use std::fmt;
use std::path::Path;
use std::sync::Arc;
use super::{Format, Input};
use crate::assets::{Assets, Memory};
use crate::document::{Document, Keep};
use crate::{Bytes, Result};
#[cfg(feature = "fs")]
pub fn open(path: impl AsRef<Path>) -> Result<Document> {
Loader::new().open(path)
}
pub fn read(bytes: impl Into<Bytes>, name: &str) -> Result<Document> {
Loader::new().read(bytes, name)
}
#[derive(Clone, Default)]
pub struct Loader {
keep: Keep,
assets: Option<Arc<dyn Assets + Send + Sync>>,
format: Option<Format>,
}
impl fmt::Debug for Loader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Loader")
.field("keep", &self.keep)
.field("assets", &self.assets.is_some())
.field("format", &self.format)
.finish()
}
}
impl Loader {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn keep(mut self, keep: Keep) -> Self {
self.keep = keep;
self
}
#[must_use]
pub fn assets(mut self, assets: impl Assets + Send + Sync + 'static) -> Self {
self.assets = Some(Arc::new(assets));
self
}
#[must_use]
pub fn format(mut self, format: Format) -> Self {
self.format = Some(format);
self
}
#[cfg(feature = "fs")]
pub fn open(&self, path: impl AsRef<Path>) -> Result<Document> {
let path = std::path::absolute(path.as_ref()).map_err(|e| crate::Error::from(e).at(path.as_ref()))?;
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let folder;
let assets: &dyn Assets = if let Some(a) = &self.assets {
&**a
} else {
folder = crate::assets::Folder::new(path.parent().unwrap_or(&path));
&folder
};
super::load_as(&path, ext, self.format, assets, self.keep)
}
pub fn read(&self, bytes: impl Into<Bytes>, name: &str) -> Result<Document> {
let bytes = bytes.into();
let path = Path::new(name);
let input = Input::shared(&bytes, path);
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let ext = super::extension_as(input, ext, self.format);
let none = Memory::new();
let assets: &dyn Assets = match &self.assets {
Some(a) => &**a,
None => &none,
};
super::read_input(input, ext, assets, self.keep)
}
}
#[cfg(all(test, feature = "obj"))]
mod tests {
use super::*;
const TRIANGLE: &[u8] = b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
#[test]
fn a_model_in_memory_is_read_by_its_name_or_its_format() {
assert_eq!(read(TRIANGLE, "a.OBJ").unwrap().counts().triangles, 1);
let told = read(TRIANGLE, "a.bin").unwrap();
assert_eq!(
told.counts().triangles,
1,
"an unknown extension's format is told by the bytes"
);
assert!(read(&b"nothing to tell"[..], "a.bin").is_err());
assert!(
read(TRIANGLE, "a.stl").is_err(),
"a known extension wins over the bytes"
);
let doc = Loader::new().format(Format::Obj).read(TRIANGLE, "a.stl").unwrap();
assert_eq!(doc.counts().triangles, 1);
}
#[test]
fn what_a_loader_keeps_and_where_it_finds_files() {
let obj = b"mtllib a.mtl\nusemtl red\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
let mtl = b"newmtl red\nKd 1 0 0\n";
let loader = Loader::new().assets(Memory::new().with("m/a.mtl", &mtl[..]));
let doc = loader.read(&obj[..], "m/a.obj").unwrap();
assert_eq!(doc.json()["materials"][0]["name"], "red");
let doc = loader
.clone()
.keep(Keep::ALL.with_materials(false))
.read(&obj[..], "m/a.obj")
.unwrap();
assert!(doc.json().get("materials").is_none());
assert!(format!("{loader:?}").contains("Loader"));
}
#[cfg(feature = "gltf")]
#[test]
fn a_glb_in_memory_keeps_its_bytes_shared() {
let glb = Bytes::from(read(TRIANGLE, "t.obj").unwrap().to_glb().unwrap());
let doc = read(glb.clone(), "m.glb").unwrap();
let crate::document::Blob::Bytes(kept) = &doc.buffers[0] else {
panic!("the binary chunk is held as bytes")
};
let (all, part) = (glb.as_ptr_range(), kept.as_ptr_range());
assert!(
all.start <= part.start && part.end <= all.end,
"and shared with the GLB's"
);
}
}