use crate::mesh::Mesh;
use crate::paint::{
DecodePaintError, EncodePaintError, MAX_PAINT_DEPTH, PaintDocument, PaintNode, PaintPiece,
PaintRun, PaintRuns, PaintTrees, PaintedTriangle, decode_paint, encode_paint, mesh_fingerprint,
};
use crate::surface::SurfaceEntry;
const PRINT: [u8; 48] = [7; 48];
fn leaf(value: u8) -> PaintNode {
PaintNode::Leaf(value)
}
fn split(special: u8, children: Vec<PaintNode>) -> PaintNode {
PaintNode::Split { special, children }
}
fn trees(triangle_count: u32, triangles: Vec<(u32, PaintNode)>) -> PaintDocument {
PaintDocument::Trees(PaintTrees {
triangle_count,
fingerprint: PRINT,
triangles: triangles
.into_iter()
.map(|(triangle, tree)| PaintedTriangle { triangle, tree })
.collect(),
})
}
fn raw_trees(triangle_count: u32, gaps: &[u32], groups: &[u8]) -> Vec<u8> {
let mut out = triangle_count.to_le_bytes().to_vec();
out.extend(PRINT);
out.extend((gaps.len() as u32).to_le_bytes());
for gap in gaps {
out.extend(gap.to_le_bytes());
}
let mut stream = Vec::new();
for (i, &group) in groups.iter().enumerate() {
if i % 2 == 0 {
stream.push(group);
} else {
*stream.last_mut().unwrap() |= group << 4;
}
}
out.extend((stream.len() as u32).to_le_bytes());
out.extend(stream);
out
}
fn a_tree() -> PaintNode {
split(
1,
vec![
leaf(1),
split(
0,
vec![leaf(2), leaf(0), leaf(1), split(2, vec![leaf(2), leaf(0)])],
),
leaf(0),
],
)
}
#[test]
fn documents_come_back_identical() {
let documents = [
PaintDocument::Runs(PaintRuns {
triangle_count: 12,
fingerprint: PRINT,
runs: vec![
PaintRun {
length: 2,
value: 255,
},
PaintRun {
length: 10,
value: 0,
},
],
}),
trees(12, vec![]),
trees(12, vec![(0, leaf(1)), (3, a_tree()), (11, leaf(255))]),
trees(5, vec![(2, leaf(17)), (4, leaf(3))]),
];
for document in &documents {
let bytes = encode_paint(document).unwrap();
assert_eq!(&decode_paint(document.version(), &bytes).unwrap(), document);
}
}
#[test]
fn every_value_round_trips_with_the_fewest_groups() {
for value in 0..=255u8 {
let document = trees(1, vec![(0, leaf(value))]);
let bytes = encode_paint(&document).unwrap();
assert_eq!(decode_paint(2, &bytes).unwrap(), document);
let groups = match value {
0..=2 => 1,
_ => 2 + usize::from(value - 3) / 15,
};
assert_eq!(leaf(value).to_3mf().unwrap().len(), groups, "value {value}");
}
}
#[test]
fn the_stream_holds_the_first_group_in_the_low_half_and_the_last_child_first() {
let document = trees(3, vec![(2, split(1, vec![leaf(1), leaf(2)]))]);
let bytes = encode_paint(&document).unwrap();
assert_eq!(bytes, raw_trees(3, &[2], &[5, 8, 4]));
assert_eq!(bytes[bytes.len() - 2..], [0x85, 0x04]);
}
#[test]
fn gaps_give_the_painted_triangles() {
let bytes = raw_trees(10, &[2, 3, 1], &[4, 8, 4]);
let PaintDocument::Trees(document) = decode_paint(2, &bytes).unwrap() else {
panic!("version 2 gives trees");
};
let indices: Vec<u32> = document.triangles.iter().map(|t| t.triangle).collect();
assert_eq!(indices, [2, 5, 6]);
}
#[test]
fn malformed_documents_are_refused() {
let deep = {
let mut groups = vec![1u8; MAX_PAINT_DEPTH + 1];
groups.extend(vec![0u8; MAX_PAINT_DEPTH + 2]);
groups
};
let just_deep_enough = {
let mut groups = vec![1u8; MAX_PAINT_DEPTH];
groups.extend(vec![0u8; MAX_PAINT_DEPTH + 1]);
groups
};
assert!(decode_paint(2, &raw_trees(1, &[0], &just_deep_enough)).is_ok());
let mut odd_tail = raw_trees(1, &[0], &[4]);
*odd_tail.last_mut().unwrap() = 0x14;
let cases: Vec<(&str, Vec<u8>)> = vec![
("a gap of 0 after the first", raw_trees(4, &[1, 0], &[4, 4])),
("a triangle past the mesh", raw_trees(4, &[4], &[4])),
(
"gaps that add up past the mesh",
raw_trees(4, &[2, 2], &[4, 4]),
),
("special corner 3", raw_trees(1, &[0], &[1 | 3 << 2, 0, 0])),
("too deep", raw_trees(1, &[0], &deep)),
(
"a value of 256",
raw_trees(
1,
&[0],
&[
12, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 14,
],
),
),
("a stream cut inside a tree", raw_trees(1, &[0], &[2, 0])),
("a tree missing", raw_trees(3, &[0, 1, 1], &[4, 4])),
("a group after the last tree", raw_trees(1, &[0], &[4, 4])),
("a byte after the last tree", raw_trees(1, &[0], &[4, 0, 0])),
("unused bits that are not 0", odd_tail),
("a count larger than the bytes", {
let mut bytes = raw_trees(1, &[], &[]);
bytes[52..56].copy_from_slice(&u32::MAX.to_le_bytes());
bytes
}),
("bytes after the trees", {
let mut bytes = raw_trees(1, &[0], &[4]);
bytes.push(0);
bytes
}),
(
"a document cut short",
raw_trees(1, &[0], &[4])[..20].to_vec(),
),
];
for (why, bytes) in cases {
assert_eq!(
decode_paint(2, &bytes),
Err(DecodePaintError::Malformed),
"{why}"
);
}
let mut most = vec![12];
most.extend([15; 16]);
most.push(12);
assert!(decode_paint(2, &raw_trees(1, &[0], &most)).is_ok());
}
#[test]
fn unknown_versions_are_named() {
assert_eq!(
decode_paint(3, &raw_trees(1, &[], &[])),
Err(DecodePaintError::UnknownVersion(3))
);
}
#[test]
fn encoding_checks_the_rules() {
let bad: [(PaintDocument, EncodePaintError); 6] = [
(
PaintDocument::Runs(PaintRuns {
triangle_count: 3,
fingerprint: PRINT,
runs: vec![PaintRun {
length: 2,
value: 1,
}],
}),
EncodePaintError::RunsDoNotCover,
),
(
trees(3, vec![(2, leaf(1)), (1, leaf(1))]),
EncodePaintError::NotInOrder,
),
(trees(3, vec![(3, leaf(1))]), EncodePaintError::NotInOrder),
(
trees(3, vec![(0, split(0, vec![leaf(1)]))]),
EncodePaintError::BadSplit,
),
(
trees(3, vec![(0, split(3, vec![leaf(1), leaf(2)]))]),
EncodePaintError::BadSplit,
),
(
trees(
3,
vec![(0, {
let mut node = leaf(1);
for _ in 0..=MAX_PAINT_DEPTH {
node = split(0, vec![node, leaf(0)]);
}
node
})],
),
EncodePaintError::TooDeep,
),
];
for (document, error) in bad {
assert_eq!(encode_paint(&document), Err(error));
}
}
fn corners(piece: &PaintPiece) -> [[f64; 3]; 3] {
piece.corners
}
#[test]
fn splits_make_the_pieces_the_spec_lists() {
let a = [1.0, 0.0, 0.0];
let b = [0.0, 1.0, 0.0];
let c = [0.0, 0.0, 1.0];
let mid = |p: [f64; 3], q: [f64; 3]| {
[
0.5 * (p[0] + q[0]),
0.5 * (p[1] + q[1]),
0.5 * (p[2] + q[2]),
]
};
let (p0, p1, p2) = (b, c, a);
let one = split(1, vec![leaf(1), leaf(2)]).pieces();
assert_eq!(
one.iter().map(corners).collect::<Vec<_>>(),
[[p0, p1, mid(p1, p2)], [mid(p1, p2), p2, p0]]
);
assert_eq!(one.iter().map(|p| p.value).collect::<Vec<_>>(), [1, 2]);
let two = split(1, vec![leaf(0), leaf(1), leaf(2)]).pieces();
assert_eq!(
two.iter().map(corners).collect::<Vec<_>>(),
[
[p0, mid(p0, p1), mid(p2, p0)],
[mid(p0, p1), p1, mid(p2, p0)],
[p1, p2, mid(p2, p0)]
]
);
let three = split(1, vec![leaf(0), leaf(1), leaf(2), leaf(1)]).pieces();
assert_eq!(
three.iter().map(corners).collect::<Vec<_>>(),
[
[p0, mid(p0, p1), mid(p2, p0)],
[mid(p0, p1), p1, mid(p1, p2)],
[mid(p1, p2), p2, mid(p2, p0)],
[mid(p0, p1), mid(p1, p2), mid(p2, p0)]
]
);
}
fn share(piece: &PaintPiece) -> f64 {
let [p, q, r] = piece.corners;
(q[1] - p[1]) * (r[2] - p[2]) - (q[2] - p[2]) * (r[1] - p[1])
}
#[test]
fn pieces_cover_the_triangle_once_and_keep_its_winding() {
for tree in [
a_tree(),
split(2, vec![a_tree(), leaf(1), split(0, vec![leaf(0), leaf(1)])]),
] {
let pieces = tree.pieces();
assert!(pieces.iter().all(|piece| share(piece) > 0.0));
assert_eq!(pieces.iter().map(share).sum::<f64>(), 1.0);
}
}
#[test]
fn points_mix_the_triangle_corners() {
let piece = &split(0, vec![leaf(0), leaf(1)]).pieces()[0];
let triangle = [[0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [0.0, 2.0, 0.0]];
assert_eq!(
piece.points(triangle),
[[0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [2.0, 1.0, 0.0]]
);
}
#[test]
fn trees_convert_to_and_from_3mf_strings() {
let tree = a_tree();
let digits = tree.to_3mf().unwrap();
assert_eq!(PaintNode::from_3mf(&digits), Some(tree));
assert_eq!(
PaintNode::from_3mf(&digits.to_lowercase()),
PaintNode::from_3mf(&digits)
);
assert_eq!(split(1, vec![leaf(1), leaf(2)]).to_3mf().unwrap(), "485");
assert_eq!(PaintNode::from_3mf("4"), Some(leaf(1)));
for bad in ["", "G", "0485", "1", "D"] {
assert_eq!(PaintNode::from_3mf(bad), None, "{bad:?}");
}
}
fn cube_like() -> Mesh {
Mesh {
meta: None,
vertices: vec![
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
],
triangles: vec![[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]],
}
}
fn entry(kind: u8, document: &PaintDocument) -> SurfaceEntry {
SurfaceEntry {
program: Some("nudl".into()),
leaf: 0,
kind,
version: document.version(),
document: encode_paint(document).unwrap(),
}
}
#[test]
fn entries_apply_only_to_the_mesh_and_kind_they_fit() {
let mesh = cube_like();
let print = mesh_fingerprint(&mesh);
let made = |values: Vec<(u32, PaintNode)>| {
let PaintDocument::Trees(mut document) = trees(4, values) else {
unreachable!()
};
document.fingerprint = print;
PaintDocument::Trees(document)
};
let both_ways = made(vec![(1, split(0, vec![leaf(1), leaf(2)]))]);
assert_eq!(entry(3, &both_ways).paint(&mesh), Some(both_ways.clone()));
assert_eq!(entry(1, &both_ways).paint(&mesh), Some(both_ways.clone()));
let soft = made(vec![(0, leaf(128))]);
assert_eq!(entry(0, &soft).paint(&mesh), Some(soft.clone()));
assert_eq!(
entry(3, &soft).paint(&mesh),
None,
"kind 3 allows values up to 2"
);
assert_eq!(entry(4, &soft).paint(&mesh), None, "kind 4 is reserved");
let mut other = cube_like();
other.vertices[3][2] = 2.0;
assert_eq!(entry(3, &both_ways).paint(&other), None, "another mesh");
let mut unknown = entry(3, &both_ways);
unknown.version = 9;
assert_eq!(unknown.paint(&mesh), None);
let runs = PaintDocument::Runs(PaintRuns {
triangle_count: 4,
fingerprint: print,
runs: vec![PaintRun {
length: 4,
value: 2,
}],
});
assert_eq!(entry(3, &runs).paint(&mesh), Some(runs.clone()));
let PaintDocument::Runs(short) = &runs else {
unreachable!()
};
let short = PaintRuns {
runs: vec![PaintRun {
length: 3,
value: 2,
}],
..short.clone()
};
let mut bytes = 4u32.to_le_bytes().to_vec();
bytes.extend(print);
bytes.extend(1u32.to_le_bytes());
bytes.extend(3u32.to_le_bytes());
bytes.push(2);
let entry = SurfaceEntry {
program: Some("nudl".into()),
leaf: 0,
kind: 1,
version: 1,
document: bytes,
};
assert_eq!(
decode_paint(1, &entry.document),
Ok(PaintDocument::Runs(short))
);
assert_eq!(entry.paint(&mesh), None, "runs that do not cover the mesh");
}
#[test]
fn runs_give_a_value_per_triangle() {
let runs = PaintRuns {
triangle_count: 5,
fingerprint: PRINT,
runs: vec![
PaintRun {
length: 2,
value: 9,
},
PaintRun {
length: 0,
value: 4,
},
PaintRun {
length: 3,
value: 0,
},
],
};
assert_eq!(runs.values().collect::<Vec<_>>(), [9, 9, 0, 0, 0]);
}