use std::collections::{HashMap, HashSet};
use std::fmt;
use crate::bytes::{In, Out, fits_u32};
use crate::container::ChunkTag;
use crate::program::is_name;
use crate::scene::{NodeKind, Scene, Transform, read_transform, write_transform};
pub const VOLUME_TAG: ChunkTag = ChunkTag(*b"VOLM");
pub const VOLUME_VERSION: u16 = 1;
pub const VOLUME_SUPPORT_ENFORCER: u8 = 1;
pub const VOLUME_SUPPORT_BLOCKER: u8 = 2;
pub const VOLUME_MODIFIER: u8 = 3;
pub const VOLUME_NEGATIVE: u8 = 4;
pub const VOLUME_UNCUT: u8 = 5;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VolumeEntry {
pub model: usize,
pub kind: u8,
pub mesh: usize,
pub name: Option<String>,
pub transform: Option<Transform>,
pub program: String,
pub version: u32,
pub document: Vec<u8>,
}
impl VolumeEntry {
pub fn is_known(&self) -> bool {
matches!(
self.kind,
VOLUME_SUPPORT_ENFORCER
| VOLUME_SUPPORT_BLOCKER
| VOLUME_MODIFIER
| VOLUME_NEGATIVE
| VOLUME_UNCUT
)
}
pub fn is_volume(&self) -> bool {
self.is_known() && self.kind != VOLUME_UNCUT
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodeVolumesError {
BadName { program: String },
NotALeaf,
NoSuchMesh,
VolumeShown,
UncutMoved,
UncutCount,
ReservedKind,
TooLarge,
}
impl fmt::Display for EncodeVolumesError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BadName { program } => write!(f, "{program:?} is not a program name"),
Self::NotALeaf => f.write_str(NOT_A_LEAF),
Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
Self::VolumeShown => f.write_str(VOLUME_SHOWN),
Self::UncutMoved => f.write_str(UNCUT_MOVED),
Self::UncutCount => f.write_str(UNCUT_COUNT),
Self::ReservedKind => f.write_str("a volume entry has a reserved kind"),
Self::TooLarge => f.write_str("the volumes are too large for their chunk"),
}
}
}
impl std::error::Error for EncodeVolumesError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodeVolumesError {
Malformed,
NotALeaf,
NoSuchMesh,
VolumeShown,
UncutMoved,
UncutCount,
}
impl fmt::Display for DecodeVolumesError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed => f.write_str("the volume data is malformed"),
Self::NotALeaf => f.write_str(NOT_A_LEAF),
Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
Self::VolumeShown => f.write_str(VOLUME_SHOWN),
Self::UncutMoved => f.write_str(UNCUT_MOVED),
Self::UncutCount => f.write_str(UNCUT_COUNT),
}
}
}
impl std::error::Error for DecodeVolumesError {}
const NOT_A_LEAF: &str = "a volume belongs to a scene part that is not a leaf";
const NO_SUCH_MESH: &str = "a volume names a mesh the file does not have";
const VOLUME_SHOWN: &str = "a leaf shows the mesh of a volume, which never prints";
const UNCUT_MOVED: &str = "the uncut model of a volume entry has a transform";
const UNCUT_COUNT: &str = "a model's negative volumes and its uncut model do not go together";
enum Broken {
NotALeaf,
NoSuchMesh,
VolumeShown,
UncutMoved,
UncutCount,
}
impl From<Broken> for EncodeVolumesError {
fn from(broken: Broken) -> Self {
match broken {
Broken::NotALeaf => Self::NotALeaf,
Broken::NoSuchMesh => Self::NoSuchMesh,
Broken::VolumeShown => Self::VolumeShown,
Broken::UncutMoved => Self::UncutMoved,
Broken::UncutCount => Self::UncutCount,
}
}
}
impl From<Broken> for DecodeVolumesError {
fn from(broken: Broken) -> Self {
match broken {
Broken::NotALeaf => Self::NotALeaf,
Broken::NoSuchMesh => Self::NoSuchMesh,
Broken::VolumeShown => Self::VolumeShown,
Broken::UncutMoved => Self::UncutMoved,
Broken::UncutCount => Self::UncutCount,
}
}
}
const MIN_ENTRY: usize = 4 + 1 + 4 + 1 + 1 + 5 + 4 + 4;
pub fn encode_volumes(
entries: &[VolumeEntry],
scene: &Scene,
) -> Result<Vec<u8>, EncodeVolumesError> {
if let Some(entry) = entries
.iter()
.find(|entry| !is_name(entry.program.as_bytes()))
{
return Err(EncodeVolumesError::BadName {
program: entry.program.clone(),
});
}
check(entries, scene)?;
if entries.iter().any(|entry| !entry.is_known()) {
return Err(EncodeVolumesError::ReservedKind);
}
let fits = fits_u32(entries.len())
&& entries.iter().all(|entry| {
entry.name.as_ref().is_none_or(|name| fits_u32(name.len()))
&& fits_u32(entry.document.len())
});
if !fits {
return Err(EncodeVolumesError::TooLarge);
}
let mut out = Out::default();
out.len(entries.len());
for entry in entries {
out.len(entry.model);
out.u8(entry.kind);
out.len(entry.mesh);
out.text(entry.name.as_deref());
write_transform(&mut out, entry.transform.as_ref());
out.bytes(entry.program.as_bytes());
out.u32(entry.version);
out.bytes(&entry.document);
}
Ok(out.0)
}
pub fn decode_volumes(
payload: &[u8],
scene: &Scene,
) -> Result<Vec<VolumeEntry>, DecodeVolumesError> {
let mut input = In(payload);
let entries = read(&mut input).ok_or(DecodeVolumesError::Malformed)?;
if !input.is_empty() {
return Err(DecodeVolumesError::Malformed);
}
check(&entries, scene)?;
Ok(entries)
}
fn read(input: &mut In<'_>) -> Option<Vec<VolumeEntry>> {
let count = input.count(MIN_ENTRY)?;
let mut entries = Vec::with_capacity(count);
for _ in 0..count {
let model = input.len()?;
let kind = input.u8()?;
let mesh = input.len()?;
let name = input.text()?;
let transform = read_transform(input)?;
let program = input.bytes()?;
if !is_name(program) {
return None;
}
let program = String::from_utf8_lossy(program).into_owned();
let version = input.u32()?;
let document = input.bytes()?.to_vec();
entries.push(VolumeEntry {
model,
kind,
mesh,
name,
transform,
program,
version,
document,
});
}
Some(entries)
}
fn check(entries: &[VolumeEntry], scene: &Scene) -> Result<(), Broken> {
for entry in entries {
scene.leaf_mesh(entry.model).ok_or(Broken::NotALeaf)?;
if entry.mesh >= scene.meshes.len() {
return Err(Broken::NoSuchMesh);
}
}
let shown = shown_meshes(scene);
let mut cut = HashSet::new();
let mut uncut: HashMap<usize, usize> = HashMap::new();
for entry in entries.iter().filter(|entry| entry.is_known()) {
if entry.is_volume() && shown.contains(&entry.mesh) {
return Err(Broken::VolumeShown);
}
match entry.kind {
VOLUME_NEGATIVE => {
cut.insert(entry.model);
}
VOLUME_UNCUT => {
if entry.transform.is_some() {
return Err(Broken::UncutMoved);
}
*uncut.entry(entry.model).or_default() += 1;
}
_ => {}
}
}
let one_each = uncut.values().all(|&n| n == 1);
let same_models = cut.len() == uncut.len() && cut.iter().all(|model| uncut.contains_key(model));
if !one_each || !same_models {
return Err(Broken::UncutCount);
}
Ok(())
}
fn shown_meshes(scene: &Scene) -> HashSet<usize> {
scene
.nodes
.iter()
.filter_map(|node| match node.kind {
NodeKind::Leaf { mesh } => Some(mesh),
NodeKind::SharedLeaf { resource } => scene.mesh_resources.get(resource).copied(),
_ => None,
})
.collect()
}