use std::collections::BTreeSet;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, PoisonError};
use serde_json::{Map, Value};
use crate::document::Document;
use crate::mesh::{MAX_POINTS, MAX_TRIANGLES, TRIANGLE_CEILING};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(clippy::struct_excessive_bools, reason = "independent switches")]
pub struct Keep {
pub animations: bool,
pub skins: bool,
pub morph_targets: bool,
pub materials: bool,
pub textures: bool,
pub image_bytes: bool,
pub cameras: bool,
pub lights: bool,
pub extras: bool,
pub max_triangles: usize,
pub lines_and_points: bool,
pub max_points: usize,
pub threads: usize,
crease: u16,
}
impl Default for Keep {
fn default() -> Self {
Self::ALL
}
}
impl Keep {
pub const ALL: Keep = Keep {
animations: true,
skins: true,
morph_targets: true,
materials: true,
textures: true,
image_bytes: true,
cameras: true,
lights: true,
extras: true,
max_triangles: MAX_TRIANGLES,
lines_and_points: true,
max_points: MAX_POINTS,
threads: 1,
crease: 3000,
};
pub const MESHES: Keep = Keep {
animations: false,
cameras: false,
lights: false,
..Keep::ALL
};
pub const LIGHT: Keep = Keep {
image_bytes: false,
..Keep::MESHES
};
#[must_use]
pub const fn with_animations(mut self, animations: bool) -> Self {
self.animations = animations;
self
}
#[must_use]
pub const fn with_skins(mut self, skins: bool) -> Self {
self.skins = skins;
self
}
#[must_use]
pub const fn with_morph_targets(mut self, morph_targets: bool) -> Self {
self.morph_targets = morph_targets;
self
}
#[must_use]
pub const fn with_materials(mut self, materials: bool) -> Self {
self.materials = materials;
self
}
#[must_use]
pub const fn with_textures(mut self, textures: bool) -> Self {
self.textures = textures;
self
}
#[must_use]
pub const fn with_image_bytes(mut self, image_bytes: bool) -> Self {
self.image_bytes = image_bytes;
self
}
#[must_use]
pub const fn with_cameras(mut self, cameras: bool) -> Self {
self.cameras = cameras;
self
}
#[must_use]
pub const fn with_lights(mut self, lights: bool) -> Self {
self.lights = lights;
self
}
#[must_use]
pub const fn with_extras(mut self, extras: bool) -> Self {
self.extras = extras;
self
}
#[must_use]
pub const fn with_max_triangles(mut self, max_triangles: usize) -> Self {
self.max_triangles = max_triangles;
self
}
#[must_use]
pub const fn with_lines_and_points(mut self, lines_and_points: bool) -> Self {
self.lines_and_points = lines_and_points;
self
}
#[must_use]
pub const fn with_max_points(mut self, max_points: usize) -> Self {
self.max_points = max_points;
self
}
#[must_use]
pub const fn with_threads(mut self, threads: usize) -> Self {
self.threads = threads;
self
}
#[must_use]
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "between 0 and 18000 once clamped"
)]
pub const fn with_crease_angle(mut self, degrees: f32) -> Self {
self.crease = if degrees.is_nan() {
3000
} else if degrees <= 0.0 {
0
} else if degrees >= 180.0 {
18000
} else {
(degrees * 100.0 + 0.5) as u16
};
self
}
#[must_use]
pub const fn crease_angle(&self) -> f32 {
self.crease as f32 / 100.0
}
pub(crate) fn triangles(self) -> usize {
self.max_triangles.min(TRIANGLE_CEILING)
}
pub(crate) fn points(self) -> usize {
self.max_points.min(TRIANGLE_CEILING)
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "spz",
feature = "las",
feature = "pcd",
feature = "xyz",
feature = "e57",
feature = "ac3d"
)),
allow(dead_code, reason = "only the OBJ and SPZ readers take threads")
)]
pub(crate) fn thread_count(self) -> usize {
thread_count(self.threads)
}
}
pub(crate) fn thread_count(threads: usize) -> usize {
if cfg!(all(target_family = "wasm", not(target_feature = "atomics"))) {
1
} else if threads == 0 {
std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
} else {
threads
}
}
#[cfg(test)]
thread_local! {
pub(crate) static NO_THREADS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg_attr(
not(any(
feature = "obj",
feature = "spz",
feature = "las",
feature = "pcd",
feature = "xyz",
feature = "e57",
feature = "ac3d",
feature = "fbx"
)),
allow(dead_code, reason = "only some readers, and the FBX writer, take threads")
)]
pub(crate) fn spawn<'s>(s: &'s std::thread::Scope<'s, '_>, f: impl FnOnce() + Send + 's) -> bool {
#[cfg(test)]
if NO_THREADS.get() {
return false;
}
std::thread::Builder::new().spawn_scoped(s, f).is_ok()
}
#[cfg_attr(
not(any(feature = "ac3d", feature = "fbx")),
allow(dead_code, reason = "only the AC3D reader and the FBX writer share work this way")
)]
pub(crate) fn par_map_with<T: Sync, S, R: Send>(
items: &[T],
threads: usize,
init: impl Fn() -> S + Sync,
f: impl Fn(&mut S, &T) -> R + Sync,
) -> Vec<R> {
if threads <= 1 || items.len() <= 1 {
let mut state = init();
return items.iter().map(|t| f(&mut state, t)).collect();
}
let next = AtomicUsize::new(0);
let done: Mutex<Vec<Option<R>>> = Mutex::new((0..items.len()).map(|_| None).collect());
let run = || {
let mut state = init();
loop {
let k = next.fetch_add(1, Ordering::Relaxed);
let Some(item) = items.get(k) else { break };
let r = f(&mut state, item);
done.lock().unwrap_or_else(PoisonError::into_inner)[k] = Some(r);
}
};
std::thread::scope(|s| {
for _ in 1..threads.min(items.len()) {
if !spawn(s, run) {
break;
}
}
run();
});
done.into_inner()
.unwrap_or_else(PoisonError::into_inner)
.into_iter()
.flatten()
.collect()
}
fn each(obj: &mut Map<String, Value>, key: &str, mut f: impl FnMut(&mut Map<String, Value>)) {
let items = obj.get_mut(key).and_then(Value::as_array_mut);
for item in items.into_iter().flatten().filter_map(Value::as_object_mut) {
f(item);
}
}
fn primitives(json: &mut Map<String, Value>, mut f: impl FnMut(&mut Map<String, Value>)) {
each(json, "meshes", |m| each(m, "primitives", &mut f));
}
fn remove_extension(obj: &mut Map<String, Value>, name: &str) {
if let Some(exts) = obj.get_mut("extensions").and_then(Value::as_object_mut) {
exts.remove(name);
if exts.is_empty() {
obj.remove("extensions");
}
}
}
fn remove_extension_everywhere(v: &mut Value, name: &str) {
match v {
Value::Object(obj) => {
remove_extension(obj, name);
obj.values_mut().for_each(|v| remove_extension_everywhere(v, name));
}
Value::Array(a) => a.iter_mut().for_each(|v| remove_extension_everywhere(v, name)),
_ => {}
}
}
fn remove_key_everywhere(v: &mut Value, key: &str) {
match v {
Value::Object(obj) => {
obj.remove(key);
obj.values_mut().for_each(|v| remove_key_everywhere(v, key));
}
Value::Array(a) => a.iter_mut().for_each(|v| remove_key_everywhere(v, key)),
_ => {}
}
}
fn remove_textures(obj: &mut Map<String, Value>) {
obj.retain(|k, v| !(k.ends_with("Texture") && v.is_object()));
for v in obj.values_mut() {
if let Value::Object(o) = v {
remove_textures(o);
}
}
}
fn extensions_present(v: &Value, out: &mut BTreeSet<String>) {
match v {
Value::Object(obj) => {
if let Some(exts) = obj.get("extensions").and_then(Value::as_object) {
out.extend(exts.keys().cloned());
}
obj.values().for_each(|v| extensions_present(v, out));
}
Value::Array(a) => a.iter().for_each(|v| extensions_present(v, out)),
_ => {}
}
}
impl Document {
pub fn prune(&mut self, keep: Keep) {
self.lines_and_points = keep.lines_and_points;
self.max_points = keep.points();
if (Keep {
image_bytes: true,
max_triangles: Keep::ALL.max_triangles,
lines_and_points: true,
max_points: Keep::ALL.max_points,
threads: Keep::ALL.threads,
..keep
}) == Keep::ALL
{
return;
}
let missed = if keep.textures && keep.materials {
None
} else {
self.missed.take()
};
let mut before = BTreeSet::new();
let mut root = Value::Object(std::mem::take(self.json_mut()));
if let Some(missed) = missed
&& let Some(source) = root.pointer_mut("/asset/extras/source").and_then(Value::as_object_mut)
{
let (missed, counted) = *missed;
if counted {
source.remove("droppedTextures");
}
if let Some(Value::Array(files)) = source.get_mut("missingFiles") {
files.retain(|f| !f.as_str().is_some_and(|f| missed.files.iter().any(|m| m == f)));
if files.is_empty() {
source.remove("missingFiles");
}
}
}
extensions_present(&root, &mut before);
let Value::Object(json) = &mut root else { unreachable!() };
let mut dead: Vec<&str> = Vec::new();
if !keep.animations {
json.remove("animations");
}
if !keep.cameras {
json.remove("cameras");
each(json, "nodes", |n| {
n.remove("camera");
});
dead.push("/cameras/");
}
if !keep.lights {
remove_extension_everywhere(&mut root, "KHR_lights_punctual");
dead.push("/extensions/KHR_lights_punctual/");
}
let Value::Object(json) = &mut root else { unreachable!() };
if !keep.skins {
json.remove("skins");
each(json, "nodes", |n| {
n.remove("skin");
});
primitives(json, |p| {
let skinning = |k: &String| k.starts_with("JOINTS_") || k.starts_with("WEIGHTS_");
if let Some(a) = p.get_mut("attributes").and_then(Value::as_object_mut) {
a.retain(|k, _| !skinning(k));
}
let draco = p
.get_mut("extensions")
.and_then(|e| e.get_mut("KHR_draco_mesh_compression"))
.and_then(|d| d.get_mut("attributes"))
.and_then(Value::as_object_mut);
if let Some(a) = draco {
a.retain(|k, _| !skinning(k));
}
});
}
if !keep.morph_targets {
primitives(json, |p| {
p.remove("targets");
});
each(json, "meshes", |m| {
m.remove("weights");
if let Some(x) = m.get_mut("extras").and_then(Value::as_object_mut) {
x.remove("targetNames");
}
});
each(json, "nodes", |n| {
n.remove("weights");
});
each(json, "animations", |a| {
if let Some(ch) = a.get_mut("channels").and_then(Value::as_array_mut) {
ch.retain(|c| c.pointer("/target/path").and_then(Value::as_str) != Some("weights"));
}
});
dead.extend(["/meshes/*/weights", "/nodes/*/weights"]);
}
let textures = keep.textures && keep.materials;
if !keep.materials {
json.remove("materials");
primitives(json, |p| {
p.remove("material");
});
dead.push("/materials/");
}
if !keep.materials {
remove_extension_everywhere(&mut root, "KHR_materials_variants");
}
let Value::Object(json) = &mut root else { unreachable!() };
if !textures {
for key in ["textures", "images", "samplers"] {
json.remove(key);
}
each(json, "materials", remove_textures);
dead.push("/textures/");
self.refs.clear();
}
if !keep.extras {
let info: Option<Map<String, Value>> = root
.pointer("/asset/extras/source")
.and_then(Value::as_object)
.map(|s| {
s.iter()
.filter(|(k, _)| crate::source::KEYS.contains(&k.as_str()))
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
})
.filter(|m: &Map<String, Value>| !m.is_empty());
remove_key_everywhere(&mut root, "extras");
if let (Some(info), Some(asset)) = (info, root.get_mut("asset").and_then(Value::as_object_mut)) {
asset.insert("extras".into(), serde_json::json!({ "source": info }));
}
}
let Value::Object(json) = &mut root else { unreachable!() };
if !dead.is_empty() {
each(json, "animations", |a| {
if let Some(ch) = a.get_mut("channels").and_then(Value::as_array_mut) {
ch.retain(|c| {
let pointer = c
.pointer("/target/extensions/KHR_animation_pointer/pointer")
.and_then(Value::as_str);
!pointer.is_some_and(|p| dead.iter().any(|d| matches_pointer(p, d)))
});
}
});
}
if let Some(anims) = json.get_mut("animations").and_then(Value::as_array_mut) {
anims.retain(|a| {
a.get("channels")
.and_then(Value::as_array)
.is_some_and(|c| !c.is_empty())
});
if anims.is_empty() {
json.remove("animations");
}
}
if !keep.animations
&& let Some(Value::Object(source)) = json.get_mut("asset").and_then(|a| a.pointer_mut("/extras/source"))
{
crate::source::drop_assumed_frame_rate(source);
}
let mut after = BTreeSet::new();
extensions_present(&root, &mut after);
let Value::Object(json) = &mut root else { unreachable!() };
for key in ["extensionsUsed", "extensionsRequired"] {
if let Some(list) = json.get_mut(key).and_then(Value::as_array_mut) {
list.retain(|e| e.as_str().is_none_or(|e| !before.contains(e) || after.contains(e)));
if list.is_empty() {
json.remove(key);
}
}
}
let Value::Object(json) = root else { unreachable!() };
*self.json_mut() = json;
}
}
fn matches_pointer(p: &str, prefix: &str) -> bool {
let mut segs = p.split('/');
let pre: Vec<&str> = prefix.trim_end_matches('/').split('/').collect();
pre.iter()
.all(|want| segs.next().is_some_and(|s| *want == "*" || s == *want))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn doc(v: Value) -> Document {
let Value::Object(json) = v else { unreachable!() };
let mut d = Document::empty(Map::new());
*d.json_mut() = json;
d
}
#[test]
fn keeps_everything_by_default() {
let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [{}] }], "extras": { "a": 1 } });
let mut d = doc(v.clone());
d.prune(Keep::default());
assert_eq!(Value::Object(d.json().clone()), v);
}
#[test]
fn a_triangle_limit_alone_prunes_nothing() {
let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [] }] });
let mut d = doc(v.clone());
d.prune(Keep {
max_triangles: 10,
image_bytes: false,
..Keep::ALL
});
assert_eq!(Value::Object(d.json().clone()), v);
let mut d = doc(v);
d.prune(Keep {
extras: false,
..Keep::ALL
});
assert!(!d.json().contains_key("animations"));
}
#[test]
fn point_settings_prune_nothing_but_reach_flatten() {
let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [] }] });
let mut d = doc(v.clone());
d.prune(Keep {
lines_and_points: false,
max_points: usize::MAX,
..Keep::ALL
});
assert_eq!(Value::Object(d.json().clone()), v);
assert!(!d.lines_and_points());
assert_eq!(d.max_points(), TRIANGLE_CEILING);
d.prune(Keep::LIGHT);
assert!(d.lines_and_points());
assert_eq!(d.max_points(), MAX_POINTS);
}
#[test]
fn the_triangle_limit_is_clamped() {
assert_eq!(Keep::ALL.triangles(), MAX_TRIANGLES);
assert_eq!(Keep::LIGHT.max_triangles, MAX_TRIANGLES);
let keep = |max_triangles| Keep {
max_triangles,
..Keep::ALL
};
assert_eq!(keep(12_000_000).triangles(), 12_000_000);
assert_eq!(keep(usize::MAX).triangles(), TRIANGLE_CEILING);
}
#[test]
fn drops_animations_but_keeps_skins() {
let mut d = doc(json!({
"asset": { "version": "2.0" },
"nodes": [{ "mesh": 0, "skin": 0 }, { "camera": 0 }],
"skins": [{ "joints": [1] }],
"cameras": [{ "type": "perspective" }],
"meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1, "WEIGHTS_0": 2 } }] }],
"animations": [{ "channels": [{ "sampler": 0, "target": { "node": 1, "path": "rotation" } }] }],
"extensions": { "KHR_lights_punctual": { "lights": [{ "type": "point" }] } },
"extensionsUsed": ["KHR_lights_punctual", "KHR_mesh_quantization"],
}));
d.prune(Keep::MESHES);
assert_eq!(
Value::Object(d.json().clone()),
json!({
"asset": { "version": "2.0" },
"nodes": [{ "mesh": 0, "skin": 0 }, {}],
"skins": [{ "joints": [1] }],
"meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1, "WEIGHTS_0": 2 } }] }],
"extensionsUsed": ["KHR_mesh_quantization"],
})
);
}
#[test]
fn drops_skins_morphs_and_textures() {
let mut d = doc(json!({
"asset": { "version": "2.0" },
"nodes": [{ "mesh": 0, "skin": 0, "weights": [0.5] }],
"skins": [{ "joints": [0] }],
"meshes": [{
"weights": [0.0],
"extras": { "targetNames": ["smile"], "keep": true },
"primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1 }, "targets": [{ "POSITION": 2 }], "material": 0 }],
}],
"materials": [{
"pbrMetallicRoughness": { "baseColorTexture": { "index": 0 }, "baseColorFactor": [1, 1, 1, 1] },
"extensions": { "KHR_materials_clearcoat": { "clearcoatTexture": { "index": 0 }, "clearcoatFactor": 1 } },
}],
"textures": [{ "source": 0 }],
"images": [{ "uri": "a.png" }],
"animations": [
{ "channels": [{ "sampler": 0, "target": { "node": 0, "path": "weights" } }] },
{ "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] },
],
"extensionsUsed": ["KHR_materials_clearcoat"],
}));
d.prune(Keep {
skins: false,
morph_targets: false,
textures: false,
..Keep::ALL
});
assert_eq!(
Value::Object(d.json().clone()),
json!({
"asset": { "version": "2.0" },
"nodes": [{ "mesh": 0 }],
"meshes": [{ "extras": { "keep": true }, "primitives": [{ "attributes": { "POSITION": 0 }, "material": 0 }] }],
"materials": [{
"pbrMetallicRoughness": { "baseColorFactor": [1, 1, 1, 1] },
"extensions": { "KHR_materials_clearcoat": { "clearcoatFactor": 1 } },
}],
"animations": [{ "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] }],
"extensionsUsed": ["KHR_materials_clearcoat"],
})
);
}
#[test]
fn drops_extras_and_pointer_channels() {
let mut d = doc(json!({
"asset": { "version": "2.0", "extras": 1 },
"materials": [{ "extras": { "x": 1 } }],
"animations": [{ "channels": [
{ "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/materials/0/emissiveFactor" } } } },
{ "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/nodes/0/translation" } } } },
] }],
}));
d.prune(Keep {
materials: false,
extras: false,
..Keep::ALL
});
assert_eq!(
Value::Object(d.json().clone()),
json!({
"asset": { "version": "2.0" },
"animations": [{ "channels": [
{ "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/nodes/0/translation" } } } },
] }],
})
);
}
#[test]
fn pointer_prefixes() {
assert!(matches_pointer("/meshes/3/weights", "/meshes/*/weights"));
assert!(matches_pointer("/meshes/3/weights/1", "/meshes/*/weights"));
assert!(!matches_pointer("/meshes/3/primitives", "/meshes/*/weights"));
assert!(matches_pointer("/cameras/0/perspective/yfov", "/cameras/"));
assert!(!matches_pointer("/camerasx/0", "/cameras/"));
}
}