From a7009395fcbdcded2c6adeffc26950cbe32bc608 Mon Sep 17 00:00:00 2001 From: Ken Mantle Date: Mon, 16 Nov 2026 21:29:51 -0500 Subject: [PATCH] craft-prc: write triangle-mesh scenes as PRC (#1934) --- crates/prc/Cargo.toml | 2 +- crates/prc/README.md | 14 +- crates/prc/src/acof.rs | 17 +- crates/prc/src/lib.rs | 8 + crates/prc/src/tree/mod.rs | 13 ++ crates/prc/src/tree/style.rs | 21 +- crates/prc/src/tree/tests.rs | 2 +- crates/prc/src/write/bits.rs | 164 +++++++++++++++ crates/prc/src/write/bounds.rs | 45 ++++ crates/prc/src/write/container.rs | 80 +++++++ crates/prc/src/write/mod.rs | 287 +++++++++++++++++++++++++ crates/prc/src/write/readback.rs | 32 +++ crates/prc/src/write/sections.rs | 300 ++++++++++++++++++++++++++ crates/prc/src/write/tess.rs | 118 +++++++++++ crates/prc/src/write/tests.rs | 339 ++++++++++++++++++++++++++++++ crates/prc/src/write/textures.rs | 240 +++++++++++++++++++++ crates/prc/src/write/validate.rs | 292 +++++++++++++++++++++++++ crates/prc/src/write/vec3.rs | 53 +++++ 18 files changed, 2016 insertions(+), 11 deletions(-) create mode 100644 crates/prc/src/write/bits.rs create mode 100644 crates/prc/src/write/bounds.rs create mode 100644 crates/prc/src/write/container.rs create mode 100644 crates/prc/src/write/mod.rs create mode 100644 crates/prc/src/write/readback.rs create mode 100644 crates/prc/src/write/sections.rs create mode 100644 crates/prc/src/write/tess.rs create mode 100644 crates/prc/src/write/tests.rs create mode 100644 crates/prc/src/write/textures.rs create mode 100644 crates/prc/src/write/validate.rs create mode 100644 crates/prc/src/write/vec3.rs diff --git a/crates/prc/Cargo.toml b/crates/prc/Cargo.toml index 08d3d2563..37fce806a 100644 --- a/crates/prc/Cargo.toml +++ b/crates/prc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-prc" -description = "PRC 3D model reader (ISO 14739-1): container, bit-level primitives, schema" +description = "PRC 3D model reader and triangle-mesh writer (ISO 14739-1)" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/prc/README.md b/crates/prc/README.md index c76d0af5b..084b42374 100644 --- a/crates/prc/README.md +++ b/crates/prc/README.md @@ -1,6 +1,6 @@ # craft-prc -A reader for PRC (ISO 14739-1), the 3D model format a PDF `/3D` stream of `/Subtype /PRC` carries (ISO 32000-2 §13.6.3). +A reader and triangle-mesh writer for PRC (ISO 14739-1), the 3D model format a PDF `/3D` stream of `/Subtype /PRC` carries (ISO 32000-2 §13.6.3). - Standalone: no PDF code and no app code. The caller hands it the stream's bytes; drawing the model stays in the app. - **Licence:** MIT OR Apache-2.0. Inflation through `flate2` with a pure-Rust backend (`miniz_oxide` unless the app's build selects `zlib-rs`). @@ -42,3 +42,15 @@ BitReader: bit, bits, character, unsigned_integer, integer, integer_vbn, double_ - Not yet in the crate: stored-normal or one-status compressed mesh reconstruction, textures. - The `Double` code table's rows come from [prc-rs](https://github.com/ralovich/prc-rs) (MIT); its notice is in `src/acof/table.rs`. A few reading choices also follow prc-rs; each is marked `// prc-rs:` in the source. + +## Writing + +```rust +write_prc(&MeshScene) -> Result // one file structure, readable by PrcFile::parse +MeshScene::bounds() -> Option<[[f64; 3]; 2]> // the placed triangles' box, for a 3D view +``` + +- A `MeshScene` is nodes (name, optional 4x4 matrix, optional mesh, children), roots, meshes of triangle primitives (positions, optional per-vertex normals and texture coordinates, a material), materials (RGBA and emissive) and PNG or JPEG textures with S and T wraps. +- The whole scene is checked before a bit is written: indices, finite numbers, a tree (one parent per node, no repeated root, nesting at most `MAX_NODE_DEPTH`, 64, the reader's walk limit), and each texture's header. A failure is `PrcWriteError`, never a partial stream. +- `PrcWriteReport` holds the stream and counts what the writer supplied itself: flat normals for primitives without normals, and empty primitives dropped. +- Not written: lights, markups, views, B-rep, compressed tessellation. diff --git a/crates/prc/src/acof.rs b/crates/prc/src/acof.rs index fc11a663a..de53d44e2 100644 --- a/crates/prc/src/acof.rs +++ b/crates/prc/src/acof.rs @@ -58,10 +58,21 @@ pub(crate) fn lookup(nbits: u32, code: u32) -> Option { table()?.get(&key(nbits, code)).copied() } -/// The `(nbits, code)` of IEEE exponent `e`'s row, the test writer's half of [`lookup`]. -#[cfg(test)] +/// The `(nbits, code)` of IEEE exponent `e`'s row (`e` in 0..=2047), the writer's half of [`lookup`]. pub(crate) fn exponent_code(e: u32) -> Option<(u32, u32)> { - table()?.iter().find(|(_, v)| matches!(v, Entry::Exponent(hi) if (hi >> 20) & 0x7ff == e)).map(|(&k, _)| (k >> 24, k & 0xff_ffff)) + static CODES: OnceLock>> = OnceLock::new(); + let codes = CODES.get_or_init(|| { + let mut codes = vec![None; 2048]; + for (&k, v) in table().into_iter().flatten() { + if let Entry::Exponent(upper) = v + && let Some(slot) = codes.get_mut((upper >> 20) as usize & 0x7ff) + { + *slot = Some((k >> 24, k & 0xff_ffff)); + } + } + codes + }); + codes.get(e as usize).copied().flatten() } #[cfg(test)] diff --git a/crates/prc/src/lib.rs b/crates/prc/src/lib.rs index 74c6cd52a..6cdf5a4c8 100644 --- a/crates/prc/src/lib.rs +++ b/crates/prc/src/lib.rs @@ -7,6 +7,9 @@ //! tessellations and walks the product tree into placed, coloured meshes //! ([`PrcFile::placements`], [`PrcFile::model_tree`]). //! +//! [`write_prc`] writes a triangle-mesh scene ([`MeshScene`]: named nodes, shared meshes, colours, +//! PNG/JPEG base-colour textures) as a single-file-structure stream. +//! //! Clause numbers in `[WD x.y]` refer to the PRC working draft, ISO/TC 171/SC 2 N570. //! //! Every read is bounded: inflation by [`MAX_INFLATED_BYTES`] (or a caller's limit), decoded @@ -27,6 +30,7 @@ mod tess; #[cfg(test)] mod testw; mod tree; +mod write; pub use bits::{BitReader, MAX_DECODED_ELEMENTS, MAX_SCHEMA_STEPS}; pub use container::{FileStructure, MAX_FILE_STRUCTURES, MAX_INFLATED_BYTES, PRC_READER_VERSION, PrcFile, PrcHeader, SectionKind, UniqueId}; @@ -35,3 +39,7 @@ pub use geometry::Matrix; pub use schema::Schema; pub use tess::{Tessellation, TriangleMesh, TriangleStyle}; pub use tree::{EntityOverrides, MAX_PLACEMENTS, ModelNode, ModelUnits, NameSource, Placement, Rgba, StyleAlpha}; +pub use write::{ + MAX_NODE_DEPTH, MeshScene, PrcWriteError, PrcWriteReport, SceneMaterial, SceneMesh, SceneNode, ScenePrimitive, SceneTexture, TextureWrap, + write_prc, +}; diff --git a/crates/prc/src/tree/mod.rs b/crates/prc/src/tree/mod.rs index db2d5352c..5f20435e1 100644 --- a/crates/prc/src/tree/mod.rs +++ b/crates/prc/src/tree/mod.rs @@ -353,6 +353,19 @@ fn places_by_system(tree: &Tree) -> bool { tree.parts.iter().flatten().any(|i| !i.local.is_empty()) || tree.products.iter().flat_map(|p| &p.overrides).any(|o| o.local != 0) } +#[cfg(test)] +impl PrcFile { + /// Each file structure's materials' emissive colours, in material order. + pub(crate) fn material_emissives(&self) -> Result>>, PrcError> { + let of = |fs: &crate::FileStructure| { + let mut r = BitReader::new(fs.section(SectionKind::Globals)); + let schema = Schema::read(&mut r)?; + Ok(Ctx::new(r, &schema, fs.authoring_version).globals()?.emissives()) + }; + self.file_structures.iter().map(of).collect() + } +} + #[cfg(test)] mod markup_tests; #[cfg(test)] diff --git a/crates/prc/src/tree/style.rs b/crates/prc/src/tree/style.rs index d313fb2f6..4ccd66fe0 100644 --- a/crates/prc/src/tree/style.rs +++ b/crates/prc/src/tree/style.rs @@ -69,8 +69,9 @@ pub(crate) struct Style { /// A `materials` entry as far as colour. #[derive(Debug, Clone, Copy, PartialEq)] pub(crate) enum Material { - /// `Material` (702): `diffuse + 1` (a colour index) and the diffuse alpha. - Plain { diffuse: u32, alpha: f64 }, + /// `Material` (702): `diffuse + 1` and `emissive + 1` (colour indices) and the + /// diffuse alpha. + Plain { diffuse: u32, emissive: u32, alpha: f64 }, /// `TextureApplication` (711) [WD 7.5.6]: `material_generic_index + 1`, the material /// under the texture. Textured { base: u32 }, @@ -93,6 +94,16 @@ pub(crate) fn biased(list: &[T], biased: u32) -> Option<&T> { } impl Globals { + /// Each material's emissive colour; `None` for a texture application or no emission. + #[cfg_attr(not(test), expect(dead_code, reason = "called by unit tests"))] + pub(crate) fn emissives(&self) -> Vec> { + let of = |m: &Material| match *m { + Material::Plain { emissive, .. } => self.colour(emissive), + Material::Textured { .. } => None, + }; + self.materials.iter().map(of).collect() + } + /// The colour a style or material names by `biased` (`index + 1`). Stored indices count /// the colour array's doubles, so `colours[i]` is stored as `3i + 1`; an index that is /// not of that form names nothing. @@ -114,7 +125,7 @@ impl Globals { m = biased(&self.materials, base)?; } match *m { - Material::Plain { diffuse, alpha } => (self.colour(diffuse)?, alpha), + Material::Plain { diffuse, alpha, .. } => (self.colour(diffuse)?, alpha), Material::Textured { .. } => return None, } } else { @@ -234,14 +245,14 @@ impl Ctx<'_, '_> { MATERIAL => { self.r.unsigned_integer()?; // ambient + 1 let diffuse = self.r.unsigned_integer()?; - self.r.unsigned_integer()?; // emissive + 1 + let emissive = self.r.unsigned_integer()?; self.r.unsigned_integer()?; // specular + 1 self.r.double()?; // shininess self.r.double()?; // ambient alpha let alpha = self.r.double()?; self.r.double()?; // emissive alpha self.r.double()?; // specular alpha - Material::Plain { diffuse, alpha } + Material::Plain { diffuse, emissive, alpha } } TEXTURE_APPLICATION => { let base = self.r.unsigned_integer()?; diff --git a/crates/prc/src/tree/tests.rs b/crates/prc/src/tree/tests.rs index fe9c72aa5..bf5a38faf 100644 --- a/crates/prc/src/tree/tests.rs +++ b/crates/prc/src/tree/tests.rs @@ -647,7 +647,7 @@ fn a_colour_index_counts_doubles() { fn style_alpha_rules_combine_transparency_with_material_alpha() { let g = |alpha, transparency| Globals { colours: vec![BLUE], - materials: vec![Material::Plain { diffuse: 1, alpha }], + materials: vec![Material::Plain { diffuse: 1, emissive: 0, alpha }], styles: vec![Style { is_material: true, index: 1, transparency }], ..Globals::default() }; diff --git a/crates/prc/src/write/bits.rs b/crates/prc/src/write/bits.rs new file mode 100644 index 000000000..565f723a5 --- /dev/null +++ b/crates/prc/src/write/bits.rs @@ -0,0 +1,164 @@ +//! The bit-level writer for PRC compressed sections: the inverse of +//! [`crate::bits::BitReader`] for the types the writer emits [WD 10.3, +//! 11.1-11.17]. + +use crate::acof; + +/// An MSB-first bit sink. +/// +/// Every value the writer can be handed is encodable except a non-finite +/// `Double`; one of those is recorded and reported by [`Self::finish`] +/// rather than written. +#[derive(Debug, Default, Clone)] +pub(crate) struct BitWriter { + bytes: Vec, + len: usize, + non_finite: bool, +} + +impl BitWriter { + /// The low `n` bits of `v` (`n` ≤ 64), most significant first. + pub(crate) fn put(&mut self, v: u64, n: u32) -> &mut Self { + for i in (0..n).rev() { + self.bit((v >> i) & 1 == 1); + } + self + } + + /// One bit; a PRC `Boolean`. + pub(crate) fn bit(&mut self, b: bool) -> &mut Self { + if self.len.is_multiple_of(8) { + self.bytes.push(0); + } + if b && let Some(last) = self.bytes.last_mut() { + *last |= 0x80 >> (self.len % 8); + } + self.len += 1; + self + } + + /// Every bit of `other`, unaligned. + #[cfg(test)] + pub(crate) fn append(&mut self, other: &Self) -> &mut Self { + for i in 0..other.len { + let byte = other.bytes.get(i / 8).copied().unwrap_or(0); + self.bit((byte >> (7 - i % 8)) & 1 == 1); + } + self.non_finite |= other.non_finite; + self + } + + /// An `UnsignedInteger` [WD 11.2]: per byte, a continuation bit then + /// eight bits, low byte first; a final zero bit. + pub(crate) fn uint(&mut self, mut v: u32) -> &mut Self { + while v != 0 { + self.bit(true).put(u64::from(v & 0xff), 8); + v >>= 8; + } + self.bit(false) + } + + /// An `Integer` [WD 11.3]: two's-complement bytes, low first, each + /// followed by a continue bit. + pub(crate) fn int(&mut self, v: i32) -> &mut Self { + if v == 0 { + return self.bit(false); + } + self.bit(true); + let mut v = i64::from(v); + loop { + let byte = (v & 0xff) as u8; + self.put(u64::from(byte), 8); + v >>= 8; + let done = (v == 0 && byte & 0x80 == 0) || (v == -1 && byte & 0x80 != 0); + self.bit(!done); + if done { + return self; + } + } + } + + /// A `String` [WD 11.4]: presence bit, byte count, raw UTF-8 bytes. + pub(crate) fn string(&mut self, s: Option<&str>) -> &mut Self { + let Some(s) = s else { + return self.bit(false); + }; + self.bit(true).uint(u32::try_from(s.len()).unwrap_or(u32::MAX)); + for b in s.bytes() { + self.put(u64::from(b), 8); + } + self + } + + /// A `Double` [WD 11.17]: ±0 as the two-bit zero code; any other finite + /// value as its exponent row, the sign, then the mantissa as literal + /// bytes, never as a back-reference to a previous double (the + /// simplest form a reader can take; the writer never needs the others). + pub(crate) fn double(&mut self, v: f64) -> &mut Self { + if v == 0.0 { + return self.put(0b01, 2); + } + let bits = v.to_bits(); + let Some((n, c)) = v.is_finite().then(|| acof::exponent_code(((bits >> 52) & 0x7ff) as u32)).flatten() else { + self.non_finite = true; + return self.put(0b01, 2); + }; + let le = bits.to_le_bytes(); + self.put(u64::from(c), n).bit(v < 0.0).bit(true).put(u64::from(le[6] & 0x0f), 4); + for &b in le[..6].iter().rev() { + self.bit(true).put(u64::from(b), 8); + } + self + } + + /// `n` doubles. + pub(crate) fn doubles(&mut self, vs: impl IntoIterator) -> &mut Self { + for v in vs { + self.double(v); + } + self + } + + /// The packed bytes, or `None` when a non-finite double was written. + pub(crate) fn finish(self) -> Option> { + (!self.non_finite).then_some(self.bytes) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + use crate::bits::BitReader; + + #[test] + fn every_type_reads_back() { + let values = [1.0, -0.5, 1e-300, 123_456.789, -6.02e23, 0.0, 2000.0]; + let mut w = BitWriter::default(); + w.uint(0).uint(300).int(-129).int(4).string(Some("glass")); + w.string(None).doubles(values); + let bytes = w.finish().unwrap(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.unsigned_integer().unwrap(), 0); + assert_eq!(r.unsigned_integer().unwrap(), 300); + assert_eq!(r.integer().unwrap(), -129); + assert_eq!(r.integer().unwrap(), 4); + assert_eq!(r.string().unwrap().as_deref(), Some("glass")); + assert_eq!(r.string().unwrap(), None); + for v in values { + assert_eq!(r.double().unwrap(), v); + } + } + + #[test] + fn a_non_finite_double_fails_the_section() { + let mut w = BitWriter::default(); + w.double(f64::NAN); + assert!(w.finish().is_none()); + let mut inner = BitWriter::default(); + inner.double(f64::INFINITY); + let mut w = BitWriter::default(); + w.append(&inner); + assert!(w.finish().is_none()); + } +} diff --git a/crates/prc/src/write/bounds.rs b/crates/prc/src/write/bounds.rs new file mode 100644 index 000000000..b03c33b7a --- /dev/null +++ b/crates/prc/src/write/bounds.rs @@ -0,0 +1,45 @@ +//! The box a scene's triangles fill, for fitting a camera to it. + +use super::MeshScene; +use crate::Matrix; + +impl MeshScene { + /// The smallest axis-aligned box `[min, max]` holding every vertex of every triangle the + /// scene draws, placed by its nodes' matrices, in scene units. `None` when it draws no + /// triangle or a placed coordinate is not finite. Each node is visited once, so a scene that + /// is not a forest (which [`write_prc`](super::write_prc) refuses) still ends. + #[must_use] + pub fn bounds(&self) -> Option<[[f64; 3]; 2]> { + let mut seen = vec![false; self.nodes.len()]; + let mut stack: Vec<(usize, Matrix)> = self.roots.iter().map(|&r| (r, Matrix::IDENTITY)).collect(); + let mut out: Option<[[f64; 3]; 2]> = None; + while let Some((index, parent)) = stack.pop() { + let (Some(node), Some(visited)) = (self.nodes.get(index), seen.get_mut(index)) else { continue }; + if std::mem::replace(visited, true) { + continue; + } + let world = node.matrix.map_or(parent, |m| parent.multiply(&column_major(&m))); + for p in node.mesh.and_then(|m| self.meshes.get(m)).into_iter().flat_map(|m| &m.primitives) { + for i in p.triangles.iter().flatten() { + let Some(v) = usize::try_from(*i).ok().and_then(|i| p.positions.get(i)) else { continue }; + let q = world.transform_point(*v); + if !q.iter().all(|c| c.is_finite()) { + return None; + } + let [lo, hi] = out.get_or_insert([q, q]); + for ((l, h), c) in lo.iter_mut().zip(hi.iter_mut()).zip(q) { + *l = l.min(c); + *h = h.max(c); + } + } + } + stack.extend(node.children.iter().map(|&c| (c, world))); + } + out + } +} + +/// A column-major 4×4 matrix (glTF's order) as a [`Matrix`]. +fn column_major(m: &[f64; 16]) -> Matrix { + Matrix(std::array::from_fn(|row| std::array::from_fn(|col| m.get(col * 4 + row).copied().unwrap_or(0.0)))) +} diff --git a/crates/prc/src/write/container.rs b/crates/prc/src/write/container.rs new file mode 100644 index 000000000..e98f5007e --- /dev/null +++ b/crates/prc/src/write/container.rs @@ -0,0 +1,80 @@ +//! The PRC container writer: the file header, file-structure descriptions, +//! each structure's header and its five zlib sections, then the model file +//! [WD 6.1-6.2, 10.2]. The inverse of [`crate::PrcFile::parse`]. + +use std::io::Write as _; + +use crate::{PRC_READER_VERSION, UniqueId}; + +/// One file structure: its id, its five inflated sections in +/// [`crate::SectionKind`] order, and the uncompressed files its header +/// carries (texture pictures, WD 6.2.2). +pub(crate) struct Structure<'a> { + pub(crate) id: UniqueId, + pub(crate) sections: [&'a [u8]; 5], + pub(crate) files: Vec<&'a [u8]>, +} + +/// The ids a container carries besides its structures'. +pub(crate) struct Ids { + pub(crate) file: UniqueId, + pub(crate) application: UniqueId, +} + +fn zlib(data: &[u8]) -> Vec { + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + // Writing into a Vec cannot fail. + drop(e.write_all(data)); + e.finish().unwrap_or_default() +} + +fn le(out: &mut Vec, vs: &[u32]) { + vs.iter().for_each(|v| out.extend_from_slice(&v.to_le_bytes())); +} + +/// Offsets past `u32::MAX` are unrepresentable; `None` then. +fn offset(at: usize) -> Option { + u32::try_from(at).ok() +} + +/// The PRC stream: version 8137 for reading and authoring (the version +/// this crate's reader is tested against), no file-header uncompressed files. `None` past 4 GiB. +pub(crate) fn container(structures: &[Structure<'_>], model: &[u8], ids: &Ids) -> Option> { + let v = PRC_READER_VERSION; + // "PRC", 2 versions, 2 ids, count; 48 bytes per description; model + // extent; uncompressed-file count. + let header_len = 3 + 4 * 11 + 48 * structures.len() + 8 + 4; + let mut body = Vec::new(); + let mut descriptions = Vec::new(); + for s in structures { + let start = offset(header_len + body.len())?; + body.extend_from_slice(b"PRC"); + le(&mut body, &[v, v]); + le(&mut body, &s.id.0); + le(&mut body, &ids.application.0); + le(&mut body, &[u32::try_from(s.files.len()).ok()?]); + for f in &s.files { + le(&mut body, &[u32::try_from(f.len()).ok()?]); + body.extend_from_slice(f); + } + le(&mut descriptions, &s.id.0); + le(&mut descriptions, &[0, 6, start]); + for section in s.sections { + le(&mut descriptions, &[offset(header_len + body.len())?]); + body.extend(zlib(section)); + } + } + let mf_start = offset(header_len + body.len())?; + body.extend(zlib(model)); + let mf_end = offset(header_len + body.len())?; + + let mut out = b"PRC".to_vec(); + le(&mut out, &[v, v]); + le(&mut out, &ids.file.0); + le(&mut out, &ids.application.0); + le(&mut out, &[u32::try_from(structures.len()).ok()?]); + out.extend(descriptions); + le(&mut out, &[mf_start, mf_end, 0]); + out.extend(body); + Some(out) +} diff --git a/crates/prc/src/write/mod.rs b/crates/prc/src/write/mod.rs new file mode 100644 index 000000000..150fa66de --- /dev/null +++ b/crates/prc/src/write/mod.rs @@ -0,0 +1,287 @@ +//! Writing a triangle-mesh scene as a PRC stream (Adobe PRC 8137, the +//! format 3D PDF embeds as `/Subtype /PRC`). +//! +//! The scene is a node hierarchy over shared meshes, the shape glTF and +//! most mesh formats carry. Each node becomes a `ProductOccurrence` named +//! for it (the names a viewer's model tree lists), each referenced mesh a +//! `PartDefinition`, each primitive a poly-B-rep item over one `TESS_3D` +//! styled by its material's RGB colour and transparency, or by a base-colour +//! texture over stored (u, v) coordinates. + +mod bits; +mod bounds; +mod container; +mod sections; +mod tess; +mod textures; +mod validate; +mod vec3; + +#[cfg(test)] +pub(crate) mod readback; +#[cfg(test)] +mod tests; + +use crate::UniqueId; + +pub(crate) use bits::BitWriter; + +/// How a texture repeats outside the 0–1 coordinate range. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum TextureWrap { + /// Tiled. + #[default] + Repeat, + /// The edge texels extended. + Clamp, + /// Tiled, every other tile mirrored. + MirroredRepeat, +} + +/// A triangle-mesh scene to write as PRC. +/// +/// `nodes` form a forest: every index in [`SceneNode::children`] and +/// [`Self::roots`] names a node, no node has two parents, and a root has +/// none. Nodes no root reaches are not written. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MeshScene { + /// Every node. + pub nodes: Vec, + /// The top-level nodes. More than one is written under an unnamed + /// root occurrence. + pub roots: Vec, + /// Meshes, shared by any number of nodes. + pub meshes: Vec, + /// Materials, named by [`ScenePrimitive::material`]. + pub materials: Vec, + /// Textures, named by [`SceneMaterial::texture`]. + pub textures: Vec, + /// Millimetres per scene unit: 1000 for metres (glTF), 1 for + /// millimetres. Positive and finite. + pub units_in_mm: f64, +} + +/// One node: a placement, an optional mesh, children. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct SceneNode { + /// The name a model tree shows; `None` writes a null name. + pub name: Option, + /// Placement relative to the parent, a column-major 4×4 matrix (glTF's + /// order); `None` for identity. The bottom row must be `0 0 0 1`. + pub matrix: Option<[f64; 16]>, + /// Index into [`MeshScene::meshes`]. + pub mesh: Option, + /// Indices into [`MeshScene::nodes`]. + pub children: Vec, +} + +/// A mesh: one or more primitives, each with its own material. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct SceneMesh { + /// The part name. + pub name: Option, + /// Its primitives; one with no triangles is not written. + pub primitives: Vec, +} + +/// One indexed triangle list. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ScenePrimitive { + /// Vertex positions, in scene units. + pub positions: Vec<[f64; 3]>, + /// Per-vertex normals, the same length as `positions`; empty to have + /// the writer compute one flat normal per triangle (reported in + /// [`PrcWriteReport::flat_normals`]). + pub normals: Vec<[f64; 3]>, + /// Counter-clockwise triangles, indexing `positions`. + pub triangles: Vec<[u32; 3]>, + /// Index into [`MeshScene::materials`]; `None` leaves the colour to + /// the viewer. + pub material: Option, + /// Texture coordinates per vertex, the same length as `positions`, or + /// empty. (0, 0) is the picture's bottom-left corner and (1, 1) its + /// top-right. Written only when the material is textured; a textured + /// material over a primitive with none draws its base colour. + pub uvs: Vec<[f64; 2]>, +} + +/// A material as PRC can display it: one colour, its opacity and the +/// light it gives off. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct SceneMaterial { + /// The material's name (carried in the scene only; PRC styles are + /// unnamed). + pub name: Option, + /// Display (sRGB-encoded) red, green, blue and opacity, each 0–1; + /// opacity 1 is opaque. Values outside 0–1 are clamped. + pub rgba: [f64; 4], + /// Index into [`MeshScene::textures`]: a picture multiplying `rgba` + /// over the primitive's [`ScenePrimitive::uvs`]. + pub texture: Option, + /// Display (sRGB-encoded) light the surface gives off, each 0–1 + /// (clamped); black for none. A non-black one is written as the + /// material's emissive colour [WD 7.5.4], so its primitives are drawn + /// through a material style; a textured material's primitive without + /// coordinates is drawn in its RGB style and does not glow. + pub emissive: [f64; 3], +} + +/// A base-colour picture. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SceneTexture { + /// A complete PNG or JPEG file, stored in the PRC as it is. + pub image: Vec, + /// Wrapping along u, then v. + pub wrap: [TextureWrap; 2], + /// Whether the picture's alpha multiplies the material's opacity; + /// otherwise only its colour is used. + pub alpha: bool, +} + +/// A written PRC stream and what the writer had to supply itself. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PrcWriteReport { + /// The PRC stream, ready for a 3D PDF's `/Subtype /PRC` stream. + pub prc: Vec, + /// Triangles written. + pub triangles: usize, + /// Primitives that had no normals, given flat per-triangle ones. + pub flat_normals: usize, + /// Primitives left out for holding no triangles. + pub empty_primitives: usize, + /// Primitives written with a texture and coordinates. + pub textured: usize, +} + +/// Why a scene could not be written. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum PrcWriteError { + /// The scene draws nothing: no root reaches a triangle. + #[error("the scene holds no triangles")] + Empty, + /// An index names nothing: `what` with the offending `index`. + #[error("{what} index {index} is out of range")] + BadIndex { + /// What the index was for. + what: &'static str, + /// The value found. + index: usize, + }, + /// The nodes are not a forest (a node with two parents, a parented + /// root, or a nesting deeper than [`MAX_NODE_DEPTH`]). + #[error("the node hierarchy is not a tree: {0}")] + NotATree(&'static str), + /// A coordinate, normal, matrix entry, colour (emissive too) or the unit is NaN or + /// infinite, or the unit is not positive. + #[error("the scene holds a non-finite or invalid number ({0})")] + BadNumber(&'static str), + /// The scene's counts or the stream exceed what PRC can address + /// (32-bit counts and offsets). + #[error("the scene is too large for a PRC stream")] + TooLarge, + /// Texture `index` is not a PNG or JPEG file whose size can be read. + #[error("texture {index} is not a readable PNG or JPEG file")] + BadTexture { + /// Index into [`MeshScene::textures`]. + index: usize, + }, +} + +/// The deepest node nesting the writer accepts, counting a root as 1: this +/// crate's reader walks 64 levels below the root occurrence, and the writer +/// may add a root of its own. +pub const MAX_NODE_DEPTH: usize = 64; + +/// Write `scene` as a single-file-structure PRC stream. +/// +/// # Errors +/// +/// [`PrcWriteError`] when the scene is not a valid forest over valid +/// indices, holds a non-finite number or an unreadable texture, or draws +/// no triangle. +/// +/// # Example +/// +/// ``` +/// use craft_prc::{MeshScene, SceneMesh, SceneNode, ScenePrimitive, write_prc}; +/// +/// let tri = ScenePrimitive { +/// positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], +/// triangles: vec![[0, 1, 2]], +/// ..ScenePrimitive::default() +/// }; +/// let scene = MeshScene { +/// nodes: vec![SceneNode { name: Some("tri".into()), mesh: Some(0), ..SceneNode::default() }], +/// roots: vec![0], +/// meshes: vec![SceneMesh { name: None, primitives: vec![tri] }], +/// materials: vec![], +/// textures: vec![], +/// units_in_mm: 1000.0, +/// }; +/// let report = write_prc(&scene)?; +/// assert_eq!(report.triangles, 1); +/// assert_eq!(report.flat_normals, 1); +/// let prc = craft_prc::PrcFile::parse(&report.prc).unwrap(); +/// assert_eq!(prc.placements().unwrap().len(), 1); +/// # Ok::<(), craft_prc::PrcWriteError>(()) +/// ``` +pub fn write_prc(scene: &MeshScene) -> Result { + let plan = validate::plan(scene)?; + let ids = ids(scene); + let tess = tess::section(scene, &plan)?; + let globals = sections::globals(scene, &plan).finish(); + let tree = sections::tree(scene, &plan).finish(); + let geometry = sections::empty_geometry(306).finish(); + let extra = sections::empty_geometry(307).finish(); + let model = sections::model_file(scene, &plan, ids.structure).finish(); + let (Some(globals), Some(tree), Some(geometry), Some(extra), Some(model)) = (globals, tree, geometry, extra, model) else { + return Err(PrcWriteError::BadNumber("matrix, colour or unit")); + }; + let structure = container::Structure { + id: ids.structure, + sections: [&globals, &tree, &tess.bytes, &geometry, &extra], + files: scene.textures.iter().map(|t| t.image.as_slice()).collect(), + }; + let prc = container::container(&[structure], &model, &ids.container).ok_or(PrcWriteError::TooLarge)?; + Ok(PrcWriteReport { + prc, + triangles: tess.triangles, + flat_normals: tess.flat_normals, + empty_primitives: plan.empty_primitives, + textured: tess.textured, + }) +} + +struct AllIds { + structure: UniqueId, + container: container::Ids, +} + +/// FNV-1a over the scene's debug form: the same scene always gets the same +/// ids, so writing is deterministic, and different scenes differ. +fn ids(scene: &MeshScene) -> AllIds { + struct Fnv(u64); + impl std::fmt::Write for Fnv { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for b in s.bytes() { + self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); + } + Ok(()) + } + } + let mut fnv = Fnv(0xcbf2_9ce4_8422_2325); + // Formatting into a hasher cannot fail. + std::fmt::Write::write_fmt(&mut fnv, format_args!("{scene:?}")).ok(); + let h = fnv.0; + let (hi, lo) = ((h >> 32) as u32, h as u32); + AllIds { + structure: UniqueId([hi, lo, 0x6372_6166, 1]), + container: container::Ids { + file: UniqueId([hi, lo, 0x6372_6166, 0]), + // "craf" "tlib": who wrote the stream. + application: UniqueId([0x6661_7263, 0x6269_6c74, 0, 1]), + }, + } +} diff --git a/crates/prc/src/write/readback.rs b/crates/prc/src/write/readback.rs new file mode 100644 index 000000000..f61e5a840 --- /dev/null +++ b/crates/prc/src/write/readback.rs @@ -0,0 +1,32 @@ +//! Test-only: a written stream read back through this crate's reader. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use crate::{PrcFile, Tessellation, TriangleMesh}; + +/// What a PRC stream draws, every placement in world coordinates. +#[derive(Debug, Default)] +pub(crate) struct Model { + /// Triangles over every placement. + pub(crate) triangles: usize, + /// Each placement's colour as straight 8-bit RGBA. + pub(crate) colours: Vec>, + /// Each placement's mesh, placed. + pub(crate) meshes: Vec, +} + +/// `prc` parsed and its placements resolved to placed meshes. +pub(crate) fn assemble(prc: &[u8]) -> Model { + let file = PrcFile::parse(prc).unwrap(); + let tessellations: Vec> = file.file_structures.iter().map(|fs| fs.tessellations().unwrap()).collect(); + let mut out = Model::default(); + for p in file.placements().unwrap() { + let Some(Tessellation::Mesh(mesh)) = tessellations.get(p.file_structure).and_then(|t| t.get(p.tessellation)) else { + panic!("placement {p:?} names no mesh"); + }; + out.triangles += mesh.triangles.len(); + out.colours.push(p.colour.map(|c| [c.r, c.g, c.b, c.a].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8))); + out.meshes.push(mesh.transformed(&p.matrix)); + } + out +} diff --git a/crates/prc/src/write/sections.rs b/crates/prc/src/write/sections.rs new file mode 100644 index 000000000..4bc8912d4 --- /dev/null +++ b/crates/prc/src/write/sections.rs @@ -0,0 +1,300 @@ +//! The globals (303), tree (304 + 302), empty geometry (306, 307) and +//! model-file (301) entities [WD 7.3.3-7.3.11, 7.4.9-7.4.11, 7.5.3]. + +use super::validate::Plan; +use super::vec3::{cross, dot}; +use super::{BitWriter, MeshScene, SceneMaterial}; +use crate::UniqueId; + +const MODEL_FILE: u32 = 301; +const FILE_STRUCTURE: u32 = 302; +const GLOBALS: u32 = 303; +const TREE: u32 = 304; +const PRODUCT_OCCURRENCE: u32 = 310; +const PART_DEFINITION: u32 = 311; +const CARTESIAN_TRANSFORMATION: u32 = 202; +const GENERAL_TRANSFORMATION: u32 = 207; +const RI_POLY_BREP_MODEL: u32 = 237; +const STYLE: u32 = 701; +const LINE_PATTERN: u32 = 721; + +/// `PRC_GRAPHICS_Show` [WD 7.2.4.2]. +const SHOW: u16 = 0x0001; +/// `EPRCProductLoadStatus` given to every product written. +const LOAD_STATUS: i32 = 4; + +/// `ContentPRCBase` with no attributes and the current (section-start: +/// empty) name [WD 7.2.3]. +pub(super) fn base(w: &mut BitWriter) { + w.uint(0).bit(true); +} + +/// `ContentPRCBase` naming the entity explicitly; `None` is a null name. +fn named(w: &mut BitWriter, name: Option<&str>) { + w.uint(0).bit(false).string(name); +} + +/// `ContentPRCRefBase`: `ContentPRCBase`, CAD ids 0, then `id`. +pub(super) fn ref_base(w: &mut BitWriter, name: Option>, id: u32) { + match name { + None => base(w), + Some(n) => named(w, n), + } + w.uint(0).uint(0).uint(id); +} + +/// `PRCBaseWithGraphics` with explicit graphics: no layer, line style +/// `style` (`None` inheriting), behaviour Show. +fn graphics(w: &mut BitWriter, name: Option<&str>, id: u32, style: Option) { + ref_base(w, Some(name), id); + w.bit(false).uint(0).uint(style.map_or(0, |s| s + 1)).put(u64::from(SHOW & 0xff), 8).put(u64::from(SHOW >> 8), 8); +} + +/// Unique ids for referenceable entities, from 1. +struct Ids(u32); + +impl Ids { + fn next(&mut self) -> u32 { + self.0 += 1; + self.0 + } +} + +/// The globals section: an empty schema, one colour and one RGB style per +/// material, then the emissive colours, the texture entities, one material +/// style per textured and per glowing material, and the solid line pattern +/// every style names. +pub(super) fn globals(scene: &MeshScene, plan: &Plan) -> BitWriter { + let mut w = BitWriter::default(); + w.uint(0).uint(GLOBALS); + base(&mut w); + // No referenced structures; chord and angle tolerances; markup font + // helper empty. + w.uint(0).double(2000.0).double(40.0).string(Some("")).uint(0); + let emissive = super::textures::emissive_colours(scene); + let emissive_first = scene.materials.len() as u32; + w.uint(emissive_first + emissive.len() as u32); + for m in &scene.materials { + w.doubles(m.rgba[..3].iter().map(|c| c.clamp(0.0, 1.0))); + } + for c in emissive { + w.doubles(c); + } + let styles = plan.styles(scene) as u32; + super::textures::pictures(&mut w, &plan.pictures); + super::textures::definitions(&mut w, scene, 2 + styles); + let first = 2 + styles + scene.textures.len() as u32; + super::textures::materials(&mut w, (scene, plan), emissive_first, first); + w.uint(1).uint(LINE_PATTERN); + ref_base(&mut w, None, 1); + w.uint(2).double(1.0e6).double(0.0).double(0.0).bit(false); + w.uint(styles); + for (k, m) in scene.materials.iter().enumerate() { + w.uint(STYLE); + ref_base(&mut w, None, 2 + k as u32); + // Width 1, no vpicture, line pattern 1 (biased), an RGB colour + // (double-scaled biased index, WD 7.5.3). + w.double(1.0).bit(false).uint(1).bit(false); + w.uint(3 * k as u32 + 1); + transparency(&mut w, m); + w.bit(false).bit(false).bit(false); + } + for j in 0..plan.textured.len() as u32 { + w.uint(STYLE); + ref_base(&mut w, None, 2 + scene.materials.len() as u32 + j); + // As above, but a material: the TextureApplication entry (biased). + // The material carries the alpha too, but a reader may take a + // material alpha of 0 under a style without one as unset. + w.double(1.0).bit(false).uint(1).bit(true); + w.uint(2 * j + 2); + match plan.textured.get(j as usize).and_then(|&m| scene.materials.get(m)) { + Some(m) => transparency(&mut w, m), + None => { + w.bit(false); + } + } + w.bit(false).bit(false).bit(false); + } + let pairs = 2 * plan.textured.len() as u32; + let first_glow = 2 + (scene.materials.len() + plan.textured.len()) as u32; + for g in 0..plan.glowing.len() as u32 { + w.uint(STYLE); + ref_base(&mut w, None, first_glow + g); + // A material style naming the glowing material's `Material` + // (biased entry), which carries its own alpha. + w.double(1.0).bit(false).uint(1).bit(true); + w.uint(pairs + g + 1); + w.bit(false).bit(false).bit(false).bit(false); + } + // Fill patterns, reference coordinate systems, user data. + w.uint(0).uint(0).uint(0); + w +} + +/// An empty exact-geometry (306) or extra-geometry (307) section: no +/// topological contexts [WD 7.3.8, 7.3.9]. Viewers reject a zero-byte one. +pub(super) fn empty_geometry(kind: u32) -> BitWriter { + let mut w = BitWriter::default(); + w.uint(kind); + base(&mut w); + w.uint(0).uint(0); + w +} + +/// The tree section: parts, occurrences, then the file structure's +/// internal data. +pub(super) fn tree(scene: &MeshScene, plan: &Plan) -> BitWriter { + let mut ids = Ids(plan.global_ids(scene)); + let mut w = BitWriter::default(); + w.uint(TREE); + base(&mut w); + w.uint(plan.parts.len() as u32); + let mut tess = 0u32; + for &m in &plan.parts { + part(&mut w, scene, plan, m, &mut tess, &mut ids); + } + w.uint(plan.occurrences.len() as u32); + for o in &plan.occurrences { + occurrence(&mut w, scene, plan, o, &mut ids); + } + w.uint(FILE_STRUCTURE); + base(&mut w); + // The root occurrence is the last (biased index = count). + let next = ids.next(); + w.uint(next).uint(plan.occurrences.len() as u32).uint(0); + w +} + +/// Mesh `m`'s part: its bounding box and one poly-B-rep item per +/// tessellated primitive, numbered on from `tess`. +fn part(w: &mut BitWriter, scene: &MeshScene, plan: &Plan, m: usize, tess: &mut u32, ids: &mut Ids) { + let mesh = scene.meshes.get(m); + w.uint(PART_DEFINITION); + graphics(w, mesh.and_then(|m| m.name.as_deref()), ids.next(), None); + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + // A part's tessellations follow the previous parts', in part order. + let ours = plan.tessellations.get(*tess as usize..).unwrap_or(&[]).iter().take_while(|t| t.0 == m); + let prims: Vec<_> = ours.filter_map(|&(_, p)| mesh?.primitives.get(p)).collect(); + for v in prims.iter().flat_map(|p| &p.positions) { + for ((l, h), c) in lo.iter_mut().zip(hi.iter_mut()).zip(v) { + *l = l.min(*c); + *h = h.max(*c); + } + } + if prims.is_empty() { + (lo, hi) = ([1.0, 0.0, 0.0], [-1.0, 0.0, 0.0]); + } + w.doubles(lo).doubles(hi); + w.uint(prims.len() as u32); + for p in prims { + w.uint(RI_POLY_BREP_MODEL); + graphics(w, None, ids.next(), plan.style_of(scene, p)); + *tess += 1; + // No local coordinate system; tessellation (biased); not closed; + // no user data. + w.uint(0).uint(*tess).bit(false).uint(0); + } + // Markups (4 lists), views, user data. + w.uint(0).uint(0).uint(0).uint(0).uint(0).uint(0); +} + +fn occurrence(w: &mut BitWriter, scene: &MeshScene, plan: &Plan, o: &super::validate::Occ, ids: &mut Ids) { + let node = o.node.and_then(|n| scene.nodes.get(n)); + w.uint(PRODUCT_OCCURRENCE); + graphics(w, node.and_then(|n| n.name.as_deref()), ids.next(), None); + let part = node.and_then(|n| n.mesh).and_then(|m| *plan.part_of_mesh.get(m)?).map_or(0, |p| p + 1); + // Part (biased), no prototype, no external data, sons (raw). + w.uint(part).uint(0).uint(0).uint(o.sons.len() as u32); + for &s in &o.sons { + w.uint(s); + } + // Not suppressed; ProductInformation: units from the scene, no flags. + w.put(0, 8).bit(true).double(scene.units_in_mm).put(0, 8).int(LOAD_STATUS); + let matrix = node.and_then(|n| n.matrix).filter(|m| *m != IDENTITY); + w.bit(matrix.is_some()); + if let Some(m) = matrix { + transformation(w, &m); + } + // No entity references, markups (4 lists), views, no entity filter, + // display filters, scene display parameters, user data. + w.uint(0).uint(0).uint(0).uint(0).uint(0).uint(0); + w.bit(false).uint(0).uint(0).uint(0); +} + +const IDENTITY: [f64; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]; + +/// A rotation (possibly mirrored) times a uniform scale as a +/// `CartesianTransformation` [WD 7.4.11]; anything else (shear, non-uniform +/// scale) as a column-major `GeneralTransformation` [WD 7.4.9]. +fn transformation(w: &mut BitWriter, m: &[f64; 16]) { + let mut cols = [[0.0; 3]; 4]; + for (dst, src) in cols.iter_mut().zip(m.as_chunks::<4>().0) { + for (d, s) in dst.iter_mut().zip(src) { + *d = *s; + } + } + let [x, y, z, t] = cols; + let det = dot(x, cross(y, z)); + let s = det.abs().cbrt(); + let unit = |v: [f64; 3]| v.map(|c| c / s); + let (rx, ry, rz) = (unit(x), unit(y), unit(z)); + let orthonormal = s > 1e-12 + && [(rx, rx, 1.0), (ry, ry, 1.0), (rz, rz, 1.0), (rx, ry, 0.0), (rx, rz, 0.0), (ry, rz, 0.0)] + .iter() + .all(|&(a, b, e)| (dot(a, b) - e).abs() < 1e-9); + if !orthonormal { + w.uint(GENERAL_TRANSFORMATION).doubles(m.iter().copied()); + return; + } + let rotated = det < 0.0 || rx != [1.0, 0.0, 0.0] || ry != [0.0, 1.0, 0.0]; + let scaled = (s - 1.0).abs() > 1e-12; + let mut b = 0u8; + if t != [0.0; 3] { + b |= 0x01; + } + if rotated { + b |= 0x02; + } + if det < 0.0 { + b |= 0x04; + } + if scaled { + b |= 0x08; + } + w.uint(CARTESIAN_TRANSFORMATION).put(u64::from(b), 8); + if b & 0x01 != 0 { + w.doubles(t); + } + if rotated { + w.doubles(rx).doubles(ry); + } + if scaled { + w.double(s); + } +} + +/// The model file: an empty schema, the units, the one root. +pub(super) fn model_file(scene: &MeshScene, plan: &Plan, structure: UniqueId) -> BitWriter { + let mut w = BitWriter::default(); + w.uint(0).uint(MODEL_FILE); + base(&mut w); + w.bit(true).double(scene.units_in_mm).uint(1); + for c in structure.0 { + w.uint(c); + } + // Root occurrence, the last (biased), active; file structure 0's index + // in the model file; no user data. + w.uint(plan.occurrences.len() as u32).bit(true).uint(0).uint(0); + w +} + +/// A style's transparency: a flag, and when the material is not opaque its +/// alpha as a byte. +fn transparency(w: &mut BitWriter, m: &SceneMaterial) { + let alpha = m.rgba[3].clamp(0.0, 1.0); + w.bit(alpha < 1.0); + if alpha < 1.0 { + w.put((alpha * 255.0).round() as u64, 8); + } +} diff --git a/crates/prc/src/write/tess.rs b/crates/prc/src/write/tess.rs new file mode 100644 index 000000000..e9c2f5cb7 --- /dev/null +++ b/crates/prc/src/write/tess.rs @@ -0,0 +1,118 @@ +//! The tessellation section (305): one `TESS_3D` (172) per primitive, each +//! a single `TESS_Face` (174) of plain triangles [WD 7.3.7, 7.8.5, 7.8.9]. + +use super::validate::Plan; +use super::vec3; +use super::{BitWriter, MeshScene, PrcWriteError, ScenePrimitive}; + +const TESSELLATION: u32 = 305; +const TESS_3D: u32 = 172; +const TESS_FACE: u32 = 174; +/// `PRC_FACETESSDATA_Triangle` [WD 7.8.9.2]. +const TRIANGLE: u32 = 0x2; +/// `PRC_FACETESSDATA_TriangleTextured`: each corner's normal, texture and +/// point indices [WD 7.8.9.2]. +const TRIANGLE_TEXTURED: u32 = 0x0200; + +/// The written section and its counts. +pub(super) struct Section { + pub(super) bytes: Vec, + pub(super) triangles: usize, + pub(super) flat_normals: usize, + pub(super) textured: usize, +} + +/// Every planned primitive's mesh, in plan order. +pub(super) fn section(scene: &MeshScene, plan: &Plan) -> Result { + let mut w = BitWriter::default(); + w.uint(TESSELLATION).uint(0).bit(true); + w.uint(plan.tessellations.len() as u32); + let (mut triangles, mut flat_normals, mut textured) = (0, 0, 0); + for &(m, p) in &plan.tessellations { + let Some(prim) = scene.meshes.get(m).and_then(|m| m.primitives.get(p)) else { + continue; + }; + triangles += prim.triangles.len(); + flat_normals += usize::from(prim.normals.is_empty()); + let uvs = plan.is_textured(scene, prim); + textured += usize::from(uvs); + tess_3d(&mut w, prim, uvs); + } + w.uint(0); + let bytes = w.finish().ok_or(PrcWriteError::BadNumber("position or normal"))?; + Ok(Section { bytes, triangles, flat_normals, textured }) +} + +/// The unit normal of triangle `t`, or +z for a degenerate one. +fn face_normal(p: &ScenePrimitive, t: [u32; 3]) -> [f64; 3] { + let at = |i: u32| p.positions.get(i as usize).copied().unwrap_or([0.0; 3]); + let (a, b, c) = (at(t[0]), at(t[1]), at(t[2])); + // Scaled by a power of two (exactly) to at most 1 first, so finite corners far apart give + // no infinite edge or product. + let big = a.iter().chain(&b).chain(&c).fold(0.0f64, |m, x| m.max(x.abs())); + let scale = if big > 1.0 { 2.0f64.powi(-(big.log2().ceil() as i32)) } else { 1.0 }; + let (a, b, c) = (a.map(|x| x * scale), b.map(|x| x * scale), c.map(|x| x * scale)); + let n = vec3::cross(vec3::sub(b, a), vec3::sub(c, a)); + vec3::normalize(n).unwrap_or([0.0, 0.0, 1.0]) +} + +/// `p` as a `TESS_3D`; with `uvs`, its texture coordinates too, a corner's +/// pair at twice its vertex index. +fn tess_3d(w: &mut BitWriter, p: &ScenePrimitive, uvs: bool) { + // Not calculated; the coordinates. + w.uint(TESS_3D).bit(false); + w.uint(3 * p.positions.len() as u32); + w.doubles(p.positions.iter().flatten().copied()); + // Has faces; no loops (8137 >= 7039); normals stored, not to be + // recalculated (8137 >= 7047). + w.bit(true).bit(false).bit(false); + let flat = p.normals.is_empty(); + if flat { + w.uint(3 * p.triangles.len() as u32); + for &t in &p.triangles { + w.doubles(face_normal(p, t)); + } + } else { + w.uint(3 * p.normals.len() as u32); + w.doubles(p.normals.iter().flatten().copied()); + } + // No wire; the (normal, [texture,] point) offsets of every corner. + let per_corner = if uvs { 3 } else { 2 }; + w.uint(0).uint(3 * per_corner * p.triangles.len() as u32); + for (k, t) in p.triangles.iter().enumerate() { + for v in t { + let n = if flat { k as u32 } else { *v }; + w.uint(3 * n); + if uvs { + w.uint(2 * v); + } + w.uint(3 * v); + } + } + // One face: no line attributes or wires, triangles from index 0, one + // texture-coordinate set or none, no vertex colours. + w.uint(1).uint(TESS_FACE).uint(0).uint(0).uint(0); + w.uint(if uvs { TRIANGLE_TEXTURED } else { TRIANGLE }).uint(0).uint(1).uint(p.triangles.len() as u32); + w.uint(u32::from(uvs)).bit(false); + if uvs { + w.uint(2 * p.uvs.len() as u32); + w.doubles(p.uvs.iter().flatten().copied()); + } else { + w.uint(0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_huge_triangle_keeps_its_normal() { + let p = ScenePrimitive { positions: vec![[0.0; 3], [0.0, 1e200, 0.0], [0.0, 0.0, 1e200]], ..ScenePrimitive::default() }; + assert_eq!(face_normal(&p, [0, 1, 2]), [1.0, 0.0, 0.0]); + let p = ScenePrimitive { positions: vec![[-1e308, 0.0, 0.0], [1e308, 0.0, 0.0], [1e308, 1e308, 0.0]], ..ScenePrimitive::default() }; + assert_eq!(face_normal(&p, [0, 1, 2]), [0.0, 0.0, 1.0]); + let p = ScenePrimitive { positions: vec![[0.0; 3], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], ..ScenePrimitive::default() }; + assert_eq!(face_normal(&p, [0, 1, 2]), [1.0, 0.0, 0.0]); + } +} diff --git a/crates/prc/src/write/tests.rs b/crates/prc/src/write/tests.rs new file mode 100644 index 000000000..add63d3fc --- /dev/null +++ b/crates/prc/src/write/tests.rs @@ -0,0 +1,339 @@ +//! write_prc → reader round trips. + +#![allow(clippy::unwrap_used, clippy::indexing_slicing)] + +use super::readback::assemble; +use super::*; +use crate::PrcFile; + +fn tri(material: Option, dx: f64) -> ScenePrimitive { + ScenePrimitive { + positions: vec![[dx, 0.0, 0.0], [dx + 1.0, 0.0, 0.0], [dx, 1.0, 0.0]], + triangles: vec![[0, 1, 2]], + material, + ..ScenePrimitive::default() + } +} + +fn node(name: &str, mesh: Option, children: Vec) -> SceneNode { + SceneNode { name: Some(name.into()), mesh, children, ..SceneNode::default() } +} + +/// A frame over a glass pane and a shared bolt placed twice. +fn scene() -> MeshScene { + let mut bolt2 = node("bolt-2", Some(1), vec![]); + let mut m = [0.0; 16]; + for (i, v) in [1.0, 1.0, 1.0, 1.0].into_iter().enumerate() { + m[i * 5] = v; + } + m[12] = 10.0; + bolt2.matrix = Some(m); + MeshScene { + nodes: vec![node("frame", None, vec![1, 2, 3]), node("glass", Some(0), vec![]), node("bolt-1", Some(1), vec![]), bolt2], + roots: vec![0], + meshes: vec![ + SceneMesh { name: Some("pane".into()), primitives: vec![tri(Some(0), 0.0)] }, + SceneMesh { name: Some("bolt".into()), primitives: vec![tri(Some(1), 5.0), tri(None, 7.0)] }, + ], + materials: vec![ + SceneMaterial { name: Some("glass".into()), rgba: [0.2, 0.4, 0.6, 0.4], texture: None, emissive: [0.0; 3] }, + SceneMaterial { name: Some("steel".into()), rgba: [1.0, 0.0, 0.0, 1.0], texture: None, emissive: [0.0; 3] }, + ], + textures: vec![], + units_in_mm: 1000.0, + } +} + +#[test] +fn triangles_colours_and_alpha_read_back() { + let r = write_prc(&scene()).unwrap(); + assert_eq!((r.triangles, r.flat_normals, r.empty_primitives), (3, 3, 0)); + let m = assemble(&r.prc); + // The glass once, the bolt's two primitives at both placements. + assert_eq!(m.triangles, 5); + let mut colours: Vec<_> = m.colours.iter().flatten().copied().collect(); + colours.sort_unstable(); + assert!(colours.contains(&[51, 102, 153, 102]), "{colours:?}"); + assert_eq!(colours.iter().filter(|c| **c == [255, 0, 0, 255]).count(), 2); +} + +#[test] +fn node_names_reach_the_model_tree() { + let r = write_prc(&scene()).unwrap(); + let tree = PrcFile::parse(&r.prc).unwrap().model_tree().unwrap(); + let names: Vec<_> = tree.iter().map(|n| n.name.as_deref()).collect(); + assert_eq!(names, [Some("frame"), Some("glass"), Some("bolt-1"), Some("bolt-2")]); + assert_eq!(tree[3].parent, Some(0)); +} + +#[test] +fn a_translation_moves_the_second_placement() { + let m = assemble(&write_prc(&scene()).unwrap().prc); + let xs: Vec = m.meshes.iter().flat_map(|t| t.positions.iter().map(|p| p[0])).collect(); + // bolt-1's first primitive starts at x = 5; bolt-2's at 15. + assert!(xs.contains(&5.0) && xs.contains(&15.0), "{xs:?}"); +} + +#[test] +fn a_non_uniform_scale_is_a_general_transformation() { + let mut s = scene(); + let mut m = [0.0; 16]; + (m[0], m[5], m[10], m[15]) = (2.0, 1.0, 1.0, 1.0); + s.nodes[3].matrix = Some(m); + let a = assemble(&write_prc(&s).unwrap().prc); + let xs: Vec = a.meshes.iter().flat_map(|t| t.positions.iter().map(|p| p[0])).collect(); + assert!(xs.contains(&10.0) && xs.contains(&12.0), "{xs:?}"); +} + +#[test] +fn several_roots_get_one_synthetic_root() { + let mut s = scene(); + s.nodes[0].children = vec![1]; + s.roots = vec![0, 2, 3]; + let tree = PrcFile::parse(&write_prc(&s).unwrap().prc).unwrap().model_tree().unwrap(); + assert_eq!(tree.len(), 5); + assert_eq!(tree[0].name, None); + assert!(tree[1..].iter().all(|n| n.parent.is_some())); +} + +#[test] +fn writing_is_deterministic() { + assert_eq!(write_prc(&scene()).unwrap().prc, write_prc(&scene()).unwrap().prc); +} + +#[test] +fn invalid_scenes_are_refused() { + let mut s = scene(); + s.nodes[0].children.push(1); + s.nodes[2].children.push(1); + assert!(matches!(write_prc(&s), Err(PrcWriteError::NotATree(_)))); + let mut s = scene(); + s.roots = vec![1]; + s.nodes[0].children.clear(); + s.meshes[0].primitives[0].triangles[0] = [0, 1, 9]; + assert_eq!(write_prc(&s), Err(PrcWriteError::BadIndex { what: "vertex", index: 9 })); + let mut s = scene(); + s.meshes[0].primitives[0].positions[0][1] = f64::NAN; + assert!(matches!(write_prc(&s), Err(PrcWriteError::BadNumber(_)))); + let mut s = scene(); + s.units_in_mm = 0.0; + assert!(matches!(write_prc(&s), Err(PrcWriteError::BadNumber(_)))); + let mut s = scene(); + s.meshes.iter_mut().flat_map(|m| &mut m.primitives).for_each(|p| p.triangles.clear()); + assert_eq!(write_prc(&s), Err(PrcWriteError::Empty)); + assert_eq!(write_prc(&MeshScene::default()), Err(PrcWriteError::BadNumber("units_in_mm"))); +} + +#[test] +fn a_root_listed_twice_is_refused_not_written_twice() { + let mut s = scene(); + s.roots = vec![0; 100]; + assert_eq!(write_prc(&s), Err(PrcWriteError::NotATree("a root is listed twice"))); +} + +#[test] +fn a_cycle_is_refused_not_looped() { + let mut s = scene(); + s.nodes[1].children.push(0); + assert!(write_prc(&s).is_err()); +} + +#[test] +fn a_mirrored_rotation_reads_back() { + // 90° about z, then mirror z, scale 2, translate y by 3: x' = -2y, + // y' = 2x + 3. + let mut s = scene(); + let mut m = [0.0; 16]; + (m[1], m[4], m[10], m[13], m[15]) = (2.0, -2.0, -2.0, 3.0, 1.0); + s.nodes[3].matrix = Some(m); + let a = assemble(&write_prc(&s).unwrap().prc); + let pts: Vec<[f64; 3]> = a.meshes.iter().flat_map(|t| t.positions.clone()).collect(); + // bolt's first vertex (5,0,0) → (0,13,0); (5,1,0) → (-2,13,0). + let near = |q: [f64; 3]| pts.iter().any(|p| (0..3).all(|i| (p[i] - q[i]).abs() < 1e-9)); + assert!(near([0.0, 13.0, 0.0]) && near([-2.0, 13.0, 0.0]), "{pts:?}"); +} + +/// Every son precedes the occurrence that uses it [WD 7.3.6], so a reader +/// can resolve the tree in one forward pass. +#[test] +fn every_son_precedes_its_father_and_the_root_is_last() { + for roots in [vec![0], vec![0, 2, 3]] { + let mut s = scene(); + if roots.len() > 1 { + s.nodes[0].children = vec![1]; + } + s.roots = roots; + let occ = validate::plan(&s).unwrap().occurrences; + for (i, o) in occ.iter().enumerate() { + assert!(o.sons.iter().all(|&son| (son as usize) < i), "{i}"); + } + let root = occ.len() - 1; + let fathered = |k: usize| occ.iter().any(|o| o.sons.contains(&(k as u32))); + assert!(!fathered(root)); + assert!((0..root).all(fathered), "every other occurrence has a father"); + } +} + +#[test] +fn textures_are_checked_before_writing() { + let mut s = scene(); + s.materials[1].texture = Some(0); + assert_eq!(write_prc(&s), Err(PrcWriteError::BadIndex { what: "texture", index: 0 })); + s.textures = vec![SceneTexture { image: b"GIF89a".to_vec(), ..SceneTexture::default() }]; + assert_eq!(write_prc(&s), Err(PrcWriteError::BadTexture { index: 0 })); + let mut s = scene(); + s.meshes[0].primitives[0].uvs = vec![[0.0, 0.0]]; + assert!(matches!(write_prc(&s), Err(PrcWriteError::BadIndex { .. }))); + // Coordinates under an untextured material are not written. + let mut s = scene(); + s.meshes[0].primitives[0].uvs = vec![[0.0, 0.0]; 3]; + assert_eq!(write_prc(&s).unwrap().textured, 0); +} + +#[test] +fn texture_coordinates_read_back() { + let mut s = scene(); + // A PNG signature and header claiming 1 x 2: enough for the writer. + let image = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR\0\0\0\x01\0\0\0\x02".to_vec(); + s.textures = vec![SceneTexture { image: image.clone(), wrap: [TextureWrap::Clamp, TextureWrap::MirroredRepeat], alpha: false }]; + s.materials[1].texture = Some(0); + s.meshes[1].primitives[0].uvs = vec![[0.5, 0.1], [0.5, 0.1], [0.5, 0.9]]; + let r = write_prc(&s).unwrap(); + assert_eq!(r.textured, 1); + let file = PrcFile::parse(&r.prc).unwrap(); + let pictures: Vec<&Vec> = file.file_structures.iter().flat_map(|fs| &fs.pictures).collect(); + assert_eq!(pictures, [&image], "the picture is stored as it is"); + let m = assemble(&r.prc); + let with_uvs: Vec<_> = m.meshes.iter().filter(|t| !t.uvs.is_empty()).collect(); + assert_eq!(with_uvs.len(), 2, "the bolt's primitive at both placements"); + assert!(with_uvs.iter().all(|t| t.uvs == [[0.5, 0.1], [0.5, 0.1], [0.5, 0.9]])); +} + +/// The box holds every placed triangle, a child placed through its parent's matrix too. +#[test] +fn bounds_follow_each_node_through_its_parents() { + let mut s = scene(); + let mut lift = [0.0; 16]; + (lift[0], lift[5], lift[10], lift[15], lift[14]) = (1.0, 1.0, 1.0, 1.0, 2.0); + s.nodes[0].matrix = Some(lift); + // bolt-2 starts at x 5 + 10 and ends at 8 + 10; everything is raised to z 2 by the frame. + assert_eq!(s.bounds(), Some([[0.0, 0.0, 2.0], [18.0, 1.0, 2.0]])); + s.roots = vec![1]; + assert_eq!(s.bounds(), Some([[0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]), "only what the roots reach"); + s.nodes[1].children = vec![1]; + assert_eq!(s.bounds(), Some([[0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]), "a cycle ends"); + s.roots = vec![99]; + assert_eq!(s.bounds(), None, "nothing drawn"); +} + +/// `prc`'s materials' emissive colours as `[r, g, b]`, the unlit ones dropped. +fn emissives(prc: &[u8]) -> Vec<[f64; 3]> { + let all = PrcFile::parse(prc).unwrap().material_emissives().unwrap(); + all.into_iter().flatten().flatten().map(|c| [c.r, c.g, c.b]).collect() +} + +#[test] +fn an_emissive_colour_reads_back_on_its_material_only() { + let mut s = scene(); + s.materials[0].emissive = [0.0, 0.5, 1.0]; + let prc = write_prc(&s).unwrap().prc; + assert_eq!(emissives(&prc), [[0.0, 0.5, 1.0]]); + // The glass keeps its colour and alpha through the material style. + let colours: Vec<_> = assemble(&prc).colours.into_iter().flatten().collect(); + assert!(colours.contains(&[51, 102, 153, 102]), "{colours:?}"); + assert!(emissives(&write_prc(&scene()).unwrap().prc).is_empty()); + // A wholly transparent material does not glow. + s.materials[0].rgba[3] = 0.0; + assert!(emissives(&write_prc(&s).unwrap().prc).is_empty()); +} + +#[test] +fn a_textured_material_carries_its_glow() { + let mut s = scene(); + let image = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR\0\0\0\x01\0\0\0\x02".to_vec(); + s.textures = vec![SceneTexture { image, wrap: [TextureWrap::Clamp, TextureWrap::Clamp], alpha: false }]; + s.materials[1].texture = Some(0); + s.materials[1].emissive = [1.0, 0.0, 0.0]; + s.meshes[1].primitives[0].uvs = vec![[0.5, 0.1], [0.5, 0.1], [0.5, 0.9]]; + let r = write_prc(&s).unwrap(); + assert_eq!(r.textured, 1); + assert_eq!(emissives(&r.prc), [[1.0, 0.0, 0.0]]); +} + +/// A chain of `n` nodes, the last holding the pane. +fn chain(n: usize) -> MeshScene { + let mut s = scene(); + s.nodes = (0..n).map(|i| node("link", (i + 1 == n).then_some(0), if i + 1 < n { vec![i + 1] } else { vec![] })).collect(); + s +} + +/// The writer accepts no deeper nesting than this crate's reader walks, with +/// one root or with the root the writer adds over several. +#[test] +fn the_deepest_accepted_chain_reads_back() { + for roots in [1, 2] { + let mut s = chain(MAX_NODE_DEPTH); + if roots == 2 { + s.nodes.push(node("bolt", Some(1), vec![])); + s.roots = vec![0, MAX_NODE_DEPTH]; + } + let file = PrcFile::parse(&write_prc(&s).unwrap().prc).unwrap(); + assert!(file.model_tree().is_ok(), "{roots} root(s)"); + assert!(!file.placements().unwrap().is_empty()); + } + assert_eq!(write_prc(&chain(MAX_NODE_DEPTH + 1)), Err(PrcWriteError::NotATree("nested too deeply"))); +} + +#[test] +fn supplied_normals_are_stored_not_replaced() { + let mut s = scene(); + let up = [[0.0, 0.0, 1.0], [0.0, 0.6, 0.8], [0.6, 0.0, 0.8]]; + s.meshes[0].primitives[0].normals = up.to_vec(); + let r = write_prc(&s).unwrap(); + assert_eq!(r.flat_normals, 2, "only the bolt's primitives get flat normals"); + let file = PrcFile::parse(&r.prc).unwrap(); + let meshes: Vec<_> = file.file_structures.iter().flat_map(|fs| fs.tessellations().unwrap()).collect(); + let supplied = |t: &&crate::Tessellation| matches!(t, crate::Tessellation::Mesh(m) if m.normals.len() == 3); + let Some(crate::Tessellation::Mesh(pane)) = meshes.iter().find(supplied) else { panic!("{meshes:?}") }; + assert_eq!(pane.normals, up); + assert_eq!(pane.triangle_normals, [[0, 1, 2]]); + assert!(!pane.normals_recalculated); + let mut s = scene(); + s.meshes[0].primitives[0].normals = vec![[0.0, 0.0, 1.0]]; + assert!(matches!(write_prc(&s), Err(PrcWriteError::BadIndex { .. })), "one normal for three vertices"); +} + +/// A wholly transparent textured material stays transparent: its style says so, not only its +/// material, whose alpha of 0 a reader may take as unset. +#[test] +fn a_transparent_textured_material_reads_back_transparent() { + let mut s = scene(); + let image = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR\0\0\0\x01\0\0\0\x02".to_vec(); + s.textures = vec![SceneTexture { image, wrap: [TextureWrap::Clamp, TextureWrap::Clamp], alpha: false }]; + s.materials[1].texture = Some(0); + s.materials[1].rgba[3] = 0.0; + s.meshes[1].primitives[0].uvs = vec![[0.5, 0.1], [0.5, 0.1], [0.5, 0.9]]; + let prc = write_prc(&s).unwrap().prc; + let colours: Vec<_> = assemble(&prc).colours.into_iter().flatten().collect(); + assert!(colours.iter().filter(|c| c[..3] == [255, 0, 0]).all(|c| c[3] == 0), "{colours:?}"); + assert!(colours.iter().any(|c| c[..3] == [255, 0, 0]), "{colours:?}"); +} + +/// What the roots do not reach is checked too. +#[test] +fn unreached_nodes_and_meshes_are_checked() { + let mut s = scene(); + s.nodes.push(node("stray", Some(999), vec![])); + assert_eq!(write_prc(&s), Err(PrcWriteError::BadIndex { what: "mesh", index: 999 })); + let mut s = scene(); + s.meshes.push(SceneMesh { name: None, primitives: vec![tri(Some(999), 0.0)] }); + assert_eq!(write_prc(&s), Err(PrcWriteError::BadIndex { what: "material", index: 999 })); + let mut s = scene(); + s.nodes.push(node("a", None, vec![5])); + s.nodes.push(node("b", None, vec![4])); + assert_eq!(write_prc(&s), Err(PrcWriteError::NotATree("a cycle"))); + // An unreached tree is fine. + let mut s = scene(); + s.nodes.push(node("spare", Some(0), vec![])); + assert!(write_prc(&s).is_ok()); +} diff --git a/crates/prc/src/write/textures.rs b/crates/prc/src/write/textures.rs new file mode 100644 index 000000000..5e92a2fde --- /dev/null +++ b/crates/prc/src/write/textures.rs @@ -0,0 +1,240 @@ +//! The globals' texture entities: `Picture` (703), `TextureDefinition` (712) +//! and the materials array of `Material` (702) / `TextureApplication` (711) +//! pairs [WD 7.5.4-7.5.7]. + +use super::TextureWrap; +use super::sections::{base, ref_base}; +use super::validate::Plan; +use super::{BitWriter, MeshScene, SceneMaterial}; + +const MATERIAL: u32 = 702; +const PICTURE: u32 = 703; +const TEXTURE_APPLICATION: u32 = 711; +const TEXTURE_DEFINITION: u32 = 712; + +/// `EPRCPictureDataFormat`, counted from 0. +pub(super) const FORMAT_PNG: u32 = 0; +pub(super) const FORMAT_JPEG: u32 = 1; +/// Mapping type "stored": the coordinates come from the tessellation. +const MAPPING_STORED: i32 = 1; +/// `PRC_TEXTURE_MAPPING_DIFFUSE`. The specification does not give its +/// value; with the first bit, Acrobat Reader draws a synthetic textured +/// quad with its texels in place. +const MAPPING_DIFFUSE: u32 = 0x0001; +/// Components: red, green, blue, and alpha (WD 7.5.7 Table 100). +const COMPONENTS_RGB: u8 = 0x07; +const COMPONENTS_RGBA: u8 = 0x0F; +/// Texture function "modulate", 0-based: glTF multiplies the base colour +/// factor by the texel. +const FUNCTION_MODULATE: i32 = 1; +/// Applying mode: lighting. +const APPLY_LIGHTING: u8 = 0x01; + +/// A picture's format, width and height, read from its file header; `None` +/// when it is neither a PNG nor a JPEG with a frame header, or it has no pixels. +pub(crate) fn picture_info(image: &[u8]) -> Option<(u32, u32, u32)> { + let info = if image.starts_with(b"\x89PNG\r\n\x1a\n") && image.get(12..16) == Some(b"IHDR") { + let be = |at: usize| Some(u32::from_be_bytes(image.get(at..at + 4)?.try_into().ok()?)); + (FORMAT_PNG, be(16)?, be(20)?) + } else { + let (w, h) = jpeg_size(image)?; + (FORMAT_JPEG, w, h) + }; + (info.1 > 0 && info.2 > 0).then_some(info) +} + +/// The width and height in a JPEG's first frame header (SOFn, ITU-T T.81 +/// B.2.2). +fn jpeg_size(b: &[u8]) -> Option<(u32, u32)> { + if !b.starts_with(&[0xFF, 0xD8]) { + return None; + } + let mut at = 2; + loop { + // Fill bytes before a marker. + while b.get(at) == Some(&0xFF) && b.get(at + 1) == Some(&0xFF) { + at += 1; + } + if *b.get(at)? != 0xFF { + return None; + } + let marker = *b.get(at + 1)?; + if matches!(marker, 0x01 | 0xD0..=0xD7) { + at += 2; + continue; + } + let len = usize::from(u16::from_be_bytes([*b.get(at + 2)?, *b.get(at + 3)?])); + let sof = matches!(marker, 0xC0..=0xCF) && !matches!(marker, 0xC4 | 0xC8 | 0xCC); + if sof { + let h = u16::from_be_bytes([*b.get(at + 5)?, *b.get(at + 6)?]); + let w = u16::from_be_bytes([*b.get(at + 7)?, *b.get(at + 8)?]); + return Some((u32::from(w), u32::from(h))); + } + if marker == 0xDA || len < 2 { + return None; + } + at += 2 + len; + } +} + +/// The stored wrapping mode, 0-based as a reader defaults to +/// (`WrapBase::ZeroBased`): 1 repeat, 4 clamp to edge, 5 mirrored repeat. +fn wrap_code(w: TextureWrap) -> i32 { + match w { + TextureWrap::Repeat => 1, + TextureWrap::Clamp => 4, + TextureWrap::MirroredRepeat => 5, + } +} + +/// Pictures, one per texture, file `k` of the structure header for +/// texture `k`; `info` is each one's [`picture_info`]. +pub(super) fn pictures(w: &mut BitWriter, info: &[(u32, u32, u32)]) { + w.uint(info.len() as u32); + for (k, &(format, width, height)) in info.iter().enumerate() { + w.uint(PICTURE); + base(w); + w.uint(format).uint(k as u32 + 1).uint(width).uint(height); + } +} + +/// Texture definitions, one per texture over picture `k`, with unique ids +/// from `first_id`. +pub(super) fn definitions(w: &mut BitWriter, scene: &MeshScene, first_id: u32) { + w.uint(scene.textures.len() as u32); + for (k, t) in scene.textures.iter().enumerate() { + w.uint(TEXTURE_DEFINITION); + ref_base(w, None, first_id + k as u32); + // Picture (biased), dimension 2, stored mapping, diffuse. + w.uint(k as u32 + 1).put(2, 8).int(MAPPING_STORED).uint(MAPPING_DIFFUSE); + // No intensities (1.0); RGB(A) components; modulate; no blend + // sources; lighting; the S and T wraps; no transformation. + let components = if t.alpha { COMPONENTS_RGBA } else { COMPONENTS_RGB }; + w.uint(0).uint(1).put(u64::from(components), 8); + w.int(FUNCTION_MODULATE).int(0).int(0); + w.put(u64::from(APPLY_LIGHTING), 8); + w.int(wrap_code(t.wrap[0])).int(wrap_code(t.wrap[1])); + w.bit(false); + } +} + +/// Whether `m` gives off light the writer carries: a non-black emission +/// on a material that is not wholly transparent. +pub(super) fn glows(m: &SceneMaterial) -> bool { + m.rgba[3] > 0.0 && m.emissive.iter().any(|&c| c > 0.0) +} + +/// The emissive colours, 0–1, of the materials that [`glows`], in material +/// order; the globals write them after the materials' colours. +pub(super) fn emissive_colours(scene: &MeshScene) -> Vec<[f64; 3]> { + scene.materials.iter().filter(|m| glows(m)).map(|m| m.emissive.map(|c| c.clamp(0.0, 1.0))).collect() +} + +/// The materials array, with unique ids from `first_id`: per textured +/// material (`plan.textured`) its base `Material` then the +/// `TextureApplication` naming it, then per glowing untextured material +/// (`plan.glowing`) a `Material`. Emissive colours count from colour +/// `emissive_first`, in [`emissive_colours`] order. +pub(super) fn materials(w: &mut BitWriter, (scene, plan): (&MeshScene, &Plan), emissive_first: u32, first_id: u32) { + w.uint((2 * plan.textured.len() + plan.glowing.len()) as u32); + // Double-scaled, biased (WD 7.5.3); 0 names none. + let emissive = |m: usize| { + if scene.materials.get(m).is_some_and(glows) { + let before = scene.materials.iter().take(m).filter(|m| glows(m)).count() as u32; + 3 * (emissive_first + before) + 1 + } else { + 0 + } + }; + let mut id = first_id; + for (j, &m) in plan.textured.iter().enumerate() { + let Some(mat) = scene.materials.get(m) else { + continue; + }; + material(w, (m, mat), emissive(m), id); + w.uint(TEXTURE_APPLICATION); + ref_base(w, None, id + 1); + let texture = mat.texture.map_or(0, |t| t as u32 + 1); + // Base material (biased entry), definition, no next level, UV set 1. + w.uint(2 * j as u32 + 1).uint(texture).uint(0).uint(1); + id += 2; + } + for &m in &plan.glowing { + if let Some(mat) = scene.materials.get(m) { + material(w, (m, mat), emissive(m), id); + id += 1; + } + } +} + +/// Material `m`'s `Material` (702) with id `id`: ambient and diffuse its +/// base colour, `emissive` its emissive colour index, no specular. +fn material(w: &mut BitWriter, (m, mat): (usize, &SceneMaterial), emissive: u32, id: u32) { + let alpha = mat.rgba[3].clamp(0.0, 1.0); + // Double-scaled colour index of material m's colour (WD 7.5.3). + let colour = 3 * m as u32 + 1; + w.uint(MATERIAL); + ref_base(w, None, id); + w.uint(colour).uint(colour).uint(emissive).uint(0); + w.double(0.0).doubles([alpha; 4]); +} + +#[cfg(test)] +// Test code: a panic is the failure report. +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::super::SceneTexture; + use super::*; + + #[test] + fn png_and_jpeg_sizes_are_read_from_their_headers() { + let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec(); + png.extend([0, 0, 1, 2, 0, 0, 0, 3]); + assert_eq!(picture_info(&png), Some((FORMAT_PNG, 258, 3))); + // SOI, an APP0 of 4 bytes, fill, SOF2 (progressive) 8-bit 5 x 7. + let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xFF, 0xC2, 0, 11, 8, 0, 5, 0, 7]; + assert_eq!(picture_info(&jpeg), Some((FORMAT_JPEG, 7, 5))); + // A DHT (C4) is not a frame header; scan data before a frame is not + // read through. + let no_frame = [0xFF, 0xD8, 0xFF, 0xC4, 0, 2, 0xFF, 0xDA, 0, 2]; + assert_eq!(picture_info(&no_frame), None); + assert_eq!(picture_info(b"RIFF....WEBP"), None); + assert_eq!(picture_info(&png[..20]), None, "a cut IHDR"); + let mut empty = png.clone(); + empty[16..20].copy_from_slice(&[0; 4]); + assert_eq!(picture_info(&empty), None, "a PNG no pixels wide"); + let flat = [0xFF, 0xD8, 0xFF, 0xC0, 0, 11, 8, 0, 0, 0, 7]; + assert_eq!(picture_info(&flat), None, "a JPEG no lines high"); + } + + /// The written definition's components and S and T wraps. + fn definition(t: SceneTexture) -> (u8, [i32; 2]) { + let scene = MeshScene { textures: vec![t], ..MeshScene::default() }; + let mut w = BitWriter::default(); + definitions(&mut w, &scene, 7); + let bytes = w.finish().unwrap(); + let mut r = crate::BitReader::new(&bytes); + // Count, type, base (no attributes, default name), no CAD id, no CAD persistent id, id. + assert_eq!([r.unsigned_integer().unwrap(), r.unsigned_integer().unwrap(), r.unsigned_integer().unwrap()], [1, TEXTURE_DEFINITION, 0]); + assert!(r.bit().unwrap()); + assert_eq!([r.unsigned_integer().unwrap(), r.unsigned_integer().unwrap(), r.unsigned_integer().unwrap()], [0, 0, 7]); + // Picture, dimension, mapping, mapped attribute, intensities, one component set. + assert_eq!(r.unsigned_integer().unwrap(), 1); + assert_eq!(r.character().unwrap(), 2); + assert_eq!([r.integer().unwrap()], [MAPPING_STORED]); + r.unsigned_integer().unwrap(); + assert_eq!([r.unsigned_integer().unwrap(), r.unsigned_integer().unwrap()], [0, 1]); + let components = r.character().unwrap(); + // Function, the two blend sources, applying mode. + assert_eq!([r.integer().unwrap(), r.integer().unwrap(), r.integer().unwrap()], [FUNCTION_MODULATE, 0, 0]); + r.character().unwrap(); + (components, [r.integer().unwrap(), r.integer().unwrap()]) + } + + #[test] + fn wraps_and_alpha_are_written() { + let t = SceneTexture { image: vec![], wrap: [TextureWrap::Clamp, TextureWrap::MirroredRepeat], alpha: true }; + assert_eq!(definition(t), (COMPONENTS_RGBA, [4, 5])); + assert_eq!(definition(SceneTexture::default()), (COMPONENTS_RGB, [1, 1])); + } +} diff --git a/crates/prc/src/write/validate.rs b/crates/prc/src/write/validate.rs new file mode 100644 index 000000000..5b2d9c54c --- /dev/null +++ b/crates/prc/src/write/validate.rs @@ -0,0 +1,292 @@ +//! Checking a [`MeshScene`] and laying it out as PRC entities: the +//! occurrence order, which meshes become parts, which primitives become +//! tessellations. + +use super::{MAX_NODE_DEPTH, MeshScene, PrcWriteError, ScenePrimitive}; + +/// One `ProductOccurrence`: the node it is for (`None` for the synthetic +/// root over several roots) and its sons as occurrence indices. +pub(super) struct Occ { + pub(super) node: Option, + pub(super) sons: Vec, +} + +/// The scene as PRC entities. +pub(super) struct Plan { + /// Occurrences, sons before fathers, the root last. + pub(super) occurrences: Vec, + /// Mesh index of each part. + pub(super) parts: Vec, + /// Part index of each mesh, when it is placed. + pub(super) part_of_mesh: Vec>, + /// `(mesh, primitive)` of each tessellation, in section order. + pub(super) tessellations: Vec<(usize, usize)>, + pub(super) empty_primitives: usize, + /// Each texture's picture format, width and height. + pub(super) pictures: Vec<(u32, u32, u32)>, + /// The textured materials, in material order; the `j`th has material + /// style `materials.len() + j`. + pub(super) textured: Vec, + /// The untextured materials that glow, in material order; the `g`th + /// has material style `materials.len() + textured.len() + g`. + pub(super) glowing: Vec, +} + +impl Plan { + /// Whether `p` is drawn with its material's texture: the material has + /// one and `p` has coordinates. + pub(super) fn is_textured(&self, scene: &MeshScene, p: &ScenePrimitive) -> bool { + !p.uvs.is_empty() && p.material.and_then(|m| scene.materials.get(m)).is_some_and(|m| m.texture.is_some()) + } + + /// The 0-based style `p` names: its material's textured style when + /// [`Self::is_textured`], else its RGB style. + pub(super) fn style_of(&self, scene: &MeshScene, p: &ScenePrimitive) -> Option { + let m = p.material?; + if self.is_textured(scene, p) { + // `textured` and `glowing` are in material order. + let j = self.textured.binary_search(&m).ok()?; + return Some((scene.materials.len() + j) as u32); + } + if let Ok(g) = self.glowing.binary_search(&m) { + return Some((scene.materials.len() + self.textured.len() + g) as u32); + } + Some(m as u32) + } + + /// The last unique id the globals take: the line pattern, the styles, + /// the texture definitions, two materials per textured material and + /// one per glowing one. + pub(super) fn global_ids(&self, scene: &MeshScene) -> u32 { + let materials = 2 * self.textured.len() + self.glowing.len(); + (1 + self.styles(scene) + scene.textures.len() + materials) as u32 + } + + /// How many styles the globals write: one RGB style per material, then + /// the textured and the glowing materials' material styles. + pub(super) fn styles(&self, scene: &MeshScene) -> usize { + scene.materials.len() + self.textured.len() + self.glowing.len() + } +} + +fn bad(what: &'static str, index: usize) -> PrcWriteError { + PrcWriteError::BadIndex { what, index } +} + +fn count(n: usize) -> Result { + u32::try_from(n).map_err(|_| PrcWriteError::TooLarge) +} + +/// Check `scene` and lay it out. +pub(super) fn plan(scene: &MeshScene) -> Result { + check_numbers(scene)?; + check_forest(scene)?; + // Style ids and double-scaled colour indices (a base and an emissive + // colour per material) are u32s. + count(scene.materials.len().saturating_mul(6).saturating_add(2))?; + count(scene.textures.len().saturating_mul(3))?; + // Every global id sum (`global_ids`, the first texture id) is under + // four per material, three per texture and a constant. + count(scene.materials.len().saturating_mul(4).saturating_add(scene.textures.len().saturating_mul(3)).saturating_add(8))?; + // The whole scene, what the roots do not reach included. + for node in &scene.nodes { + if let Some(m) = node.mesh.filter(|&m| m >= scene.meshes.len()) { + return Err(bad("mesh", m)); + } + } + for prim in scene.meshes.iter().flat_map(|m| &m.primitives) { + check_primitive(scene, prim)?; + } + let occurrences = occurrences(scene)?; + let mut plan = Plan { + occurrences, + parts: Vec::new(), + part_of_mesh: vec![None; scene.meshes.len()], + tessellations: Vec::new(), + empty_primitives: 0, + pictures: pictures(scene)?, + textured: textured(scene)?, + glowing: scene.materials.iter().enumerate().filter(|(_, m)| m.texture.is_none() && super::textures::glows(m)).map(|(i, _)| i).collect(), + }; + for o in &plan.occurrences { + let Some(m) = o.node.and_then(|n| scene.nodes.get(n)?.mesh) else { + continue; + }; + let Some(slot) = plan.part_of_mesh.get_mut(m) else { + return Err(bad("mesh", m)); + }; + if slot.is_none() { + *slot = Some(count(plan.parts.len())?); + plan.parts.push(m); + } + } + for &m in &plan.parts { + for (p, prim) in scene.meshes.get(m).into_iter().flat_map(|m| m.primitives.iter().enumerate()) { + if prim.triangles.is_empty() { + plan.empty_primitives += 1; + } else { + plan.tessellations.push((m, p)); + } + } + } + if plan.tessellations.is_empty() { + return Err(PrcWriteError::Empty); + } + count(plan.tessellations.len())?; + Ok(plan) +} + +/// Each texture's [`super::textures::picture_info`]. +fn pictures(scene: &MeshScene) -> Result, PrcWriteError> { + scene.textures.iter().enumerate().map(|(index, t)| super::textures::picture_info(&t.image).ok_or(PrcWriteError::BadTexture { index })).collect() +} + +/// The materials with a texture, each naming one that exists. +fn textured(scene: &MeshScene) -> Result, PrcWriteError> { + let mut out = Vec::new(); + for (m, mat) in scene.materials.iter().enumerate() { + match mat.texture { + Some(t) if t >= scene.textures.len() => return Err(bad("texture", t)), + Some(_) => out.push(m), + None => {} + } + } + Ok(out) +} + +fn check_primitive(scene: &MeshScene, p: &ScenePrimitive) -> Result<(), PrcWriteError> { + if let Some(m) = p.material.filter(|&m| m >= scene.materials.len()) { + return Err(bad("material", m)); + } + if !p.normals.is_empty() && p.normals.len() != p.positions.len() { + return Err(bad("normal count", p.normals.len())); + } + if !p.uvs.is_empty() && p.uvs.len() != p.positions.len() { + return Err(bad("texture coordinate count", p.uvs.len())); + } + // Every count the tessellation writes is a u32, coordinates three to a + // vertex and corner indices up to nine to a triangle. + count(p.positions.len().saturating_mul(3))?; + count(p.triangles.len().saturating_mul(9))?; + let n = p.positions.len(); + match p.triangles.iter().flatten().find(|&&v| v as usize >= n) { + Some(&v) => Err(bad("vertex", v as usize)), + None => Ok(()), + } +} + +fn finite(vs: impl IntoIterator, what: &'static str) -> Result<(), PrcWriteError> { + match vs.into_iter().all(f64::is_finite) { + true => Ok(()), + false => Err(PrcWriteError::BadNumber(what)), + } +} + +fn check_numbers(scene: &MeshScene) -> Result<(), PrcWriteError> { + if !(scene.units_in_mm.is_finite() && scene.units_in_mm > 0.0) { + return Err(PrcWriteError::BadNumber("units_in_mm")); + } + for n in &scene.nodes { + if let Some(m) = n.matrix { + finite(m, "matrix")?; + if [m[3], m[7], m[11], m[15]] != [0.0, 0.0, 0.0, 1.0] { + return Err(PrcWriteError::BadNumber("matrix bottom row")); + } + } + } + finite(scene.materials.iter().flat_map(|m| m.rgba), "colour")?; + finite(scene.materials.iter().flat_map(|m| m.emissive), "emissive colour")?; + for p in scene.meshes.iter().flat_map(|m| &m.primitives) { + finite(p.positions.iter().flatten().copied(), "position")?; + finite(p.normals.iter().flatten().copied(), "normal")?; + finite(p.uvs.iter().flatten().copied(), "texture coordinate")?; + } + Ok(()) +} + +/// Every child and root names a node, no node has two parents, no root +/// has one or is listed twice, no chain from a root is deeper than +/// [`MAX_NODE_DEPTH`], and no node, reached or not, is on a cycle. +/// With one parent at most each and distinct parentless roots, what the +/// roots reach has no cycle and holds each node once, so the occurrences +/// number no more than the nodes. +fn check_forest(scene: &MeshScene) -> Result<(), PrcWriteError> { + let n = scene.nodes.len(); + let mut parent = vec![None; n]; + for (i, node) in scene.nodes.iter().enumerate() { + for &c in &node.children { + let slot = parent.get_mut(c).ok_or_else(|| bad("child node", c))?; + if slot.replace(i).is_some() { + return Err(PrcWriteError::NotATree("a node has two parents")); + } + } + } + let mut rooted = vec![false; n]; + for &r in &scene.roots { + match (parent.get(r), rooted.get_mut(r)) { + (Some(None), Some(seen)) if !*seen => *seen = true, + (Some(None), Some(_)) => return Err(PrcWriteError::NotATree("a root is listed twice")), + (Some(Some(_)), _) => return Err(PrcWriteError::NotATree("a root has a parent")), + _ => return Err(bad("root node", r)), + } + } + let mut depth = vec![0usize; n]; + let mut stack: Vec = scene.roots.clone(); + while let Some(i) = stack.pop() { + let d = depth.get(i).copied().unwrap_or(0).saturating_add(1); + if d > MAX_NODE_DEPTH { + return Err(PrcWriteError::NotATree("nested too deeply")); + } + for &c in scene.nodes.get(i).map(|n| n.children.as_slice()).unwrap_or(&[]) { + if let Some(slot) = depth.get_mut(c) { + *slot = d; + } + stack.push(c); + } + } + // Nodes the roots do not reach: with one parent each, a node no parentless node reaches + // is on a cycle. + let mut seen = vec![false; n]; + let mut stack: Vec = (0..n).filter(|&i| parent.get(i).is_some_and(Option::is_none)).collect(); + while let Some(i) = stack.pop() { + if let Some(s) = seen.get_mut(i).filter(|s| !**s) { + *s = true; + stack.extend(scene.nodes.get(i).map(|n| n.children.as_slice()).unwrap_or(&[])); + } + } + if seen.contains(&false) { + return Err(PrcWriteError::NotATree("a cycle")); + } + Ok(()) +} + +/// Occurrences with every son before its father and the root last +/// [WD 7.3.6], under a +/// synthetic root when there is not exactly one. +fn occurrences(scene: &MeshScene) -> Result, PrcWriteError> { + let mut out = Vec::new(); + let synthetic = scene.roots.len() != 1; + if synthetic { + out.push(Occ { node: None, sons: Vec::new() }); + } + // (node, parent occurrence) + let mut stack: Vec<(usize, Option)> = scene.roots.iter().rev().map(|&r| (r, synthetic.then_some(0))).collect(); + while let Some((node, parent)) = stack.pop() { + let me = out.len(); + if let Some(p) = parent.and_then(|p| out.get_mut(p)) { + p.sons.push(count(me)?); + } + out.push(Occ { node: Some(node), sons: Vec::new() }); + let children = scene.nodes.get(node).map(|n| n.children.as_slice()).unwrap_or(&[]); + stack.extend(children.iter().rev().map(|&c| (c, Some(me)))); + } + let last = count(out.len())?.saturating_sub(1); + // Reversed pre-order: each subtree precedes its root; sons keep their order. + out.reverse(); + for o in &mut out { + for s in &mut o.sons { + *s = last.saturating_sub(*s); + } + } + Ok(out) +} diff --git a/crates/prc/src/write/vec3.rs b/crates/prc/src/write/vec3.rs new file mode 100644 index 000000000..bea911487 --- /dev/null +++ b/crates/prc/src/write/vec3.rs @@ -0,0 +1,53 @@ +//! Three-component vector arithmetic for the writer's normals. + +/// A point or direction, `[x, y, z]`. +pub(crate) type Vec3 = [f64; 3]; + +/// `a - b`. +pub(crate) fn sub(a: Vec3, b: Vec3) -> Vec3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +/// The dot product `a · b`. +pub(crate) fn dot(a: Vec3, b: Vec3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// The right-handed cross product `a × b`. +pub(crate) fn cross(a: Vec3, b: Vec3) -> Vec3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +/// `a` scaled to unit length; `None` when its length is zero or not finite. Divided by its +/// largest component first, so a finite vector too long or too short to square keeps its direction. +pub(crate) fn normalize(a: Vec3) -> Option { + // `f64::max` passes over a NaN, so finiteness is checked on every component. + let big = a.iter().fold(0.0f64, |m, c| m.max(c.abs())); + if !(a.iter().all(|c| c.is_finite()) && big > 0.0) { + return None; + } + let a = a.map(|c| c / big); + let l = dot(a, a).sqrt(); + Some(a.map(|c| c / l)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cross_follows_the_right_hand_rule() { + assert_eq!(cross([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), [0.0, 0.0, 1.0]); + assert_eq!(cross([0.0, 1.0, 0.0], [1.0, 0.0, 0.0]), [0.0, 0.0, -1.0]); + } + + #[test] + fn normalize_rejects_degenerate_vectors() { + assert_eq!(normalize([0.0, 4.0, 0.0]), Some([0.0, 1.0, 0.0])); + assert_eq!(normalize([0.0; 3]), None); + assert_eq!(normalize([f64::INFINITY, 0.0, 0.0]), None); + assert_eq!(normalize([f64::NAN, 1.0, 0.0]), None); + assert_eq!(normalize([0.0, 0.0, 1e300]), Some([0.0, 0.0, 1.0])); + assert_eq!(normalize([0.0, -1e-300, 0.0]), Some([0.0, -1.0, 0.0])); + } +}