use std::fmt;
use crate::bytes::{In, Out, fits_u32};
#[cfg(feature = "fingerprint")]
use crate::mesh::Mesh;
#[cfg(feature = "fingerprint")]
use crate::surface::SurfaceEntry;
pub const PAINT_DETAIL: u8 = 0;
pub const PAINT_SUPPORTS_MUST_TOUCH: u8 = 1;
pub const PAINT_SUPPORTS_MUST_NOT_TOUCH: u8 = 2;
pub const PAINT_SUPPORTS_BOTH_WAYS: u8 = 3;
pub const MUST_TOUCH: u8 = 1;
pub const MUST_NOT_TOUCH: u8 = 2;
pub const MAX_PAINT_DEPTH: usize = 32;
pub const FINGERPRINT_SIZE: usize = 48;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PaintDocument {
Runs(PaintRuns),
Trees(PaintTrees),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaintRuns {
pub triangle_count: u32,
pub fingerprint: [u8; FINGERPRINT_SIZE],
pub runs: Vec<PaintRun>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaintRun {
pub length: u32,
pub value: u8,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaintTrees {
pub triangle_count: u32,
pub fingerprint: [u8; FINGERPRINT_SIZE],
pub triangles: Vec<PaintedTriangle>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaintedTriangle {
pub triangle: u32,
pub tree: PaintNode,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PaintNode {
Leaf(u8),
Split {
special: u8,
children: Vec<PaintNode>,
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PaintPiece {
pub corners: [[f64; 3]; 3],
pub value: u8,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodePaintError {
UnknownVersion(u32),
Malformed,
}
impl fmt::Display for DecodePaintError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownVersion(version) => {
write!(
f,
"surface paint document version {version} is not supported"
)
}
Self::Malformed => f.write_str("the surface paint document is malformed"),
}
}
}
impl std::error::Error for DecodePaintError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodePaintError {
RunsDoNotCover,
NotInOrder,
BadSplit,
TooDeep,
TooLarge,
}
impl fmt::Display for EncodePaintError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::RunsDoNotCover => "the paint runs do not cover exactly the mesh's triangles",
Self::NotInOrder => "the painted triangles are out of order, or past the mesh",
Self::BadSplit => "a paint tree splits a triangle in a way the format does not have",
Self::TooDeep => "a paint tree is deeper than the format allows",
Self::TooLarge => "the paint document is too large",
})
}
}
impl std::error::Error for EncodePaintError {}
impl PaintDocument {
#[must_use]
pub fn version(&self) -> u32 {
match self {
Self::Runs(_) => 1,
Self::Trees(_) => 2,
}
}
#[must_use]
pub fn triangle_count(&self) -> u32 {
match self {
Self::Runs(runs) => runs.triangle_count,
Self::Trees(trees) => trees.triangle_count,
}
}
#[must_use]
pub fn fingerprint(&self) -> &[u8; FINGERPRINT_SIZE] {
match self {
Self::Runs(runs) => &runs.fingerprint,
Self::Trees(trees) => &trees.fingerprint,
}
}
#[must_use]
pub fn max_value(&self) -> u8 {
match self {
Self::Runs(runs) => runs.runs.iter().map(|run| run.value).max().unwrap_or(0),
Self::Trees(trees) => trees
.triangles
.iter()
.map(|painted| painted.tree.max_value())
.max()
.unwrap_or(0),
}
}
#[must_use]
pub fn allows_kind(&self, kind: u8) -> bool {
match kind {
PAINT_DETAIL | PAINT_SUPPORTS_MUST_TOUCH | PAINT_SUPPORTS_MUST_NOT_TOUCH => true,
PAINT_SUPPORTS_BOTH_WAYS => self.max_value() <= MUST_NOT_TOUCH,
_ => false,
}
}
#[must_use]
pub fn fits(&self, triangle_count: usize, fingerprint: &[u8; FINGERPRINT_SIZE]) -> bool {
if usize::try_from(self.triangle_count()).ok() != Some(triangle_count)
|| self.fingerprint() != fingerprint
{
return false;
}
match self {
Self::Runs(runs) => runs.covered() == Some(u64::from(runs.triangle_count)),
Self::Trees(_) => true,
}
}
}
impl PaintRuns {
fn covered(&self) -> Option<u64> {
self.runs
.iter()
.try_fold(0u64, |sum, run| sum.checked_add(u64::from(run.length)))
}
pub fn values(&self) -> impl Iterator<Item = u8> + '_ {
self.runs
.iter()
.flat_map(|run| std::iter::repeat_n(run.value, run.length as usize))
}
}
impl PaintNode {
#[must_use]
pub fn max_value(&self) -> u8 {
match self {
Self::Leaf(value) => *value,
Self::Split { children, .. } => children.iter().map(Self::max_value).max().unwrap_or(0),
}
}
#[must_use]
pub fn pieces(&self) -> Vec<PaintPiece> {
const WHOLE: [[f64; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
let mut pieces = Vec::new();
let mut stack = vec![(self, WHOLE)];
while let Some((node, corners)) = stack.pop() {
match node {
Self::Leaf(value) => pieces.push(PaintPiece {
corners,
value: *value,
}),
Self::Split { special, children } => {
let Some(split) = split_corners(corners, *special, children.len()) else {
continue;
};
for (child, child_corners) in children.iter().zip(split).rev() {
stack.push((child, child_corners));
}
}
}
}
pieces
}
#[must_use]
pub fn from_3mf(digits: &str) -> Option<Self> {
let mut groups = Vec::with_capacity(digits.len());
for c in digits.chars().rev() {
groups.push(u8::try_from(c.to_digit(16)?).ok()?);
}
let mut reader = GroupReader {
groups: GroupSource::List(&groups),
next: 0,
};
let node = read_node(&mut reader, 0).ok()?;
(reader.next == groups.len()).then_some(node)
}
#[must_use]
pub fn to_3mf(&self) -> Option<String> {
let mut groups = Vec::new();
write_node(self, 0, &mut |group| groups.push(group)).ok()?;
groups
.iter()
.rev()
.map(|&group| char::from_digit(u32::from(group), 16).map(|c| c.to_ascii_uppercase()))
.collect()
}
}
impl PaintPiece {
#[must_use]
pub fn points(&self, triangle: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
self.corners.map(|weights| {
let mut point = [0.0; 3];
for (weight, corner) in weights.iter().zip(&triangle) {
for (p, c) in point.iter_mut().zip(corner) {
*p += weight * c;
}
}
point
})
}
}
fn split_corners(corners: [[f64; 3]; 3], special: u8, count: usize) -> Option<Vec<[[f64; 3]; 3]>> {
if special > 2 {
return None;
}
let s = usize::from(special);
let p = [corners[s], corners[(s + 1) % 3], corners[(s + 2) % 3]];
let mid = |a: [f64; 3], b: [f64; 3]| {
[
0.5 * (a[0] + b[0]),
0.5 * (a[1] + b[1]),
0.5 * (a[2] + b[2]),
]
};
let (m01, m12, m20) = (mid(p[0], p[1]), mid(p[1], p[2]), mid(p[2], p[0]));
Some(match count {
2 => vec![[p[0], p[1], m12], [m12, p[2], p[0]]],
3 => vec![[p[0], m01, m20], [m01, p[1], m20], [p[1], p[2], m20]],
4 => vec![
[p[0], m01, m20],
[m01, p[1], m12],
[m12, p[2], m20],
[m01, m12, m20],
],
_ => return None,
})
}
pub fn decode_paint(version: u32, document: &[u8]) -> Result<PaintDocument, DecodePaintError> {
let malformed = DecodePaintError::Malformed;
let mut input = In(document);
let triangle_count = input.u32().ok_or(malformed.clone())?;
let fingerprint: [u8; FINGERPRINT_SIZE] = input
.take(FINGERPRINT_SIZE)
.and_then(|bytes| bytes.try_into().ok())
.ok_or(malformed.clone())?;
let decoded = match version {
1 => {
let count = input.count(5).ok_or(malformed.clone())?;
let mut runs = Vec::with_capacity(count);
for _ in 0..count {
let length = input.u32().ok_or(malformed.clone())?;
let value = input.u8().ok_or(malformed.clone())?;
runs.push(PaintRun { length, value });
}
PaintDocument::Runs(PaintRuns {
triangle_count,
fingerprint,
runs,
})
}
2 => {
let count = input.count(4).ok_or(malformed.clone())?;
let mut indices = Vec::with_capacity(count);
let mut previous: Option<u32> = None;
for _ in 0..count {
let gap = input.u32().ok_or(malformed.clone())?;
let index = match previous {
None => gap,
Some(_) if gap == 0 => return Err(malformed),
Some(previous) => previous.checked_add(gap).ok_or(malformed.clone())?,
};
if index >= triangle_count {
return Err(malformed);
}
indices.push(index);
previous = Some(index);
}
let stream = input.bytes().ok_or(malformed.clone())?;
let mut reader = GroupReader {
groups: GroupSource::Bytes(stream),
next: 0,
};
let mut triangles = Vec::with_capacity(count);
for triangle in indices {
let tree = read_node(&mut reader, 0).map_err(|()| malformed.clone())?;
triangles.push(PaintedTriangle { triangle, tree });
}
let used_bytes = reader.next.div_ceil(2);
if used_bytes != stream.len()
|| (reader.next % 2 == 1 && stream.last().is_some_and(|byte| byte >> 4 != 0))
{
return Err(malformed);
}
PaintDocument::Trees(PaintTrees {
triangle_count,
fingerprint,
triangles,
})
}
other => return Err(DecodePaintError::UnknownVersion(other)),
};
if !input.is_empty() {
return Err(malformed);
}
Ok(decoded)
}
pub fn encode_paint(document: &PaintDocument) -> Result<Vec<u8>, EncodePaintError> {
let mut out = Out::default();
out.u32(document.triangle_count());
out.0.extend_from_slice(document.fingerprint());
match document {
PaintDocument::Runs(runs) => {
if runs.covered() != Some(u64::from(runs.triangle_count)) {
return Err(EncodePaintError::RunsDoNotCover);
}
if !fits_u32(runs.runs.len()) {
return Err(EncodePaintError::TooLarge);
}
out.len(runs.runs.len());
for run in &runs.runs {
out.u32(run.length);
out.u8(run.value);
}
}
PaintDocument::Trees(trees) => {
if !fits_u32(trees.triangles.len()) {
return Err(EncodePaintError::TooLarge);
}
out.len(trees.triangles.len());
let mut previous: Option<u32> = None;
for painted in &trees.triangles {
if painted.triangle >= trees.triangle_count
|| previous.is_some_and(|previous| painted.triangle <= previous)
{
return Err(EncodePaintError::NotInOrder);
}
out.u32(painted.triangle - previous.unwrap_or(0));
previous = Some(painted.triangle);
}
let mut stream = Vec::new();
let mut groups = 0usize;
for painted in &trees.triangles {
write_node(&painted.tree, 0, &mut |group| {
if groups.is_multiple_of(2) {
stream.push(group);
} else if let Some(last) = stream.last_mut() {
*last |= group << 4;
}
groups += 1;
})?;
}
if !fits_u32(stream.len()) {
return Err(EncodePaintError::TooLarge);
}
out.bytes(&stream);
}
}
Ok(out.0)
}
enum GroupSource<'a> {
Bytes(&'a [u8]),
List(&'a [u8]),
}
struct GroupReader<'a> {
groups: GroupSource<'a>,
next: usize,
}
impl GroupReader<'_> {
fn group(&mut self) -> Result<u8, ()> {
let group = match self.groups {
GroupSource::Bytes(bytes) => {
let byte = *bytes.get(self.next / 2).ok_or(())?;
if self.next.is_multiple_of(2) {
byte & 0x0f
} else {
byte >> 4
}
}
GroupSource::List(groups) => *groups.get(self.next).ok_or(())?,
};
self.next += 1;
Ok(group)
}
}
fn read_node(reader: &mut GroupReader<'_>, depth: usize) -> Result<PaintNode, ()> {
if depth > MAX_PAINT_DEPTH {
return Err(());
}
let group = reader.group()?;
let sides = group & 3;
let high = group >> 2;
if sides == 0 {
let mut value = u32::from(high);
if high == 3 {
loop {
let more = reader.group()?;
value += u32::from(more);
if value > 255 {
return Err(());
}
if more != 15 {
break;
}
}
}
return Ok(PaintNode::Leaf(u8::try_from(value).map_err(|_| ())?));
}
if high == 3 {
return Err(());
}
let mut children = Vec::with_capacity(usize::from(sides) + 1);
for _ in 0..=sides {
children.push(read_node(reader, depth + 1)?);
}
children.reverse();
Ok(PaintNode::Split {
special: high,
children,
})
}
fn write_node(
node: &PaintNode,
depth: usize,
out: &mut impl FnMut(u8),
) -> Result<(), EncodePaintError> {
if depth > MAX_PAINT_DEPTH {
return Err(EncodePaintError::TooDeep);
}
match node {
PaintNode::Leaf(value) if *value < 3 => out(value << 2),
PaintNode::Leaf(value) => {
out(3 << 2);
let mut rest = value - 3;
while rest >= 15 {
out(15);
rest -= 15;
}
out(rest);
}
PaintNode::Split { special, children } => {
let sides = match children.len() {
2 => 1,
3 => 2,
4 => 3,
_ => return Err(EncodePaintError::BadSplit),
};
if *special > 2 {
return Err(EncodePaintError::BadSplit);
}
out(sides | (special << 2));
for child in children.iter().rev() {
write_node(child, depth + 1, out)?;
}
}
}
Ok(())
}
#[cfg(feature = "fingerprint")]
#[must_use]
pub fn mesh_fingerprint(mesh: &Mesh) -> [u8; FINGERPRINT_SIZE] {
use sha2::{Digest, Sha384};
let mut hasher = Sha384::new();
hasher.update((mesh.vertices.len() as u64).to_le_bytes());
for vertex in &mesh.vertices {
for coordinate in vertex {
hasher.update(coordinate.to_bits().to_le_bytes());
}
}
hasher.update((mesh.triangles.len() as u64).to_le_bytes());
for triangle in &mesh.triangles {
for index in triangle {
hasher.update(index.to_le_bytes());
}
}
hasher.finalize().into()
}
#[cfg(feature = "fingerprint")]
impl SurfaceEntry {
#[must_use]
pub fn paint(&self, mesh: &Mesh) -> Option<PaintDocument> {
let document = decode_paint(self.version, &self.document).ok()?;
(document.allows_kind(self.kind)
&& document.fits(mesh.triangles.len(), &mesh_fingerprint(mesh)))
.then_some(document)
}
}