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 _, ErrorKind, Result};
#[cfg(any(
feature = "flt",
feature = "skp",
feature = "tga",
feature = "bmp",
feature = "gif",
feature = "tiff",
feature = "psd",
feature = "dds",
all(feature = "obj", any(feature = "webp", feature = "amf"))
))]
pub(crate) const MAX_PIXELS: usize = 1 << 28;
#[cfg(any(
feature = "flt",
feature = "tga",
feature = "bmp",
feature = "gif",
feature = "tiff",
feature = "psd",
feature = "dds"
))]
pub(crate) const FREE: usize = 1 << 22;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Location {
File(PathBuf),
Archive(String),
Embedded,
Missing,
}
static EMBEDDED: Location = Location::Embedded;
static MISSING: Location = Location::Missing;
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "lwo",
feature = "ac3d",
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,
pub found: Option<std::sync::OnceLock<bool>>,
}
impl Reference {
pub fn location(&self) -> &Location {
match (&self.location, &self.found) {
(Location::File(p), Some(found)) if !*found.get_or_init(|| p.is_file()) => &MISSING,
(l, _) => l,
}
}
}
#[derive(Debug)]
pub(crate) enum Source {
Image(Image),
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "lwo",
feature = "ac3d",
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)
}
}
#[derive(Debug, Default, Clone, PartialEq)]
pub(crate) struct Missed {
pub dropped: usize,
pub files: Vec<String>,
pub names: Vec<String>,
}
impl Missed {
pub fn is_empty(&self) -> bool {
self.dropped == 0 && self.files.is_empty()
}
pub fn drop(&mut self, name: &str) {
let name = name.trim();
if name.is_empty() {
self.dropped += 1;
} else if !self.names.iter().any(|n| n == name) {
self.names.push(name.to_owned());
self.dropped += 1;
}
}
pub fn add(&mut self, other: Missed) {
let shared = other.names.iter().filter(|n| self.names.contains(n)).count();
self.dropped += other.dropped.saturating_sub(shared);
for n in other.names {
if !self.names.contains(&n) {
self.names.push(n);
}
}
for f in other.files {
if !self.files.contains(&f) {
self.files.push(f);
}
}
}
pub fn write(&self, source: &mut serde_json::Map<String, serde_json::Value>) {
use serde_json::{Value, json};
if self.dropped > 0 && !source.contains_key("droppedTextures") {
source.insert("droppedTextures".into(), json!(self.dropped));
}
if !self.files.is_empty() {
let list = source.entry("missingFiles").or_insert_with(|| json!([]));
if let Some(list) = list.as_array_mut() {
for f in &self.files {
if !list.iter().any(|v| v.as_str() == Some(f)) {
list.push(Value::from(f.as_str()));
}
}
}
}
}
}
#[derive(Debug, Default)]
pub(crate) struct List {
items: Vec<Source>,
pub missed: Missed,
}
impl std::ops::Deref for List {
type Target = Vec<Source>;
fn deref(&self) -> &Vec<Source> {
&self.items
}
}
impl std::ops::DerefMut for List {
fn deref_mut(&mut self) -> &mut Vec<Source> {
&mut self.items
}
}
impl From<Vec<Source>> for List {
fn from(items: Vec<Source>) -> Self {
List {
items,
missed: Missed::default(),
}
}
}
impl List {
pub fn parts(self) -> (Vec<Source>, Missed) {
(self.items, self.missed)
}
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "lwo",
feature = "ac3d",
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: List,
lazy: bool,
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "lwo",
feature = "ac3d",
feature = "fbx",
feature = "usd"
)),
allow(dead_code, reason = "only readers of texture files use it")
)]
dir: PathBuf,
files: std::collections::HashMap<PathBuf, Option<usize>>,
found: std::collections::HashMap<(Vec<String>, Vec<PathBuf>), Option<usize>>,
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "lwo",
feature = "ac3d",
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: List::default(),
lazy,
dir: dir.to_path_buf(),
files: std::collections::HashMap::new(),
found: 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 = "lwo",
feature = "ac3d",
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);
if i.is_none() {
self.list.missed.drop(reference);
}
self.files.insert(path, i);
i
}
#[cfg_attr(
not(any(feature = "ply", feature = "3ds", feature = "lwo", feature = "fbx", feature = "usd")),
allow(dead_code, reason = "only readers of texture files use it")
)]
pub fn find(&mut self, assets: &dyn Assets, names: &[impl AsRef<str>], dirs: &[&Path]) -> Option<usize> {
let key = (
names.iter().map(|n| n.as_ref().to_owned()).collect(),
dirs.iter().map(|d| d.to_path_buf()).collect(),
);
if let Some(&i) = self.found.get(&key) {
return i;
}
let path = names.iter().find_map(|n| {
let n = n.as_ref();
Some((dirs.iter().find_map(|d| assets.find(n, d))?, n))
});
if path.is_none()
&& let Some(first) = names.first()
{
self.miss(first.as_ref());
}
let i = path.and_then(|(p, n)| self.file(assets, p, n));
self.found.insert(key, i);
i
}
pub fn miss(&mut self, reference: &str) {
let name = reference.trim();
if !name.is_empty() && !self.list.missed.files.iter().any(|f| f == name) {
self.list.missed.files.push(name.to_owned());
self.list.missed.drop(name);
}
}
#[cfg_attr(
not(any(feature = "fbx", feature = "usd", feature = "3mf", feature = "dae", feature = "flt")),
allow(dead_code, reason = "only readers that read their textures themselves use it")
)]
pub fn drop(&mut self, reference: &str) {
self.list.missed.drop(reference);
}
#[cfg_attr(
not(any(feature = "md3", feature = "md5", feature = "iqm")),
allow(
dead_code,
reason = "only readers of formats that name textures without extensions use it"
)
)]
pub fn find_bare(&mut self, assets: &dyn Assets, name: &str, endings: &[&str], dir: &Path) -> Option<usize> {
if name.is_empty() {
return None;
}
let mut tries = vec![name.to_owned()];
if Path::new(name).extension().is_none_or(|e| e.len() > 4) {
tries.extend(endings.iter().map(|e| format!("{name}{e}")));
}
self.find(assets, &tries, &[dir])
}
#[cfg_attr(
not(feature = "obj"),
allow(dead_code, reason = "only the OBJ reader reads texture files itself")
)]
#[allow(clippy::option_option, reason = "not asked for and not an image differ")]
pub fn known(&self, path: &Path) -> Option<Option<usize>> {
self.files.get(path).copied()
}
#[cfg_attr(
not(feature = "obj"),
allow(dead_code, reason = "only the OBJ reader reads texture files itself")
)]
pub fn read(&mut self, path: PathBuf, img: Image) -> usize {
if let Some(&Some(i)) = self.files.get(&path) {
return i;
}
let i = self.push(Source::Image(img));
self.files.insert(path, Some(i));
i
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "lwo",
feature = "ac3d",
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,
found: None,
};
Some(self.push(Source::Ref(r, uri)))
}
#[cfg_attr(
not(any(feature = "3mf", feature = "dae")),
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> {
let named = !matches!(location, Location::Embedded);
let i = self.take(bytes, reference, location, convert, false);
if i.is_none() {
let missed = &mut self.list.missed;
missed.dropped += 1;
let name = reference.trim();
if named && !name.is_empty() && !missed.names.iter().any(|n| n == name) {
missed.names.push(name.to_owned());
}
}
i
}
#[cfg_attr(
not(any(feature = "fbx", feature = "usd", feature = "flt")),
allow(
dead_code,
reason = "only readers with a file to look for in an embedded texture's place use it"
)
)]
pub fn try_bytes(
&mut self,
bytes: Cow<'_, [u8]>,
reference: &str,
location: Location,
convert: impl FnOnce(&[u8]) -> Option<Image>,
) -> Option<usize> {
self.take(bytes, reference, location, convert, true)
}
fn take(
&mut self,
bytes: Cow<'_, [u8]>,
reference: &str,
location: Location,
convert: impl FnOnce(&[u8]) -> Option<Image>,
check: bool,
) -> Option<usize> {
if self.lazy && check && Image::mime_of(&bytes).is_none() {
convert(&bytes)?;
} else 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,
found: None,
};
Some(self.push(Source::Ref(r, uri)))
}
}
#[cfg(any(feature = "obj", feature = "usd"))]
pub(crate) fn gray(b: &[u8]) -> bool {
if b.starts_with(b"\x89PNG\r\n\x1a\n") {
return b.get(12..16) == Some(b"IHDR".as_slice()) && matches!(b.get(25), Some(0 | 4));
}
if !b.starts_with(&[0xFF, 0xD8]) {
return false;
}
let mut i = 2usize;
while i + 4 <= b.len() {
if b[i] != 0xFF {
return false;
}
let marker = b[i + 1];
if marker == 0xFF {
i += 1;
continue;
}
if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
return b.get(i + 9) == Some(&1);
}
if matches!(marker, 0xD9 | 0xDA) {
return false;
}
i = i.saturating_add(2 + usize::from(u16::from_be_bytes([b[i + 2], b[i + 3]])));
}
false
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "ply",
feature = "3ds",
feature = "lwo",
feature = "ac3d",
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 = "lwo",
feature = "ac3d",
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: crate::Bytes, 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,
}
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, Reference::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_shared(crate::num::usize_of(v))?
} else {
let uri = self.json.get("uri").and_then(Value::as_str);
data_uri(uri.with_context(ErrorKind::Corrupt, || format!("image {i} has no bytes"))?)?
.1
.into()
};
return image_of(bytes, self.mime())
.with_context(ErrorKind::Unsupported, || 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)
.ok_or_else(|| crate::Error::missing(format!("image {i} can't be read")).at(p))?,
_ => bail!(MissingAsset, "image {i} ({:?}) wasn't found", r.name),
};
let img = if r.raw {
image_of(crate::Bytes::from(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(ErrorKind::Unsupported, || {
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.base.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.base_mut()["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"
);
}
}