use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::assets::Assets;
use crate::document::Document;
use crate::gltf::{data_uri, mime_from_name, sniff_mime};
use crate::mesh::Image;
use crate::{Context as _, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Location {
File(PathBuf),
Archive(String),
Embedded,
Missing,
}
static EMBEDDED: Location = Location::Embedded;
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "fbx",
feature = "usd",
feature = "3mf",
feature = "gltf"
)),
allow(dead_code, reason = "only readers with textures make references")
)]
#[derive(Debug, Clone)]
pub(crate) struct Reference {
pub name: String,
pub location: Location,
pub bytes: Option<Vec<u8>>,
pub raw: bool,
}
#[derive(Debug, Clone)]
pub(crate) enum Source {
Image(Image),
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "fbx",
feature = "usd",
feature = "3mf"
)),
allow(dead_code, reason = "only readers with textures make references")
)]
Ref(Reference, String),
}
impl From<Image> for Source {
fn from(i: Image) -> Self {
Source::Image(i)
}
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "fbx",
feature = "usd",
feature = "3mf"
)),
allow(dead_code, reason = "only readers with textures collect images")
)]
#[derive(Debug, Default)]
pub(crate) struct Images {
pub list: Vec<Source>,
lazy: bool,
#[cfg_attr(
not(any(feature = "obj", feature = "ply", feature = "3ds", feature = "fbx", feature = "usd")),
allow(dead_code, reason = "only readers of texture files use it")
)]
dir: PathBuf,
files: std::collections::HashMap<PathBuf, Option<usize>>,
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "fbx",
feature = "usd",
feature = "3mf"
)),
allow(dead_code, reason = "only readers with textures collect images")
)]
impl Images {
pub fn new(lazy: bool, dir: &Path) -> Self {
Self {
list: Vec::new(),
lazy,
dir: dir.to_path_buf(),
files: std::collections::HashMap::new(),
}
}
fn push(&mut self, s: Source) -> usize {
self.list.push(s);
self.list.len() - 1
}
#[cfg_attr(
not(any(feature = "obj", feature = "ply", feature = "3ds", feature = "fbx", feature = "usd")),
allow(dead_code, reason = "only readers of texture files use it")
)]
pub fn file(&mut self, assets: &dyn Assets, path: PathBuf, reference: &str) -> Option<usize> {
if let Some(&i) = self.files.get(&path) {
return i;
}
let i = self.read_file(assets, path.clone(), reference);
self.files.insert(path, i);
i
}
#[cfg_attr(
not(any(feature = "obj", feature = "ply", feature = "3ds", feature = "fbx", feature = "usd")),
allow(dead_code, reason = "only readers of texture files use it")
)]
fn read_file(&mut self, assets: &dyn Assets, path: PathBuf, reference: &str) -> Option<usize> {
if !self.lazy {
let img = assets.load_image(&path)?;
return Some(self.push(Source::Image(img)));
}
let uri = file_uri(&path, &self.dir);
let r = Reference {
name: reference.to_owned(),
location: Location::File(path),
bytes: None,
raw: false,
};
Some(self.push(Source::Ref(r, uri)))
}
#[cfg_attr(
not(any(feature = "fbx", feature = "usd", feature = "3mf")),
allow(dead_code, reason = "only readers of archives and embedded textures use it")
)]
pub fn bytes(
&mut self,
bytes: Cow<'_, [u8]>,
reference: &str,
location: Location,
convert: impl FnOnce(&[u8]) -> Option<Image>,
) -> Option<usize> {
if !self.lazy {
let img = convert(&bytes)?;
return Some(self.push(Source::Image(img)));
}
let uri = match &location {
Location::Archive(entry) => encode(entry),
_ => encode(&reference.replace('\\', "/")),
};
let r = Reference {
name: reference.to_owned(),
location,
bytes: Some(bytes.into_owned()),
raw: false,
};
Some(self.push(Source::Ref(r, uri)))
}
}
#[cfg_attr(
not(any(feature = "obj", feature = "ply", feature = "3ds", feature = "fbx", feature = "usd")),
allow(dead_code, reason = "only readers of texture files use it")
)]
fn file_uri(path: &Path, dir: &Path) -> String {
let rel = path.strip_prefix(dir).unwrap_or(path);
let s = rel.to_string_lossy().replace('\\', "/");
if rel.is_absolute() || s.starts_with('/') || s.as_bytes().get(1) == Some(&b':') {
format!("file:///{}", encode(s.trim_start_matches('/')).replace("%3A", ":"))
} else {
encode(&s)
}
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "fbx",
feature = "usd",
feature = "3mf"
)),
allow(dead_code, reason = "only readers with textures make references")
)]
fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) {
out.push(char::from(b));
} else {
let _ = write!(out, "%{b:02X}");
}
}
out
}
fn image_of(bytes: Vec<u8>, mime: Option<&str>) -> Option<Image> {
let mime = sniff_mime(&bytes).or_else(|| mime_from_name(&format!("x.{}", mime?.strip_prefix("image/")?)))?;
Some(Image { bytes, mime })
}
#[derive(Debug, Clone, Copy)]
pub struct ImageHandle<'d> {
index: usize,
json: &'d Value,
reference: Option<&'d Reference>,
doc: &'d Document<'d>,
}
impl<'d> ImageHandle<'d> {
#[must_use]
pub fn index(&self) -> usize {
self.index
}
#[must_use]
pub fn name(&self) -> Option<&'d str> {
self.json.get("name").and_then(Value::as_str)
}
#[must_use]
pub fn is_pending(&self) -> bool {
self.reference.is_some()
}
#[must_use]
pub fn reference(&self) -> Option<&'d str> {
self.reference.map(|r| r.name.as_str())
}
#[must_use]
pub fn location(&self) -> &'d Location {
self.reference.map_or(&EMBEDDED, |r| &r.location)
}
#[must_use]
pub fn path(&self) -> Option<&'d Path> {
match self.location() {
Location::File(p) => Some(p),
_ => None,
}
}
#[must_use]
pub fn mime(&self) -> Option<&'d str> {
if let Some(m) = self.json.get("mimeType").and_then(Value::as_str) {
return Some(m);
}
let r = self.reference?;
r.bytes
.as_deref()
.and_then(sniff_mime)
.or_else(|| mime_from_name(&r.name))
.or_else(|| self.path().and_then(|p| mime_from_name(&p.to_string_lossy())))
}
pub fn load(&self, assets: &dyn Assets) -> Result<Image> {
let i = self.index;
let Some(r) = self.reference else {
let bytes = if let Some(v) = self.json.get("bufferView").and_then(Value::as_u64) {
self.doc.view_bytes(crate::num::usize_of(v))?.into_owned()
} else {
let uri = self.json.get("uri").and_then(Value::as_str);
data_uri(uri.with_context(|| format!("image {i} has no bytes"))?)?.1
};
return image_of(bytes, self.mime()).with_context(|| format!("image {i}: unknown image format"));
};
let bytes: Cow<'_, [u8]> = match (&r.location, &r.bytes) {
(_, Some(b)) => Cow::Borrowed(b),
(Location::File(p), None) => assets
.read(p)
.with_context(|| format!("image {i}: can't read {}", p.display()))?,
_ => bail!("image {i} ({:?}) wasn't found", r.name),
};
let img = if r.raw {
image_of(bytes.into_owned(), self.mime())
} else {
let name = self.path().map_or_else(|| PathBuf::from(&r.name), Path::to_path_buf);
assets.image(&bytes, &name)
};
img.with_context(|| format!("image {i} ({:?}) isn't an image that can be embedded", r.name))
}
}
impl Document<'_> {
pub fn images(&self) -> impl Iterator<Item = ImageHandle<'_>> {
let list = self.json.get("images").and_then(Value::as_array);
list.into_iter()
.flatten()
.enumerate()
.map(move |(index, json)| ImageHandle {
index,
json,
reference: self.refs.get(&index),
doc: self,
})
}
pub fn embed_images(&mut self, assets: &dyn Assets) -> usize {
let mut loaded = Vec::new();
let mut failed = 0;
for h in self.images().filter(ImageHandle::is_pending) {
match h.load(assets) {
Ok(img) => loaded.push((h.index, img)),
Err(_) => failed += 1,
}
}
for (i, Image { bytes, mime }) in loaded {
let len = bytes.len();
let buffer = self.push_buffer(bytes);
let view = self.push_view(serde_json::json!({ "buffer": buffer, "byteLength": len }));
if let Some(img) = self.json["images"][i].as_object_mut() {
img.remove("uri");
img.insert("bufferView".into(), view.into());
img.insert("mimeType".into(), mime.into());
}
self.refs.remove(&i);
}
failed
}
}
pub(crate) type Refs = BTreeMap<usize, Reference>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uris() {
assert_eq!(file_uri(Path::new("m/tex/a b.png"), Path::new("m")), "tex/a%20b.png");
assert_eq!(file_uri(Path::new("other/a.png"), Path::new("m")), "other/a.png");
assert_eq!(file_uri(Path::new("/abs/a.png"), Path::new("m")), "file:///abs/a.png");
assert_eq!(
file_uri(Path::new("C:\\x\\a.png"), Path::new("m")),
"file:///C:/x/a.png"
);
}
}