use std::path::{Component, Path};
use serde_json::{Map, Value, json};
use super::{Input, gltf1};
use crate::assets::Assets;
use crate::document::{Blob, Document, Keep};
use crate::gltf as container;
use crate::images::{Location, Reference};
use crate::num::usize_of;
use crate::{Bytes, Context as _, ErrorKind, Result};
pub(crate) fn load(input: Input<'_>, assets: &dyn Assets, keep: Keep) -> Result<Document> {
let (json, mut bin) = match input.bytes() {
Some(b) if b.starts_with(b"glTF") => glb_in_memory(b, |part| input.share(part))?,
Some(b) => (gltf_json(b)?, None),
#[cfg(feature = "fs")]
None => open_file(input.path)?,
#[cfg(not(feature = "fs"))]
None => unreachable!("a model without its bytes needs the `fs` feature"),
};
let (mut json, fix) = if gltf1::is_v1(&json) {
let (json, fix) = gltf1::upgrade(json)?;
(json, Some(fix))
} else {
(json, None)
};
let version = json
.get("asset")
.and_then(|a| a.get("version"))
.and_then(Value::as_str)
.unwrap_or("")
.to_owned();
if version.starts_with('1') {
let asset = &mut json["asset"];
asset["version"] = "2.0".into();
let extras = &mut asset["extras"];
if !extras.is_object() {
*extras = Value::Object(Map::new());
}
let source = &mut extras["source"];
if !source.is_object() {
*source = Value::Object(Map::new());
}
source["version"] = version.into();
} else {
ensure!(
version.starts_with("2."),
Unsupported,
"glTF version {version:?} isn't 1.x or 2.x"
);
}
let mut doc = Document::new(json, Vec::new(), Map::new(), crate::images::Refs::new());
let n = doc.base.get("buffers").and_then(Value::as_array).map_or(0, Vec::len);
for i in 0..n {
let b = &mut doc.base_mut()["buffers"][i];
let declared = b.get("byteLength").and_then(Value::as_u64).unwrap_or(0);
let fallback = container::is_fallback(b);
let blob = match b.get("uri").and_then(Value::as_str) {
Some(uri) if uri.starts_with("data:") => Blob::Bytes(container::data_uri(uri)?.1.into()),
Some(uri) => match external(input, assets, uri) {
Ok(blob) => blob,
Err(_) if fallback => Blob::Missing(declared),
Err(e) => return Err(e),
},
None if i == 0 && bin.is_some() => bin.take().expect("checked"),
None if fallback => Blob::Missing(declared),
None if declared == 0 => Blob::Bytes(Bytes::new()),
None => bail!(Corrupt, "glTF buffer {i} has no data"),
};
ensure!(
blob.len() >= declared,
Truncated,
"glTF buffer {i} is cut short: it holds {} bytes but declares {declared}",
blob.len()
);
if let Some(b) = b.as_object_mut() {
b.remove("uri");
if declared == 0 {
b.insert("byteLength".into(), json!(blob.len()));
}
}
doc.buffers.push(blob);
}
if let Some(fix) = fix {
gltf1::finish(&mut doc, &fix)?;
}
if keep.materials && keep.textures {
if keep.image_bytes {
embed_images(&mut doc, input, assets);
} else {
reference_images(&mut doc, input, assets);
}
}
Ok(doc)
}
fn embed_images(doc: &mut Document, input: Input<'_>, assets: &dyn Assets) {
let n = doc.base.get("images").and_then(Value::as_array).map_or(0, Vec::len);
for i in 0..n {
let img = &doc.base["images"][i];
let Some(uri) = img.get("uri").and_then(Value::as_str) else {
continue;
};
let declared = img.get("mimeType").and_then(Value::as_str);
let typed =
|bytes: &[u8], named: Option<&str>| container::sniff_mime(bytes).or(declared).or(named).map(str::to_owned);
let found = if uri.starts_with("data:") {
container::data_uri(uri)
.ok()
.and_then(|(named, bytes)| Some((typed(&bytes, named.as_deref())?, Blob::Bytes(bytes.into()))))
} else {
let named = container::mime_from_name(&container::percent_decode(uri));
read_external(input, assets, uri)
.ok()
.and_then(|bytes| Some((typed(&bytes, named)?, Blob::Bytes(bytes))))
};
let Some((mime, blob)) = found else { continue };
let len = blob.len();
let buffer = doc.push_blob(blob);
let view = doc.push_view(json!({ "buffer": buffer, "byteLength": len }));
let img = doc.base_mut()["images"][i]
.as_object_mut()
.expect("an image with a uri is an object");
img.remove("uri");
img.insert("bufferView".into(), json!(view));
img.insert("mimeType".into(), json!(mime));
}
}
fn reference_images(doc: &mut Document, input: Input<'_>, assets: &dyn Assets) {
let images = doc.base.get("images").and_then(Value::as_array);
for (i, img) in images.into_iter().flatten().enumerate() {
let Some(uri) = img
.get("uri")
.and_then(Value::as_str)
.filter(|u| !u.starts_with("data:"))
else {
continue;
};
let name = container::percent_decode(uri);
let path = checked(&name).ok().map(|rel| input.dir().join(rel));
#[cfg(feature = "fs")]
let later = input.bytes().is_none();
#[cfg(not(feature = "fs"))]
let later = false;
let found = path.filter(|p| later || assets.read(p).is_some());
let location = found.map_or(Location::Missing, Location::File);
let r = Reference {
found: (later && matches!(location, Location::File(_))).then(std::sync::OnceLock::new),
name,
location,
bytes: None,
raw: true,
};
doc.refs.insert(i, r);
}
}
fn checked(rel: &str) -> Result<&str> {
let safe = !rel.contains(':')
&& Path::new(rel)
.components()
.all(|c| matches!(c, Component::Normal(_) | Component::CurDir | Component::ParentDir));
ensure!(safe, Unsupported, "refusing to read {rel:?}: not a relative path");
Ok(rel)
}
fn external(input: Input<'_>, assets: &dyn Assets, uri: &str) -> Result<Blob> {
read_external(input, assets, uri).map(Blob::Bytes)
}
fn read_external(input: Input<'_>, assets: &dyn Assets, uri: &str) -> Result<Bytes> {
let rel = container::percent_decode(uri);
let p = input.dir().join(checked(&rel)?);
#[cfg(feature = "fs")]
if input.bytes().is_none() {
return read_file(&p, Some(&rel));
}
assets
.read_shared(&p)
.ok_or_else(|| crate::Error::missing(format!("glTF file {rel:?} isn't among the assets")).at(&p))
}
#[cfg(feature = "fs")]
fn read_file(path: &Path, asset: Option<&str>) -> Result<Bytes> {
use std::io::Read as _;
let io = |e: std::io::Error| match asset {
Some(rel) => crate::Error::asset(e, path, format!("glTF file {rel:?}")),
None => crate::Error::from(e),
};
let mut file = std::fs::File::open(path).map_err(io)?;
let len = file.metadata().map_err(io)?.len();
let mut all = Vec::new();
all.try_reserve_exact(usize::try_from(len).unwrap_or(usize::MAX))
.map_err(|_| err!(LimitExceeded, "glTF file of {len} bytes"))?;
file.read_to_end(&mut all).map_err(io)?;
Ok(all.into())
}
type Span = (u64, u64);
fn glb_layout<'b>(
total: u64,
read: impl Fn(u64, usize) -> Result<&'b [u8]>,
) -> Result<(Map<String, Value>, Option<Span>)> {
let head = read(0, 20)?;
let u32_at = |b: &[u8], at: usize| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]);
if u32_at(head, 4) == 1 {
ensure!(u32_at(head, 16) == 0, Corrupt, "binary glTF 1.0 content isn't JSON");
let json_len = u64::from(u32_at(head, 12));
let end = u64::from(u32_at(head, 8)).min(total);
ensure!(20 + json_len <= end, Truncated, "GLB is cut short");
let text = read(20, usize_of(json_len))?;
let json = glb_json(text)?;
return Ok((json, Some((20 + json_len, end - 20 - json_len))));
}
ensure!(
u32_at(head, 4) == 2,
Unsupported,
"GLB version {} is not 1 or 2",
u32_at(head, 4)
);
ensure!(&head[16..20] == b"JSON", Corrupt, "GLB doesn't start with a JSON chunk");
let json_len = u64::from(u32_at(head, 12));
ensure!(20 + json_len <= total, Truncated, "GLB is cut short");
let text = read(20, usize_of(json_len))?;
let json = glb_json(text)?;
let at = (20 + json_len).next_multiple_of(4);
let mut bin = None;
if at + 8 <= total {
let h = read(at, 8)?;
if &h[4..8] == b"BIN\0" {
let base = at + 8;
bin = Some((base, u64::from(u32_at(h, 0)).min(total - base)));
}
}
Ok((json, bin))
}
fn glb_in_memory(bytes: &[u8], share: impl FnOnce(&[u8]) -> Bytes) -> Result<(Map<String, Value>, Option<Blob>)> {
let total = bytes.len() as u64;
let (json, bin) = glb_layout(total, |off, len| {
bytes
.get(usize_of(off)..usize_of(off).saturating_add(len))
.context(ErrorKind::Truncated, "GLB is cut short")
})?;
let bin = bin.map(|(base, len)| Blob::Bytes(share(&bytes[usize_of(base)..usize_of(base + len)])));
Ok((json, bin))
}
fn glb_json(text: &[u8]) -> Result<Map<String, Value>> {
let text = text.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(text);
let end = text.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1);
let Value::Object(json) =
crate::json::from_slice(&text[..end]).context(ErrorKind::Corrupt, "GLB JSON doesn't parse")?
else {
bail!(Corrupt, "glTF JSON is not an object")
};
Ok(json)
}
fn gltf_json(bytes: &[u8]) -> Result<Map<String, Value>> {
let text = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
match crate::json::from_slice(text) {
Ok(Value::Object(m)) => Ok(m),
_ => bail!(UnknownFormat, "not a glTF file: neither GLB nor glTF JSON"),
}
}
#[cfg(feature = "fs")]
fn open_file(path: &Path) -> Result<(Map<String, Value>, Option<Blob>)> {
let all = read_file(path, None)?;
if all.starts_with(b"glTF") {
return glb_in_memory(&all, |part| all.slice_ref(part));
}
Ok((gltf_json(&all)?, None))
}
#[cfg(all(test, feature = "fs"))]
mod tests {
use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::assets::Folder;
use crate::document::{Document, Keep};
fn split(glb: &[u8]) -> (Value, &[u8]) {
let n = u32::from_le_bytes(glb[12..16].try_into().unwrap()) as usize;
let text = &glb[20..20 + n];
let json = serde_json::from_slice(text.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(text)).unwrap();
let bin = glb.get(20 + n + 8..).unwrap_or(&[]);
(json, bin)
}
fn views(json: &Value, bin: &[u8]) -> Vec<Vec<u8>> {
let empty = Vec::new();
let list = json["bufferViews"].as_array().unwrap_or(&empty);
list.iter()
.map(|v| {
if v["buffer"].as_u64() != Some(0) {
return Vec::new();
}
let off = usize::try_from(v["byteOffset"].as_u64().unwrap_or(0)).unwrap();
let len = usize::try_from(v["byteLength"].as_u64().unwrap()).unwrap();
bin[off..off + len].to_vec()
})
.collect()
}
fn normalized(mut json: Value) -> Value {
if let Some(list) = json.get_mut("buffers").and_then(Value::as_array_mut) {
while list.len() > 1 && list.last().and_then(|b| b["byteLength"].as_u64()) == Some(0) {
list.pop();
}
}
for v in json["bufferViews"].as_array_mut().into_iter().flatten() {
let o = v.as_object_mut().unwrap();
if o.get("buffer").and_then(Value::as_u64) == Some(0) {
o.remove("byteOffset");
}
}
if let Some(b) = json.get_mut("buffers").and_then(|b| b.get_mut(0)) {
b.as_object_mut().unwrap().remove("byteLength");
}
json
}
fn glbs() -> Vec<PathBuf> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/gltf");
let mut out = Vec::new();
for case in std::fs::read_dir(root).unwrap().flatten() {
for f in std::fs::read_dir(case.path()).unwrap().flatten() {
if f.path().extension().is_some_and(|e| e == "glb") {
out.push(f.path());
}
}
}
out.sort();
out
}
#[cfg(feature = "fs")]
#[test]
fn a_buffer_in_a_parent_folder_is_read() {
let case = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/gltf/gltf_external_bin");
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("model")).unwrap();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::copy(case.join("cube.bin"), dir.path().join("data/cube.bin")).unwrap();
let text = std::fs::read_to_string(case.join("cube.gltf")).unwrap();
let gltf = dir.path().join("model/cube.gltf");
std::fs::write(&gltf, text.replace("\"cube.bin\"", "\"../data/cube.bin\"")).unwrap();
let doc = crate::formats::load(&gltf, "gltf", &Folder::new(dir.path()), Keep::ALL).unwrap();
assert_eq!(
doc.flatten(crate::document::Pose::Rest).unwrap().unwrap().triangles(),
12
);
std::fs::write(&gltf, text.replace("\"cube.bin\"", "\"/data/cube.bin\"")).unwrap();
let err = crate::formats::load(&gltf, "gltf", &Folder::new(dir.path()), Keep::ALL)
.err()
.unwrap();
assert!(err.to_string().contains("refusing"), "{err}");
}
#[cfg(feature = "fs")]
#[test]
fn image_files_are_written_as_they_are() {
let n = 260;
let dir = tempfile::tempdir().unwrap();
let png = |i: usize| {
let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
b.extend((0..i % 300).map(|k| u8::try_from((k * 7 + i) % 251).unwrap()));
b
};
let jpeg = b"\xff\xd8\xff\xe0 not really a jpeg".to_vec();
let mut images = Vec::new();
for i in 0..n {
let name = if i % 5 == 0 {
format!("t{i}.jpg")
} else {
format!("t{i}.png")
};
std::fs::write(dir.path().join(&name), png(i)).unwrap();
images.push(serde_json::json!({ "uri": name }));
}
std::fs::write(dir.path().join("j.png"), &jpeg).unwrap();
images.push(serde_json::json!({ "uri": "j.png", "mimeType": "image/png" }));
images.push(serde_json::json!({ "uri": "missing.png" }));
let gltf = serde_json::json!({ "asset": { "version": "2.0" }, "images": images });
let path = dir.path().join("m.gltf");
std::fs::write(&path, gltf.to_string()).unwrap();
let doc = crate::formats::load(&path, "gltf", &Folder::new(dir.path()), Keep::ALL).unwrap();
let glb = doc.to_glb().unwrap();
let (json, bin) = split(&glb);
let views = views(&json, bin);
let images = json["images"].as_array().unwrap();
assert_eq!(images.len(), n + 2);
for (i, img) in images.iter().enumerate() {
if i == n + 1 {
assert_eq!(img["uri"], "missing.png", "what isn't found keeps its URI");
continue;
}
let view = usize::try_from(img["bufferView"].as_u64().unwrap()).unwrap();
let (bytes, mime) = if i == n {
(jpeg.clone(), "image/jpeg")
} else {
(png(i), "image/png")
};
assert_eq!(views[view], bytes, "image {i}");
assert_eq!(img["mimeType"], mime, "image {i}");
}
}
#[test]
fn a_glb_reads_the_same_from_its_file_and_from_memory() {
let mut n = 0;
for path in glbs() {
let dir = path.parent().unwrap();
let Ok(doc) = crate::formats::load(&path, "glb", &Folder::new(dir), Keep::ALL) else {
continue;
};
let bytes = std::fs::read(&path).unwrap();
let mut assets = crate::assets::Memory::new();
for f in std::fs::read_dir(dir).unwrap().flatten() {
assets.insert(&f.file_name().to_string_lossy(), std::fs::read(f.path()).unwrap());
}
let name = path.file_name().unwrap().to_string_lossy().into_owned();
let mem = crate::formats::load_bytes(&bytes, &name, "glb", &assets, Keep::ALL).unwrap();
let shown = |d: &Document| {
format!(
"{:?}",
d.flatten(crate::document::Pose::Rest).map_err(|e| e.to_string())
)
};
assert_eq!(shown(&doc), shown(&mem), "{}", path.display());
assert!(doc.to_glb().unwrap() == mem.to_glb().unwrap(), "{}", path.display());
n += 1;
}
assert!(n > 20, "only {n} GLBs read");
}
#[test]
fn glb_round_trips() {
let mut n = 0;
for path in glbs() {
let dir = path.parent().unwrap();
let Ok(doc) = crate::formats::load(&path, "glb", &Folder::new(dir), Keep::ALL) else {
continue;
};
let original = std::fs::read(&path).unwrap();
let written = doc.to_glb().unwrap();
let name = path.display();
let (a, abin) = split(&original);
let in_files = a["buffers"]
.as_array()
.is_some_and(|l| l.iter().any(|b| b.get("uri").is_some()));
let mut fixed = doc.json().clone();
let repaired = crate::flatten::repaired(&doc, &mut fixed, &mut None).is_some() || fixed != *doc.json();
if original[4..8] != 1u32.to_le_bytes() && !in_files && !repaired {
let (b, bbin) = split(&written);
assert_eq!(normalized(a.clone()), normalized(b.clone()), "{name}: the JSON changed");
assert!(
views(&a, abin) == views(&b, bbin),
"{name}: a buffer view's bytes changed"
);
}
let again = crate::formats::load_bytes(&written, "x.glb", "glb", &crate::assets::Memory::new(), Keep::ALL)
.and_then(|d: Document| d.to_glb())
.unwrap();
assert!(again == written, "{name}: a second round trip changed it");
n += 1;
}
assert!(n > 20, "only {n} GLBs round-tripped");
}
#[test]
fn a_json_chunk_padded_with_zeros_reads() {
let mut json = br#"{"asset":{"version":"2.0"},"scene":0,"scenes":[{}]}"#.to_vec();
json.resize(json.len().next_multiple_of(4) + 4, 0);
let len = u32::try_from(json.len()).unwrap();
let glb = [
&b"glTF"[..],
&2u32.to_le_bytes(),
&(20 + len).to_le_bytes(),
&len.to_le_bytes(),
b"JSON",
&json,
]
.concat();
let assets = crate::assets::Memory::new();
let doc = crate::formats::load_bytes(&glb, "x.glb", "glb", &assets, Keep::ALL).unwrap();
assert_eq!(doc.json()["scene"], 0);
}
}